| 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 | #include "spirv_msl.hpp" |
| 25 | #include "GLSL.std.450.h" |
| 26 | |
| 27 | #include <algorithm> |
| 28 | #include <assert.h> |
| 29 | #include <numeric> |
| 30 | |
| 31 | using namespace spv; |
| 32 | using namespace SPIRV_CROSS_NAMESPACE; |
| 33 | using namespace std; |
| 34 | |
| 35 | static const uint32_t k_unknown_location = ~0u; |
| 36 | static const uint32_t k_unknown_component = ~0u; |
| 37 | static const char *force_inline = "static inline __attribute__((always_inline))"; |
| 38 | |
| 39 | CompilerMSL::CompilerMSL(std::vector<uint32_t> spirv_) |
| 40 | : CompilerGLSL(std::move(spirv_)) |
| 41 | { |
| 42 | } |
| 43 | |
| 44 | CompilerMSL::CompilerMSL(const uint32_t *ir_, size_t word_count) |
| 45 | : CompilerGLSL(ir_, word_count) |
| 46 | { |
| 47 | } |
| 48 | |
| 49 | CompilerMSL::CompilerMSL(const ParsedIR &ir_) |
| 50 | : CompilerGLSL(ir_) |
| 51 | { |
| 52 | } |
| 53 | |
| 54 | CompilerMSL::CompilerMSL(ParsedIR &&ir_) |
| 55 | : CompilerGLSL(std::move(ir_)) |
| 56 | { |
| 57 | } |
| 58 | |
| 59 | void CompilerMSL::add_msl_shader_input(const MSLShaderInterfaceVariable &si) |
| 60 | { |
| 61 | inputs_by_location[{si.location, si.component}] = si; |
| 62 | if (si.builtin != BuiltInMax && !inputs_by_builtin.count(si.builtin)) |
| 63 | inputs_by_builtin[si.builtin] = si; |
| 64 | } |
| 65 | |
| 66 | void CompilerMSL::add_msl_shader_output(const MSLShaderInterfaceVariable &so) |
| 67 | { |
| 68 | outputs_by_location[{so.location, so.component}] = so; |
| 69 | if (so.builtin != BuiltInMax && !outputs_by_builtin.count(so.builtin)) |
| 70 | outputs_by_builtin[so.builtin] = so; |
| 71 | } |
| 72 | |
| 73 | void CompilerMSL::add_msl_resource_binding(const MSLResourceBinding &binding) |
| 74 | { |
| 75 | StageSetBinding tuple = { binding.stage, binding.desc_set, binding.binding }; |
| 76 | resource_bindings[tuple] = { binding, false }; |
| 77 | |
| 78 | // If we might need to pad argument buffer members to positionally align |
| 79 | // arg buffer indexes, also maintain a lookup by argument buffer index. |
| 80 | if (msl_options.pad_argument_buffer_resources) |
| 81 | { |
| 82 | StageSetBinding arg_idx_tuple = { binding.stage, binding.desc_set, k_unknown_component }; |
| 83 | |
| 84 | #define ADD_ARG_IDX_TO_BINDING_NUM_LOOKUP(rez) \ |
| 85 | arg_idx_tuple.binding = binding.msl_##rez; \ |
| 86 | resource_arg_buff_idx_to_binding_number[arg_idx_tuple] = binding.binding |
| 87 | |
| 88 | switch (binding.basetype) |
| 89 | { |
| 90 | case SPIRType::Void: |
| 91 | case SPIRType::Boolean: |
| 92 | case SPIRType::SByte: |
| 93 | case SPIRType::UByte: |
| 94 | case SPIRType::Short: |
| 95 | case SPIRType::UShort: |
| 96 | case SPIRType::Int: |
| 97 | case SPIRType::UInt: |
| 98 | case SPIRType::Int64: |
| 99 | case SPIRType::UInt64: |
| 100 | case SPIRType::AtomicCounter: |
| 101 | case SPIRType::Half: |
| 102 | case SPIRType::Float: |
| 103 | case SPIRType::Double: |
| 104 | ADD_ARG_IDX_TO_BINDING_NUM_LOOKUP(buffer); |
| 105 | break; |
| 106 | case SPIRType::Image: |
| 107 | ADD_ARG_IDX_TO_BINDING_NUM_LOOKUP(texture); |
| 108 | break; |
| 109 | case SPIRType::Sampler: |
| 110 | ADD_ARG_IDX_TO_BINDING_NUM_LOOKUP(sampler); |
| 111 | break; |
| 112 | case SPIRType::SampledImage: |
| 113 | ADD_ARG_IDX_TO_BINDING_NUM_LOOKUP(texture); |
| 114 | ADD_ARG_IDX_TO_BINDING_NUM_LOOKUP(sampler); |
| 115 | break; |
| 116 | default: |
| 117 | SPIRV_CROSS_THROW("Unexpected argument buffer resource base type. When padding argument buffer elements, " |
| 118 | "all descriptor set resources must be supplied with a base type by the app."); |
| 119 | } |
| 120 | #undef ADD_ARG_IDX_TO_BINDING_NUM_LOOKUP |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | void CompilerMSL::add_dynamic_buffer(uint32_t desc_set, uint32_t binding, uint32_t index) |
| 125 | { |
| 126 | SetBindingPair pair = { desc_set, binding }; |
| 127 | buffers_requiring_dynamic_offset[pair] = { index, 0 }; |
| 128 | } |
| 129 | |
| 130 | void CompilerMSL::add_inline_uniform_block(uint32_t desc_set, uint32_t binding) |
| 131 | { |
| 132 | SetBindingPair pair = { desc_set, binding }; |
| 133 | inline_uniform_blocks.insert(pair); |
| 134 | } |
| 135 | |
| 136 | void CompilerMSL::add_discrete_descriptor_set(uint32_t desc_set) |
| 137 | { |
| 138 | if (desc_set < kMaxArgumentBuffers) |
| 139 | argument_buffer_discrete_mask |= 1u << desc_set; |
| 140 | } |
| 141 | |
| 142 | void CompilerMSL::set_argument_buffer_device_address_space(uint32_t desc_set, bool device_storage) |
| 143 | { |
| 144 | if (desc_set < kMaxArgumentBuffers) |
| 145 | { |
| 146 | if (device_storage) |
| 147 | argument_buffer_device_storage_mask |= 1u << desc_set; |
| 148 | else |
| 149 | argument_buffer_device_storage_mask &= ~(1u << desc_set); |
| 150 | } |
| 151 | } |
| 152 | |
| 153 | bool CompilerMSL::is_msl_shader_input_used(uint32_t location) |
| 154 | { |
| 155 | // Don't report internal location allocations to app. |
| 156 | return location_inputs_in_use.count(location) != 0 && |
| 157 | location_inputs_in_use_fallback.count(location) == 0; |
| 158 | } |
| 159 | |
| 160 | bool CompilerMSL::is_msl_shader_output_used(uint32_t location) |
| 161 | { |
| 162 | // Don't report internal location allocations to app. |
| 163 | return location_outputs_in_use.count(location) != 0 && |
| 164 | location_outputs_in_use_fallback.count(location) == 0; |
| 165 | } |
| 166 | |
| 167 | uint32_t CompilerMSL::get_automatic_builtin_input_location(spv::BuiltIn builtin) const |
| 168 | { |
| 169 | auto itr = builtin_to_automatic_input_location.find(builtin); |
| 170 | if (itr == builtin_to_automatic_input_location.end()) |
| 171 | return k_unknown_location; |
| 172 | else |
| 173 | return itr->second; |
| 174 | } |
| 175 | |
| 176 | uint32_t CompilerMSL::get_automatic_builtin_output_location(spv::BuiltIn builtin) const |
| 177 | { |
| 178 | auto itr = builtin_to_automatic_output_location.find(builtin); |
| 179 | if (itr == builtin_to_automatic_output_location.end()) |
| 180 | return k_unknown_location; |
| 181 | else |
| 182 | return itr->second; |
| 183 | } |
| 184 | |
| 185 | bool CompilerMSL::is_msl_resource_binding_used(ExecutionModel model, uint32_t desc_set, uint32_t binding) const |
| 186 | { |
| 187 | StageSetBinding tuple = { model, desc_set, binding }; |
| 188 | auto itr = resource_bindings.find(tuple); |
| 189 | return itr != end(resource_bindings) && itr->second.second; |
| 190 | } |
| 191 | |
| 192 | bool CompilerMSL::is_var_runtime_size_array(const SPIRVariable &var) const |
| 193 | { |
| 194 | auto& type = get_variable_data_type(var); |
| 195 | return is_runtime_size_array(type) && get_resource_array_size(type, var.self) == 0; |
| 196 | } |
| 197 | |
| 198 | // Returns the size of the array of resources used by the variable with the specified type and id. |
| 199 | // The size is first retrieved from the type, but in the case of runtime array sizing, |
| 200 | // the size is retrieved from the resource binding added using add_msl_resource_binding(). |
| 201 | uint32_t CompilerMSL::get_resource_array_size(const SPIRType &type, uint32_t id) const |
| 202 | { |
| 203 | uint32_t array_size = to_array_size_literal(type); |
| 204 | |
| 205 | if (id == 0) |
| 206 | return array_size; |
| 207 | |
| 208 | // If we have argument buffers, we need to honor the ABI by using the correct array size |
| 209 | // from the layout. Only use shader declared size if we're not using argument buffers. |
| 210 | uint32_t desc_set = get_decoration(id, DecorationDescriptorSet); |
| 211 | if (!descriptor_set_is_argument_buffer(desc_set) && array_size) |
| 212 | return array_size; |
| 213 | |
| 214 | StageSetBinding tuple = { get_entry_point().model, desc_set, |
| 215 | get_decoration(id, DecorationBinding) }; |
| 216 | auto itr = resource_bindings.find(tuple); |
| 217 | return itr != end(resource_bindings) ? itr->second.first.count : array_size; |
| 218 | } |
| 219 | |
| 220 | uint32_t CompilerMSL::get_automatic_msl_resource_binding(uint32_t id) const |
| 221 | { |
| 222 | return get_extended_decoration(id, SPIRVCrossDecorationResourceIndexPrimary); |
| 223 | } |
| 224 | |
| 225 | uint32_t CompilerMSL::get_automatic_msl_resource_binding_secondary(uint32_t id) const |
| 226 | { |
| 227 | return get_extended_decoration(id, SPIRVCrossDecorationResourceIndexSecondary); |
| 228 | } |
| 229 | |
| 230 | uint32_t CompilerMSL::get_automatic_msl_resource_binding_tertiary(uint32_t id) const |
| 231 | { |
| 232 | return get_extended_decoration(id, SPIRVCrossDecorationResourceIndexTertiary); |
| 233 | } |
| 234 | |
| 235 | uint32_t CompilerMSL::get_automatic_msl_resource_binding_quaternary(uint32_t id) const |
| 236 | { |
| 237 | return get_extended_decoration(id, SPIRVCrossDecorationResourceIndexQuaternary); |
| 238 | } |
| 239 | |
| 240 | void CompilerMSL::set_fragment_output_components(uint32_t location, uint32_t components) |
| 241 | { |
| 242 | fragment_output_components[location] = components; |
| 243 | } |
| 244 | |
| 245 | bool CompilerMSL::builtin_translates_to_nonarray(spv::BuiltIn builtin) const |
| 246 | { |
| 247 | return (builtin == BuiltInSampleMask); |
| 248 | } |
| 249 | |
| 250 | void CompilerMSL::build_implicit_builtins() |
| 251 | { |
| 252 | bool need_sample_pos = active_input_builtins.get(BuiltInSamplePosition); |
| 253 | bool need_vertex_params = capture_output_to_buffer && get_execution_model() == ExecutionModelVertex && |
| 254 | !msl_options.vertex_for_tessellation; |
| 255 | bool need_tesc_params = is_tesc_shader(); |
| 256 | bool need_tese_params = is_tese_shader() && msl_options.raw_buffer_tese_input; |
| 257 | bool need_subgroup_mask = |
| 258 | active_input_builtins.get(BuiltInSubgroupEqMask) || active_input_builtins.get(BuiltInSubgroupGeMask) || |
| 259 | active_input_builtins.get(BuiltInSubgroupGtMask) || active_input_builtins.get(BuiltInSubgroupLeMask) || |
| 260 | active_input_builtins.get(BuiltInSubgroupLtMask); |
| 261 | bool need_subgroup_ge_mask = !msl_options.is_ios() && (active_input_builtins.get(BuiltInSubgroupGeMask) || |
| 262 | active_input_builtins.get(BuiltInSubgroupGtMask)); |
| 263 | bool need_multiview = get_execution_model() == ExecutionModelVertex && !msl_options.view_index_from_device_index && |
| 264 | msl_options.multiview_layered_rendering && |
| 265 | (msl_options.multiview || active_input_builtins.get(BuiltInViewIndex)); |
| 266 | bool need_dispatch_base = |
| 267 | msl_options.dispatch_base && get_execution_model() == ExecutionModelGLCompute && |
| 268 | (active_input_builtins.get(BuiltInWorkgroupId) || active_input_builtins.get(BuiltInGlobalInvocationId)); |
| 269 | bool need_grid_params = get_execution_model() == ExecutionModelVertex && msl_options.vertex_for_tessellation; |
| 270 | bool need_vertex_base_params = |
| 271 | need_grid_params && |
| 272 | (active_input_builtins.get(BuiltInVertexId) || active_input_builtins.get(BuiltInVertexIndex) || |
| 273 | active_input_builtins.get(BuiltInBaseVertex) || active_input_builtins.get(BuiltInInstanceId) || |
| 274 | active_input_builtins.get(BuiltInInstanceIndex) || active_input_builtins.get(BuiltInBaseInstance)); |
| 275 | bool need_local_invocation_index = |
| 276 | (msl_options.emulate_subgroups && active_input_builtins.get(BuiltInSubgroupId)) || is_mesh_shader() || |
| 277 | needs_workgroup_zero_init || needs_local_invocation_index; |
| 278 | bool need_workgroup_size = msl_options.emulate_subgroups && active_input_builtins.get(BuiltInNumSubgroups); |
| 279 | bool force_frag_depth_passthrough = |
| 280 | get_execution_model() == ExecutionModelFragment && !uses_explicit_early_fragment_test() && need_subpass_input && |
| 281 | msl_options.enable_frag_depth_builtin && msl_options.input_attachment_is_ds_attachment; |
| 282 | bool need_point_size = |
| 283 | msl_options.enable_point_size_builtin && msl_options.enable_point_size_default && |
| 284 | get_execution_model() == ExecutionModelVertex; |
| 285 | |
| 286 | if (need_subpass_input || need_sample_pos || need_subgroup_mask || need_vertex_params || need_tesc_params || |
| 287 | need_tese_params || need_multiview || need_dispatch_base || need_vertex_base_params || need_grid_params || |
| 288 | needs_sample_id || needs_subgroup_invocation_id || needs_subgroup_size || needs_helper_invocation || |
| 289 | has_additional_fixed_sample_mask() || need_local_invocation_index || need_workgroup_size || |
| 290 | force_frag_depth_passthrough || need_point_size || is_mesh_shader()) |
| 291 | { |
| 292 | bool has_frag_coord = false; |
| 293 | bool has_sample_id = false; |
| 294 | bool has_vertex_idx = false; |
| 295 | bool has_base_vertex = false; |
| 296 | bool has_instance_idx = false; |
| 297 | bool has_base_instance = false; |
| 298 | bool has_invocation_id = false; |
| 299 | bool has_primitive_id = false; |
| 300 | bool has_subgroup_invocation_id = false; |
| 301 | bool has_subgroup_size = false; |
| 302 | bool has_view_idx = false; |
| 303 | bool has_layer = false; |
| 304 | bool has_helper_invocation = false; |
| 305 | bool has_local_invocation_index = false; |
| 306 | bool has_workgroup_size = false; |
| 307 | bool has_frag_depth = false; |
| 308 | bool has_point_size = false; |
| 309 | uint32_t workgroup_id_type = 0; |
| 310 | |
| 311 | ir.for_each_typed_id<SPIRVariable>([&](uint32_t, SPIRVariable &var) { |
| 312 | if (var.storage != StorageClassInput && var.storage != StorageClassOutput) |
| 313 | return; |
| 314 | if (!interface_variable_exists_in_entry_point(var.self)) |
| 315 | return; |
| 316 | |
| 317 | auto &type = this->get<SPIRType>(var.basetype); |
| 318 | if (need_point_size && has_decoration(type.self, DecorationBlock)) |
| 319 | { |
| 320 | const auto member_count = static_cast<uint32_t>(type.member_types.size()); |
| 321 | for (uint32_t i = 0; i < member_count; i++) |
| 322 | { |
| 323 | if (get_member_decoration(type.self, i, DecorationBuiltIn) == BuiltInPointSize) |
| 324 | { |
| 325 | has_point_size = true; |
| 326 | active_output_builtins.set(BuiltInPointSize); |
| 327 | break; |
| 328 | } |
| 329 | } |
| 330 | } |
| 331 | |
| 332 | if (!has_decoration(var.self, DecorationBuiltIn)) |
| 333 | return; |
| 334 | |
| 335 | BuiltIn builtin = ir.meta[var.self].decoration.builtin_type; |
| 336 | |
| 337 | if (var.storage == StorageClassOutput) |
| 338 | { |
| 339 | if (has_additional_fixed_sample_mask() && builtin == BuiltInSampleMask) |
| 340 | { |
| 341 | builtin_sample_mask_id = var.self; |
| 342 | mark_implicit_builtin(StorageClassOutput, BuiltInSampleMask, var.self); |
| 343 | does_shader_write_sample_mask = true; |
| 344 | } |
| 345 | |
| 346 | if (force_frag_depth_passthrough && builtin == BuiltInFragDepth) |
| 347 | { |
| 348 | builtin_frag_depth_id = var.self; |
| 349 | mark_implicit_builtin(StorageClassOutput, BuiltInFragDepth, var.self); |
| 350 | has_frag_depth = true; |
| 351 | } |
| 352 | } |
| 353 | |
| 354 | if (builtin == BuiltInPointSize) |
| 355 | { |
| 356 | has_point_size = true; |
| 357 | active_output_builtins.set(BuiltInPointSize); |
| 358 | } |
| 359 | |
| 360 | if (builtin == BuiltInPrimitivePointIndicesEXT || |
| 361 | builtin == BuiltInPrimitiveLineIndicesEXT || |
| 362 | builtin == BuiltInPrimitiveTriangleIndicesEXT) |
| 363 | { |
| 364 | builtin_mesh_primitive_indices_id = var.self; |
| 365 | } |
| 366 | |
| 367 | if (var.storage != StorageClassInput) |
| 368 | return; |
| 369 | |
| 370 | // Use Metal's native frame-buffer fetch API for subpass inputs. |
| 371 | if (need_subpass_input && (!msl_options.use_framebuffer_fetch_subpasses)) |
| 372 | { |
| 373 | switch (builtin) |
| 374 | { |
| 375 | case BuiltInFragCoord: |
| 376 | mark_implicit_builtin(StorageClassInput, BuiltInFragCoord, var.self); |
| 377 | builtin_frag_coord_id = var.self; |
| 378 | has_frag_coord = true; |
| 379 | break; |
| 380 | case BuiltInLayer: |
| 381 | if (!msl_options.arrayed_subpass_input || msl_options.multiview) |
| 382 | break; |
| 383 | mark_implicit_builtin(StorageClassInput, BuiltInLayer, var.self); |
| 384 | builtin_layer_id = var.self; |
| 385 | has_layer = true; |
| 386 | break; |
| 387 | case BuiltInViewIndex: |
| 388 | if (!msl_options.multiview) |
| 389 | break; |
| 390 | mark_implicit_builtin(StorageClassInput, BuiltInViewIndex, var.self); |
| 391 | builtin_view_idx_id = var.self; |
| 392 | has_view_idx = true; |
| 393 | break; |
| 394 | default: |
| 395 | break; |
| 396 | } |
| 397 | } |
| 398 | |
| 399 | if ((need_sample_pos || needs_sample_id) && builtin == BuiltInSampleId) |
| 400 | { |
| 401 | builtin_sample_id_id = var.self; |
| 402 | mark_implicit_builtin(StorageClassInput, BuiltInSampleId, var.self); |
| 403 | has_sample_id = true; |
| 404 | } |
| 405 | |
| 406 | if (need_vertex_params) |
| 407 | { |
| 408 | switch (builtin) |
| 409 | { |
| 410 | case BuiltInVertexIndex: |
| 411 | builtin_vertex_idx_id = var.self; |
| 412 | mark_implicit_builtin(StorageClassInput, BuiltInVertexIndex, var.self); |
| 413 | has_vertex_idx = true; |
| 414 | break; |
| 415 | case BuiltInBaseVertex: |
| 416 | builtin_base_vertex_id = var.self; |
| 417 | mark_implicit_builtin(StorageClassInput, BuiltInBaseVertex, var.self); |
| 418 | has_base_vertex = true; |
| 419 | break; |
| 420 | case BuiltInInstanceIndex: |
| 421 | builtin_instance_idx_id = var.self; |
| 422 | mark_implicit_builtin(StorageClassInput, BuiltInInstanceIndex, var.self); |
| 423 | has_instance_idx = true; |
| 424 | break; |
| 425 | case BuiltInBaseInstance: |
| 426 | builtin_base_instance_id = var.self; |
| 427 | mark_implicit_builtin(StorageClassInput, BuiltInBaseInstance, var.self); |
| 428 | has_base_instance = true; |
| 429 | break; |
| 430 | default: |
| 431 | break; |
| 432 | } |
| 433 | } |
| 434 | |
| 435 | if (need_tesc_params && builtin == BuiltInInvocationId) |
| 436 | { |
| 437 | builtin_invocation_id_id = var.self; |
| 438 | mark_implicit_builtin(StorageClassInput, BuiltInInvocationId, var.self); |
| 439 | has_invocation_id = true; |
| 440 | } |
| 441 | |
| 442 | if ((need_tesc_params || need_tese_params) && builtin == BuiltInPrimitiveId) |
| 443 | { |
| 444 | builtin_primitive_id_id = var.self; |
| 445 | mark_implicit_builtin(StorageClassInput, BuiltInPrimitiveId, var.self); |
| 446 | has_primitive_id = true; |
| 447 | } |
| 448 | |
| 449 | if (need_tese_params && builtin == BuiltInTessLevelOuter) |
| 450 | { |
| 451 | tess_level_outer_var_id = var.self; |
| 452 | } |
| 453 | |
| 454 | if (need_tese_params && builtin == BuiltInTessLevelInner) |
| 455 | { |
| 456 | tess_level_inner_var_id = var.self; |
| 457 | } |
| 458 | |
| 459 | if ((need_subgroup_mask || needs_subgroup_invocation_id) && builtin == BuiltInSubgroupLocalInvocationId) |
| 460 | { |
| 461 | builtin_subgroup_invocation_id_id = var.self; |
| 462 | mark_implicit_builtin(StorageClassInput, BuiltInSubgroupLocalInvocationId, var.self); |
| 463 | has_subgroup_invocation_id = true; |
| 464 | } |
| 465 | |
| 466 | if ((need_subgroup_ge_mask || needs_subgroup_size) && builtin == BuiltInSubgroupSize) |
| 467 | { |
| 468 | builtin_subgroup_size_id = var.self; |
| 469 | mark_implicit_builtin(StorageClassInput, BuiltInSubgroupSize, var.self); |
| 470 | has_subgroup_size = true; |
| 471 | } |
| 472 | |
| 473 | if (need_multiview) |
| 474 | { |
| 475 | switch (builtin) |
| 476 | { |
| 477 | case BuiltInInstanceIndex: |
| 478 | // The view index here is derived from the instance index. |
| 479 | builtin_instance_idx_id = var.self; |
| 480 | mark_implicit_builtin(StorageClassInput, BuiltInInstanceIndex, var.self); |
| 481 | has_instance_idx = true; |
| 482 | break; |
| 483 | case BuiltInBaseInstance: |
| 484 | // If a non-zero base instance is used, we need to adjust for it when calculating the view index. |
| 485 | builtin_base_instance_id = var.self; |
| 486 | mark_implicit_builtin(StorageClassInput, BuiltInBaseInstance, var.self); |
| 487 | has_base_instance = true; |
| 488 | break; |
| 489 | case BuiltInViewIndex: |
| 490 | builtin_view_idx_id = var.self; |
| 491 | mark_implicit_builtin(StorageClassInput, BuiltInViewIndex, var.self); |
| 492 | has_view_idx = true; |
| 493 | break; |
| 494 | default: |
| 495 | break; |
| 496 | } |
| 497 | } |
| 498 | |
| 499 | if (needs_helper_invocation && builtin == BuiltInHelperInvocation) |
| 500 | { |
| 501 | builtin_helper_invocation_id = var.self; |
| 502 | mark_implicit_builtin(StorageClassInput, BuiltInHelperInvocation, var.self); |
| 503 | has_helper_invocation = true; |
| 504 | } |
| 505 | |
| 506 | if (need_local_invocation_index && builtin == BuiltInLocalInvocationIndex) |
| 507 | { |
| 508 | builtin_local_invocation_index_id = var.self; |
| 509 | mark_implicit_builtin(StorageClassInput, BuiltInLocalInvocationIndex, var.self); |
| 510 | has_local_invocation_index = true; |
| 511 | } |
| 512 | |
| 513 | if (need_workgroup_size && builtin == BuiltInWorkgroupSize) |
| 514 | { |
| 515 | builtin_workgroup_size_id = var.self; |
| 516 | mark_implicit_builtin(StorageClassInput, BuiltInWorkgroupSize, var.self); |
| 517 | has_workgroup_size = true; |
| 518 | } |
| 519 | |
| 520 | // The base workgroup needs to have the same type and vector size |
| 521 | // as the workgroup or invocation ID, so keep track of the type that |
| 522 | // was used. |
| 523 | if (need_dispatch_base && workgroup_id_type == 0 && |
| 524 | (builtin == BuiltInWorkgroupId || builtin == BuiltInGlobalInvocationId)) |
| 525 | workgroup_id_type = var.basetype; |
| 526 | }); |
| 527 | |
| 528 | // Use Metal's native frame-buffer fetch API for subpass inputs. |
| 529 | if ((!has_frag_coord || (msl_options.multiview && !has_view_idx) || |
| 530 | (msl_options.arrayed_subpass_input && !msl_options.multiview && !has_layer)) && |
| 531 | (!msl_options.use_framebuffer_fetch_subpasses) && need_subpass_input) |
| 532 | { |
| 533 | if (!has_frag_coord) |
| 534 | { |
| 535 | uint32_t offset = ir.increase_bound_by(3); |
| 536 | uint32_t type_id = offset; |
| 537 | uint32_t type_ptr_id = offset + 1; |
| 538 | uint32_t var_id = offset + 2; |
| 539 | |
| 540 | // Create gl_FragCoord. |
| 541 | SPIRType vec4_type { OpTypeVector }; |
| 542 | vec4_type.basetype = SPIRType::Float; |
| 543 | vec4_type.width = 32; |
| 544 | vec4_type.vecsize = 4; |
| 545 | set<SPIRType>(type_id, vec4_type); |
| 546 | |
| 547 | SPIRType vec4_type_ptr = vec4_type; |
| 548 | vec4_type_ptr.op = OpTypePointer; |
| 549 | vec4_type_ptr.pointer = true; |
| 550 | vec4_type_ptr.pointer_depth++; |
| 551 | vec4_type_ptr.parent_type = type_id; |
| 552 | vec4_type_ptr.storage = StorageClassInput; |
| 553 | auto &ptr_type = set<SPIRType>(type_ptr_id, vec4_type_ptr); |
| 554 | ptr_type.self = type_id; |
| 555 | |
| 556 | set<SPIRVariable>(var_id, type_ptr_id, StorageClassInput); |
| 557 | set_decoration(var_id, DecorationBuiltIn, BuiltInFragCoord); |
| 558 | builtin_frag_coord_id = var_id; |
| 559 | mark_implicit_builtin(StorageClassInput, BuiltInFragCoord, var_id); |
| 560 | } |
| 561 | |
| 562 | if (!has_layer && msl_options.arrayed_subpass_input && !msl_options.multiview) |
| 563 | { |
| 564 | uint32_t offset = ir.increase_bound_by(2); |
| 565 | uint32_t type_ptr_id = offset; |
| 566 | uint32_t var_id = offset + 1; |
| 567 | |
| 568 | // Create gl_Layer. |
| 569 | SPIRType uint_type_ptr = get_uint_type(); |
| 570 | uint_type_ptr.op = OpTypePointer; |
| 571 | uint_type_ptr.pointer = true; |
| 572 | uint_type_ptr.pointer_depth++; |
| 573 | uint_type_ptr.parent_type = get_uint_type_id(); |
| 574 | uint_type_ptr.storage = StorageClassInput; |
| 575 | auto &ptr_type = set<SPIRType>(type_ptr_id, uint_type_ptr); |
| 576 | ptr_type.self = get_uint_type_id(); |
| 577 | |
| 578 | set<SPIRVariable>(var_id, type_ptr_id, StorageClassInput); |
| 579 | set_decoration(var_id, DecorationBuiltIn, BuiltInLayer); |
| 580 | builtin_layer_id = var_id; |
| 581 | mark_implicit_builtin(StorageClassInput, BuiltInLayer, var_id); |
| 582 | } |
| 583 | |
| 584 | if (!has_view_idx && msl_options.multiview) |
| 585 | { |
| 586 | uint32_t offset = ir.increase_bound_by(2); |
| 587 | uint32_t type_ptr_id = offset; |
| 588 | uint32_t var_id = offset + 1; |
| 589 | |
| 590 | // Create gl_ViewIndex. |
| 591 | SPIRType uint_type_ptr = get_uint_type(); |
| 592 | uint_type_ptr.op = OpTypePointer; |
| 593 | uint_type_ptr.pointer = true; |
| 594 | uint_type_ptr.pointer_depth++; |
| 595 | uint_type_ptr.parent_type = get_uint_type_id(); |
| 596 | uint_type_ptr.storage = StorageClassInput; |
| 597 | auto &ptr_type = set<SPIRType>(type_ptr_id, uint_type_ptr); |
| 598 | ptr_type.self = get_uint_type_id(); |
| 599 | |
| 600 | set<SPIRVariable>(var_id, type_ptr_id, StorageClassInput); |
| 601 | set_decoration(var_id, DecorationBuiltIn, BuiltInViewIndex); |
| 602 | builtin_view_idx_id = var_id; |
| 603 | mark_implicit_builtin(StorageClassInput, BuiltInViewIndex, var_id); |
| 604 | } |
| 605 | } |
| 606 | |
| 607 | if (!has_sample_id && (need_sample_pos || needs_sample_id)) |
| 608 | { |
| 609 | uint32_t offset = ir.increase_bound_by(2); |
| 610 | uint32_t type_ptr_id = offset; |
| 611 | uint32_t var_id = offset + 1; |
| 612 | |
| 613 | // Create gl_SampleID. |
| 614 | SPIRType uint_type_ptr = get_uint_type(); |
| 615 | uint_type_ptr.op = OpTypePointer; |
| 616 | uint_type_ptr.pointer = true; |
| 617 | uint_type_ptr.pointer_depth++; |
| 618 | uint_type_ptr.parent_type = get_uint_type_id(); |
| 619 | uint_type_ptr.storage = StorageClassInput; |
| 620 | auto &ptr_type = set<SPIRType>(type_ptr_id, uint_type_ptr); |
| 621 | ptr_type.self = get_uint_type_id(); |
| 622 | |
| 623 | set<SPIRVariable>(var_id, type_ptr_id, StorageClassInput); |
| 624 | set_decoration(var_id, DecorationBuiltIn, BuiltInSampleId); |
| 625 | builtin_sample_id_id = var_id; |
| 626 | mark_implicit_builtin(StorageClassInput, BuiltInSampleId, var_id); |
| 627 | } |
| 628 | |
| 629 | if ((need_vertex_params && (!has_vertex_idx || !has_base_vertex || !has_instance_idx || !has_base_instance)) || |
| 630 | (need_multiview && (!has_instance_idx || !has_base_instance || !has_view_idx))) |
| 631 | { |
| 632 | uint32_t type_ptr_id = ir.increase_bound_by(1); |
| 633 | |
| 634 | SPIRType uint_type_ptr = get_uint_type(); |
| 635 | uint_type_ptr.op = OpTypePointer; |
| 636 | uint_type_ptr.pointer = true; |
| 637 | uint_type_ptr.pointer_depth++; |
| 638 | uint_type_ptr.parent_type = get_uint_type_id(); |
| 639 | uint_type_ptr.storage = StorageClassInput; |
| 640 | auto &ptr_type = set<SPIRType>(type_ptr_id, uint_type_ptr); |
| 641 | ptr_type.self = get_uint_type_id(); |
| 642 | |
| 643 | if (need_vertex_params && !has_vertex_idx) |
| 644 | { |
| 645 | uint32_t var_id = ir.increase_bound_by(1); |
| 646 | |
| 647 | // Create gl_VertexIndex. |
| 648 | set<SPIRVariable>(var_id, type_ptr_id, StorageClassInput); |
| 649 | set_decoration(var_id, DecorationBuiltIn, BuiltInVertexIndex); |
| 650 | builtin_vertex_idx_id = var_id; |
| 651 | mark_implicit_builtin(StorageClassInput, BuiltInVertexIndex, var_id); |
| 652 | } |
| 653 | |
| 654 | if (need_vertex_params && !has_base_vertex) |
| 655 | { |
| 656 | uint32_t var_id = ir.increase_bound_by(1); |
| 657 | |
| 658 | // Create gl_BaseVertex. |
| 659 | set<SPIRVariable>(var_id, type_ptr_id, StorageClassInput); |
| 660 | set_decoration(var_id, DecorationBuiltIn, BuiltInBaseVertex); |
| 661 | builtin_base_vertex_id = var_id; |
| 662 | mark_implicit_builtin(StorageClassInput, BuiltInBaseVertex, var_id); |
| 663 | } |
| 664 | |
| 665 | if (!has_instance_idx) // Needed by both multiview and tessellation |
| 666 | { |
| 667 | uint32_t var_id = ir.increase_bound_by(1); |
| 668 | |
| 669 | // Create gl_InstanceIndex. |
| 670 | set<SPIRVariable>(var_id, type_ptr_id, StorageClassInput); |
| 671 | set_decoration(var_id, DecorationBuiltIn, BuiltInInstanceIndex); |
| 672 | builtin_instance_idx_id = var_id; |
| 673 | mark_implicit_builtin(StorageClassInput, BuiltInInstanceIndex, var_id); |
| 674 | } |
| 675 | |
| 676 | if (!has_base_instance) // Needed by both multiview and tessellation |
| 677 | { |
| 678 | uint32_t var_id = ir.increase_bound_by(1); |
| 679 | |
| 680 | // Create gl_BaseInstance. |
| 681 | set<SPIRVariable>(var_id, type_ptr_id, StorageClassInput); |
| 682 | set_decoration(var_id, DecorationBuiltIn, BuiltInBaseInstance); |
| 683 | builtin_base_instance_id = var_id; |
| 684 | mark_implicit_builtin(StorageClassInput, BuiltInBaseInstance, var_id); |
| 685 | } |
| 686 | |
| 687 | if (need_multiview) |
| 688 | { |
| 689 | // Multiview shaders are not allowed to write to gl_Layer, ostensibly because |
| 690 | // it is implicitly written from gl_ViewIndex, but we have to do that explicitly. |
| 691 | // Note that we can't just abuse gl_ViewIndex for this purpose: it's an input, but |
| 692 | // gl_Layer is an output in vertex-pipeline shaders. |
| 693 | uint32_t type_ptr_out_id = ir.increase_bound_by(2); |
| 694 | SPIRType uint_type_ptr_out = get_uint_type(); |
| 695 | uint_type_ptr.op = OpTypePointer; |
| 696 | uint_type_ptr_out.pointer = true; |
| 697 | uint_type_ptr_out.pointer_depth++; |
| 698 | uint_type_ptr_out.parent_type = get_uint_type_id(); |
| 699 | uint_type_ptr_out.storage = StorageClassOutput; |
| 700 | auto &ptr_out_type = set<SPIRType>(type_ptr_out_id, uint_type_ptr_out); |
| 701 | ptr_out_type.self = get_uint_type_id(); |
| 702 | uint32_t var_id = type_ptr_out_id + 1; |
| 703 | set<SPIRVariable>(var_id, type_ptr_out_id, StorageClassOutput); |
| 704 | set_decoration(var_id, DecorationBuiltIn, BuiltInLayer); |
| 705 | builtin_layer_id = var_id; |
| 706 | mark_implicit_builtin(StorageClassOutput, BuiltInLayer, var_id); |
| 707 | } |
| 708 | |
| 709 | if (need_multiview && !has_view_idx) |
| 710 | { |
| 711 | uint32_t var_id = ir.increase_bound_by(1); |
| 712 | |
| 713 | // Create gl_ViewIndex. |
| 714 | set<SPIRVariable>(var_id, type_ptr_id, StorageClassInput); |
| 715 | set_decoration(var_id, DecorationBuiltIn, BuiltInViewIndex); |
| 716 | builtin_view_idx_id = var_id; |
| 717 | mark_implicit_builtin(StorageClassInput, BuiltInViewIndex, var_id); |
| 718 | } |
| 719 | } |
| 720 | |
| 721 | if ((need_tesc_params && (msl_options.multi_patch_workgroup || !has_invocation_id || !has_primitive_id)) || |
| 722 | (need_tese_params && !has_primitive_id) || need_grid_params) |
| 723 | { |
| 724 | uint32_t type_ptr_id = ir.increase_bound_by(1); |
| 725 | |
| 726 | SPIRType uint_type_ptr = get_uint_type(); |
| 727 | uint_type_ptr.op = OpTypePointer; |
| 728 | uint_type_ptr.pointer = true; |
| 729 | uint_type_ptr.pointer_depth++; |
| 730 | uint_type_ptr.parent_type = get_uint_type_id(); |
| 731 | uint_type_ptr.storage = StorageClassInput; |
| 732 | auto &ptr_type = set<SPIRType>(type_ptr_id, uint_type_ptr); |
| 733 | ptr_type.self = get_uint_type_id(); |
| 734 | |
| 735 | if ((need_tesc_params && msl_options.multi_patch_workgroup) || need_grid_params) |
| 736 | { |
| 737 | uint32_t var_id = ir.increase_bound_by(1); |
| 738 | |
| 739 | // Create gl_GlobalInvocationID. |
| 740 | set<SPIRVariable>(var_id, type_ptr_id, StorageClassInput); |
| 741 | set_decoration(var_id, DecorationBuiltIn, BuiltInGlobalInvocationId); |
| 742 | builtin_invocation_id_id = var_id; |
| 743 | mark_implicit_builtin(StorageClassInput, BuiltInGlobalInvocationId, var_id); |
| 744 | } |
| 745 | else if (need_tesc_params && !has_invocation_id) |
| 746 | { |
| 747 | uint32_t var_id = ir.increase_bound_by(1); |
| 748 | |
| 749 | // Create gl_InvocationID. |
| 750 | set<SPIRVariable>(var_id, type_ptr_id, StorageClassInput); |
| 751 | set_decoration(var_id, DecorationBuiltIn, BuiltInInvocationId); |
| 752 | builtin_invocation_id_id = var_id; |
| 753 | mark_implicit_builtin(StorageClassInput, BuiltInInvocationId, var_id); |
| 754 | } |
| 755 | |
| 756 | if ((need_tesc_params || need_tese_params) && !has_primitive_id) |
| 757 | { |
| 758 | uint32_t var_id = ir.increase_bound_by(1); |
| 759 | |
| 760 | // Create gl_PrimitiveID. |
| 761 | set<SPIRVariable>(var_id, type_ptr_id, StorageClassInput); |
| 762 | set_decoration(var_id, DecorationBuiltIn, BuiltInPrimitiveId); |
| 763 | builtin_primitive_id_id = var_id; |
| 764 | mark_implicit_builtin(StorageClassInput, BuiltInPrimitiveId, var_id); |
| 765 | } |
| 766 | |
| 767 | if (need_grid_params) |
| 768 | { |
| 769 | uint32_t var_id = ir.increase_bound_by(1); |
| 770 | |
| 771 | set<SPIRVariable>(var_id, build_extended_vector_type(get_uint_type_id(), 3), StorageClassInput); |
| 772 | set_extended_decoration(var_id, SPIRVCrossDecorationBuiltInStageInputSize); |
| 773 | get_entry_point().interface_variables.push_back(var_id); |
| 774 | set_name(var_id, "spvStageInputSize"); |
| 775 | builtin_stage_input_size_id = var_id; |
| 776 | } |
| 777 | } |
| 778 | |
| 779 | if (!has_subgroup_invocation_id && (need_subgroup_mask || needs_subgroup_invocation_id)) |
| 780 | { |
| 781 | uint32_t offset = ir.increase_bound_by(2); |
| 782 | uint32_t type_ptr_id = offset; |
| 783 | uint32_t var_id = offset + 1; |
| 784 | |
| 785 | // Create gl_SubgroupInvocationID. |
| 786 | SPIRType uint_type_ptr = get_uint_type(); |
| 787 | uint_type_ptr.op = OpTypePointer; |
| 788 | uint_type_ptr.pointer = true; |
| 789 | uint_type_ptr.pointer_depth++; |
| 790 | uint_type_ptr.parent_type = get_uint_type_id(); |
| 791 | uint_type_ptr.storage = StorageClassInput; |
| 792 | auto &ptr_type = set<SPIRType>(type_ptr_id, uint_type_ptr); |
| 793 | ptr_type.self = get_uint_type_id(); |
| 794 | |
| 795 | set<SPIRVariable>(var_id, type_ptr_id, StorageClassInput); |
| 796 | set_decoration(var_id, DecorationBuiltIn, BuiltInSubgroupLocalInvocationId); |
| 797 | builtin_subgroup_invocation_id_id = var_id; |
| 798 | mark_implicit_builtin(StorageClassInput, BuiltInSubgroupLocalInvocationId, var_id); |
| 799 | } |
| 800 | |
| 801 | if (!has_subgroup_size && (need_subgroup_ge_mask || needs_subgroup_size)) |
| 802 | { |
| 803 | uint32_t offset = ir.increase_bound_by(2); |
| 804 | uint32_t type_ptr_id = offset; |
| 805 | uint32_t var_id = offset + 1; |
| 806 | |
| 807 | // Create gl_SubgroupSize. |
| 808 | SPIRType uint_type_ptr = get_uint_type(); |
| 809 | uint_type_ptr.op = OpTypePointer; |
| 810 | uint_type_ptr.pointer = true; |
| 811 | uint_type_ptr.pointer_depth++; |
| 812 | uint_type_ptr.parent_type = get_uint_type_id(); |
| 813 | uint_type_ptr.storage = StorageClassInput; |
| 814 | auto &ptr_type = set<SPIRType>(type_ptr_id, uint_type_ptr); |
| 815 | ptr_type.self = get_uint_type_id(); |
| 816 | |
| 817 | set<SPIRVariable>(var_id, type_ptr_id, StorageClassInput); |
| 818 | set_decoration(var_id, DecorationBuiltIn, BuiltInSubgroupSize); |
| 819 | builtin_subgroup_size_id = var_id; |
| 820 | mark_implicit_builtin(StorageClassInput, BuiltInSubgroupSize, var_id); |
| 821 | } |
| 822 | |
| 823 | if (need_dispatch_base || need_vertex_base_params) |
| 824 | { |
| 825 | if (workgroup_id_type == 0) |
| 826 | workgroup_id_type = build_extended_vector_type(get_uint_type_id(), 3); |
| 827 | uint32_t var_id; |
| 828 | if (msl_options.supports_msl_version(1, 2)) |
| 829 | { |
| 830 | // If we have MSL 1.2, we can (ab)use the [[grid_origin]] builtin |
| 831 | // to convey this information and save a buffer slot. |
| 832 | uint32_t offset = ir.increase_bound_by(1); |
| 833 | var_id = offset; |
| 834 | |
| 835 | set<SPIRVariable>(var_id, workgroup_id_type, StorageClassInput); |
| 836 | set_extended_decoration(var_id, SPIRVCrossDecorationBuiltInDispatchBase); |
| 837 | get_entry_point().interface_variables.push_back(var_id); |
| 838 | } |
| 839 | else |
| 840 | { |
| 841 | // Otherwise, we need to fall back to a good ol' fashioned buffer. |
| 842 | uint32_t offset = ir.increase_bound_by(2); |
| 843 | var_id = offset; |
| 844 | uint32_t type_id = offset + 1; |
| 845 | |
| 846 | SPIRType var_type = get<SPIRType>(workgroup_id_type); |
| 847 | var_type.storage = StorageClassUniform; |
| 848 | set<SPIRType>(type_id, var_type); |
| 849 | |
| 850 | set<SPIRVariable>(var_id, type_id, StorageClassUniform); |
| 851 | // This should never match anything. |
| 852 | set_decoration(var_id, DecorationDescriptorSet, ~(5u)); |
| 853 | set_decoration(var_id, DecorationBinding, msl_options.indirect_params_buffer_index); |
| 854 | set_extended_decoration(var_id, SPIRVCrossDecorationResourceIndexPrimary, |
| 855 | msl_options.indirect_params_buffer_index); |
| 856 | } |
| 857 | set_name(var_id, "spvDispatchBase"); |
| 858 | builtin_dispatch_base_id = var_id; |
| 859 | } |
| 860 | |
| 861 | if (has_additional_fixed_sample_mask() && !does_shader_write_sample_mask) |
| 862 | { |
| 863 | uint32_t offset = ir.increase_bound_by(2); |
| 864 | uint32_t var_id = offset + 1; |
| 865 | |
| 866 | // Create gl_SampleMask. |
| 867 | SPIRType uint_type_ptr_out = get_uint_type(); |
| 868 | uint_type_ptr_out.op = OpTypePointer; |
| 869 | uint_type_ptr_out.pointer = true; |
| 870 | uint_type_ptr_out.pointer_depth++; |
| 871 | uint_type_ptr_out.parent_type = get_uint_type_id(); |
| 872 | uint_type_ptr_out.storage = StorageClassOutput; |
| 873 | |
| 874 | auto &ptr_out_type = set<SPIRType>(offset, uint_type_ptr_out); |
| 875 | ptr_out_type.self = get_uint_type_id(); |
| 876 | set<SPIRVariable>(var_id, offset, StorageClassOutput); |
| 877 | set_decoration(var_id, DecorationBuiltIn, BuiltInSampleMask); |
| 878 | builtin_sample_mask_id = var_id; |
| 879 | mark_implicit_builtin(StorageClassOutput, BuiltInSampleMask, var_id); |
| 880 | } |
| 881 | |
| 882 | if (!has_helper_invocation && needs_helper_invocation) |
| 883 | { |
| 884 | uint32_t offset = ir.increase_bound_by(3); |
| 885 | uint32_t type_id = offset; |
| 886 | uint32_t type_ptr_id = offset + 1; |
| 887 | uint32_t var_id = offset + 2; |
| 888 | |
| 889 | // Create gl_HelperInvocation. |
| 890 | SPIRType bool_type { OpTypeBool }; |
| 891 | bool_type.basetype = SPIRType::Boolean; |
| 892 | bool_type.width = 8; |
| 893 | bool_type.vecsize = 1; |
| 894 | set<SPIRType>(type_id, bool_type); |
| 895 | |
| 896 | SPIRType bool_type_ptr_in = bool_type; |
| 897 | bool_type_ptr_in.op = spv::OpTypePointer; |
| 898 | bool_type_ptr_in.pointer = true; |
| 899 | bool_type_ptr_in.pointer_depth++; |
| 900 | bool_type_ptr_in.parent_type = type_id; |
| 901 | bool_type_ptr_in.storage = StorageClassInput; |
| 902 | |
| 903 | auto &ptr_in_type = set<SPIRType>(type_ptr_id, bool_type_ptr_in); |
| 904 | ptr_in_type.self = type_id; |
| 905 | set<SPIRVariable>(var_id, type_ptr_id, StorageClassInput); |
| 906 | set_decoration(var_id, DecorationBuiltIn, BuiltInHelperInvocation); |
| 907 | builtin_helper_invocation_id = var_id; |
| 908 | mark_implicit_builtin(StorageClassInput, BuiltInHelperInvocation, var_id); |
| 909 | } |
| 910 | |
| 911 | if (need_local_invocation_index && !has_local_invocation_index) |
| 912 | { |
| 913 | uint32_t offset = ir.increase_bound_by(2); |
| 914 | uint32_t type_ptr_id = offset; |
| 915 | uint32_t var_id = offset + 1; |
| 916 | |
| 917 | // Create gl_LocalInvocationIndex. |
| 918 | SPIRType uint_type_ptr = get_uint_type(); |
| 919 | uint_type_ptr.op = OpTypePointer; |
| 920 | uint_type_ptr.pointer = true; |
| 921 | uint_type_ptr.pointer_depth++; |
| 922 | uint_type_ptr.parent_type = get_uint_type_id(); |
| 923 | uint_type_ptr.storage = StorageClassInput; |
| 924 | |
| 925 | auto &ptr_type = set<SPIRType>(type_ptr_id, uint_type_ptr); |
| 926 | ptr_type.self = get_uint_type_id(); |
| 927 | set<SPIRVariable>(var_id, type_ptr_id, StorageClassInput); |
| 928 | set_decoration(var_id, DecorationBuiltIn, BuiltInLocalInvocationIndex); |
| 929 | builtin_local_invocation_index_id = var_id; |
| 930 | mark_implicit_builtin(StorageClassInput, BuiltInLocalInvocationIndex, var_id); |
| 931 | } |
| 932 | |
| 933 | if (need_workgroup_size && !has_workgroup_size) |
| 934 | { |
| 935 | auto &execution = get_entry_point(); |
| 936 | // First, check if the workgroup size _constant_ were defined. |
| 937 | // If it were, we don't need to do--in fact, shouldn't do--anything. |
| 938 | builtin_workgroup_size_id = execution.workgroup_size.constant; |
| 939 | if (builtin_workgroup_size_id == 0) |
| 940 | { |
| 941 | uint32_t var_id = ir.increase_bound_by(1); |
| 942 | |
| 943 | // Create gl_WorkgroupSize. |
| 944 | uint32_t type_id = build_extended_vector_type(get_uint_type_id(), 3); |
| 945 | // If we have LocalSize or LocalSizeId, use those to define the workgroup size. |
| 946 | if (execution.flags.get(ExecutionModeLocalSizeId)) |
| 947 | { |
| 948 | const SPIRConstant *init[] = { &get<SPIRConstant>(execution.workgroup_size.id_x), |
| 949 | &get<SPIRConstant>(execution.workgroup_size.id_y), |
| 950 | &get<SPIRConstant>(execution.workgroup_size.id_z) }; |
| 951 | bool specialized = init[0]->specialization || init[1]->specialization || init[2]->specialization; |
| 952 | set<SPIRConstant>(var_id, type_id, init, 3, specialized); |
| 953 | execution.workgroup_size.constant = var_id; |
| 954 | } |
| 955 | else if (execution.flags.get(ExecutionModeLocalSize)) |
| 956 | { |
| 957 | uint32_t offset = ir.increase_bound_by(3); |
| 958 | const SPIRConstant *init[] = { |
| 959 | &set<SPIRConstant>(offset, get_uint_type_id(), execution.workgroup_size.x, false), |
| 960 | &set<SPIRConstant>(offset + 1, get_uint_type_id(), execution.workgroup_size.y, false), |
| 961 | &set<SPIRConstant>(offset + 2, get_uint_type_id(), execution.workgroup_size.z, false) |
| 962 | }; |
| 963 | set<SPIRConstant>(var_id, type_id, init, 3, false); |
| 964 | execution.workgroup_size.constant = var_id; |
| 965 | } |
| 966 | else |
| 967 | { |
| 968 | uint32_t type_ptr_id = ir.increase_bound_by(1); |
| 969 | SPIRType uint_type_ptr = get<SPIRType>(type_id); |
| 970 | uint_type_ptr.op = OpTypePointer; |
| 971 | uint_type_ptr.pointer = true; |
| 972 | uint_type_ptr.pointer_depth++; |
| 973 | uint_type_ptr.parent_type = type_id; |
| 974 | uint_type_ptr.storage = StorageClassInput; |
| 975 | |
| 976 | auto &ptr_type = set<SPIRType>(type_ptr_id, uint_type_ptr); |
| 977 | ptr_type.self = type_id; |
| 978 | set<SPIRVariable>(var_id, type_ptr_id, StorageClassInput); |
| 979 | mark_implicit_builtin(StorageClassInput, BuiltInWorkgroupSize, var_id); |
| 980 | } |
| 981 | set_decoration(var_id, DecorationBuiltIn, BuiltInWorkgroupSize); |
| 982 | builtin_workgroup_size_id = var_id; |
| 983 | } |
| 984 | } |
| 985 | |
| 986 | if (!has_frag_depth && force_frag_depth_passthrough) |
| 987 | { |
| 988 | uint32_t offset = ir.increase_bound_by(3); |
| 989 | uint32_t type_id = offset; |
| 990 | uint32_t type_ptr_id = offset + 1; |
| 991 | uint32_t var_id = offset + 2; |
| 992 | |
| 993 | // Create gl_FragDepth |
| 994 | SPIRType float_type { OpTypeFloat }; |
| 995 | float_type.basetype = SPIRType::Float; |
| 996 | float_type.width = 32; |
| 997 | float_type.vecsize = 1; |
| 998 | set<SPIRType>(type_id, float_type); |
| 999 | |
| 1000 | SPIRType float_type_ptr_in = float_type; |
| 1001 | float_type_ptr_in.op = spv::OpTypePointer; |
| 1002 | float_type_ptr_in.pointer = true; |
| 1003 | float_type_ptr_in.pointer_depth++; |
| 1004 | float_type_ptr_in.parent_type = type_id; |
| 1005 | float_type_ptr_in.storage = StorageClassOutput; |
| 1006 | |
| 1007 | auto &ptr_in_type = set<SPIRType>(type_ptr_id, float_type_ptr_in); |
| 1008 | ptr_in_type.self = type_id; |
| 1009 | set<SPIRVariable>(var_id, type_ptr_id, StorageClassOutput); |
| 1010 | set_decoration(var_id, DecorationBuiltIn, BuiltInFragDepth); |
| 1011 | builtin_frag_depth_id = var_id; |
| 1012 | mark_implicit_builtin(StorageClassOutput, BuiltInFragDepth, var_id); |
| 1013 | active_output_builtins.set(BuiltInFragDepth); |
| 1014 | } |
| 1015 | |
| 1016 | if (!has_point_size && need_point_size) |
| 1017 | { |
| 1018 | uint32_t offset = ir.increase_bound_by(3); |
| 1019 | uint32_t type_id = offset; |
| 1020 | uint32_t type_ptr_id = offset + 1; |
| 1021 | uint32_t var_id = offset + 2; |
| 1022 | |
| 1023 | // Create gl_PointSize |
| 1024 | SPIRType float_type { OpTypeFloat }; |
| 1025 | float_type.basetype = SPIRType::Float; |
| 1026 | float_type.width = 32; |
| 1027 | float_type.vecsize = 1; |
| 1028 | set<SPIRType>(type_id, float_type); |
| 1029 | |
| 1030 | SPIRType float_type_ptr_in = float_type; |
| 1031 | float_type_ptr_in.op = spv::OpTypePointer; |
| 1032 | float_type_ptr_in.pointer = true; |
| 1033 | float_type_ptr_in.pointer_depth++; |
| 1034 | float_type_ptr_in.parent_type = type_id; |
| 1035 | float_type_ptr_in.storage = StorageClassOutput; |
| 1036 | |
| 1037 | auto &ptr_in_type = set<SPIRType>(type_ptr_id, float_type_ptr_in); |
| 1038 | ptr_in_type.self = type_id; |
| 1039 | set<SPIRVariable>(var_id, type_ptr_id, StorageClassOutput); |
| 1040 | set_decoration(var_id, DecorationBuiltIn, BuiltInPointSize); |
| 1041 | mark_implicit_builtin(StorageClassOutput, BuiltInPointSize, var_id); |
| 1042 | } |
| 1043 | } |
| 1044 | |
| 1045 | if (needs_swizzle_buffer_def) |
| 1046 | { |
| 1047 | uint32_t var_id = build_constant_uint_array_pointer(); |
| 1048 | set_name(var_id, "spvSwizzleConstants"); |
| 1049 | // This should never match anything. |
| 1050 | set_decoration(var_id, DecorationDescriptorSet, kSwizzleBufferBinding); |
| 1051 | set_decoration(var_id, DecorationBinding, msl_options.swizzle_buffer_index); |
| 1052 | set_extended_decoration(var_id, SPIRVCrossDecorationResourceIndexPrimary, msl_options.swizzle_buffer_index); |
| 1053 | swizzle_buffer_id = var_id; |
| 1054 | } |
| 1055 | |
| 1056 | if (needs_buffer_size_buffer()) |
| 1057 | { |
| 1058 | uint32_t var_id = build_constant_uint_array_pointer(); |
| 1059 | set_name(var_id, "spvBufferSizeConstants"); |
| 1060 | // This should never match anything. |
| 1061 | set_decoration(var_id, DecorationDescriptorSet, kBufferSizeBufferBinding); |
| 1062 | set_decoration(var_id, DecorationBinding, msl_options.buffer_size_buffer_index); |
| 1063 | set_extended_decoration(var_id, SPIRVCrossDecorationResourceIndexPrimary, msl_options.buffer_size_buffer_index); |
| 1064 | buffer_size_buffer_id = var_id; |
| 1065 | } |
| 1066 | |
| 1067 | if (needs_view_mask_buffer()) |
| 1068 | { |
| 1069 | uint32_t var_id = build_constant_uint_array_pointer(); |
| 1070 | set_name(var_id, "spvViewMask"); |
| 1071 | // This should never match anything. |
| 1072 | set_decoration(var_id, DecorationDescriptorSet, ~(4u)); |
| 1073 | set_decoration(var_id, DecorationBinding, msl_options.view_mask_buffer_index); |
| 1074 | set_extended_decoration(var_id, SPIRVCrossDecorationResourceIndexPrimary, msl_options.view_mask_buffer_index); |
| 1075 | view_mask_buffer_id = var_id; |
| 1076 | } |
| 1077 | |
| 1078 | if (!buffers_requiring_dynamic_offset.empty()) |
| 1079 | { |
| 1080 | uint32_t var_id = build_constant_uint_array_pointer(); |
| 1081 | set_name(var_id, "spvDynamicOffsets"); |
| 1082 | // This should never match anything. |
| 1083 | set_decoration(var_id, DecorationDescriptorSet, ~(5u)); |
| 1084 | set_decoration(var_id, DecorationBinding, msl_options.dynamic_offsets_buffer_index); |
| 1085 | set_extended_decoration(var_id, SPIRVCrossDecorationResourceIndexPrimary, |
| 1086 | msl_options.dynamic_offsets_buffer_index); |
| 1087 | dynamic_offsets_buffer_id = var_id; |
| 1088 | } |
| 1089 | |
| 1090 | // If we're returning a struct from a vertex-like entry point, we must return a position attribute. |
| 1091 | bool need_position = (get_execution_model() == ExecutionModelVertex || is_tese_shader()) && |
| 1092 | !capture_output_to_buffer && !get_is_rasterization_disabled() && |
| 1093 | !msl_options.auto_disable_rasterization && |
| 1094 | !active_output_builtins.get(BuiltInPosition); |
| 1095 | |
| 1096 | if (need_position) |
| 1097 | { |
| 1098 | // If we can get away with returning void from entry point, we don't need to care. |
| 1099 | // If there is at least one other stage output, we need to return [[position]], |
| 1100 | // so we need to create one if it doesn't appear in the SPIR-V. Before adding the |
| 1101 | // implicit variable, check if it actually exists already, but just has not been used |
| 1102 | // or initialized, and if so, mark it as active, and do not create the implicit variable. |
| 1103 | bool has_output = false; |
| 1104 | ir.for_each_typed_id<SPIRVariable>([&](uint32_t, SPIRVariable &var) { |
| 1105 | if (var.storage == StorageClassOutput && interface_variable_exists_in_entry_point(var.self)) |
| 1106 | { |
| 1107 | has_output = true; |
| 1108 | |
| 1109 | // Check if the var is the Position builtin |
| 1110 | if (has_decoration(var.self, DecorationBuiltIn) && get_decoration(var.self, DecorationBuiltIn) == BuiltInPosition) |
| 1111 | active_output_builtins.set(BuiltInPosition); |
| 1112 | |
| 1113 | // If the var is a struct, check if any members is the Position builtin |
| 1114 | auto &var_type = get_variable_element_type(var); |
| 1115 | if (var_type.basetype == SPIRType::Struct) |
| 1116 | { |
| 1117 | auto mbr_cnt = var_type.member_types.size(); |
| 1118 | for (uint32_t mbr_idx = 0; mbr_idx < mbr_cnt; mbr_idx++) |
| 1119 | { |
| 1120 | auto builtin = BuiltInMax; |
| 1121 | bool is_builtin = is_member_builtin(var_type, mbr_idx, &builtin); |
| 1122 | if (is_builtin && builtin == BuiltInPosition) |
| 1123 | active_output_builtins.set(BuiltInPosition); |
| 1124 | } |
| 1125 | } |
| 1126 | } |
| 1127 | }); |
| 1128 | need_position = has_output && !active_output_builtins.get(BuiltInPosition); |
| 1129 | } |
| 1130 | else if (!active_output_builtins.get(BuiltInPosition) && msl_options.auto_disable_rasterization) |
| 1131 | { |
| 1132 | is_rasterization_disabled = true; |
| 1133 | } |
| 1134 | |
| 1135 | if (need_position) |
| 1136 | { |
| 1137 | uint32_t offset = ir.increase_bound_by(3); |
| 1138 | uint32_t type_id = offset; |
| 1139 | uint32_t type_ptr_id = offset + 1; |
| 1140 | uint32_t var_id = offset + 2; |
| 1141 | |
| 1142 | // Create gl_Position. |
| 1143 | SPIRType vec4_type { OpTypeVector }; |
| 1144 | vec4_type.basetype = SPIRType::Float; |
| 1145 | vec4_type.width = 32; |
| 1146 | vec4_type.vecsize = 4; |
| 1147 | set<SPIRType>(type_id, vec4_type); |
| 1148 | |
| 1149 | SPIRType vec4_type_ptr = vec4_type; |
| 1150 | vec4_type_ptr.op = OpTypePointer; |
| 1151 | vec4_type_ptr.pointer = true; |
| 1152 | vec4_type_ptr.pointer_depth++; |
| 1153 | vec4_type_ptr.parent_type = type_id; |
| 1154 | vec4_type_ptr.storage = StorageClassOutput; |
| 1155 | auto &ptr_type = set<SPIRType>(type_ptr_id, vec4_type_ptr); |
| 1156 | ptr_type.self = type_id; |
| 1157 | |
| 1158 | set<SPIRVariable>(var_id, type_ptr_id, StorageClassOutput); |
| 1159 | set_decoration(var_id, DecorationBuiltIn, BuiltInPosition); |
| 1160 | mark_implicit_builtin(StorageClassOutput, BuiltInPosition, var_id); |
| 1161 | } |
| 1162 | |
| 1163 | if (is_mesh_shader()) |
| 1164 | { |
| 1165 | uint32_t offset = ir.increase_bound_by(2); |
| 1166 | uint32_t type_ptr_id = offset; |
| 1167 | uint32_t var_id = offset + 1; |
| 1168 | |
| 1169 | // Create variable to store meshlet size. |
| 1170 | uint32_t type_id = build_extended_vector_type(get_uint_type_id(), 2); |
| 1171 | SPIRType uint_type_ptr = get<SPIRType>(type_id); |
| 1172 | uint_type_ptr.op = OpTypePointer; |
| 1173 | uint_type_ptr.pointer = true; |
| 1174 | uint_type_ptr.pointer_depth++; |
| 1175 | uint_type_ptr.parent_type = type_id; |
| 1176 | uint_type_ptr.storage = StorageClassWorkgroup; |
| 1177 | |
| 1178 | auto &ptr_type = set<SPIRType>(type_ptr_id, uint_type_ptr); |
| 1179 | ptr_type.self = type_id; |
| 1180 | set<SPIRVariable>(var_id, type_ptr_id, StorageClassWorkgroup); |
| 1181 | set_name(var_id, "spvMeshSizes"); |
| 1182 | builtin_mesh_sizes_id = var_id; |
| 1183 | } |
| 1184 | |
| 1185 | if (get_execution_model() == spv::ExecutionModelTaskEXT) |
| 1186 | { |
| 1187 | uint32_t offset = ir.increase_bound_by(3); |
| 1188 | uint32_t type_id = offset; |
| 1189 | uint32_t type_ptr_id = offset + 1; |
| 1190 | uint32_t var_id = offset + 2; |
| 1191 | |
| 1192 | SPIRType mesh_grid_type { OpTypeStruct }; |
| 1193 | mesh_grid_type.basetype = SPIRType::MeshGridProperties; |
| 1194 | set<SPIRType>(type_id, mesh_grid_type); |
| 1195 | |
| 1196 | SPIRType mesh_grid_type_ptr = mesh_grid_type; |
| 1197 | mesh_grid_type_ptr.op = spv::OpTypePointer; |
| 1198 | mesh_grid_type_ptr.pointer = true; |
| 1199 | mesh_grid_type_ptr.pointer_depth++; |
| 1200 | mesh_grid_type_ptr.parent_type = type_id; |
| 1201 | mesh_grid_type_ptr.storage = StorageClassOutput; |
| 1202 | |
| 1203 | auto &ptr_in_type = set<SPIRType>(type_ptr_id, mesh_grid_type_ptr); |
| 1204 | ptr_in_type.self = type_id; |
| 1205 | set<SPIRVariable>(var_id, type_ptr_id, StorageClassOutput); |
| 1206 | set_name(var_id, "spvMgp"); |
| 1207 | builtin_task_grid_id = var_id; |
| 1208 | } |
| 1209 | } |
| 1210 | |
| 1211 | // Checks if the specified builtin variable (e.g. gl_InstanceIndex) is marked as active. |
| 1212 | // If not, it marks it as active and forces a recompilation. |
| 1213 | // This might be used when the optimization of inactive builtins was too optimistic (e.g. when "spvOut" is emitted). |
| 1214 | void CompilerMSL::ensure_builtin(spv::StorageClass storage, spv::BuiltIn builtin) |
| 1215 | { |
| 1216 | Bitset *active_builtins = nullptr; |
| 1217 | switch (storage) |
| 1218 | { |
| 1219 | case StorageClassInput: |
| 1220 | active_builtins = &active_input_builtins; |
| 1221 | break; |
| 1222 | |
| 1223 | case StorageClassOutput: |
| 1224 | active_builtins = &active_output_builtins; |
| 1225 | break; |
| 1226 | |
| 1227 | default: |
| 1228 | break; |
| 1229 | } |
| 1230 | |
| 1231 | // At this point, the specified builtin variable must have already been declared in the entry point. |
| 1232 | // If not, mark as active and force recompile. |
| 1233 | if (active_builtins != nullptr && !active_builtins->get(builtin)) |
| 1234 | { |
| 1235 | active_builtins->set(builtin); |
| 1236 | force_recompile(); |
| 1237 | } |
| 1238 | } |
| 1239 | |
| 1240 | void CompilerMSL::mark_implicit_builtin(StorageClass storage, BuiltIn builtin, uint32_t id) |
| 1241 | { |
| 1242 | Bitset *active_builtins = nullptr; |
| 1243 | switch (storage) |
| 1244 | { |
| 1245 | case StorageClassInput: |
| 1246 | active_builtins = &active_input_builtins; |
| 1247 | break; |
| 1248 | |
| 1249 | case StorageClassOutput: |
| 1250 | active_builtins = &active_output_builtins; |
| 1251 | break; |
| 1252 | |
| 1253 | default: |
| 1254 | break; |
| 1255 | } |
| 1256 | |
| 1257 | assert(active_builtins != nullptr); |
| 1258 | active_builtins->set(builtin); |
| 1259 | |
| 1260 | auto &var = get_entry_point().interface_variables; |
| 1261 | if (find(begin(var), end(var), VariableID(id)) == end(var)) |
| 1262 | var.push_back(id); |
| 1263 | } |
| 1264 | |
| 1265 | uint32_t CompilerMSL::build_constant_uint_array_pointer() |
| 1266 | { |
| 1267 | uint32_t offset = ir.increase_bound_by(3); |
| 1268 | uint32_t type_ptr_id = offset; |
| 1269 | uint32_t type_ptr_ptr_id = offset + 1; |
| 1270 | uint32_t var_id = offset + 2; |
| 1271 | |
| 1272 | // Create a buffer to hold extra data, including the swizzle constants. |
| 1273 | SPIRType uint_type_pointer = get_uint_type(); |
| 1274 | uint_type_pointer.op = OpTypePointer; |
| 1275 | uint_type_pointer.pointer = true; |
| 1276 | uint_type_pointer.pointer_depth++; |
| 1277 | uint_type_pointer.parent_type = get_uint_type_id(); |
| 1278 | uint_type_pointer.storage = StorageClassUniform; |
| 1279 | set<SPIRType>(type_ptr_id, uint_type_pointer); |
| 1280 | set_decoration(type_ptr_id, DecorationArrayStride, 4); |
| 1281 | |
| 1282 | SPIRType uint_type_pointer2 = uint_type_pointer; |
| 1283 | uint_type_pointer2.pointer_depth++; |
| 1284 | uint_type_pointer2.parent_type = type_ptr_id; |
| 1285 | set<SPIRType>(type_ptr_ptr_id, uint_type_pointer2); |
| 1286 | |
| 1287 | set<SPIRVariable>(var_id, type_ptr_ptr_id, StorageClassUniformConstant); |
| 1288 | return var_id; |
| 1289 | } |
| 1290 | |
| 1291 | static string create_sampler_address(const char *prefix, MSLSamplerAddress addr) |
| 1292 | { |
| 1293 | switch (addr) |
| 1294 | { |
| 1295 | case MSL_SAMPLER_ADDRESS_CLAMP_TO_EDGE: |
| 1296 | return join(prefix, "address::clamp_to_edge"); |
| 1297 | case MSL_SAMPLER_ADDRESS_CLAMP_TO_ZERO: |
| 1298 | return join(prefix, "address::clamp_to_zero"); |
| 1299 | case MSL_SAMPLER_ADDRESS_CLAMP_TO_BORDER: |
| 1300 | return join(prefix, "address::clamp_to_border"); |
| 1301 | case MSL_SAMPLER_ADDRESS_REPEAT: |
| 1302 | return join(prefix, "address::repeat"); |
| 1303 | case MSL_SAMPLER_ADDRESS_MIRRORED_REPEAT: |
| 1304 | return join(prefix, "address::mirrored_repeat"); |
| 1305 | default: |
| 1306 | SPIRV_CROSS_THROW("Invalid sampler addressing mode."); |
| 1307 | } |
| 1308 | } |
| 1309 | |
| 1310 | SPIRType &CompilerMSL::get_stage_in_struct_type() |
| 1311 | { |
| 1312 | auto &si_var = get<SPIRVariable>(stage_in_var_id); |
| 1313 | return get_variable_data_type(si_var); |
| 1314 | } |
| 1315 | |
| 1316 | SPIRType &CompilerMSL::get_stage_out_struct_type() |
| 1317 | { |
| 1318 | auto &so_var = get<SPIRVariable>(stage_out_var_id); |
| 1319 | return get_variable_data_type(so_var); |
| 1320 | } |
| 1321 | |
| 1322 | SPIRType &CompilerMSL::get_patch_stage_in_struct_type() |
| 1323 | { |
| 1324 | auto &si_var = get<SPIRVariable>(patch_stage_in_var_id); |
| 1325 | return get_variable_data_type(si_var); |
| 1326 | } |
| 1327 | |
| 1328 | SPIRType &CompilerMSL::get_patch_stage_out_struct_type() |
| 1329 | { |
| 1330 | auto &so_var = get<SPIRVariable>(patch_stage_out_var_id); |
| 1331 | return get_variable_data_type(so_var); |
| 1332 | } |
| 1333 | |
| 1334 | std::string CompilerMSL::get_tess_factor_struct_name() |
| 1335 | { |
| 1336 | if (is_tessellating_triangles()) |
| 1337 | return "MTLTriangleTessellationFactorsHalf"; |
| 1338 | return "MTLQuadTessellationFactorsHalf"; |
| 1339 | } |
| 1340 | |
| 1341 | SPIRType &CompilerMSL::get_uint_type() |
| 1342 | { |
| 1343 | return get<SPIRType>(get_uint_type_id()); |
| 1344 | } |
| 1345 | |
| 1346 | uint32_t CompilerMSL::get_uint_type_id() |
| 1347 | { |
| 1348 | if (uint_type_id != 0) |
| 1349 | return uint_type_id; |
| 1350 | |
| 1351 | uint_type_id = ir.increase_bound_by(1); |
| 1352 | |
| 1353 | SPIRType type { OpTypeInt }; |
| 1354 | type.basetype = SPIRType::UInt; |
| 1355 | type.width = 32; |
| 1356 | set<SPIRType>(uint_type_id, type); |
| 1357 | return uint_type_id; |
| 1358 | } |
| 1359 | |
| 1360 | void CompilerMSL::emit_entry_point_declarations() |
| 1361 | { |
| 1362 | // FIXME: Get test coverage here ... |
| 1363 | // Constant arrays of non-primitive types (i.e. matrices) won't link properly into Metal libraries |
| 1364 | declare_complex_constant_arrays(); |
| 1365 | |
| 1366 | // Emit constexpr samplers here. |
| 1367 | for (auto &samp : constexpr_samplers_by_id) |
| 1368 | { |
| 1369 | auto &var = get<SPIRVariable>(samp.first); |
| 1370 | auto &type = get<SPIRType>(var.basetype); |
| 1371 | if (type.basetype == SPIRType::Sampler) |
| 1372 | add_resource_name(samp.first); |
| 1373 | |
| 1374 | SmallVector<string> args; |
| 1375 | auto &s = samp.second; |
| 1376 | |
| 1377 | if (s.coord != MSL_SAMPLER_COORD_NORMALIZED) |
| 1378 | args.push_back("coord::pixel"); |
| 1379 | |
| 1380 | if (s.min_filter == s.mag_filter) |
| 1381 | { |
| 1382 | if (s.min_filter != MSL_SAMPLER_FILTER_NEAREST) |
| 1383 | args.push_back("filter::linear"); |
| 1384 | } |
| 1385 | else |
| 1386 | { |
| 1387 | if (s.min_filter != MSL_SAMPLER_FILTER_NEAREST) |
| 1388 | args.push_back("min_filter::linear"); |
| 1389 | if (s.mag_filter != MSL_SAMPLER_FILTER_NEAREST) |
| 1390 | args.push_back("mag_filter::linear"); |
| 1391 | } |
| 1392 | |
| 1393 | switch (s.mip_filter) |
| 1394 | { |
| 1395 | case MSL_SAMPLER_MIP_FILTER_NONE: |
| 1396 | // Default |
| 1397 | break; |
| 1398 | case MSL_SAMPLER_MIP_FILTER_NEAREST: |
| 1399 | args.push_back("mip_filter::nearest"); |
| 1400 | break; |
| 1401 | case MSL_SAMPLER_MIP_FILTER_LINEAR: |
| 1402 | args.push_back("mip_filter::linear"); |
| 1403 | break; |
| 1404 | default: |
| 1405 | SPIRV_CROSS_THROW("Invalid mip filter."); |
| 1406 | } |
| 1407 | |
| 1408 | if (s.s_address == s.t_address && s.s_address == s.r_address) |
| 1409 | { |
| 1410 | if (s.s_address != MSL_SAMPLER_ADDRESS_CLAMP_TO_EDGE) |
| 1411 | args.push_back(create_sampler_address("", s.s_address)); |
| 1412 | } |
| 1413 | else |
| 1414 | { |
| 1415 | if (s.s_address != MSL_SAMPLER_ADDRESS_CLAMP_TO_EDGE) |
| 1416 | args.push_back(create_sampler_address("s_", s.s_address)); |
| 1417 | if (s.t_address != MSL_SAMPLER_ADDRESS_CLAMP_TO_EDGE) |
| 1418 | args.push_back(create_sampler_address("t_", s.t_address)); |
| 1419 | if (s.r_address != MSL_SAMPLER_ADDRESS_CLAMP_TO_EDGE) |
| 1420 | args.push_back(create_sampler_address("r_", s.r_address)); |
| 1421 | } |
| 1422 | |
| 1423 | if (s.compare_enable) |
| 1424 | { |
| 1425 | switch (s.compare_func) |
| 1426 | { |
| 1427 | case MSL_SAMPLER_COMPARE_FUNC_ALWAYS: |
| 1428 | args.push_back("compare_func::always"); |
| 1429 | break; |
| 1430 | case MSL_SAMPLER_COMPARE_FUNC_NEVER: |
| 1431 | args.push_back("compare_func::never"); |
| 1432 | break; |
| 1433 | case MSL_SAMPLER_COMPARE_FUNC_EQUAL: |
| 1434 | args.push_back("compare_func::equal"); |
| 1435 | break; |
| 1436 | case MSL_SAMPLER_COMPARE_FUNC_NOT_EQUAL: |
| 1437 | args.push_back("compare_func::not_equal"); |
| 1438 | break; |
| 1439 | case MSL_SAMPLER_COMPARE_FUNC_LESS: |
| 1440 | args.push_back("compare_func::less"); |
| 1441 | break; |
| 1442 | case MSL_SAMPLER_COMPARE_FUNC_LESS_EQUAL: |
| 1443 | args.push_back("compare_func::less_equal"); |
| 1444 | break; |
| 1445 | case MSL_SAMPLER_COMPARE_FUNC_GREATER: |
| 1446 | args.push_back("compare_func::greater"); |
| 1447 | break; |
| 1448 | case MSL_SAMPLER_COMPARE_FUNC_GREATER_EQUAL: |
| 1449 | args.push_back("compare_func::greater_equal"); |
| 1450 | break; |
| 1451 | default: |
| 1452 | SPIRV_CROSS_THROW("Invalid sampler compare function."); |
| 1453 | } |
| 1454 | } |
| 1455 | |
| 1456 | if (s.s_address == MSL_SAMPLER_ADDRESS_CLAMP_TO_BORDER || s.t_address == MSL_SAMPLER_ADDRESS_CLAMP_TO_BORDER || |
| 1457 | s.r_address == MSL_SAMPLER_ADDRESS_CLAMP_TO_BORDER) |
| 1458 | { |
| 1459 | switch (s.border_color) |
| 1460 | { |
| 1461 | case MSL_SAMPLER_BORDER_COLOR_OPAQUE_BLACK: |
| 1462 | args.push_back("border_color::opaque_black"); |
| 1463 | break; |
| 1464 | case MSL_SAMPLER_BORDER_COLOR_OPAQUE_WHITE: |
| 1465 | args.push_back("border_color::opaque_white"); |
| 1466 | break; |
| 1467 | case MSL_SAMPLER_BORDER_COLOR_TRANSPARENT_BLACK: |
| 1468 | args.push_back("border_color::transparent_black"); |
| 1469 | break; |
| 1470 | default: |
| 1471 | SPIRV_CROSS_THROW("Invalid sampler border color."); |
| 1472 | } |
| 1473 | } |
| 1474 | |
| 1475 | if (s.anisotropy_enable) |
| 1476 | args.push_back(join("max_anisotropy(", s.max_anisotropy, ")")); |
| 1477 | if (s.lod_clamp_enable) |
| 1478 | { |
| 1479 | args.push_back(join("lod_clamp(", format_float(s.lod_clamp_min), ", ", format_float(s.lod_clamp_max), ")")); |
| 1480 | } |
| 1481 | |
| 1482 | // If we would emit no arguments, then omit the parentheses entirely. Otherwise, |
| 1483 | // we'll wind up with a "most vexing parse" situation. |
| 1484 | if (args.empty()) |
| 1485 | statement("constexpr sampler ", |
| 1486 | type.basetype == SPIRType::SampledImage ? to_sampler_expression(samp.first) : to_name(samp.first), |
| 1487 | ";"); |
| 1488 | else |
| 1489 | statement("constexpr sampler ", |
| 1490 | type.basetype == SPIRType::SampledImage ? to_sampler_expression(samp.first) : to_name(samp.first), |
| 1491 | "(", merge(args), ");"); |
| 1492 | } |
| 1493 | |
| 1494 | // Emit dynamic buffers here. |
| 1495 | for (auto &dynamic_buffer : buffers_requiring_dynamic_offset) |
| 1496 | { |
| 1497 | if (!dynamic_buffer.second.second) |
| 1498 | { |
| 1499 | // Could happen if no buffer was used at requested binding point. |
| 1500 | continue; |
| 1501 | } |
| 1502 | |
| 1503 | const auto &var = get<SPIRVariable>(dynamic_buffer.second.second); |
| 1504 | uint32_t var_id = var.self; |
| 1505 | const auto &type = get_variable_data_type(var); |
| 1506 | string name = to_name(var.self); |
| 1507 | uint32_t desc_set = get_decoration(var.self, DecorationDescriptorSet); |
| 1508 | uint32_t arg_id = argument_buffer_ids[desc_set]; |
| 1509 | uint32_t base_index = dynamic_buffer.second.first; |
| 1510 | |
| 1511 | if (is_array(type)) |
| 1512 | { |
| 1513 | is_using_builtin_array = true; |
| 1514 | statement(get_argument_address_space(var), " ", type_to_glsl(type), "* ", to_restrict(var_id, true), name, |
| 1515 | type_to_array_glsl(type, var_id), " ="); |
| 1516 | |
| 1517 | uint32_t array_size = get_resource_array_size(type, var_id); |
| 1518 | if (array_size == 0) |
| 1519 | SPIRV_CROSS_THROW("Size of runtime array with dynamic offset could not be determined from resource bindings."); |
| 1520 | |
| 1521 | begin_scope(); |
| 1522 | |
| 1523 | for (uint32_t i = 0; i < array_size; i++) |
| 1524 | { |
| 1525 | statement("(", get_argument_address_space(var), " ", type_to_glsl(type), "* ", |
| 1526 | to_restrict(var_id, false), ")((", get_argument_address_space(var), " char* ", |
| 1527 | to_restrict(var_id, false), ")", to_name(arg_id), ".", ensure_valid_name(name, "m"), |
| 1528 | "[", i, "]", " + ", to_name(dynamic_offsets_buffer_id), "[", base_index + i, "]),"); |
| 1529 | } |
| 1530 | |
| 1531 | end_scope_decl(); |
| 1532 | statement_no_indent(""); |
| 1533 | is_using_builtin_array = false; |
| 1534 | } |
| 1535 | else |
| 1536 | { |
| 1537 | statement(get_argument_address_space(var), " auto& ", to_restrict(var_id, true), name, " = *(", |
| 1538 | get_argument_address_space(var), " ", type_to_glsl(type), "* ", to_restrict(var_id, false), ")((", |
| 1539 | get_argument_address_space(var), " char* ", to_restrict(var_id, false), ")", to_name(arg_id), ".", |
| 1540 | ensure_valid_name(name, "m"), " + ", to_name(dynamic_offsets_buffer_id), "[", base_index, "]);"); |
| 1541 | } |
| 1542 | } |
| 1543 | |
| 1544 | bool has_runtime_array_declaration = false; |
| 1545 | for (SPIRVariable *arg : entry_point_bindings) |
| 1546 | { |
| 1547 | const auto &var = *arg; |
| 1548 | const auto &type = get_variable_data_type(var); |
| 1549 | const auto &buffer_type = get_variable_element_type(var); |
| 1550 | const string name = to_name(var.self); |
| 1551 | |
| 1552 | if (is_var_runtime_size_array(var)) |
| 1553 | { |
| 1554 | if (msl_options.argument_buffers_tier < Options::ArgumentBuffersTier::Tier2) |
| 1555 | { |
| 1556 | SPIRV_CROSS_THROW("Unsized array of descriptors requires argument buffer tier 2"); |
| 1557 | } |
| 1558 | |
| 1559 | string resource_name; |
| 1560 | if (descriptor_set_is_argument_buffer(get_decoration(var.self, DecorationDescriptorSet))) |
| 1561 | resource_name = ir.meta[var.self].decoration.qualified_alias; |
| 1562 | else |
| 1563 | resource_name = name + "_"; |
| 1564 | |
| 1565 | switch (type.basetype) |
| 1566 | { |
| 1567 | case SPIRType::Image: |
| 1568 | case SPIRType::Sampler: |
| 1569 | case SPIRType::AccelerationStructure: |
| 1570 | statement("spvDescriptorArray<", type_to_glsl(buffer_type, var.self), "> ", name, " {", resource_name, "};"); |
| 1571 | break; |
| 1572 | case SPIRType::SampledImage: |
| 1573 | statement("spvDescriptorArray<", type_to_glsl(buffer_type, var.self), "> ", name, " {", resource_name, "};"); |
| 1574 | // Unsupported with argument buffer for now. |
| 1575 | statement("spvDescriptorArray<sampler> ", name, "Smplr {", name, "Smplr_};"); |
| 1576 | break; |
| 1577 | case SPIRType::Struct: |
| 1578 | statement("spvDescriptorArray<", get_argument_address_space(var), " ", type_to_glsl(buffer_type), "*> ", |
| 1579 | name, " {", resource_name, "};"); |
| 1580 | break; |
| 1581 | default: |
| 1582 | break; |
| 1583 | } |
| 1584 | has_runtime_array_declaration = true; |
| 1585 | } |
| 1586 | else if (!type.array.empty() && type.basetype == SPIRType::Struct) |
| 1587 | { |
| 1588 | // Emit only buffer arrays here. |
| 1589 | statement(get_argument_address_space(var), " ", type_to_glsl(buffer_type), "* ", |
| 1590 | to_restrict(var.self, true), name, "[] ="); |
| 1591 | begin_scope(); |
| 1592 | uint32_t array_size = get_resource_array_size(type, var.self); |
| 1593 | for (uint32_t i = 0; i < array_size; ++i) |
| 1594 | statement(name, "_", i, ","); |
| 1595 | end_scope_decl(); |
| 1596 | statement_no_indent(""); |
| 1597 | } |
| 1598 | } |
| 1599 | |
| 1600 | if (has_runtime_array_declaration) |
| 1601 | statement_no_indent(""); |
| 1602 | |
| 1603 | // Emit buffer aliases here. |
| 1604 | for (auto &var_id : buffer_aliases_discrete) |
| 1605 | { |
| 1606 | const auto &var = get<SPIRVariable>(var_id); |
| 1607 | const auto &type = get_variable_data_type(var); |
| 1608 | auto addr_space = get_argument_address_space(var); |
| 1609 | auto name = to_name(var_id); |
| 1610 | |
| 1611 | uint32_t desc_set = get_decoration(var_id, DecorationDescriptorSet); |
| 1612 | uint32_t desc_binding = get_decoration(var_id, DecorationBinding); |
| 1613 | auto alias_name = join("spvBufferAliasSet", desc_set, "Binding", desc_binding); |
| 1614 | |
| 1615 | statement(addr_space, " auto& ", to_restrict(var_id, true), |
| 1616 | name, |
| 1617 | " = *(", addr_space, " ", type_to_glsl(type), "*)", alias_name, ";"); |
| 1618 | } |
| 1619 | // Discrete descriptors are processed in entry point emission every compiler iteration. |
| 1620 | buffer_aliases_discrete.clear(); |
| 1621 | |
| 1622 | for (auto &var_pair : buffer_aliases_argument) |
| 1623 | { |
| 1624 | uint32_t var_id = var_pair.first; |
| 1625 | uint32_t alias_id = var_pair.second; |
| 1626 | |
| 1627 | const auto &var = get<SPIRVariable>(var_id); |
| 1628 | const auto &type = get_variable_data_type(var); |
| 1629 | auto addr_space = get_argument_address_space(var); |
| 1630 | |
| 1631 | if (type.array.empty()) |
| 1632 | { |
| 1633 | statement(addr_space, " auto& ", to_restrict(var_id, true), to_name(var_id), " = (", addr_space, " ", |
| 1634 | type_to_glsl(type), "&)", ir.meta[alias_id].decoration.qualified_alias, ";"); |
| 1635 | } |
| 1636 | else |
| 1637 | { |
| 1638 | const char *desc_addr_space = descriptor_address_space(var_id, var.storage, "thread"); |
| 1639 | |
| 1640 | // Esoteric type cast. Reference to array of pointers. |
| 1641 | // Auto here defers to UBO or SSBO. The address space of the reference needs to refer to the |
| 1642 | // address space of the argument buffer itself, which is usually constant, but can be const device for |
| 1643 | // large argument buffers. |
| 1644 | is_using_builtin_array = true; |
| 1645 | statement(desc_addr_space, " auto& ", to_restrict(var_id, true), to_name(var_id), " = (", addr_space, " ", |
| 1646 | type_to_glsl(type), "* ", desc_addr_space, " (&)", |
| 1647 | type_to_array_glsl(type, var_id), ")", ir.meta[alias_id].decoration.qualified_alias, ";"); |
| 1648 | is_using_builtin_array = false; |
| 1649 | } |
| 1650 | } |
| 1651 | |
| 1652 | // Emit disabled fragment outputs. |
| 1653 | std::sort(disabled_frag_outputs.begin(), disabled_frag_outputs.end()); |
| 1654 | for (uint32_t var_id : disabled_frag_outputs) |
| 1655 | { |
| 1656 | auto &var = get<SPIRVariable>(var_id); |
| 1657 | add_local_variable_name(var_id); |
| 1658 | statement(CompilerGLSL::variable_decl(var), ";"); |
| 1659 | var.deferred_declaration = false; |
| 1660 | } |
| 1661 | |
| 1662 | // Holds SetMeshOutputsEXT information. Threadgroup since first thread wins. |
| 1663 | if (processing_entry_point && is_mesh_shader()) |
| 1664 | statement("threadgroup uint2 spvMeshSizes;"); |
| 1665 | } |
| 1666 | |
| 1667 | string CompilerMSL::compile() |
| 1668 | { |
| 1669 | replace_illegal_entry_point_names(); |
| 1670 | ir.fixup_reserved_names(); |
| 1671 | |
| 1672 | // Do not deal with GLES-isms like precision, older extensions and such. |
| 1673 | options.vulkan_semantics = true; |
| 1674 | options.es = false; |
| 1675 | options.version = 450; |
| 1676 | backend.null_pointer_literal = "nullptr"; |
| 1677 | backend.float_literal_suffix = false; |
| 1678 | backend.uint32_t_literal_suffix = true; |
| 1679 | backend.int16_t_literal_suffix = ""; |
| 1680 | backend.uint16_t_literal_suffix = ""; |
| 1681 | backend.basic_int_type = "int"; |
| 1682 | backend.basic_uint_type = "uint"; |
| 1683 | backend.basic_int8_type = "char"; |
| 1684 | backend.basic_uint8_type = "uchar"; |
| 1685 | backend.basic_int16_type = "short"; |
| 1686 | backend.basic_uint16_type = "ushort"; |
| 1687 | backend.boolean_mix_function = "select"; |
| 1688 | backend.printf_function = "os_log_default.log"; |
| 1689 | backend.swizzle_is_function = false; |
| 1690 | backend.shared_is_implied = false; |
| 1691 | backend.use_initializer_list = true; |
| 1692 | backend.use_typed_initializer_list = true; |
| 1693 | backend.native_row_major_matrix = false; |
| 1694 | backend.unsized_array_supported = false; |
| 1695 | backend.can_declare_arrays_inline = false; |
| 1696 | backend.allow_truncated_access_chain = true; |
| 1697 | backend.comparison_image_samples_scalar = true; |
| 1698 | backend.native_pointers = true; |
| 1699 | backend.nonuniform_qualifier = ""; |
| 1700 | backend.support_small_type_sampling_result = true; |
| 1701 | backend.force_merged_mesh_block = false; |
| 1702 | backend.force_gl_in_out_block = false; |
| 1703 | backend.supports_empty_struct = true; |
| 1704 | backend.support_64bit_switch = true; |
| 1705 | backend.boolean_in_struct_remapped_type = SPIRType::Short; |
| 1706 | |
| 1707 | // Allow Metal to use the array<T> template unless we force it off. |
| 1708 | backend.can_return_array = !msl_options.force_native_arrays; |
| 1709 | backend.array_is_value_type = !msl_options.force_native_arrays; |
| 1710 | // Arrays which are part of buffer objects are never considered to be value types (just plain C-style). |
| 1711 | backend.array_is_value_type_in_buffer_blocks = false; |
| 1712 | backend.support_pointer_to_pointer = true; |
| 1713 | backend.implicit_c_integer_promotion_rules = true; |
| 1714 | |
| 1715 | capture_output_to_buffer = msl_options.capture_output_to_buffer; |
| 1716 | is_rasterization_disabled = msl_options.disable_rasterization || capture_output_to_buffer; |
| 1717 | |
| 1718 | if (is_mesh_shader() && !get_entry_point().flags.get(ExecutionModeOutputPoints)) |
| 1719 | msl_options.enable_point_size_builtin = false; |
| 1720 | |
| 1721 | // Initialize array here rather than constructor, MSVC 2013 workaround. |
| 1722 | for (auto &id : next_metal_resource_ids) |
| 1723 | id = 0; |
| 1724 | |
| 1725 | fixup_anonymous_struct_names(); |
| 1726 | fixup_type_alias(); |
| 1727 | replace_illegal_names(); |
| 1728 | if (get_execution_model() == ExecutionModelMeshEXT) |
| 1729 | { |
| 1730 | // Emit proxy entry-point for the sake of copy-pass |
| 1731 | emit_mesh_entry_point(); |
| 1732 | } |
| 1733 | sync_entry_point_aliases_and_names(); |
| 1734 | |
| 1735 | build_function_control_flow_graphs_and_analyze(); |
| 1736 | update_active_builtins(); |
| 1737 | analyze_image_and_sampler_usage(); |
| 1738 | analyze_sampled_image_usage(); |
| 1739 | analyze_interlocked_resource_usage(); |
| 1740 | analyze_workgroup_variables(); |
| 1741 | preprocess_op_codes(); |
| 1742 | build_implicit_builtins(); |
| 1743 | |
| 1744 | if (needs_manual_helper_invocation_updates() && needs_helper_invocation) |
| 1745 | { |
| 1746 | string builtin_helper_invocation = builtin_to_glsl(BuiltInHelperInvocation, StorageClassInput); |
| 1747 | string discard_expr = join(builtin_helper_invocation, " = true, discard_fragment()"); |
| 1748 | if (msl_options.force_fragment_with_side_effects_execution) |
| 1749 | discard_expr = join("!", builtin_helper_invocation, " ? (", discard_expr, ") : (void)0"); |
| 1750 | backend.discard_literal = discard_expr; |
| 1751 | backend.demote_literal = discard_expr; |
| 1752 | } |
| 1753 | else |
| 1754 | { |
| 1755 | backend.discard_literal = "discard_fragment()"; |
| 1756 | backend.demote_literal = "discard_fragment()"; |
| 1757 | } |
| 1758 | |
| 1759 | fixup_image_load_store_access(); |
| 1760 | |
| 1761 | set_enabled_interface_variables(get_active_interface_variables()); |
| 1762 | if (msl_options.force_active_argument_buffer_resources) |
| 1763 | activate_argument_buffer_resources(); |
| 1764 | |
| 1765 | if (swizzle_buffer_id) |
| 1766 | add_active_interface_variable(swizzle_buffer_id); |
| 1767 | if (buffer_size_buffer_id) |
| 1768 | add_active_interface_variable(buffer_size_buffer_id); |
| 1769 | if (view_mask_buffer_id) |
| 1770 | add_active_interface_variable(view_mask_buffer_id); |
| 1771 | if (dynamic_offsets_buffer_id) |
| 1772 | add_active_interface_variable(dynamic_offsets_buffer_id); |
| 1773 | if (builtin_layer_id) |
| 1774 | add_active_interface_variable(builtin_layer_id); |
| 1775 | if (builtin_dispatch_base_id && !msl_options.supports_msl_version(1, 2)) |
| 1776 | add_active_interface_variable(builtin_dispatch_base_id); |
| 1777 | if (builtin_sample_mask_id) |
| 1778 | add_active_interface_variable(builtin_sample_mask_id); |
| 1779 | if (builtin_frag_depth_id) |
| 1780 | add_active_interface_variable(builtin_frag_depth_id); |
| 1781 | |
| 1782 | // Create structs to hold input, output and uniform variables. |
| 1783 | // Do output first to ensure out. is declared at top of entry function. |
| 1784 | qual_pos_var_name = ""; |
| 1785 | if (is_mesh_shader()) |
| 1786 | { |
| 1787 | fixup_implicit_builtin_block_names(get_execution_model()); |
| 1788 | } |
| 1789 | else |
| 1790 | { |
| 1791 | stage_out_var_id = add_interface_block(StorageClassOutput); |
| 1792 | patch_stage_out_var_id = add_interface_block(StorageClassOutput, true); |
| 1793 | stage_in_var_id = add_interface_block(StorageClassInput); |
| 1794 | } |
| 1795 | |
| 1796 | if (is_tese_shader()) |
| 1797 | patch_stage_in_var_id = add_interface_block(StorageClassInput, true); |
| 1798 | |
| 1799 | if (is_tesc_shader()) |
| 1800 | stage_out_ptr_var_id = add_interface_block_pointer(stage_out_var_id, StorageClassOutput); |
| 1801 | if (is_tessellation_shader()) |
| 1802 | stage_in_ptr_var_id = add_interface_block_pointer(stage_in_var_id, StorageClassInput); |
| 1803 | |
| 1804 | if (is_mesh_shader()) |
| 1805 | { |
| 1806 | mesh_out_per_vertex = add_meshlet_block(false); |
| 1807 | mesh_out_per_primitive = add_meshlet_block(true); |
| 1808 | } |
| 1809 | |
| 1810 | // Metal vertex functions that define no output must disable rasterization and return void. |
| 1811 | if (!stage_out_var_id) |
| 1812 | is_rasterization_disabled = true; |
| 1813 | |
| 1814 | // Convert the use of global variables to recursively-passed function parameters |
| 1815 | localize_global_variables(); |
| 1816 | extract_global_variables_from_functions(); |
| 1817 | |
| 1818 | // Mark any non-stage-in structs to be tightly packed. |
| 1819 | mark_packable_structs(); |
| 1820 | reorder_type_alias(); |
| 1821 | |
| 1822 | // Add fixup hooks required by shader inputs and outputs. This needs to happen before |
| 1823 | // the loop, so the hooks aren't added multiple times. |
| 1824 | fix_up_shader_inputs_outputs(); |
| 1825 | |
| 1826 | // If we are using argument buffers, we create argument buffer structures for them here. |
| 1827 | // These buffers will be used in the entry point, not the individual resources. |
| 1828 | if (msl_options.argument_buffers) |
| 1829 | { |
| 1830 | if (!msl_options.supports_msl_version(2, 0)) |
| 1831 | SPIRV_CROSS_THROW("Argument buffers can only be used with MSL 2.0 and up."); |
| 1832 | analyze_argument_buffers(); |
| 1833 | } |
| 1834 | |
| 1835 | uint32_t pass_count = 0; |
| 1836 | do |
| 1837 | { |
| 1838 | reset(pass_count); |
| 1839 | |
| 1840 | // Start bindings at zero. |
| 1841 | next_metal_resource_index_buffer = 0; |
| 1842 | next_metal_resource_index_texture = 0; |
| 1843 | next_metal_resource_index_sampler = 0; |
| 1844 | for (auto &id : next_metal_resource_ids) |
| 1845 | id = 0; |
| 1846 | |
| 1847 | // Move constructor for this type is broken on GCC 4.9 ... |
| 1848 | buffer.reset(); |
| 1849 | |
| 1850 | emit_header(); |
| 1851 | emit_custom_templates(); |
| 1852 | emit_custom_functions(); |
| 1853 | emit_specialization_constants_and_structs(); |
| 1854 | emit_resources(); |
| 1855 | emit_function(get<SPIRFunction>(ir.default_entry_point), Bitset()); |
| 1856 | |
| 1857 | pass_count++; |
| 1858 | } while (is_forcing_recompilation()); |
| 1859 | |
| 1860 | return buffer.str(); |
| 1861 | } |
| 1862 | |
| 1863 | // Register the need to output any custom functions. |
| 1864 | void CompilerMSL::preprocess_op_codes() |
| 1865 | { |
| 1866 | OpCodePreprocessor preproc(*this); |
| 1867 | traverse_all_reachable_opcodes(get<SPIRFunction>(ir.default_entry_point), preproc); |
| 1868 | |
| 1869 | suppress_missing_prototypes = preproc.suppress_missing_prototypes; |
| 1870 | |
| 1871 | if (preproc.uses_atomics) |
| 1872 | { |
| 1873 | add_header_line("#include <metal_atomic>"); |
| 1874 | add_pragma_line("#pragma clang diagnostic ignored \"-Wunused-variable\"", false); |
| 1875 | } |
| 1876 | |
| 1877 | // Before MSL 2.1 (2.2 for textures), Metal vertex functions that write to |
| 1878 | // resources must disable rasterization and return void. |
| 1879 | if ((preproc.uses_buffer_write && !msl_options.supports_msl_version(2, 1)) || |
| 1880 | (preproc.uses_image_write && !msl_options.supports_msl_version(2, 2))) |
| 1881 | is_rasterization_disabled = true; |
| 1882 | |
| 1883 | // Tessellation control shaders are run as compute functions in Metal, and so |
| 1884 | // must capture their output to a buffer. |
| 1885 | if (is_tesc_shader() || (get_execution_model() == ExecutionModelVertex && msl_options.vertex_for_tessellation)) |
| 1886 | { |
| 1887 | is_rasterization_disabled = true; |
| 1888 | capture_output_to_buffer = true; |
| 1889 | } |
| 1890 | |
| 1891 | if (preproc.needs_local_invocation_index) |
| 1892 | needs_local_invocation_index = true; |
| 1893 | if (preproc.needs_subgroup_invocation_id) |
| 1894 | needs_subgroup_invocation_id = true; |
| 1895 | if (preproc.needs_subgroup_size) |
| 1896 | needs_subgroup_size = true; |
| 1897 | // build_implicit_builtins() hasn't run yet, and in fact, this needs to execute |
| 1898 | // before then so that gl_SampleID will get added; so we also need to check if |
| 1899 | // that function would add gl_FragCoord. |
| 1900 | if (preproc.needs_sample_id || msl_options.force_sample_rate_shading || |
| 1901 | (is_sample_rate() && (active_input_builtins.get(BuiltInFragCoord) || |
| 1902 | (need_subpass_input_ms && !msl_options.use_framebuffer_fetch_subpasses)))) |
| 1903 | needs_sample_id = true; |
| 1904 | if (preproc.needs_helper_invocation || active_input_builtins.get(BuiltInHelperInvocation)) |
| 1905 | needs_helper_invocation = true; |
| 1906 | |
| 1907 | // OpKill is removed by the parser, so we need to identify those by inspecting |
| 1908 | // blocks. |
| 1909 | ir.for_each_typed_id<SPIRBlock>([&preproc](uint32_t, SPIRBlock &block) { |
| 1910 | if (block.terminator == SPIRBlock::Kill) |
| 1911 | preproc.uses_discard = true; |
| 1912 | }); |
| 1913 | |
| 1914 | // Fragment shaders that both write to storage resources and discard fragments |
| 1915 | // need checks on the writes, to work around Metal allowing these writes despite |
| 1916 | // the fragment being dead. We also require to force Metal to execute fragment |
| 1917 | // shaders instead of being prematurely discarded. |
| 1918 | if (preproc.uses_discard && (preproc.uses_buffer_write || preproc.uses_image_write)) |
| 1919 | { |
| 1920 | bool should_enable = (msl_options.check_discarded_frag_stores || msl_options.force_fragment_with_side_effects_execution); |
| 1921 | frag_shader_needs_discard_checks |= msl_options.check_discarded_frag_stores; |
| 1922 | needs_helper_invocation |= should_enable; |
| 1923 | // Fragment discard store checks imply manual HelperInvocation updates. |
| 1924 | msl_options.manual_helper_invocation_updates |= should_enable; |
| 1925 | } |
| 1926 | |
| 1927 | if (is_intersection_query()) |
| 1928 | { |
| 1929 | add_header_line("#if __METAL_VERSION__ >= 230"); |
| 1930 | add_header_line("#include <metal_raytracing>"); |
| 1931 | add_header_line("using namespace metal::raytracing;"); |
| 1932 | add_header_line("#endif"); |
| 1933 | } |
| 1934 | } |
| 1935 | |
| 1936 | // Move the Private and Workgroup global variables to the entry function. |
| 1937 | // Non-constant variables cannot have global scope in Metal. |
| 1938 | void CompilerMSL::localize_global_variables() |
| 1939 | { |
| 1940 | auto &entry_func = get<SPIRFunction>(ir.default_entry_point); |
| 1941 | auto iter = global_variables.begin(); |
| 1942 | while (iter != global_variables.end()) |
| 1943 | { |
| 1944 | uint32_t v_id = *iter; |
| 1945 | auto &var = get<SPIRVariable>(v_id); |
| 1946 | if (var.storage == StorageClassPrivate || var.storage == StorageClassWorkgroup || |
| 1947 | var.storage == StorageClassTaskPayloadWorkgroupEXT) |
| 1948 | { |
| 1949 | if (!variable_is_lut(var)) |
| 1950 | entry_func.add_local_variable(v_id); |
| 1951 | iter = global_variables.erase(iter); |
| 1952 | } |
| 1953 | else if (var.storage == StorageClassOutput && is_mesh_shader()) |
| 1954 | { |
| 1955 | entry_func.add_local_variable(v_id); |
| 1956 | iter = global_variables.erase(iter); |
| 1957 | } |
| 1958 | else |
| 1959 | iter++; |
| 1960 | } |
| 1961 | } |
| 1962 | |
| 1963 | // For any global variable accessed directly by a function, |
| 1964 | // extract that variable and add it as an argument to that function. |
| 1965 | void CompilerMSL::extract_global_variables_from_functions() |
| 1966 | { |
| 1967 | // Uniforms |
| 1968 | unordered_set<uint32_t> global_var_ids; |
| 1969 | ir.for_each_typed_id<SPIRVariable>([&](uint32_t, SPIRVariable &var) { |
| 1970 | // Some builtins resolve directly to a function call which does not need any declared variables. |
| 1971 | // Skip these. |
| 1972 | if (var.storage == StorageClassInput && has_decoration(var.self, DecorationBuiltIn)) |
| 1973 | { |
| 1974 | auto bi_type = BuiltIn(get_decoration(var.self, DecorationBuiltIn)); |
| 1975 | if (bi_type == BuiltInHelperInvocation && !needs_manual_helper_invocation_updates()) |
| 1976 | return; |
| 1977 | if (bi_type == BuiltInHelperInvocation && needs_manual_helper_invocation_updates()) |
| 1978 | { |
| 1979 | if (msl_options.is_ios() && !msl_options.supports_msl_version(2, 3)) |
| 1980 | SPIRV_CROSS_THROW("simd_is_helper_thread() requires version 2.3 on iOS."); |
| 1981 | else if (msl_options.is_macos() && !msl_options.supports_msl_version(2, 1)) |
| 1982 | SPIRV_CROSS_THROW("simd_is_helper_thread() requires version 2.1 on macOS."); |
| 1983 | // Make sure this is declared and initialized. |
| 1984 | // Force this to have the proper name. |
| 1985 | set_name(var.self, builtin_to_glsl(BuiltInHelperInvocation, StorageClassInput)); |
| 1986 | auto &entry_func = this->get<SPIRFunction>(ir.default_entry_point); |
| 1987 | entry_func.add_local_variable(var.self); |
| 1988 | vars_needing_early_declaration.push_back(var.self); |
| 1989 | entry_func.fixup_hooks_in.push_back([this, &var]() |
| 1990 | { statement(to_name(var.self), " = simd_is_helper_thread();"); }); |
| 1991 | } |
| 1992 | } |
| 1993 | |
| 1994 | if (var.storage == StorageClassInput || var.storage == StorageClassOutput || |
| 1995 | var.storage == StorageClassUniform || var.storage == StorageClassUniformConstant || |
| 1996 | var.storage == StorageClassPushConstant || var.storage == StorageClassStorageBuffer) |
| 1997 | { |
| 1998 | global_var_ids.insert(var.self); |
| 1999 | } |
| 2000 | }); |
| 2001 | |
| 2002 | // Local vars that are declared in the main function and accessed directly by a function |
| 2003 | auto &entry_func = get<SPIRFunction>(ir.default_entry_point); |
| 2004 | for (auto &var : entry_func.local_variables) |
| 2005 | if (get<SPIRVariable>(var).storage != StorageClassFunction) |
| 2006 | global_var_ids.insert(var); |
| 2007 | |
| 2008 | std::set<uint32_t> added_arg_ids; |
| 2009 | unordered_set<uint32_t> processed_func_ids; |
| 2010 | extract_global_variables_from_function(ir.default_entry_point, added_arg_ids, global_var_ids, processed_func_ids); |
| 2011 | } |
| 2012 | |
| 2013 | // MSL does not support the use of global variables for shader input content. |
| 2014 | // For any global variable accessed directly by the specified function, extract that variable, |
| 2015 | // add it as an argument to that function, and the arg to the added_arg_ids collection. |
| 2016 | void CompilerMSL::extract_global_variables_from_function(uint32_t func_id, std::set<uint32_t> &added_arg_ids, |
| 2017 | unordered_set<uint32_t> &global_var_ids, |
| 2018 | unordered_set<uint32_t> &processed_func_ids) |
| 2019 | { |
| 2020 | // Avoid processing a function more than once |
| 2021 | if (processed_func_ids.find(func_id) != processed_func_ids.end()) |
| 2022 | { |
| 2023 | // Return function global variables |
| 2024 | added_arg_ids = function_global_vars[func_id]; |
| 2025 | return; |
| 2026 | } |
| 2027 | |
| 2028 | processed_func_ids.insert(func_id); |
| 2029 | |
| 2030 | auto &func = get<SPIRFunction>(func_id); |
| 2031 | |
| 2032 | // Recursively establish global args added to functions on which we depend. |
| 2033 | for (auto block : func.blocks) |
| 2034 | { |
| 2035 | auto &b = get<SPIRBlock>(block); |
| 2036 | for (auto &i : b.ops) |
| 2037 | { |
| 2038 | auto ops = stream(i); |
| 2039 | auto op = static_cast<Op>(i.op); |
| 2040 | |
| 2041 | switch (op) |
| 2042 | { |
| 2043 | case OpLoad: |
| 2044 | case OpInBoundsAccessChain: |
| 2045 | case OpAccessChain: |
| 2046 | case OpPtrAccessChain: |
| 2047 | case OpArrayLength: |
| 2048 | { |
| 2049 | uint32_t base_id = ops[2]; |
| 2050 | if (global_var_ids.find(base_id) != global_var_ids.end()) |
| 2051 | added_arg_ids.insert(base_id); |
| 2052 | |
| 2053 | // Use Metal's native frame-buffer fetch API for subpass inputs. |
| 2054 | auto &type = get<SPIRType>(ops[0]); |
| 2055 | if (type.basetype == SPIRType::Image && type.image.dim == DimSubpassData && |
| 2056 | (!msl_options.use_framebuffer_fetch_subpasses)) |
| 2057 | { |
| 2058 | // Implicitly reads gl_FragCoord. |
| 2059 | assert(builtin_frag_coord_id != 0); |
| 2060 | added_arg_ids.insert(builtin_frag_coord_id); |
| 2061 | if (msl_options.multiview) |
| 2062 | { |
| 2063 | // Implicitly reads gl_ViewIndex. |
| 2064 | assert(builtin_view_idx_id != 0); |
| 2065 | added_arg_ids.insert(builtin_view_idx_id); |
| 2066 | } |
| 2067 | else if (msl_options.arrayed_subpass_input) |
| 2068 | { |
| 2069 | // Implicitly reads gl_Layer. |
| 2070 | assert(builtin_layer_id != 0); |
| 2071 | added_arg_ids.insert(builtin_layer_id); |
| 2072 | } |
| 2073 | } |
| 2074 | |
| 2075 | break; |
| 2076 | } |
| 2077 | |
| 2078 | case OpFunctionCall: |
| 2079 | { |
| 2080 | // First see if any of the function call args are globals |
| 2081 | for (uint32_t arg_idx = 3; arg_idx < i.length; arg_idx++) |
| 2082 | { |
| 2083 | uint32_t arg_id = ops[arg_idx]; |
| 2084 | if (global_var_ids.find(arg_id) != global_var_ids.end()) |
| 2085 | added_arg_ids.insert(arg_id); |
| 2086 | } |
| 2087 | |
| 2088 | // Then recurse into the function itself to extract globals used internally in the function |
| 2089 | uint32_t inner_func_id = ops[2]; |
| 2090 | std::set<uint32_t> inner_func_args; |
| 2091 | extract_global_variables_from_function(inner_func_id, inner_func_args, global_var_ids, |
| 2092 | processed_func_ids); |
| 2093 | added_arg_ids.insert(inner_func_args.begin(), inner_func_args.end()); |
| 2094 | break; |
| 2095 | } |
| 2096 | |
| 2097 | case OpStore: |
| 2098 | { |
| 2099 | uint32_t base_id = ops[0]; |
| 2100 | if (global_var_ids.find(base_id) != global_var_ids.end()) |
| 2101 | { |
| 2102 | added_arg_ids.insert(base_id); |
| 2103 | |
| 2104 | if (msl_options.input_attachment_is_ds_attachment && base_id == builtin_frag_depth_id) |
| 2105 | writes_to_depth = true; |
| 2106 | } |
| 2107 | |
| 2108 | uint32_t rvalue_id = ops[1]; |
| 2109 | if (global_var_ids.find(rvalue_id) != global_var_ids.end()) |
| 2110 | added_arg_ids.insert(rvalue_id); |
| 2111 | |
| 2112 | if (needs_frag_discard_checks()) |
| 2113 | added_arg_ids.insert(builtin_helper_invocation_id); |
| 2114 | |
| 2115 | break; |
| 2116 | } |
| 2117 | |
| 2118 | case OpSelect: |
| 2119 | { |
| 2120 | uint32_t base_id = ops[3]; |
| 2121 | if (global_var_ids.find(base_id) != global_var_ids.end()) |
| 2122 | added_arg_ids.insert(base_id); |
| 2123 | base_id = ops[4]; |
| 2124 | if (global_var_ids.find(base_id) != global_var_ids.end()) |
| 2125 | added_arg_ids.insert(base_id); |
| 2126 | break; |
| 2127 | } |
| 2128 | |
| 2129 | case OpAtomicExchange: |
| 2130 | case OpAtomicCompareExchange: |
| 2131 | case OpAtomicStore: |
| 2132 | case OpAtomicIIncrement: |
| 2133 | case OpAtomicIDecrement: |
| 2134 | case OpAtomicIAdd: |
| 2135 | case OpAtomicFAddEXT: |
| 2136 | case OpAtomicISub: |
| 2137 | case OpAtomicSMin: |
| 2138 | case OpAtomicUMin: |
| 2139 | case OpAtomicSMax: |
| 2140 | case OpAtomicUMax: |
| 2141 | case OpAtomicAnd: |
| 2142 | case OpAtomicOr: |
| 2143 | case OpAtomicXor: |
| 2144 | case OpImageWrite: |
| 2145 | { |
| 2146 | if (needs_frag_discard_checks()) |
| 2147 | added_arg_ids.insert(builtin_helper_invocation_id); |
| 2148 | uint32_t ptr = 0; |
| 2149 | if (op == OpAtomicStore || op == OpImageWrite) |
| 2150 | ptr = ops[0]; |
| 2151 | else |
| 2152 | ptr = ops[2]; |
| 2153 | if (global_var_ids.find(ptr) != global_var_ids.end()) |
| 2154 | added_arg_ids.insert(ptr); |
| 2155 | break; |
| 2156 | } |
| 2157 | |
| 2158 | // Emulate texture2D atomic operations |
| 2159 | case OpImageTexelPointer: |
| 2160 | { |
| 2161 | // When using the pointer, we need to know which variable it is actually loaded from. |
| 2162 | uint32_t base_id = ops[2]; |
| 2163 | auto *var = maybe_get_backing_variable(base_id); |
| 2164 | if (var) |
| 2165 | { |
| 2166 | if (atomic_image_vars_emulated.count(var->self) && |
| 2167 | !get<SPIRType>(var->basetype).array.empty()) |
| 2168 | { |
| 2169 | SPIRV_CROSS_THROW( |
| 2170 | "Cannot emulate array of storage images with atomics. Use MSL 3.1 for native support."); |
| 2171 | } |
| 2172 | |
| 2173 | if (global_var_ids.find(base_id) != global_var_ids.end()) |
| 2174 | added_arg_ids.insert(base_id); |
| 2175 | } |
| 2176 | break; |
| 2177 | } |
| 2178 | |
| 2179 | case OpExtInst: |
| 2180 | { |
| 2181 | uint32_t extension_set = ops[2]; |
| 2182 | if (get<SPIRExtension>(extension_set).ext == SPIRExtension::GLSL) |
| 2183 | { |
| 2184 | auto op_450 = static_cast<GLSLstd450>(ops[3]); |
| 2185 | switch (op_450) |
| 2186 | { |
| 2187 | case GLSLstd450InterpolateAtCentroid: |
| 2188 | case GLSLstd450InterpolateAtSample: |
| 2189 | case GLSLstd450InterpolateAtOffset: |
| 2190 | { |
| 2191 | // For these, we really need the stage-in block. It is theoretically possible to pass the |
| 2192 | // interpolant object, but a) doing so would require us to create an entirely new variable |
| 2193 | // with Interpolant type, and b) if we have a struct or array, handling all the members and |
| 2194 | // elements could get unwieldy fast. |
| 2195 | added_arg_ids.insert(stage_in_var_id); |
| 2196 | break; |
| 2197 | } |
| 2198 | |
| 2199 | case GLSLstd450Modf: |
| 2200 | case GLSLstd450Frexp: |
| 2201 | { |
| 2202 | uint32_t base_id = ops[5]; |
| 2203 | if (global_var_ids.find(base_id) != global_var_ids.end()) |
| 2204 | added_arg_ids.insert(base_id); |
| 2205 | break; |
| 2206 | } |
| 2207 | |
| 2208 | default: |
| 2209 | break; |
| 2210 | } |
| 2211 | } |
| 2212 | break; |
| 2213 | } |
| 2214 | |
| 2215 | case OpGroupNonUniformInverseBallot: |
| 2216 | { |
| 2217 | added_arg_ids.insert(builtin_subgroup_invocation_id_id); |
| 2218 | break; |
| 2219 | } |
| 2220 | |
| 2221 | case OpGroupNonUniformBallotFindLSB: |
| 2222 | case OpGroupNonUniformBallotFindMSB: |
| 2223 | { |
| 2224 | added_arg_ids.insert(builtin_subgroup_size_id); |
| 2225 | break; |
| 2226 | } |
| 2227 | |
| 2228 | case OpGroupNonUniformBallotBitCount: |
| 2229 | { |
| 2230 | auto operation = static_cast<GroupOperation>(ops[3]); |
| 2231 | switch (operation) |
| 2232 | { |
| 2233 | case GroupOperationReduce: |
| 2234 | added_arg_ids.insert(builtin_subgroup_size_id); |
| 2235 | break; |
| 2236 | case GroupOperationInclusiveScan: |
| 2237 | case GroupOperationExclusiveScan: |
| 2238 | added_arg_ids.insert(builtin_subgroup_invocation_id_id); |
| 2239 | break; |
| 2240 | default: |
| 2241 | break; |
| 2242 | } |
| 2243 | break; |
| 2244 | } |
| 2245 | |
| 2246 | case OpGroupNonUniformRotateKHR: |
| 2247 | { |
| 2248 | // Add the correct invocation ID for calculating clustered rotate case. |
| 2249 | if (i.length > 5) |
| 2250 | added_arg_ids.insert(static_cast<Scope>(evaluate_constant_u32(ops[2])) == ScopeSubgroup |
| 2251 | ? builtin_subgroup_invocation_id_id : builtin_local_invocation_index_id); |
| 2252 | break; |
| 2253 | } |
| 2254 | |
| 2255 | case OpGroupNonUniformFAdd: |
| 2256 | case OpGroupNonUniformFMul: |
| 2257 | case OpGroupNonUniformFMin: |
| 2258 | case OpGroupNonUniformFMax: |
| 2259 | case OpGroupNonUniformIAdd: |
| 2260 | case OpGroupNonUniformIMul: |
| 2261 | case OpGroupNonUniformSMin: |
| 2262 | case OpGroupNonUniformSMax: |
| 2263 | case OpGroupNonUniformUMin: |
| 2264 | case OpGroupNonUniformUMax: |
| 2265 | case OpGroupNonUniformBitwiseAnd: |
| 2266 | case OpGroupNonUniformBitwiseOr: |
| 2267 | case OpGroupNonUniformBitwiseXor: |
| 2268 | case OpGroupNonUniformLogicalAnd: |
| 2269 | case OpGroupNonUniformLogicalOr: |
| 2270 | case OpGroupNonUniformLogicalXor: |
| 2271 | if ((get_execution_model() != ExecutionModelFragment || msl_options.supports_msl_version(2, 2)) && |
| 2272 | ops[3] == GroupOperationClusteredReduce) |
| 2273 | added_arg_ids.insert(builtin_subgroup_invocation_id_id); |
| 2274 | break; |
| 2275 | |
| 2276 | case OpDemoteToHelperInvocation: |
| 2277 | if (needs_manual_helper_invocation_updates() && needs_helper_invocation) |
| 2278 | added_arg_ids.insert(builtin_helper_invocation_id); |
| 2279 | break; |
| 2280 | |
| 2281 | case OpIsHelperInvocationEXT: |
| 2282 | if (needs_manual_helper_invocation_updates()) |
| 2283 | added_arg_ids.insert(builtin_helper_invocation_id); |
| 2284 | break; |
| 2285 | |
| 2286 | case OpRayQueryInitializeKHR: |
| 2287 | case OpRayQueryProceedKHR: |
| 2288 | case OpRayQueryTerminateKHR: |
| 2289 | case OpRayQueryGenerateIntersectionKHR: |
| 2290 | case OpRayQueryConfirmIntersectionKHR: |
| 2291 | { |
| 2292 | // Ray query accesses memory directly, need check pass down object if using Private storage class. |
| 2293 | uint32_t base_id = ops[0]; |
| 2294 | if (global_var_ids.find(base_id) != global_var_ids.end()) |
| 2295 | added_arg_ids.insert(base_id); |
| 2296 | break; |
| 2297 | } |
| 2298 | |
| 2299 | case OpRayQueryGetRayTMinKHR: |
| 2300 | case OpRayQueryGetRayFlagsKHR: |
| 2301 | case OpRayQueryGetWorldRayOriginKHR: |
| 2302 | case OpRayQueryGetWorldRayDirectionKHR: |
| 2303 | case OpRayQueryGetIntersectionCandidateAABBOpaqueKHR: |
| 2304 | case OpRayQueryGetIntersectionTypeKHR: |
| 2305 | case OpRayQueryGetIntersectionTKHR: |
| 2306 | case OpRayQueryGetIntersectionInstanceCustomIndexKHR: |
| 2307 | case OpRayQueryGetIntersectionInstanceIdKHR: |
| 2308 | case OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR: |
| 2309 | case OpRayQueryGetIntersectionGeometryIndexKHR: |
| 2310 | case OpRayQueryGetIntersectionPrimitiveIndexKHR: |
| 2311 | case OpRayQueryGetIntersectionBarycentricsKHR: |
| 2312 | case OpRayQueryGetIntersectionFrontFaceKHR: |
| 2313 | case OpRayQueryGetIntersectionObjectRayDirectionKHR: |
| 2314 | case OpRayQueryGetIntersectionObjectRayOriginKHR: |
| 2315 | case OpRayQueryGetIntersectionObjectToWorldKHR: |
| 2316 | case OpRayQueryGetIntersectionWorldToObjectKHR: |
| 2317 | { |
| 2318 | // Ray query accesses memory directly, need check pass down object if using Private storage class. |
| 2319 | uint32_t base_id = ops[2]; |
| 2320 | if (global_var_ids.find(base_id) != global_var_ids.end()) |
| 2321 | added_arg_ids.insert(base_id); |
| 2322 | break; |
| 2323 | } |
| 2324 | |
| 2325 | case OpSetMeshOutputsEXT: |
| 2326 | { |
| 2327 | if (builtin_local_invocation_index_id != 0) |
| 2328 | added_arg_ids.insert(builtin_local_invocation_index_id); |
| 2329 | if (builtin_mesh_sizes_id != 0) |
| 2330 | added_arg_ids.insert(builtin_mesh_sizes_id); |
| 2331 | break; |
| 2332 | } |
| 2333 | |
| 2334 | default: |
| 2335 | break; |
| 2336 | } |
| 2337 | |
| 2338 | if (needs_manual_helper_invocation_updates() && b.terminator == SPIRBlock::Kill && |
| 2339 | needs_helper_invocation) |
| 2340 | added_arg_ids.insert(builtin_helper_invocation_id); |
| 2341 | |
| 2342 | // TODO: Add all other operations which can affect memory. |
| 2343 | // We should consider a more unified system here to reduce boiler-plate. |
| 2344 | // This kind of analysis is done in several places ... |
| 2345 | } |
| 2346 | |
| 2347 | if (b.terminator == SPIRBlock::EmitMeshTasks && builtin_task_grid_id != 0) |
| 2348 | added_arg_ids.insert(builtin_task_grid_id); |
| 2349 | } |
| 2350 | |
| 2351 | function_global_vars[func_id] = added_arg_ids; |
| 2352 | |
| 2353 | // Add the global variables as arguments to the function |
| 2354 | if (func_id != ir.default_entry_point) |
| 2355 | { |
| 2356 | bool control_point_added_in = false; |
| 2357 | bool control_point_added_out = false; |
| 2358 | bool patch_added_in = false; |
| 2359 | bool patch_added_out = false; |
| 2360 | |
| 2361 | for (uint32_t arg_id : added_arg_ids) |
| 2362 | { |
| 2363 | auto &var = get<SPIRVariable>(arg_id); |
| 2364 | uint32_t type_id = var.basetype; |
| 2365 | auto *p_type = &get<SPIRType>(type_id); |
| 2366 | BuiltIn bi_type = BuiltIn(get_decoration(arg_id, DecorationBuiltIn)); |
| 2367 | |
| 2368 | bool is_patch = has_decoration(arg_id, DecorationPatch) || is_patch_block(*p_type); |
| 2369 | bool is_block = has_decoration(p_type->self, DecorationBlock); |
| 2370 | bool is_control_point_storage = |
| 2371 | !is_patch && ((is_tessellation_shader() && var.storage == StorageClassInput) || |
| 2372 | (is_tesc_shader() && var.storage == StorageClassOutput)); |
| 2373 | bool is_patch_block_storage = is_patch && is_block && var.storage == StorageClassOutput; |
| 2374 | bool is_builtin = is_builtin_variable(var); |
| 2375 | bool variable_is_stage_io = |
| 2376 | !is_builtin || bi_type == BuiltInPosition || bi_type == BuiltInPointSize || |
| 2377 | bi_type == BuiltInClipDistance || bi_type == BuiltInCullDistance || |
| 2378 | p_type->basetype == SPIRType::Struct; |
| 2379 | bool is_redirected_to_global_stage_io = (is_control_point_storage || is_patch_block_storage) && |
| 2380 | variable_is_stage_io; |
| 2381 | |
| 2382 | // If output is masked it is not considered part of the global stage IO interface. |
| 2383 | if (is_redirected_to_global_stage_io && var.storage == StorageClassOutput) |
| 2384 | is_redirected_to_global_stage_io = !is_stage_output_variable_masked(var); |
| 2385 | |
| 2386 | if (is_redirected_to_global_stage_io) |
| 2387 | { |
| 2388 | // Tessellation control shaders see inputs and per-point outputs as arrays. |
| 2389 | // Similarly, tessellation evaluation shaders see per-point inputs as arrays. |
| 2390 | // We collected them into a structure; we must pass the array of this |
| 2391 | // structure to the function. |
| 2392 | std::string name; |
| 2393 | if (is_patch) |
| 2394 | name = var.storage == StorageClassInput ? patch_stage_in_var_name : patch_stage_out_var_name; |
| 2395 | else |
| 2396 | name = var.storage == StorageClassInput ? "gl_in" : "gl_out"; |
| 2397 | |
| 2398 | if (var.storage == StorageClassOutput && has_decoration(p_type->self, DecorationBlock)) |
| 2399 | { |
| 2400 | // If we're redirecting a block, we might still need to access the original block |
| 2401 | // variable if we're masking some members. |
| 2402 | for (uint32_t mbr_idx = 0; mbr_idx < uint32_t(p_type->member_types.size()); mbr_idx++) |
| 2403 | { |
| 2404 | if (is_stage_output_block_member_masked(var, mbr_idx, true)) |
| 2405 | { |
| 2406 | func.add_parameter(var.basetype, var.self, true); |
| 2407 | break; |
| 2408 | } |
| 2409 | } |
| 2410 | } |
| 2411 | |
| 2412 | if (var.storage == StorageClassInput) |
| 2413 | { |
| 2414 | auto &added_in = is_patch ? patch_added_in : control_point_added_in; |
| 2415 | if (added_in) |
| 2416 | continue; |
| 2417 | arg_id = is_patch ? patch_stage_in_var_id : stage_in_ptr_var_id; |
| 2418 | added_in = true; |
| 2419 | } |
| 2420 | else if (var.storage == StorageClassOutput) |
| 2421 | { |
| 2422 | auto &added_out = is_patch ? patch_added_out : control_point_added_out; |
| 2423 | if (added_out) |
| 2424 | continue; |
| 2425 | arg_id = is_patch ? patch_stage_out_var_id : stage_out_ptr_var_id; |
| 2426 | added_out = true; |
| 2427 | } |
| 2428 | |
| 2429 | type_id = get<SPIRVariable>(arg_id).basetype; |
| 2430 | uint32_t next_id = ir.increase_bound_by(1); |
| 2431 | func.add_parameter(type_id, next_id, true); |
| 2432 | set<SPIRVariable>(next_id, type_id, StorageClassFunction, 0, arg_id); |
| 2433 | |
| 2434 | set_name(next_id, name); |
| 2435 | if (is_tese_shader() && msl_options.raw_buffer_tese_input && var.storage == StorageClassInput) |
| 2436 | set_decoration(next_id, DecorationNonWritable); |
| 2437 | } |
| 2438 | else if (is_builtin && is_mesh_shader()) |
| 2439 | { |
| 2440 | uint32_t next_id = ir.increase_bound_by(1); |
| 2441 | func.add_parameter(type_id, next_id, true); |
| 2442 | auto &v = set<SPIRVariable>(next_id, type_id, StorageClassFunction, 0, arg_id); |
| 2443 | v.storage = StorageClassWorkgroup; |
| 2444 | |
| 2445 | // Ensure the existing variable has a valid name and the new variable has all the same meta info |
| 2446 | if (ir.meta[arg_id].decoration.builtin) |
| 2447 | { |
| 2448 | set_name(arg_id, builtin_to_glsl(bi_type, var.storage)); |
| 2449 | } |
| 2450 | else |
| 2451 | { |
| 2452 | set_name(arg_id, ensure_valid_name(to_name(arg_id), "v")); |
| 2453 | } |
| 2454 | ir.meta[next_id] = ir.meta[arg_id]; |
| 2455 | } |
| 2456 | else if (is_builtin && has_decoration(p_type->self, DecorationBlock)) |
| 2457 | { |
| 2458 | // Get the pointee type |
| 2459 | type_id = get_pointee_type_id(type_id); |
| 2460 | p_type = &get<SPIRType>(type_id); |
| 2461 | |
| 2462 | uint32_t mbr_idx = 0; |
| 2463 | for (auto &mbr_type_id : p_type->member_types) |
| 2464 | { |
| 2465 | BuiltIn builtin = BuiltInMax; |
| 2466 | is_builtin = is_member_builtin(*p_type, mbr_idx, &builtin); |
| 2467 | if (is_builtin && has_active_builtin(builtin, var.storage)) |
| 2468 | { |
| 2469 | // Add a arg variable with the same type and decorations as the member |
| 2470 | uint32_t next_ids = ir.increase_bound_by(2); |
| 2471 | uint32_t ptr_type_id = next_ids + 0; |
| 2472 | uint32_t var_id = next_ids + 1; |
| 2473 | |
| 2474 | // Make sure we have an actual pointer type, |
| 2475 | // so that we will get the appropriate address space when declaring these builtins. |
| 2476 | auto &ptr = set<SPIRType>(ptr_type_id, get<SPIRType>(mbr_type_id)); |
| 2477 | ptr.self = mbr_type_id; |
| 2478 | ptr.storage = var.storage; |
| 2479 | ptr.pointer = true; |
| 2480 | ptr.pointer_depth++; |
| 2481 | ptr.parent_type = mbr_type_id; |
| 2482 | |
| 2483 | func.add_parameter(mbr_type_id, var_id, true); |
| 2484 | set<SPIRVariable>(var_id, ptr_type_id, StorageClassFunction); |
| 2485 | ir.meta[var_id].decoration = ir.meta[type_id].members[mbr_idx]; |
| 2486 | } |
| 2487 | mbr_idx++; |
| 2488 | } |
| 2489 | } |
| 2490 | else |
| 2491 | { |
| 2492 | uint32_t next_id = ir.increase_bound_by(1); |
| 2493 | func.add_parameter(type_id, next_id, true); |
| 2494 | set<SPIRVariable>(next_id, type_id, StorageClassFunction, 0, arg_id); |
| 2495 | |
| 2496 | // Ensure the new variable has all the same meta info |
| 2497 | ir.meta[next_id] = ir.meta[arg_id]; |
| 2498 | } |
| 2499 | } |
| 2500 | } |
| 2501 | } |
| 2502 | |
| 2503 | // For all variables that are some form of non-input-output interface block, mark that all the structs |
| 2504 | // that are recursively contained within the type referenced by that variable should be packed tightly. |
| 2505 | void CompilerMSL::mark_packable_structs() |
| 2506 | { |
| 2507 | ir.for_each_typed_id<SPIRVariable>([&](uint32_t, SPIRVariable &var) { |
| 2508 | if (var.storage != StorageClassFunction && !is_hidden_variable(var)) |
| 2509 | { |
| 2510 | auto &type = this->get<SPIRType>(var.basetype); |
| 2511 | if (type.pointer && |
| 2512 | (type.storage == StorageClassUniform || type.storage == StorageClassUniformConstant || |
| 2513 | type.storage == StorageClassPushConstant || type.storage == StorageClassStorageBuffer) && |
| 2514 | (has_decoration(type.self, DecorationBlock) || has_decoration(type.self, DecorationBufferBlock))) |
| 2515 | mark_as_packable(type); |
| 2516 | } |
| 2517 | |
| 2518 | if (var.storage == StorageClassWorkgroup) |
| 2519 | { |
| 2520 | auto *type = &this->get<SPIRType>(var.basetype); |
| 2521 | if (type->basetype == SPIRType::Struct) |
| 2522 | mark_as_workgroup_struct(*type); |
| 2523 | } |
| 2524 | }); |
| 2525 | |
| 2526 | // Physical storage buffer pointers can appear outside of the context of a variable, if the address |
| 2527 | // is calculated from a ulong or uvec2 and cast to a pointer, so check if they need to be packed too. |
| 2528 | ir.for_each_typed_id<SPIRType>([&](uint32_t, SPIRType &type) { |
| 2529 | if (type.basetype == SPIRType::Struct && type.pointer && type.storage == StorageClassPhysicalStorageBuffer) |
| 2530 | mark_as_packable(type); |
| 2531 | }); |
| 2532 | } |
| 2533 | |
| 2534 | // If the specified type is a struct, it and any nested structs |
| 2535 | // are marked as packable with the SPIRVCrossDecorationBufferBlockRepacked decoration, |
| 2536 | void CompilerMSL::mark_as_packable(SPIRType &type) |
| 2537 | { |
| 2538 | // If this is not the base type (eg. it's a pointer or array), tunnel down |
| 2539 | if (type.parent_type) |
| 2540 | { |
| 2541 | mark_as_packable(get<SPIRType>(type.parent_type)); |
| 2542 | return; |
| 2543 | } |
| 2544 | |
| 2545 | // Handle possible recursion when a struct contains a pointer to its own type nested somewhere. |
| 2546 | if (type.basetype == SPIRType::Struct && !has_extended_decoration(type.self, SPIRVCrossDecorationBufferBlockRepacked)) |
| 2547 | { |
| 2548 | set_extended_decoration(type.self, SPIRVCrossDecorationBufferBlockRepacked); |
| 2549 | |
| 2550 | // Recurse |
| 2551 | uint32_t mbr_cnt = uint32_t(type.member_types.size()); |
| 2552 | for (uint32_t mbr_idx = 0; mbr_idx < mbr_cnt; mbr_idx++) |
| 2553 | { |
| 2554 | uint32_t mbr_type_id = type.member_types[mbr_idx]; |
| 2555 | auto &mbr_type = get<SPIRType>(mbr_type_id); |
| 2556 | mark_as_packable(mbr_type); |
| 2557 | if (mbr_type.type_alias) |
| 2558 | { |
| 2559 | auto &mbr_type_alias = get<SPIRType>(mbr_type.type_alias); |
| 2560 | mark_as_packable(mbr_type_alias); |
| 2561 | } |
| 2562 | } |
| 2563 | } |
| 2564 | } |
| 2565 | |
| 2566 | // If the specified type is a struct, it and any nested structs |
| 2567 | // are marked as used with workgroup storage using the SPIRVCrossDecorationWorkgroupStruct decoration. |
| 2568 | void CompilerMSL::mark_as_workgroup_struct(SPIRType &type) |
| 2569 | { |
| 2570 | // If this is not the base type (eg. it's a pointer or array), tunnel down |
| 2571 | if (type.parent_type) |
| 2572 | { |
| 2573 | mark_as_workgroup_struct(get<SPIRType>(type.parent_type)); |
| 2574 | return; |
| 2575 | } |
| 2576 | |
| 2577 | // Handle possible recursion when a struct contains a pointer to its own type nested somewhere. |
| 2578 | if (type.basetype == SPIRType::Struct && !has_extended_decoration(type.self, SPIRVCrossDecorationWorkgroupStruct)) |
| 2579 | { |
| 2580 | set_extended_decoration(type.self, SPIRVCrossDecorationWorkgroupStruct); |
| 2581 | |
| 2582 | // Recurse |
| 2583 | uint32_t mbr_cnt = uint32_t(type.member_types.size()); |
| 2584 | for (uint32_t mbr_idx = 0; mbr_idx < mbr_cnt; mbr_idx++) |
| 2585 | { |
| 2586 | uint32_t mbr_type_id = type.member_types[mbr_idx]; |
| 2587 | auto &mbr_type = get<SPIRType>(mbr_type_id); |
| 2588 | mark_as_workgroup_struct(mbr_type); |
| 2589 | if (mbr_type.type_alias) |
| 2590 | { |
| 2591 | auto &mbr_type_alias = get<SPIRType>(mbr_type.type_alias); |
| 2592 | mark_as_workgroup_struct(mbr_type_alias); |
| 2593 | } |
| 2594 | } |
| 2595 | } |
| 2596 | } |
| 2597 | |
| 2598 | // If a shader input exists at the location, it is marked as being used by this shader |
| 2599 | void CompilerMSL::mark_location_as_used_by_shader(uint32_t location, const SPIRType &type, |
| 2600 | StorageClass storage, bool fallback) |
| 2601 | { |
| 2602 | uint32_t count = type_to_location_count(type); |
| 2603 | switch (storage) |
| 2604 | { |
| 2605 | case StorageClassInput: |
| 2606 | for (uint32_t i = 0; i < count; i++) |
| 2607 | { |
| 2608 | location_inputs_in_use.insert(location + i); |
| 2609 | if (fallback) |
| 2610 | location_inputs_in_use_fallback.insert(location + i); |
| 2611 | } |
| 2612 | break; |
| 2613 | case StorageClassOutput: |
| 2614 | for (uint32_t i = 0; i < count; i++) |
| 2615 | { |
| 2616 | location_outputs_in_use.insert(location + i); |
| 2617 | if (fallback) |
| 2618 | location_outputs_in_use_fallback.insert(location + i); |
| 2619 | } |
| 2620 | break; |
| 2621 | default: |
| 2622 | return; |
| 2623 | } |
| 2624 | } |
| 2625 | |
| 2626 | uint32_t CompilerMSL::get_target_components_for_fragment_location(uint32_t location) const |
| 2627 | { |
| 2628 | auto itr = fragment_output_components.find(location); |
| 2629 | if (itr == end(fragment_output_components)) |
| 2630 | return 4; |
| 2631 | else |
| 2632 | return itr->second; |
| 2633 | } |
| 2634 | |
| 2635 | uint32_t CompilerMSL::build_extended_vector_type(uint32_t type_id, uint32_t components, SPIRType::BaseType basetype) |
| 2636 | { |
| 2637 | assert(components > 1); |
| 2638 | uint32_t new_type_id = ir.increase_bound_by(1); |
| 2639 | const auto *p_old_type = &get<SPIRType>(type_id); |
| 2640 | const SPIRType *old_ptr_t = nullptr; |
| 2641 | const SPIRType *old_array_t = nullptr; |
| 2642 | |
| 2643 | if (is_pointer(*p_old_type)) |
| 2644 | { |
| 2645 | old_ptr_t = p_old_type; |
| 2646 | p_old_type = &get_pointee_type(*old_ptr_t); |
| 2647 | } |
| 2648 | |
| 2649 | if (is_array(*p_old_type)) |
| 2650 | { |
| 2651 | old_array_t = p_old_type; |
| 2652 | p_old_type = &get_type(old_array_t->parent_type); |
| 2653 | } |
| 2654 | |
| 2655 | auto *type = &set<SPIRType>(new_type_id, *p_old_type); |
| 2656 | assert(is_scalar(*type) || is_vector(*type)); |
| 2657 | type->op = OpTypeVector; |
| 2658 | type->vecsize = components; |
| 2659 | if (basetype != SPIRType::Unknown) |
| 2660 | type->basetype = basetype; |
| 2661 | type->self = new_type_id; |
| 2662 | // We want parent type to point to the scalar type. |
| 2663 | type->parent_type = is_scalar(*p_old_type) ? TypeID(p_old_type->self) : p_old_type->parent_type; |
| 2664 | assert(is_scalar(get<SPIRType>(type->parent_type))); |
| 2665 | type->array.clear(); |
| 2666 | type->array_size_literal.clear(); |
| 2667 | type->pointer = false; |
| 2668 | |
| 2669 | if (old_array_t) |
| 2670 | { |
| 2671 | uint32_t array_type_id = ir.increase_bound_by(1); |
| 2672 | type = &set<SPIRType>(array_type_id, *type); |
| 2673 | type->op = OpTypeArray; |
| 2674 | type->parent_type = new_type_id; |
| 2675 | type->array = old_array_t->array; |
| 2676 | type->array_size_literal = old_array_t->array_size_literal; |
| 2677 | new_type_id = array_type_id; |
| 2678 | } |
| 2679 | |
| 2680 | if (old_ptr_t) |
| 2681 | { |
| 2682 | uint32_t ptr_type_id = ir.increase_bound_by(1); |
| 2683 | type = &set<SPIRType>(ptr_type_id, *type); |
| 2684 | type->op = OpTypePointer; |
| 2685 | type->parent_type = new_type_id; |
| 2686 | type->storage = old_ptr_t->storage; |
| 2687 | type->pointer = true; |
| 2688 | type->pointer_depth++; |
| 2689 | new_type_id = ptr_type_id; |
| 2690 | } |
| 2691 | |
| 2692 | return new_type_id; |
| 2693 | } |
| 2694 | |
| 2695 | uint32_t CompilerMSL::build_msl_interpolant_type(uint32_t type_id, bool is_noperspective) |
| 2696 | { |
| 2697 | uint32_t new_type_id = ir.increase_bound_by(1); |
| 2698 | SPIRType &type = set<SPIRType>(new_type_id, get<SPIRType>(type_id)); |
| 2699 | type.basetype = SPIRType::Interpolant; |
| 2700 | type.parent_type = type_id; |
| 2701 | // In Metal, the pull-model interpolant type encodes perspective-vs-no-perspective in the type itself. |
| 2702 | // Add this decoration so we know which argument to pass to the template. |
| 2703 | if (is_noperspective) |
| 2704 | set_decoration(new_type_id, DecorationNoPerspective); |
| 2705 | return new_type_id; |
| 2706 | } |
| 2707 | |
| 2708 | bool CompilerMSL::add_component_variable_to_interface_block(spv::StorageClass storage, const std::string &ib_var_ref, |
| 2709 | SPIRVariable &var, |
| 2710 | const SPIRType &type, |
| 2711 | InterfaceBlockMeta &meta) |
| 2712 | { |
| 2713 | // Deal with Component decorations. |
| 2714 | const InterfaceBlockMeta::LocationMeta *location_meta = nullptr; |
| 2715 | uint32_t location = ~0u; |
| 2716 | if (has_decoration(var.self, DecorationLocation)) |
| 2717 | { |
| 2718 | location = get_decoration(var.self, DecorationLocation); |
| 2719 | auto location_meta_itr = meta.location_meta.find(location); |
| 2720 | if (location_meta_itr != end(meta.location_meta)) |
| 2721 | location_meta = &location_meta_itr->second; |
| 2722 | } |
| 2723 | |
| 2724 | // Check if we need to pad fragment output to match a certain number of components. |
| 2725 | if (location_meta) |
| 2726 | { |
| 2727 | bool pad_fragment_output = has_decoration(var.self, DecorationLocation) && |
| 2728 | msl_options.pad_fragment_output_components && |
| 2729 | get_entry_point().model == ExecutionModelFragment && storage == StorageClassOutput; |
| 2730 | |
| 2731 | auto &entry_func = get<SPIRFunction>(ir.default_entry_point); |
| 2732 | uint32_t start_component = get_decoration(var.self, DecorationComponent); |
| 2733 | uint32_t type_components = type.vecsize; |
| 2734 | uint32_t num_components = location_meta->num_components; |
| 2735 | |
| 2736 | if (pad_fragment_output) |
| 2737 | { |
| 2738 | uint32_t locn = get_decoration(var.self, DecorationLocation); |
| 2739 | num_components = max<uint32_t>(num_components, get_target_components_for_fragment_location(locn)); |
| 2740 | } |
| 2741 | |
| 2742 | // We have already declared an IO block member as m_location_N. |
| 2743 | // Just emit an early-declared variable and fixup as needed. |
| 2744 | // Arrays need to be unrolled here since each location might need a different number of components. |
| 2745 | entry_func.add_local_variable(var.self); |
| 2746 | vars_needing_early_declaration.push_back(var.self); |
| 2747 | |
| 2748 | if (var.storage == StorageClassInput) |
| 2749 | { |
| 2750 | entry_func.fixup_hooks_in.push_back([=, &type, &var]() { |
| 2751 | if (!type.array.empty()) |
| 2752 | { |
| 2753 | uint32_t array_size = to_array_size_literal(type); |
| 2754 | for (uint32_t loc_off = 0; loc_off < array_size; loc_off++) |
| 2755 | { |
| 2756 | statement(to_name(var.self), "[", loc_off, "]", " = ", ib_var_ref, |
| 2757 | ".m_location_", location + loc_off, |
| 2758 | vector_swizzle(type_components, start_component), ";"); |
| 2759 | } |
| 2760 | } |
| 2761 | else |
| 2762 | { |
| 2763 | statement(to_name(var.self), " = ", ib_var_ref, ".m_location_", location, |
| 2764 | vector_swizzle(type_components, start_component), ";"); |
| 2765 | } |
| 2766 | }); |
| 2767 | } |
| 2768 | else |
| 2769 | { |
| 2770 | entry_func.fixup_hooks_out.push_back([=, &type, &var]() { |
| 2771 | if (!type.array.empty()) |
| 2772 | { |
| 2773 | uint32_t array_size = to_array_size_literal(type); |
| 2774 | for (uint32_t loc_off = 0; loc_off < array_size; loc_off++) |
| 2775 | { |
| 2776 | statement(ib_var_ref, ".m_location_", location + loc_off, |
| 2777 | vector_swizzle(type_components, start_component), " = ", |
| 2778 | to_name(var.self), "[", loc_off, "];"); |
| 2779 | } |
| 2780 | } |
| 2781 | else |
| 2782 | { |
| 2783 | statement(ib_var_ref, ".m_location_", location, |
| 2784 | vector_swizzle(type_components, start_component), " = ", to_name(var.self), ";"); |
| 2785 | } |
| 2786 | }); |
| 2787 | } |
| 2788 | return true; |
| 2789 | } |
| 2790 | else |
| 2791 | return false; |
| 2792 | } |
| 2793 | |
| 2794 | void CompilerMSL::add_plain_variable_to_interface_block(StorageClass storage, const string &ib_var_ref, |
| 2795 | SPIRType &ib_type, SPIRVariable &var, InterfaceBlockMeta &meta) |
| 2796 | { |
| 2797 | bool is_builtin = is_builtin_variable(var); |
| 2798 | BuiltIn builtin = BuiltIn(get_decoration(var.self, DecorationBuiltIn)); |
| 2799 | bool is_flat = has_decoration(var.self, DecorationFlat); |
| 2800 | bool is_noperspective = has_decoration(var.self, DecorationNoPerspective); |
| 2801 | bool is_centroid = has_decoration(var.self, DecorationCentroid); |
| 2802 | bool is_sample = has_decoration(var.self, DecorationSample); |
| 2803 | |
| 2804 | // Add a reference to the variable type to the interface struct. |
| 2805 | uint32_t ib_mbr_idx = uint32_t(ib_type.member_types.size()); |
| 2806 | uint32_t type_id = ensure_correct_builtin_type(var.basetype, builtin); |
| 2807 | var.basetype = type_id; |
| 2808 | |
| 2809 | type_id = get_pointee_type_id(var.basetype); |
| 2810 | if (meta.strip_array && is_array(get<SPIRType>(type_id))) |
| 2811 | type_id = get<SPIRType>(type_id).parent_type; |
| 2812 | auto &type = get<SPIRType>(type_id); |
| 2813 | uint32_t target_components = 0; |
| 2814 | uint32_t type_components = type.vecsize; |
| 2815 | |
| 2816 | bool padded_output = false; |
| 2817 | bool padded_input = false; |
| 2818 | uint32_t start_component = 0; |
| 2819 | |
| 2820 | auto &entry_func = get<SPIRFunction>(ir.default_entry_point); |
| 2821 | |
| 2822 | if (add_component_variable_to_interface_block(storage, ib_var_ref, var, type, meta)) |
| 2823 | return; |
| 2824 | |
| 2825 | bool pad_fragment_output = has_decoration(var.self, DecorationLocation) && |
| 2826 | msl_options.pad_fragment_output_components && |
| 2827 | get_entry_point().model == ExecutionModelFragment && storage == StorageClassOutput; |
| 2828 | |
| 2829 | if (pad_fragment_output) |
| 2830 | { |
| 2831 | uint32_t locn = get_decoration(var.self, DecorationLocation); |
| 2832 | target_components = get_target_components_for_fragment_location(locn); |
| 2833 | if (type_components < target_components) |
| 2834 | { |
| 2835 | // Make a new type here. |
| 2836 | type_id = build_extended_vector_type(type_id, target_components); |
| 2837 | padded_output = true; |
| 2838 | } |
| 2839 | } |
| 2840 | |
| 2841 | if (storage == StorageClassInput && pull_model_inputs.count(var.self)) |
| 2842 | ib_type.member_types.push_back(build_msl_interpolant_type(type_id, is_noperspective)); |
| 2843 | else |
| 2844 | ib_type.member_types.push_back(type_id); |
| 2845 | |
| 2846 | // Give the member a name |
| 2847 | string mbr_name = ensure_valid_name(to_expression(var.self), "m"); |
| 2848 | set_member_name(ib_type.self, ib_mbr_idx, mbr_name); |
| 2849 | |
| 2850 | // Update the original variable reference to include the structure reference |
| 2851 | string qual_var_name = ib_var_ref + "." + mbr_name; |
| 2852 | // If using pull-model interpolation, need to add a call to the correct interpolation method. |
| 2853 | if (storage == StorageClassInput && pull_model_inputs.count(var.self)) |
| 2854 | { |
| 2855 | if (is_centroid) |
| 2856 | qual_var_name += ".interpolate_at_centroid()"; |
| 2857 | else if (is_sample) |
| 2858 | qual_var_name += join(".interpolate_at_sample(", to_expression(builtin_sample_id_id), ")"); |
| 2859 | else |
| 2860 | qual_var_name += ".interpolate_at_center()"; |
| 2861 | } |
| 2862 | |
| 2863 | if (padded_output || padded_input) |
| 2864 | { |
| 2865 | entry_func.add_local_variable(var.self); |
| 2866 | vars_needing_early_declaration.push_back(var.self); |
| 2867 | |
| 2868 | if (padded_output) |
| 2869 | { |
| 2870 | entry_func.fixup_hooks_out.push_back([=, &var]() { |
| 2871 | statement(qual_var_name, vector_swizzle(type_components, start_component), " = ", to_name(var.self), |
| 2872 | ";"); |
| 2873 | }); |
| 2874 | } |
| 2875 | else |
| 2876 | { |
| 2877 | entry_func.fixup_hooks_in.push_back([=, &var]() { |
| 2878 | statement(to_name(var.self), " = ", qual_var_name, vector_swizzle(type_components, start_component), |
| 2879 | ";"); |
| 2880 | }); |
| 2881 | } |
| 2882 | } |
| 2883 | else if (!meta.strip_array) |
| 2884 | ir.meta[var.self].decoration.qualified_alias = qual_var_name; |
| 2885 | |
| 2886 | if (var.storage == StorageClassOutput && var.initializer != ID(0)) |
| 2887 | { |
| 2888 | if (padded_output || padded_input) |
| 2889 | { |
| 2890 | entry_func.fixup_hooks_in.push_back( |
| 2891 | [=, &var]() { statement(to_name(var.self), " = ", to_expression(var.initializer), ";"); }); |
| 2892 | } |
| 2893 | else |
| 2894 | { |
| 2895 | if (meta.strip_array) |
| 2896 | { |
| 2897 | entry_func.fixup_hooks_in.push_back([=, &var]() { |
| 2898 | uint32_t index = get_extended_decoration(var.self, SPIRVCrossDecorationInterfaceMemberIndex); |
| 2899 | auto invocation = to_tesc_invocation_id(); |
| 2900 | statement(to_expression(stage_out_ptr_var_id), "[", |
| 2901 | invocation, "].", |
| 2902 | to_member_name(ib_type, index), " = ", to_expression(var.initializer), "[", |
| 2903 | invocation, "];"); |
| 2904 | }); |
| 2905 | } |
| 2906 | else |
| 2907 | { |
| 2908 | entry_func.fixup_hooks_in.push_back([=, &var]() { |
| 2909 | statement(qual_var_name, " = ", to_expression(var.initializer), ";"); |
| 2910 | }); |
| 2911 | } |
| 2912 | } |
| 2913 | } |
| 2914 | |
| 2915 | // Copy the variable location from the original variable to the member |
| 2916 | if (get_decoration_bitset(var.self).get(DecorationLocation)) |
| 2917 | { |
| 2918 | uint32_t locn = get_decoration(var.self, DecorationLocation); |
| 2919 | uint32_t comp = get_decoration(var.self, DecorationComponent); |
| 2920 | if (storage == StorageClassInput) |
| 2921 | { |
| 2922 | type_id = ensure_correct_input_type(var.basetype, locn, comp, 0, meta.strip_array); |
| 2923 | var.basetype = type_id; |
| 2924 | |
| 2925 | type_id = get_pointee_type_id(type_id); |
| 2926 | if (meta.strip_array && is_array(get<SPIRType>(type_id))) |
| 2927 | type_id = get<SPIRType>(type_id).parent_type; |
| 2928 | if (pull_model_inputs.count(var.self)) |
| 2929 | ib_type.member_types[ib_mbr_idx] = build_msl_interpolant_type(type_id, is_noperspective); |
| 2930 | else |
| 2931 | ib_type.member_types[ib_mbr_idx] = type_id; |
| 2932 | } |
| 2933 | set_member_decoration(ib_type.self, ib_mbr_idx, DecorationLocation, locn); |
| 2934 | if (comp) |
| 2935 | set_member_decoration(ib_type.self, ib_mbr_idx, DecorationComponent, comp); |
| 2936 | mark_location_as_used_by_shader(locn, get<SPIRType>(type_id), storage); |
| 2937 | } |
| 2938 | else if (is_builtin && is_tessellation_shader() && storage == StorageClassInput && inputs_by_builtin.count(builtin)) |
| 2939 | { |
| 2940 | uint32_t locn = inputs_by_builtin[builtin].location; |
| 2941 | set_member_decoration(ib_type.self, ib_mbr_idx, DecorationLocation, locn); |
| 2942 | mark_location_as_used_by_shader(locn, type, storage); |
| 2943 | } |
| 2944 | else if (is_builtin && capture_output_to_buffer && storage == StorageClassOutput && outputs_by_builtin.count(builtin)) |
| 2945 | { |
| 2946 | uint32_t locn = outputs_by_builtin[builtin].location; |
| 2947 | set_member_decoration(ib_type.self, ib_mbr_idx, DecorationLocation, locn); |
| 2948 | mark_location_as_used_by_shader(locn, type, storage); |
| 2949 | } |
| 2950 | |
| 2951 | if (get_decoration_bitset(var.self).get(DecorationComponent)) |
| 2952 | { |
| 2953 | uint32_t component = get_decoration(var.self, DecorationComponent); |
| 2954 | set_member_decoration(ib_type.self, ib_mbr_idx, DecorationComponent, component); |
| 2955 | } |
| 2956 | |
| 2957 | if (get_decoration_bitset(var.self).get(DecorationIndex)) |
| 2958 | { |
| 2959 | uint32_t index = get_decoration(var.self, DecorationIndex); |
| 2960 | set_member_decoration(ib_type.self, ib_mbr_idx, DecorationIndex, index); |
| 2961 | } |
| 2962 | |
| 2963 | // Mark the member as builtin if needed |
| 2964 | if (is_builtin) |
| 2965 | { |
| 2966 | set_member_decoration(ib_type.self, ib_mbr_idx, DecorationBuiltIn, builtin); |
| 2967 | if (builtin == BuiltInPosition && storage == StorageClassOutput) |
| 2968 | qual_pos_var_name = qual_var_name; |
| 2969 | } |
| 2970 | |
| 2971 | // Copy interpolation decorations if needed |
| 2972 | if (storage != StorageClassInput || !pull_model_inputs.count(var.self)) |
| 2973 | { |
| 2974 | if (is_flat) |
| 2975 | set_member_decoration(ib_type.self, ib_mbr_idx, DecorationFlat); |
| 2976 | if (is_noperspective) |
| 2977 | set_member_decoration(ib_type.self, ib_mbr_idx, DecorationNoPerspective); |
| 2978 | if (is_centroid) |
| 2979 | set_member_decoration(ib_type.self, ib_mbr_idx, DecorationCentroid); |
| 2980 | if (is_sample) |
| 2981 | set_member_decoration(ib_type.self, ib_mbr_idx, DecorationSample); |
| 2982 | } |
| 2983 | |
| 2984 | set_extended_member_decoration(ib_type.self, ib_mbr_idx, SPIRVCrossDecorationInterfaceOrigID, var.self); |
| 2985 | } |
| 2986 | |
| 2987 | void CompilerMSL::add_composite_variable_to_interface_block(StorageClass storage, const string &ib_var_ref, |
| 2988 | SPIRType &ib_type, SPIRVariable &var, |
| 2989 | InterfaceBlockMeta &meta) |
| 2990 | { |
| 2991 | auto &entry_func = get<SPIRFunction>(ir.default_entry_point); |
| 2992 | auto &var_type = meta.strip_array ? get_variable_element_type(var) : get_variable_data_type(var); |
| 2993 | uint32_t elem_cnt = 0; |
| 2994 | |
| 2995 | if (add_component_variable_to_interface_block(storage, ib_var_ref, var, var_type, meta)) |
| 2996 | return; |
| 2997 | |
| 2998 | if (is_matrix(var_type)) |
| 2999 | { |
| 3000 | if (is_array(var_type)) |
| 3001 | SPIRV_CROSS_THROW("MSL cannot emit arrays-of-matrices in input and output variables."); |
| 3002 | |
| 3003 | elem_cnt = var_type.columns; |
| 3004 | } |
| 3005 | else if (is_array(var_type)) |
| 3006 | { |
| 3007 | if (var_type.array.size() != 1) |
| 3008 | SPIRV_CROSS_THROW("MSL cannot emit arrays-of-arrays in input and output variables."); |
| 3009 | |
| 3010 | elem_cnt = to_array_size_literal(var_type); |
| 3011 | } |
| 3012 | |
| 3013 | bool is_builtin = is_builtin_variable(var); |
| 3014 | BuiltIn builtin = BuiltIn(get_decoration(var.self, DecorationBuiltIn)); |
| 3015 | bool is_flat = has_decoration(var.self, DecorationFlat); |
| 3016 | bool is_noperspective = has_decoration(var.self, DecorationNoPerspective); |
| 3017 | bool is_centroid = has_decoration(var.self, DecorationCentroid); |
| 3018 | bool is_sample = has_decoration(var.self, DecorationSample); |
| 3019 | |
| 3020 | auto *usable_type = &var_type; |
| 3021 | if (usable_type->pointer) |
| 3022 | usable_type = &get<SPIRType>(usable_type->parent_type); |
| 3023 | while (is_array(*usable_type) || is_matrix(*usable_type)) |
| 3024 | usable_type = &get<SPIRType>(usable_type->parent_type); |
| 3025 | |
| 3026 | // If a builtin, force it to have the proper name. |
| 3027 | if (is_builtin) |
| 3028 | set_name(var.self, builtin_to_glsl(builtin, StorageClassFunction)); |
| 3029 | |
| 3030 | bool flatten_from_ib_var = false; |
| 3031 | string flatten_from_ib_mbr_name; |
| 3032 | |
| 3033 | if (storage == StorageClassOutput && is_builtin && builtin == BuiltInClipDistance) |
| 3034 | { |
| 3035 | // Also declare [[clip_distance]] attribute here. |
| 3036 | uint32_t clip_array_mbr_idx = uint32_t(ib_type.member_types.size()); |
| 3037 | ib_type.member_types.push_back(get_variable_data_type_id(var)); |
| 3038 | set_member_decoration(ib_type.self, clip_array_mbr_idx, DecorationBuiltIn, BuiltInClipDistance); |
| 3039 | |
| 3040 | flatten_from_ib_mbr_name = builtin_to_glsl(BuiltInClipDistance, StorageClassOutput); |
| 3041 | set_member_name(ib_type.self, clip_array_mbr_idx, flatten_from_ib_mbr_name); |
| 3042 | |
| 3043 | // When we flatten, we flatten directly from the "out" struct, |
| 3044 | // not from a function variable. |
| 3045 | flatten_from_ib_var = true; |
| 3046 | |
| 3047 | if (!msl_options.enable_clip_distance_user_varying) |
| 3048 | return; |
| 3049 | } |
| 3050 | else if (!meta.strip_array) |
| 3051 | { |
| 3052 | // Only flatten/unflatten IO composites for non-tessellation cases where arrays are not stripped. |
| 3053 | entry_func.add_local_variable(var.self); |
| 3054 | // We need to declare the variable early and at entry-point scope. |
| 3055 | vars_needing_early_declaration.push_back(var.self); |
| 3056 | } |
| 3057 | |
| 3058 | for (uint32_t i = 0; i < elem_cnt; i++) |
| 3059 | { |
| 3060 | // Add a reference to the variable type to the interface struct. |
| 3061 | uint32_t ib_mbr_idx = uint32_t(ib_type.member_types.size()); |
| 3062 | |
| 3063 | uint32_t target_components = 0; |
| 3064 | bool padded_output = false; |
| 3065 | uint32_t type_id = usable_type->self; |
| 3066 | |
| 3067 | // Check if we need to pad fragment output to match a certain number of components. |
| 3068 | if (get_decoration_bitset(var.self).get(DecorationLocation) && msl_options.pad_fragment_output_components && |
| 3069 | get_entry_point().model == ExecutionModelFragment && storage == StorageClassOutput) |
| 3070 | { |
| 3071 | uint32_t locn = get_decoration(var.self, DecorationLocation) + i; |
| 3072 | target_components = get_target_components_for_fragment_location(locn); |
| 3073 | if (usable_type->vecsize < target_components) |
| 3074 | { |
| 3075 | // Make a new type here. |
| 3076 | type_id = build_extended_vector_type(usable_type->self, target_components); |
| 3077 | padded_output = true; |
| 3078 | } |
| 3079 | } |
| 3080 | |
| 3081 | if (storage == StorageClassInput && pull_model_inputs.count(var.self)) |
| 3082 | ib_type.member_types.push_back(build_msl_interpolant_type(get_pointee_type_id(type_id), is_noperspective)); |
| 3083 | else |
| 3084 | ib_type.member_types.push_back(get_pointee_type_id(type_id)); |
| 3085 | |
| 3086 | // Give the member a name |
| 3087 | string mbr_name = ensure_valid_name(join(to_expression(var.self), "_", i), "m"); |
| 3088 | set_member_name(ib_type.self, ib_mbr_idx, mbr_name); |
| 3089 | |
| 3090 | // There is no qualified alias since we need to flatten the internal array on return. |
| 3091 | if (get_decoration_bitset(var.self).get(DecorationLocation)) |
| 3092 | { |
| 3093 | uint32_t locn = get_decoration(var.self, DecorationLocation) + i; |
| 3094 | uint32_t comp = get_decoration(var.self, DecorationComponent); |
| 3095 | if (storage == StorageClassInput) |
| 3096 | { |
| 3097 | var.basetype = ensure_correct_input_type(var.basetype, locn, comp, 0, meta.strip_array); |
| 3098 | uint32_t mbr_type_id = ensure_correct_input_type(usable_type->self, locn, comp, 0, meta.strip_array); |
| 3099 | if (storage == StorageClassInput && pull_model_inputs.count(var.self)) |
| 3100 | ib_type.member_types[ib_mbr_idx] = build_msl_interpolant_type(mbr_type_id, is_noperspective); |
| 3101 | else |
| 3102 | ib_type.member_types[ib_mbr_idx] = mbr_type_id; |
| 3103 | } |
| 3104 | set_member_decoration(ib_type.self, ib_mbr_idx, DecorationLocation, locn); |
| 3105 | if (comp) |
| 3106 | set_member_decoration(ib_type.self, ib_mbr_idx, DecorationComponent, comp); |
| 3107 | mark_location_as_used_by_shader(locn, *usable_type, storage); |
| 3108 | } |
| 3109 | else if (is_builtin && is_tessellation_shader() && storage == StorageClassInput && inputs_by_builtin.count(builtin)) |
| 3110 | { |
| 3111 | uint32_t locn = inputs_by_builtin[builtin].location + i; |
| 3112 | set_member_decoration(ib_type.self, ib_mbr_idx, DecorationLocation, locn); |
| 3113 | mark_location_as_used_by_shader(locn, *usable_type, storage); |
| 3114 | } |
| 3115 | else if (is_builtin && capture_output_to_buffer && storage == StorageClassOutput && outputs_by_builtin.count(builtin)) |
| 3116 | { |
| 3117 | uint32_t locn = outputs_by_builtin[builtin].location + i; |
| 3118 | set_member_decoration(ib_type.self, ib_mbr_idx, DecorationLocation, locn); |
| 3119 | mark_location_as_used_by_shader(locn, *usable_type, storage); |
| 3120 | } |
| 3121 | else if (is_builtin && (builtin == BuiltInClipDistance || builtin == BuiltInCullDistance)) |
| 3122 | { |
| 3123 | // Declare the Clip/CullDistance as [[user(clip/cullN)]]. |
| 3124 | set_member_decoration(ib_type.self, ib_mbr_idx, DecorationBuiltIn, builtin); |
| 3125 | set_member_decoration(ib_type.self, ib_mbr_idx, DecorationIndex, i); |
| 3126 | } |
| 3127 | |
| 3128 | if (get_decoration_bitset(var.self).get(DecorationIndex)) |
| 3129 | { |
| 3130 | uint32_t index = get_decoration(var.self, DecorationIndex); |
| 3131 | set_member_decoration(ib_type.self, ib_mbr_idx, DecorationIndex, index); |
| 3132 | } |
| 3133 | |
| 3134 | if (storage != StorageClassInput || !pull_model_inputs.count(var.self)) |
| 3135 | { |
| 3136 | // Copy interpolation decorations if needed |
| 3137 | if (is_flat) |
| 3138 | set_member_decoration(ib_type.self, ib_mbr_idx, DecorationFlat); |
| 3139 | if (is_noperspective) |
| 3140 | set_member_decoration(ib_type.self, ib_mbr_idx, DecorationNoPerspective); |
| 3141 | if (is_centroid) |
| 3142 | set_member_decoration(ib_type.self, ib_mbr_idx, DecorationCentroid); |
| 3143 | if (is_sample) |
| 3144 | set_member_decoration(ib_type.self, ib_mbr_idx, DecorationSample); |
| 3145 | } |
| 3146 | |
| 3147 | set_extended_member_decoration(ib_type.self, ib_mbr_idx, SPIRVCrossDecorationInterfaceOrigID, var.self); |
| 3148 | |
| 3149 | // Only flatten/unflatten IO composites for non-tessellation cases where arrays are not stripped. |
| 3150 | if (!meta.strip_array) |
| 3151 | { |
| 3152 | switch (storage) |
| 3153 | { |
| 3154 | case StorageClassInput: |
| 3155 | entry_func.fixup_hooks_in.push_back([=, &var]() { |
| 3156 | if (pull_model_inputs.count(var.self)) |
| 3157 | { |
| 3158 | string lerp_call; |
| 3159 | if (is_centroid) |
| 3160 | lerp_call = ".interpolate_at_centroid()"; |
| 3161 | else if (is_sample) |
| 3162 | lerp_call = join(".interpolate_at_sample(", to_expression(builtin_sample_id_id), ")"); |
| 3163 | else |
| 3164 | lerp_call = ".interpolate_at_center()"; |
| 3165 | statement(to_name(var.self), "[", i, "] = ", ib_var_ref, ".", mbr_name, lerp_call, ";"); |
| 3166 | } |
| 3167 | else |
| 3168 | { |
| 3169 | statement(to_name(var.self), "[", i, "] = ", ib_var_ref, ".", mbr_name, ";"); |
| 3170 | } |
| 3171 | }); |
| 3172 | break; |
| 3173 | |
| 3174 | case StorageClassOutput: |
| 3175 | entry_func.fixup_hooks_out.push_back([=, &var]() { |
| 3176 | if (padded_output) |
| 3177 | { |
| 3178 | auto &padded_type = this->get<SPIRType>(type_id); |
| 3179 | statement( |
| 3180 | ib_var_ref, ".", mbr_name, " = ", |
| 3181 | remap_swizzle(padded_type, usable_type->vecsize, join(to_name(var.self), "[", i, "]")), |
| 3182 | ";"); |
| 3183 | } |
| 3184 | else if (flatten_from_ib_var) |
| 3185 | statement(ib_var_ref, ".", mbr_name, " = ", ib_var_ref, ".", flatten_from_ib_mbr_name, "[", i, |
| 3186 | "];"); |
| 3187 | else |
| 3188 | statement(ib_var_ref, ".", mbr_name, " = ", to_name(var.self), "[", i, "];"); |
| 3189 | }); |
| 3190 | break; |
| 3191 | |
| 3192 | default: |
| 3193 | break; |
| 3194 | } |
| 3195 | } |
| 3196 | } |
| 3197 | } |
| 3198 | |
| 3199 | void CompilerMSL::add_composite_member_variable_to_interface_block(StorageClass storage, |
| 3200 | const string &ib_var_ref, SPIRType &ib_type, |
| 3201 | SPIRVariable &var, SPIRType &var_type, |
| 3202 | uint32_t mbr_idx, InterfaceBlockMeta &meta, |
| 3203 | const string &mbr_name_qual, |
| 3204 | const string &var_chain_qual, |
| 3205 | uint32_t &location, uint32_t &var_mbr_idx, |
| 3206 | const Bitset &interpolation_qual) |
| 3207 | { |
| 3208 | auto &entry_func = get<SPIRFunction>(ir.default_entry_point); |
| 3209 | |
| 3210 | BuiltIn builtin = BuiltInMax; |
| 3211 | bool is_builtin = is_member_builtin(var_type, mbr_idx, &builtin); |
| 3212 | bool is_flat = interpolation_qual.get(DecorationFlat) || |
| 3213 | has_member_decoration(var_type.self, mbr_idx, DecorationFlat) || |
| 3214 | has_decoration(var.self, DecorationFlat); |
| 3215 | bool is_noperspective = interpolation_qual.get(DecorationNoPerspective) || |
| 3216 | has_member_decoration(var_type.self, mbr_idx, DecorationNoPerspective) || |
| 3217 | has_decoration(var.self, DecorationNoPerspective); |
| 3218 | bool is_centroid = interpolation_qual.get(DecorationCentroid) || |
| 3219 | has_member_decoration(var_type.self, mbr_idx, DecorationCentroid) || |
| 3220 | has_decoration(var.self, DecorationCentroid); |
| 3221 | bool is_sample = interpolation_qual.get(DecorationSample) || |
| 3222 | has_member_decoration(var_type.self, mbr_idx, DecorationSample) || |
| 3223 | has_decoration(var.self, DecorationSample); |
| 3224 | |
| 3225 | Bitset inherited_qual; |
| 3226 | if (is_flat) |
| 3227 | inherited_qual.set(DecorationFlat); |
| 3228 | if (is_noperspective) |
| 3229 | inherited_qual.set(DecorationNoPerspective); |
| 3230 | if (is_centroid) |
| 3231 | inherited_qual.set(DecorationCentroid); |
| 3232 | if (is_sample) |
| 3233 | inherited_qual.set(DecorationSample); |
| 3234 | |
| 3235 | uint32_t mbr_type_id = var_type.member_types[mbr_idx]; |
| 3236 | auto &mbr_type = get<SPIRType>(mbr_type_id); |
| 3237 | |
| 3238 | bool mbr_is_indexable = false; |
| 3239 | uint32_t elem_cnt = 1; |
| 3240 | if (is_matrix(mbr_type)) |
| 3241 | { |
| 3242 | if (is_array(mbr_type)) |
| 3243 | SPIRV_CROSS_THROW("MSL cannot emit arrays-of-matrices in input and output variables."); |
| 3244 | |
| 3245 | mbr_is_indexable = true; |
| 3246 | elem_cnt = mbr_type.columns; |
| 3247 | } |
| 3248 | else if (is_array(mbr_type)) |
| 3249 | { |
| 3250 | if (mbr_type.array.size() != 1) |
| 3251 | SPIRV_CROSS_THROW("MSL cannot emit arrays-of-arrays in input and output variables."); |
| 3252 | |
| 3253 | mbr_is_indexable = true; |
| 3254 | elem_cnt = to_array_size_literal(mbr_type); |
| 3255 | } |
| 3256 | |
| 3257 | auto *usable_type = &mbr_type; |
| 3258 | if (usable_type->pointer) |
| 3259 | usable_type = &get<SPIRType>(usable_type->parent_type); |
| 3260 | while (is_array(*usable_type) || is_matrix(*usable_type)) |
| 3261 | usable_type = &get<SPIRType>(usable_type->parent_type); |
| 3262 | |
| 3263 | bool flatten_from_ib_var = false; |
| 3264 | string flatten_from_ib_mbr_name; |
| 3265 | |
| 3266 | if (storage == StorageClassOutput && is_builtin && builtin == BuiltInClipDistance) |
| 3267 | { |
| 3268 | // Also declare [[clip_distance]] attribute here. |
| 3269 | uint32_t clip_array_mbr_idx = uint32_t(ib_type.member_types.size()); |
| 3270 | ib_type.member_types.push_back(mbr_type_id); |
| 3271 | set_member_decoration(ib_type.self, clip_array_mbr_idx, DecorationBuiltIn, BuiltInClipDistance); |
| 3272 | |
| 3273 | flatten_from_ib_mbr_name = builtin_to_glsl(BuiltInClipDistance, StorageClassOutput); |
| 3274 | set_member_name(ib_type.self, clip_array_mbr_idx, flatten_from_ib_mbr_name); |
| 3275 | |
| 3276 | // When we flatten, we flatten directly from the "out" struct, |
| 3277 | // not from a function variable. |
| 3278 | flatten_from_ib_var = true; |
| 3279 | |
| 3280 | if (!msl_options.enable_clip_distance_user_varying) |
| 3281 | return; |
| 3282 | } |
| 3283 | |
| 3284 | // Recursively handle nested structures. |
| 3285 | if (mbr_type.basetype == SPIRType::Struct) |
| 3286 | { |
| 3287 | for (uint32_t i = 0; i < elem_cnt; i++) |
| 3288 | { |
| 3289 | string mbr_name = append_member_name(mbr_name_qual, var_type, mbr_idx) + (mbr_is_indexable ? join("_", i) : ""); |
| 3290 | string var_chain = join(var_chain_qual, ".", to_member_name(var_type, mbr_idx), (mbr_is_indexable ? join("[", i, "]") : "")); |
| 3291 | uint32_t sub_mbr_cnt = uint32_t(mbr_type.member_types.size()); |
| 3292 | for (uint32_t sub_mbr_idx = 0; sub_mbr_idx < sub_mbr_cnt; sub_mbr_idx++) |
| 3293 | { |
| 3294 | add_composite_member_variable_to_interface_block(storage, ib_var_ref, ib_type, |
| 3295 | var, mbr_type, sub_mbr_idx, |
| 3296 | meta, mbr_name, var_chain, |
| 3297 | location, var_mbr_idx, inherited_qual); |
| 3298 | // FIXME: Recursive structs and tessellation breaks here. |
| 3299 | var_mbr_idx++; |
| 3300 | } |
| 3301 | } |
| 3302 | return; |
| 3303 | } |
| 3304 | |
| 3305 | for (uint32_t i = 0; i < elem_cnt; i++) |
| 3306 | { |
| 3307 | // Add a reference to the variable type to the interface struct. |
| 3308 | uint32_t ib_mbr_idx = uint32_t(ib_type.member_types.size()); |
| 3309 | if (storage == StorageClassInput && pull_model_inputs.count(var.self)) |
| 3310 | ib_type.member_types.push_back(build_msl_interpolant_type(usable_type->self, is_noperspective)); |
| 3311 | else |
| 3312 | ib_type.member_types.push_back(usable_type->self); |
| 3313 | |
| 3314 | // Give the member a name |
| 3315 | string mbr_name = ensure_valid_name(append_member_name(mbr_name_qual, var_type, mbr_idx) + (mbr_is_indexable ? join("_", i) : ""), "m"); |
| 3316 | set_member_name(ib_type.self, ib_mbr_idx, mbr_name); |
| 3317 | |
| 3318 | // The SPIRV location of interface variable, used to obtain the initial |
| 3319 | // MSL location (the location variable) and interface matching |
| 3320 | uint32_t ir_location = UINT32_MAX; |
| 3321 | bool has_member_loc_decor = has_member_decoration(var_type.self, mbr_idx, DecorationLocation); |
| 3322 | bool has_var_loc_decor = has_decoration(var.self, DecorationLocation); |
| 3323 | uint32_t orig_vecsize = UINT32_MAX; |
| 3324 | |
| 3325 | // If we haven't established a location base yet, do so here. |
| 3326 | if (location == UINT32_MAX) |
| 3327 | { |
| 3328 | if (has_member_loc_decor) |
| 3329 | ir_location = get_member_decoration(var_type.self, mbr_idx, DecorationLocation); |
| 3330 | else if (has_var_loc_decor) |
| 3331 | ir_location = get_accumulated_member_location(var, mbr_idx, meta.strip_array); |
| 3332 | else if (is_builtin) |
| 3333 | { |
| 3334 | if (is_tessellation_shader() && storage == StorageClassInput && inputs_by_builtin.count(builtin)) |
| 3335 | ir_location = inputs_by_builtin[builtin].location; |
| 3336 | else if (capture_output_to_buffer && storage == StorageClassOutput && outputs_by_builtin.count(builtin)) |
| 3337 | ir_location = outputs_by_builtin[builtin].location; |
| 3338 | } |
| 3339 | } |
| 3340 | |
| 3341 | // Once we determine the location of the first member within nested structures, |
| 3342 | // from a var of the topmost structure, the remaining flattened members of |
| 3343 | // the nested structures will have consecutive location values. At this point, |
| 3344 | // we've recursively tunnelled into structs, arrays, and matrices, and are |
| 3345 | // down to a single location for each member now. |
| 3346 | if (location == UINT32_MAX && ir_location != UINT32_MAX) |
| 3347 | location = ir_location + i; |
| 3348 | |
| 3349 | if (storage == StorageClassInput && (has_member_loc_decor || has_var_loc_decor)) |
| 3350 | { |
| 3351 | uint32_t component = 0; |
| 3352 | uint32_t orig_mbr_type_id = usable_type->self; |
| 3353 | |
| 3354 | if (has_member_loc_decor) |
| 3355 | component = get_member_decoration(var_type.self, mbr_idx, DecorationComponent); |
| 3356 | |
| 3357 | var.basetype = ensure_correct_input_type(var.basetype, location, component, 0, meta.strip_array); |
| 3358 | mbr_type_id = ensure_correct_input_type(usable_type->self, location, component, 0, meta.strip_array); |
| 3359 | |
| 3360 | // For members of the composite interface block, we only change the interface block type |
| 3361 | // when interface matching happens. In the meantime, we store the original vector size |
| 3362 | // and insert a swizzle when loading from metal interface block (see fixup below) |
| 3363 | if (mbr_type_id != orig_mbr_type_id) |
| 3364 | orig_vecsize = get<SPIRType>(orig_mbr_type_id).vecsize; |
| 3365 | |
| 3366 | if (storage == StorageClassInput && pull_model_inputs.count(var.self)) |
| 3367 | ib_type.member_types[ib_mbr_idx] = build_msl_interpolant_type(mbr_type_id, is_noperspective); |
| 3368 | else |
| 3369 | ib_type.member_types[ib_mbr_idx] = mbr_type_id; |
| 3370 | } |
| 3371 | |
| 3372 | if ((!is_builtin && location != UINT32_MAX) || (is_builtin && ir_location != UINT32_MAX)) |
| 3373 | { |
| 3374 | set_member_decoration(ib_type.self, ib_mbr_idx, DecorationLocation, location); |
| 3375 | mark_location_as_used_by_shader(location, *usable_type, storage); |
| 3376 | location++; |
| 3377 | } |
| 3378 | else if (is_builtin && (builtin == BuiltInClipDistance || builtin == BuiltInCullDistance)) |
| 3379 | { |
| 3380 | // Declare the Clip/CullDistance as [[user(clip/cullN)]]. |
| 3381 | set_member_decoration(ib_type.self, ib_mbr_idx, DecorationBuiltIn, builtin); |
| 3382 | set_member_decoration(ib_type.self, ib_mbr_idx, DecorationIndex, i); |
| 3383 | } |
| 3384 | |
| 3385 | if (has_member_decoration(var_type.self, mbr_idx, DecorationComponent)) |
| 3386 | SPIRV_CROSS_THROW("DecorationComponent on matrices and arrays is not supported."); |
| 3387 | |
| 3388 | if (storage != StorageClassInput || !pull_model_inputs.count(var.self)) |
| 3389 | { |
| 3390 | // Copy interpolation decorations if needed |
| 3391 | if (is_flat) |
| 3392 | set_member_decoration(ib_type.self, ib_mbr_idx, DecorationFlat); |
| 3393 | if (is_noperspective) |
| 3394 | set_member_decoration(ib_type.self, ib_mbr_idx, DecorationNoPerspective); |
| 3395 | if (is_centroid) |
| 3396 | set_member_decoration(ib_type.self, ib_mbr_idx, DecorationCentroid); |
| 3397 | if (is_sample) |
| 3398 | set_member_decoration(ib_type.self, ib_mbr_idx, DecorationSample); |
| 3399 | } |
| 3400 | |
| 3401 | set_extended_member_decoration(ib_type.self, ib_mbr_idx, SPIRVCrossDecorationInterfaceOrigID, var.self); |
| 3402 | set_extended_member_decoration(ib_type.self, ib_mbr_idx, SPIRVCrossDecorationInterfaceMemberIndex, var_mbr_idx); |
| 3403 | |
| 3404 | // Unflatten or flatten from [[stage_in]] or [[stage_out]] as appropriate. |
| 3405 | if (!meta.strip_array && meta.allow_local_declaration) |
| 3406 | { |
| 3407 | string var_chain = join(var_chain_qual, ".", to_member_name(var_type, mbr_idx), (mbr_is_indexable ? join("[", i, "]") : "")); |
| 3408 | switch (storage) |
| 3409 | { |
| 3410 | case StorageClassInput: |
| 3411 | entry_func.fixup_hooks_in.push_back([=, &var]() { |
| 3412 | string lerp_call; |
| 3413 | string swizzle; |
| 3414 | if (pull_model_inputs.count(var.self)) |
| 3415 | { |
| 3416 | if (is_centroid) |
| 3417 | lerp_call = ".interpolate_at_centroid()"; |
| 3418 | else if (is_sample) |
| 3419 | lerp_call = join(".interpolate_at_sample(", to_expression(builtin_sample_id_id), ")"); |
| 3420 | else |
| 3421 | lerp_call = ".interpolate_at_center()"; |
| 3422 | } |
| 3423 | if (orig_vecsize != UINT32_MAX) |
| 3424 | swizzle = vector_swizzle(orig_vecsize, 0); |
| 3425 | statement(var_chain, " = ", ib_var_ref, ".", mbr_name, lerp_call, swizzle, ";"); |
| 3426 | }); |
| 3427 | break; |
| 3428 | |
| 3429 | case StorageClassOutput: |
| 3430 | entry_func.fixup_hooks_out.push_back([=]() { |
| 3431 | if (flatten_from_ib_var) |
| 3432 | statement(ib_var_ref, ".", mbr_name, " = ", ib_var_ref, ".", flatten_from_ib_mbr_name, "[", i, "];"); |
| 3433 | else |
| 3434 | statement(ib_var_ref, ".", mbr_name, " = ", var_chain, ";"); |
| 3435 | }); |
| 3436 | break; |
| 3437 | |
| 3438 | default: |
| 3439 | break; |
| 3440 | } |
| 3441 | } |
| 3442 | } |
| 3443 | } |
| 3444 | |
| 3445 | void CompilerMSL::add_plain_member_variable_to_interface_block(StorageClass storage, |
| 3446 | const string &ib_var_ref, SPIRType &ib_type, |
| 3447 | SPIRVariable &var, SPIRType &var_type, |
| 3448 | uint32_t mbr_idx, InterfaceBlockMeta &meta, |
| 3449 | const string &mbr_name_qual, |
| 3450 | const string &var_chain_qual, |
| 3451 | uint32_t &location, uint32_t &var_mbr_idx) |
| 3452 | { |
| 3453 | auto &entry_func = get<SPIRFunction>(ir.default_entry_point); |
| 3454 | |
| 3455 | BuiltIn builtin = BuiltInMax; |
| 3456 | bool is_builtin = is_member_builtin(var_type, mbr_idx, &builtin); |
| 3457 | bool is_flat = |
| 3458 | has_member_decoration(var_type.self, mbr_idx, DecorationFlat) || has_decoration(var.self, DecorationFlat); |
| 3459 | bool is_noperspective = has_member_decoration(var_type.self, mbr_idx, DecorationNoPerspective) || |
| 3460 | has_decoration(var.self, DecorationNoPerspective); |
| 3461 | bool is_centroid = has_member_decoration(var_type.self, mbr_idx, DecorationCentroid) || |
| 3462 | has_decoration(var.self, DecorationCentroid); |
| 3463 | bool is_sample = |
| 3464 | has_member_decoration(var_type.self, mbr_idx, DecorationSample) || has_decoration(var.self, DecorationSample); |
| 3465 | |
| 3466 | // Add a reference to the member to the interface struct. |
| 3467 | uint32_t mbr_type_id = var_type.member_types[mbr_idx]; |
| 3468 | uint32_t ib_mbr_idx = uint32_t(ib_type.member_types.size()); |
| 3469 | mbr_type_id = ensure_correct_builtin_type(mbr_type_id, builtin); |
| 3470 | var_type.member_types[mbr_idx] = mbr_type_id; |
| 3471 | if (storage == StorageClassInput && pull_model_inputs.count(var.self)) |
| 3472 | ib_type.member_types.push_back(build_msl_interpolant_type(mbr_type_id, is_noperspective)); |
| 3473 | else |
| 3474 | ib_type.member_types.push_back(mbr_type_id); |
| 3475 | |
| 3476 | // Give the member a name |
| 3477 | string mbr_name = ensure_valid_name(append_member_name(mbr_name_qual, var_type, mbr_idx), "m"); |
| 3478 | set_member_name(ib_type.self, ib_mbr_idx, mbr_name); |
| 3479 | |
| 3480 | // Update the original variable reference to include the structure reference |
| 3481 | string qual_var_name = ib_var_ref + "." + mbr_name; |
| 3482 | // If using pull-model interpolation, need to add a call to the correct interpolation method. |
| 3483 | if (storage == StorageClassInput && pull_model_inputs.count(var.self)) |
| 3484 | { |
| 3485 | if (is_centroid) |
| 3486 | qual_var_name += ".interpolate_at_centroid()"; |
| 3487 | else if (is_sample) |
| 3488 | qual_var_name += join(".interpolate_at_sample(", to_expression(builtin_sample_id_id), ")"); |
| 3489 | else |
| 3490 | qual_var_name += ".interpolate_at_center()"; |
| 3491 | } |
| 3492 | |
| 3493 | // The SPIRV location of interface variable, used to obtain the initial |
| 3494 | // MSL location (the location variable) and interface matching |
| 3495 | uint32_t ir_location = UINT32_MAX; |
| 3496 | bool has_member_loc_decor = has_member_decoration(var_type.self, mbr_idx, DecorationLocation); |
| 3497 | bool has_var_loc_decor = has_decoration(var.self, DecorationLocation); |
| 3498 | uint32_t orig_vecsize = UINT32_MAX; |
| 3499 | |
| 3500 | if (has_member_loc_decor) |
| 3501 | ir_location = get_member_decoration(var_type.self, mbr_idx, DecorationLocation); |
| 3502 | else if (has_var_loc_decor) |
| 3503 | ir_location = get_accumulated_member_location(var, mbr_idx, meta.strip_array); |
| 3504 | else if (is_builtin) |
| 3505 | { |
| 3506 | if (is_tessellation_shader() && storage == StorageClassInput && inputs_by_builtin.count(builtin)) |
| 3507 | ir_location = inputs_by_builtin[builtin].location; |
| 3508 | else if (capture_output_to_buffer && storage == StorageClassOutput && outputs_by_builtin.count(builtin)) |
| 3509 | ir_location = outputs_by_builtin[builtin].location; |
| 3510 | } |
| 3511 | |
| 3512 | // Once we determine the location of the first member within nested structures, |
| 3513 | // from a var of the topmost structure, the remaining flattened members of |
| 3514 | // the nested structures will have consecutive location values. At this point, |
| 3515 | // we've recursively tunnelled into structs, arrays, and matrices, and are |
| 3516 | // down to a single location for each member now. |
| 3517 | if (location == UINT32_MAX && ir_location != UINT32_MAX) |
| 3518 | location = ir_location; |
| 3519 | |
| 3520 | if (storage == StorageClassInput && (has_member_loc_decor || has_var_loc_decor)) |
| 3521 | { |
| 3522 | uint32_t component = 0; |
| 3523 | uint32_t orig_mbr_type_id = mbr_type_id; |
| 3524 | |
| 3525 | if (has_member_loc_decor) |
| 3526 | component = get_member_decoration(var_type.self, mbr_idx, DecorationComponent); |
| 3527 | |
| 3528 | mbr_type_id = ensure_correct_input_type(mbr_type_id, location, component, 0, meta.strip_array); |
| 3529 | |
| 3530 | // For members of the composite interface block, we only change the interface block type |
| 3531 | // when interface matching happens. In the meantime, we store the original vector size |
| 3532 | // and insert a swizzle when loading from metal interface block (see fixup below) |
| 3533 | if (mbr_type_id != orig_mbr_type_id) |
| 3534 | orig_vecsize = get<SPIRType>(orig_mbr_type_id).vecsize; |
| 3535 | |
| 3536 | if (storage == StorageClassInput && pull_model_inputs.count(var.self)) |
| 3537 | ib_type.member_types[ib_mbr_idx] = build_msl_interpolant_type(mbr_type_id, is_noperspective); |
| 3538 | else |
| 3539 | ib_type.member_types[ib_mbr_idx] = mbr_type_id; |
| 3540 | } |
| 3541 | |
| 3542 | bool flatten_stage_out = false; |
| 3543 | string var_chain = var_chain_qual + "." + to_member_name(var_type, mbr_idx); |
| 3544 | if (is_builtin && !meta.strip_array) |
| 3545 | { |
| 3546 | // For the builtin gl_PerVertex, we cannot treat it as a block anyways, |
| 3547 | // so redirect to qualified name. |
| 3548 | set_member_qualified_name(var_type.self, mbr_idx, qual_var_name); |
| 3549 | } |
| 3550 | else if (!meta.strip_array && meta.allow_local_declaration) |
| 3551 | { |
| 3552 | // Unflatten or flatten from [[stage_in]] or [[stage_out]] as appropriate. |
| 3553 | switch (storage) |
| 3554 | { |
| 3555 | case StorageClassInput: |
| 3556 | entry_func.fixup_hooks_in.push_back([=]() { |
| 3557 | string swizzle; |
| 3558 | // Insert swizzle for widened interface block vector from interface matching |
| 3559 | if (orig_vecsize != UINT32_MAX) |
| 3560 | swizzle = vector_swizzle(orig_vecsize, 0); |
| 3561 | statement(var_chain, " = ", qual_var_name, swizzle, ";"); |
| 3562 | }); |
| 3563 | break; |
| 3564 | |
| 3565 | case StorageClassOutput: |
| 3566 | flatten_stage_out = true; |
| 3567 | entry_func.fixup_hooks_out.push_back([=]() { |
| 3568 | statement(qual_var_name, " = ", var_chain, ";"); |
| 3569 | }); |
| 3570 | break; |
| 3571 | |
| 3572 | default: |
| 3573 | break; |
| 3574 | } |
| 3575 | } |
| 3576 | |
| 3577 | if ((!is_builtin && location != UINT32_MAX) || (is_builtin && ir_location != UINT32_MAX)) |
| 3578 | { |
| 3579 | set_member_decoration(ib_type.self, ib_mbr_idx, DecorationLocation, location); |
| 3580 | mark_location_as_used_by_shader(location, get<SPIRType>(mbr_type_id), storage); |
| 3581 | location += type_to_location_count(get<SPIRType>(mbr_type_id)); |
| 3582 | } |
| 3583 | |
| 3584 | // Copy the component location, if present. |
| 3585 | if (has_member_decoration(var_type.self, mbr_idx, DecorationComponent)) |
| 3586 | { |
| 3587 | uint32_t comp = get_member_decoration(var_type.self, mbr_idx, DecorationComponent); |
| 3588 | set_member_decoration(ib_type.self, ib_mbr_idx, DecorationComponent, comp); |
| 3589 | } |
| 3590 | |
| 3591 | // Mark the member as builtin if needed |
| 3592 | if (is_builtin) |
| 3593 | { |
| 3594 | set_member_decoration(ib_type.self, ib_mbr_idx, DecorationBuiltIn, builtin); |
| 3595 | if (builtin == BuiltInPosition && storage == StorageClassOutput) |
| 3596 | qual_pos_var_name = qual_var_name; |
| 3597 | } |
| 3598 | |
| 3599 | const SPIRConstant *c = nullptr; |
| 3600 | if (!flatten_stage_out && var.storage == StorageClassOutput && |
| 3601 | var.initializer != ID(0) && (c = maybe_get<SPIRConstant>(var.initializer))) |
| 3602 | { |
| 3603 | if (meta.strip_array) |
| 3604 | { |
| 3605 | entry_func.fixup_hooks_in.push_back([=, &var]() { |
| 3606 | auto &type = this->get<SPIRType>(var.basetype); |
| 3607 | uint32_t index = get_extended_member_decoration(var.self, mbr_idx, SPIRVCrossDecorationInterfaceMemberIndex); |
| 3608 | |
| 3609 | auto invocation = to_tesc_invocation_id(); |
| 3610 | auto constant_chain = join(to_expression(var.initializer), "[", invocation, "]"); |
| 3611 | statement(to_expression(stage_out_ptr_var_id), "[", |
| 3612 | invocation, "].", |
| 3613 | to_member_name(ib_type, index), " = ", |
| 3614 | constant_chain, ".", to_member_name(type, mbr_idx), ";"); |
| 3615 | }); |
| 3616 | } |
| 3617 | else |
| 3618 | { |
| 3619 | entry_func.fixup_hooks_in.push_back([=]() { |
| 3620 | statement(qual_var_name, " = ", constant_expression( |
| 3621 | this->get<SPIRConstant>(c->subconstants[mbr_idx])), ";"); |
| 3622 | }); |
| 3623 | } |
| 3624 | } |
| 3625 | |
| 3626 | if (storage != StorageClassInput || !pull_model_inputs.count(var.self)) |
| 3627 | { |
| 3628 | // Copy interpolation decorations if needed |
| 3629 | if (is_flat) |
| 3630 | set_member_decoration(ib_type.self, ib_mbr_idx, DecorationFlat); |
| 3631 | if (is_noperspective) |
| 3632 | set_member_decoration(ib_type.self, ib_mbr_idx, DecorationNoPerspective); |
| 3633 | if (is_centroid) |
| 3634 | set_member_decoration(ib_type.self, ib_mbr_idx, DecorationCentroid); |
| 3635 | if (is_sample) |
| 3636 | set_member_decoration(ib_type.self, ib_mbr_idx, DecorationSample); |
| 3637 | } |
| 3638 | |
| 3639 | set_extended_member_decoration(ib_type.self, ib_mbr_idx, SPIRVCrossDecorationInterfaceOrigID, var.self); |
| 3640 | set_extended_member_decoration(ib_type.self, ib_mbr_idx, SPIRVCrossDecorationInterfaceMemberIndex, var_mbr_idx); |
| 3641 | } |
| 3642 | |
| 3643 | // In Metal, the tessellation levels are stored as tightly packed half-precision floating point values. |
| 3644 | // But, stage-in attribute offsets and strides must be multiples of four, so we can't pass the levels |
| 3645 | // individually. Therefore, we must pass them as vectors. Triangles get a single float4, with the outer |
| 3646 | // levels in 'xyz' and the inner level in 'w'. Quads get a float4 containing the outer levels and a |
| 3647 | // float2 containing the inner levels. |
| 3648 | void CompilerMSL::add_tess_level_input_to_interface_block(const std::string &ib_var_ref, SPIRType &ib_type, |
| 3649 | SPIRVariable &var) |
| 3650 | { |
| 3651 | auto &var_type = get_variable_element_type(var); |
| 3652 | |
| 3653 | BuiltIn builtin = BuiltIn(get_decoration(var.self, DecorationBuiltIn)); |
| 3654 | bool triangles = is_tessellating_triangles(); |
| 3655 | string mbr_name; |
| 3656 | |
| 3657 | // Add a reference to the variable type to the interface struct. |
| 3658 | uint32_t ib_mbr_idx = uint32_t(ib_type.member_types.size()); |
| 3659 | |
| 3660 | const auto mark_locations = [&](const SPIRType &new_var_type) { |
| 3661 | if (get_decoration_bitset(var.self).get(DecorationLocation)) |
| 3662 | { |
| 3663 | uint32_t locn = get_decoration(var.self, DecorationLocation); |
| 3664 | set_member_decoration(ib_type.self, ib_mbr_idx, DecorationLocation, locn); |
| 3665 | mark_location_as_used_by_shader(locn, new_var_type, StorageClassInput); |
| 3666 | } |
| 3667 | else if (inputs_by_builtin.count(builtin)) |
| 3668 | { |
| 3669 | uint32_t locn = inputs_by_builtin[builtin].location; |
| 3670 | set_member_decoration(ib_type.self, ib_mbr_idx, DecorationLocation, locn); |
| 3671 | mark_location_as_used_by_shader(locn, new_var_type, StorageClassInput); |
| 3672 | } |
| 3673 | }; |
| 3674 | |
| 3675 | if (triangles) |
| 3676 | { |
| 3677 | // Triangles are tricky, because we want only one member in the struct. |
| 3678 | mbr_name = "gl_TessLevel"; |
| 3679 | |
| 3680 | // If we already added the other one, we can skip this step. |
| 3681 | if (!added_builtin_tess_level) |
| 3682 | { |
| 3683 | uint32_t type_id = build_extended_vector_type(var_type.self, 4); |
| 3684 | |
| 3685 | ib_type.member_types.push_back(type_id); |
| 3686 | |
| 3687 | // Give the member a name |
| 3688 | set_member_name(ib_type.self, ib_mbr_idx, mbr_name); |
| 3689 | |
| 3690 | // We cannot decorate both, but the important part is that |
| 3691 | // it's marked as builtin so we can get automatic attribute assignment if needed. |
| 3692 | set_member_decoration(ib_type.self, ib_mbr_idx, DecorationBuiltIn, builtin); |
| 3693 | |
| 3694 | mark_locations(var_type); |
| 3695 | added_builtin_tess_level = true; |
| 3696 | } |
| 3697 | } |
| 3698 | else |
| 3699 | { |
| 3700 | mbr_name = builtin_to_glsl(builtin, StorageClassFunction); |
| 3701 | |
| 3702 | uint32_t type_id = build_extended_vector_type(var_type.self, builtin == BuiltInTessLevelOuter ? 4 : 2); |
| 3703 | |
| 3704 | uint32_t ptr_type_id = ir.increase_bound_by(1); |
| 3705 | auto &new_var_type = set<SPIRType>(ptr_type_id, get<SPIRType>(type_id)); |
| 3706 | new_var_type.pointer = true; |
| 3707 | new_var_type.pointer_depth++; |
| 3708 | new_var_type.storage = StorageClassInput; |
| 3709 | new_var_type.parent_type = type_id; |
| 3710 | |
| 3711 | ib_type.member_types.push_back(type_id); |
| 3712 | |
| 3713 | // Give the member a name |
| 3714 | set_member_name(ib_type.self, ib_mbr_idx, mbr_name); |
| 3715 | set_member_decoration(ib_type.self, ib_mbr_idx, DecorationBuiltIn, builtin); |
| 3716 | |
| 3717 | mark_locations(new_var_type); |
| 3718 | } |
| 3719 | |
| 3720 | add_tess_level_input(ib_var_ref, mbr_name, var); |
| 3721 | } |
| 3722 | |
| 3723 | void CompilerMSL::add_tess_level_input(const std::string &base_ref, const std::string &mbr_name, SPIRVariable &var) |
| 3724 | { |
| 3725 | auto &entry_func = get<SPIRFunction>(ir.default_entry_point); |
| 3726 | BuiltIn builtin = BuiltIn(get_decoration(var.self, DecorationBuiltIn)); |
| 3727 | |
| 3728 | // Force the variable to have the proper name. |
| 3729 | string var_name = builtin_to_glsl(builtin, StorageClassFunction); |
| 3730 | set_name(var.self, var_name); |
| 3731 | |
| 3732 | // We need to declare the variable early and at entry-point scope. |
| 3733 | entry_func.add_local_variable(var.self); |
| 3734 | vars_needing_early_declaration.push_back(var.self); |
| 3735 | bool triangles = is_tessellating_triangles(); |
| 3736 | |
| 3737 | if (builtin == BuiltInTessLevelOuter) |
| 3738 | { |
| 3739 | entry_func.fixup_hooks_in.push_back( |
| 3740 | [=]() |
| 3741 | { |
| 3742 | statement(var_name, "[0] = ", base_ref, ".", mbr_name, "[0];"); |
| 3743 | statement(var_name, "[1] = ", base_ref, ".", mbr_name, "[1];"); |
| 3744 | statement(var_name, "[2] = ", base_ref, ".", mbr_name, "[2];"); |
| 3745 | if (!triangles) |
| 3746 | statement(var_name, "[3] = ", base_ref, ".", mbr_name, "[3];"); |
| 3747 | }); |
| 3748 | } |
| 3749 | else |
| 3750 | { |
| 3751 | entry_func.fixup_hooks_in.push_back([=]() { |
| 3752 | if (triangles) |
| 3753 | { |
| 3754 | if (msl_options.raw_buffer_tese_input) |
| 3755 | statement(var_name, "[0] = ", base_ref, ".", mbr_name, ";"); |
| 3756 | else |
| 3757 | statement(var_name, "[0] = ", base_ref, ".", mbr_name, "[3];"); |
| 3758 | } |
| 3759 | else |
| 3760 | { |
| 3761 | statement(var_name, "[0] = ", base_ref, ".", mbr_name, "[0];"); |
| 3762 | statement(var_name, "[1] = ", base_ref, ".", mbr_name, "[1];"); |
| 3763 | } |
| 3764 | }); |
| 3765 | } |
| 3766 | } |
| 3767 | |
| 3768 | bool CompilerMSL::variable_storage_requires_stage_io(spv::StorageClass storage) const |
| 3769 | { |
| 3770 | if (storage == StorageClassOutput) |
| 3771 | return !capture_output_to_buffer; |
| 3772 | else if (storage == StorageClassInput) |
| 3773 | return !(is_tesc_shader() && msl_options.multi_patch_workgroup) && |
| 3774 | !(is_tese_shader() && msl_options.raw_buffer_tese_input); |
| 3775 | else |
| 3776 | return false; |
| 3777 | } |
| 3778 | |
| 3779 | string CompilerMSL::to_tesc_invocation_id() |
| 3780 | { |
| 3781 | if (msl_options.multi_patch_workgroup) |
| 3782 | { |
| 3783 | // n.b. builtin_invocation_id_id here is the dispatch global invocation ID, |
| 3784 | // not the TC invocation ID. |
| 3785 | return join(to_expression(builtin_invocation_id_id), ".x % ", get_entry_point().output_vertices); |
| 3786 | } |
| 3787 | else |
| 3788 | return builtin_to_glsl(BuiltInInvocationId, StorageClassInput); |
| 3789 | } |
| 3790 | |
| 3791 | void CompilerMSL::emit_local_masked_variable(const SPIRVariable &masked_var, bool strip_array) |
| 3792 | { |
| 3793 | auto &entry_func = get<SPIRFunction>(ir.default_entry_point); |
| 3794 | bool threadgroup_storage = variable_decl_is_remapped_storage(masked_var, StorageClassWorkgroup); |
| 3795 | |
| 3796 | if (threadgroup_storage && msl_options.multi_patch_workgroup) |
| 3797 | { |
| 3798 | // We need one threadgroup block per patch, so fake this. |
| 3799 | entry_func.fixup_hooks_in.push_back([this, &masked_var]() { |
| 3800 | auto &type = get_variable_data_type(masked_var); |
| 3801 | add_local_variable_name(masked_var.self); |
| 3802 | |
| 3803 | const uint32_t max_control_points_per_patch = 32u; |
| 3804 | uint32_t max_num_instances = |
| 3805 | (max_control_points_per_patch + get_entry_point().output_vertices - 1u) / |
| 3806 | get_entry_point().output_vertices; |
| 3807 | statement("threadgroup ", type_to_glsl(type), " ", |
| 3808 | "spvStorage", to_name(masked_var.self), "[", max_num_instances, "]", |
| 3809 | type_to_array_glsl(type, 0), ";"); |
| 3810 | |
| 3811 | // Assign a threadgroup slice to each PrimitiveID. |
| 3812 | // We assume here that workgroup size is rounded to 32, |
| 3813 | // since that's the maximum number of control points per patch. |
| 3814 | // We cannot size the array based on fixed dispatch parameters, |
| 3815 | // since Metal does not allow that. :( |
| 3816 | // FIXME: We will likely need an option to support passing down target workgroup size, |
| 3817 | // so we can emit appropriate size here. |
| 3818 | statement("threadgroup auto ", |
| 3819 | "&", to_name(masked_var.self), |
| 3820 | " = spvStorage", to_name(masked_var.self), "[", |
| 3821 | "(", to_expression(builtin_invocation_id_id), ".x / ", |
| 3822 | get_entry_point().output_vertices, ") % ", |
| 3823 | max_num_instances, "];"); |
| 3824 | }); |
| 3825 | } |
| 3826 | else |
| 3827 | { |
| 3828 | entry_func.add_local_variable(masked_var.self); |
| 3829 | } |
| 3830 | |
| 3831 | if (!threadgroup_storage) |
| 3832 | { |
| 3833 | vars_needing_early_declaration.push_back(masked_var.self); |
| 3834 | } |
| 3835 | else if (masked_var.initializer) |
| 3836 | { |
| 3837 | // Cannot directly initialize threadgroup variables. Need fixup hooks. |
| 3838 | ID initializer = masked_var.initializer; |
| 3839 | if (strip_array) |
| 3840 | { |
| 3841 | entry_func.fixup_hooks_in.push_back([this, &masked_var, initializer]() { |
| 3842 | auto invocation = to_tesc_invocation_id(); |
| 3843 | statement(to_expression(masked_var.self), "[", |
| 3844 | invocation, "] = ", |
| 3845 | to_expression(initializer), "[", |
| 3846 | invocation, "];"); |
| 3847 | }); |
| 3848 | } |
| 3849 | else |
| 3850 | { |
| 3851 | entry_func.fixup_hooks_in.push_back([this, &masked_var, initializer]() { |
| 3852 | statement(to_expression(masked_var.self), " = ", to_expression(initializer), ";"); |
| 3853 | }); |
| 3854 | } |
| 3855 | } |
| 3856 | } |
| 3857 | |
| 3858 | void CompilerMSL::add_variable_to_interface_block(StorageClass storage, const string &ib_var_ref, SPIRType &ib_type, |
| 3859 | SPIRVariable &var, InterfaceBlockMeta &meta) |
| 3860 | { |
| 3861 | auto &entry_func = get<SPIRFunction>(ir.default_entry_point); |
| 3862 | // Tessellation control I/O variables and tessellation evaluation per-point inputs are |
| 3863 | // usually declared as arrays. In these cases, we want to add the element type to the |
| 3864 | // interface block, since in Metal it's the interface block itself which is arrayed. |
| 3865 | auto &var_type = meta.strip_array ? get_variable_element_type(var) : get_variable_data_type(var); |
| 3866 | bool is_builtin = is_builtin_variable(var); |
| 3867 | auto builtin = BuiltIn(get_decoration(var.self, DecorationBuiltIn)); |
| 3868 | bool is_block = has_decoration(var_type.self, DecorationBlock); |
| 3869 | |
| 3870 | // If stage variables are masked out, emit them as plain variables instead. |
| 3871 | // For builtins, we query them one by one later. |
| 3872 | // IO blocks are not masked here, we need to mask them per-member instead. |
| 3873 | if (storage == StorageClassOutput && is_stage_output_variable_masked(var)) |
| 3874 | { |
| 3875 | // If we ignore an output, we must still emit it, since it might be used by app. |
| 3876 | // Instead, just emit it as early declaration. |
| 3877 | emit_local_masked_variable(var, meta.strip_array); |
| 3878 | return; |
| 3879 | } |
| 3880 | |
| 3881 | // Tesselation stages pass I/O via buffer content which may contain nested structs. |
| 3882 | // Ensure the vector sizes of any nested struct members within these input variables match |
| 3883 | // the vector sizes of the corresponding output variables from the previous pipeline stage. |
| 3884 | // This adjustment is handled here instead of ensure_correct_input_type() in order to |
| 3885 | // perform the necessary recursive processing. |
| 3886 | if (storage == StorageClassInput && var_type.basetype == SPIRType::Struct && |
| 3887 | ((is_tesc_shader() && msl_options.multi_patch_workgroup) || |
| 3888 | (is_tese_shader() && msl_options.raw_buffer_tese_input)) && |
| 3889 | has_decoration(var.self, DecorationLocation)) |
| 3890 | { |
| 3891 | uint32_t locn = get_decoration(var.self, DecorationLocation); |
| 3892 | ensure_struct_members_valid_vecsizes(get_variable_data_type(var), locn); |
| 3893 | } |
| 3894 | |
| 3895 | if (storage == StorageClassInput && has_decoration(var.self, DecorationPerVertexKHR)) |
| 3896 | SPIRV_CROSS_THROW("PerVertexKHR decoration is not supported in MSL."); |
| 3897 | |
| 3898 | // If variable names alias, they will end up with wrong names in the interface struct, because |
| 3899 | // there might be aliases in the member name cache and there would be a mismatch in fixup_in code. |
| 3900 | // Make sure to register the variables as unique resource names ahead of time. |
| 3901 | // This would normally conflict with the name cache when emitting local variables, |
| 3902 | // but this happens in the setup stage, before we hit compilation loops. |
| 3903 | // The name cache is cleared before we actually emit code, so this is safe. |
| 3904 | add_resource_name(var.self); |
| 3905 | |
| 3906 | if (var_type.basetype == SPIRType::Struct) |
| 3907 | { |
| 3908 | bool block_requires_flattening = |
| 3909 | variable_storage_requires_stage_io(storage) || (is_block && var_type.array.empty()); |
| 3910 | bool needs_local_declaration = !is_builtin && block_requires_flattening && meta.allow_local_declaration; |
| 3911 | |
| 3912 | if (needs_local_declaration) |
| 3913 | { |
| 3914 | // For I/O blocks or structs, we will need to pass the block itself around |
| 3915 | // to functions if they are used globally in leaf functions. |
| 3916 | // Rather than passing down member by member, |
| 3917 | // we unflatten I/O blocks while running the shader, |
| 3918 | // and pass the actual struct type down to leaf functions. |
| 3919 | // We then unflatten inputs, and flatten outputs in the "fixup" stages. |
| 3920 | emit_local_masked_variable(var, meta.strip_array); |
| 3921 | } |
| 3922 | |
| 3923 | if (!block_requires_flattening) |
| 3924 | { |
| 3925 | // In Metal tessellation shaders, the interface block itself is arrayed. This makes things |
| 3926 | // very complicated, since stage-in structures in MSL don't support nested structures. |
| 3927 | // Luckily, for stage-out when capturing output, we can avoid this and just add |
| 3928 | // composite members directly, because the stage-out structure is stored to a buffer, |
| 3929 | // not returned. |
| 3930 | add_plain_variable_to_interface_block(storage, ib_var_ref, ib_type, var, meta); |
| 3931 | } |
| 3932 | else |
| 3933 | { |
| 3934 | bool masked_block = false; |
| 3935 | uint32_t location = UINT32_MAX; |
| 3936 | uint32_t var_mbr_idx = 0; |
| 3937 | uint32_t elem_cnt = 1; |
| 3938 | if (is_matrix(var_type)) |
| 3939 | { |
| 3940 | if (is_array(var_type)) |
| 3941 | SPIRV_CROSS_THROW("MSL cannot emit arrays-of-matrices in input and output variables."); |
| 3942 | |
| 3943 | elem_cnt = var_type.columns; |
| 3944 | } |
| 3945 | else if (is_array(var_type)) |
| 3946 | { |
| 3947 | if (var_type.array.size() != 1) |
| 3948 | SPIRV_CROSS_THROW("MSL cannot emit arrays-of-arrays in input and output variables."); |
| 3949 | |
| 3950 | elem_cnt = to_array_size_literal(var_type); |
| 3951 | } |
| 3952 | |
| 3953 | for (uint32_t elem_idx = 0; elem_idx < elem_cnt; elem_idx++) |
| 3954 | { |
| 3955 | // Flatten the struct members into the interface struct |
| 3956 | for (uint32_t mbr_idx = 0; mbr_idx < uint32_t(var_type.member_types.size()); mbr_idx++) |
| 3957 | { |
| 3958 | builtin = BuiltInMax; |
| 3959 | is_builtin = is_member_builtin(var_type, mbr_idx, &builtin); |
| 3960 | auto &mbr_type = get<SPIRType>(var_type.member_types[mbr_idx]); |
| 3961 | |
| 3962 | if (storage == StorageClassOutput && is_stage_output_block_member_masked(var, mbr_idx, meta.strip_array)) |
| 3963 | { |
| 3964 | location = UINT32_MAX; // Skip this member and resolve location again on next var member |
| 3965 | |
| 3966 | if (is_block) |
| 3967 | masked_block = true; |
| 3968 | |
| 3969 | // Non-builtin block output variables are just ignored, since they will still access |
| 3970 | // the block variable as-is. They're just not flattened. |
| 3971 | if (is_builtin && !meta.strip_array) |
| 3972 | { |
| 3973 | // Emit a fake variable instead. |
| 3974 | uint32_t ids = ir.increase_bound_by(2); |
| 3975 | uint32_t ptr_type_id = ids + 0; |
| 3976 | uint32_t var_id = ids + 1; |
| 3977 | |
| 3978 | auto ptr_type = mbr_type; |
| 3979 | ptr_type.pointer = true; |
| 3980 | ptr_type.pointer_depth++; |
| 3981 | ptr_type.parent_type = var_type.member_types[mbr_idx]; |
| 3982 | ptr_type.storage = StorageClassOutput; |
| 3983 | |
| 3984 | uint32_t initializer = 0; |
| 3985 | if (var.initializer) |
| 3986 | if (auto *c = maybe_get<SPIRConstant>(var.initializer)) |
| 3987 | initializer = c->subconstants[mbr_idx]; |
| 3988 | |
| 3989 | set<SPIRType>(ptr_type_id, ptr_type); |
| 3990 | set<SPIRVariable>(var_id, ptr_type_id, StorageClassOutput, initializer); |
| 3991 | entry_func.add_local_variable(var_id); |
| 3992 | vars_needing_early_declaration.push_back(var_id); |
| 3993 | set_name(var_id, builtin_to_glsl(builtin, StorageClassOutput)); |
| 3994 | set_decoration(var_id, DecorationBuiltIn, builtin); |
| 3995 | } |
| 3996 | } |
| 3997 | else if (!is_builtin || has_active_builtin(builtin, storage)) |
| 3998 | { |
| 3999 | bool is_composite_type = is_matrix(mbr_type) || is_array(mbr_type) || mbr_type.basetype == SPIRType::Struct; |
| 4000 | bool attribute_load_store = |
| 4001 | storage == StorageClassInput && get_execution_model() != ExecutionModelFragment; |
| 4002 | bool storage_is_stage_io = variable_storage_requires_stage_io(storage); |
| 4003 | |
| 4004 | // Clip/CullDistance always need to be declared as user attributes. |
| 4005 | if (builtin == BuiltInClipDistance || builtin == BuiltInCullDistance) |
| 4006 | is_builtin = false; |
| 4007 | |
| 4008 | const string var_name = to_name(var.self); |
| 4009 | string mbr_name_qual = var_name; |
| 4010 | string var_chain_qual = var_name; |
| 4011 | if (elem_cnt > 1) |
| 4012 | { |
| 4013 | mbr_name_qual += join("_", elem_idx); |
| 4014 | var_chain_qual += join("[", elem_idx, "]"); |
| 4015 | } |
| 4016 | |
| 4017 | if ((!is_builtin || attribute_load_store) && storage_is_stage_io && is_composite_type) |
| 4018 | { |
| 4019 | add_composite_member_variable_to_interface_block(storage, ib_var_ref, ib_type, |
| 4020 | var, var_type, mbr_idx, meta, |
| 4021 | mbr_name_qual, var_chain_qual, |
| 4022 | location, var_mbr_idx, {}); |
| 4023 | } |
| 4024 | else |
| 4025 | { |
| 4026 | add_plain_member_variable_to_interface_block(storage, ib_var_ref, ib_type, |
| 4027 | var, var_type, mbr_idx, meta, |
| 4028 | mbr_name_qual, var_chain_qual, |
| 4029 | location, var_mbr_idx); |
| 4030 | } |
| 4031 | } |
| 4032 | var_mbr_idx++; |
| 4033 | } |
| 4034 | } |
| 4035 | |
| 4036 | // If we're redirecting a block, we might still need to access the original block |
| 4037 | // variable if we're masking some members. |
| 4038 | if (masked_block && !needs_local_declaration && (!is_builtin_variable(var) || is_tesc_shader())) |
| 4039 | { |
| 4040 | if (is_builtin_variable(var)) |
| 4041 | { |
| 4042 | // Ensure correct names for the block members if we're actually going to |
| 4043 | // declare gl_PerVertex. |
| 4044 | for (uint32_t mbr_idx = 0; mbr_idx < uint32_t(var_type.member_types.size()); mbr_idx++) |
| 4045 | { |
| 4046 | set_member_name(var_type.self, mbr_idx, builtin_to_glsl( |
| 4047 | BuiltIn(get_member_decoration(var_type.self, mbr_idx, DecorationBuiltIn)), |
| 4048 | StorageClassOutput)); |
| 4049 | } |
| 4050 | |
| 4051 | set_name(var_type.self, "gl_PerVertex"); |
| 4052 | set_name(var.self, "gl_out_masked"); |
| 4053 | stage_out_masked_builtin_type_id = var_type.self; |
| 4054 | } |
| 4055 | emit_local_masked_variable(var, meta.strip_array); |
| 4056 | } |
| 4057 | } |
| 4058 | } |
| 4059 | else if (is_tese_shader() && storage == StorageClassInput && !meta.strip_array && is_builtin && |
| 4060 | (builtin == BuiltInTessLevelOuter || builtin == BuiltInTessLevelInner)) |
| 4061 | { |
| 4062 | add_tess_level_input_to_interface_block(ib_var_ref, ib_type, var); |
| 4063 | } |
| 4064 | else if (var_type.basetype == SPIRType::Boolean || var_type.basetype == SPIRType::Char || |
| 4065 | type_is_integral(var_type) || type_is_floating_point(var_type)) |
| 4066 | { |
| 4067 | if (!is_builtin || has_active_builtin(builtin, storage)) |
| 4068 | { |
| 4069 | bool is_composite_type = is_matrix(var_type) || is_array(var_type); |
| 4070 | bool storage_is_stage_io = variable_storage_requires_stage_io(storage); |
| 4071 | bool attribute_load_store = storage == StorageClassInput && get_execution_model() != ExecutionModelFragment; |
| 4072 | |
| 4073 | // Clip/CullDistance always needs to be declared as user attributes. |
| 4074 | if (builtin == BuiltInClipDistance || builtin == BuiltInCullDistance) |
| 4075 | is_builtin = false; |
| 4076 | |
| 4077 | // MSL does not allow matrices or arrays in input or output variables, so need to handle it specially. |
| 4078 | if ((!is_builtin || attribute_load_store) && storage_is_stage_io && is_composite_type) |
| 4079 | { |
| 4080 | add_composite_variable_to_interface_block(storage, ib_var_ref, ib_type, var, meta); |
| 4081 | } |
| 4082 | else |
| 4083 | { |
| 4084 | add_plain_variable_to_interface_block(storage, ib_var_ref, ib_type, var, meta); |
| 4085 | } |
| 4086 | } |
| 4087 | } |
| 4088 | } |
| 4089 | |
| 4090 | // Recursively iterate into the input struct type, and adjust the vecsize |
| 4091 | // of any nested members, based on location info provided through the API. |
| 4092 | // The location parameter is modified recursively. |
| 4093 | void CompilerMSL::ensure_struct_members_valid_vecsizes(SPIRType &struct_type, uint32_t &location) |
| 4094 | { |
| 4095 | assert(struct_type.basetype == SPIRType::Struct); |
| 4096 | |
| 4097 | auto mbr_cnt = struct_type.member_types.size(); |
| 4098 | for (size_t mbr_idx = 0; mbr_idx < mbr_cnt; mbr_idx++) |
| 4099 | { |
| 4100 | auto mbr_type_id = struct_type.member_types[mbr_idx]; |
| 4101 | auto &mbr_type = get<SPIRType>(mbr_type_id); |
| 4102 | |
| 4103 | if (mbr_type.basetype == SPIRType::Struct) |
| 4104 | ensure_struct_members_valid_vecsizes(mbr_type, location); |
| 4105 | else |
| 4106 | { |
| 4107 | auto p_va = inputs_by_location.find({location, 0}); |
| 4108 | if (p_va != end(inputs_by_location) && p_va->second.vecsize > mbr_type.vecsize) |
| 4109 | { |
| 4110 | // Set a new member type into the struct type, and all its parent types. |
| 4111 | auto new_mbr_type_id = build_extended_vector_type(mbr_type_id, p_va->second.vecsize); |
| 4112 | for (auto *p_type = &struct_type; p_type; p_type = maybe_get<SPIRType>(p_type->parent_type)) |
| 4113 | p_type->member_types[mbr_idx] = new_mbr_type_id; |
| 4114 | } |
| 4115 | |
| 4116 | // Calc location of next member |
| 4117 | uint32_t loc_cnt = mbr_type.columns; |
| 4118 | auto dim_cnt = mbr_type.array.size(); |
| 4119 | for (uint32_t i = 0; i < dim_cnt; i++) |
| 4120 | loc_cnt *= to_array_size_literal(mbr_type, i); |
| 4121 | |
| 4122 | location += loc_cnt; |
| 4123 | } |
| 4124 | } |
| 4125 | } |
| 4126 | |
| 4127 | // Fix up the mapping of variables to interface member indices, which is used to compile access chains |
| 4128 | // for per-vertex variables in a tessellation control shader. |
| 4129 | void CompilerMSL::fix_up_interface_member_indices(StorageClass storage, uint32_t ib_type_id) |
| 4130 | { |
| 4131 | // Only needed for tessellation shaders and pull-model interpolants. |
| 4132 | // Need to redirect interface indices back to variables themselves. |
| 4133 | // For structs, each member of the struct need a separate instance. |
| 4134 | if (!is_tesc_shader() && !(is_tese_shader() && storage == StorageClassInput) && |
| 4135 | !(get_execution_model() == ExecutionModelFragment && storage == StorageClassInput && |
| 4136 | !pull_model_inputs.empty())) |
| 4137 | return; |
| 4138 | |
| 4139 | auto mbr_cnt = uint32_t(ir.meta[ib_type_id].members.size()); |
| 4140 | for (uint32_t i = 0; i < mbr_cnt; i++) |
| 4141 | { |
| 4142 | uint32_t var_id = get_extended_member_decoration(ib_type_id, i, SPIRVCrossDecorationInterfaceOrigID); |
| 4143 | if (!var_id) |
| 4144 | continue; |
| 4145 | auto &var = get<SPIRVariable>(var_id); |
| 4146 | |
| 4147 | auto &type = get_variable_element_type(var); |
| 4148 | |
| 4149 | bool flatten_composites = variable_storage_requires_stage_io(var.storage); |
| 4150 | bool is_block = has_decoration(type.self, DecorationBlock); |
| 4151 | |
| 4152 | uint32_t mbr_idx = uint32_t(-1); |
| 4153 | if (type.basetype == SPIRType::Struct && (flatten_composites || is_block)) |
| 4154 | mbr_idx = get_extended_member_decoration(ib_type_id, i, SPIRVCrossDecorationInterfaceMemberIndex); |
| 4155 | |
| 4156 | if (mbr_idx != uint32_t(-1)) |
| 4157 | { |
| 4158 | // Only set the lowest InterfaceMemberIndex for each variable member. |
| 4159 | // IB struct members will be emitted in-order w.r.t. interface member index. |
| 4160 | if (!has_extended_member_decoration(var_id, mbr_idx, SPIRVCrossDecorationInterfaceMemberIndex)) |
| 4161 | set_extended_member_decoration(var_id, mbr_idx, SPIRVCrossDecorationInterfaceMemberIndex, i); |
| 4162 | } |
| 4163 | else |
| 4164 | { |
| 4165 | // Only set the lowest InterfaceMemberIndex for each variable. |
| 4166 | // IB struct members will be emitted in-order w.r.t. interface member index. |
| 4167 | if (!has_extended_decoration(var_id, SPIRVCrossDecorationInterfaceMemberIndex)) |
| 4168 | set_extended_decoration(var_id, SPIRVCrossDecorationInterfaceMemberIndex, i); |
| 4169 | } |
| 4170 | } |
| 4171 | } |
| 4172 | |
| 4173 | // Add an interface structure for the type of storage, which is either StorageClassInput or StorageClassOutput. |
| 4174 | // Returns the ID of the newly added variable, or zero if no variable was added. |
| 4175 | uint32_t CompilerMSL::add_interface_block(StorageClass storage, bool patch) |
| 4176 | { |
| 4177 | // Accumulate the variables that should appear in the interface struct. |
| 4178 | SmallVector<SPIRVariable *> vars; |
| 4179 | bool incl_builtins = storage == StorageClassOutput || is_tessellation_shader(); |
| 4180 | bool has_seen_barycentric = false; |
| 4181 | |
| 4182 | InterfaceBlockMeta meta; |
| 4183 | |
| 4184 | // Varying interfaces between stages which use "user()" attribute can be dealt with |
| 4185 | // without explicit packing and unpacking of components. For any variables which link against the runtime |
| 4186 | // in some way (vertex attributes, fragment output, etc), we'll need to deal with it somehow. |
| 4187 | bool pack_components = |
| 4188 | (storage == StorageClassInput && get_execution_model() == ExecutionModelVertex) || |
| 4189 | (storage == StorageClassOutput && get_execution_model() == ExecutionModelFragment) || |
| 4190 | (storage == StorageClassOutput && get_execution_model() == ExecutionModelVertex && capture_output_to_buffer); |
| 4191 | |
| 4192 | ir.for_each_typed_id<SPIRVariable>([&](uint32_t var_id, SPIRVariable &var) { |
| 4193 | if (var.storage != storage) |
| 4194 | return; |
| 4195 | |
| 4196 | auto &type = this->get<SPIRType>(var.basetype); |
| 4197 | |
| 4198 | bool is_builtin = is_builtin_variable(var); |
| 4199 | bool is_block = has_decoration(type.self, DecorationBlock); |
| 4200 | |
| 4201 | auto bi_type = BuiltInMax; |
| 4202 | bool builtin_is_gl_in_out = false; |
| 4203 | if (is_builtin && !is_block) |
| 4204 | { |
| 4205 | bi_type = BuiltIn(get_decoration(var_id, DecorationBuiltIn)); |
| 4206 | builtin_is_gl_in_out = bi_type == BuiltInPosition || bi_type == BuiltInPointSize || |
| 4207 | bi_type == BuiltInClipDistance || bi_type == BuiltInCullDistance; |
| 4208 | } |
| 4209 | |
| 4210 | if (is_builtin && is_block) |
| 4211 | builtin_is_gl_in_out = true; |
| 4212 | |
| 4213 | uint32_t location = get_decoration(var_id, DecorationLocation); |
| 4214 | |
| 4215 | bool builtin_is_stage_in_out = builtin_is_gl_in_out || |
| 4216 | bi_type == BuiltInLayer || bi_type == BuiltInViewportIndex || |
| 4217 | bi_type == BuiltInBaryCoordKHR || bi_type == BuiltInBaryCoordNoPerspKHR || |
| 4218 | bi_type == BuiltInFragDepth || |
| 4219 | bi_type == BuiltInFragStencilRefEXT || bi_type == BuiltInSampleMask; |
| 4220 | |
| 4221 | // These builtins are part of the stage in/out structs. |
| 4222 | bool is_interface_block_builtin = |
| 4223 | builtin_is_stage_in_out || (is_tese_shader() && !msl_options.raw_buffer_tese_input && |
| 4224 | (bi_type == BuiltInTessLevelOuter || bi_type == BuiltInTessLevelInner)); |
| 4225 | |
| 4226 | bool is_active = interface_variable_exists_in_entry_point(var.self); |
| 4227 | if (is_builtin && is_active) |
| 4228 | { |
| 4229 | // Only emit the builtin if it's active in this entry point. Interface variable list might lie. |
| 4230 | if (is_block) |
| 4231 | { |
| 4232 | // If any builtin is active, the block is active. |
| 4233 | uint32_t mbr_cnt = uint32_t(type.member_types.size()); |
| 4234 | for (uint32_t i = 0; !is_active && i < mbr_cnt; i++) |
| 4235 | is_active = has_active_builtin(BuiltIn(get_member_decoration(type.self, i, DecorationBuiltIn)), storage); |
| 4236 | } |
| 4237 | else |
| 4238 | { |
| 4239 | is_active = has_active_builtin(bi_type, storage); |
| 4240 | } |
| 4241 | } |
| 4242 | |
| 4243 | bool filter_patch_decoration = (has_decoration(var_id, DecorationPatch) || is_patch_block(type)) == patch; |
| 4244 | |
| 4245 | bool hidden = is_hidden_variable(var, incl_builtins); |
| 4246 | |
| 4247 | // ClipDistance is never hidden, we need to emulate it when used as an input. |
| 4248 | if (bi_type == BuiltInClipDistance || bi_type == BuiltInCullDistance) |
| 4249 | hidden = false; |
| 4250 | |
| 4251 | // It's not enough to simply avoid marking fragment outputs if the pipeline won't |
| 4252 | // accept them. We can't put them in the struct at all, or otherwise the compiler |
| 4253 | // complains that the outputs weren't explicitly marked. |
| 4254 | // Frag depth and stencil outputs are incompatible with explicit early fragment tests. |
| 4255 | // In GLSL, depth and stencil outputs are just ignored when explicit early fragment tests are required. |
| 4256 | // In Metal, it's a compilation error, so we need to exclude them from the output struct. |
| 4257 | if (get_execution_model() == ExecutionModelFragment && storage == StorageClassOutput && !patch && |
| 4258 | ((is_builtin && ((bi_type == BuiltInFragDepth && (!msl_options.enable_frag_depth_builtin || uses_explicit_early_fragment_test())) || |
| 4259 | (bi_type == BuiltInFragStencilRefEXT && (!msl_options.enable_frag_stencil_ref_builtin || uses_explicit_early_fragment_test())))) || |
| 4260 | (!is_builtin && !(msl_options.enable_frag_output_mask & (1 << location))))) |
| 4261 | { |
| 4262 | hidden = true; |
| 4263 | disabled_frag_outputs.push_back(var_id); |
| 4264 | // If a builtin, force it to have the proper name, and mark it as not part of the output struct. |
| 4265 | if (is_builtin) |
| 4266 | { |
| 4267 | set_name(var_id, builtin_to_glsl(bi_type, StorageClassFunction)); |
| 4268 | mask_stage_output_by_builtin(bi_type); |
| 4269 | } |
| 4270 | } |
| 4271 | |
| 4272 | // Barycentric inputs must be emitted in stage-in, because they can have interpolation arguments. |
| 4273 | if (is_active && (bi_type == BuiltInBaryCoordKHR || bi_type == BuiltInBaryCoordNoPerspKHR)) |
| 4274 | { |
| 4275 | if (has_seen_barycentric) |
| 4276 | SPIRV_CROSS_THROW("Cannot declare both BaryCoordNV and BaryCoordNoPerspNV in same shader in MSL."); |
| 4277 | has_seen_barycentric = true; |
| 4278 | hidden = false; |
| 4279 | } |
| 4280 | |
| 4281 | if (is_active && !hidden && type.pointer && filter_patch_decoration && |
| 4282 | (!is_builtin || is_interface_block_builtin)) |
| 4283 | { |
| 4284 | vars.push_back(&var); |
| 4285 | |
| 4286 | if (!is_builtin) |
| 4287 | { |
| 4288 | // Need to deal specially with DecorationComponent. |
| 4289 | // Multiple variables can alias the same Location, and try to make sure each location is declared only once. |
| 4290 | // We will swizzle data in and out to make this work. |
| 4291 | // This is only relevant for vertex inputs and fragment outputs. |
| 4292 | // Technically tessellation as well, but it is too complicated to support. |
| 4293 | uint32_t component = get_decoration(var_id, DecorationComponent); |
| 4294 | if (component != 0) |
| 4295 | { |
| 4296 | if (is_tessellation_shader()) |
| 4297 | SPIRV_CROSS_THROW("Component decoration is not supported in tessellation shaders."); |
| 4298 | else if (pack_components) |
| 4299 | { |
| 4300 | uint32_t array_size = 1; |
| 4301 | if (!type.array.empty()) |
| 4302 | array_size = to_array_size_literal(type); |
| 4303 | |
| 4304 | for (uint32_t location_offset = 0; location_offset < array_size; location_offset++) |
| 4305 | { |
| 4306 | auto &location_meta = meta.location_meta[location + location_offset]; |
| 4307 | location_meta.num_components = max<uint32_t>(location_meta.num_components, component + type.vecsize); |
| 4308 | |
| 4309 | // For variables sharing location, decorations and base type must match. |
| 4310 | location_meta.base_type_id = type.self; |
| 4311 | location_meta.flat = has_decoration(var.self, DecorationFlat); |
| 4312 | location_meta.noperspective = has_decoration(var.self, DecorationNoPerspective); |
| 4313 | location_meta.centroid = has_decoration(var.self, DecorationCentroid); |
| 4314 | location_meta.sample = has_decoration(var.self, DecorationSample); |
| 4315 | } |
| 4316 | } |
| 4317 | } |
| 4318 | } |
| 4319 | } |
| 4320 | |
| 4321 | if (is_tese_shader() && msl_options.raw_buffer_tese_input && patch && storage == StorageClassInput && |
| 4322 | (bi_type == BuiltInTessLevelOuter || bi_type == BuiltInTessLevelInner)) |
| 4323 | { |
| 4324 | // In this case, we won't add the builtin to the interface struct, |
| 4325 | // but we still need the hook to run to populate the arrays. |
| 4326 | string base_ref = join(tess_factor_buffer_var_name, "[", to_expression(builtin_primitive_id_id), "]"); |
| 4327 | const char *mbr_name = |
| 4328 | bi_type == BuiltInTessLevelOuter ? "edgeTessellationFactor" : "insideTessellationFactor"; |
| 4329 | add_tess_level_input(base_ref, mbr_name, var); |
| 4330 | if (inputs_by_builtin.count(bi_type)) |
| 4331 | { |
| 4332 | uint32_t locn = inputs_by_builtin[bi_type].location; |
| 4333 | mark_location_as_used_by_shader(locn, type, StorageClassInput); |
| 4334 | } |
| 4335 | } |
| 4336 | }); |
| 4337 | |
| 4338 | // If no variables qualify, leave. |
| 4339 | // For patch input in a tessellation evaluation shader, the per-vertex stage inputs |
| 4340 | // are included in a special patch control point array. |
| 4341 | if (vars.empty() && |
| 4342 | !(!msl_options.raw_buffer_tese_input && storage == StorageClassInput && patch && stage_in_var_id)) |
| 4343 | return 0; |
| 4344 | |
| 4345 | // Add a new typed variable for this interface structure. |
| 4346 | // The initializer expression is allocated here, but populated when the function |
| 4347 | // declaraion is emitted, because it is cleared after each compilation pass. |
| 4348 | uint32_t next_id = ir.increase_bound_by(3); |
| 4349 | uint32_t ib_type_id = next_id++; |
| 4350 | auto &ib_type = set<SPIRType>(ib_type_id, OpTypeStruct); |
| 4351 | ib_type.basetype = SPIRType::Struct; |
| 4352 | ib_type.storage = storage; |
| 4353 | set_decoration(ib_type_id, DecorationBlock); |
| 4354 | |
| 4355 | uint32_t ib_var_id = next_id++; |
| 4356 | auto &var = set<SPIRVariable>(ib_var_id, ib_type_id, storage, 0); |
| 4357 | var.initializer = next_id++; |
| 4358 | |
| 4359 | string ib_var_ref; |
| 4360 | auto &entry_func = get<SPIRFunction>(ir.default_entry_point); |
| 4361 | switch (storage) |
| 4362 | { |
| 4363 | case StorageClassInput: |
| 4364 | ib_var_ref = patch ? patch_stage_in_var_name : stage_in_var_name; |
| 4365 | switch (get_execution_model()) |
| 4366 | { |
| 4367 | case ExecutionModelTessellationControl: |
| 4368 | // Add a hook to populate the shared workgroup memory containing the gl_in array. |
| 4369 | entry_func.fixup_hooks_in.push_back([=]() { |
| 4370 | // Can't use PatchVertices, PrimitiveId, or InvocationId yet; the hooks for those may not have run yet. |
| 4371 | if (msl_options.multi_patch_workgroup) |
| 4372 | { |
| 4373 | // n.b. builtin_invocation_id_id here is the dispatch global invocation ID, |
| 4374 | // not the TC invocation ID. |
| 4375 | statement("device ", to_name(ir.default_entry_point), "_", ib_var_ref, "* gl_in = &", |
| 4376 | input_buffer_var_name, "[min(", to_expression(builtin_invocation_id_id), ".x / ", |
| 4377 | get_entry_point().output_vertices, |
| 4378 | ", spvIndirectParams[1] - 1) * spvIndirectParams[0]];"); |
| 4379 | } |
| 4380 | else |
| 4381 | { |
| 4382 | // It's safe to use InvocationId here because it's directly mapped to a |
| 4383 | // Metal builtin, and therefore doesn't need a hook. |
| 4384 | statement("if (", to_expression(builtin_invocation_id_id), " < spvIndirectParams[0])"); |
| 4385 | statement(" ", input_wg_var_name, "[", to_expression(builtin_invocation_id_id), |
| 4386 | "] = ", ib_var_ref, ";"); |
| 4387 | statement("threadgroup_barrier(mem_flags::mem_threadgroup);"); |
| 4388 | statement("if (", to_expression(builtin_invocation_id_id), |
| 4389 | " >= ", get_entry_point().output_vertices, ")"); |
| 4390 | statement(" return;"); |
| 4391 | } |
| 4392 | }); |
| 4393 | break; |
| 4394 | case ExecutionModelTessellationEvaluation: |
| 4395 | if (!msl_options.raw_buffer_tese_input) |
| 4396 | break; |
| 4397 | if (patch) |
| 4398 | { |
| 4399 | entry_func.fixup_hooks_in.push_back( |
| 4400 | [=]() |
| 4401 | { |
| 4402 | statement("const device ", to_name(ir.default_entry_point), "_", ib_var_ref, "& ", ib_var_ref, |
| 4403 | " = ", patch_input_buffer_var_name, "[", to_expression(builtin_primitive_id_id), |
| 4404 | "];"); |
| 4405 | }); |
| 4406 | } |
| 4407 | else |
| 4408 | { |
| 4409 | entry_func.fixup_hooks_in.push_back( |
| 4410 | [=]() |
| 4411 | { |
| 4412 | statement("const device ", to_name(ir.default_entry_point), "_", ib_var_ref, "* gl_in = &", |
| 4413 | input_buffer_var_name, "[", to_expression(builtin_primitive_id_id), " * ", |
| 4414 | get_entry_point().output_vertices, "];"); |
| 4415 | }); |
| 4416 | } |
| 4417 | break; |
| 4418 | default: |
| 4419 | break; |
| 4420 | } |
| 4421 | break; |
| 4422 | |
| 4423 | case StorageClassOutput: |
| 4424 | { |
| 4425 | ib_var_ref = patch ? patch_stage_out_var_name : stage_out_var_name; |
| 4426 | |
| 4427 | // Add the output interface struct as a local variable to the entry function. |
| 4428 | // If the entry point should return the output struct, set the entry function |
| 4429 | // to return the output interface struct, otherwise to return nothing. |
| 4430 | // Watch out for the rare case where the terminator of the last entry point block is a |
| 4431 | // Kill or Unreachable, instead of a Return. Based on SPIR-V's block-domination rules, |
| 4432 | // we assume that any block that has a Kill will also have a terminating Return, except |
| 4433 | // the last block. |
| 4434 | // Indicate the output var requires early initialization. |
| 4435 | bool ep_should_return_output = !get_is_rasterization_disabled(); |
| 4436 | uint32_t rtn_id = ep_should_return_output ? ib_var_id : 0; |
| 4437 | if (!capture_output_to_buffer) |
| 4438 | { |
| 4439 | entry_func.add_local_variable(ib_var_id); |
| 4440 | for (auto &blk_id : entry_func.blocks) |
| 4441 | { |
| 4442 | auto &blk = get<SPIRBlock>(blk_id); |
| 4443 | auto last_blk_return = blk.terminator == SPIRBlock::Kill || blk.terminator == SPIRBlock::Unreachable; |
| 4444 | if (blk.terminator == SPIRBlock::Return || (last_blk_return && blk_id == entry_func.blocks.back())) |
| 4445 | blk.return_value = rtn_id; |
| 4446 | } |
| 4447 | vars_needing_early_declaration.push_back(ib_var_id); |
| 4448 | } |
| 4449 | else |
| 4450 | { |
| 4451 | switch (get_execution_model()) |
| 4452 | { |
| 4453 | case ExecutionModelVertex: |
| 4454 | case ExecutionModelTessellationEvaluation: |
| 4455 | // Instead of declaring a struct variable to hold the output and then |
| 4456 | // copying that to the output buffer, we'll declare the output variable |
| 4457 | // as a reference to the final output element in the buffer. Then we can |
| 4458 | // avoid the extra copy. |
| 4459 | entry_func.fixup_hooks_in.push_back([=]() { |
| 4460 | if (stage_out_var_id) |
| 4461 | { |
| 4462 | // The first member of the indirect buffer is always the number of vertices |
| 4463 | // to draw. |
| 4464 | // We zero-base the InstanceID & VertexID variables for HLSL emulation elsewhere, so don't do it twice |
| 4465 | if (get_execution_model() == ExecutionModelVertex && msl_options.vertex_for_tessellation) |
| 4466 | { |
| 4467 | statement("device ", to_name(ir.default_entry_point), "_", ib_var_ref, "& ", ib_var_ref, |
| 4468 | " = ", output_buffer_var_name, "[", to_expression(builtin_invocation_id_id), |
| 4469 | ".y * ", to_expression(builtin_stage_input_size_id), ".x + ", |
| 4470 | to_expression(builtin_invocation_id_id), ".x];"); |
| 4471 | } |
| 4472 | else if (msl_options.enable_base_index_zero) |
| 4473 | { |
| 4474 | statement("device ", to_name(ir.default_entry_point), "_", ib_var_ref, "& ", ib_var_ref, |
| 4475 | " = ", output_buffer_var_name, "[", to_expression(builtin_instance_idx_id), |
| 4476 | " * spvIndirectParams[0] + ", to_expression(builtin_vertex_idx_id), "];"); |
| 4477 | } |
| 4478 | else |
| 4479 | { |
| 4480 | statement("device ", to_name(ir.default_entry_point), "_", ib_var_ref, "& ", ib_var_ref, |
| 4481 | " = ", output_buffer_var_name, "[(", to_expression(builtin_instance_idx_id), |
| 4482 | " - ", to_expression(builtin_base_instance_id), ") * spvIndirectParams[0] + ", |
| 4483 | to_expression(builtin_vertex_idx_id), " - ", |
| 4484 | to_expression(builtin_base_vertex_id), "];"); |
| 4485 | } |
| 4486 | } |
| 4487 | }); |
| 4488 | break; |
| 4489 | case ExecutionModelTessellationControl: |
| 4490 | if (msl_options.multi_patch_workgroup) |
| 4491 | { |
| 4492 | // We cannot use PrimitiveId here, because the hook may not have run yet. |
| 4493 | if (patch) |
| 4494 | { |
| 4495 | entry_func.fixup_hooks_in.push_back([=]() { |
| 4496 | statement("device ", to_name(ir.default_entry_point), "_", ib_var_ref, "& ", ib_var_ref, |
| 4497 | " = ", patch_output_buffer_var_name, "[", to_expression(builtin_invocation_id_id), |
| 4498 | ".x / ", get_entry_point().output_vertices, "];"); |
| 4499 | }); |
| 4500 | } |
| 4501 | else |
| 4502 | { |
| 4503 | entry_func.fixup_hooks_in.push_back([=]() { |
| 4504 | statement("device ", to_name(ir.default_entry_point), "_", ib_var_ref, "* gl_out = &", |
| 4505 | output_buffer_var_name, "[", to_expression(builtin_invocation_id_id), ".x - ", |
| 4506 | to_expression(builtin_invocation_id_id), ".x % ", |
| 4507 | get_entry_point().output_vertices, "];"); |
| 4508 | }); |
| 4509 | } |
| 4510 | } |
| 4511 | else |
| 4512 | { |
| 4513 | if (patch) |
| 4514 | { |
| 4515 | entry_func.fixup_hooks_in.push_back([=]() { |
| 4516 | statement("device ", to_name(ir.default_entry_point), "_", ib_var_ref, "& ", ib_var_ref, |
| 4517 | " = ", patch_output_buffer_var_name, "[", to_expression(builtin_primitive_id_id), |
| 4518 | "];"); |
| 4519 | }); |
| 4520 | } |
| 4521 | else |
| 4522 | { |
| 4523 | entry_func.fixup_hooks_in.push_back([=]() { |
| 4524 | statement("device ", to_name(ir.default_entry_point), "_", ib_var_ref, "* gl_out = &", |
| 4525 | output_buffer_var_name, "[", to_expression(builtin_primitive_id_id), " * ", |
| 4526 | get_entry_point().output_vertices, "];"); |
| 4527 | }); |
| 4528 | } |
| 4529 | } |
| 4530 | break; |
| 4531 | default: |
| 4532 | break; |
| 4533 | } |
| 4534 | } |
| 4535 | break; |
| 4536 | } |
| 4537 | |
| 4538 | default: |
| 4539 | break; |
| 4540 | } |
| 4541 | |
| 4542 | set_name(ib_type_id, to_name(ir.default_entry_point) + "_" + ib_var_ref); |
| 4543 | set_name(ib_var_id, ib_var_ref); |
| 4544 | |
| 4545 | for (auto *p_var : vars) |
| 4546 | { |
| 4547 | bool strip_array = (is_tesc_shader() || (is_tese_shader() && storage == StorageClassInput)) && !patch; |
| 4548 | |
| 4549 | // Fixing up flattened stores in TESC is impossible since the memory is group shared either via |
| 4550 | // device (not masked) or threadgroup (masked) storage classes and it's race condition city. |
| 4551 | meta.strip_array = strip_array; |
| 4552 | meta.allow_local_declaration = !strip_array && !(is_tesc_shader() && storage == StorageClassOutput); |
| 4553 | add_variable_to_interface_block(storage, ib_var_ref, ib_type, *p_var, meta); |
| 4554 | } |
| 4555 | |
| 4556 | if (((is_tesc_shader() && msl_options.multi_patch_workgroup) || |
| 4557 | (is_tese_shader() && msl_options.raw_buffer_tese_input)) && |
| 4558 | storage == StorageClassInput) |
| 4559 | { |
| 4560 | // For tessellation inputs, add all outputs from the previous stage to ensure |
| 4561 | // the struct containing them is the correct size and layout. |
| 4562 | for (auto &input : inputs_by_location) |
| 4563 | { |
| 4564 | if (location_inputs_in_use.count(input.first.location) != 0) |
| 4565 | continue; |
| 4566 | |
| 4567 | if (patch != (input.second.rate == MSL_SHADER_VARIABLE_RATE_PER_PATCH)) |
| 4568 | continue; |
| 4569 | |
| 4570 | // Tessellation levels have their own struct, so there's no need to add them here. |
| 4571 | if (input.second.builtin == BuiltInTessLevelOuter || input.second.builtin == BuiltInTessLevelInner) |
| 4572 | continue; |
| 4573 | |
| 4574 | // Create a fake variable to put at the location. |
| 4575 | uint32_t offset = ir.increase_bound_by(5); |
| 4576 | uint32_t type_id = offset; |
| 4577 | uint32_t vec_type_id = offset + 1; |
| 4578 | uint32_t array_type_id = offset + 2; |
| 4579 | uint32_t ptr_type_id = offset + 3; |
| 4580 | uint32_t var_id = offset + 4; |
| 4581 | |
| 4582 | SPIRType type { OpTypeInt }; |
| 4583 | switch (input.second.format) |
| 4584 | { |
| 4585 | case MSL_SHADER_VARIABLE_FORMAT_UINT16: |
| 4586 | case MSL_SHADER_VARIABLE_FORMAT_ANY16: |
| 4587 | type.basetype = SPIRType::UShort; |
| 4588 | type.width = 16; |
| 4589 | break; |
| 4590 | case MSL_SHADER_VARIABLE_FORMAT_ANY32: |
| 4591 | default: |
| 4592 | type.basetype = SPIRType::UInt; |
| 4593 | type.width = 32; |
| 4594 | break; |
| 4595 | } |
| 4596 | set<SPIRType>(type_id, type); |
| 4597 | if (input.second.vecsize > 1) |
| 4598 | { |
| 4599 | type.op = OpTypeVector; |
| 4600 | type.vecsize = input.second.vecsize; |
| 4601 | set<SPIRType>(vec_type_id, type); |
| 4602 | type_id = vec_type_id; |
| 4603 | } |
| 4604 | |
| 4605 | type.op = OpTypeArray; |
| 4606 | type.array.push_back(0); |
| 4607 | type.array_size_literal.push_back(true); |
| 4608 | type.parent_type = type_id; |
| 4609 | set<SPIRType>(array_type_id, type); |
| 4610 | type.self = type_id; |
| 4611 | |
| 4612 | type.op = OpTypePointer; |
| 4613 | type.pointer = true; |
| 4614 | type.pointer_depth++; |
| 4615 | type.parent_type = array_type_id; |
| 4616 | type.storage = storage; |
| 4617 | auto &ptr_type = set<SPIRType>(ptr_type_id, type); |
| 4618 | ptr_type.self = array_type_id; |
| 4619 | |
| 4620 | auto &fake_var = set<SPIRVariable>(var_id, ptr_type_id, storage); |
| 4621 | set_decoration(var_id, DecorationLocation, input.first.location); |
| 4622 | if (input.first.component) |
| 4623 | set_decoration(var_id, DecorationComponent, input.first.component); |
| 4624 | |
| 4625 | meta.strip_array = true; |
| 4626 | meta.allow_local_declaration = false; |
| 4627 | add_variable_to_interface_block(storage, ib_var_ref, ib_type, fake_var, meta); |
| 4628 | } |
| 4629 | } |
| 4630 | |
| 4631 | if (capture_output_to_buffer && storage == StorageClassOutput) |
| 4632 | { |
| 4633 | // For captured output, add all inputs from the next stage to ensure |
| 4634 | // the struct containing them is the correct size and layout. This is |
| 4635 | // necessary for certain implicit builtins that may nonetheless be read, |
| 4636 | // even when they aren't written. |
| 4637 | for (auto &output : outputs_by_location) |
| 4638 | { |
| 4639 | if (location_outputs_in_use.count(output.first.location) != 0) |
| 4640 | continue; |
| 4641 | |
| 4642 | // Create a fake variable to put at the location. |
| 4643 | uint32_t offset = ir.increase_bound_by(5); |
| 4644 | uint32_t type_id = offset; |
| 4645 | uint32_t vec_type_id = offset + 1; |
| 4646 | uint32_t array_type_id = offset + 2; |
| 4647 | uint32_t ptr_type_id = offset + 3; |
| 4648 | uint32_t var_id = offset + 4; |
| 4649 | |
| 4650 | SPIRType type { OpTypeInt }; |
| 4651 | switch (output.second.format) |
| 4652 | { |
| 4653 | case MSL_SHADER_VARIABLE_FORMAT_UINT16: |
| 4654 | case MSL_SHADER_VARIABLE_FORMAT_ANY16: |
| 4655 | type.basetype = SPIRType::UShort; |
| 4656 | type.width = 16; |
| 4657 | break; |
| 4658 | case MSL_SHADER_VARIABLE_FORMAT_ANY32: |
| 4659 | default: |
| 4660 | type.basetype = SPIRType::UInt; |
| 4661 | type.width = 32; |
| 4662 | break; |
| 4663 | } |
| 4664 | set<SPIRType>(type_id, type); |
| 4665 | if (output.second.vecsize > 1) |
| 4666 | { |
| 4667 | type.op = OpTypeVector; |
| 4668 | type.vecsize = output.second.vecsize; |
| 4669 | set<SPIRType>(vec_type_id, type); |
| 4670 | type_id = vec_type_id; |
| 4671 | } |
| 4672 | |
| 4673 | if (is_tesc_shader()) |
| 4674 | { |
| 4675 | type.op = OpTypeArray; |
| 4676 | type.array.push_back(0); |
| 4677 | type.array_size_literal.push_back(true); |
| 4678 | type.parent_type = type_id; |
| 4679 | set<SPIRType>(array_type_id, type); |
| 4680 | } |
| 4681 | |
| 4682 | type.op = OpTypePointer; |
| 4683 | type.pointer = true; |
| 4684 | type.pointer_depth++; |
| 4685 | type.parent_type = is_tesc_shader() ? array_type_id : type_id; |
| 4686 | type.storage = storage; |
| 4687 | auto &ptr_type = set<SPIRType>(ptr_type_id, type); |
| 4688 | ptr_type.self = type.parent_type; |
| 4689 | |
| 4690 | auto &fake_var = set<SPIRVariable>(var_id, ptr_type_id, storage); |
| 4691 | set_decoration(var_id, DecorationLocation, output.first.location); |
| 4692 | if (output.first.component) |
| 4693 | set_decoration(var_id, DecorationComponent, output.first.component); |
| 4694 | |
| 4695 | meta.strip_array = true; |
| 4696 | meta.allow_local_declaration = false; |
| 4697 | add_variable_to_interface_block(storage, ib_var_ref, ib_type, fake_var, meta); |
| 4698 | } |
| 4699 | } |
| 4700 | |
| 4701 | // When multiple variables need to access same location, |
| 4702 | // unroll locations one by one and we will flatten output or input as necessary. |
| 4703 | for (auto &loc : meta.location_meta) |
| 4704 | { |
| 4705 | uint32_t location = loc.first; |
| 4706 | auto &location_meta = loc.second; |
| 4707 | |
| 4708 | uint32_t ib_mbr_idx = uint32_t(ib_type.member_types.size()); |
| 4709 | uint32_t type_id = build_extended_vector_type(location_meta.base_type_id, location_meta.num_components); |
| 4710 | ib_type.member_types.push_back(type_id); |
| 4711 | |
| 4712 | set_member_name(ib_type.self, ib_mbr_idx, join("m_location_", location)); |
| 4713 | set_member_decoration(ib_type.self, ib_mbr_idx, DecorationLocation, location); |
| 4714 | mark_location_as_used_by_shader(location, get<SPIRType>(type_id), storage); |
| 4715 | |
| 4716 | if (location_meta.flat) |
| 4717 | set_member_decoration(ib_type.self, ib_mbr_idx, DecorationFlat); |
| 4718 | if (location_meta.noperspective) |
| 4719 | set_member_decoration(ib_type.self, ib_mbr_idx, DecorationNoPerspective); |
| 4720 | if (location_meta.centroid) |
| 4721 | set_member_decoration(ib_type.self, ib_mbr_idx, DecorationCentroid); |
| 4722 | if (location_meta.sample) |
| 4723 | set_member_decoration(ib_type.self, ib_mbr_idx, DecorationSample); |
| 4724 | } |
| 4725 | |
| 4726 | // Sort the members of the structure by their locations. |
| 4727 | MemberSorter member_sorter(ib_type, ir.meta[ib_type_id], MemberSorter::LocationThenBuiltInType); |
| 4728 | member_sorter.sort(); |
| 4729 | |
| 4730 | // The member indices were saved to the original variables, but after the members |
| 4731 | // were sorted, those indices are now likely incorrect. Fix those up now. |
| 4732 | fix_up_interface_member_indices(storage, ib_type_id); |
| 4733 | |
| 4734 | // For patch inputs, add one more member, holding the array of control point data. |
| 4735 | if (is_tese_shader() && !msl_options.raw_buffer_tese_input && storage == StorageClassInput && patch && |
| 4736 | stage_in_var_id) |
| 4737 | { |
| 4738 | uint32_t pcp_type_id = ir.increase_bound_by(1); |
| 4739 | auto &pcp_type = set<SPIRType>(pcp_type_id, ib_type); |
| 4740 | pcp_type.basetype = SPIRType::ControlPointArray; |
| 4741 | pcp_type.parent_type = pcp_type.type_alias = get_stage_in_struct_type().self; |
| 4742 | pcp_type.storage = storage; |
| 4743 | ir.meta[pcp_type_id] = ir.meta[ib_type.self]; |
| 4744 | uint32_t mbr_idx = uint32_t(ib_type.member_types.size()); |
| 4745 | ib_type.member_types.push_back(pcp_type_id); |
| 4746 | set_member_name(ib_type.self, mbr_idx, "gl_in"); |
| 4747 | } |
| 4748 | |
| 4749 | if (storage == StorageClassInput) |
| 4750 | set_decoration(ib_var_id, DecorationNonWritable); |
| 4751 | |
| 4752 | return ib_var_id; |
| 4753 | } |
| 4754 | |
| 4755 | uint32_t CompilerMSL::add_interface_block_pointer(uint32_t ib_var_id, StorageClass storage) |
| 4756 | { |
| 4757 | if (!ib_var_id) |
| 4758 | return 0; |
| 4759 | |
| 4760 | uint32_t ib_ptr_var_id; |
| 4761 | uint32_t next_id = ir.increase_bound_by(3); |
| 4762 | auto &ib_type = expression_type(ib_var_id); |
| 4763 | if (is_tesc_shader() || (is_tese_shader() && msl_options.raw_buffer_tese_input)) |
| 4764 | { |
| 4765 | // Tessellation control per-vertex I/O is presented as an array, so we must |
| 4766 | // do the same with our struct here. |
| 4767 | uint32_t ib_ptr_type_id = next_id++; |
| 4768 | auto &ib_ptr_type = set<SPIRType>(ib_ptr_type_id, ib_type); |
| 4769 | ib_ptr_type.op = OpTypePointer; |
| 4770 | ib_ptr_type.parent_type = ib_ptr_type.type_alias = ib_type.self; |
| 4771 | ib_ptr_type.pointer = true; |
| 4772 | ib_ptr_type.pointer_depth++; |
| 4773 | ib_ptr_type.storage = storage == StorageClassInput ? |
| 4774 | ((is_tesc_shader() && msl_options.multi_patch_workgroup) || |
| 4775 | (is_tese_shader() && msl_options.raw_buffer_tese_input) ? |
| 4776 | StorageClassStorageBuffer : |
| 4777 | StorageClassWorkgroup) : |
| 4778 | StorageClassStorageBuffer; |
| 4779 | ir.meta[ib_ptr_type_id] = ir.meta[ib_type.self]; |
| 4780 | // To ensure that get_variable_data_type() doesn't strip off the pointer, |
| 4781 | // which we need, use another pointer. |
| 4782 | uint32_t ib_ptr_ptr_type_id = next_id++; |
| 4783 | auto &ib_ptr_ptr_type = set<SPIRType>(ib_ptr_ptr_type_id, ib_ptr_type); |
| 4784 | ib_ptr_ptr_type.parent_type = ib_ptr_type_id; |
| 4785 | ib_ptr_ptr_type.type_alias = ib_type.self; |
| 4786 | ib_ptr_ptr_type.storage = StorageClassFunction; |
| 4787 | ir.meta[ib_ptr_ptr_type_id] = ir.meta[ib_type.self]; |
| 4788 | |
| 4789 | ib_ptr_var_id = next_id; |
| 4790 | set<SPIRVariable>(ib_ptr_var_id, ib_ptr_ptr_type_id, StorageClassFunction, 0); |
| 4791 | set_name(ib_ptr_var_id, storage == StorageClassInput ? "gl_in" : "gl_out"); |
| 4792 | if (storage == StorageClassInput) |
| 4793 | set_decoration(ib_ptr_var_id, DecorationNonWritable); |
| 4794 | } |
| 4795 | else |
| 4796 | { |
| 4797 | // Tessellation evaluation per-vertex inputs are also presented as arrays. |
| 4798 | // But, in Metal, this array uses a very special type, 'patch_control_point<T>', |
| 4799 | // which is a container that can be used to access the control point data. |
| 4800 | // To represent this, a special 'ControlPointArray' type has been added to the |
| 4801 | // SPIRV-Cross type system. It should only be generated by and seen in the MSL |
| 4802 | // backend (i.e. this one). |
| 4803 | uint32_t pcp_type_id = next_id++; |
| 4804 | auto &pcp_type = set<SPIRType>(pcp_type_id, ib_type); |
| 4805 | pcp_type.basetype = SPIRType::ControlPointArray; |
| 4806 | pcp_type.parent_type = pcp_type.type_alias = ib_type.self; |
| 4807 | pcp_type.storage = storage; |
| 4808 | ir.meta[pcp_type_id] = ir.meta[ib_type.self]; |
| 4809 | |
| 4810 | ib_ptr_var_id = next_id; |
| 4811 | set<SPIRVariable>(ib_ptr_var_id, pcp_type_id, storage, 0); |
| 4812 | set_name(ib_ptr_var_id, "gl_in"); |
| 4813 | ir.meta[ib_ptr_var_id].decoration.qualified_alias = join(patch_stage_in_var_name, ".gl_in"); |
| 4814 | } |
| 4815 | return ib_ptr_var_id; |
| 4816 | } |
| 4817 | |
| 4818 | uint32_t CompilerMSL::add_meshlet_block(bool per_primitive) |
| 4819 | { |
| 4820 | // Accumulate the variables that should appear in the interface struct. |
| 4821 | SmallVector<SPIRVariable *> vars; |
| 4822 | |
| 4823 | ir.for_each_typed_id<SPIRVariable>([&](uint32_t, SPIRVariable &var) { |
| 4824 | if (var.storage != StorageClassOutput || var.self == builtin_mesh_primitive_indices_id) |
| 4825 | return; |
| 4826 | if (is_per_primitive_variable(var) != per_primitive) |
| 4827 | return; |
| 4828 | vars.push_back(&var); |
| 4829 | }); |
| 4830 | |
| 4831 | if (vars.empty()) |
| 4832 | return 0; |
| 4833 | |
| 4834 | uint32_t next_id = ir.increase_bound_by(1); |
| 4835 | auto &type = set<SPIRType>(next_id, SPIRType(OpTypeStruct)); |
| 4836 | type.basetype = SPIRType::Struct; |
| 4837 | |
| 4838 | InterfaceBlockMeta meta; |
| 4839 | for (auto *p_var : vars) |
| 4840 | { |
| 4841 | meta.strip_array = true; |
| 4842 | meta.allow_local_declaration = false; |
| 4843 | add_variable_to_interface_block(StorageClassOutput, "", type, *p_var, meta); |
| 4844 | } |
| 4845 | |
| 4846 | if (per_primitive) |
| 4847 | set_name(type.self, "spvPerPrimitive"); |
| 4848 | else |
| 4849 | set_name(type.self, "spvPerVertex"); |
| 4850 | |
| 4851 | return next_id; |
| 4852 | } |
| 4853 | |
| 4854 | // Ensure that the type is compatible with the builtin. |
| 4855 | // If it is, simply return the given type ID. |
| 4856 | // Otherwise, create a new type, and return it's ID. |
| 4857 | uint32_t CompilerMSL::ensure_correct_builtin_type(uint32_t type_id, BuiltIn builtin) |
| 4858 | { |
| 4859 | auto &type = get<SPIRType>(type_id); |
| 4860 | auto &pointee_type = get_pointee_type(type); |
| 4861 | |
| 4862 | if ((builtin == BuiltInSampleMask && is_array(pointee_type)) || |
| 4863 | ((builtin == BuiltInLayer || builtin == BuiltInViewportIndex || builtin == BuiltInFragStencilRefEXT) && |
| 4864 | pointee_type.basetype != SPIRType::UInt)) |
| 4865 | { |
| 4866 | uint32_t next_id = ir.increase_bound_by(is_pointer(type) ? 2 : 1); |
| 4867 | uint32_t base_type_id = next_id++; |
| 4868 | auto &base_type = set<SPIRType>(base_type_id, OpTypeInt); |
| 4869 | base_type.basetype = SPIRType::UInt; |
| 4870 | base_type.width = 32; |
| 4871 | |
| 4872 | if (!is_pointer(type)) |
| 4873 | return base_type_id; |
| 4874 | |
| 4875 | uint32_t ptr_type_id = next_id++; |
| 4876 | auto &ptr_type = set<SPIRType>(ptr_type_id, base_type); |
| 4877 | ptr_type.op = spv::OpTypePointer; |
| 4878 | ptr_type.pointer = true; |
| 4879 | ptr_type.pointer_depth++; |
| 4880 | ptr_type.storage = type.storage; |
| 4881 | ptr_type.parent_type = base_type_id; |
| 4882 | return ptr_type_id; |
| 4883 | } |
| 4884 | |
| 4885 | return type_id; |
| 4886 | } |
| 4887 | |
| 4888 | // Ensure that the type is compatible with the shader input. |
| 4889 | // If it is, simply return the given type ID. |
| 4890 | // Otherwise, create a new type, and return its ID. |
| 4891 | uint32_t CompilerMSL::ensure_correct_input_type(uint32_t type_id, uint32_t location, uint32_t component, uint32_t num_components, bool strip_array) |
| 4892 | { |
| 4893 | auto &type = get<SPIRType>(type_id); |
| 4894 | |
| 4895 | uint32_t max_array_dimensions = strip_array ? 1 : 0; |
| 4896 | |
| 4897 | // Struct and array types must match exactly. |
| 4898 | if (type.basetype == SPIRType::Struct || type.array.size() > max_array_dimensions) |
| 4899 | return type_id; |
| 4900 | |
| 4901 | auto p_va = inputs_by_location.find({location, component}); |
| 4902 | if (p_va == end(inputs_by_location)) |
| 4903 | { |
| 4904 | if (num_components > type.vecsize) |
| 4905 | return build_extended_vector_type(type_id, num_components); |
| 4906 | else |
| 4907 | return type_id; |
| 4908 | } |
| 4909 | |
| 4910 | if (num_components == 0) |
| 4911 | num_components = p_va->second.vecsize; |
| 4912 | |
| 4913 | switch (p_va->second.format) |
| 4914 | { |
| 4915 | case MSL_SHADER_VARIABLE_FORMAT_UINT8: |
| 4916 | { |
| 4917 | switch (type.basetype) |
| 4918 | { |
| 4919 | case SPIRType::UByte: |
| 4920 | case SPIRType::UShort: |
| 4921 | case SPIRType::UInt: |
| 4922 | if (num_components > type.vecsize) |
| 4923 | return build_extended_vector_type(type_id, num_components); |
| 4924 | else |
| 4925 | return type_id; |
| 4926 | |
| 4927 | case SPIRType::Short: |
| 4928 | return build_extended_vector_type(type_id, num_components > type.vecsize ? num_components : type.vecsize, |
| 4929 | SPIRType::UShort); |
| 4930 | case SPIRType::Int: |
| 4931 | return build_extended_vector_type(type_id, num_components > type.vecsize ? num_components : type.vecsize, |
| 4932 | SPIRType::UInt); |
| 4933 | |
| 4934 | default: |
| 4935 | SPIRV_CROSS_THROW("Vertex attribute type mismatch between host and shader"); |
| 4936 | } |
| 4937 | } |
| 4938 | |
| 4939 | case MSL_SHADER_VARIABLE_FORMAT_UINT16: |
| 4940 | { |
| 4941 | switch (type.basetype) |
| 4942 | { |
| 4943 | case SPIRType::UShort: |
| 4944 | case SPIRType::UInt: |
| 4945 | if (num_components > type.vecsize) |
| 4946 | return build_extended_vector_type(type_id, num_components); |
| 4947 | else |
| 4948 | return type_id; |
| 4949 | |
| 4950 | case SPIRType::Int: |
| 4951 | return build_extended_vector_type(type_id, num_components > type.vecsize ? num_components : type.vecsize, |
| 4952 | SPIRType::UInt); |
| 4953 | |
| 4954 | default: |
| 4955 | SPIRV_CROSS_THROW("Vertex attribute type mismatch between host and shader"); |
| 4956 | } |
| 4957 | } |
| 4958 | |
| 4959 | default: |
| 4960 | if (num_components > type.vecsize) |
| 4961 | type_id = build_extended_vector_type(type_id, num_components); |
| 4962 | break; |
| 4963 | } |
| 4964 | |
| 4965 | return type_id; |
| 4966 | } |
| 4967 | |
| 4968 | void CompilerMSL::mark_struct_members_packed(const SPIRType &type) |
| 4969 | { |
| 4970 | // Handle possible recursion when a struct contains a pointer to its own type nested somewhere. |
| 4971 | if (has_extended_decoration(type.self, SPIRVCrossDecorationPhysicalTypePacked)) |
| 4972 | return; |
| 4973 | |
| 4974 | set_extended_decoration(type.self, SPIRVCrossDecorationPhysicalTypePacked); |
| 4975 | |
| 4976 | // Problem case! Struct needs to be placed at an awkward alignment. |
| 4977 | // Mark every member of the child struct as packed. |
| 4978 | uint32_t mbr_cnt = uint32_t(type.member_types.size()); |
| 4979 | for (uint32_t i = 0; i < mbr_cnt; i++) |
| 4980 | { |
| 4981 | auto &mbr_type = get<SPIRType>(type.member_types[i]); |
| 4982 | if (mbr_type.basetype == SPIRType::Struct) |
| 4983 | { |
| 4984 | // Recursively mark structs as packed. |
| 4985 | auto *struct_type = &mbr_type; |
| 4986 | while (!struct_type->array.empty()) |
| 4987 | struct_type = &get<SPIRType>(struct_type->parent_type); |
| 4988 | mark_struct_members_packed(*struct_type); |
| 4989 | } |
| 4990 | else if (!is_scalar(mbr_type)) |
| 4991 | set_extended_member_decoration(type.self, i, SPIRVCrossDecorationPhysicalTypePacked); |
| 4992 | } |
| 4993 | } |
| 4994 | |
| 4995 | void CompilerMSL::mark_scalar_layout_structs(const SPIRType &type) |
| 4996 | { |
| 4997 | uint32_t mbr_cnt = uint32_t(type.member_types.size()); |
| 4998 | for (uint32_t i = 0; i < mbr_cnt; i++) |
| 4999 | { |
| 5000 | // Handle possible recursion when a struct contains a pointer to its own type nested somewhere. |
| 5001 | auto &mbr_type = get<SPIRType>(type.member_types[i]); |
| 5002 | if (mbr_type.basetype == SPIRType::Struct && !(mbr_type.pointer && mbr_type.storage == StorageClassPhysicalStorageBuffer)) |
| 5003 | { |
| 5004 | auto *struct_type = &mbr_type; |
| 5005 | while (!struct_type->array.empty()) |
| 5006 | struct_type = &get<SPIRType>(struct_type->parent_type); |
| 5007 | |
| 5008 | if (has_extended_decoration(struct_type->self, SPIRVCrossDecorationPhysicalTypePacked)) |
| 5009 | continue; |
| 5010 | |
| 5011 | uint32_t msl_alignment = get_declared_struct_member_alignment_msl(type, i); |
| 5012 | uint32_t msl_size = get_declared_struct_member_size_msl(type, i); |
| 5013 | uint32_t spirv_offset = type_struct_member_offset(type, i); |
| 5014 | uint32_t spirv_offset_next; |
| 5015 | if (i + 1 < mbr_cnt) |
| 5016 | spirv_offset_next = type_struct_member_offset(type, i + 1); |
| 5017 | else |
| 5018 | spirv_offset_next = spirv_offset + msl_size; |
| 5019 | |
| 5020 | // Both are complicated cases. In scalar layout, a struct of float3 might just consume 12 bytes, |
| 5021 | // and the next member will be placed at offset 12. |
| 5022 | bool struct_is_misaligned = (spirv_offset % msl_alignment) != 0; |
| 5023 | bool struct_is_too_large = spirv_offset + msl_size > spirv_offset_next; |
| 5024 | uint32_t array_stride = 0; |
| 5025 | bool struct_needs_explicit_padding = false; |
| 5026 | |
| 5027 | // Verify that if a struct is used as an array that ArrayStride matches the effective size of the struct. |
| 5028 | if (!mbr_type.array.empty()) |
| 5029 | { |
| 5030 | array_stride = type_struct_member_array_stride(type, i); |
| 5031 | uint32_t dimensions = uint32_t(mbr_type.array.size() - 1); |
| 5032 | for (uint32_t dim = 0; dim < dimensions; dim++) |
| 5033 | { |
| 5034 | uint32_t array_size = to_array_size_literal(mbr_type, dim); |
| 5035 | array_stride /= max<uint32_t>(array_size, 1u); |
| 5036 | } |
| 5037 | |
| 5038 | // Set expected struct size based on ArrayStride. |
| 5039 | struct_needs_explicit_padding = true; |
| 5040 | |
| 5041 | // If struct size is larger than array stride, we might be able to fit, if we tightly pack. |
| 5042 | if (get_declared_struct_size_msl(*struct_type) > array_stride) |
| 5043 | struct_is_too_large = true; |
| 5044 | } |
| 5045 | |
| 5046 | if (struct_is_misaligned || struct_is_too_large) |
| 5047 | mark_struct_members_packed(*struct_type); |
| 5048 | mark_scalar_layout_structs(*struct_type); |
| 5049 | |
| 5050 | if (struct_needs_explicit_padding) |
| 5051 | { |
| 5052 | msl_size = get_declared_struct_size_msl(*struct_type, true, true); |
| 5053 | if (array_stride < msl_size) |
| 5054 | { |
| 5055 | SPIRV_CROSS_THROW("Cannot express an array stride smaller than size of struct type."); |
| 5056 | } |
| 5057 | else |
| 5058 | { |
| 5059 | if (has_extended_decoration(struct_type->self, SPIRVCrossDecorationPaddingTarget)) |
| 5060 | { |
| 5061 | if (array_stride != |
| 5062 | get_extended_decoration(struct_type->self, SPIRVCrossDecorationPaddingTarget)) |
| 5063 | SPIRV_CROSS_THROW( |
| 5064 | "A struct is used with different array strides. Cannot express this in MSL."); |
| 5065 | } |
| 5066 | else |
| 5067 | set_extended_decoration(struct_type->self, SPIRVCrossDecorationPaddingTarget, array_stride); |
| 5068 | } |
| 5069 | } |
| 5070 | } |
| 5071 | } |
| 5072 | } |
| 5073 | |
| 5074 | // Sort the members of the struct type by offset, and pack and then pad members where needed |
| 5075 | // to align MSL members with SPIR-V offsets. The struct members are iterated twice. Packing |
| 5076 | // occurs first, followed by padding, because packing a member reduces both its size and its |
| 5077 | // natural alignment, possibly requiring a padding member to be added ahead of it. |
| 5078 | void CompilerMSL::align_struct(SPIRType &ib_type, unordered_set<uint32_t> &aligned_structs) |
| 5079 | { |
| 5080 | // We align structs recursively, so stop any redundant work. |
| 5081 | ID &ib_type_id = ib_type.self; |
| 5082 | if (aligned_structs.count(ib_type_id)) |
| 5083 | return; |
| 5084 | aligned_structs.insert(ib_type_id); |
| 5085 | |
| 5086 | // Sort the members of the interface structure by their offset. |
| 5087 | // They should already be sorted per SPIR-V spec anyway. |
| 5088 | MemberSorter member_sorter(ib_type, ir.meta[ib_type_id], MemberSorter::Offset); |
| 5089 | member_sorter.sort(); |
| 5090 | |
| 5091 | auto mbr_cnt = uint32_t(ib_type.member_types.size()); |
| 5092 | |
| 5093 | for (uint32_t mbr_idx = 0; mbr_idx < mbr_cnt; mbr_idx++) |
| 5094 | { |
| 5095 | // Pack any dependent struct types before we pack a parent struct. |
| 5096 | auto &mbr_type = get<SPIRType>(ib_type.member_types[mbr_idx]); |
| 5097 | if (mbr_type.basetype == SPIRType::Struct) |
| 5098 | align_struct(mbr_type, aligned_structs); |
| 5099 | } |
| 5100 | |
| 5101 | // Test the alignment of each member, and if a member should be closer to the previous |
| 5102 | // member than the default spacing expects, it is likely that the previous member is in |
| 5103 | // a packed format. If so, and the previous member is packable, pack it. |
| 5104 | // For example ... this applies to any 3-element vector that is followed by a scalar. |
| 5105 | uint32_t msl_offset = 0; |
| 5106 | for (uint32_t mbr_idx = 0; mbr_idx < mbr_cnt; mbr_idx++) |
| 5107 | { |
| 5108 | // This checks the member in isolation, if the member needs some kind of type remapping to conform to SPIR-V |
| 5109 | // offsets, array strides and matrix strides. |
| 5110 | ensure_member_packing_rules_msl(ib_type, mbr_idx); |
| 5111 | |
| 5112 | // Align current offset to the current member's default alignment. If the member was packed, it will observe |
| 5113 | // the updated alignment here. |
| 5114 | uint32_t msl_align_mask = get_declared_struct_member_alignment_msl(ib_type, mbr_idx) - 1; |
| 5115 | uint32_t aligned_msl_offset = (msl_offset + msl_align_mask) & ~msl_align_mask; |
| 5116 | |
| 5117 | // Fetch the member offset as declared in the SPIRV. |
| 5118 | uint32_t spirv_mbr_offset = get_member_decoration(ib_type_id, mbr_idx, DecorationOffset); |
| 5119 | if (spirv_mbr_offset > aligned_msl_offset) |
| 5120 | { |
| 5121 | // Since MSL and SPIR-V have slightly different struct member alignment and |
| 5122 | // size rules, we'll pad to standard C-packing rules with a char[] array. If the member is farther |
| 5123 | // away than C-packing, expects, add an inert padding member before the the member. |
| 5124 | uint32_t padding_bytes = spirv_mbr_offset - aligned_msl_offset; |
| 5125 | set_extended_member_decoration(ib_type_id, mbr_idx, SPIRVCrossDecorationPaddingTarget, padding_bytes); |
| 5126 | |
| 5127 | // Re-align as a sanity check that aligning post-padding matches up. |
| 5128 | msl_offset += padding_bytes; |
| 5129 | aligned_msl_offset = (msl_offset + msl_align_mask) & ~msl_align_mask; |
| 5130 | } |
| 5131 | else if (spirv_mbr_offset < aligned_msl_offset) |
| 5132 | { |
| 5133 | // This should not happen, but deal with unexpected scenarios. |
| 5134 | // It *might* happen if a sub-struct has a larger alignment requirement in MSL than SPIR-V. |
| 5135 | SPIRV_CROSS_THROW("Cannot represent buffer block correctly in MSL."); |
| 5136 | } |
| 5137 | |
| 5138 | assert(aligned_msl_offset == spirv_mbr_offset); |
| 5139 | |
| 5140 | // Increment the current offset to be positioned immediately after the current member. |
| 5141 | // Don't do this for the last member since it can be unsized, and it is not relevant for padding purposes here. |
| 5142 | if (mbr_idx + 1 < mbr_cnt) |
| 5143 | msl_offset = aligned_msl_offset + get_declared_struct_member_size_msl(ib_type, mbr_idx); |
| 5144 | } |
| 5145 | } |
| 5146 | |
| 5147 | bool CompilerMSL::validate_member_packing_rules_msl(const SPIRType &type, uint32_t index) const |
| 5148 | { |
| 5149 | auto &mbr_type = get<SPIRType>(type.member_types[index]); |
| 5150 | uint32_t spirv_offset = get_member_decoration(type.self, index, DecorationOffset); |
| 5151 | |
| 5152 | if (index + 1 < type.member_types.size()) |
| 5153 | { |
| 5154 | // First, we will check offsets. If SPIR-V offset + MSL size > SPIR-V offset of next member, |
| 5155 | // we *must* perform some kind of remapping, no way getting around it. |
| 5156 | // We can always pad after this member if necessary, so that case is fine. |
| 5157 | uint32_t spirv_offset_next = get_member_decoration(type.self, index + 1, DecorationOffset); |
| 5158 | assert(spirv_offset_next >= spirv_offset); |
| 5159 | uint32_t maximum_size = spirv_offset_next - spirv_offset; |
| 5160 | uint32_t msl_mbr_size = get_declared_struct_member_size_msl(type, index); |
| 5161 | if (msl_mbr_size > maximum_size) |
| 5162 | return false; |
| 5163 | } |
| 5164 | |
| 5165 | if (is_array(mbr_type)) |
| 5166 | { |
| 5167 | // If we have an array type, array stride must match exactly with SPIR-V. |
| 5168 | |
| 5169 | // An exception to this requirement is if we have one array element. |
| 5170 | // This comes from DX scalar layout workaround. |
| 5171 | // If app tries to be cheeky and access the member out of bounds, this will not work, but this is the best we can do. |
| 5172 | // In OpAccessChain with logical memory models, access chains must be in-bounds in SPIR-V specification. |
| 5173 | bool relax_array_stride = mbr_type.array.back() == 1 && mbr_type.array_size_literal.back(); |
| 5174 | |
| 5175 | if (!relax_array_stride) |
| 5176 | { |
| 5177 | uint32_t spirv_array_stride = type_struct_member_array_stride(type, index); |
| 5178 | uint32_t msl_array_stride = get_declared_struct_member_array_stride_msl(type, index); |
| 5179 | if (spirv_array_stride != msl_array_stride) |
| 5180 | return false; |
| 5181 | } |
| 5182 | } |
| 5183 | |
| 5184 | if (is_matrix(mbr_type)) |
| 5185 | { |
| 5186 | // Need to check MatrixStride as well. |
| 5187 | uint32_t spirv_matrix_stride = type_struct_member_matrix_stride(type, index); |
| 5188 | uint32_t msl_matrix_stride = get_declared_struct_member_matrix_stride_msl(type, index); |
| 5189 | if (spirv_matrix_stride != msl_matrix_stride) |
| 5190 | return false; |
| 5191 | } |
| 5192 | |
| 5193 | // Now, we check alignment. |
| 5194 | uint32_t msl_alignment = get_declared_struct_member_alignment_msl(type, index); |
| 5195 | if ((spirv_offset % msl_alignment) != 0) |
| 5196 | return false; |
| 5197 | |
| 5198 | // We're in the clear. |
| 5199 | return true; |
| 5200 | } |
| 5201 | |
| 5202 | // Here we need to verify that the member type we declare conforms to Offset, ArrayStride or MatrixStride restrictions. |
| 5203 | // If there is a mismatch, we need to emit remapped types, either normal types, or "packed_X" types. |
| 5204 | // In odd cases we need to emit packed and remapped types, for e.g. weird matrices or arrays with weird array strides. |
| 5205 | void CompilerMSL::ensure_member_packing_rules_msl(SPIRType &ib_type, uint32_t index) |
| 5206 | { |
| 5207 | if (validate_member_packing_rules_msl(ib_type, index)) |
| 5208 | return; |
| 5209 | |
| 5210 | // We failed validation. |
| 5211 | // This case will be nightmare-ish to deal with. This could possibly happen if struct alignment does not quite |
| 5212 | // match up with what we want. Scalar block layout comes to mind here where we might have to work around the rule |
| 5213 | // that struct alignment == max alignment of all members and struct size depends on this alignment. |
| 5214 | // Can't repack structs, but can repack pointers to structs. |
| 5215 | auto &mbr_type = get<SPIRType>(ib_type.member_types[index]); |
| 5216 | bool is_buff_ptr = mbr_type.pointer && mbr_type.storage == StorageClassPhysicalStorageBuffer; |
| 5217 | if (mbr_type.basetype == SPIRType::Struct && !is_buff_ptr) |
| 5218 | SPIRV_CROSS_THROW("Cannot perform any repacking for structs when it is used as a member of another struct."); |
| 5219 | |
| 5220 | // Perform remapping here. |
| 5221 | // There is nothing to be gained by using packed scalars, so don't attempt it. |
| 5222 | if (!is_scalar(ib_type)) |
| 5223 | set_extended_member_decoration(ib_type.self, index, SPIRVCrossDecorationPhysicalTypePacked); |
| 5224 | |
| 5225 | // Try validating again, now with packed. |
| 5226 | if (validate_member_packing_rules_msl(ib_type, index)) |
| 5227 | return; |
| 5228 | |
| 5229 | // We're in deep trouble, and we need to create a new PhysicalType which matches up with what we expect. |
| 5230 | // A lot of work goes here ... |
| 5231 | // We will need remapping on Load and Store to translate the types between Logical and Physical. |
| 5232 | |
| 5233 | // First, we check if we have small vector std140 array. |
| 5234 | // We detect this if we have an array of vectors, and array stride is greater than number of elements. |
| 5235 | if (!mbr_type.array.empty() && !is_matrix(mbr_type)) |
| 5236 | { |
| 5237 | uint32_t array_stride = type_struct_member_array_stride(ib_type, index); |
| 5238 | |
| 5239 | // Hack off array-of-arrays until we find the array stride per element we must have to make it work. |
| 5240 | uint32_t dimensions = uint32_t(mbr_type.array.size() - 1); |
| 5241 | for (uint32_t dim = 0; dim < dimensions; dim++) |
| 5242 | array_stride /= max<uint32_t>(to_array_size_literal(mbr_type, dim), 1u); |
| 5243 | |
| 5244 | // Pointers are 8 bytes |
| 5245 | uint32_t mbr_width_in_bytes = is_buff_ptr ? 8 : (mbr_type.width / 8); |
| 5246 | uint32_t elems_per_stride = array_stride / mbr_width_in_bytes; |
| 5247 | |
| 5248 | if (elems_per_stride == 3) |
| 5249 | SPIRV_CROSS_THROW("Cannot use ArrayStride of 3 elements in remapping scenarios."); |
| 5250 | else if (elems_per_stride > 4 && elems_per_stride != 8) |
| 5251 | SPIRV_CROSS_THROW("Cannot represent vectors with more than 4 elements in MSL."); |
| 5252 | |
| 5253 | if (elems_per_stride == 8) |
| 5254 | { |
| 5255 | if (mbr_type.width == 16) |
| 5256 | add_spv_func_and_recompile(SPVFuncImplPaddedStd140); |
| 5257 | else |
| 5258 | SPIRV_CROSS_THROW("Unexpected type in std140 wide array resolve."); |
| 5259 | } |
| 5260 | |
| 5261 | auto physical_type = mbr_type; |
| 5262 | physical_type.vecsize = elems_per_stride; |
| 5263 | physical_type.parent_type = 0; |
| 5264 | |
| 5265 | // If this is a physical buffer pointer, replace type with a ulongn vector. |
| 5266 | if (is_buff_ptr) |
| 5267 | { |
| 5268 | physical_type.width = 64; |
| 5269 | physical_type.basetype = to_unsigned_basetype(physical_type.width); |
| 5270 | physical_type.pointer = false; |
| 5271 | physical_type.pointer_depth = false; |
| 5272 | physical_type.forward_pointer = false; |
| 5273 | } |
| 5274 | |
| 5275 | uint32_t type_id = ir.increase_bound_by(1); |
| 5276 | set<SPIRType>(type_id, physical_type); |
| 5277 | set_extended_member_decoration(ib_type.self, index, SPIRVCrossDecorationPhysicalTypeID, type_id); |
| 5278 | set_decoration(type_id, DecorationArrayStride, array_stride); |
| 5279 | |
| 5280 | // Remove packed_ for vectors of size 1, 2 and 4. |
| 5281 | unset_extended_member_decoration(ib_type.self, index, SPIRVCrossDecorationPhysicalTypePacked); |
| 5282 | } |
| 5283 | else if (is_matrix(mbr_type)) |
| 5284 | { |
| 5285 | // MatrixStride might be std140-esque. |
| 5286 | uint32_t matrix_stride = type_struct_member_matrix_stride(ib_type, index); |
| 5287 | |
| 5288 | uint32_t elems_per_stride = matrix_stride / (mbr_type.width / 8); |
| 5289 | |
| 5290 | if (elems_per_stride == 3) |
| 5291 | SPIRV_CROSS_THROW("Cannot use ArrayStride of 3 elements in remapping scenarios."); |
| 5292 | else if (elems_per_stride > 4 && elems_per_stride != 8) |
| 5293 | SPIRV_CROSS_THROW("Cannot represent vectors with more than 4 elements in MSL."); |
| 5294 | |
| 5295 | if (elems_per_stride == 8) |
| 5296 | { |
| 5297 | if (mbr_type.basetype != SPIRType::Half) |
| 5298 | SPIRV_CROSS_THROW("Unexpected type in std140 wide matrix stride resolve."); |
| 5299 | add_spv_func_and_recompile(SPVFuncImplPaddedStd140); |
| 5300 | } |
| 5301 | |
| 5302 | bool row_major = has_member_decoration(ib_type.self, index, DecorationRowMajor); |
| 5303 | auto physical_type = mbr_type; |
| 5304 | physical_type.parent_type = 0; |
| 5305 | |
| 5306 | if (row_major) |
| 5307 | physical_type.columns = elems_per_stride; |
| 5308 | else |
| 5309 | physical_type.vecsize = elems_per_stride; |
| 5310 | uint32_t type_id = ir.increase_bound_by(1); |
| 5311 | set<SPIRType>(type_id, physical_type); |
| 5312 | set_extended_member_decoration(ib_type.self, index, SPIRVCrossDecorationPhysicalTypeID, type_id); |
| 5313 | |
| 5314 | // Remove packed_ for vectors of size 1, 2 and 4. |
| 5315 | unset_extended_member_decoration(ib_type.self, index, SPIRVCrossDecorationPhysicalTypePacked); |
| 5316 | } |
| 5317 | else |
| 5318 | SPIRV_CROSS_THROW("Found a buffer packing case which we cannot represent in MSL."); |
| 5319 | |
| 5320 | // Try validating again, now with physical type remapping. |
| 5321 | if (validate_member_packing_rules_msl(ib_type, index)) |
| 5322 | return; |
| 5323 | |
| 5324 | // We might have a particular odd scalar layout case where the last element of an array |
| 5325 | // does not take up as much space as the ArrayStride or MatrixStride. This can happen with DX cbuffers. |
| 5326 | // The "proper" workaround for this is extremely painful and essentially impossible in the edge case of float3[], |
| 5327 | // so we hack around it by declaring the offending array or matrix with one less array size/col/row, |
| 5328 | // and rely on padding to get the correct value. We will technically access arrays out of bounds into the padding region, |
| 5329 | // but it should spill over gracefully without too much trouble. We rely on behavior like this for unsized arrays anyways. |
| 5330 | |
| 5331 | // E.g. we might observe a physical layout of: |
| 5332 | // { float2 a[2]; float b; } in cbuffer layout where ArrayStride of a is 16, but offset of b is 24, packed right after a[1] ... |
| 5333 | uint32_t type_id = get_extended_member_decoration(ib_type.self, index, SPIRVCrossDecorationPhysicalTypeID); |
| 5334 | auto &type = get<SPIRType>(type_id); |
| 5335 | |
| 5336 | // Modify the physical type in-place. This is safe since each physical type workaround is a copy. |
| 5337 | if (is_array(type)) |
| 5338 | { |
| 5339 | if (type.array.back() > 1) |
| 5340 | { |
| 5341 | if (!type.array_size_literal.back()) |
| 5342 | SPIRV_CROSS_THROW("Cannot apply scalar layout workaround with spec constant array size."); |
| 5343 | type.array.back() -= 1; |
| 5344 | } |
| 5345 | else |
| 5346 | { |
| 5347 | // We have an array of size 1, so we cannot decrement that. Our only option now is to |
| 5348 | // force a packed layout instead, and drop the physical type remap since ArrayStride is meaningless now. |
| 5349 | unset_extended_member_decoration(ib_type.self, index, SPIRVCrossDecorationPhysicalTypeID); |
| 5350 | set_extended_member_decoration(ib_type.self, index, SPIRVCrossDecorationPhysicalTypePacked); |
| 5351 | } |
| 5352 | } |
| 5353 | else if (is_matrix(type)) |
| 5354 | { |
| 5355 | bool row_major = has_member_decoration(ib_type.self, index, DecorationRowMajor); |
| 5356 | if (!row_major) |
| 5357 | { |
| 5358 | // Slice off one column. If we only have 2 columns, this might turn the matrix into a vector with one array element instead. |
| 5359 | if (type.columns > 2) |
| 5360 | { |
| 5361 | type.columns--; |
| 5362 | } |
| 5363 | else if (type.columns == 2) |
| 5364 | { |
| 5365 | type.columns = 1; |
| 5366 | assert(type.array.empty()); |
| 5367 | type.op = OpTypeArray; |
| 5368 | type.array.push_back(1); |
| 5369 | type.array_size_literal.push_back(true); |
| 5370 | } |
| 5371 | } |
| 5372 | else |
| 5373 | { |
| 5374 | // Slice off one row. If we only have 2 rows, this might turn the matrix into a vector with one array element instead. |
| 5375 | if (type.vecsize > 2) |
| 5376 | { |
| 5377 | type.vecsize--; |
| 5378 | } |
| 5379 | else if (type.vecsize == 2) |
| 5380 | { |
| 5381 | type.vecsize = type.columns; |
| 5382 | type.columns = 1; |
| 5383 | assert(type.array.empty()); |
| 5384 | type.op = OpTypeArray; |
| 5385 | type.array.push_back(1); |
| 5386 | type.array_size_literal.push_back(true); |
| 5387 | } |
| 5388 | } |
| 5389 | } |
| 5390 | |
| 5391 | // This better validate now, or we must fail gracefully. |
| 5392 | if (!validate_member_packing_rules_msl(ib_type, index)) |
| 5393 | SPIRV_CROSS_THROW("Found a buffer packing case which we cannot represent in MSL."); |
| 5394 | } |
| 5395 | |
| 5396 | void CompilerMSL::emit_store_statement(uint32_t lhs_expression, uint32_t rhs_expression) |
| 5397 | { |
| 5398 | auto &type = expression_type(rhs_expression); |
| 5399 | |
| 5400 | bool lhs_remapped_type = has_extended_decoration(lhs_expression, SPIRVCrossDecorationPhysicalTypeID); |
| 5401 | bool lhs_packed_type = has_extended_decoration(lhs_expression, SPIRVCrossDecorationPhysicalTypePacked); |
| 5402 | auto *lhs_e = maybe_get<SPIRExpression>(lhs_expression); |
| 5403 | auto *rhs_e = maybe_get<SPIRExpression>(rhs_expression); |
| 5404 | |
| 5405 | bool transpose = lhs_e && lhs_e->need_transpose; |
| 5406 | |
| 5407 | if (has_decoration(lhs_expression, DecorationBuiltIn) && |
| 5408 | BuiltIn(get_decoration(lhs_expression, DecorationBuiltIn)) == BuiltInSampleMask && |
| 5409 | is_array(type)) |
| 5410 | { |
| 5411 | // Storing an array to SampleMask, have to remove the array-ness before storing. |
| 5412 | statement(to_expression(lhs_expression), " = ", to_enclosed_unpacked_expression(rhs_expression), "[0];"); |
| 5413 | register_write(lhs_expression); |
| 5414 | } |
| 5415 | else if (!lhs_remapped_type && !lhs_packed_type) |
| 5416 | { |
| 5417 | // No physical type remapping, and no packed type, so can just emit a store directly. |
| 5418 | |
| 5419 | // We might not be dealing with remapped physical types or packed types, |
| 5420 | // but we might be doing a clean store to a row-major matrix. |
| 5421 | // In this case, we just flip transpose states, and emit the store, a transpose must be in the RHS expression, if any. |
| 5422 | if (is_matrix(type) && lhs_e && lhs_e->need_transpose) |
| 5423 | { |
| 5424 | lhs_e->need_transpose = false; |
| 5425 | |
| 5426 | if (rhs_e && rhs_e->need_transpose) |
| 5427 | { |
| 5428 | // Direct copy, but might need to unpack RHS. |
| 5429 | // Skip the transpose, as we will transpose when writing to LHS and transpose(transpose(T)) == T. |
| 5430 | rhs_e->need_transpose = false; |
| 5431 | statement(to_expression(lhs_expression), " = ", to_unpacked_row_major_matrix_expression(rhs_expression), |
| 5432 | ";"); |
| 5433 | rhs_e->need_transpose = true; |
| 5434 | } |
| 5435 | else |
| 5436 | statement(to_expression(lhs_expression), " = transpose(", to_unpacked_expression(rhs_expression), ");"); |
| 5437 | |
| 5438 | lhs_e->need_transpose = true; |
| 5439 | register_write(lhs_expression); |
| 5440 | } |
| 5441 | else if (lhs_e && lhs_e->need_transpose) |
| 5442 | { |
| 5443 | lhs_e->need_transpose = false; |
| 5444 | |
| 5445 | // Storing a column to a row-major matrix. Unroll the write. |
| 5446 | for (uint32_t c = 0; c < type.vecsize; c++) |
| 5447 | { |
| 5448 | auto lhs_expr = to_dereferenced_expression(lhs_expression); |
| 5449 | auto column_index = lhs_expr.find_last_of('['); |
| 5450 | if (column_index != string::npos) |
| 5451 | { |
| 5452 | statement(lhs_expr.insert(column_index, join('[', c, ']')), " = ", |
| 5453 | to_extract_component_expression(rhs_expression, c), ";"); |
| 5454 | } |
| 5455 | } |
| 5456 | lhs_e->need_transpose = true; |
| 5457 | register_write(lhs_expression); |
| 5458 | } |
| 5459 | else |
| 5460 | CompilerGLSL::emit_store_statement(lhs_expression, rhs_expression); |
| 5461 | } |
| 5462 | else if (!lhs_remapped_type && !is_matrix(type) && !transpose) |
| 5463 | { |
| 5464 | // Even if the target type is packed, we can directly store to it. We cannot store to packed matrices directly, |
| 5465 | // since they are declared as array of vectors instead, and we need the fallback path below. |
| 5466 | CompilerGLSL::emit_store_statement(lhs_expression, rhs_expression); |
| 5467 | } |
| 5468 | else |
| 5469 | { |
| 5470 | // Special handling when storing to a remapped physical type. |
| 5471 | // This is mostly to deal with std140 padded matrices or vectors. |
| 5472 | |
| 5473 | TypeID physical_type_id = lhs_remapped_type ? |
| 5474 | ID(get_extended_decoration(lhs_expression, SPIRVCrossDecorationPhysicalTypeID)) : |
| 5475 | type.self; |
| 5476 | |
| 5477 | auto &physical_type = get<SPIRType>(physical_type_id); |
| 5478 | |
| 5479 | string cast_addr_space = "thread"; |
| 5480 | auto *p_var_lhs = maybe_get_backing_variable(lhs_expression); |
| 5481 | if (p_var_lhs) |
| 5482 | cast_addr_space = get_type_address_space(get<SPIRType>(p_var_lhs->basetype), lhs_expression); |
| 5483 | |
| 5484 | if (is_matrix(type)) |
| 5485 | { |
| 5486 | const char *packed_pfx = lhs_packed_type ? "packed_" : ""; |
| 5487 | |
| 5488 | // Packed matrices are stored as arrays of packed vectors, so we need |
| 5489 | // to assign the vectors one at a time. |
| 5490 | // For row-major matrices, we need to transpose the *right-hand* side, |
| 5491 | // not the left-hand side. |
| 5492 | |
| 5493 | // Lots of cases to cover here ... |
| 5494 | |
| 5495 | bool rhs_transpose = rhs_e && rhs_e->need_transpose; |
| 5496 | SPIRType write_type = type; |
| 5497 | string cast_expr; |
| 5498 | |
| 5499 | // We're dealing with transpose manually. |
| 5500 | if (rhs_transpose) |
| 5501 | rhs_e->need_transpose = false; |
| 5502 | |
| 5503 | if (transpose) |
| 5504 | { |
| 5505 | // We're dealing with transpose manually. |
| 5506 | lhs_e->need_transpose = false; |
| 5507 | write_type.vecsize = type.columns; |
| 5508 | write_type.columns = 1; |
| 5509 | |
| 5510 | if (physical_type.columns != type.columns) |
| 5511 | cast_expr = join("(", cast_addr_space, " ", packed_pfx, type_to_glsl(write_type), "&)"); |
| 5512 | |
| 5513 | if (rhs_transpose) |
| 5514 | { |
| 5515 | // If RHS is also transposed, we can just copy row by row. |
| 5516 | for (uint32_t i = 0; i < type.vecsize; i++) |
| 5517 | { |
| 5518 | statement(cast_expr, to_enclosed_expression(lhs_expression), "[", i, "]", " = ", |
| 5519 | to_unpacked_row_major_matrix_expression(rhs_expression), "[", i, "];"); |
| 5520 | } |
| 5521 | } |
| 5522 | else |
| 5523 | { |
| 5524 | auto vector_type = expression_type(rhs_expression); |
| 5525 | vector_type.vecsize = vector_type.columns; |
| 5526 | vector_type.columns = 1; |
| 5527 | |
| 5528 | // Transpose on the fly. Emitting a lot of full transpose() ops and extracting lanes seems very bad, |
| 5529 | // so pick out individual components instead. |
| 5530 | for (uint32_t i = 0; i < type.vecsize; i++) |
| 5531 | { |
| 5532 | string rhs_row = type_to_glsl_constructor(vector_type) + "("; |
| 5533 | for (uint32_t j = 0; j < vector_type.vecsize; j++) |
| 5534 | { |
| 5535 | rhs_row += join(to_enclosed_unpacked_expression(rhs_expression), "[", j, "][", i, "]"); |
| 5536 | if (j + 1 < vector_type.vecsize) |
| 5537 | rhs_row += ", "; |
| 5538 | } |
| 5539 | rhs_row += ")"; |
| 5540 | |
| 5541 | statement(cast_expr, to_enclosed_expression(lhs_expression), "[", i, "]", " = ", rhs_row, ";"); |
| 5542 | } |
| 5543 | } |
| 5544 | |
| 5545 | // We're dealing with transpose manually. |
| 5546 | lhs_e->need_transpose = true; |
| 5547 | } |
| 5548 | else |
| 5549 | { |
| 5550 | write_type.columns = 1; |
| 5551 | |
| 5552 | if (physical_type.vecsize != type.vecsize) |
| 5553 | cast_expr = join("(", cast_addr_space, " ", packed_pfx, type_to_glsl(write_type), "&)"); |
| 5554 | |
| 5555 | if (rhs_transpose) |
| 5556 | { |
| 5557 | auto vector_type = expression_type(rhs_expression); |
| 5558 | vector_type.columns = 1; |
| 5559 | |
| 5560 | // Transpose on the fly. Emitting a lot of full transpose() ops and extracting lanes seems very bad, |
| 5561 | // so pick out individual components instead. |
| 5562 | for (uint32_t i = 0; i < type.columns; i++) |
| 5563 | { |
| 5564 | string rhs_row = type_to_glsl_constructor(vector_type) + "("; |
| 5565 | for (uint32_t j = 0; j < vector_type.vecsize; j++) |
| 5566 | { |
| 5567 | // Need to explicitly unpack expression since we've mucked with transpose state. |
| 5568 | auto unpacked_expr = to_unpacked_row_major_matrix_expression(rhs_expression); |
| 5569 | rhs_row += join(unpacked_expr, "[", j, "][", i, "]"); |
| 5570 | if (j + 1 < vector_type.vecsize) |
| 5571 | rhs_row += ", "; |
| 5572 | } |
| 5573 | rhs_row += ")"; |
| 5574 | |
| 5575 | statement(cast_expr, to_enclosed_expression(lhs_expression), "[", i, "]", " = ", rhs_row, ";"); |
| 5576 | } |
| 5577 | } |
| 5578 | else |
| 5579 | { |
| 5580 | // Copy column-by-column. |
| 5581 | for (uint32_t i = 0; i < type.columns; i++) |
| 5582 | { |
| 5583 | statement(cast_expr, to_enclosed_expression(lhs_expression), "[", i, "]", " = ", |
| 5584 | to_enclosed_unpacked_expression(rhs_expression), "[", i, "];"); |
| 5585 | } |
| 5586 | } |
| 5587 | } |
| 5588 | |
| 5589 | // We're dealing with transpose manually. |
| 5590 | if (rhs_transpose) |
| 5591 | rhs_e->need_transpose = true; |
| 5592 | } |
| 5593 | else if (transpose) |
| 5594 | { |
| 5595 | lhs_e->need_transpose = false; |
| 5596 | |
| 5597 | SPIRType write_type = type; |
| 5598 | write_type.vecsize = 1; |
| 5599 | write_type.columns = 1; |
| 5600 | |
| 5601 | // Storing a column to a row-major matrix. Unroll the write. |
| 5602 | for (uint32_t c = 0; c < type.vecsize; c++) |
| 5603 | { |
| 5604 | auto lhs_expr = to_enclosed_expression(lhs_expression); |
| 5605 | auto column_index = lhs_expr.find_last_of('['); |
| 5606 | |
| 5607 | // Get rid of any ".data" half8 handling here, we're casting to scalar anyway. |
| 5608 | auto end_column_index = lhs_expr.find_last_of(']'); |
| 5609 | auto end_dot_index = lhs_expr.find_last_of('.'); |
| 5610 | if (end_dot_index != string::npos && end_dot_index > end_column_index) |
| 5611 | lhs_expr.resize(end_dot_index); |
| 5612 | |
| 5613 | if (column_index != string::npos) |
| 5614 | { |
| 5615 | statement("((", cast_addr_space, " ", type_to_glsl(write_type), "*)&", |
| 5616 | lhs_expr.insert(column_index, join('[', c, ']', ")")), " = ", |
| 5617 | to_extract_component_expression(rhs_expression, c), ";"); |
| 5618 | } |
| 5619 | } |
| 5620 | |
| 5621 | lhs_e->need_transpose = true; |
| 5622 | } |
| 5623 | else if ((is_matrix(physical_type) || is_array(physical_type)) && |
| 5624 | physical_type.vecsize <= 4 && |
| 5625 | physical_type.vecsize > type.vecsize) |
| 5626 | { |
| 5627 | assert(type.vecsize >= 1 && type.vecsize <= 3); |
| 5628 | |
| 5629 | // If we have packed types, we cannot use swizzled stores. |
| 5630 | // We could technically unroll the store for each element if needed. |
| 5631 | // When remapping to a std140 physical type, we always get float4, |
| 5632 | // and the packed decoration should always be removed. |
| 5633 | assert(!lhs_packed_type); |
| 5634 | |
| 5635 | string lhs = to_dereferenced_expression(lhs_expression); |
| 5636 | string rhs = to_pointer_expression(rhs_expression); |
| 5637 | |
| 5638 | // Unpack the expression so we can store to it with a float or float2. |
| 5639 | // It's still an l-value, so it's fine. Most other unpacking of expressions turn them into r-values instead. |
| 5640 | lhs = join("(", cast_addr_space, " ", type_to_glsl(type), "&)", enclose_expression(lhs)); |
| 5641 | if (!optimize_read_modify_write(expression_type(rhs_expression), lhs, rhs)) |
| 5642 | statement(lhs, " = ", rhs, ";"); |
| 5643 | } |
| 5644 | else if (!is_matrix(type)) |
| 5645 | { |
| 5646 | string lhs = to_dereferenced_expression(lhs_expression); |
| 5647 | string rhs = to_pointer_expression(rhs_expression); |
| 5648 | if (!optimize_read_modify_write(expression_type(rhs_expression), lhs, rhs)) |
| 5649 | statement(lhs, " = ", rhs, ";"); |
| 5650 | } |
| 5651 | |
| 5652 | register_write(lhs_expression); |
| 5653 | } |
| 5654 | } |
| 5655 | |
| 5656 | static bool expression_ends_with(const string &expr_str, const std::string &ending) |
| 5657 | { |
| 5658 | if (expr_str.length() >= ending.length()) |
| 5659 | return (expr_str.compare(expr_str.length() - ending.length(), ending.length(), ending) == 0); |
| 5660 | else |
| 5661 | return false; |
| 5662 | } |
| 5663 | |
| 5664 | // Converts the format of the current expression from packed to unpacked, |
| 5665 | // by wrapping the expression in a constructor of the appropriate type. |
| 5666 | // Also, handle special physical ID remapping scenarios, similar to emit_store_statement(). |
| 5667 | string CompilerMSL::unpack_expression_type(string expr_str, const SPIRType &type, uint32_t physical_type_id, |
| 5668 | bool packed, bool row_major) |
| 5669 | { |
| 5670 | // Trivial case, nothing to do. |
| 5671 | if (physical_type_id == 0 && !packed) |
| 5672 | return expr_str; |
| 5673 | |
| 5674 | const SPIRType *physical_type = nullptr; |
| 5675 | if (physical_type_id) |
| 5676 | physical_type = &get<SPIRType>(physical_type_id); |
| 5677 | |
| 5678 | static const char *swizzle_lut[] = { |
| 5679 | ".x", |
| 5680 | ".xy", |
| 5681 | ".xyz", |
| 5682 | "", |
| 5683 | }; |
| 5684 | |
| 5685 | // TODO: Move everything to the template wrapper? |
| 5686 | bool uses_std140_wrapper = physical_type && physical_type->vecsize > 4; |
| 5687 | |
| 5688 | if (physical_type && is_vector(*physical_type) && is_array(*physical_type) && |
| 5689 | !uses_std140_wrapper && |
| 5690 | physical_type->vecsize > type.vecsize && !expression_ends_with(expr_str, swizzle_lut[type.vecsize - 1])) |
| 5691 | { |
| 5692 | // std140 array cases for vectors. |
| 5693 | assert(type.vecsize >= 1 && type.vecsize <= 3); |
| 5694 | return enclose_expression(expr_str) + swizzle_lut[type.vecsize - 1]; |
| 5695 | } |
| 5696 | else if (physical_type && is_matrix(*physical_type) && is_vector(type) && |
| 5697 | !uses_std140_wrapper && |
| 5698 | physical_type->vecsize > type.vecsize) |
| 5699 | { |
| 5700 | // Extract column from padded matrix. |
| 5701 | assert(type.vecsize >= 1 && type.vecsize <= 4); |
| 5702 | return enclose_expression(expr_str) + swizzle_lut[type.vecsize - 1]; |
| 5703 | } |
| 5704 | else if (is_matrix(type)) |
| 5705 | { |
| 5706 | // Packed matrices are stored as arrays of packed vectors. Unfortunately, |
| 5707 | // we can't just pass the array straight to the matrix constructor. We have to |
| 5708 | // pass each vector individually, so that they can be unpacked to normal vectors. |
| 5709 | if (!physical_type) |
| 5710 | physical_type = &type; |
| 5711 | |
| 5712 | uint32_t vecsize = type.vecsize; |
| 5713 | uint32_t columns = type.columns; |
| 5714 | if (row_major) |
| 5715 | swap(vecsize, columns); |
| 5716 | |
| 5717 | uint32_t physical_vecsize = row_major ? physical_type->columns : physical_type->vecsize; |
| 5718 | |
| 5719 | const char *base_type = type.width == 16 ? "half" : "float"; |
| 5720 | string unpack_expr = join(base_type, columns, "x", vecsize, "("); |
| 5721 | |
| 5722 | const char *load_swiz = ""; |
| 5723 | const char *data_swiz = physical_vecsize > 4 ? ".data" : ""; |
| 5724 | |
| 5725 | if (physical_vecsize != vecsize) |
| 5726 | load_swiz = swizzle_lut[vecsize - 1]; |
| 5727 | |
| 5728 | for (uint32_t i = 0; i < columns; i++) |
| 5729 | { |
| 5730 | if (i > 0) |
| 5731 | unpack_expr += ", "; |
| 5732 | |
| 5733 | if (packed) |
| 5734 | unpack_expr += join(base_type, physical_vecsize, "(", expr_str, "[", i, "]", ")", load_swiz); |
| 5735 | else |
| 5736 | unpack_expr += join(expr_str, "[", i, "]", data_swiz, load_swiz); |
| 5737 | } |
| 5738 | |
| 5739 | unpack_expr += ")"; |
| 5740 | return unpack_expr; |
| 5741 | } |
| 5742 | else |
| 5743 | { |
| 5744 | return join(type_to_glsl(type), "(", expr_str, ")"); |
| 5745 | } |
| 5746 | } |
| 5747 | |
| 5748 | // Emits the file header info |
| 5749 | void CompilerMSL::emit_header() |
| 5750 | { |
| 5751 | // This particular line can be overridden during compilation, so make it a flag and not a pragma line. |
| 5752 | if (suppress_missing_prototypes) |
| 5753 | add_pragma_line("#pragma clang diagnostic ignored \"-Wmissing-prototypes\"", false); |
| 5754 | if (suppress_incompatible_pointer_types_discard_qualifiers) |
| 5755 | add_pragma_line("#pragma clang diagnostic ignored \"-Wincompatible-pointer-types-discards-qualifiers\"", false); |
| 5756 | |
| 5757 | // Disable warning about "sometimes unitialized" when zero-initializing simple threadgroup variables |
| 5758 | if (suppress_sometimes_unitialized) |
| 5759 | add_pragma_line("#pragma clang diagnostic ignored \"-Wsometimes-uninitialized\"", false); |
| 5760 | |
| 5761 | // Disable warning about missing braces for array<T> template to make arrays a value type |
| 5762 | if (spv_function_implementations.count(SPVFuncImplUnsafeArray) != 0) |
| 5763 | add_pragma_line("#pragma clang diagnostic ignored \"-Wmissing-braces\"", false); |
| 5764 | |
| 5765 | // Floating point fast math compile declarations |
| 5766 | if (msl_options.use_fast_math_pragmas && msl_options.supports_msl_version(3, 2)) |
| 5767 | { |
| 5768 | uint32_t contract_mask = FPFastMathModeAllowContractMask; |
| 5769 | uint32_t relax_mask = (FPFastMathModeNSZMask | FPFastMathModeAllowRecipMask | FPFastMathModeAllowReassocMask); |
| 5770 | uint32_t fast_mask = (relax_mask | FPFastMathModeNotNaNMask | FPFastMathModeNotInfMask); |
| 5771 | |
| 5772 | // FP math mode |
| 5773 | uint32_t fp_flags = get_fp_fast_math_flags(true); |
| 5774 | const char *math_mode = "safe"; |
| 5775 | if ((fp_flags & fast_mask) == fast_mask) // Must have all flags |
| 5776 | math_mode = "fast"; |
| 5777 | else if ((fp_flags & relax_mask) == relax_mask) // Must have all flags |
| 5778 | math_mode = "relaxed"; |
| 5779 | |
| 5780 | add_pragma_line(join("#pragma metal fp math_mode(", math_mode, ")"), false); |
| 5781 | |
| 5782 | // FP contraction |
| 5783 | const char *contract_mode = ((fp_flags & contract_mask) == contract_mask) ? "fast" : "off"; |
| 5784 | add_pragma_line(join("#pragma metal fp contract(", contract_mode, ")"), false); |
| 5785 | } |
| 5786 | |
| 5787 | for (auto &pragma : pragma_lines) |
| 5788 | statement(pragma); |
| 5789 | |
| 5790 | if (!pragma_lines.empty()) |
| 5791 | statement(""); |
| 5792 | |
| 5793 | statement("#include <metal_stdlib>"); |
| 5794 | statement("#include <simd/simd.h>"); |
| 5795 | |
| 5796 | for (auto &header : header_lines) |
| 5797 | statement(header); |
| 5798 | |
| 5799 | statement(""); |
| 5800 | statement("using namespace metal;"); |
| 5801 | statement(""); |
| 5802 | |
| 5803 | for (auto &td : typedef_lines) |
| 5804 | statement(td); |
| 5805 | |
| 5806 | if (!typedef_lines.empty()) |
| 5807 | statement(""); |
| 5808 | } |
| 5809 | |
| 5810 | void CompilerMSL::add_pragma_line(const string &line, bool recompile_on_unique) |
| 5811 | { |
| 5812 | if (std::find(pragma_lines.begin(), pragma_lines.end(), line) == pragma_lines.end()) |
| 5813 | { |
| 5814 | pragma_lines.push_back(line); |
| 5815 | if (recompile_on_unique) |
| 5816 | force_recompile(); |
| 5817 | } |
| 5818 | } |
| 5819 | |
| 5820 | void CompilerMSL::add_typedef_line(const string &line) |
| 5821 | { |
| 5822 | if (std::find(typedef_lines.begin(), typedef_lines.end(), line) == typedef_lines.end()) |
| 5823 | { |
| 5824 | typedef_lines.push_back(line); |
| 5825 | force_recompile(); |
| 5826 | } |
| 5827 | } |
| 5828 | |
| 5829 | // Template struct like spvUnsafeArray<> need to be declared *before* any resources are declared |
| 5830 | void CompilerMSL::emit_custom_templates() |
| 5831 | { |
| 5832 | static const char * const address_spaces[] = { |
| 5833 | "thread", "constant", "device", "threadgroup", "threadgroup_imageblock", "ray_data", "object_data" |
| 5834 | }; |
| 5835 | |
| 5836 | for (const auto &spv_func : spv_function_implementations) |
| 5837 | { |
| 5838 | switch (spv_func) |
| 5839 | { |
| 5840 | case SPVFuncImplUnsafeArray: |
| 5841 | statement("template<typename T, size_t Num>"); |
| 5842 | statement("struct spvUnsafeArray"); |
| 5843 | begin_scope(); |
| 5844 | statement("T elements[Num ? Num : 1];"); |
| 5845 | statement(""); |
| 5846 | statement("thread T& operator [] (size_t pos) thread"); |
| 5847 | begin_scope(); |
| 5848 | statement("return elements[pos];"); |
| 5849 | end_scope(); |
| 5850 | statement("constexpr const thread T& operator [] (size_t pos) const thread"); |
| 5851 | begin_scope(); |
| 5852 | statement("return elements[pos];"); |
| 5853 | end_scope(); |
| 5854 | statement(""); |
| 5855 | statement("device T& operator [] (size_t pos) device"); |
| 5856 | begin_scope(); |
| 5857 | statement("return elements[pos];"); |
| 5858 | end_scope(); |
| 5859 | statement("constexpr const device T& operator [] (size_t pos) const device"); |
| 5860 | begin_scope(); |
| 5861 | statement("return elements[pos];"); |
| 5862 | end_scope(); |
| 5863 | statement(""); |
| 5864 | statement("constexpr const constant T& operator [] (size_t pos) const constant"); |
| 5865 | begin_scope(); |
| 5866 | statement("return elements[pos];"); |
| 5867 | end_scope(); |
| 5868 | statement(""); |
| 5869 | statement("threadgroup T& operator [] (size_t pos) threadgroup"); |
| 5870 | begin_scope(); |
| 5871 | statement("return elements[pos];"); |
| 5872 | end_scope(); |
| 5873 | statement("constexpr const threadgroup T& operator [] (size_t pos) const threadgroup"); |
| 5874 | begin_scope(); |
| 5875 | statement("return elements[pos];"); |
| 5876 | end_scope(); |
| 5877 | if (get_execution_model() == spv::ExecutionModelMeshEXT || |
| 5878 | get_execution_model() == spv::ExecutionModelTaskEXT) |
| 5879 | { |
| 5880 | statement(""); |
| 5881 | statement("object_data T& operator [] (size_t pos) object_data"); |
| 5882 | begin_scope(); |
| 5883 | statement("return elements[pos];"); |
| 5884 | end_scope(); |
| 5885 | statement("constexpr const object_data T& operator [] (size_t pos) const object_data"); |
| 5886 | begin_scope(); |
| 5887 | statement("return elements[pos];"); |
| 5888 | end_scope(); |
| 5889 | } |
| 5890 | end_scope_decl(); |
| 5891 | statement(""); |
| 5892 | break; |
| 5893 | |
| 5894 | case SPVFuncImplStorageMatrix: |
| 5895 | statement("template<typename T, int Cols, int Rows=Cols>"); |
| 5896 | statement("struct spvStorageMatrix"); |
| 5897 | begin_scope(); |
| 5898 | statement("vec<T, Rows> columns[Cols];"); |
| 5899 | statement(""); |
| 5900 | for (size_t method_idx = 0; method_idx < sizeof(address_spaces) / sizeof(address_spaces[0]); ++method_idx) |
| 5901 | { |
| 5902 | // Some address spaces require particular features. |
| 5903 | if (method_idx == 4) // threadgroup_imageblock |
| 5904 | statement("#ifdef __HAVE_IMAGEBLOCKS__"); |
| 5905 | else if (method_idx == 5) // ray_data |
| 5906 | statement("#ifdef __HAVE_RAYTRACING__"); |
| 5907 | else if (method_idx == 6) // object_data |
| 5908 | statement("#ifdef __HAVE_MESH__"); |
| 5909 | const string &method_as = address_spaces[method_idx]; |
| 5910 | statement("spvStorageMatrix() ", method_as, " = default;"); |
| 5911 | if (method_idx != 1) // constant |
| 5912 | { |
| 5913 | statement(method_as, " spvStorageMatrix& operator=(initializer_list<vec<T, Rows>> cols) ", |
| 5914 | method_as); |
| 5915 | begin_scope(); |
| 5916 | statement("size_t i;"); |
| 5917 | statement("thread vec<T, Rows>* col;"); |
| 5918 | statement("for (i = 0, col = cols.begin(); i < Cols; ++i, ++col)"); |
| 5919 | statement(" columns[i] = *col;"); |
| 5920 | statement("return *this;"); |
| 5921 | end_scope(); |
| 5922 | } |
| 5923 | statement(""); |
| 5924 | for (size_t param_idx = 0; param_idx < sizeof(address_spaces) / sizeof(address_spaces[0]); ++param_idx) |
| 5925 | { |
| 5926 | if (param_idx != method_idx) |
| 5927 | { |
| 5928 | if (param_idx == 4) // threadgroup_imageblock |
| 5929 | statement("#ifdef __HAVE_IMAGEBLOCKS__"); |
| 5930 | else if (param_idx == 5) // ray_data |
| 5931 | statement("#ifdef __HAVE_RAYTRACING__"); |
| 5932 | else if (param_idx == 6) // object_data |
| 5933 | statement("#ifdef __HAVE_MESH__"); |
| 5934 | } |
| 5935 | const string ¶m_as = address_spaces[param_idx]; |
| 5936 | statement("spvStorageMatrix(const ", param_as, " matrix<T, Cols, Rows>& m) ", method_as); |
| 5937 | begin_scope(); |
| 5938 | statement("for (size_t i = 0; i < Cols; ++i)"); |
| 5939 | statement(" columns[i] = m.columns[i];"); |
| 5940 | end_scope(); |
| 5941 | statement("spvStorageMatrix(const ", param_as, " spvStorageMatrix& m) ", method_as, " = default;"); |
| 5942 | if (method_idx != 1) // constant |
| 5943 | { |
| 5944 | statement(method_as, " spvStorageMatrix& operator=(const ", param_as, |
| 5945 | " matrix<T, Cols, Rows>& m) ", method_as); |
| 5946 | begin_scope(); |
| 5947 | statement("for (size_t i = 0; i < Cols; ++i)"); |
| 5948 | statement(" columns[i] = m.columns[i];"); |
| 5949 | statement("return *this;"); |
| 5950 | end_scope(); |
| 5951 | statement(method_as, " spvStorageMatrix& operator=(const ", param_as, " spvStorageMatrix& m) ", |
| 5952 | method_as, " = default;"); |
| 5953 | } |
| 5954 | if (param_idx != method_idx && param_idx >= 4) |
| 5955 | statement("#endif"); |
| 5956 | statement(""); |
| 5957 | } |
| 5958 | statement("operator matrix<T, Cols, Rows>() const ", method_as); |
| 5959 | begin_scope(); |
| 5960 | statement("matrix<T, Cols, Rows> m;"); |
| 5961 | statement("for (int i = 0; i < Cols; ++i)"); |
| 5962 | statement(" m.columns[i] = columns[i];"); |
| 5963 | statement("return m;"); |
| 5964 | end_scope(); |
| 5965 | statement(""); |
| 5966 | statement("vec<T, Rows> operator[](size_t idx) const ", method_as); |
| 5967 | begin_scope(); |
| 5968 | statement("return columns[idx];"); |
| 5969 | end_scope(); |
| 5970 | if (method_idx != 1) // constant |
| 5971 | { |
| 5972 | statement(method_as, " vec<T, Rows>& operator[](size_t idx) ", method_as); |
| 5973 | begin_scope(); |
| 5974 | statement("return columns[idx];"); |
| 5975 | end_scope(); |
| 5976 | } |
| 5977 | if (method_idx >= 4) |
| 5978 | statement("#endif"); |
| 5979 | statement(""); |
| 5980 | } |
| 5981 | end_scope_decl(); |
| 5982 | statement(""); |
| 5983 | statement("template<typename T, int Cols, int Rows>"); |
| 5984 | statement("matrix<T, Rows, Cols> transpose(spvStorageMatrix<T, Cols, Rows> m)"); |
| 5985 | begin_scope(); |
| 5986 | statement("return transpose(matrix<T, Cols, Rows>(m));"); |
| 5987 | end_scope(); |
| 5988 | statement(""); |
| 5989 | statement("typedef spvStorageMatrix<half, 2, 2> spvStorage_half2x2;"); |
| 5990 | statement("typedef spvStorageMatrix<half, 2, 3> spvStorage_half2x3;"); |
| 5991 | statement("typedef spvStorageMatrix<half, 2, 4> spvStorage_half2x4;"); |
| 5992 | statement("typedef spvStorageMatrix<half, 3, 2> spvStorage_half3x2;"); |
| 5993 | statement("typedef spvStorageMatrix<half, 3, 3> spvStorage_half3x3;"); |
| 5994 | statement("typedef spvStorageMatrix<half, 3, 4> spvStorage_half3x4;"); |
| 5995 | statement("typedef spvStorageMatrix<half, 4, 2> spvStorage_half4x2;"); |
| 5996 | statement("typedef spvStorageMatrix<half, 4, 3> spvStorage_half4x3;"); |
| 5997 | statement("typedef spvStorageMatrix<half, 4, 4> spvStorage_half4x4;"); |
| 5998 | statement("typedef spvStorageMatrix<float, 2, 2> spvStorage_float2x2;"); |
| 5999 | statement("typedef spvStorageMatrix<float, 2, 3> spvStorage_float2x3;"); |
| 6000 | statement("typedef spvStorageMatrix<float, 2, 4> spvStorage_float2x4;"); |
| 6001 | statement("typedef spvStorageMatrix<float, 3, 2> spvStorage_float3x2;"); |
| 6002 | statement("typedef spvStorageMatrix<float, 3, 3> spvStorage_float3x3;"); |
| 6003 | statement("typedef spvStorageMatrix<float, 3, 4> spvStorage_float3x4;"); |
| 6004 | statement("typedef spvStorageMatrix<float, 4, 2> spvStorage_float4x2;"); |
| 6005 | statement("typedef spvStorageMatrix<float, 4, 3> spvStorage_float4x3;"); |
| 6006 | statement("typedef spvStorageMatrix<float, 4, 4> spvStorage_float4x4;"); |
| 6007 | statement(""); |
| 6008 | break; |
| 6009 | |
| 6010 | default: |
| 6011 | break; |
| 6012 | } |
| 6013 | } |
| 6014 | } |
| 6015 | |
| 6016 | // Emits any needed custom function bodies. |
| 6017 | // Metal helper functions must be static force-inline, i.e. static inline __attribute__((always_inline)) |
| 6018 | // otherwise they will cause problems when linked together in a single Metallib. |
| 6019 | void CompilerMSL::emit_custom_functions() |
| 6020 | { |
| 6021 | // Use when outputting overloaded functions to cover different address spaces. |
| 6022 | static const char *texture_addr_spaces[] = { "device", "constant", "thread" }; |
| 6023 | static uint32_t texture_addr_space_count = sizeof(texture_addr_spaces) / sizeof(char*); |
| 6024 | |
| 6025 | if (spv_function_implementations.count(SPVFuncImplArrayCopyMultidim)) |
| 6026 | spv_function_implementations.insert(SPVFuncImplArrayCopy); |
| 6027 | |
| 6028 | if (spv_function_implementations.count(SPVFuncImplDynamicImageSampler)) |
| 6029 | { |
| 6030 | // Unfortunately, this one needs a lot of the other functions to compile OK. |
| 6031 | if (!msl_options.supports_msl_version(2)) |
| 6032 | SPIRV_CROSS_THROW( |
| 6033 | "spvDynamicImageSampler requires default-constructible texture objects, which require MSL 2.0."); |
| 6034 | spv_function_implementations.insert(SPVFuncImplTextureSwizzle); |
| 6035 | if (msl_options.swizzle_texture_samples) |
| 6036 | spv_function_implementations.insert(SPVFuncImplGatherSwizzle); |
| 6037 | for (uint32_t i = SPVFuncImplChromaReconstructNearest2Plane; |
| 6038 | i <= SPVFuncImplChromaReconstructLinear420XMidpointYMidpoint3Plane; i++) |
| 6039 | spv_function_implementations.insert(static_cast<SPVFuncImpl>(i)); |
| 6040 | spv_function_implementations.insert(SPVFuncImplExpandITUFullRange); |
| 6041 | spv_function_implementations.insert(SPVFuncImplExpandITUNarrowRange); |
| 6042 | spv_function_implementations.insert(SPVFuncImplConvertYCbCrBT709); |
| 6043 | spv_function_implementations.insert(SPVFuncImplConvertYCbCrBT601); |
| 6044 | spv_function_implementations.insert(SPVFuncImplConvertYCbCrBT2020); |
| 6045 | } |
| 6046 | |
| 6047 | if (spv_function_implementations.count(SPVFuncImplGatherSwizzle) || |
| 6048 | spv_function_implementations.count(SPVFuncImplGatherConstOffsets)) |
| 6049 | { |
| 6050 | spv_function_implementations.insert(SPVFuncImplGatherReturn); |
| 6051 | } |
| 6052 | |
| 6053 | if (spv_function_implementations.count(SPVFuncImplGatherCompareSwizzle) || |
| 6054 | spv_function_implementations.count(SPVFuncImplGatherCompareConstOffsets)) |
| 6055 | { |
| 6056 | spv_function_implementations.insert(SPVFuncImplGatherCompareReturn); |
| 6057 | } |
| 6058 | |
| 6059 | if (spv_function_implementations.count(SPVFuncImplTextureSwizzle) || |
| 6060 | spv_function_implementations.count(SPVFuncImplGatherSwizzle) || |
| 6061 | spv_function_implementations.count(SPVFuncImplGatherCompareSwizzle)) |
| 6062 | { |
| 6063 | spv_function_implementations.insert(SPVFuncImplGetSwizzle); |
| 6064 | } |
| 6065 | |
| 6066 | for (const auto &spv_func : spv_function_implementations) |
| 6067 | { |
| 6068 | switch (spv_func) |
| 6069 | { |
| 6070 | case SPVFuncImplSMod: |
| 6071 | statement("// Implementation of signed integer mod accurate to SPIR-V specification"); |
| 6072 | statement("template<typename Tx, typename Ty>"); |
| 6073 | statement("inline Tx spvSMod(Tx x, Ty y)"); |
| 6074 | begin_scope(); |
| 6075 | statement("Tx remainder = x - y * (x / y);"); |
| 6076 | statement("return select(Tx(remainder + y), remainder, remainder == 0 || (x >= 0) == (y >= 0));"); |
| 6077 | end_scope(); |
| 6078 | statement(""); |
| 6079 | break; |
| 6080 | |
| 6081 | case SPVFuncImplMod: |
| 6082 | statement("// Implementation of the GLSL mod() function, which is slightly different than Metal fmod()"); |
| 6083 | statement("template<typename Tx, typename Ty>"); |
| 6084 | statement("inline Tx mod(Tx x, Ty y)"); |
| 6085 | begin_scope(); |
| 6086 | statement("return x - y * floor(x / y);"); |
| 6087 | end_scope(); |
| 6088 | statement(""); |
| 6089 | break; |
| 6090 | |
| 6091 | case SPVFuncImplRadians: |
| 6092 | statement("// Implementation of the GLSL radians() function"); |
| 6093 | statement("template<typename T>"); |
| 6094 | statement("inline T radians(T d)"); |
| 6095 | begin_scope(); |
| 6096 | statement("return d * T(0.01745329251);"); |
| 6097 | end_scope(); |
| 6098 | statement(""); |
| 6099 | break; |
| 6100 | |
| 6101 | case SPVFuncImplDegrees: |
| 6102 | statement("// Implementation of the GLSL degrees() function"); |
| 6103 | statement("template<typename T>"); |
| 6104 | statement("inline T degrees(T r)"); |
| 6105 | begin_scope(); |
| 6106 | statement("return r * T(57.2957795131);"); |
| 6107 | end_scope(); |
| 6108 | statement(""); |
| 6109 | break; |
| 6110 | |
| 6111 | case SPVFuncImplFindILsb: |
| 6112 | statement("// Implementation of the GLSL findLSB() function"); |
| 6113 | statement("template<typename T>"); |
| 6114 | statement("inline T spvFindLSB(T x)"); |
| 6115 | begin_scope(); |
| 6116 | statement("return select(ctz(x), T(-1), x == T(0));"); |
| 6117 | end_scope(); |
| 6118 | statement(""); |
| 6119 | break; |
| 6120 | |
| 6121 | case SPVFuncImplFindUMsb: |
| 6122 | statement("// Implementation of the unsigned GLSL findMSB() function"); |
| 6123 | statement("template<typename T>"); |
| 6124 | statement("inline T spvFindUMSB(T x)"); |
| 6125 | begin_scope(); |
| 6126 | statement("return select(clz(T(0)) - (clz(x) + T(1)), T(-1), x == T(0));"); |
| 6127 | end_scope(); |
| 6128 | statement(""); |
| 6129 | break; |
| 6130 | |
| 6131 | case SPVFuncImplFindSMsb: |
| 6132 | statement("// Implementation of the signed GLSL findMSB() function"); |
| 6133 | statement("template<typename T>"); |
| 6134 | statement("inline T spvFindSMSB(T x)"); |
| 6135 | begin_scope(); |
| 6136 | statement("T v = select(x, T(-1) - x, x < T(0));"); |
| 6137 | statement("return select(clz(T(0)) - (clz(v) + T(1)), T(-1), v == T(0));"); |
| 6138 | end_scope(); |
| 6139 | statement(""); |
| 6140 | break; |
| 6141 | |
| 6142 | case SPVFuncImplSSign: |
| 6143 | statement("// Implementation of the GLSL sign() function for integer types"); |
| 6144 | statement("template<typename T, typename E = typename enable_if<is_integral<T>::value>::type>"); |
| 6145 | statement("inline T sign(T x)"); |
| 6146 | begin_scope(); |
| 6147 | statement("return select(select(select(x, T(0), x == T(0)), T(1), x > T(0)), T(-1), x < T(0));"); |
| 6148 | end_scope(); |
| 6149 | statement(""); |
| 6150 | break; |
| 6151 | |
| 6152 | case SPVFuncImplArrayCopy: |
| 6153 | case SPVFuncImplArrayCopyMultidim: |
| 6154 | { |
| 6155 | // Unfortunately we cannot template on the address space, so combinatorial explosion it is. |
| 6156 | static const char *function_name_tags[] = { |
| 6157 | "FromConstantToStack", "FromConstantToThreadGroup", "FromStackToStack", |
| 6158 | "FromStackToThreadGroup", "FromThreadGroupToStack", "FromThreadGroupToThreadGroup", |
| 6159 | "FromDeviceToDevice", "FromConstantToDevice", "FromStackToDevice", |
| 6160 | "FromThreadGroupToDevice", "FromDeviceToStack", "FromDeviceToThreadGroup", |
| 6161 | }; |
| 6162 | |
| 6163 | static const char *src_address_space[] = { |
| 6164 | "constant", "constant", "thread const", "thread const", |
| 6165 | "threadgroup const", "threadgroup const", "device const", "constant", |
| 6166 | "thread const", "threadgroup const", "device const", "device const", |
| 6167 | }; |
| 6168 | |
| 6169 | static const char *dst_address_space[] = { |
| 6170 | "thread", "threadgroup", "thread", "threadgroup", "thread", "threadgroup", |
| 6171 | "device", "device", "device", "device", "thread", "threadgroup", |
| 6172 | }; |
| 6173 | |
| 6174 | for (uint32_t variant = 0; variant < 12; variant++) |
| 6175 | { |
| 6176 | bool is_multidim = spv_func == SPVFuncImplArrayCopyMultidim; |
| 6177 | const char* dim = is_multidim ? "[N][M]" : "[N]"; |
| 6178 | statement("template<typename T, uint N", is_multidim ? ", uint M>" : ">"); |
| 6179 | statement("inline void spvArrayCopy", function_name_tags[variant], "(", |
| 6180 | dst_address_space[variant], " T (&dst)", dim, ", ", |
| 6181 | src_address_space[variant], " T (&src)", dim, ")"); |
| 6182 | begin_scope(); |
| 6183 | statement("for (uint i = 0; i < N; i++)"); |
| 6184 | begin_scope(); |
| 6185 | if (is_multidim) |
| 6186 | statement("spvArrayCopy", function_name_tags[variant], "(dst[i], src[i]);"); |
| 6187 | else |
| 6188 | statement("dst[i] = src[i];"); |
| 6189 | end_scope(); |
| 6190 | end_scope(); |
| 6191 | statement(""); |
| 6192 | } |
| 6193 | break; |
| 6194 | } |
| 6195 | |
| 6196 | // Support for Metal 2.1's new texture_buffer type. |
| 6197 | case SPVFuncImplTexelBufferCoords: |
| 6198 | { |
| 6199 | if (msl_options.texel_buffer_texture_width > 0) |
| 6200 | { |
| 6201 | string tex_width_str = convert_to_string(msl_options.texel_buffer_texture_width); |
| 6202 | statement("// Returns 2D texture coords corresponding to 1D texel buffer coords"); |
| 6203 | statement(force_inline); |
| 6204 | statement("uint2 spvTexelBufferCoord(uint tc)"); |
| 6205 | begin_scope(); |
| 6206 | statement(join("return uint2(tc % ", tex_width_str, ", tc / ", tex_width_str, ");")); |
| 6207 | end_scope(); |
| 6208 | statement(""); |
| 6209 | } |
| 6210 | else |
| 6211 | { |
| 6212 | statement("// Returns 2D texture coords corresponding to 1D texel buffer coords"); |
| 6213 | statement( |
| 6214 | "#define spvTexelBufferCoord(tc, tex) uint2((tc) % (tex).get_width(), (tc) / (tex).get_width())"); |
| 6215 | statement(""); |
| 6216 | } |
| 6217 | break; |
| 6218 | } |
| 6219 | |
| 6220 | // Emulate texture2D atomic operations |
| 6221 | case SPVFuncImplImage2DAtomicCoords: |
| 6222 | { |
| 6223 | if (msl_options.supports_msl_version(1, 2)) |
| 6224 | { |
| 6225 | statement("// The required alignment of a linear texture of R32Uint format."); |
| 6226 | statement("constant uint spvLinearTextureAlignmentOverride [[function_constant(", |
| 6227 | msl_options.r32ui_alignment_constant_id, ")]];"); |
| 6228 | statement("constant uint spvLinearTextureAlignment = ", |
| 6229 | "is_function_constant_defined(spvLinearTextureAlignmentOverride) ? ", |
| 6230 | "spvLinearTextureAlignmentOverride : ", msl_options.r32ui_linear_texture_alignment, ";"); |
| 6231 | } |
| 6232 | else |
| 6233 | { |
| 6234 | statement("// The required alignment of a linear texture of R32Uint format."); |
| 6235 | statement("constant uint spvLinearTextureAlignment = ", msl_options.r32ui_linear_texture_alignment, |
| 6236 | ";"); |
| 6237 | } |
| 6238 | statement("// Returns buffer coords corresponding to 2D texture coords for emulating 2D texture atomics"); |
| 6239 | statement("#define spvImage2DAtomicCoord(tc, tex) (((((tex).get_width() + ", |
| 6240 | " spvLinearTextureAlignment / 4 - 1) & ~(", |
| 6241 | " spvLinearTextureAlignment / 4 - 1)) * (tc).y) + (tc).x)"); |
| 6242 | statement(""); |
| 6243 | break; |
| 6244 | } |
| 6245 | |
| 6246 | // Fix up gradient vectors when sampling a cube texture for Apple Silicon. |
| 6247 | // h/t Alexey Knyazev (https://github.com/KhronosGroup/MoltenVK/issues/2068#issuecomment-1817799067) for the code. |
| 6248 | case SPVFuncImplGradientCube: |
| 6249 | statement("static inline gradientcube spvGradientCube(float3 P, float3 dPdx, float3 dPdy)"); |
| 6250 | begin_scope(); |
| 6251 | statement("// Major axis selection"); |
| 6252 | statement("float3 absP = abs(P);"); |
| 6253 | statement("bool xMajor = absP.x >= max(absP.y, absP.z);"); |
| 6254 | statement("bool yMajor = absP.y >= absP.z;"); |
| 6255 | statement("float3 Q = xMajor ? P.yzx : (yMajor ? P.xzy : P);"); |
| 6256 | statement("float3 dQdx = xMajor ? dPdx.yzx : (yMajor ? dPdx.xzy : dPdx);"); |
| 6257 | statement("float3 dQdy = xMajor ? dPdy.yzx : (yMajor ? dPdy.xzy : dPdy);"); |
| 6258 | statement_no_indent(""); |
| 6259 | statement("// Skip a couple of operations compared to usual projection"); |
| 6260 | statement("float4 d = float4(dQdx.xy, dQdy.xy) - (Q.xy / Q.z).xyxy * float4(dQdx.zz, dQdy.zz);"); |
| 6261 | statement_no_indent(""); |
| 6262 | statement("// Final swizzle to put the intermediate values into non-ignored components"); |
| 6263 | statement("// X major: X and Z"); |
| 6264 | statement("// Y major: X and Y"); |
| 6265 | statement("// Z major: Y and Z"); |
| 6266 | statement("return gradientcube(xMajor ? d.xxy : d.xyx, xMajor ? d.zzw : d.zwz);"); |
| 6267 | end_scope(); |
| 6268 | statement(""); |
| 6269 | break; |
| 6270 | |
| 6271 | // "fadd" intrinsic support |
| 6272 | case SPVFuncImplFAdd: |
| 6273 | statement("template<typename T>"); |
| 6274 | statement("[[clang::optnone]] T spvFAdd(T l, T r)"); |
| 6275 | begin_scope(); |
| 6276 | statement("return fma(T(1), l, r);"); |
| 6277 | end_scope(); |
| 6278 | statement(""); |
| 6279 | break; |
| 6280 | |
| 6281 | // "fsub" intrinsic support |
| 6282 | case SPVFuncImplFSub: |
| 6283 | statement("template<typename T>"); |
| 6284 | statement("[[clang::optnone]] T spvFSub(T l, T r)"); |
| 6285 | begin_scope(); |
| 6286 | statement("return fma(T(-1), r, l);"); |
| 6287 | end_scope(); |
| 6288 | statement(""); |
| 6289 | break; |
| 6290 | |
| 6291 | // "fmul' intrinsic support |
| 6292 | case SPVFuncImplFMul: |
| 6293 | statement("template<typename T>"); |
| 6294 | statement("[[clang::optnone]] T spvFMul(T l, T r)"); |
| 6295 | begin_scope(); |
| 6296 | statement("return fma(l, r, T(0));"); |
| 6297 | end_scope(); |
| 6298 | statement(""); |
| 6299 | |
| 6300 | statement("template<typename T, int Cols, int Rows>"); |
| 6301 | statement("[[clang::optnone]] vec<T, Cols> spvFMulVectorMatrix(vec<T, Rows> v, matrix<T, Cols, Rows> m)"); |
| 6302 | begin_scope(); |
| 6303 | statement("vec<T, Cols> res = vec<T, Cols>(0);"); |
| 6304 | statement("for (uint i = Rows; i > 0; --i)"); |
| 6305 | begin_scope(); |
| 6306 | statement("vec<T, Cols> tmp(0);"); |
| 6307 | statement("for (uint j = 0; j < Cols; ++j)"); |
| 6308 | begin_scope(); |
| 6309 | statement("tmp[j] = m[j][i - 1];"); |
| 6310 | end_scope(); |
| 6311 | statement("res = fma(tmp, vec<T, Cols>(v[i - 1]), res);"); |
| 6312 | end_scope(); |
| 6313 | statement("return res;"); |
| 6314 | end_scope(); |
| 6315 | statement(""); |
| 6316 | |
| 6317 | statement("template<typename T, int Cols, int Rows>"); |
| 6318 | statement("[[clang::optnone]] vec<T, Rows> spvFMulMatrixVector(matrix<T, Cols, Rows> m, vec<T, Cols> v)"); |
| 6319 | begin_scope(); |
| 6320 | statement("vec<T, Rows> res = vec<T, Rows>(0);"); |
| 6321 | statement("for (uint i = Cols; i > 0; --i)"); |
| 6322 | begin_scope(); |
| 6323 | statement("res = fma(m[i - 1], vec<T, Rows>(v[i - 1]), res);"); |
| 6324 | end_scope(); |
| 6325 | statement("return res;"); |
| 6326 | end_scope(); |
| 6327 | statement(""); |
| 6328 | |
| 6329 | statement("template<typename T, int LCols, int LRows, int RCols, int RRows>"); |
| 6330 | statement("[[clang::optnone]] matrix<T, RCols, LRows> spvFMulMatrixMatrix(matrix<T, LCols, LRows> l, matrix<T, RCols, RRows> r)"); |
| 6331 | begin_scope(); |
| 6332 | statement("matrix<T, RCols, LRows> res;"); |
| 6333 | statement("for (uint i = 0; i < RCols; i++)"); |
| 6334 | begin_scope(); |
| 6335 | statement("vec<T, RCols> tmp(0);"); |
| 6336 | statement("for (uint j = 0; j < LCols; j++)"); |
| 6337 | begin_scope(); |
| 6338 | statement("tmp = fma(vec<T, RCols>(r[i][j]), l[j], tmp);"); |
| 6339 | end_scope(); |
| 6340 | statement("res[i] = tmp;"); |
| 6341 | end_scope(); |
| 6342 | statement("return res;"); |
| 6343 | end_scope(); |
| 6344 | statement(""); |
| 6345 | break; |
| 6346 | |
| 6347 | case SPVFuncImplQuantizeToF16: |
| 6348 | // Ensure fast-math is disabled to match Vulkan results. |
| 6349 | // SpvHalfTypeSelector is used to match the half* template type to the float* template type. |
| 6350 | // Depending on GPU, MSL does not always flush converted subnormal halfs to zero, |
| 6351 | // as required by OpQuantizeToF16, so check for subnormals and flush them to zero. |
| 6352 | statement("template <typename F> struct SpvHalfTypeSelector;"); |
| 6353 | statement("template <> struct SpvHalfTypeSelector<float> { public: using H = half; };"); |
| 6354 | statement("template<uint N> struct SpvHalfTypeSelector<vec<float, N>> { using H = vec<half, N>; };"); |
| 6355 | statement("template<typename F, typename H = typename SpvHalfTypeSelector<F>::H>"); |
| 6356 | statement("[[clang::optnone]] F spvQuantizeToF16(F fval)"); |
| 6357 | begin_scope(); |
| 6358 | statement("H hval = H(fval);"); |
| 6359 | statement("hval = select(copysign(H(0), hval), hval, isnormal(hval) || isinf(hval) || isnan(hval));"); |
| 6360 | statement("return F(hval);"); |
| 6361 | end_scope(); |
| 6362 | statement(""); |
| 6363 | break; |
| 6364 | |
| 6365 | // Emulate texturecube_array with texture2d_array for iOS where this type is not available |
| 6366 | case SPVFuncImplCubemapTo2DArrayFace: |
| 6367 | statement(force_inline); |
| 6368 | statement("float3 spvCubemapTo2DArrayFace(float3 P)"); |
| 6369 | begin_scope(); |
| 6370 | statement("float3 Coords = abs(P.xyz);"); |
| 6371 | statement("float CubeFace = 0;"); |
| 6372 | statement("float ProjectionAxis = 0;"); |
| 6373 | statement("float u = 0;"); |
| 6374 | statement("float v = 0;"); |
| 6375 | statement("if (Coords.x >= Coords.y && Coords.x >= Coords.z)"); |
| 6376 | begin_scope(); |
| 6377 | statement("CubeFace = P.x >= 0 ? 0 : 1;"); |
| 6378 | statement("ProjectionAxis = Coords.x;"); |
| 6379 | statement("u = P.x >= 0 ? -P.z : P.z;"); |
| 6380 | statement("v = -P.y;"); |
| 6381 | end_scope(); |
| 6382 | statement("else if (Coords.y >= Coords.x && Coords.y >= Coords.z)"); |
| 6383 | begin_scope(); |
| 6384 | statement("CubeFace = P.y >= 0 ? 2 : 3;"); |
| 6385 | statement("ProjectionAxis = Coords.y;"); |
| 6386 | statement("u = P.x;"); |
| 6387 | statement("v = P.y >= 0 ? P.z : -P.z;"); |
| 6388 | end_scope(); |
| 6389 | statement("else"); |
| 6390 | begin_scope(); |
| 6391 | statement("CubeFace = P.z >= 0 ? 4 : 5;"); |
| 6392 | statement("ProjectionAxis = Coords.z;"); |
| 6393 | statement("u = P.z >= 0 ? P.x : -P.x;"); |
| 6394 | statement("v = -P.y;"); |
| 6395 | end_scope(); |
| 6396 | statement("u = 0.5 * (u/ProjectionAxis + 1);"); |
| 6397 | statement("v = 0.5 * (v/ProjectionAxis + 1);"); |
| 6398 | statement("return float3(u, v, CubeFace);"); |
| 6399 | end_scope(); |
| 6400 | statement(""); |
| 6401 | break; |
| 6402 | |
| 6403 | case SPVFuncImplInverse4x4: |
| 6404 | statement("// Returns the determinant of a 2x2 matrix."); |
| 6405 | statement(force_inline); |
| 6406 | statement("float spvDet2x2(float a1, float a2, float b1, float b2)"); |
| 6407 | begin_scope(); |
| 6408 | statement("return a1 * b2 - b1 * a2;"); |
| 6409 | end_scope(); |
| 6410 | statement(""); |
| 6411 | |
| 6412 | statement("// Returns the determinant of a 3x3 matrix."); |
| 6413 | statement(force_inline); |
| 6414 | statement("float spvDet3x3(float a1, float a2, float a3, float b1, float b2, float b3, float c1, " |
| 6415 | "float c2, float c3)"); |
| 6416 | begin_scope(); |
| 6417 | statement("return a1 * spvDet2x2(b2, b3, c2, c3) - b1 * spvDet2x2(a2, a3, c2, c3) + c1 * spvDet2x2(a2, a3, " |
| 6418 | "b2, b3);"); |
| 6419 | end_scope(); |
| 6420 | statement(""); |
| 6421 | statement("// Returns the inverse of a matrix, by using the algorithm of calculating the classical"); |
| 6422 | statement("// adjoint and dividing by the determinant. The contents of the matrix are changed."); |
| 6423 | statement(force_inline); |
| 6424 | statement("float4x4 spvInverse4x4(float4x4 m)"); |
| 6425 | begin_scope(); |
| 6426 | statement("float4x4 adj; // The adjoint matrix (inverse after dividing by determinant)"); |
| 6427 | statement_no_indent(""); |
| 6428 | statement("// Create the transpose of the cofactors, as the classical adjoint of the matrix."); |
| 6429 | statement("adj[0][0] = spvDet3x3(m[1][1], m[1][2], m[1][3], m[2][1], m[2][2], m[2][3], m[3][1], m[3][2], " |
| 6430 | "m[3][3]);"); |
| 6431 | statement("adj[0][1] = -spvDet3x3(m[0][1], m[0][2], m[0][3], m[2][1], m[2][2], m[2][3], m[3][1], m[3][2], " |
| 6432 | "m[3][3]);"); |
| 6433 | statement("adj[0][2] = spvDet3x3(m[0][1], m[0][2], m[0][3], m[1][1], m[1][2], m[1][3], m[3][1], m[3][2], " |
| 6434 | "m[3][3]);"); |
| 6435 | statement("adj[0][3] = -spvDet3x3(m[0][1], m[0][2], m[0][3], m[1][1], m[1][2], m[1][3], m[2][1], m[2][2], " |
| 6436 | "m[2][3]);"); |
| 6437 | statement_no_indent(""); |
| 6438 | statement("adj[1][0] = -spvDet3x3(m[1][0], m[1][2], m[1][3], m[2][0], m[2][2], m[2][3], m[3][0], m[3][2], " |
| 6439 | "m[3][3]);"); |
| 6440 | statement("adj[1][1] = spvDet3x3(m[0][0], m[0][2], m[0][3], m[2][0], m[2][2], m[2][3], m[3][0], m[3][2], " |
| 6441 | "m[3][3]);"); |
| 6442 | statement("adj[1][2] = -spvDet3x3(m[0][0], m[0][2], m[0][3], m[1][0], m[1][2], m[1][3], m[3][0], m[3][2], " |
| 6443 | "m[3][3]);"); |
| 6444 | statement("adj[1][3] = spvDet3x3(m[0][0], m[0][2], m[0][3], m[1][0], m[1][2], m[1][3], m[2][0], m[2][2], " |
| 6445 | "m[2][3]);"); |
| 6446 | statement_no_indent(""); |
| 6447 | statement("adj[2][0] = spvDet3x3(m[1][0], m[1][1], m[1][3], m[2][0], m[2][1], m[2][3], m[3][0], m[3][1], " |
| 6448 | "m[3][3]);"); |
| 6449 | statement("adj[2][1] = -spvDet3x3(m[0][0], m[0][1], m[0][3], m[2][0], m[2][1], m[2][3], m[3][0], m[3][1], " |
| 6450 | "m[3][3]);"); |
| 6451 | statement("adj[2][2] = spvDet3x3(m[0][0], m[0][1], m[0][3], m[1][0], m[1][1], m[1][3], m[3][0], m[3][1], " |
| 6452 | "m[3][3]);"); |
| 6453 | statement("adj[2][3] = -spvDet3x3(m[0][0], m[0][1], m[0][3], m[1][0], m[1][1], m[1][3], m[2][0], m[2][1], " |
| 6454 | "m[2][3]);"); |
| 6455 | statement_no_indent(""); |
| 6456 | statement("adj[3][0] = -spvDet3x3(m[1][0], m[1][1], m[1][2], m[2][0], m[2][1], m[2][2], m[3][0], m[3][1], " |
| 6457 | "m[3][2]);"); |
| 6458 | statement("adj[3][1] = spvDet3x3(m[0][0], m[0][1], m[0][2], m[2][0], m[2][1], m[2][2], m[3][0], m[3][1], " |
| 6459 | "m[3][2]);"); |
| 6460 | statement("adj[3][2] = -spvDet3x3(m[0][0], m[0][1], m[0][2], m[1][0], m[1][1], m[1][2], m[3][0], m[3][1], " |
| 6461 | "m[3][2]);"); |
| 6462 | statement("adj[3][3] = spvDet3x3(m[0][0], m[0][1], m[0][2], m[1][0], m[1][1], m[1][2], m[2][0], m[2][1], " |
| 6463 | "m[2][2]);"); |
| 6464 | statement_no_indent(""); |
| 6465 | statement("// Calculate the determinant as a combination of the cofactors of the first row."); |
| 6466 | statement("float det = (adj[0][0] * m[0][0]) + (adj[0][1] * m[1][0]) + (adj[0][2] * m[2][0]) + (adj[0][3] " |
| 6467 | "* m[3][0]);"); |
| 6468 | statement_no_indent(""); |
| 6469 | statement("// Divide the classical adjoint matrix by the determinant."); |
| 6470 | statement("// If determinant is zero, matrix is not invertable, so leave it unchanged."); |
| 6471 | statement("return (det != 0.0f) ? (adj * (1.0f / det)) : m;"); |
| 6472 | end_scope(); |
| 6473 | statement(""); |
| 6474 | break; |
| 6475 | |
| 6476 | case SPVFuncImplInverse3x3: |
| 6477 | if (spv_function_implementations.count(SPVFuncImplInverse4x4) == 0) |
| 6478 | { |
| 6479 | statement("// Returns the determinant of a 2x2 matrix."); |
| 6480 | statement(force_inline); |
| 6481 | statement("float spvDet2x2(float a1, float a2, float b1, float b2)"); |
| 6482 | begin_scope(); |
| 6483 | statement("return a1 * b2 - b1 * a2;"); |
| 6484 | end_scope(); |
| 6485 | statement(""); |
| 6486 | } |
| 6487 | |
| 6488 | statement("// Returns the inverse of a matrix, by using the algorithm of calculating the classical"); |
| 6489 | statement("// adjoint and dividing by the determinant. The contents of the matrix are changed."); |
| 6490 | statement(force_inline); |
| 6491 | statement("float3x3 spvInverse3x3(float3x3 m)"); |
| 6492 | begin_scope(); |
| 6493 | statement("float3x3 adj; // The adjoint matrix (inverse after dividing by determinant)"); |
| 6494 | statement_no_indent(""); |
| 6495 | statement("// Create the transpose of the cofactors, as the classical adjoint of the matrix."); |
| 6496 | statement("adj[0][0] = spvDet2x2(m[1][1], m[1][2], m[2][1], m[2][2]);"); |
| 6497 | statement("adj[0][1] = -spvDet2x2(m[0][1], m[0][2], m[2][1], m[2][2]);"); |
| 6498 | statement("adj[0][2] = spvDet2x2(m[0][1], m[0][2], m[1][1], m[1][2]);"); |
| 6499 | statement_no_indent(""); |
| 6500 | statement("adj[1][0] = -spvDet2x2(m[1][0], m[1][2], m[2][0], m[2][2]);"); |
| 6501 | statement("adj[1][1] = spvDet2x2(m[0][0], m[0][2], m[2][0], m[2][2]);"); |
| 6502 | statement("adj[1][2] = -spvDet2x2(m[0][0], m[0][2], m[1][0], m[1][2]);"); |
| 6503 | statement_no_indent(""); |
| 6504 | statement("adj[2][0] = spvDet2x2(m[1][0], m[1][1], m[2][0], m[2][1]);"); |
| 6505 | statement("adj[2][1] = -spvDet2x2(m[0][0], m[0][1], m[2][0], m[2][1]);"); |
| 6506 | statement("adj[2][2] = spvDet2x2(m[0][0], m[0][1], m[1][0], m[1][1]);"); |
| 6507 | statement_no_indent(""); |
| 6508 | statement("// Calculate the determinant as a combination of the cofactors of the first row."); |
| 6509 | statement("float det = (adj[0][0] * m[0][0]) + (adj[0][1] * m[1][0]) + (adj[0][2] * m[2][0]);"); |
| 6510 | statement_no_indent(""); |
| 6511 | statement("// Divide the classical adjoint matrix by the determinant."); |
| 6512 | statement("// If determinant is zero, matrix is not invertable, so leave it unchanged."); |
| 6513 | statement("return (det != 0.0f) ? (adj * (1.0f / det)) : m;"); |
| 6514 | end_scope(); |
| 6515 | statement(""); |
| 6516 | break; |
| 6517 | |
| 6518 | case SPVFuncImplInverse2x2: |
| 6519 | statement("// Returns the inverse of a matrix, by using the algorithm of calculating the classical"); |
| 6520 | statement("// adjoint and dividing by the determinant. The contents of the matrix are changed."); |
| 6521 | statement(force_inline); |
| 6522 | statement("float2x2 spvInverse2x2(float2x2 m)"); |
| 6523 | begin_scope(); |
| 6524 | statement("float2x2 adj; // The adjoint matrix (inverse after dividing by determinant)"); |
| 6525 | statement_no_indent(""); |
| 6526 | statement("// Create the transpose of the cofactors, as the classical adjoint of the matrix."); |
| 6527 | statement("adj[0][0] = m[1][1];"); |
| 6528 | statement("adj[0][1] = -m[0][1];"); |
| 6529 | statement_no_indent(""); |
| 6530 | statement("adj[1][0] = -m[1][0];"); |
| 6531 | statement("adj[1][1] = m[0][0];"); |
| 6532 | statement_no_indent(""); |
| 6533 | statement("// Calculate the determinant as a combination of the cofactors of the first row."); |
| 6534 | statement("float det = (adj[0][0] * m[0][0]) + (adj[0][1] * m[1][0]);"); |
| 6535 | statement_no_indent(""); |
| 6536 | statement("// Divide the classical adjoint matrix by the determinant."); |
| 6537 | statement("// If determinant is zero, matrix is not invertable, so leave it unchanged."); |
| 6538 | statement("return (det != 0.0f) ? (adj * (1.0f / det)) : m;"); |
| 6539 | end_scope(); |
| 6540 | statement(""); |
| 6541 | break; |
| 6542 | |
| 6543 | case SPVFuncImplGetSwizzle: |
| 6544 | statement("enum class spvSwizzle : uint"); |
| 6545 | begin_scope(); |
| 6546 | statement("none = 0,"); |
| 6547 | statement("zero,"); |
| 6548 | statement("one,"); |
| 6549 | statement("red,"); |
| 6550 | statement("green,"); |
| 6551 | statement("blue,"); |
| 6552 | statement("alpha"); |
| 6553 | end_scope_decl(); |
| 6554 | statement(""); |
| 6555 | statement("template<typename T>"); |
| 6556 | statement("inline T spvGetSwizzle(vec<T, 4> x, T c, spvSwizzle s)"); |
| 6557 | begin_scope(); |
| 6558 | statement("switch (s)"); |
| 6559 | begin_scope(); |
| 6560 | statement("case spvSwizzle::none:"); |
| 6561 | statement(" return c;"); |
| 6562 | statement("case spvSwizzle::zero:"); |
| 6563 | statement(" return 0;"); |
| 6564 | statement("case spvSwizzle::one:"); |
| 6565 | statement(" return 1;"); |
| 6566 | statement("case spvSwizzle::red:"); |
| 6567 | statement(" return x.r;"); |
| 6568 | statement("case spvSwizzle::green:"); |
| 6569 | statement(" return x.g;"); |
| 6570 | statement("case spvSwizzle::blue:"); |
| 6571 | statement(" return x.b;"); |
| 6572 | statement("case spvSwizzle::alpha:"); |
| 6573 | statement(" return x.a;"); |
| 6574 | end_scope(); |
| 6575 | end_scope(); |
| 6576 | statement(""); |
| 6577 | break; |
| 6578 | |
| 6579 | case SPVFuncImplTextureSwizzle: |
| 6580 | statement("// Wrapper function that swizzles texture samples and fetches."); |
| 6581 | statement("template<typename T>"); |
| 6582 | statement("inline vec<T, 4> spvTextureSwizzle(vec<T, 4> x, uint s)"); |
| 6583 | begin_scope(); |
| 6584 | statement("if (!s)"); |
| 6585 | statement(" return x;"); |
| 6586 | statement("return vec<T, 4>(spvGetSwizzle(x, x.r, spvSwizzle((s >> 0) & 0xFF)), " |
| 6587 | "spvGetSwizzle(x, x.g, spvSwizzle((s >> 8) & 0xFF)), spvGetSwizzle(x, x.b, spvSwizzle((s >> 16) " |
| 6588 | "& 0xFF)), " |
| 6589 | "spvGetSwizzle(x, x.a, spvSwizzle((s >> 24) & 0xFF)));"); |
| 6590 | end_scope(); |
| 6591 | statement(""); |
| 6592 | statement("template<typename T>"); |
| 6593 | statement("inline T spvTextureSwizzle(T x, uint s)"); |
| 6594 | begin_scope(); |
| 6595 | statement("return spvTextureSwizzle(vec<T, 4>(x, 0, 0, 1), s).x;"); |
| 6596 | end_scope(); |
| 6597 | statement(""); |
| 6598 | break; |
| 6599 | |
| 6600 | case SPVFuncImplGatherReturn: |
| 6601 | statement("template<typename Tex, typename... Tp>"); |
| 6602 | statement("using spvGatherReturn = decltype(declval<Tex>().gather(declval<sampler>(), declval<Tp>()...));"); |
| 6603 | statement(""); |
| 6604 | break; |
| 6605 | |
| 6606 | case SPVFuncImplGatherCompareReturn: |
| 6607 | statement("template<typename Tex, typename... Tp>"); |
| 6608 | statement("using spvGatherCompareReturn = decltype(declval<Tex>().gather_compare(declval<sampler>(), declval<Tp>()...));"); |
| 6609 | statement(""); |
| 6610 | break; |
| 6611 | |
| 6612 | case SPVFuncImplGatherSwizzle: |
| 6613 | statement("// Wrapper function that swizzles texture gathers."); |
| 6614 | statement("template<typename Tex, typename... Ts>"); |
| 6615 | statement("inline spvGatherReturn<Tex, Ts...> spvGatherSwizzle(const thread Tex& t, sampler s, " |
| 6616 | "uint sw, component c, Ts... params) METAL_CONST_ARG(c)"); |
| 6617 | begin_scope(); |
| 6618 | statement("if (sw)"); |
| 6619 | begin_scope(); |
| 6620 | statement("switch (spvSwizzle((sw >> (uint(c) * 8)) & 0xFF))"); |
| 6621 | begin_scope(); |
| 6622 | statement("case spvSwizzle::none:"); |
| 6623 | statement(" break;"); |
| 6624 | statement("case spvSwizzle::zero:"); |
| 6625 | statement(" return spvGatherReturn<Tex, Ts...>(0, 0, 0, 0);"); |
| 6626 | statement("case spvSwizzle::one:"); |
| 6627 | statement(" return spvGatherReturn<Tex, Ts...>(1, 1, 1, 1);"); |
| 6628 | statement("case spvSwizzle::red:"); |
| 6629 | statement(" return t.gather(s, params..., component::x);"); |
| 6630 | statement("case spvSwizzle::green:"); |
| 6631 | statement(" return t.gather(s, params..., component::y);"); |
| 6632 | statement("case spvSwizzle::blue:"); |
| 6633 | statement(" return t.gather(s, params..., component::z);"); |
| 6634 | statement("case spvSwizzle::alpha:"); |
| 6635 | statement(" return t.gather(s, params..., component::w);"); |
| 6636 | end_scope(); |
| 6637 | end_scope(); |
| 6638 | // texture::gather insists on its component parameter being a constant |
| 6639 | // expression, so we need this silly workaround just to compile the shader. |
| 6640 | statement("switch (c)"); |
| 6641 | begin_scope(); |
| 6642 | statement("case component::x:"); |
| 6643 | statement(" return t.gather(s, params..., component::x);"); |
| 6644 | statement("case component::y:"); |
| 6645 | statement(" return t.gather(s, params..., component::y);"); |
| 6646 | statement("case component::z:"); |
| 6647 | statement(" return t.gather(s, params..., component::z);"); |
| 6648 | statement("case component::w:"); |
| 6649 | statement(" return t.gather(s, params..., component::w);"); |
| 6650 | end_scope(); |
| 6651 | end_scope(); |
| 6652 | statement(""); |
| 6653 | break; |
| 6654 | |
| 6655 | case SPVFuncImplGatherCompareSwizzle: |
| 6656 | statement("// Wrapper function that swizzles depth texture gathers."); |
| 6657 | statement("template<typename Tex, typename... Ts>"); |
| 6658 | statement("inline spvGatherCompareReturn<Tex, Ts...> spvGatherCompareSwizzle(const thread Tex& t, sampler s, uint sw, Ts... params)"); |
| 6659 | begin_scope(); |
| 6660 | statement("if (sw)"); |
| 6661 | begin_scope(); |
| 6662 | statement("switch (spvSwizzle(sw & 0xFF))"); |
| 6663 | begin_scope(); |
| 6664 | statement("case spvSwizzle::none:"); |
| 6665 | statement("case spvSwizzle::red:"); |
| 6666 | statement(" break;"); |
| 6667 | statement("case spvSwizzle::zero:"); |
| 6668 | statement("case spvSwizzle::green:"); |
| 6669 | statement("case spvSwizzle::blue:"); |
| 6670 | statement("case spvSwizzle::alpha:"); |
| 6671 | statement(" return spvGatherCompareReturn<Tex, Ts...>(0, 0, 0, 0);"); |
| 6672 | statement("case spvSwizzle::one:"); |
| 6673 | statement(" return spvGatherCompareReturn<Tex, Ts...>(1, 1, 1, 1);"); |
| 6674 | end_scope(); |
| 6675 | end_scope(); |
| 6676 | statement("return t.gather_compare(s, params...);"); |
| 6677 | end_scope(); |
| 6678 | statement(""); |
| 6679 | break; |
| 6680 | |
| 6681 | case SPVFuncImplGatherConstOffsets: |
| 6682 | // Because we are passing a texture reference, we have to output an overloaded version of this function for each address space. |
| 6683 | for (uint32_t i = 0; i < texture_addr_space_count; i++) |
| 6684 | { |
| 6685 | statement("// Wrapper function that processes a ", texture_addr_spaces[i], " texture gather with a constant offset array."); |
| 6686 | statement("template<typename Tex, typename Toff, typename... Tp>"); |
| 6687 | statement("inline spvGatherReturn<Tex, Tp...> spvGatherConstOffsets(const ", texture_addr_spaces[i], " Tex& t, sampler s, " |
| 6688 | "Toff coffsets, component c, Tp... params) METAL_CONST_ARG(c)"); |
| 6689 | begin_scope(); |
| 6690 | statement("spvGatherReturn<Tex, Tp...> rslts[4];"); |
| 6691 | statement("for (uint i = 0; i < 4; i++)"); |
| 6692 | begin_scope(); |
| 6693 | statement("switch (c)"); |
| 6694 | begin_scope(); |
| 6695 | // Work around texture::gather() requiring its component parameter to be a constant expression |
| 6696 | statement("case component::x:"); |
| 6697 | statement(" rslts[i] = t.gather(s, params..., coffsets[i], component::x);"); |
| 6698 | statement(" break;"); |
| 6699 | statement("case component::y:"); |
| 6700 | statement(" rslts[i] = t.gather(s, params..., coffsets[i], component::y);"); |
| 6701 | statement(" break;"); |
| 6702 | statement("case component::z:"); |
| 6703 | statement(" rslts[i] = t.gather(s, params..., coffsets[i], component::z);"); |
| 6704 | statement(" break;"); |
| 6705 | statement("case component::w:"); |
| 6706 | statement(" rslts[i] = t.gather(s, params..., coffsets[i], component::w);"); |
| 6707 | statement(" break;"); |
| 6708 | end_scope(); |
| 6709 | end_scope(); |
| 6710 | // Pull all values from the i0j0 component of each gather footprint |
| 6711 | statement("return spvGatherReturn<Tex, Tp...>(rslts[0].w, rslts[1].w, rslts[2].w, rslts[3].w);"); |
| 6712 | end_scope(); |
| 6713 | statement(""); |
| 6714 | } |
| 6715 | break; |
| 6716 | |
| 6717 | case SPVFuncImplGatherCompareConstOffsets: |
| 6718 | // Because we are passing a texture reference, we have to output an overloaded version of this function for each address space. |
| 6719 | for (uint32_t i = 0; i < texture_addr_space_count; i++) |
| 6720 | { |
| 6721 | statement("// Wrapper function that processes a ", texture_addr_spaces[i], " texture gather with a constant offset array."); |
| 6722 | statement("template<typename Tex, typename Toff, typename... Tp>"); |
| 6723 | statement("inline spvGatherCompareReturn<Tex, Tp...> spvGatherCompareConstOffsets(const ", texture_addr_spaces[i], " Tex& t, sampler s, " |
| 6724 | "Toff coffsets, Tp... params)"); |
| 6725 | begin_scope(); |
| 6726 | statement("spvGatherCompareReturn<Tex, Tp...> rslts[4];"); |
| 6727 | statement("for (uint i = 0; i < 4; i++)"); |
| 6728 | begin_scope(); |
| 6729 | statement(" rslts[i] = t.gather_compare(s, params..., coffsets[i]);"); |
| 6730 | end_scope(); |
| 6731 | // Pull all values from the i0j0 component of each gather footprint |
| 6732 | statement("return spvGatherCompareReturn<Tex, Tp...>(rslts[0].w, rslts[1].w, rslts[2].w, rslts[3].w);"); |
| 6733 | end_scope(); |
| 6734 | statement(""); |
| 6735 | } |
| 6736 | break; |
| 6737 | |
| 6738 | case SPVFuncImplSubgroupBroadcast: |
| 6739 | // Metal doesn't allow broadcasting boolean values directly, but we can work around that by broadcasting |
| 6740 | // them as integers. |
| 6741 | statement("template<typename T>"); |
| 6742 | statement("inline T spvSubgroupBroadcast(T value, ushort lane)"); |
| 6743 | begin_scope(); |
| 6744 | if (msl_options.use_quadgroup_operation()) |
| 6745 | statement("return quad_broadcast(value, lane);"); |
| 6746 | else |
| 6747 | statement("return simd_broadcast(value, lane);"); |
| 6748 | end_scope(); |
| 6749 | statement(""); |
| 6750 | statement("template<>"); |
| 6751 | statement("inline bool spvSubgroupBroadcast(bool value, ushort lane)"); |
| 6752 | begin_scope(); |
| 6753 | if (msl_options.use_quadgroup_operation()) |
| 6754 | statement("return !!quad_broadcast((ushort)value, lane);"); |
| 6755 | else |
| 6756 | statement("return !!simd_broadcast((ushort)value, lane);"); |
| 6757 | end_scope(); |
| 6758 | statement(""); |
| 6759 | statement("template<uint N>"); |
| 6760 | statement("inline vec<bool, N> spvSubgroupBroadcast(vec<bool, N> value, ushort lane)"); |
| 6761 | begin_scope(); |
| 6762 | if (msl_options.use_quadgroup_operation()) |
| 6763 | statement("return (vec<bool, N>)quad_broadcast((vec<ushort, N>)value, lane);"); |
| 6764 | else |
| 6765 | statement("return (vec<bool, N>)simd_broadcast((vec<ushort, N>)value, lane);"); |
| 6766 | end_scope(); |
| 6767 | statement(""); |
| 6768 | break; |
| 6769 | |
| 6770 | case SPVFuncImplSubgroupBroadcastFirst: |
| 6771 | statement("template<typename T>"); |
| 6772 | statement("inline T spvSubgroupBroadcastFirst(T value)"); |
| 6773 | begin_scope(); |
| 6774 | if (msl_options.use_quadgroup_operation()) |
| 6775 | statement("return quad_broadcast_first(value);"); |
| 6776 | else |
| 6777 | statement("return simd_broadcast_first(value);"); |
| 6778 | end_scope(); |
| 6779 | statement(""); |
| 6780 | statement("template<>"); |
| 6781 | statement("inline bool spvSubgroupBroadcastFirst(bool value)"); |
| 6782 | begin_scope(); |
| 6783 | if (msl_options.use_quadgroup_operation()) |
| 6784 | statement("return !!quad_broadcast_first((ushort)value);"); |
| 6785 | else |
| 6786 | statement("return !!simd_broadcast_first((ushort)value);"); |
| 6787 | end_scope(); |
| 6788 | statement(""); |
| 6789 | statement("template<uint N>"); |
| 6790 | statement("inline vec<bool, N> spvSubgroupBroadcastFirst(vec<bool, N> value)"); |
| 6791 | begin_scope(); |
| 6792 | if (msl_options.use_quadgroup_operation()) |
| 6793 | statement("return (vec<bool, N>)quad_broadcast_first((vec<ushort, N>)value);"); |
| 6794 | else |
| 6795 | statement("return (vec<bool, N>)simd_broadcast_first((vec<ushort, N>)value);"); |
| 6796 | end_scope(); |
| 6797 | statement(""); |
| 6798 | break; |
| 6799 | |
| 6800 | case SPVFuncImplSubgroupBallot: |
| 6801 | statement("inline uint4 spvSubgroupBallot(bool value)"); |
| 6802 | begin_scope(); |
| 6803 | if (msl_options.use_quadgroup_operation()) |
| 6804 | { |
| 6805 | statement("return uint4((quad_vote::vote_t)quad_ballot(value), 0, 0, 0);"); |
| 6806 | } |
| 6807 | else if (msl_options.is_ios()) |
| 6808 | { |
| 6809 | // The current simd_vote on iOS uses a 32-bit integer-like object. |
| 6810 | statement("return uint4((simd_vote::vote_t)simd_ballot(value), 0, 0, 0);"); |
| 6811 | } |
| 6812 | else |
| 6813 | { |
| 6814 | statement("simd_vote vote = simd_ballot(value);"); |
| 6815 | statement("// simd_ballot() returns a 64-bit integer-like object, but"); |
| 6816 | statement("// SPIR-V callers expect a uint4. We must convert."); |
| 6817 | statement("// FIXME: This won't include higher bits if Apple ever supports"); |
| 6818 | statement("// 128 lanes in an SIMD-group."); |
| 6819 | statement("return uint4(as_type<uint2>((simd_vote::vote_t)vote), 0, 0);"); |
| 6820 | } |
| 6821 | end_scope(); |
| 6822 | statement(""); |
| 6823 | break; |
| 6824 | |
| 6825 | case SPVFuncImplSubgroupBallotBitExtract: |
| 6826 | statement("inline bool spvSubgroupBallotBitExtract(uint4 ballot, uint bit)"); |
| 6827 | begin_scope(); |
| 6828 | statement("return !!extract_bits(ballot[bit / 32], bit % 32, 1);"); |
| 6829 | end_scope(); |
| 6830 | statement(""); |
| 6831 | break; |
| 6832 | |
| 6833 | case SPVFuncImplSubgroupBallotFindLSB: |
| 6834 | statement("inline uint spvSubgroupBallotFindLSB(uint4 ballot, uint gl_SubgroupSize)"); |
| 6835 | begin_scope(); |
| 6836 | if (msl_options.is_ios()) |
| 6837 | { |
| 6838 | statement("uint4 mask = uint4(extract_bits(0xFFFFFFFF, 0, gl_SubgroupSize), uint3(0));"); |
| 6839 | } |
| 6840 | else |
| 6841 | { |
| 6842 | statement("uint4 mask = uint4(extract_bits(0xFFFFFFFF, 0, min(gl_SubgroupSize, 32u)), " |
| 6843 | "extract_bits(0xFFFFFFFF, 0, (uint)max((int)gl_SubgroupSize - 32, 0)), uint2(0));"); |
| 6844 | } |
| 6845 | statement("ballot &= mask;"); |
| 6846 | statement("return select(ctz(ballot.x), select(32 + ctz(ballot.y), select(64 + ctz(ballot.z), select(96 + " |
| 6847 | "ctz(ballot.w), uint(-1), ballot.w == 0), ballot.z == 0), ballot.y == 0), ballot.x == 0);"); |
| 6848 | end_scope(); |
| 6849 | statement(""); |
| 6850 | break; |
| 6851 | |
| 6852 | case SPVFuncImplSubgroupBallotFindMSB: |
| 6853 | statement("inline uint spvSubgroupBallotFindMSB(uint4 ballot, uint gl_SubgroupSize)"); |
| 6854 | begin_scope(); |
| 6855 | if (msl_options.is_ios()) |
| 6856 | { |
| 6857 | statement("uint4 mask = uint4(extract_bits(0xFFFFFFFF, 0, gl_SubgroupSize), uint3(0));"); |
| 6858 | } |
| 6859 | else |
| 6860 | { |
| 6861 | statement("uint4 mask = uint4(extract_bits(0xFFFFFFFF, 0, min(gl_SubgroupSize, 32u)), " |
| 6862 | "extract_bits(0xFFFFFFFF, 0, (uint)max((int)gl_SubgroupSize - 32, 0)), uint2(0));"); |
| 6863 | } |
| 6864 | statement("ballot &= mask;"); |
| 6865 | statement("return select(128 - (clz(ballot.w) + 1), select(96 - (clz(ballot.z) + 1), select(64 - " |
| 6866 | "(clz(ballot.y) + 1), select(32 - (clz(ballot.x) + 1), uint(-1), ballot.x == 0), ballot.y == 0), " |
| 6867 | "ballot.z == 0), ballot.w == 0);"); |
| 6868 | end_scope(); |
| 6869 | statement(""); |
| 6870 | break; |
| 6871 | |
| 6872 | case SPVFuncImplSubgroupBallotBitCount: |
| 6873 | statement("inline uint spvPopCount4(uint4 ballot)"); |
| 6874 | begin_scope(); |
| 6875 | statement("return popcount(ballot.x) + popcount(ballot.y) + popcount(ballot.z) + popcount(ballot.w);"); |
| 6876 | end_scope(); |
| 6877 | statement(""); |
| 6878 | statement("inline uint spvSubgroupBallotBitCount(uint4 ballot, uint gl_SubgroupSize)"); |
| 6879 | begin_scope(); |
| 6880 | if (msl_options.is_ios()) |
| 6881 | { |
| 6882 | statement("uint4 mask = uint4(extract_bits(0xFFFFFFFF, 0, gl_SubgroupSize), uint3(0));"); |
| 6883 | } |
| 6884 | else |
| 6885 | { |
| 6886 | statement("uint4 mask = uint4(extract_bits(0xFFFFFFFF, 0, min(gl_SubgroupSize, 32u)), " |
| 6887 | "extract_bits(0xFFFFFFFF, 0, (uint)max((int)gl_SubgroupSize - 32, 0)), uint2(0));"); |
| 6888 | } |
| 6889 | statement("return spvPopCount4(ballot & mask);"); |
| 6890 | end_scope(); |
| 6891 | statement(""); |
| 6892 | statement("inline uint spvSubgroupBallotInclusiveBitCount(uint4 ballot, uint gl_SubgroupInvocationID)"); |
| 6893 | begin_scope(); |
| 6894 | if (msl_options.is_ios()) |
| 6895 | { |
| 6896 | statement("uint4 mask = uint4(extract_bits(0xFFFFFFFF, 0, gl_SubgroupInvocationID + 1), uint3(0));"); |
| 6897 | } |
| 6898 | else |
| 6899 | { |
| 6900 | statement("uint4 mask = uint4(extract_bits(0xFFFFFFFF, 0, min(gl_SubgroupInvocationID + 1, 32u)), " |
| 6901 | "extract_bits(0xFFFFFFFF, 0, (uint)max((int)gl_SubgroupInvocationID + 1 - 32, 0)), " |
| 6902 | "uint2(0));"); |
| 6903 | } |
| 6904 | statement("return spvPopCount4(ballot & mask);"); |
| 6905 | end_scope(); |
| 6906 | statement(""); |
| 6907 | statement("inline uint spvSubgroupBallotExclusiveBitCount(uint4 ballot, uint gl_SubgroupInvocationID)"); |
| 6908 | begin_scope(); |
| 6909 | if (msl_options.is_ios()) |
| 6910 | { |
| 6911 | statement("uint4 mask = uint4(extract_bits(0xFFFFFFFF, 0, gl_SubgroupInvocationID), uint2(0));"); |
| 6912 | } |
| 6913 | else |
| 6914 | { |
| 6915 | statement("uint4 mask = uint4(extract_bits(0xFFFFFFFF, 0, min(gl_SubgroupInvocationID, 32u)), " |
| 6916 | "extract_bits(0xFFFFFFFF, 0, (uint)max((int)gl_SubgroupInvocationID - 32, 0)), uint2(0));"); |
| 6917 | } |
| 6918 | statement("return spvPopCount4(ballot & mask);"); |
| 6919 | end_scope(); |
| 6920 | statement(""); |
| 6921 | break; |
| 6922 | |
| 6923 | case SPVFuncImplSubgroupAllEqual: |
| 6924 | // Metal doesn't provide a function to evaluate this directly. But, we can |
| 6925 | // implement this by comparing every thread's value to one thread's value |
| 6926 | // (in this case, the value of the first active thread). Then, by the transitive |
| 6927 | // property of equality, if all comparisons return true, then they are all equal. |
| 6928 | statement("template<typename T>"); |
| 6929 | statement("inline bool spvSubgroupAllEqual(T value)"); |
| 6930 | begin_scope(); |
| 6931 | if (msl_options.use_quadgroup_operation()) |
| 6932 | statement("return quad_all(all(value == quad_broadcast_first(value)));"); |
| 6933 | else |
| 6934 | statement("return simd_all(all(value == simd_broadcast_first(value)));"); |
| 6935 | end_scope(); |
| 6936 | statement(""); |
| 6937 | statement("template<>"); |
| 6938 | statement("inline bool spvSubgroupAllEqual(bool value)"); |
| 6939 | begin_scope(); |
| 6940 | if (msl_options.use_quadgroup_operation()) |
| 6941 | statement("return quad_all(value) || !quad_any(value);"); |
| 6942 | else |
| 6943 | statement("return simd_all(value) || !simd_any(value);"); |
| 6944 | end_scope(); |
| 6945 | statement(""); |
| 6946 | statement("template<uint N>"); |
| 6947 | statement("inline bool spvSubgroupAllEqual(vec<bool, N> value)"); |
| 6948 | begin_scope(); |
| 6949 | if (msl_options.use_quadgroup_operation()) |
| 6950 | statement("return quad_all(all(value == (vec<bool, N>)quad_broadcast_first((vec<ushort, N>)value)));"); |
| 6951 | else |
| 6952 | statement("return simd_all(all(value == (vec<bool, N>)simd_broadcast_first((vec<ushort, N>)value)));"); |
| 6953 | end_scope(); |
| 6954 | statement(""); |
| 6955 | break; |
| 6956 | |
| 6957 | case SPVFuncImplSubgroupShuffle: |
| 6958 | statement("template<typename T>"); |
| 6959 | statement("inline T spvSubgroupShuffle(T value, ushort lane)"); |
| 6960 | begin_scope(); |
| 6961 | if (msl_options.use_quadgroup_operation()) |
| 6962 | statement("return quad_shuffle(value, lane);"); |
| 6963 | else |
| 6964 | statement("return simd_shuffle(value, lane);"); |
| 6965 | end_scope(); |
| 6966 | statement(""); |
| 6967 | statement("template<>"); |
| 6968 | statement("inline bool spvSubgroupShuffle(bool value, ushort lane)"); |
| 6969 | begin_scope(); |
| 6970 | if (msl_options.use_quadgroup_operation()) |
| 6971 | statement("return !!quad_shuffle((ushort)value, lane);"); |
| 6972 | else |
| 6973 | statement("return !!simd_shuffle((ushort)value, lane);"); |
| 6974 | end_scope(); |
| 6975 | statement(""); |
| 6976 | statement("template<uint N>"); |
| 6977 | statement("inline vec<bool, N> spvSubgroupShuffle(vec<bool, N> value, ushort lane)"); |
| 6978 | begin_scope(); |
| 6979 | if (msl_options.use_quadgroup_operation()) |
| 6980 | statement("return (vec<bool, N>)quad_shuffle((vec<ushort, N>)value, lane);"); |
| 6981 | else |
| 6982 | statement("return (vec<bool, N>)simd_shuffle((vec<ushort, N>)value, lane);"); |
| 6983 | end_scope(); |
| 6984 | statement(""); |
| 6985 | break; |
| 6986 | |
| 6987 | case SPVFuncImplSubgroupShuffleXor: |
| 6988 | statement("template<typename T>"); |
| 6989 | statement("inline T spvSubgroupShuffleXor(T value, ushort mask)"); |
| 6990 | begin_scope(); |
| 6991 | if (msl_options.use_quadgroup_operation()) |
| 6992 | statement("return quad_shuffle_xor(value, mask);"); |
| 6993 | else |
| 6994 | statement("return simd_shuffle_xor(value, mask);"); |
| 6995 | end_scope(); |
| 6996 | statement(""); |
| 6997 | statement("template<>"); |
| 6998 | statement("inline bool spvSubgroupShuffleXor(bool value, ushort mask)"); |
| 6999 | begin_scope(); |
| 7000 | if (msl_options.use_quadgroup_operation()) |
| 7001 | statement("return !!quad_shuffle_xor((ushort)value, mask);"); |
| 7002 | else |
| 7003 | statement("return !!simd_shuffle_xor((ushort)value, mask);"); |
| 7004 | end_scope(); |
| 7005 | statement(""); |
| 7006 | statement("template<uint N>"); |
| 7007 | statement("inline vec<bool, N> spvSubgroupShuffleXor(vec<bool, N> value, ushort mask)"); |
| 7008 | begin_scope(); |
| 7009 | if (msl_options.use_quadgroup_operation()) |
| 7010 | statement("return (vec<bool, N>)quad_shuffle_xor((vec<ushort, N>)value, mask);"); |
| 7011 | else |
| 7012 | statement("return (vec<bool, N>)simd_shuffle_xor((vec<ushort, N>)value, mask);"); |
| 7013 | end_scope(); |
| 7014 | statement(""); |
| 7015 | break; |
| 7016 | |
| 7017 | case SPVFuncImplSubgroupShuffleUp: |
| 7018 | statement("template<typename T>"); |
| 7019 | statement("inline T spvSubgroupShuffleUp(T value, ushort delta)"); |
| 7020 | begin_scope(); |
| 7021 | if (msl_options.use_quadgroup_operation()) |
| 7022 | statement("return quad_shuffle_up(value, delta);"); |
| 7023 | else |
| 7024 | statement("return simd_shuffle_up(value, delta);"); |
| 7025 | end_scope(); |
| 7026 | statement(""); |
| 7027 | statement("template<>"); |
| 7028 | statement("inline bool spvSubgroupShuffleUp(bool value, ushort delta)"); |
| 7029 | begin_scope(); |
| 7030 | if (msl_options.use_quadgroup_operation()) |
| 7031 | statement("return !!quad_shuffle_up((ushort)value, delta);"); |
| 7032 | else |
| 7033 | statement("return !!simd_shuffle_up((ushort)value, delta);"); |
| 7034 | end_scope(); |
| 7035 | statement(""); |
| 7036 | statement("template<uint N>"); |
| 7037 | statement("inline vec<bool, N> spvSubgroupShuffleUp(vec<bool, N> value, ushort delta)"); |
| 7038 | begin_scope(); |
| 7039 | if (msl_options.use_quadgroup_operation()) |
| 7040 | statement("return (vec<bool, N>)quad_shuffle_up((vec<ushort, N>)value, delta);"); |
| 7041 | else |
| 7042 | statement("return (vec<bool, N>)simd_shuffle_up((vec<ushort, N>)value, delta);"); |
| 7043 | end_scope(); |
| 7044 | statement(""); |
| 7045 | break; |
| 7046 | |
| 7047 | case SPVFuncImplSubgroupShuffleDown: |
| 7048 | statement("template<typename T>"); |
| 7049 | statement("inline T spvSubgroupShuffleDown(T value, ushort delta)"); |
| 7050 | begin_scope(); |
| 7051 | if (msl_options.use_quadgroup_operation()) |
| 7052 | statement("return quad_shuffle_down(value, delta);"); |
| 7053 | else |
| 7054 | statement("return simd_shuffle_down(value, delta);"); |
| 7055 | end_scope(); |
| 7056 | statement(""); |
| 7057 | statement("template<>"); |
| 7058 | statement("inline bool spvSubgroupShuffleDown(bool value, ushort delta)"); |
| 7059 | begin_scope(); |
| 7060 | if (msl_options.use_quadgroup_operation()) |
| 7061 | statement("return !!quad_shuffle_down((ushort)value, delta);"); |
| 7062 | else |
| 7063 | statement("return !!simd_shuffle_down((ushort)value, delta);"); |
| 7064 | end_scope(); |
| 7065 | statement(""); |
| 7066 | statement("template<uint N>"); |
| 7067 | statement("inline vec<bool, N> spvSubgroupShuffleDown(vec<bool, N> value, ushort delta)"); |
| 7068 | begin_scope(); |
| 7069 | if (msl_options.use_quadgroup_operation()) |
| 7070 | statement("return (vec<bool, N>)quad_shuffle_down((vec<ushort, N>)value, delta);"); |
| 7071 | else |
| 7072 | statement("return (vec<bool, N>)simd_shuffle_down((vec<ushort, N>)value, delta);"); |
| 7073 | end_scope(); |
| 7074 | statement(""); |
| 7075 | break; |
| 7076 | |
| 7077 | case SPVFuncImplSubgroupRotate: |
| 7078 | statement("template<typename T>"); |
| 7079 | statement("inline T spvSubgroupRotate(T value, ushort delta)"); |
| 7080 | begin_scope(); |
| 7081 | if (msl_options.use_quadgroup_operation()) |
| 7082 | statement("return quad_shuffle_rotate_down(value, delta);"); |
| 7083 | else |
| 7084 | statement("return simd_shuffle_rotate_down(value, delta);"); |
| 7085 | end_scope(); |
| 7086 | statement(""); |
| 7087 | statement("template<>"); |
| 7088 | statement("inline bool spvSubgroupRotate(bool value, ushort delta)"); |
| 7089 | begin_scope(); |
| 7090 | if (msl_options.use_quadgroup_operation()) |
| 7091 | statement("return !!quad_shuffle_rotate_down((ushort)value, delta);"); |
| 7092 | else |
| 7093 | statement("return !!simd_shuffle_rotate_down((ushort)value, delta);"); |
| 7094 | end_scope(); |
| 7095 | statement(""); |
| 7096 | statement("template<uint N>"); |
| 7097 | statement("inline vec<bool, N> spvSubgroupRotate(vec<bool, N> value, ushort delta)"); |
| 7098 | begin_scope(); |
| 7099 | if (msl_options.use_quadgroup_operation()) |
| 7100 | statement("return (vec<bool, N>)quad_shuffle_rotate_down((vec<ushort, N>)value, delta);"); |
| 7101 | else |
| 7102 | statement("return (vec<bool, N>)simd_shuffle_rotate_down((vec<ushort, N>)value, delta);"); |
| 7103 | end_scope(); |
| 7104 | statement(""); |
| 7105 | break; |
| 7106 | |
| 7107 | // C++ disallows partial specializations of function templates, |
| 7108 | // hence the use of a struct. |
| 7109 | // clang-format off |
| 7110 | #define FUNC_SUBGROUP_CLUSTERED(spv, msl, combine, op, ident) \ |
| 7111 | case SPVFuncImplSubgroupClustered##spv: \ |
| 7112 | statement("template<uint N, uint offset>"); \ |
| 7113 | statement("struct spvClustered" #spv "Detail;"); \ |
| 7114 | statement(""); \ |
| 7115 | statement("// Base cases"); \ |
| 7116 | statement("template<>"); \ |
| 7117 | statement("struct spvClustered" #spv "Detail<1, 0>"); \ |
| 7118 | begin_scope(); \ |
| 7119 | statement("template<typename T>"); \ |
| 7120 | statement("static T op(T value, uint)"); \ |
| 7121 | begin_scope(); \ |
| 7122 | statement("return value;"); \ |
| 7123 | end_scope(); \ |
| 7124 | end_scope_decl(); \ |
| 7125 | statement(""); \ |
| 7126 | statement("template<uint offset>"); \ |
| 7127 | statement("struct spvClustered" #spv "Detail<1, offset>"); \ |
| 7128 | begin_scope(); \ |
| 7129 | statement("template<typename T>"); \ |
| 7130 | statement("static T op(T value, uint lid)"); \ |
| 7131 | begin_scope(); \ |
| 7132 | statement("// If the target lane is inactive, then return identity."); \ |
| 7133 | if (msl_options.use_quadgroup_operation()) \ |
| 7134 | statement("if (!extract_bits((quad_vote::vote_t)quad_active_threads_mask(), (lid ^ offset), 1))"); \ |
| 7135 | else \ |
| 7136 | statement("if (!extract_bits(as_type<uint2>((simd_vote::vote_t)simd_active_threads_mask())[(lid ^ offset) / 32], (lid ^ offset) % 32, 1))"); \ |
| 7137 | statement(" return " #ident ";"); \ |
| 7138 | if (msl_options.use_quadgroup_operation()) \ |
| 7139 | statement("return quad_shuffle_xor(value, offset);"); \ |
| 7140 | else \ |
| 7141 | statement("return simd_shuffle_xor(value, offset);"); \ |
| 7142 | end_scope(); \ |
| 7143 | end_scope_decl(); \ |
| 7144 | statement(""); \ |
| 7145 | statement("template<>"); \ |
| 7146 | statement("struct spvClustered" #spv "Detail<4, 0>"); \ |
| 7147 | begin_scope(); \ |
| 7148 | statement("template<typename T>"); \ |
| 7149 | statement("static T op(T value, uint)"); \ |
| 7150 | begin_scope(); \ |
| 7151 | statement("return quad_" #msl "(value);"); \ |
| 7152 | end_scope(); \ |
| 7153 | end_scope_decl(); \ |
| 7154 | statement(""); \ |
| 7155 | statement("template<uint offset>"); \ |
| 7156 | statement("struct spvClustered" #spv "Detail<4, offset>"); \ |
| 7157 | begin_scope(); \ |
| 7158 | statement("template<typename T>"); \ |
| 7159 | statement("static T op(T value, uint lid)"); \ |
| 7160 | begin_scope(); \ |
| 7161 | statement("// Here, we care if any of the lanes in the quad are active."); \ |
| 7162 | statement("uint quad_mask = extract_bits(as_type<uint2>((simd_vote::vote_t)simd_active_threads_mask())[(lid ^ offset) / 32], ((lid ^ offset) % 32) & ~3, 4);"); \ |
| 7163 | statement("if (!quad_mask)"); \ |
| 7164 | statement(" return " #ident ";"); \ |
| 7165 | statement("// But we need to make sure we shuffle from an active lane."); \ |
| 7166 | if (msl_options.use_quadgroup_operation()) \ |
| 7167 | SPIRV_CROSS_THROW("Subgroup size with quadgroup operation cannot exceed 4."); \ |
| 7168 | else \ |
| 7169 | statement("return simd_shuffle(quad_" #msl "(value), ((lid ^ offset) & ~3) | ctz(quad_mask));"); \ |
| 7170 | end_scope(); \ |
| 7171 | end_scope_decl(); \ |
| 7172 | statement(""); \ |
| 7173 | statement("// General case"); \ |
| 7174 | statement("template<uint N, uint offset>"); \ |
| 7175 | statement("struct spvClustered" #spv "Detail"); \ |
| 7176 | begin_scope(); \ |
| 7177 | statement("template<typename T>"); \ |
| 7178 | statement("static T op(T value, uint lid)"); \ |
| 7179 | begin_scope(); \ |
| 7180 | statement("return " combine(msl, op, "spvClustered" #spv "Detail<N/2, offset>::op(value, lid)", "spvClustered" #spv "Detail<N/2, offset + N/2>::op(value, lid)") ";"); \ |
| 7181 | end_scope(); \ |
| 7182 | end_scope_decl(); \ |
| 7183 | statement(""); \ |
| 7184 | statement("template<uint N, typename T>"); \ |
| 7185 | statement("T spvClustered_" #msl "(T value, uint lid)"); \ |
| 7186 | begin_scope(); \ |
| 7187 | statement("return spvClustered" #spv "Detail<N, 0>::op(value, lid);"); \ |
| 7188 | end_scope(); \ |
| 7189 | statement(""); \ |
| 7190 | break |
| 7191 | #define BINOP(msl, op, l, r) l " " #op " " r |
| 7192 | #define BINFUNC(msl, op, l, r) #msl "(" l ", " r ")" |
| 7193 | |
| 7194 | FUNC_SUBGROUP_CLUSTERED(Add, sum, BINOP, +, 0); |
| 7195 | FUNC_SUBGROUP_CLUSTERED(Mul, product, BINOP, *, 1); |
| 7196 | FUNC_SUBGROUP_CLUSTERED(Min, min, BINFUNC, , numeric_limits<T>::max()); |
| 7197 | FUNC_SUBGROUP_CLUSTERED(Max, max, BINFUNC, , numeric_limits<T>::min()); |
| 7198 | FUNC_SUBGROUP_CLUSTERED(And, and, BINOP, &, ~T(0)); |
| 7199 | FUNC_SUBGROUP_CLUSTERED(Or, or, BINOP, |, 0); |
| 7200 | FUNC_SUBGROUP_CLUSTERED(Xor, xor, BINOP, ^, 0); |
| 7201 | // clang-format on |
| 7202 | #undef FUNC_SUBGROUP_CLUSTERED |
| 7203 | #undef BINOP |
| 7204 | #undef BINFUNC |
| 7205 | |
| 7206 | case SPVFuncImplQuadBroadcast: |
| 7207 | statement("template<typename T>"); |
| 7208 | statement("inline T spvQuadBroadcast(T value, uint lane)"); |
| 7209 | begin_scope(); |
| 7210 | statement("return quad_broadcast(value, lane);"); |
| 7211 | end_scope(); |
| 7212 | statement(""); |
| 7213 | statement("template<>"); |
| 7214 | statement("inline bool spvQuadBroadcast(bool value, uint lane)"); |
| 7215 | begin_scope(); |
| 7216 | statement("return !!quad_broadcast((ushort)value, lane);"); |
| 7217 | end_scope(); |
| 7218 | statement(""); |
| 7219 | statement("template<uint N>"); |
| 7220 | statement("inline vec<bool, N> spvQuadBroadcast(vec<bool, N> value, uint lane)"); |
| 7221 | begin_scope(); |
| 7222 | statement("return (vec<bool, N>)quad_broadcast((vec<ushort, N>)value, lane);"); |
| 7223 | end_scope(); |
| 7224 | statement(""); |
| 7225 | break; |
| 7226 | |
| 7227 | case SPVFuncImplQuadSwap: |
| 7228 | // We can implement this easily based on the following table giving |
| 7229 | // the target lane ID from the direction and current lane ID: |
| 7230 | // Direction |
| 7231 | // | 0 | 1 | 2 | |
| 7232 | // ---+---+---+---+ |
| 7233 | // L 0 | 1 2 3 |
| 7234 | // a 1 | 0 3 2 |
| 7235 | // n 2 | 3 0 1 |
| 7236 | // e 3 | 2 1 0 |
| 7237 | // Notice that target = source ^ (direction + 1). |
| 7238 | statement("template<typename T>"); |
| 7239 | statement("inline T spvQuadSwap(T value, uint dir)"); |
| 7240 | begin_scope(); |
| 7241 | statement("return quad_shuffle_xor(value, dir + 1);"); |
| 7242 | end_scope(); |
| 7243 | statement(""); |
| 7244 | statement("template<>"); |
| 7245 | statement("inline bool spvQuadSwap(bool value, uint dir)"); |
| 7246 | begin_scope(); |
| 7247 | statement("return !!quad_shuffle_xor((ushort)value, dir + 1);"); |
| 7248 | end_scope(); |
| 7249 | statement(""); |
| 7250 | statement("template<uint N>"); |
| 7251 | statement("inline vec<bool, N> spvQuadSwap(vec<bool, N> value, uint dir)"); |
| 7252 | begin_scope(); |
| 7253 | statement("return (vec<bool, N>)quad_shuffle_xor((vec<ushort, N>)value, dir + 1);"); |
| 7254 | end_scope(); |
| 7255 | statement(""); |
| 7256 | break; |
| 7257 | |
| 7258 | case SPVFuncImplReflectScalar: |
| 7259 | // Metal does not support scalar versions of these functions. |
| 7260 | // Ensure fast-math is disabled to match Vulkan results. |
| 7261 | statement("template<typename T>"); |
| 7262 | statement("[[clang::optnone]] T spvReflect(T i, T n)"); |
| 7263 | begin_scope(); |
| 7264 | statement("return i - T(2) * i * n * n;"); |
| 7265 | end_scope(); |
| 7266 | statement(""); |
| 7267 | break; |
| 7268 | |
| 7269 | case SPVFuncImplRefractScalar: |
| 7270 | // Metal does not support scalar versions of these functions. |
| 7271 | statement("template<typename T>"); |
| 7272 | statement("inline T spvRefract(T i, T n, T eta)"); |
| 7273 | begin_scope(); |
| 7274 | statement("T NoI = n * i;"); |
| 7275 | statement("T NoI2 = NoI * NoI;"); |
| 7276 | statement("T k = T(1) - eta * eta * (T(1) - NoI2);"); |
| 7277 | statement("if (k < T(0))"); |
| 7278 | begin_scope(); |
| 7279 | statement("return T(0);"); |
| 7280 | end_scope(); |
| 7281 | statement("else"); |
| 7282 | begin_scope(); |
| 7283 | statement("return eta * i - (eta * NoI + sqrt(k)) * n;"); |
| 7284 | end_scope(); |
| 7285 | end_scope(); |
| 7286 | statement(""); |
| 7287 | break; |
| 7288 | |
| 7289 | case SPVFuncImplFaceForwardScalar: |
| 7290 | // Metal does not support scalar versions of these functions. |
| 7291 | statement("template<typename T>"); |
| 7292 | statement("inline T spvFaceForward(T n, T i, T nref)"); |
| 7293 | begin_scope(); |
| 7294 | statement("return i * nref < T(0) ? n : -n;"); |
| 7295 | end_scope(); |
| 7296 | statement(""); |
| 7297 | break; |
| 7298 | |
| 7299 | case SPVFuncImplChromaReconstructNearest2Plane: |
| 7300 | statement("template<typename T, typename... LodOptions>"); |
| 7301 | statement("inline vec<T, 4> spvChromaReconstructNearest(texture2d<T> plane0, texture2d<T> plane1, sampler " |
| 7302 | "samp, float2 coord, LodOptions... options)"); |
| 7303 | begin_scope(); |
| 7304 | statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);"); |
| 7305 | statement("ycbcr.g = plane0.sample(samp, coord, options...).r;"); |
| 7306 | statement("ycbcr.br = plane1.sample(samp, coord, options...).rg;"); |
| 7307 | statement("return ycbcr;"); |
| 7308 | end_scope(); |
| 7309 | statement(""); |
| 7310 | break; |
| 7311 | |
| 7312 | case SPVFuncImplChromaReconstructNearest3Plane: |
| 7313 | statement("template<typename T, typename... LodOptions>"); |
| 7314 | statement("inline vec<T, 4> spvChromaReconstructNearest(texture2d<T> plane0, texture2d<T> plane1, " |
| 7315 | "texture2d<T> plane2, sampler samp, float2 coord, LodOptions... options)"); |
| 7316 | begin_scope(); |
| 7317 | statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);"); |
| 7318 | statement("ycbcr.g = plane0.sample(samp, coord, options...).r;"); |
| 7319 | statement("ycbcr.b = plane1.sample(samp, coord, options...).r;"); |
| 7320 | statement("ycbcr.r = plane2.sample(samp, coord, options...).r;"); |
| 7321 | statement("return ycbcr;"); |
| 7322 | end_scope(); |
| 7323 | statement(""); |
| 7324 | break; |
| 7325 | |
| 7326 | case SPVFuncImplChromaReconstructLinear422CositedEven2Plane: |
| 7327 | statement("template<typename T, typename... LodOptions>"); |
| 7328 | statement("inline vec<T, 4> spvChromaReconstructLinear422CositedEven(texture2d<T> plane0, texture2d<T> " |
| 7329 | "plane1, sampler samp, float2 coord, LodOptions... options)"); |
| 7330 | begin_scope(); |
| 7331 | statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);"); |
| 7332 | statement("ycbcr.g = plane0.sample(samp, coord, options...).r;"); |
| 7333 | statement("if (fract(coord.x * plane1.get_width()) != 0.0)"); |
| 7334 | begin_scope(); |
| 7335 | statement("ycbcr.br = vec<T, 2>(mix(plane1.sample(samp, coord, options...), " |
| 7336 | "plane1.sample(samp, coord, options..., int2(1, 0)), 0.5).rg);"); |
| 7337 | end_scope(); |
| 7338 | statement("else"); |
| 7339 | begin_scope(); |
| 7340 | statement("ycbcr.br = plane1.sample(samp, coord, options...).rg;"); |
| 7341 | end_scope(); |
| 7342 | statement("return ycbcr;"); |
| 7343 | end_scope(); |
| 7344 | statement(""); |
| 7345 | break; |
| 7346 | |
| 7347 | case SPVFuncImplChromaReconstructLinear422CositedEven3Plane: |
| 7348 | statement("template<typename T, typename... LodOptions>"); |
| 7349 | statement("inline vec<T, 4> spvChromaReconstructLinear422CositedEven(texture2d<T> plane0, texture2d<T> " |
| 7350 | "plane1, texture2d<T> plane2, sampler samp, float2 coord, LodOptions... options)"); |
| 7351 | begin_scope(); |
| 7352 | statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);"); |
| 7353 | statement("ycbcr.g = plane0.sample(samp, coord, options...).r;"); |
| 7354 | statement("if (fract(coord.x * plane1.get_width()) != 0.0)"); |
| 7355 | begin_scope(); |
| 7356 | statement("ycbcr.b = T(mix(plane1.sample(samp, coord, options...), " |
| 7357 | "plane1.sample(samp, coord, options..., int2(1, 0)), 0.5).r);"); |
| 7358 | statement("ycbcr.r = T(mix(plane2.sample(samp, coord, options...), " |
| 7359 | "plane2.sample(samp, coord, options..., int2(1, 0)), 0.5).r);"); |
| 7360 | end_scope(); |
| 7361 | statement("else"); |
| 7362 | begin_scope(); |
| 7363 | statement("ycbcr.b = plane1.sample(samp, coord, options...).r;"); |
| 7364 | statement("ycbcr.r = plane2.sample(samp, coord, options...).r;"); |
| 7365 | end_scope(); |
| 7366 | statement("return ycbcr;"); |
| 7367 | end_scope(); |
| 7368 | statement(""); |
| 7369 | break; |
| 7370 | |
| 7371 | case SPVFuncImplChromaReconstructLinear422Midpoint2Plane: |
| 7372 | statement("template<typename T, typename... LodOptions>"); |
| 7373 | statement("inline vec<T, 4> spvChromaReconstructLinear422Midpoint(texture2d<T> plane0, texture2d<T> " |
| 7374 | "plane1, sampler samp, float2 coord, LodOptions... options)"); |
| 7375 | begin_scope(); |
| 7376 | statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);"); |
| 7377 | statement("ycbcr.g = plane0.sample(samp, coord, options...).r;"); |
| 7378 | statement("int2 offs = int2(fract(coord.x * plane1.get_width()) != 0.0 ? 1 : -1, 0);"); |
| 7379 | statement("ycbcr.br = vec<T, 2>(mix(plane1.sample(samp, coord, options...), " |
| 7380 | "plane1.sample(samp, coord, options..., offs), 0.25).rg);"); |
| 7381 | statement("return ycbcr;"); |
| 7382 | end_scope(); |
| 7383 | statement(""); |
| 7384 | break; |
| 7385 | |
| 7386 | case SPVFuncImplChromaReconstructLinear422Midpoint3Plane: |
| 7387 | statement("template<typename T, typename... LodOptions>"); |
| 7388 | statement("inline vec<T, 4> spvChromaReconstructLinear422Midpoint(texture2d<T> plane0, texture2d<T> " |
| 7389 | "plane1, texture2d<T> plane2, sampler samp, float2 coord, LodOptions... options)"); |
| 7390 | begin_scope(); |
| 7391 | statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);"); |
| 7392 | statement("ycbcr.g = plane0.sample(samp, coord, options...).r;"); |
| 7393 | statement("int2 offs = int2(fract(coord.x * plane1.get_width()) != 0.0 ? 1 : -1, 0);"); |
| 7394 | statement("ycbcr.b = T(mix(plane1.sample(samp, coord, options...), " |
| 7395 | "plane1.sample(samp, coord, options..., offs), 0.25).r);"); |
| 7396 | statement("ycbcr.r = T(mix(plane2.sample(samp, coord, options...), " |
| 7397 | "plane2.sample(samp, coord, options..., offs), 0.25).r);"); |
| 7398 | statement("return ycbcr;"); |
| 7399 | end_scope(); |
| 7400 | statement(""); |
| 7401 | break; |
| 7402 | |
| 7403 | case SPVFuncImplChromaReconstructLinear420XCositedEvenYCositedEven2Plane: |
| 7404 | statement("template<typename T, typename... LodOptions>"); |
| 7405 | statement("inline vec<T, 4> spvChromaReconstructLinear420XCositedEvenYCositedEven(texture2d<T> plane0, " |
| 7406 | "texture2d<T> plane1, sampler samp, float2 coord, LodOptions... options)"); |
| 7407 | begin_scope(); |
| 7408 | statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);"); |
| 7409 | statement("ycbcr.g = plane0.sample(samp, coord, options...).r;"); |
| 7410 | statement("float2 ab = fract(round(coord * float2(plane0.get_width(), plane0.get_height())) * 0.5);"); |
| 7411 | statement("ycbcr.br = vec<T, 2>(mix(mix(plane1.sample(samp, coord, options...), " |
| 7412 | "plane1.sample(samp, coord, options..., int2(1, 0)), ab.x), " |
| 7413 | "mix(plane1.sample(samp, coord, options..., int2(0, 1)), " |
| 7414 | "plane1.sample(samp, coord, options..., int2(1, 1)), ab.x), ab.y).rg);"); |
| 7415 | statement("return ycbcr;"); |
| 7416 | end_scope(); |
| 7417 | statement(""); |
| 7418 | break; |
| 7419 | |
| 7420 | case SPVFuncImplChromaReconstructLinear420XCositedEvenYCositedEven3Plane: |
| 7421 | statement("template<typename T, typename... LodOptions>"); |
| 7422 | statement("inline vec<T, 4> spvChromaReconstructLinear420XCositedEvenYCositedEven(texture2d<T> plane0, " |
| 7423 | "texture2d<T> plane1, texture2d<T> plane2, sampler samp, float2 coord, LodOptions... options)"); |
| 7424 | begin_scope(); |
| 7425 | statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);"); |
| 7426 | statement("ycbcr.g = plane0.sample(samp, coord, options...).r;"); |
| 7427 | statement("float2 ab = fract(round(coord * float2(plane0.get_width(), plane0.get_height())) * 0.5);"); |
| 7428 | statement("ycbcr.b = T(mix(mix(plane1.sample(samp, coord, options...), " |
| 7429 | "plane1.sample(samp, coord, options..., int2(1, 0)), ab.x), " |
| 7430 | "mix(plane1.sample(samp, coord, options..., int2(0, 1)), " |
| 7431 | "plane1.sample(samp, coord, options..., int2(1, 1)), ab.x), ab.y).r);"); |
| 7432 | statement("ycbcr.r = T(mix(mix(plane2.sample(samp, coord, options...), " |
| 7433 | "plane2.sample(samp, coord, options..., int2(1, 0)), ab.x), " |
| 7434 | "mix(plane2.sample(samp, coord, options..., int2(0, 1)), " |
| 7435 | "plane2.sample(samp, coord, options..., int2(1, 1)), ab.x), ab.y).r);"); |
| 7436 | statement("return ycbcr;"); |
| 7437 | end_scope(); |
| 7438 | statement(""); |
| 7439 | break; |
| 7440 | |
| 7441 | case SPVFuncImplChromaReconstructLinear420XMidpointYCositedEven2Plane: |
| 7442 | statement("template<typename T, typename... LodOptions>"); |
| 7443 | statement("inline vec<T, 4> spvChromaReconstructLinear420XMidpointYCositedEven(texture2d<T> plane0, " |
| 7444 | "texture2d<T> plane1, sampler samp, float2 coord, LodOptions... options)"); |
| 7445 | begin_scope(); |
| 7446 | statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);"); |
| 7447 | statement("ycbcr.g = plane0.sample(samp, coord, options...).r;"); |
| 7448 | statement("float2 ab = fract((round(coord * float2(plane0.get_width(), plane0.get_height())) - float2(0.5, " |
| 7449 | "0)) * 0.5);"); |
| 7450 | statement("ycbcr.br = vec<T, 2>(mix(mix(plane1.sample(samp, coord, options...), " |
| 7451 | "plane1.sample(samp, coord, options..., int2(1, 0)), ab.x), " |
| 7452 | "mix(plane1.sample(samp, coord, options..., int2(0, 1)), " |
| 7453 | "plane1.sample(samp, coord, options..., int2(1, 1)), ab.x), ab.y).rg);"); |
| 7454 | statement("return ycbcr;"); |
| 7455 | end_scope(); |
| 7456 | statement(""); |
| 7457 | break; |
| 7458 | |
| 7459 | case SPVFuncImplChromaReconstructLinear420XMidpointYCositedEven3Plane: |
| 7460 | statement("template<typename T, typename... LodOptions>"); |
| 7461 | statement("inline vec<T, 4> spvChromaReconstructLinear420XMidpointYCositedEven(texture2d<T> plane0, " |
| 7462 | "texture2d<T> plane1, texture2d<T> plane2, sampler samp, float2 coord, LodOptions... options)"); |
| 7463 | begin_scope(); |
| 7464 | statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);"); |
| 7465 | statement("ycbcr.g = plane0.sample(samp, coord, options...).r;"); |
| 7466 | statement("float2 ab = fract((round(coord * float2(plane0.get_width(), plane0.get_height())) - float2(0.5, " |
| 7467 | "0)) * 0.5);"); |
| 7468 | statement("ycbcr.b = T(mix(mix(plane1.sample(samp, coord, options...), " |
| 7469 | "plane1.sample(samp, coord, options..., int2(1, 0)), ab.x), " |
| 7470 | "mix(plane1.sample(samp, coord, options..., int2(0, 1)), " |
| 7471 | "plane1.sample(samp, coord, options..., int2(1, 1)), ab.x), ab.y).r);"); |
| 7472 | statement("ycbcr.r = T(mix(mix(plane2.sample(samp, coord, options...), " |
| 7473 | "plane2.sample(samp, coord, options..., int2(1, 0)), ab.x), " |
| 7474 | "mix(plane2.sample(samp, coord, options..., int2(0, 1)), " |
| 7475 | "plane2.sample(samp, coord, options..., int2(1, 1)), ab.x), ab.y).r);"); |
| 7476 | statement("return ycbcr;"); |
| 7477 | end_scope(); |
| 7478 | statement(""); |
| 7479 | break; |
| 7480 | |
| 7481 | case SPVFuncImplChromaReconstructLinear420XCositedEvenYMidpoint2Plane: |
| 7482 | statement("template<typename T, typename... LodOptions>"); |
| 7483 | statement("inline vec<T, 4> spvChromaReconstructLinear420XCositedEvenYMidpoint(texture2d<T> plane0, " |
| 7484 | "texture2d<T> plane1, sampler samp, float2 coord, LodOptions... options)"); |
| 7485 | begin_scope(); |
| 7486 | statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);"); |
| 7487 | statement("ycbcr.g = plane0.sample(samp, coord, options...).r;"); |
| 7488 | statement("float2 ab = fract((round(coord * float2(plane0.get_width(), plane0.get_height())) - float2(0, " |
| 7489 | "0.5)) * 0.5);"); |
| 7490 | statement("ycbcr.br = vec<T, 2>(mix(mix(plane1.sample(samp, coord, options...), " |
| 7491 | "plane1.sample(samp, coord, options..., int2(1, 0)), ab.x), " |
| 7492 | "mix(plane1.sample(samp, coord, options..., int2(0, 1)), " |
| 7493 | "plane1.sample(samp, coord, options..., int2(1, 1)), ab.x), ab.y).rg);"); |
| 7494 | statement("return ycbcr;"); |
| 7495 | end_scope(); |
| 7496 | statement(""); |
| 7497 | break; |
| 7498 | |
| 7499 | case SPVFuncImplChromaReconstructLinear420XCositedEvenYMidpoint3Plane: |
| 7500 | statement("template<typename T, typename... LodOptions>"); |
| 7501 | statement("inline vec<T, 4> spvChromaReconstructLinear420XCositedEvenYMidpoint(texture2d<T> plane0, " |
| 7502 | "texture2d<T> plane1, texture2d<T> plane2, sampler samp, float2 coord, LodOptions... options)"); |
| 7503 | begin_scope(); |
| 7504 | statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);"); |
| 7505 | statement("ycbcr.g = plane0.sample(samp, coord, options...).r;"); |
| 7506 | statement("float2 ab = fract((round(coord * float2(plane0.get_width(), plane0.get_height())) - float2(0, " |
| 7507 | "0.5)) * 0.5);"); |
| 7508 | statement("ycbcr.b = T(mix(mix(plane1.sample(samp, coord, options...), " |
| 7509 | "plane1.sample(samp, coord, options..., int2(1, 0)), ab.x), " |
| 7510 | "mix(plane1.sample(samp, coord, options..., int2(0, 1)), " |
| 7511 | "plane1.sample(samp, coord, options..., int2(1, 1)), ab.x), ab.y).r);"); |
| 7512 | statement("ycbcr.r = T(mix(mix(plane2.sample(samp, coord, options...), " |
| 7513 | "plane2.sample(samp, coord, options..., int2(1, 0)), ab.x), " |
| 7514 | "mix(plane2.sample(samp, coord, options..., int2(0, 1)), " |
| 7515 | "plane2.sample(samp, coord, options..., int2(1, 1)), ab.x), ab.y).r);"); |
| 7516 | statement("return ycbcr;"); |
| 7517 | end_scope(); |
| 7518 | statement(""); |
| 7519 | break; |
| 7520 | |
| 7521 | case SPVFuncImplChromaReconstructLinear420XMidpointYMidpoint2Plane: |
| 7522 | statement("template<typename T, typename... LodOptions>"); |
| 7523 | statement("inline vec<T, 4> spvChromaReconstructLinear420XMidpointYMidpoint(texture2d<T> plane0, " |
| 7524 | "texture2d<T> plane1, sampler samp, float2 coord, LodOptions... options)"); |
| 7525 | begin_scope(); |
| 7526 | statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);"); |
| 7527 | statement("ycbcr.g = plane0.sample(samp, coord, options...).r;"); |
| 7528 | statement("float2 ab = fract((round(coord * float2(plane0.get_width(), plane0.get_height())) - float2(0.5, " |
| 7529 | "0.5)) * 0.5);"); |
| 7530 | statement("ycbcr.br = vec<T, 2>(mix(mix(plane1.sample(samp, coord, options...), " |
| 7531 | "plane1.sample(samp, coord, options..., int2(1, 0)), ab.x), " |
| 7532 | "mix(plane1.sample(samp, coord, options..., int2(0, 1)), " |
| 7533 | "plane1.sample(samp, coord, options..., int2(1, 1)), ab.x), ab.y).rg);"); |
| 7534 | statement("return ycbcr;"); |
| 7535 | end_scope(); |
| 7536 | statement(""); |
| 7537 | break; |
| 7538 | |
| 7539 | case SPVFuncImplChromaReconstructLinear420XMidpointYMidpoint3Plane: |
| 7540 | statement("template<typename T, typename... LodOptions>"); |
| 7541 | statement("inline vec<T, 4> spvChromaReconstructLinear420XMidpointYMidpoint(texture2d<T> plane0, " |
| 7542 | "texture2d<T> plane1, texture2d<T> plane2, sampler samp, float2 coord, LodOptions... options)"); |
| 7543 | begin_scope(); |
| 7544 | statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);"); |
| 7545 | statement("ycbcr.g = plane0.sample(samp, coord, options...).r;"); |
| 7546 | statement("float2 ab = fract((round(coord * float2(plane0.get_width(), plane0.get_height())) - float2(0.5, " |
| 7547 | "0.5)) * 0.5);"); |
| 7548 | statement("ycbcr.b = T(mix(mix(plane1.sample(samp, coord, options...), " |
| 7549 | "plane1.sample(samp, coord, options..., int2(1, 0)), ab.x), " |
| 7550 | "mix(plane1.sample(samp, coord, options..., int2(0, 1)), " |
| 7551 | "plane1.sample(samp, coord, options..., int2(1, 1)), ab.x), ab.y).r);"); |
| 7552 | statement("ycbcr.r = T(mix(mix(plane2.sample(samp, coord, options...), " |
| 7553 | "plane2.sample(samp, coord, options..., int2(1, 0)), ab.x), " |
| 7554 | "mix(plane2.sample(samp, coord, options..., int2(0, 1)), " |
| 7555 | "plane2.sample(samp, coord, options..., int2(1, 1)), ab.x), ab.y).r);"); |
| 7556 | statement("return ycbcr;"); |
| 7557 | end_scope(); |
| 7558 | statement(""); |
| 7559 | break; |
| 7560 | |
| 7561 | case SPVFuncImplExpandITUFullRange: |
| 7562 | statement("template<typename T>"); |
| 7563 | statement("inline vec<T, 4> spvExpandITUFullRange(vec<T, 4> ycbcr, int n)"); |
| 7564 | begin_scope(); |
| 7565 | statement("ycbcr.br -= exp2(T(n-1))/(exp2(T(n))-1);"); |
| 7566 | statement("return ycbcr;"); |
| 7567 | end_scope(); |
| 7568 | statement(""); |
| 7569 | break; |
| 7570 | |
| 7571 | case SPVFuncImplExpandITUNarrowRange: |
| 7572 | statement("template<typename T>"); |
| 7573 | statement("inline vec<T, 4> spvExpandITUNarrowRange(vec<T, 4> ycbcr, int n)"); |
| 7574 | begin_scope(); |
| 7575 | statement("ycbcr.g = (ycbcr.g * (exp2(T(n)) - 1) - ldexp(T(16), n - 8))/ldexp(T(219), n - 8);"); |
| 7576 | statement("ycbcr.br = (ycbcr.br * (exp2(T(n)) - 1) - ldexp(T(128), n - 8))/ldexp(T(224), n - 8);"); |
| 7577 | statement("return ycbcr;"); |
| 7578 | end_scope(); |
| 7579 | statement(""); |
| 7580 | break; |
| 7581 | |
| 7582 | case SPVFuncImplConvertYCbCrBT709: |
| 7583 | statement("// cf. Khronos Data Format Specification, section 15.1.1"); |
| 7584 | statement("constant float3x3 spvBT709Factors = {{1, 1, 1}, {0, -0.13397432/0.7152, 1.8556}, {1.5748, " |
| 7585 | "-0.33480248/0.7152, 0}};"); |
| 7586 | statement(""); |
| 7587 | statement("template<typename T>"); |
| 7588 | statement("inline vec<T, 4> spvConvertYCbCrBT709(vec<T, 4> ycbcr)"); |
| 7589 | begin_scope(); |
| 7590 | statement("vec<T, 4> rgba;"); |
| 7591 | statement("rgba.rgb = vec<T, 3>(spvBT709Factors * ycbcr.gbr);"); |
| 7592 | statement("rgba.a = ycbcr.a;"); |
| 7593 | statement("return rgba;"); |
| 7594 | end_scope(); |
| 7595 | statement(""); |
| 7596 | break; |
| 7597 | |
| 7598 | case SPVFuncImplConvertYCbCrBT601: |
| 7599 | statement("// cf. Khronos Data Format Specification, section 15.1.2"); |
| 7600 | statement("constant float3x3 spvBT601Factors = {{1, 1, 1}, {0, -0.202008/0.587, 1.772}, {1.402, " |
| 7601 | "-0.419198/0.587, 0}};"); |
| 7602 | statement(""); |
| 7603 | statement("template<typename T>"); |
| 7604 | statement("inline vec<T, 4> spvConvertYCbCrBT601(vec<T, 4> ycbcr)"); |
| 7605 | begin_scope(); |
| 7606 | statement("vec<T, 4> rgba;"); |
| 7607 | statement("rgba.rgb = vec<T, 3>(spvBT601Factors * ycbcr.gbr);"); |
| 7608 | statement("rgba.a = ycbcr.a;"); |
| 7609 | statement("return rgba;"); |
| 7610 | end_scope(); |
| 7611 | statement(""); |
| 7612 | break; |
| 7613 | |
| 7614 | case SPVFuncImplConvertYCbCrBT2020: |
| 7615 | statement("// cf. Khronos Data Format Specification, section 15.1.3"); |
| 7616 | statement("constant float3x3 spvBT2020Factors = {{1, 1, 1}, {0, -0.11156702/0.6780, 1.8814}, {1.4746, " |
| 7617 | "-0.38737742/0.6780, 0}};"); |
| 7618 | statement(""); |
| 7619 | statement("template<typename T>"); |
| 7620 | statement("inline vec<T, 4> spvConvertYCbCrBT2020(vec<T, 4> ycbcr)"); |
| 7621 | begin_scope(); |
| 7622 | statement("vec<T, 4> rgba;"); |
| 7623 | statement("rgba.rgb = vec<T, 3>(spvBT2020Factors * ycbcr.gbr);"); |
| 7624 | statement("rgba.a = ycbcr.a;"); |
| 7625 | statement("return rgba;"); |
| 7626 | end_scope(); |
| 7627 | statement(""); |
| 7628 | break; |
| 7629 | |
| 7630 | case SPVFuncImplDynamicImageSampler: |
| 7631 | statement("enum class spvFormatResolution"); |
| 7632 | begin_scope(); |
| 7633 | statement("_444 = 0,"); |
| 7634 | statement("_422,"); |
| 7635 | statement("_420"); |
| 7636 | end_scope_decl(); |
| 7637 | statement(""); |
| 7638 | statement("enum class spvChromaFilter"); |
| 7639 | begin_scope(); |
| 7640 | statement("nearest = 0,"); |
| 7641 | statement("linear"); |
| 7642 | end_scope_decl(); |
| 7643 | statement(""); |
| 7644 | statement("enum class spvXChromaLocation"); |
| 7645 | begin_scope(); |
| 7646 | statement("cosited_even = 0,"); |
| 7647 | statement("midpoint"); |
| 7648 | end_scope_decl(); |
| 7649 | statement(""); |
| 7650 | statement("enum class spvYChromaLocation"); |
| 7651 | begin_scope(); |
| 7652 | statement("cosited_even = 0,"); |
| 7653 | statement("midpoint"); |
| 7654 | end_scope_decl(); |
| 7655 | statement(""); |
| 7656 | statement("enum class spvYCbCrModelConversion"); |
| 7657 | begin_scope(); |
| 7658 | statement("rgb_identity = 0,"); |
| 7659 | statement("ycbcr_identity,"); |
| 7660 | statement("ycbcr_bt_709,"); |
| 7661 | statement("ycbcr_bt_601,"); |
| 7662 | statement("ycbcr_bt_2020"); |
| 7663 | end_scope_decl(); |
| 7664 | statement(""); |
| 7665 | statement("enum class spvYCbCrRange"); |
| 7666 | begin_scope(); |
| 7667 | statement("itu_full = 0,"); |
| 7668 | statement("itu_narrow"); |
| 7669 | end_scope_decl(); |
| 7670 | statement(""); |
| 7671 | statement("struct spvComponentBits"); |
| 7672 | begin_scope(); |
| 7673 | statement("constexpr explicit spvComponentBits(int v) thread : value(v) {}"); |
| 7674 | statement("uchar value : 6;"); |
| 7675 | end_scope_decl(); |
| 7676 | statement("// A class corresponding to metal::sampler which holds sampler"); |
| 7677 | statement("// Y'CbCr conversion info."); |
| 7678 | statement("struct spvYCbCrSampler"); |
| 7679 | begin_scope(); |
| 7680 | statement("constexpr spvYCbCrSampler() thread : val(build()) {}"); |
| 7681 | statement("template<typename... Ts>"); |
| 7682 | statement("constexpr spvYCbCrSampler(Ts... t) thread : val(build(t...)) {}"); |
| 7683 | statement("constexpr spvYCbCrSampler(const thread spvYCbCrSampler& s) thread = default;"); |
| 7684 | statement(""); |
| 7685 | statement("spvFormatResolution get_resolution() const thread"); |
| 7686 | begin_scope(); |
| 7687 | statement("return spvFormatResolution((val & resolution_mask) >> resolution_base);"); |
| 7688 | end_scope(); |
| 7689 | statement("spvChromaFilter get_chroma_filter() const thread"); |
| 7690 | begin_scope(); |
| 7691 | statement("return spvChromaFilter((val & chroma_filter_mask) >> chroma_filter_base);"); |
| 7692 | end_scope(); |
| 7693 | statement("spvXChromaLocation get_x_chroma_offset() const thread"); |
| 7694 | begin_scope(); |
| 7695 | statement("return spvXChromaLocation((val & x_chroma_off_mask) >> x_chroma_off_base);"); |
| 7696 | end_scope(); |
| 7697 | statement("spvYChromaLocation get_y_chroma_offset() const thread"); |
| 7698 | begin_scope(); |
| 7699 | statement("return spvYChromaLocation((val & y_chroma_off_mask) >> y_chroma_off_base);"); |
| 7700 | end_scope(); |
| 7701 | statement("spvYCbCrModelConversion get_ycbcr_model() const thread"); |
| 7702 | begin_scope(); |
| 7703 | statement("return spvYCbCrModelConversion((val & ycbcr_model_mask) >> ycbcr_model_base);"); |
| 7704 | end_scope(); |
| 7705 | statement("spvYCbCrRange get_ycbcr_range() const thread"); |
| 7706 | begin_scope(); |
| 7707 | statement("return spvYCbCrRange((val & ycbcr_range_mask) >> ycbcr_range_base);"); |
| 7708 | end_scope(); |
| 7709 | statement("int get_bpc() const thread { return (val & bpc_mask) >> bpc_base; }"); |
| 7710 | statement(""); |
| 7711 | statement("private:"); |
| 7712 | statement("ushort val;"); |
| 7713 | statement(""); |
| 7714 | statement("constexpr static constant ushort resolution_bits = 2;"); |
| 7715 | statement("constexpr static constant ushort chroma_filter_bits = 2;"); |
| 7716 | statement("constexpr static constant ushort x_chroma_off_bit = 1;"); |
| 7717 | statement("constexpr static constant ushort y_chroma_off_bit = 1;"); |
| 7718 | statement("constexpr static constant ushort ycbcr_model_bits = 3;"); |
| 7719 | statement("constexpr static constant ushort ycbcr_range_bit = 1;"); |
| 7720 | statement("constexpr static constant ushort bpc_bits = 6;"); |
| 7721 | statement(""); |
| 7722 | statement("constexpr static constant ushort resolution_base = 0;"); |
| 7723 | statement("constexpr static constant ushort chroma_filter_base = 2;"); |
| 7724 | statement("constexpr static constant ushort x_chroma_off_base = 4;"); |
| 7725 | statement("constexpr static constant ushort y_chroma_off_base = 5;"); |
| 7726 | statement("constexpr static constant ushort ycbcr_model_base = 6;"); |
| 7727 | statement("constexpr static constant ushort ycbcr_range_base = 9;"); |
| 7728 | statement("constexpr static constant ushort bpc_base = 10;"); |
| 7729 | statement(""); |
| 7730 | statement( |
| 7731 | "constexpr static constant ushort resolution_mask = ((1 << resolution_bits) - 1) << resolution_base;"); |
| 7732 | statement("constexpr static constant ushort chroma_filter_mask = ((1 << chroma_filter_bits) - 1) << " |
| 7733 | "chroma_filter_base;"); |
| 7734 | statement("constexpr static constant ushort x_chroma_off_mask = ((1 << x_chroma_off_bit) - 1) << " |
| 7735 | "x_chroma_off_base;"); |
| 7736 | statement("constexpr static constant ushort y_chroma_off_mask = ((1 << y_chroma_off_bit) - 1) << " |
| 7737 | "y_chroma_off_base;"); |
| 7738 | statement("constexpr static constant ushort ycbcr_model_mask = ((1 << ycbcr_model_bits) - 1) << " |
| 7739 | "ycbcr_model_base;"); |
| 7740 | statement("constexpr static constant ushort ycbcr_range_mask = ((1 << ycbcr_range_bit) - 1) << " |
| 7741 | "ycbcr_range_base;"); |
| 7742 | statement("constexpr static constant ushort bpc_mask = ((1 << bpc_bits) - 1) << bpc_base;"); |
| 7743 | statement(""); |
| 7744 | statement("static constexpr ushort build()"); |
| 7745 | begin_scope(); |
| 7746 | statement("return 0;"); |
| 7747 | end_scope(); |
| 7748 | statement(""); |
| 7749 | statement("template<typename... Ts>"); |
| 7750 | statement("static constexpr ushort build(spvFormatResolution res, Ts... t)"); |
| 7751 | begin_scope(); |
| 7752 | statement("return (ushort(res) << resolution_base) | (build(t...) & ~resolution_mask);"); |
| 7753 | end_scope(); |
| 7754 | statement(""); |
| 7755 | statement("template<typename... Ts>"); |
| 7756 | statement("static constexpr ushort build(spvChromaFilter filt, Ts... t)"); |
| 7757 | begin_scope(); |
| 7758 | statement("return (ushort(filt) << chroma_filter_base) | (build(t...) & ~chroma_filter_mask);"); |
| 7759 | end_scope(); |
| 7760 | statement(""); |
| 7761 | statement("template<typename... Ts>"); |
| 7762 | statement("static constexpr ushort build(spvXChromaLocation loc, Ts... t)"); |
| 7763 | begin_scope(); |
| 7764 | statement("return (ushort(loc) << x_chroma_off_base) | (build(t...) & ~x_chroma_off_mask);"); |
| 7765 | end_scope(); |
| 7766 | statement(""); |
| 7767 | statement("template<typename... Ts>"); |
| 7768 | statement("static constexpr ushort build(spvYChromaLocation loc, Ts... t)"); |
| 7769 | begin_scope(); |
| 7770 | statement("return (ushort(loc) << y_chroma_off_base) | (build(t...) & ~y_chroma_off_mask);"); |
| 7771 | end_scope(); |
| 7772 | statement(""); |
| 7773 | statement("template<typename... Ts>"); |
| 7774 | statement("static constexpr ushort build(spvYCbCrModelConversion model, Ts... t)"); |
| 7775 | begin_scope(); |
| 7776 | statement("return (ushort(model) << ycbcr_model_base) | (build(t...) & ~ycbcr_model_mask);"); |
| 7777 | end_scope(); |
| 7778 | statement(""); |
| 7779 | statement("template<typename... Ts>"); |
| 7780 | statement("static constexpr ushort build(spvYCbCrRange range, Ts... t)"); |
| 7781 | begin_scope(); |
| 7782 | statement("return (ushort(range) << ycbcr_range_base) | (build(t...) & ~ycbcr_range_mask);"); |
| 7783 | end_scope(); |
| 7784 | statement(""); |
| 7785 | statement("template<typename... Ts>"); |
| 7786 | statement("static constexpr ushort build(spvComponentBits bpc, Ts... t)"); |
| 7787 | begin_scope(); |
| 7788 | statement("return (ushort(bpc.value) << bpc_base) | (build(t...) & ~bpc_mask);"); |
| 7789 | end_scope(); |
| 7790 | end_scope_decl(); |
| 7791 | statement(""); |
| 7792 | statement("// A class which can hold up to three textures and a sampler, including"); |
| 7793 | statement("// Y'CbCr conversion info, used to pass combined image-samplers"); |
| 7794 | statement("// dynamically to functions."); |
| 7795 | statement("template<typename T>"); |
| 7796 | statement("struct spvDynamicImageSampler"); |
| 7797 | begin_scope(); |
| 7798 | statement("texture2d<T> plane0;"); |
| 7799 | statement("texture2d<T> plane1;"); |
| 7800 | statement("texture2d<T> plane2;"); |
| 7801 | statement("sampler samp;"); |
| 7802 | statement("spvYCbCrSampler ycbcr_samp;"); |
| 7803 | statement("uint swizzle = 0;"); |
| 7804 | statement(""); |
| 7805 | if (msl_options.swizzle_texture_samples) |
| 7806 | { |
| 7807 | statement("constexpr spvDynamicImageSampler(texture2d<T> tex, sampler samp, uint sw) thread :"); |
| 7808 | statement(" plane0(tex), samp(samp), swizzle(sw) {}"); |
| 7809 | } |
| 7810 | else |
| 7811 | { |
| 7812 | statement("constexpr spvDynamicImageSampler(texture2d<T> tex, sampler samp) thread :"); |
| 7813 | statement(" plane0(tex), samp(samp) {}"); |
| 7814 | } |
| 7815 | statement("constexpr spvDynamicImageSampler(texture2d<T> tex, sampler samp, spvYCbCrSampler ycbcr_samp, " |
| 7816 | "uint sw) thread :"); |
| 7817 | statement(" plane0(tex), samp(samp), ycbcr_samp(ycbcr_samp), swizzle(sw) {}"); |
| 7818 | statement("constexpr spvDynamicImageSampler(texture2d<T> plane0, texture2d<T> plane1,"); |
| 7819 | statement(" sampler samp, spvYCbCrSampler ycbcr_samp, uint sw) thread :"); |
| 7820 | statement(" plane0(plane0), plane1(plane1), samp(samp), ycbcr_samp(ycbcr_samp), swizzle(sw) {}"); |
| 7821 | statement( |
| 7822 | "constexpr spvDynamicImageSampler(texture2d<T> plane0, texture2d<T> plane1, texture2d<T> plane2,"); |
| 7823 | statement(" sampler samp, spvYCbCrSampler ycbcr_samp, uint sw) thread :"); |
| 7824 | statement(" plane0(plane0), plane1(plane1), plane2(plane2), samp(samp), ycbcr_samp(ycbcr_samp), " |
| 7825 | "swizzle(sw) {}"); |
| 7826 | statement(""); |
| 7827 | // XXX This is really hard to follow... I've left comments to make it a bit easier. |
| 7828 | statement("template<typename... LodOptions>"); |
| 7829 | statement("vec<T, 4> do_sample(float2 coord, LodOptions... options) const thread"); |
| 7830 | begin_scope(); |
| 7831 | statement("if (!is_null_texture(plane1))"); |
| 7832 | begin_scope(); |
| 7833 | statement("if (ycbcr_samp.get_resolution() == spvFormatResolution::_444 ||"); |
| 7834 | statement(" ycbcr_samp.get_chroma_filter() == spvChromaFilter::nearest)"); |
| 7835 | begin_scope(); |
| 7836 | statement("if (!is_null_texture(plane2))"); |
| 7837 | statement(" return spvChromaReconstructNearest(plane0, plane1, plane2, samp, coord, options...);"); |
| 7838 | statement("return spvChromaReconstructNearest(plane0, plane1, samp, coord, options...);"); |
| 7839 | end_scope(); // if (resolution == 422 || chroma_filter == nearest) |
| 7840 | statement("switch (ycbcr_samp.get_resolution())"); |
| 7841 | begin_scope(); |
| 7842 | statement("case spvFormatResolution::_444: break;"); |
| 7843 | statement("case spvFormatResolution::_422:"); |
| 7844 | begin_scope(); |
| 7845 | statement("switch (ycbcr_samp.get_x_chroma_offset())"); |
| 7846 | begin_scope(); |
| 7847 | statement("case spvXChromaLocation::cosited_even:"); |
| 7848 | statement(" if (!is_null_texture(plane2))"); |
| 7849 | statement(" return spvChromaReconstructLinear422CositedEven("); |
| 7850 | statement(" plane0, plane1, plane2, samp,"); |
| 7851 | statement(" coord, options...);"); |
| 7852 | statement(" return spvChromaReconstructLinear422CositedEven("); |
| 7853 | statement(" plane0, plane1, samp, coord,"); |
| 7854 | statement(" options...);"); |
| 7855 | statement("case spvXChromaLocation::midpoint:"); |
| 7856 | statement(" if (!is_null_texture(plane2))"); |
| 7857 | statement(" return spvChromaReconstructLinear422Midpoint("); |
| 7858 | statement(" plane0, plane1, plane2, samp,"); |
| 7859 | statement(" coord, options...);"); |
| 7860 | statement(" return spvChromaReconstructLinear422Midpoint("); |
| 7861 | statement(" plane0, plane1, samp, coord,"); |
| 7862 | statement(" options...);"); |
| 7863 | end_scope(); // switch (x_chroma_offset) |
| 7864 | end_scope(); // case 422: |
| 7865 | statement("case spvFormatResolution::_420:"); |
| 7866 | begin_scope(); |
| 7867 | statement("switch (ycbcr_samp.get_x_chroma_offset())"); |
| 7868 | begin_scope(); |
| 7869 | statement("case spvXChromaLocation::cosited_even:"); |
| 7870 | begin_scope(); |
| 7871 | statement("switch (ycbcr_samp.get_y_chroma_offset())"); |
| 7872 | begin_scope(); |
| 7873 | statement("case spvYChromaLocation::cosited_even:"); |
| 7874 | statement(" if (!is_null_texture(plane2))"); |
| 7875 | statement(" return spvChromaReconstructLinear420XCositedEvenYCositedEven("); |
| 7876 | statement(" plane0, plane1, plane2, samp,"); |
| 7877 | statement(" coord, options...);"); |
| 7878 | statement(" return spvChromaReconstructLinear420XCositedEvenYCositedEven("); |
| 7879 | statement(" plane0, plane1, samp, coord,"); |
| 7880 | statement(" options...);"); |
| 7881 | statement("case spvYChromaLocation::midpoint:"); |
| 7882 | statement(" if (!is_null_texture(plane2))"); |
| 7883 | statement(" return spvChromaReconstructLinear420XCositedEvenYMidpoint("); |
| 7884 | statement(" plane0, plane1, plane2, samp,"); |
| 7885 | statement(" coord, options...);"); |
| 7886 | statement(" return spvChromaReconstructLinear420XCositedEvenYMidpoint("); |
| 7887 | statement(" plane0, plane1, samp, coord,"); |
| 7888 | statement(" options...);"); |
| 7889 | end_scope(); // switch (y_chroma_offset) |
| 7890 | end_scope(); // case x::cosited_even: |
| 7891 | statement("case spvXChromaLocation::midpoint:"); |
| 7892 | begin_scope(); |
| 7893 | statement("switch (ycbcr_samp.get_y_chroma_offset())"); |
| 7894 | begin_scope(); |
| 7895 | statement("case spvYChromaLocation::cosited_even:"); |
| 7896 | statement(" if (!is_null_texture(plane2))"); |
| 7897 | statement(" return spvChromaReconstructLinear420XMidpointYCositedEven("); |
| 7898 | statement(" plane0, plane1, plane2, samp,"); |
| 7899 | statement(" coord, options...);"); |
| 7900 | statement(" return spvChromaReconstructLinear420XMidpointYCositedEven("); |
| 7901 | statement(" plane0, plane1, samp, coord,"); |
| 7902 | statement(" options...);"); |
| 7903 | statement("case spvYChromaLocation::midpoint:"); |
| 7904 | statement(" if (!is_null_texture(plane2))"); |
| 7905 | statement(" return spvChromaReconstructLinear420XMidpointYMidpoint("); |
| 7906 | statement(" plane0, plane1, plane2, samp,"); |
| 7907 | statement(" coord, options...);"); |
| 7908 | statement(" return spvChromaReconstructLinear420XMidpointYMidpoint("); |
| 7909 | statement(" plane0, plane1, samp, coord,"); |
| 7910 | statement(" options...);"); |
| 7911 | end_scope(); // switch (y_chroma_offset) |
| 7912 | end_scope(); // case x::midpoint |
| 7913 | end_scope(); // switch (x_chroma_offset) |
| 7914 | end_scope(); // case 420: |
| 7915 | end_scope(); // switch (resolution) |
| 7916 | end_scope(); // if (multiplanar) |
| 7917 | statement("return plane0.sample(samp, coord, options...);"); |
| 7918 | end_scope(); // do_sample() |
| 7919 | statement("template <typename... LodOptions>"); |
| 7920 | statement("vec<T, 4> sample(float2 coord, LodOptions... options) const thread"); |
| 7921 | begin_scope(); |
| 7922 | statement("vec<T, 4> s = spvTextureSwizzle(do_sample(coord, options...), swizzle);"); |
| 7923 | statement("if (ycbcr_samp.get_ycbcr_model() == spvYCbCrModelConversion::rgb_identity)"); |
| 7924 | statement(" return s;"); |
| 7925 | statement(""); |
| 7926 | statement("switch (ycbcr_samp.get_ycbcr_range())"); |
| 7927 | begin_scope(); |
| 7928 | statement("case spvYCbCrRange::itu_full:"); |
| 7929 | statement(" s = spvExpandITUFullRange(s, ycbcr_samp.get_bpc());"); |
| 7930 | statement(" break;"); |
| 7931 | statement("case spvYCbCrRange::itu_narrow:"); |
| 7932 | statement(" s = spvExpandITUNarrowRange(s, ycbcr_samp.get_bpc());"); |
| 7933 | statement(" break;"); |
| 7934 | end_scope(); |
| 7935 | statement(""); |
| 7936 | statement("switch (ycbcr_samp.get_ycbcr_model())"); |
| 7937 | begin_scope(); |
| 7938 | statement("case spvYCbCrModelConversion::rgb_identity:"); // Silence Clang warning |
| 7939 | statement("case spvYCbCrModelConversion::ycbcr_identity:"); |
| 7940 | statement(" return s;"); |
| 7941 | statement("case spvYCbCrModelConversion::ycbcr_bt_709:"); |
| 7942 | statement(" return spvConvertYCbCrBT709(s);"); |
| 7943 | statement("case spvYCbCrModelConversion::ycbcr_bt_601:"); |
| 7944 | statement(" return spvConvertYCbCrBT601(s);"); |
| 7945 | statement("case spvYCbCrModelConversion::ycbcr_bt_2020:"); |
| 7946 | statement(" return spvConvertYCbCrBT2020(s);"); |
| 7947 | end_scope(); |
| 7948 | end_scope(); |
| 7949 | statement(""); |
| 7950 | // Sampler Y'CbCr conversion forbids offsets. |
| 7951 | statement("vec<T, 4> sample(float2 coord, int2 offset) const thread"); |
| 7952 | begin_scope(); |
| 7953 | if (msl_options.swizzle_texture_samples) |
| 7954 | statement("return spvTextureSwizzle(plane0.sample(samp, coord, offset), swizzle);"); |
| 7955 | else |
| 7956 | statement("return plane0.sample(samp, coord, offset);"); |
| 7957 | end_scope(); |
| 7958 | statement("template<typename lod_options>"); |
| 7959 | statement("vec<T, 4> sample(float2 coord, lod_options options, int2 offset) const thread"); |
| 7960 | begin_scope(); |
| 7961 | if (msl_options.swizzle_texture_samples) |
| 7962 | statement("return spvTextureSwizzle(plane0.sample(samp, coord, options, offset), swizzle);"); |
| 7963 | else |
| 7964 | statement("return plane0.sample(samp, coord, options, offset);"); |
| 7965 | end_scope(); |
| 7966 | statement("#if __HAVE_MIN_LOD_CLAMP__"); |
| 7967 | statement("vec<T, 4> sample(float2 coord, bias b, min_lod_clamp min_lod, int2 offset) const thread"); |
| 7968 | begin_scope(); |
| 7969 | statement("return plane0.sample(samp, coord, b, min_lod, offset);"); |
| 7970 | end_scope(); |
| 7971 | statement( |
| 7972 | "vec<T, 4> sample(float2 coord, gradient2d grad, min_lod_clamp min_lod, int2 offset) const thread"); |
| 7973 | begin_scope(); |
| 7974 | statement("return plane0.sample(samp, coord, grad, min_lod, offset);"); |
| 7975 | end_scope(); |
| 7976 | statement("#endif"); |
| 7977 | statement(""); |
| 7978 | // Y'CbCr conversion forbids all operations but sampling. |
| 7979 | statement("vec<T, 4> read(uint2 coord, uint lod = 0) const thread"); |
| 7980 | begin_scope(); |
| 7981 | statement("return plane0.read(coord, lod);"); |
| 7982 | end_scope(); |
| 7983 | statement(""); |
| 7984 | statement("vec<T, 4> gather(float2 coord, int2 offset = int2(0), component c = component::x) const thread"); |
| 7985 | begin_scope(); |
| 7986 | if (msl_options.swizzle_texture_samples) |
| 7987 | statement("return spvGatherSwizzle(plane0, samp, swizzle, c, coord, offset);"); |
| 7988 | else |
| 7989 | statement("return plane0.gather(samp, coord, offset, c);"); |
| 7990 | end_scope(); |
| 7991 | end_scope_decl(); |
| 7992 | statement(""); |
| 7993 | break; |
| 7994 | |
| 7995 | case SPVFuncImplRayQueryIntersectionParams: |
| 7996 | statement("intersection_params spvMakeIntersectionParams(uint flags)"); |
| 7997 | begin_scope(); |
| 7998 | statement("intersection_params ip;"); |
| 7999 | statement("if ((flags & ", RayFlagsOpaqueKHRMask, ") != 0)"); |
| 8000 | statement(" ip.force_opacity(forced_opacity::opaque);"); |
| 8001 | statement("if ((flags & ", RayFlagsNoOpaqueKHRMask, ") != 0)"); |
| 8002 | statement(" ip.force_opacity(forced_opacity::non_opaque);"); |
| 8003 | statement("if ((flags & ", RayFlagsTerminateOnFirstHitKHRMask, ") != 0)"); |
| 8004 | statement(" ip.accept_any_intersection(true);"); |
| 8005 | // RayFlagsSkipClosestHitShaderKHRMask is not available in MSL |
| 8006 | statement("if ((flags & ", RayFlagsCullBackFacingTrianglesKHRMask, ") != 0)"); |
| 8007 | statement(" ip.set_triangle_cull_mode(triangle_cull_mode::back);"); |
| 8008 | statement("if ((flags & ", RayFlagsCullFrontFacingTrianglesKHRMask, ") != 0)"); |
| 8009 | statement(" ip.set_triangle_cull_mode(triangle_cull_mode::front);"); |
| 8010 | statement("if ((flags & ", RayFlagsCullOpaqueKHRMask, ") != 0)"); |
| 8011 | statement(" ip.set_opacity_cull_mode(opacity_cull_mode::opaque);"); |
| 8012 | statement("if ((flags & ", RayFlagsCullNoOpaqueKHRMask, ") != 0)"); |
| 8013 | statement(" ip.set_opacity_cull_mode(opacity_cull_mode::non_opaque);"); |
| 8014 | statement("if ((flags & ", RayFlagsSkipTrianglesKHRMask, ") != 0)"); |
| 8015 | statement(" ip.set_geometry_cull_mode(geometry_cull_mode::triangle);"); |
| 8016 | statement("if ((flags & ", RayFlagsSkipAABBsKHRMask, ") != 0)"); |
| 8017 | statement(" ip.set_geometry_cull_mode(geometry_cull_mode::bounding_box);"); |
| 8018 | statement("return ip;"); |
| 8019 | end_scope(); |
| 8020 | statement(""); |
| 8021 | break; |
| 8022 | |
| 8023 | case SPVFuncImplVariableDescriptor: |
| 8024 | statement("template<typename T>"); |
| 8025 | statement("struct spvDescriptor"); |
| 8026 | begin_scope(); |
| 8027 | statement("T value;"); |
| 8028 | end_scope_decl(); |
| 8029 | statement(""); |
| 8030 | break; |
| 8031 | |
| 8032 | case SPVFuncImplVariableSizedDescriptor: |
| 8033 | statement("template<typename T>"); |
| 8034 | statement("struct spvBufferDescriptor"); |
| 8035 | begin_scope(); |
| 8036 | statement("T value;"); |
| 8037 | statement("int length;"); |
| 8038 | statement("const device T& operator -> () const device"); |
| 8039 | begin_scope(); |
| 8040 | statement("return value;"); |
| 8041 | end_scope(); |
| 8042 | statement("const device T& operator * () const device"); |
| 8043 | begin_scope(); |
| 8044 | statement("return value;"); |
| 8045 | end_scope(); |
| 8046 | end_scope_decl(); |
| 8047 | statement(""); |
| 8048 | break; |
| 8049 | |
| 8050 | case SPVFuncImplVariableDescriptorArray: |
| 8051 | if (spv_function_implementations.count(SPVFuncImplVariableDescriptor) != 0) |
| 8052 | { |
| 8053 | statement("template<typename T>"); |
| 8054 | statement("struct spvDescriptorArray"); |
| 8055 | begin_scope(); |
| 8056 | statement("spvDescriptorArray(const device spvDescriptor<T>* ptr) : ptr(&ptr->value)"); |
| 8057 | begin_scope(); |
| 8058 | end_scope(); |
| 8059 | statement("const device T& operator [] (size_t i) const"); |
| 8060 | begin_scope(); |
| 8061 | statement("return ptr[i];"); |
| 8062 | end_scope(); |
| 8063 | statement("const device T* ptr;"); |
| 8064 | end_scope_decl(); |
| 8065 | statement(""); |
| 8066 | } |
| 8067 | else |
| 8068 | { |
| 8069 | statement("template<typename T>"); |
| 8070 | statement("struct spvDescriptorArray;"); |
| 8071 | statement(""); |
| 8072 | } |
| 8073 | |
| 8074 | if (msl_options.runtime_array_rich_descriptor && |
| 8075 | spv_function_implementations.count(SPVFuncImplVariableSizedDescriptor) != 0) |
| 8076 | { |
| 8077 | statement("template<typename T>"); |
| 8078 | statement("struct spvDescriptorArray<device T*>"); |
| 8079 | begin_scope(); |
| 8080 | statement("spvDescriptorArray(const device spvBufferDescriptor<device T*>* ptr) : ptr(ptr)"); |
| 8081 | begin_scope(); |
| 8082 | end_scope(); |
| 8083 | statement("const device T* operator [] (size_t i) const"); |
| 8084 | begin_scope(); |
| 8085 | statement("return ptr[i].value;"); |
| 8086 | end_scope(); |
| 8087 | statement("const int length(int i) const"); |
| 8088 | begin_scope(); |
| 8089 | statement("return ptr[i].length;"); |
| 8090 | end_scope(); |
| 8091 | statement("const device spvBufferDescriptor<device T*>* ptr;"); |
| 8092 | end_scope_decl(); |
| 8093 | statement(""); |
| 8094 | } |
| 8095 | break; |
| 8096 | |
| 8097 | case SPVFuncImplPaddedStd140: |
| 8098 | // .data is used in access chain. |
| 8099 | statement("template <typename T>"); |
| 8100 | statement("struct spvPaddedStd140 { alignas(16) T data; };"); |
| 8101 | statement("template <typename T, int n>"); |
| 8102 | statement("using spvPaddedStd140Matrix = spvPaddedStd140<T>[n];"); |
| 8103 | statement(""); |
| 8104 | break; |
| 8105 | |
| 8106 | case SPVFuncImplReduceAdd: |
| 8107 | // Metal doesn't support __builtin_reduce_add or simd_reduce_add, so we need this. |
| 8108 | // Metal also doesn't support the other vector builtins, which would have been useful to make this a single template. |
| 8109 | |
| 8110 | statement("template <typename T>"); |
| 8111 | statement("T reduce_add(vec<T, 2> v) { return v.x + v.y; }"); |
| 8112 | |
| 8113 | statement("template <typename T>"); |
| 8114 | statement("T reduce_add(vec<T, 3> v) { return v.x + v.y + v.z; }"); |
| 8115 | |
| 8116 | statement("template <typename T>"); |
| 8117 | statement("T reduce_add(vec<T, 4> v) { return v.x + v.y + v.z + v.w; }"); |
| 8118 | |
| 8119 | statement(""); |
| 8120 | break; |
| 8121 | |
| 8122 | case SPVFuncImplImageFence: |
| 8123 | statement("template <typename ImageT>"); |
| 8124 | statement("void spvImageFence(ImageT img) { img.fence(); }"); |
| 8125 | statement(""); |
| 8126 | break; |
| 8127 | |
| 8128 | case SPVFuncImplTextureCast: |
| 8129 | statement("template <typename T, typename U>"); |
| 8130 | statement("T spvTextureCast(U img)"); |
| 8131 | begin_scope(); |
| 8132 | // MSL complains if you try to cast the texture itself, but casting the reference type is ... ok? *shrug* |
| 8133 | // Gotta go what you gotta do I suppose. |
| 8134 | statement("return reinterpret_cast<thread const T &>(img);"); |
| 8135 | end_scope(); |
| 8136 | statement(""); |
| 8137 | break; |
| 8138 | |
| 8139 | case SPVFuncImplMulExtended: |
| 8140 | // Compiler may hit an internal error with mulhi, but doesn't when encapsulated for some reason. |
| 8141 | statement("template<typename T, typename U, typename V>"); |
| 8142 | statement("[[clang::optnone]] T spvMulExtended(V l, V r)"); |
| 8143 | begin_scope(); |
| 8144 | statement("return T{U(l * r), U(mulhi(l, r))};"); |
| 8145 | end_scope(); |
| 8146 | statement(""); |
| 8147 | break; |
| 8148 | |
| 8149 | case SPVFuncImplSetMeshOutputsEXT: |
| 8150 | statement("void spvSetMeshOutputsEXT(uint gl_LocalInvocationIndex, threadgroup uint2& spvMeshSizes, uint vertexCount, uint primitiveCount)"); |
| 8151 | begin_scope(); |
| 8152 | statement("if (gl_LocalInvocationIndex == 0)"); |
| 8153 | begin_scope(); |
| 8154 | statement("spvMeshSizes.x = vertexCount;"); |
| 8155 | statement("spvMeshSizes.y = primitiveCount;"); |
| 8156 | end_scope(); |
| 8157 | end_scope(); |
| 8158 | statement(""); |
| 8159 | break; |
| 8160 | |
| 8161 | case SPVFuncImplAssume: |
| 8162 | statement_no_indent("#if defined(__has_builtin)"); |
| 8163 | statement_no_indent("#if !defined(SPV_ASSUME) && __has_builtin(__builtin_assume)"); |
| 8164 | statement_no_indent("#define SPV_ASSUME(x) __builtin_assume(x);"); |
| 8165 | statement_no_indent("#endif"); |
| 8166 | statement_no_indent("#if !defined(SPV_EXPECT) && __has_builtin(__builtin_expect)"); |
| 8167 | statement_no_indent("#define SPV_EXPECT(x, y) __builtin_expect(x, y);"); |
| 8168 | statement_no_indent("#endif"); |
| 8169 | statement_no_indent("#endif"); |
| 8170 | |
| 8171 | statement_no_indent("#ifndef SPV_ASSUME"); |
| 8172 | statement_no_indent("#define SPV_ASSUME(x)"); |
| 8173 | statement_no_indent("#endif"); |
| 8174 | |
| 8175 | statement_no_indent("#ifndef SPV_EXPECT"); |
| 8176 | statement_no_indent("#define SPV_EXPECT(x, y) x"); |
| 8177 | statement_no_indent("#endif"); |
| 8178 | |
| 8179 | break; |
| 8180 | |
| 8181 | default: |
| 8182 | break; |
| 8183 | } |
| 8184 | } |
| 8185 | } |
| 8186 | |
| 8187 | static string inject_top_level_storage_qualifier(const string &expr, const string &qualifier) |
| 8188 | { |
| 8189 | // Easier to do this through text munging since the qualifier does not exist in the type system at all, |
| 8190 | // and plumbing in all that information is not very helpful. |
| 8191 | size_t last_reference = expr.find_last_of('&'); |
| 8192 | size_t last_pointer = expr.find_last_of('*'); |
| 8193 | size_t last_significant = string::npos; |
| 8194 | |
| 8195 | if (last_reference == string::npos) |
| 8196 | last_significant = last_pointer; |
| 8197 | else if (last_pointer == string::npos) |
| 8198 | last_significant = last_reference; |
| 8199 | else |
| 8200 | last_significant = max<size_t>(last_reference, last_pointer); |
| 8201 | |
| 8202 | if (last_significant == string::npos) |
| 8203 | return join(qualifier, " ", expr); |
| 8204 | else |
| 8205 | { |
| 8206 | return join(expr.substr(0, last_significant + 1), " ", |
| 8207 | qualifier, expr.substr(last_significant + 1, string::npos)); |
| 8208 | } |
| 8209 | } |
| 8210 | |
| 8211 | void CompilerMSL::declare_constant_arrays() |
| 8212 | { |
| 8213 | bool fully_inlined = ir.ids_for_type[TypeFunction].size() == 1; |
| 8214 | |
| 8215 | // MSL cannot declare arrays inline (except when declaring a variable), so we must move them out to |
| 8216 | // global constants directly, so we are able to use constants as variable expressions. |
| 8217 | bool emitted = false; |
| 8218 | |
| 8219 | ir.for_each_typed_id<SPIRConstant>([&](uint32_t, SPIRConstant &c) { |
| 8220 | if (c.specialization) |
| 8221 | return; |
| 8222 | |
| 8223 | auto &type = this->get<SPIRType>(c.constant_type); |
| 8224 | // Constant arrays of non-primitive types (i.e. matrices) won't link properly into Metal libraries. |
| 8225 | // FIXME: However, hoisting constants to main() means we need to pass down constant arrays to leaf functions if they are used there. |
| 8226 | // If there are multiple functions in the module, drop this case to avoid breaking use cases which do not need to |
| 8227 | // link into Metal libraries. This is hacky. |
| 8228 | if (is_array(type) && (!fully_inlined || is_scalar(type) || is_vector(type))) |
| 8229 | { |
| 8230 | add_resource_name(c.self); |
| 8231 | auto name = to_name(c.self); |
| 8232 | statement(inject_top_level_storage_qualifier(variable_decl(type, name), "constant"), |
| 8233 | " = ", constant_expression(c), ";"); |
| 8234 | emitted = true; |
| 8235 | } |
| 8236 | }); |
| 8237 | |
| 8238 | if (emitted) |
| 8239 | statement(""); |
| 8240 | } |
| 8241 | |
| 8242 | // Constant arrays of non-primitive types (i.e. matrices) won't link properly into Metal libraries |
| 8243 | void CompilerMSL::declare_complex_constant_arrays() |
| 8244 | { |
| 8245 | // If we do not have a fully inlined module, we did not opt in to |
| 8246 | // declaring constant arrays of complex types. See CompilerMSL::declare_constant_arrays(). |
| 8247 | bool fully_inlined = ir.ids_for_type[TypeFunction].size() == 1; |
| 8248 | if (!fully_inlined) |
| 8249 | return; |
| 8250 | |
| 8251 | // MSL cannot declare arrays inline (except when declaring a variable), so we must move them out to |
| 8252 | // global constants directly, so we are able to use constants as variable expressions. |
| 8253 | bool emitted = false; |
| 8254 | |
| 8255 | ir.for_each_typed_id<SPIRConstant>([&](uint32_t, SPIRConstant &c) { |
| 8256 | if (c.specialization) |
| 8257 | return; |
| 8258 | |
| 8259 | auto &type = this->get<SPIRType>(c.constant_type); |
| 8260 | if (is_array(type) && !(is_scalar(type) || is_vector(type))) |
| 8261 | { |
| 8262 | add_resource_name(c.self); |
| 8263 | auto name = to_name(c.self); |
| 8264 | statement("", variable_decl(type, name), " = ", constant_expression(c), ";"); |
| 8265 | emitted = true; |
| 8266 | } |
| 8267 | }); |
| 8268 | |
| 8269 | if (emitted) |
| 8270 | statement(""); |
| 8271 | } |
| 8272 | |
| 8273 | void CompilerMSL::emit_resources() |
| 8274 | { |
| 8275 | declare_constant_arrays(); |
| 8276 | |
| 8277 | // Emit the special [[stage_in]] and [[stage_out]] interface blocks which we created. |
| 8278 | emit_interface_block(stage_out_var_id); |
| 8279 | emit_interface_block(patch_stage_out_var_id); |
| 8280 | emit_interface_block(stage_in_var_id); |
| 8281 | emit_interface_block(patch_stage_in_var_id); |
| 8282 | |
| 8283 | if (get_execution_model() == ExecutionModelMeshEXT) |
| 8284 | { |
| 8285 | auto &execution = get_entry_point(); |
| 8286 | const char *topology = ""; |
| 8287 | if (execution.flags.get(ExecutionModeOutputTrianglesEXT)) |
| 8288 | topology = "topology::triangle"; |
| 8289 | else if (execution.flags.get(ExecutionModeOutputLinesEXT)) |
| 8290 | topology = "topology::line"; |
| 8291 | else if (execution.flags.get(ExecutionModeOutputPoints)) |
| 8292 | topology = "topology::point"; |
| 8293 | |
| 8294 | const char *per_primitive = mesh_out_per_primitive ? "spvPerPrimitive" : "void"; |
| 8295 | statement("using spvMesh_t = mesh<", "spvPerVertex, ", per_primitive, ", ", execution.output_vertices, ", ", |
| 8296 | execution.output_primitives, ", ", topology, ">;"); |
| 8297 | statement(""); |
| 8298 | } |
| 8299 | } |
| 8300 | |
| 8301 | // Emit declarations for the specialization Metal function constants |
| 8302 | void CompilerMSL::emit_specialization_constants_and_structs() |
| 8303 | { |
| 8304 | SpecializationConstant wg_x, wg_y, wg_z; |
| 8305 | ID workgroup_size_id = get_work_group_size_specialization_constants(wg_x, wg_y, wg_z); |
| 8306 | if (workgroup_size_id == 0 && is_mesh_shader()) |
| 8307 | { |
| 8308 | auto &execution = get_entry_point(); |
| 8309 | statement("constant uint3 ", builtin_to_glsl(BuiltInWorkgroupSize, StorageClassWorkgroup), |
| 8310 | " [[maybe_unused]] = ", "uint3(", execution.workgroup_size.x, ", ", execution.workgroup_size.y, ", ", |
| 8311 | execution.workgroup_size.z, ");"); |
| 8312 | statement(""); |
| 8313 | } |
| 8314 | |
| 8315 | bool emitted = false; |
| 8316 | unordered_set<uint32_t> declared_structs; |
| 8317 | unordered_set<uint32_t> aligned_structs; |
| 8318 | |
| 8319 | // First, we need to deal with scalar block layout. |
| 8320 | // It is possible that a struct may have to be placed at an alignment which does not match the innate alignment of the struct itself. |
| 8321 | // In that case, if such a case exists for a struct, we must force that all elements of the struct become packed_ types. |
| 8322 | // This makes the struct alignment as small as physically possible. |
| 8323 | // When we actually align the struct later, we can insert padding as necessary to make the packed members behave like normally aligned types. |
| 8324 | ir.for_each_typed_id<SPIRType>([&](uint32_t type_id, const SPIRType &type) { |
| 8325 | if (type.basetype == SPIRType::Struct && |
| 8326 | has_extended_decoration(type_id, SPIRVCrossDecorationBufferBlockRepacked)) |
| 8327 | mark_scalar_layout_structs(type); |
| 8328 | }); |
| 8329 | |
| 8330 | bool builtin_block_type_is_required = is_mesh_shader(); |
| 8331 | // Very special case. If gl_PerVertex is initialized as an array (tessellation) |
| 8332 | // we have to potentially emit the gl_PerVertex struct type so that we can emit a constant LUT. |
| 8333 | ir.for_each_typed_id<SPIRConstant>([&](uint32_t, SPIRConstant &c) { |
| 8334 | auto &type = this->get<SPIRType>(c.constant_type); |
| 8335 | if (is_array(type) && has_decoration(type.self, DecorationBlock) && is_builtin_type(type)) |
| 8336 | builtin_block_type_is_required = true; |
| 8337 | }); |
| 8338 | |
| 8339 | // Very particular use of the soft loop lock. |
| 8340 | // align_struct may need to create custom types on the fly, but we don't care about |
| 8341 | // these types for purpose of iterating over them in ir.ids_for_type and friends. |
| 8342 | auto loop_lock = ir.create_loop_soft_lock(); |
| 8343 | |
| 8344 | // Physical storage buffer pointers can have cyclical references, |
| 8345 | // so emit forward declarations of them before other structs. |
| 8346 | // Ignore type_id because we want the underlying struct type from the pointer. |
| 8347 | ir.for_each_typed_id<SPIRType>([&](uint32_t /* type_id */, const SPIRType &type) { |
| 8348 | if (type.basetype == SPIRType::Struct && |
| 8349 | type.pointer && type.storage == StorageClassPhysicalStorageBuffer && |
| 8350 | declared_structs.count(type.self) == 0) |
| 8351 | { |
| 8352 | statement("struct ", to_name(type.self), ";"); |
| 8353 | declared_structs.insert(type.self); |
| 8354 | emitted = true; |
| 8355 | } |
| 8356 | }); |
| 8357 | if (emitted) |
| 8358 | statement(""); |
| 8359 | |
| 8360 | emitted = false; |
| 8361 | declared_structs.clear(); |
| 8362 | |
| 8363 | // It is possible to have multiple spec constants that use the same spec constant ID. |
| 8364 | // The most common cause of this is defining spec constants in GLSL while also declaring |
| 8365 | // the workgroup size to use those spec constants. But, Metal forbids declaring more than |
| 8366 | // one variable with the same function constant ID. |
| 8367 | // In this case, we must only declare one variable with the [[function_constant(id)]] |
| 8368 | // attribute, and use its initializer to initialize all the spec constants with |
| 8369 | // that ID. |
| 8370 | std::unordered_map<uint32_t, ConstantID> unique_func_constants; |
| 8371 | |
| 8372 | for (auto &id_ : ir.ids_for_constant_undef_or_type) |
| 8373 | { |
| 8374 | auto &id = ir.ids[id_]; |
| 8375 | |
| 8376 | if (id.get_type() == TypeConstant) |
| 8377 | { |
| 8378 | auto &c = id.get<SPIRConstant>(); |
| 8379 | |
| 8380 | if (c.self == workgroup_size_id) |
| 8381 | { |
| 8382 | // TODO: This can be expressed as a [[threads_per_threadgroup]] input semantic, but we need to know |
| 8383 | // the work group size at compile time in SPIR-V, and [[threads_per_threadgroup]] would need to be passed around as a global. |
| 8384 | // The work group size may be a specialization constant. |
| 8385 | statement("constant uint3 ", builtin_to_glsl(BuiltInWorkgroupSize, StorageClassWorkgroup), |
| 8386 | " [[maybe_unused]] = ", constant_expression(get<SPIRConstant>(workgroup_size_id)), ";"); |
| 8387 | emitted = true; |
| 8388 | } |
| 8389 | else if (c.specialization) |
| 8390 | { |
| 8391 | auto &type = get<SPIRType>(c.constant_type); |
| 8392 | string sc_type_name = type_to_glsl(type); |
| 8393 | add_resource_name(c.self); |
| 8394 | string sc_name = to_name(c.self); |
| 8395 | |
| 8396 | // Function constants are only supported in MSL 1.2 and later. |
| 8397 | // If we don't support it just declare the "default" directly. |
| 8398 | // This "default" value can be overridden to the true specialization constant by the API user. |
| 8399 | // Specialization constants which are used as array length expressions cannot be function constants in MSL, |
| 8400 | // so just fall back to macros. |
| 8401 | if (msl_options.supports_msl_version(1, 2) && has_decoration(c.self, DecorationSpecId) && |
| 8402 | !c.is_used_as_array_length) |
| 8403 | { |
| 8404 | // Only scalar, non-composite values can be function constants. |
| 8405 | uint32_t constant_id = get_decoration(c.self, DecorationSpecId); |
| 8406 | if (!unique_func_constants.count(constant_id)) |
| 8407 | unique_func_constants.insert(make_pair(constant_id, c.self)); |
| 8408 | SPIRType::BaseType sc_tmp_type = expression_type(unique_func_constants[constant_id]).basetype; |
| 8409 | string sc_tmp_name = to_name(unique_func_constants[constant_id]) + "_tmp"; |
| 8410 | if (unique_func_constants[constant_id] == c.self) |
| 8411 | statement("constant ", sc_type_name, " ", sc_tmp_name, " [[function_constant(", constant_id, |
| 8412 | ")]];"); |
| 8413 | statement("constant ", sc_type_name, " ", sc_name, " = is_function_constant_defined(", sc_tmp_name, |
| 8414 | ") ? ", bitcast_expression(type, sc_tmp_type, sc_tmp_name), " : ", constant_expression(c), |
| 8415 | ";"); |
| 8416 | } |
| 8417 | else if (has_decoration(c.self, DecorationSpecId)) |
| 8418 | { |
| 8419 | // Fallback to macro overrides. |
| 8420 | uint32_t constant_id = get_decoration(c.self, DecorationSpecId); |
| 8421 | c.specialization_constant_macro_name = |
| 8422 | constant_value_macro_name(constant_id); |
| 8423 | |
| 8424 | statement("#ifndef ", c.specialization_constant_macro_name); |
| 8425 | statement("#define ", c.specialization_constant_macro_name, " ", constant_expression(c)); |
| 8426 | statement("#endif"); |
| 8427 | statement("constant ", sc_type_name, " ", sc_name, " = ", c.specialization_constant_macro_name, |
| 8428 | ";"); |
| 8429 | |
| 8430 | // Record the usage of macro |
| 8431 | constant_macro_ids.insert(constant_id); |
| 8432 | } |
| 8433 | else |
| 8434 | { |
| 8435 | // Composite specialization constants must be built from other specialization constants. |
| 8436 | statement("constant ", sc_type_name, " ", sc_name, " = ", constant_expression(c), ";"); |
| 8437 | } |
| 8438 | emitted = true; |
| 8439 | } |
| 8440 | } |
| 8441 | else if (id.get_type() == TypeConstantOp) |
| 8442 | { |
| 8443 | auto &c = id.get<SPIRConstantOp>(); |
| 8444 | auto &type = get<SPIRType>(c.basetype); |
| 8445 | add_resource_name(c.self); |
| 8446 | auto name = to_name(c.self); |
| 8447 | statement("constant ", variable_decl(type, name), " = ", constant_op_expression(c), ";"); |
| 8448 | emitted = true; |
| 8449 | } |
| 8450 | else if (id.get_type() == TypeType) |
| 8451 | { |
| 8452 | // Output non-builtin interface structs. These include local function structs |
| 8453 | // and structs nested within uniform and read-write buffers. |
| 8454 | auto &type = id.get<SPIRType>(); |
| 8455 | TypeID type_id = type.self; |
| 8456 | |
| 8457 | bool is_struct = (type.basetype == SPIRType::Struct) && type.array.empty() && !type.pointer; |
| 8458 | bool is_block = |
| 8459 | has_decoration(type.self, DecorationBlock) || has_decoration(type.self, DecorationBufferBlock); |
| 8460 | |
| 8461 | bool is_builtin_block = is_block && is_builtin_type(type); |
| 8462 | bool is_declarable_struct = is_struct && (!is_builtin_block || builtin_block_type_is_required); |
| 8463 | |
| 8464 | // We'll declare this later. |
| 8465 | if (stage_out_var_id && get_stage_out_struct_type().self == type_id) |
| 8466 | is_declarable_struct = false; |
| 8467 | if (patch_stage_out_var_id && get_patch_stage_out_struct_type().self == type_id) |
| 8468 | is_declarable_struct = false; |
| 8469 | if (stage_in_var_id && get_stage_in_struct_type().self == type_id) |
| 8470 | is_declarable_struct = false; |
| 8471 | if (patch_stage_in_var_id && get_patch_stage_in_struct_type().self == type_id) |
| 8472 | is_declarable_struct = false; |
| 8473 | |
| 8474 | // Special case. Declare builtin struct anyways if we need to emit a threadgroup version of it. |
| 8475 | if (stage_out_masked_builtin_type_id == type_id) |
| 8476 | is_declarable_struct = true; |
| 8477 | |
| 8478 | // Align and emit declarable structs...but avoid declaring each more than once. |
| 8479 | if (is_declarable_struct && declared_structs.count(type_id) == 0) |
| 8480 | { |
| 8481 | if (emitted) |
| 8482 | statement(""); |
| 8483 | emitted = false; |
| 8484 | |
| 8485 | declared_structs.insert(type_id); |
| 8486 | |
| 8487 | if (has_extended_decoration(type_id, SPIRVCrossDecorationBufferBlockRepacked)) |
| 8488 | align_struct(type, aligned_structs); |
| 8489 | |
| 8490 | // Make sure we declare the underlying struct type, and not the "decorated" type with pointers, etc. |
| 8491 | emit_struct(get<SPIRType>(type_id)); |
| 8492 | } |
| 8493 | } |
| 8494 | else if (id.get_type() == TypeUndef) |
| 8495 | { |
| 8496 | auto &undef = id.get<SPIRUndef>(); |
| 8497 | auto &type = get<SPIRType>(undef.basetype); |
| 8498 | // OpUndef can be void for some reason ... |
| 8499 | if (type.basetype == SPIRType::Void) |
| 8500 | return; |
| 8501 | |
| 8502 | // Undefined global memory is not allowed in MSL. |
| 8503 | // Declare constant and init to zeros. Use {}, as global constructors can break Metal. |
| 8504 | statement( |
| 8505 | inject_top_level_storage_qualifier(variable_decl(type, to_name(undef.self), undef.self), "constant"), |
| 8506 | " = {};"); |
| 8507 | emitted = true; |
| 8508 | } |
| 8509 | } |
| 8510 | |
| 8511 | if (emitted) |
| 8512 | statement(""); |
| 8513 | } |
| 8514 | |
| 8515 | void CompilerMSL::emit_binary_ptr_op(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1, const char *op) |
| 8516 | { |
| 8517 | bool forward = should_forward(op0) && should_forward(op1); |
| 8518 | emit_op(result_type, result_id, join(to_ptr_expression(op0), " ", op, " ", to_ptr_expression(op1)), forward); |
| 8519 | inherit_expression_dependencies(result_id, op0); |
| 8520 | inherit_expression_dependencies(result_id, op1); |
| 8521 | } |
| 8522 | |
| 8523 | string CompilerMSL::to_ptr_expression(uint32_t id, bool register_expression_read) |
| 8524 | { |
| 8525 | auto *e = maybe_get<SPIRExpression>(id); |
| 8526 | auto expr = enclose_expression(e && e->need_transpose ? e->expression : to_expression(id, register_expression_read)); |
| 8527 | if (!should_dereference(id)) |
| 8528 | expr = address_of_expression(expr); |
| 8529 | return expr; |
| 8530 | } |
| 8531 | |
| 8532 | void CompilerMSL::emit_binary_unord_op(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1, |
| 8533 | const char *op) |
| 8534 | { |
| 8535 | bool forward = should_forward(op0) && should_forward(op1); |
| 8536 | emit_op(result_type, result_id, |
| 8537 | join("(isunordered(", to_enclosed_unpacked_expression(op0), ", ", to_enclosed_unpacked_expression(op1), |
| 8538 | ") || ", to_enclosed_unpacked_expression(op0), " ", op, " ", to_enclosed_unpacked_expression(op1), |
| 8539 | ")"), |
| 8540 | forward); |
| 8541 | |
| 8542 | inherit_expression_dependencies(result_id, op0); |
| 8543 | inherit_expression_dependencies(result_id, op1); |
| 8544 | } |
| 8545 | |
| 8546 | bool CompilerMSL::emit_tessellation_io_load(uint32_t result_type_id, uint32_t id, uint32_t ptr) |
| 8547 | { |
| 8548 | auto &ptr_type = expression_type(ptr); |
| 8549 | auto &result_type = get<SPIRType>(result_type_id); |
| 8550 | if (ptr_type.storage != StorageClassInput && ptr_type.storage != StorageClassOutput) |
| 8551 | return false; |
| 8552 | if (ptr_type.storage == StorageClassOutput && is_tese_shader()) |
| 8553 | return false; |
| 8554 | |
| 8555 | if (has_decoration(ptr, DecorationPatch)) |
| 8556 | return false; |
| 8557 | bool ptr_is_io_variable = ir.ids[ptr].get_type() == TypeVariable; |
| 8558 | |
| 8559 | bool flattened_io = variable_storage_requires_stage_io(ptr_type.storage); |
| 8560 | |
| 8561 | bool flat_data_type = flattened_io && |
| 8562 | (is_matrix(result_type) || is_array(result_type) || result_type.basetype == SPIRType::Struct); |
| 8563 | |
| 8564 | // Edge case, even with multi-patch workgroups, we still need to unroll load |
| 8565 | // if we're loading control points directly. |
| 8566 | if (ptr_is_io_variable && is_array(result_type)) |
| 8567 | flat_data_type = true; |
| 8568 | |
| 8569 | if (!flat_data_type) |
| 8570 | return false; |
| 8571 | |
| 8572 | // Now, we must unflatten a composite type and take care of interleaving array access with gl_in/gl_out. |
| 8573 | // Lots of painful code duplication since we *really* should not unroll these kinds of loads in entry point fixup |
| 8574 | // unless we're forced to do this when the code is emitting inoptimal OpLoads. |
| 8575 | string expr; |
| 8576 | |
| 8577 | uint32_t interface_index = get_extended_decoration(ptr, SPIRVCrossDecorationInterfaceMemberIndex); |
| 8578 | auto *var = maybe_get_backing_variable(ptr); |
| 8579 | auto &expr_type = get_pointee_type(ptr_type.self); |
| 8580 | |
| 8581 | const auto &iface_type = expression_type(stage_in_ptr_var_id); |
| 8582 | |
| 8583 | if (!flattened_io) |
| 8584 | { |
| 8585 | // Simplest case for multi-patch workgroups, just unroll array as-is. |
| 8586 | if (interface_index == uint32_t(-1)) |
| 8587 | return false; |
| 8588 | |
| 8589 | expr += type_to_glsl(result_type) + "({ "; |
| 8590 | uint32_t num_control_points = to_array_size_literal(result_type, uint32_t(result_type.array.size()) - 1); |
| 8591 | |
| 8592 | for (uint32_t i = 0; i < num_control_points; i++) |
| 8593 | { |
| 8594 | const uint32_t indices[2] = { i, interface_index }; |
| 8595 | AccessChainMeta meta; |
| 8596 | expr += access_chain_internal(stage_in_ptr_var_id, indices, 2, |
| 8597 | ACCESS_CHAIN_INDEX_IS_LITERAL_BIT | ACCESS_CHAIN_PTR_CHAIN_BIT, &meta); |
| 8598 | if (i + 1 < num_control_points) |
| 8599 | expr += ", "; |
| 8600 | } |
| 8601 | expr += " })"; |
| 8602 | } |
| 8603 | else if (result_type.array.size() > 2) |
| 8604 | { |
| 8605 | SPIRV_CROSS_THROW("Cannot load tessellation IO variables with more than 2 dimensions."); |
| 8606 | } |
| 8607 | else if (result_type.array.size() == 2) |
| 8608 | { |
| 8609 | if (!ptr_is_io_variable) |
| 8610 | SPIRV_CROSS_THROW("Loading an array-of-array must be loaded directly from an IO variable."); |
| 8611 | if (interface_index == uint32_t(-1)) |
| 8612 | SPIRV_CROSS_THROW("Interface index is unknown. Cannot continue."); |
| 8613 | if (result_type.basetype == SPIRType::Struct || is_matrix(result_type)) |
| 8614 | SPIRV_CROSS_THROW("Cannot load array-of-array of composite type in tessellation IO."); |
| 8615 | |
| 8616 | expr += type_to_glsl(result_type) + "({ "; |
| 8617 | uint32_t num_control_points = to_array_size_literal(result_type, 1); |
| 8618 | uint32_t base_interface_index = interface_index; |
| 8619 | |
| 8620 | auto &sub_type = get<SPIRType>(result_type.parent_type); |
| 8621 | |
| 8622 | for (uint32_t i = 0; i < num_control_points; i++) |
| 8623 | { |
| 8624 | expr += type_to_glsl(sub_type) + "({ "; |
| 8625 | interface_index = base_interface_index; |
| 8626 | uint32_t array_size = to_array_size_literal(result_type, 0); |
| 8627 | for (uint32_t j = 0; j < array_size; j++, interface_index++) |
| 8628 | { |
| 8629 | const uint32_t indices[2] = { i, interface_index }; |
| 8630 | |
| 8631 | AccessChainMeta meta; |
| 8632 | expr += access_chain_internal(stage_in_ptr_var_id, indices, 2, |
| 8633 | ACCESS_CHAIN_INDEX_IS_LITERAL_BIT | ACCESS_CHAIN_PTR_CHAIN_BIT, &meta); |
| 8634 | if (!is_matrix(sub_type) && sub_type.basetype != SPIRType::Struct && |
| 8635 | expr_type.vecsize > sub_type.vecsize) |
| 8636 | expr += vector_swizzle(sub_type.vecsize, 0); |
| 8637 | |
| 8638 | if (j + 1 < array_size) |
| 8639 | expr += ", "; |
| 8640 | } |
| 8641 | expr += " })"; |
| 8642 | if (i + 1 < num_control_points) |
| 8643 | expr += ", "; |
| 8644 | } |
| 8645 | expr += " })"; |
| 8646 | } |
| 8647 | else if (result_type.basetype == SPIRType::Struct) |
| 8648 | { |
| 8649 | bool is_array_of_struct = is_array(result_type); |
| 8650 | if (is_array_of_struct && !ptr_is_io_variable) |
| 8651 | SPIRV_CROSS_THROW("Loading array of struct from IO variable must come directly from IO variable."); |
| 8652 | |
| 8653 | uint32_t num_control_points = 1; |
| 8654 | if (is_array_of_struct) |
| 8655 | { |
| 8656 | num_control_points = to_array_size_literal(result_type, 0); |
| 8657 | expr += type_to_glsl(result_type) + "({ "; |
| 8658 | } |
| 8659 | |
| 8660 | auto &struct_type = is_array_of_struct ? get<SPIRType>(result_type.parent_type) : result_type; |
| 8661 | assert(struct_type.array.empty()); |
| 8662 | |
| 8663 | for (uint32_t i = 0; i < num_control_points; i++) |
| 8664 | { |
| 8665 | expr += type_to_glsl(struct_type) + "{ "; |
| 8666 | for (uint32_t j = 0; j < uint32_t(struct_type.member_types.size()); j++) |
| 8667 | { |
| 8668 | // The base interface index is stored per variable for structs. |
| 8669 | if (var) |
| 8670 | { |
| 8671 | interface_index = |
| 8672 | get_extended_member_decoration(var->self, j, SPIRVCrossDecorationInterfaceMemberIndex); |
| 8673 | } |
| 8674 | |
| 8675 | if (interface_index == uint32_t(-1)) |
| 8676 | SPIRV_CROSS_THROW("Interface index is unknown. Cannot continue."); |
| 8677 | |
| 8678 | const auto &mbr_type = get<SPIRType>(struct_type.member_types[j]); |
| 8679 | const auto &expr_mbr_type = get<SPIRType>(expr_type.member_types[j]); |
| 8680 | if (is_matrix(mbr_type) && ptr_type.storage == StorageClassInput) |
| 8681 | { |
| 8682 | expr += type_to_glsl(mbr_type) + "("; |
| 8683 | for (uint32_t k = 0; k < mbr_type.columns; k++, interface_index++) |
| 8684 | { |
| 8685 | if (is_array_of_struct) |
| 8686 | { |
| 8687 | const uint32_t indices[2] = { i, interface_index }; |
| 8688 | AccessChainMeta meta; |
| 8689 | expr += access_chain_internal( |
| 8690 | stage_in_ptr_var_id, indices, 2, |
| 8691 | ACCESS_CHAIN_INDEX_IS_LITERAL_BIT | ACCESS_CHAIN_PTR_CHAIN_BIT, &meta); |
| 8692 | } |
| 8693 | else |
| 8694 | expr += to_expression(ptr) + "." + to_member_name(iface_type, interface_index); |
| 8695 | if (expr_mbr_type.vecsize > mbr_type.vecsize) |
| 8696 | expr += vector_swizzle(mbr_type.vecsize, 0); |
| 8697 | |
| 8698 | if (k + 1 < mbr_type.columns) |
| 8699 | expr += ", "; |
| 8700 | } |
| 8701 | expr += ")"; |
| 8702 | } |
| 8703 | else if (is_array(mbr_type)) |
| 8704 | { |
| 8705 | expr += type_to_glsl(mbr_type) + "({ "; |
| 8706 | uint32_t array_size = to_array_size_literal(mbr_type, 0); |
| 8707 | for (uint32_t k = 0; k < array_size; k++, interface_index++) |
| 8708 | { |
| 8709 | if (is_array_of_struct) |
| 8710 | { |
| 8711 | const uint32_t indices[2] = { i, interface_index }; |
| 8712 | AccessChainMeta meta; |
| 8713 | expr += access_chain_internal( |
| 8714 | stage_in_ptr_var_id, indices, 2, |
| 8715 | ACCESS_CHAIN_INDEX_IS_LITERAL_BIT | ACCESS_CHAIN_PTR_CHAIN_BIT, &meta); |
| 8716 | } |
| 8717 | else |
| 8718 | expr += to_expression(ptr) + "." + to_member_name(iface_type, interface_index); |
| 8719 | if (expr_mbr_type.vecsize > mbr_type.vecsize) |
| 8720 | expr += vector_swizzle(mbr_type.vecsize, 0); |
| 8721 | |
| 8722 | if (k + 1 < array_size) |
| 8723 | expr += ", "; |
| 8724 | } |
| 8725 | expr += " })"; |
| 8726 | } |
| 8727 | else |
| 8728 | { |
| 8729 | if (is_array_of_struct) |
| 8730 | { |
| 8731 | const uint32_t indices[2] = { i, interface_index }; |
| 8732 | AccessChainMeta meta; |
| 8733 | expr += access_chain_internal(stage_in_ptr_var_id, indices, 2, |
| 8734 | ACCESS_CHAIN_INDEX_IS_LITERAL_BIT | ACCESS_CHAIN_PTR_CHAIN_BIT, |
| 8735 | &meta); |
| 8736 | } |
| 8737 | else |
| 8738 | expr += to_expression(ptr) + "." + to_member_name(iface_type, interface_index); |
| 8739 | if (expr_mbr_type.vecsize > mbr_type.vecsize) |
| 8740 | expr += vector_swizzle(mbr_type.vecsize, 0); |
| 8741 | } |
| 8742 | |
| 8743 | if (j + 1 < struct_type.member_types.size()) |
| 8744 | expr += ", "; |
| 8745 | } |
| 8746 | expr += " }"; |
| 8747 | if (i + 1 < num_control_points) |
| 8748 | expr += ", "; |
| 8749 | } |
| 8750 | if (is_array_of_struct) |
| 8751 | expr += " })"; |
| 8752 | } |
| 8753 | else if (is_matrix(result_type)) |
| 8754 | { |
| 8755 | bool is_array_of_matrix = is_array(result_type); |
| 8756 | if (is_array_of_matrix && !ptr_is_io_variable) |
| 8757 | SPIRV_CROSS_THROW("Loading array of matrix from IO variable must come directly from IO variable."); |
| 8758 | if (interface_index == uint32_t(-1)) |
| 8759 | SPIRV_CROSS_THROW("Interface index is unknown. Cannot continue."); |
| 8760 | |
| 8761 | if (is_array_of_matrix) |
| 8762 | { |
| 8763 | // Loading a matrix from each control point. |
| 8764 | uint32_t base_interface_index = interface_index; |
| 8765 | uint32_t num_control_points = to_array_size_literal(result_type, 0); |
| 8766 | expr += type_to_glsl(result_type) + "({ "; |
| 8767 | |
| 8768 | auto &matrix_type = get_variable_element_type(get<SPIRVariable>(ptr)); |
| 8769 | |
| 8770 | for (uint32_t i = 0; i < num_control_points; i++) |
| 8771 | { |
| 8772 | interface_index = base_interface_index; |
| 8773 | expr += type_to_glsl(matrix_type) + "("; |
| 8774 | for (uint32_t j = 0; j < result_type.columns; j++, interface_index++) |
| 8775 | { |
| 8776 | const uint32_t indices[2] = { i, interface_index }; |
| 8777 | |
| 8778 | AccessChainMeta meta; |
| 8779 | expr += access_chain_internal(stage_in_ptr_var_id, indices, 2, |
| 8780 | ACCESS_CHAIN_INDEX_IS_LITERAL_BIT | ACCESS_CHAIN_PTR_CHAIN_BIT, &meta); |
| 8781 | if (expr_type.vecsize > result_type.vecsize) |
| 8782 | expr += vector_swizzle(result_type.vecsize, 0); |
| 8783 | if (j + 1 < result_type.columns) |
| 8784 | expr += ", "; |
| 8785 | } |
| 8786 | expr += ")"; |
| 8787 | if (i + 1 < num_control_points) |
| 8788 | expr += ", "; |
| 8789 | } |
| 8790 | |
| 8791 | expr += " })"; |
| 8792 | } |
| 8793 | else |
| 8794 | { |
| 8795 | expr += type_to_glsl(result_type) + "("; |
| 8796 | for (uint32_t i = 0; i < result_type.columns; i++, interface_index++) |
| 8797 | { |
| 8798 | expr += to_expression(ptr) + "." + to_member_name(iface_type, interface_index); |
| 8799 | if (expr_type.vecsize > result_type.vecsize) |
| 8800 | expr += vector_swizzle(result_type.vecsize, 0); |
| 8801 | if (i + 1 < result_type.columns) |
| 8802 | expr += ", "; |
| 8803 | } |
| 8804 | expr += ")"; |
| 8805 | } |
| 8806 | } |
| 8807 | else if (ptr_is_io_variable) |
| 8808 | { |
| 8809 | assert(is_array(result_type)); |
| 8810 | assert(result_type.array.size() == 1); |
| 8811 | if (interface_index == uint32_t(-1)) |
| 8812 | SPIRV_CROSS_THROW("Interface index is unknown. Cannot continue."); |
| 8813 | |
| 8814 | // We're loading an array directly from a global variable. |
| 8815 | // This means we're loading one member from each control point. |
| 8816 | expr += type_to_glsl(result_type) + "({ "; |
| 8817 | uint32_t num_control_points = to_array_size_literal(result_type, 0); |
| 8818 | |
| 8819 | for (uint32_t i = 0; i < num_control_points; i++) |
| 8820 | { |
| 8821 | const uint32_t indices[2] = { i, interface_index }; |
| 8822 | |
| 8823 | AccessChainMeta meta; |
| 8824 | expr += access_chain_internal(stage_in_ptr_var_id, indices, 2, |
| 8825 | ACCESS_CHAIN_INDEX_IS_LITERAL_BIT | ACCESS_CHAIN_PTR_CHAIN_BIT, &meta); |
| 8826 | if (expr_type.vecsize > result_type.vecsize) |
| 8827 | expr += vector_swizzle(result_type.vecsize, 0); |
| 8828 | |
| 8829 | if (i + 1 < num_control_points) |
| 8830 | expr += ", "; |
| 8831 | } |
| 8832 | expr += " })"; |
| 8833 | } |
| 8834 | else |
| 8835 | { |
| 8836 | // We're loading an array from a concrete control point. |
| 8837 | assert(is_array(result_type)); |
| 8838 | assert(result_type.array.size() == 1); |
| 8839 | if (interface_index == uint32_t(-1)) |
| 8840 | SPIRV_CROSS_THROW("Interface index is unknown. Cannot continue."); |
| 8841 | |
| 8842 | expr += type_to_glsl(result_type) + "({ "; |
| 8843 | uint32_t array_size = to_array_size_literal(result_type, 0); |
| 8844 | for (uint32_t i = 0; i < array_size; i++, interface_index++) |
| 8845 | { |
| 8846 | expr += to_expression(ptr) + "." + to_member_name(iface_type, interface_index); |
| 8847 | if (expr_type.vecsize > result_type.vecsize) |
| 8848 | expr += vector_swizzle(result_type.vecsize, 0); |
| 8849 | if (i + 1 < array_size) |
| 8850 | expr += ", "; |
| 8851 | } |
| 8852 | expr += " })"; |
| 8853 | } |
| 8854 | |
| 8855 | emit_op(result_type_id, id, expr, false); |
| 8856 | register_read(id, ptr, false); |
| 8857 | return true; |
| 8858 | } |
| 8859 | |
| 8860 | bool CompilerMSL::emit_tessellation_access_chain(const uint32_t *ops, uint32_t length) |
| 8861 | { |
| 8862 | // If this is a per-vertex output, remap it to the I/O array buffer. |
| 8863 | |
| 8864 | // Any object which did not go through IO flattening shenanigans will go there instead. |
| 8865 | // We will unflatten on-demand instead as needed, but not all possible cases can be supported, especially with arrays. |
| 8866 | |
| 8867 | auto *var = maybe_get_backing_variable(ops[2]); |
| 8868 | bool patch = false; |
| 8869 | bool flat_data = false; |
| 8870 | bool ptr_is_chain = false; |
| 8871 | bool flatten_composites = false; |
| 8872 | |
| 8873 | bool is_block = false; |
| 8874 | bool is_arrayed = false; |
| 8875 | |
| 8876 | if (var) |
| 8877 | { |
| 8878 | auto &type = get_variable_data_type(*var); |
| 8879 | is_block = has_decoration(type.self, DecorationBlock); |
| 8880 | is_arrayed = !type.array.empty(); |
| 8881 | |
| 8882 | flatten_composites = variable_storage_requires_stage_io(var->storage); |
| 8883 | patch = has_decoration(ops[2], DecorationPatch) || is_patch_block(type); |
| 8884 | |
| 8885 | // Should match strip_array in add_interface_block. |
| 8886 | flat_data = var->storage == StorageClassInput || (var->storage == StorageClassOutput && is_tesc_shader()); |
| 8887 | |
| 8888 | // Patch inputs are treated as normal block IO variables, so they don't deal with this path at all. |
| 8889 | if (patch && (!is_block || is_arrayed || var->storage == StorageClassInput)) |
| 8890 | flat_data = false; |
| 8891 | |
| 8892 | // We might have a chained access chain, where |
| 8893 | // we first take the access chain to the control point, and then we chain into a member or something similar. |
| 8894 | // In this case, we need to skip gl_in/gl_out remapping. |
| 8895 | // Also, skip ptr chain for patches. |
| 8896 | ptr_is_chain = var->self != ID(ops[2]); |
| 8897 | } |
| 8898 | |
| 8899 | bool builtin_variable = false; |
| 8900 | bool variable_is_flat = false; |
| 8901 | |
| 8902 | if (var && flat_data) |
| 8903 | { |
| 8904 | builtin_variable = is_builtin_variable(*var); |
| 8905 | |
| 8906 | BuiltIn bi_type = BuiltInMax; |
| 8907 | if (builtin_variable && !is_block) |
| 8908 | bi_type = BuiltIn(get_decoration(var->self, DecorationBuiltIn)); |
| 8909 | |
| 8910 | variable_is_flat = !builtin_variable || is_block || |
| 8911 | bi_type == BuiltInPosition || bi_type == BuiltInPointSize || |
| 8912 | bi_type == BuiltInClipDistance || bi_type == BuiltInCullDistance; |
| 8913 | } |
| 8914 | |
| 8915 | if (variable_is_flat) |
| 8916 | { |
| 8917 | // If output is masked, it is emitted as a "normal" variable, just go through normal code paths. |
| 8918 | // Only check this for the first level of access chain. |
| 8919 | // Dealing with this for partial access chains should be possible, but awkward. |
| 8920 | if (var->storage == StorageClassOutput && !ptr_is_chain) |
| 8921 | { |
| 8922 | bool masked = false; |
| 8923 | if (is_block) |
| 8924 | { |
| 8925 | uint32_t relevant_member_index = patch ? 3 : 4; |
| 8926 | // FIXME: This won't work properly if the application first access chains into gl_out element, |
| 8927 | // then access chains into the member. Super weird, but theoretically possible ... |
| 8928 | if (length > relevant_member_index) |
| 8929 | { |
| 8930 | uint32_t mbr_idx = get<SPIRConstant>(ops[relevant_member_index]).scalar(); |
| 8931 | masked = is_stage_output_block_member_masked(*var, mbr_idx, true); |
| 8932 | } |
| 8933 | } |
| 8934 | else if (var) |
| 8935 | masked = is_stage_output_variable_masked(*var); |
| 8936 | |
| 8937 | if (masked) |
| 8938 | return false; |
| 8939 | } |
| 8940 | |
| 8941 | AccessChainMeta meta; |
| 8942 | SmallVector<uint32_t> indices; |
| 8943 | uint32_t next_id = ir.increase_bound_by(1); |
| 8944 | |
| 8945 | indices.reserve(length - 3 + 1); |
| 8946 | |
| 8947 | uint32_t first_non_array_index = (ptr_is_chain ? 3 : 4) - (patch ? 1 : 0); |
| 8948 | |
| 8949 | VariableID stage_var_id; |
| 8950 | if (patch) |
| 8951 | stage_var_id = var->storage == StorageClassInput ? patch_stage_in_var_id : patch_stage_out_var_id; |
| 8952 | else |
| 8953 | stage_var_id = var->storage == StorageClassInput ? stage_in_ptr_var_id : stage_out_ptr_var_id; |
| 8954 | |
| 8955 | VariableID ptr = ptr_is_chain ? VariableID(ops[2]) : stage_var_id; |
| 8956 | if (!ptr_is_chain && !patch) |
| 8957 | { |
| 8958 | // Index into gl_in/gl_out with first array index. |
| 8959 | indices.push_back(ops[first_non_array_index - 1]); |
| 8960 | } |
| 8961 | |
| 8962 | auto &result_ptr_type = get<SPIRType>(ops[0]); |
| 8963 | |
| 8964 | uint32_t const_mbr_id = next_id++; |
| 8965 | uint32_t index = get_extended_decoration(ops[2], SPIRVCrossDecorationInterfaceMemberIndex); |
| 8966 | |
| 8967 | // If we have a pointer chain expression, and we are no longer pointing to a composite |
| 8968 | // object, we are in the clear. There is no longer a need to flatten anything. |
| 8969 | bool further_access_chain_is_trivial = false; |
| 8970 | if (ptr_is_chain && flatten_composites) |
| 8971 | { |
| 8972 | auto &ptr_type = expression_type(ptr); |
| 8973 | if (!is_array(ptr_type) && !is_matrix(ptr_type) && ptr_type.basetype != SPIRType::Struct) |
| 8974 | further_access_chain_is_trivial = true; |
| 8975 | } |
| 8976 | |
| 8977 | if (!further_access_chain_is_trivial && (flatten_composites || is_block)) |
| 8978 | { |
| 8979 | uint32_t i = first_non_array_index; |
| 8980 | auto *type = &get_variable_element_type(*var); |
| 8981 | if (index == uint32_t(-1) && length >= (first_non_array_index + 1)) |
| 8982 | { |
| 8983 | // Maybe this is a struct type in the input class, in which case |
| 8984 | // we put it as a decoration on the corresponding member. |
| 8985 | uint32_t mbr_idx = get_constant(ops[first_non_array_index]).scalar(); |
| 8986 | index = get_extended_member_decoration(var->self, mbr_idx, |
| 8987 | SPIRVCrossDecorationInterfaceMemberIndex); |
| 8988 | assert(index != uint32_t(-1)); |
| 8989 | i++; |
| 8990 | type = &get<SPIRType>(type->member_types[mbr_idx]); |
| 8991 | } |
| 8992 | |
| 8993 | // In this case, we're poking into flattened structures and arrays, so now we have to |
| 8994 | // combine the following indices. If we encounter a non-constant index, |
| 8995 | // we're hosed. |
| 8996 | for (; flatten_composites && i < length; ++i) |
| 8997 | { |
| 8998 | if (!is_array(*type) && !is_matrix(*type) && type->basetype != SPIRType::Struct) |
| 8999 | break; |
| 9000 | |
| 9001 | auto *c = maybe_get<SPIRConstant>(ops[i]); |
| 9002 | if (!c || c->specialization) |
| 9003 | SPIRV_CROSS_THROW("Trying to dynamically index into an array interface variable in tessellation. " |
| 9004 | "This is currently unsupported."); |
| 9005 | |
| 9006 | // We're in flattened space, so just increment the member index into IO block. |
| 9007 | // We can only do this once in the current implementation, so either: |
| 9008 | // Struct, Matrix or 1-dimensional array for a control point. |
| 9009 | if (type->basetype == SPIRType::Struct && var->storage == StorageClassOutput) |
| 9010 | { |
| 9011 | // Need to consider holes, since individual block members might be masked away. |
| 9012 | uint32_t mbr_idx = c->scalar(); |
| 9013 | for (uint32_t j = 0; j < mbr_idx; j++) |
| 9014 | if (!is_stage_output_block_member_masked(*var, j, true)) |
| 9015 | index++; |
| 9016 | } |
| 9017 | else |
| 9018 | index += c->scalar(); |
| 9019 | |
| 9020 | if (type->parent_type) |
| 9021 | type = &get<SPIRType>(type->parent_type); |
| 9022 | else if (type->basetype == SPIRType::Struct) |
| 9023 | type = &get<SPIRType>(type->member_types[c->scalar()]); |
| 9024 | } |
| 9025 | |
| 9026 | // We're not going to emit the actual member name, we let any further OpLoad take care of that. |
| 9027 | // Tag the access chain with the member index we're referencing. |
| 9028 | auto &result_pointee_type = get_pointee_type(result_ptr_type); |
| 9029 | bool defer_access_chain = flatten_composites && (is_matrix(result_pointee_type) || is_array(result_pointee_type) || |
| 9030 | result_pointee_type.basetype == SPIRType::Struct); |
| 9031 | |
| 9032 | if (!defer_access_chain) |
| 9033 | { |
| 9034 | // Access the appropriate member of gl_in/gl_out. |
| 9035 | set<SPIRConstant>(const_mbr_id, get_uint_type_id(), index, false); |
| 9036 | indices.push_back(const_mbr_id); |
| 9037 | |
| 9038 | // Member index is now irrelevant. |
| 9039 | index = uint32_t(-1); |
| 9040 | |
| 9041 | // Append any straggling access chain indices. |
| 9042 | if (i < length) |
| 9043 | indices.insert(indices.end(), ops + i, ops + length); |
| 9044 | } |
| 9045 | else |
| 9046 | { |
| 9047 | // We must have consumed the entire access chain if we're deferring it. |
| 9048 | assert(i == length); |
| 9049 | } |
| 9050 | |
| 9051 | if (index != uint32_t(-1)) |
| 9052 | set_extended_decoration(ops[1], SPIRVCrossDecorationInterfaceMemberIndex, index); |
| 9053 | else |
| 9054 | unset_extended_decoration(ops[1], SPIRVCrossDecorationInterfaceMemberIndex); |
| 9055 | } |
| 9056 | else |
| 9057 | { |
| 9058 | if (index != uint32_t(-1)) |
| 9059 | { |
| 9060 | set<SPIRConstant>(const_mbr_id, get_uint_type_id(), index, false); |
| 9061 | indices.push_back(const_mbr_id); |
| 9062 | } |
| 9063 | |
| 9064 | // Member index is now irrelevant. |
| 9065 | index = uint32_t(-1); |
| 9066 | unset_extended_decoration(ops[1], SPIRVCrossDecorationInterfaceMemberIndex); |
| 9067 | |
| 9068 | indices.insert(indices.end(), ops + first_non_array_index, ops + length); |
| 9069 | } |
| 9070 | |
| 9071 | // We use the pointer to the base of the input/output array here, |
| 9072 | // so this is always a pointer chain. |
| 9073 | string e; |
| 9074 | |
| 9075 | if (!ptr_is_chain) |
| 9076 | { |
| 9077 | // This is the start of an access chain, use ptr_chain to index into control point array. |
| 9078 | e = access_chain(ptr, indices.data(), uint32_t(indices.size()), result_ptr_type, &meta, !patch); |
| 9079 | } |
| 9080 | else |
| 9081 | { |
| 9082 | // If we're accessing a struct, we need to use member indices which are based on the IO block, |
| 9083 | // not actual struct type, so we have to use a split access chain here where |
| 9084 | // first path resolves the control point index, i.e. gl_in[index], and second half deals with |
| 9085 | // looking up flattened member name. |
| 9086 | |
| 9087 | // However, it is possible that we partially accessed a struct, |
| 9088 | // by taking pointer to member inside the control-point array. |
| 9089 | // For this case, we fall back to a natural access chain since we have already dealt with remapping struct members. |
| 9090 | // One way to check this here is if we have 2 implied read expressions. |
| 9091 | // First one is the gl_in/gl_out struct itself, then an index into that array. |
| 9092 | // If we have traversed further, we use a normal access chain formulation. |
| 9093 | auto *ptr_expr = maybe_get<SPIRExpression>(ptr); |
| 9094 | bool split_access_chain_formulation = flatten_composites && ptr_expr && |
| 9095 | ptr_expr->implied_read_expressions.size() == 2 && |
| 9096 | !further_access_chain_is_trivial; |
| 9097 | |
| 9098 | if (split_access_chain_formulation) |
| 9099 | { |
| 9100 | e = join(to_expression(ptr), |
| 9101 | access_chain_internal(stage_var_id, indices.data(), uint32_t(indices.size()), |
| 9102 | ACCESS_CHAIN_CHAIN_ONLY_BIT, &meta)); |
| 9103 | } |
| 9104 | else |
| 9105 | { |
| 9106 | e = access_chain_internal(ptr, indices.data(), uint32_t(indices.size()), 0, &meta); |
| 9107 | } |
| 9108 | } |
| 9109 | |
| 9110 | // Get the actual type of the object that was accessed. If it's a vector type and we changed it, |
| 9111 | // then we'll need to add a swizzle. |
| 9112 | // For this, we can't necessarily rely on the type of the base expression, because it might be |
| 9113 | // another access chain, and it will therefore already have the "correct" type. |
| 9114 | auto *expr_type = &get_variable_data_type(*var); |
| 9115 | if (has_extended_decoration(ops[2], SPIRVCrossDecorationTessIOOriginalInputTypeID)) |
| 9116 | expr_type = &get<SPIRType>(get_extended_decoration(ops[2], SPIRVCrossDecorationTessIOOriginalInputTypeID)); |
| 9117 | for (uint32_t i = 3; i < length; i++) |
| 9118 | { |
| 9119 | if (!is_array(*expr_type) && expr_type->basetype == SPIRType::Struct) |
| 9120 | expr_type = &get<SPIRType>(expr_type->member_types[get<SPIRConstant>(ops[i]).scalar()]); |
| 9121 | else |
| 9122 | expr_type = &get<SPIRType>(expr_type->parent_type); |
| 9123 | } |
| 9124 | if (!is_array(*expr_type) && !is_matrix(*expr_type) && expr_type->basetype != SPIRType::Struct && |
| 9125 | expr_type->vecsize > result_ptr_type.vecsize) |
| 9126 | e += vector_swizzle(result_ptr_type.vecsize, 0); |
| 9127 | |
| 9128 | auto &expr = set<SPIRExpression>(ops[1], std::move(e), ops[0], should_forward(ops[2])); |
| 9129 | expr.loaded_from = var->self; |
| 9130 | expr.need_transpose = meta.need_transpose; |
| 9131 | expr.access_chain = true; |
| 9132 | |
| 9133 | // Mark the result as being packed if necessary. |
| 9134 | if (meta.storage_is_packed) |
| 9135 | set_extended_decoration(ops[1], SPIRVCrossDecorationPhysicalTypePacked); |
| 9136 | if (meta.storage_physical_type != 0) |
| 9137 | set_extended_decoration(ops[1], SPIRVCrossDecorationPhysicalTypeID, meta.storage_physical_type); |
| 9138 | if (meta.storage_is_invariant) |
| 9139 | set_decoration(ops[1], DecorationInvariant); |
| 9140 | // Save the type we found in case the result is used in another access chain. |
| 9141 | set_extended_decoration(ops[1], SPIRVCrossDecorationTessIOOriginalInputTypeID, expr_type->self); |
| 9142 | |
| 9143 | // If we have some expression dependencies in our access chain, this access chain is technically a forwarded |
| 9144 | // temporary which could be subject to invalidation. |
| 9145 | // Need to assume we're forwarded while calling inherit_expression_depdendencies. |
| 9146 | forwarded_temporaries.insert(ops[1]); |
| 9147 | // The access chain itself is never forced to a temporary, but its dependencies might. |
| 9148 | suppressed_usage_tracking.insert(ops[1]); |
| 9149 | |
| 9150 | for (uint32_t i = 2; i < length; i++) |
| 9151 | { |
| 9152 | inherit_expression_dependencies(ops[1], ops[i]); |
| 9153 | add_implied_read_expression(expr, ops[i]); |
| 9154 | } |
| 9155 | |
| 9156 | // If we have no dependencies after all, i.e., all indices in the access chain are immutable temporaries, |
| 9157 | // we're not forwarded after all. |
| 9158 | if (expr.expression_dependencies.empty()) |
| 9159 | forwarded_temporaries.erase(ops[1]); |
| 9160 | |
| 9161 | return true; |
| 9162 | } |
| 9163 | |
| 9164 | // If this is the inner tessellation level, and we're tessellating triangles, |
| 9165 | // drop the last index. It isn't an array in this case, so we can't have an |
| 9166 | // array reference here. We need to make this ID a variable instead of an |
| 9167 | // expression so we don't try to dereference it as a variable pointer. |
| 9168 | // Don't do this if the index is a constant 1, though. We need to drop stores |
| 9169 | // to that one. |
| 9170 | auto *m = ir.find_meta(var ? var->self : ID(0)); |
| 9171 | if (is_tesc_shader() && var && m && m->decoration.builtin_type == BuiltInTessLevelInner && |
| 9172 | is_tessellating_triangles()) |
| 9173 | { |
| 9174 | auto *c = maybe_get<SPIRConstant>(ops[3]); |
| 9175 | if (c && c->scalar() == 1) |
| 9176 | return false; |
| 9177 | auto &dest_var = set<SPIRVariable>(ops[1], *var); |
| 9178 | dest_var.basetype = ops[0]; |
| 9179 | ir.meta[ops[1]] = ir.meta[ops[2]]; |
| 9180 | inherit_expression_dependencies(ops[1], ops[2]); |
| 9181 | return true; |
| 9182 | } |
| 9183 | |
| 9184 | return false; |
| 9185 | } |
| 9186 | |
| 9187 | bool CompilerMSL::is_out_of_bounds_tessellation_level(uint32_t id_lhs) |
| 9188 | { |
| 9189 | if (!is_tessellating_triangles()) |
| 9190 | return false; |
| 9191 | |
| 9192 | // In SPIR-V, TessLevelInner always has two elements and TessLevelOuter always has |
| 9193 | // four. This is true even if we are tessellating triangles. This allows clients |
| 9194 | // to use a single tessellation control shader with multiple tessellation evaluation |
| 9195 | // shaders. |
| 9196 | // In Metal, however, only the first element of TessLevelInner and the first three |
| 9197 | // of TessLevelOuter are accessible. This stems from how in Metal, the tessellation |
| 9198 | // levels must be stored to a dedicated buffer in a particular format that depends |
| 9199 | // on the patch type. Therefore, in Triangles mode, any store to the second |
| 9200 | // inner level or the fourth outer level must be dropped. |
| 9201 | const auto *e = maybe_get<SPIRExpression>(id_lhs); |
| 9202 | if (!e || !e->access_chain) |
| 9203 | return false; |
| 9204 | BuiltIn builtin = BuiltIn(get_decoration(e->loaded_from, DecorationBuiltIn)); |
| 9205 | if (builtin != BuiltInTessLevelInner && builtin != BuiltInTessLevelOuter) |
| 9206 | return false; |
| 9207 | auto *c = maybe_get<SPIRConstant>(e->implied_read_expressions[1]); |
| 9208 | if (!c) |
| 9209 | return false; |
| 9210 | return (builtin == BuiltInTessLevelInner && c->scalar() == 1) || |
| 9211 | (builtin == BuiltInTessLevelOuter && c->scalar() == 3); |
| 9212 | } |
| 9213 | |
| 9214 | bool CompilerMSL::prepare_access_chain_for_scalar_access(std::string &expr, const SPIRType &type, |
| 9215 | spv::StorageClass storage, bool &is_packed) |
| 9216 | { |
| 9217 | // If there is any risk of writes happening with the access chain in question, |
| 9218 | // and there is a risk of concurrent write access to other components, |
| 9219 | // we must cast the access chain to a plain pointer to ensure we only access the exact scalars we expect. |
| 9220 | // The MSL compiler refuses to allow component-level access for any non-packed vector types. |
| 9221 | if (!is_packed && (storage == StorageClassStorageBuffer || storage == StorageClassWorkgroup)) |
| 9222 | { |
| 9223 | const char *addr_space = storage == StorageClassWorkgroup ? "threadgroup" : "device"; |
| 9224 | expr = join("((", addr_space, " ", type_to_glsl(type), "*)&", enclose_expression(expr), ")"); |
| 9225 | |
| 9226 | // Further indexing should happen with packed rules (array index, not swizzle). |
| 9227 | is_packed = true; |
| 9228 | return true; |
| 9229 | } |
| 9230 | else |
| 9231 | return false; |
| 9232 | } |
| 9233 | |
| 9234 | bool CompilerMSL::access_chain_needs_stage_io_builtin_translation(uint32_t base) |
| 9235 | { |
| 9236 | auto *var = maybe_get_backing_variable(base); |
| 9237 | if (!var || !is_tessellation_shader()) |
| 9238 | return true; |
| 9239 | |
| 9240 | // We only need to rewrite builtin access chains when accessing flattened builtins like gl_ClipDistance_N. |
| 9241 | // Avoid overriding it back to just gl_ClipDistance. |
| 9242 | // This can only happen in scenarios where we cannot flatten/unflatten access chains, so, the only case |
| 9243 | // where this triggers is evaluation shader inputs. |
| 9244 | bool redirect_builtin = is_tese_shader() ? var->storage == StorageClassOutput : false; |
| 9245 | return redirect_builtin; |
| 9246 | } |
| 9247 | |
| 9248 | // Sets the interface member index for an access chain to a pull-model interpolant. |
| 9249 | void CompilerMSL::fix_up_interpolant_access_chain(const uint32_t *ops, uint32_t length) |
| 9250 | { |
| 9251 | auto *var = maybe_get_backing_variable(ops[2]); |
| 9252 | if (!var || !pull_model_inputs.count(var->self)) |
| 9253 | return; |
| 9254 | // Get the base index. |
| 9255 | uint32_t interface_index; |
| 9256 | auto &var_type = get_variable_data_type(*var); |
| 9257 | auto &result_type = get<SPIRType>(ops[0]); |
| 9258 | auto *type = &var_type; |
| 9259 | if (has_extended_decoration(ops[2], SPIRVCrossDecorationInterfaceMemberIndex)) |
| 9260 | { |
| 9261 | interface_index = get_extended_decoration(ops[2], SPIRVCrossDecorationInterfaceMemberIndex); |
| 9262 | } |
| 9263 | else |
| 9264 | { |
| 9265 | // Assume an access chain into a struct variable. |
| 9266 | assert(var_type.basetype == SPIRType::Struct); |
| 9267 | auto &c = get<SPIRConstant>(ops[3 + var_type.array.size()]); |
| 9268 | interface_index = |
| 9269 | get_extended_member_decoration(var->self, c.scalar(), SPIRVCrossDecorationInterfaceMemberIndex); |
| 9270 | } |
| 9271 | // Accumulate indices. We'll have to skip over the one for the struct, if present, because we already accounted |
| 9272 | // for that getting the base index. |
| 9273 | for (uint32_t i = 3; i < length; ++i) |
| 9274 | { |
| 9275 | if (is_vector(*type) && !is_array(*type) && is_scalar(result_type)) |
| 9276 | { |
| 9277 | // We don't want to combine the next index. Actually, we need to save it |
| 9278 | // so we know to apply a swizzle to the result of the interpolation. |
| 9279 | set_extended_decoration(ops[1], SPIRVCrossDecorationInterpolantComponentExpr, ops[i]); |
| 9280 | break; |
| 9281 | } |
| 9282 | |
| 9283 | auto *c = maybe_get<SPIRConstant>(ops[i]); |
| 9284 | if (!c || c->specialization) |
| 9285 | SPIRV_CROSS_THROW("Trying to dynamically index into an array interface variable using pull-model " |
| 9286 | "interpolation. This is currently unsupported."); |
| 9287 | |
| 9288 | if (type->parent_type) |
| 9289 | type = &get<SPIRType>(type->parent_type); |
| 9290 | else if (type->basetype == SPIRType::Struct) |
| 9291 | type = &get<SPIRType>(type->member_types[c->scalar()]); |
| 9292 | |
| 9293 | if (!has_extended_decoration(ops[2], SPIRVCrossDecorationInterfaceMemberIndex) && |
| 9294 | i - 3 == var_type.array.size()) |
| 9295 | continue; |
| 9296 | |
| 9297 | interface_index += c->scalar(); |
| 9298 | } |
| 9299 | // Save this to the access chain itself so we can recover it later when calling an interpolation function. |
| 9300 | set_extended_decoration(ops[1], SPIRVCrossDecorationInterfaceMemberIndex, interface_index); |
| 9301 | } |
| 9302 | |
| 9303 | |
| 9304 | // If the physical type of a physical buffer pointer has been changed |
| 9305 | // to a ulong or ulongn vector, add a cast back to the pointer type. |
| 9306 | bool CompilerMSL::check_physical_type_cast(std::string &expr, const SPIRType *type, uint32_t physical_type) |
| 9307 | { |
| 9308 | auto *p_physical_type = maybe_get<SPIRType>(physical_type); |
| 9309 | if (p_physical_type && |
| 9310 | p_physical_type->storage == StorageClassPhysicalStorageBuffer && |
| 9311 | p_physical_type->basetype == to_unsigned_basetype(64)) |
| 9312 | { |
| 9313 | if (p_physical_type->vecsize > 1) |
| 9314 | expr += ".x"; |
| 9315 | |
| 9316 | expr = join("((", type_to_glsl(*type), ")", expr, ")"); |
| 9317 | return true; |
| 9318 | } |
| 9319 | |
| 9320 | return false; |
| 9321 | } |
| 9322 | |
| 9323 | // Override for MSL-specific syntax instructions |
| 9324 | void CompilerMSL::emit_instruction(const Instruction &instruction) |
| 9325 | { |
| 9326 | #define MSL_BOP(op) emit_binary_op(ops[0], ops[1], ops[2], ops[3], #op) |
| 9327 | #define MSL_PTR_BOP(op) emit_binary_ptr_op(ops[0], ops[1], ops[2], ops[3], #op) |
| 9328 | // MSL does care about implicit integer promotion, but those cases are all handled in common code. |
| 9329 | #define MSL_BOP_CAST(op, type) \ |
| 9330 | emit_binary_op_cast(ops[0], ops[1], ops[2], ops[3], #op, type, opcode_is_sign_invariant(opcode), false) |
| 9331 | #define MSL_UOP(op) emit_unary_op(ops[0], ops[1], ops[2], #op) |
| 9332 | #define MSL_QFOP(op) emit_quaternary_func_op(ops[0], ops[1], ops[2], ops[3], ops[4], ops[5], #op) |
| 9333 | #define MSL_TFOP(op) emit_trinary_func_op(ops[0], ops[1], ops[2], ops[3], ops[4], #op) |
| 9334 | #define MSL_BFOP(op) emit_binary_func_op(ops[0], ops[1], ops[2], ops[3], #op) |
| 9335 | #define MSL_BFOP_CAST(op, type) \ |
| 9336 | emit_binary_func_op_cast(ops[0], ops[1], ops[2], ops[3], #op, type, opcode_is_sign_invariant(opcode)) |
| 9337 | #define MSL_UFOP(op) emit_unary_func_op(ops[0], ops[1], ops[2], #op) |
| 9338 | #define MSL_UNORD_BOP(op) emit_binary_unord_op(ops[0], ops[1], ops[2], ops[3], #op) |
| 9339 | |
| 9340 | auto ops = stream(instruction); |
| 9341 | auto opcode = static_cast<Op>(instruction.op); |
| 9342 | |
| 9343 | opcode = get_remapped_spirv_op(opcode); |
| 9344 | |
| 9345 | // If we need to do implicit bitcasts, make sure we do it with the correct type. |
| 9346 | uint32_t integer_width = get_integer_width_for_instruction(instruction); |
| 9347 | auto int_type = to_signed_basetype(integer_width); |
| 9348 | auto uint_type = to_unsigned_basetype(integer_width); |
| 9349 | |
| 9350 | switch (opcode) |
| 9351 | { |
| 9352 | case OpLoad: |
| 9353 | { |
| 9354 | uint32_t id = ops[1]; |
| 9355 | uint32_t ptr = ops[2]; |
| 9356 | if (is_tessellation_shader()) |
| 9357 | { |
| 9358 | if (!emit_tessellation_io_load(ops[0], id, ptr)) |
| 9359 | CompilerGLSL::emit_instruction(instruction); |
| 9360 | } |
| 9361 | else |
| 9362 | { |
| 9363 | // Sample mask input for Metal is not an array |
| 9364 | if (BuiltIn(get_decoration(ptr, DecorationBuiltIn)) == BuiltInSampleMask) |
| 9365 | set_decoration(id, DecorationBuiltIn, BuiltInSampleMask); |
| 9366 | CompilerGLSL::emit_instruction(instruction); |
| 9367 | } |
| 9368 | break; |
| 9369 | } |
| 9370 | |
| 9371 | // Comparisons |
| 9372 | case OpIEqual: |
| 9373 | MSL_BOP_CAST(==, int_type); |
| 9374 | break; |
| 9375 | |
| 9376 | case OpLogicalEqual: |
| 9377 | case OpFOrdEqual: |
| 9378 | MSL_BOP(==); |
| 9379 | break; |
| 9380 | |
| 9381 | case OpINotEqual: |
| 9382 | MSL_BOP_CAST(!=, int_type); |
| 9383 | break; |
| 9384 | |
| 9385 | case OpLogicalNotEqual: |
| 9386 | case OpFOrdNotEqual: |
| 9387 | // TODO: Should probably negate the == result here. |
| 9388 | // Typically OrdNotEqual comes from GLSL which itself does not really specify what |
| 9389 | // happens with NaN. |
| 9390 | // Consider fixing this if we run into real issues. |
| 9391 | MSL_BOP(!=); |
| 9392 | break; |
| 9393 | |
| 9394 | case OpUGreaterThan: |
| 9395 | MSL_BOP_CAST(>, uint_type); |
| 9396 | break; |
| 9397 | |
| 9398 | case OpSGreaterThan: |
| 9399 | MSL_BOP_CAST(>, int_type); |
| 9400 | break; |
| 9401 | |
| 9402 | case OpFOrdGreaterThan: |
| 9403 | MSL_BOP(>); |
| 9404 | break; |
| 9405 | |
| 9406 | case OpUGreaterThanEqual: |
| 9407 | MSL_BOP_CAST(>=, uint_type); |
| 9408 | break; |
| 9409 | |
| 9410 | case OpSGreaterThanEqual: |
| 9411 | MSL_BOP_CAST(>=, int_type); |
| 9412 | break; |
| 9413 | |
| 9414 | case OpFOrdGreaterThanEqual: |
| 9415 | MSL_BOP(>=); |
| 9416 | break; |
| 9417 | |
| 9418 | case OpULessThan: |
| 9419 | MSL_BOP_CAST(<, uint_type); |
| 9420 | break; |
| 9421 | |
| 9422 | case OpSLessThan: |
| 9423 | MSL_BOP_CAST(<, int_type); |
| 9424 | break; |
| 9425 | |
| 9426 | case OpFOrdLessThan: |
| 9427 | MSL_BOP(<); |
| 9428 | break; |
| 9429 | |
| 9430 | case OpULessThanEqual: |
| 9431 | MSL_BOP_CAST(<=, uint_type); |
| 9432 | break; |
| 9433 | |
| 9434 | case OpSLessThanEqual: |
| 9435 | MSL_BOP_CAST(<=, int_type); |
| 9436 | break; |
| 9437 | |
| 9438 | case OpFOrdLessThanEqual: |
| 9439 | MSL_BOP(<=); |
| 9440 | break; |
| 9441 | |
| 9442 | case OpFUnordEqual: |
| 9443 | MSL_UNORD_BOP(==); |
| 9444 | break; |
| 9445 | |
| 9446 | case OpFUnordNotEqual: |
| 9447 | // not equal in MSL generates une opcodes to begin with. |
| 9448 | // Since unordered not equal is how it works in C, just inherit that behavior. |
| 9449 | MSL_BOP(!=); |
| 9450 | break; |
| 9451 | |
| 9452 | case OpFUnordGreaterThan: |
| 9453 | MSL_UNORD_BOP(>); |
| 9454 | break; |
| 9455 | |
| 9456 | case OpFUnordGreaterThanEqual: |
| 9457 | MSL_UNORD_BOP(>=); |
| 9458 | break; |
| 9459 | |
| 9460 | case OpFUnordLessThan: |
| 9461 | MSL_UNORD_BOP(<); |
| 9462 | break; |
| 9463 | |
| 9464 | case OpFUnordLessThanEqual: |
| 9465 | MSL_UNORD_BOP(<=); |
| 9466 | break; |
| 9467 | |
| 9468 | // Pointer math |
| 9469 | case OpPtrEqual: |
| 9470 | MSL_PTR_BOP(==); |
| 9471 | break; |
| 9472 | |
| 9473 | case OpPtrNotEqual: |
| 9474 | MSL_PTR_BOP(!=); |
| 9475 | break; |
| 9476 | |
| 9477 | case OpPtrDiff: |
| 9478 | MSL_PTR_BOP(-); |
| 9479 | break; |
| 9480 | |
| 9481 | // Derivatives |
| 9482 | case OpDPdx: |
| 9483 | case OpDPdxFine: |
| 9484 | case OpDPdxCoarse: |
| 9485 | MSL_UFOP(dfdx); |
| 9486 | register_control_dependent_expression(ops[1]); |
| 9487 | break; |
| 9488 | |
| 9489 | case OpDPdy: |
| 9490 | case OpDPdyFine: |
| 9491 | case OpDPdyCoarse: |
| 9492 | MSL_UFOP(dfdy); |
| 9493 | register_control_dependent_expression(ops[1]); |
| 9494 | break; |
| 9495 | |
| 9496 | case OpFwidth: |
| 9497 | case OpFwidthCoarse: |
| 9498 | case OpFwidthFine: |
| 9499 | MSL_UFOP(fwidth); |
| 9500 | register_control_dependent_expression(ops[1]); |
| 9501 | break; |
| 9502 | |
| 9503 | // Bitfield |
| 9504 | case OpBitFieldInsert: |
| 9505 | { |
| 9506 | emit_bitfield_insert_op(ops[0], ops[1], ops[2], ops[3], ops[4], ops[5], "insert_bits", SPIRType::UInt); |
| 9507 | break; |
| 9508 | } |
| 9509 | |
| 9510 | case OpBitFieldSExtract: |
| 9511 | { |
| 9512 | emit_trinary_func_op_bitextract(ops[0], ops[1], ops[2], ops[3], ops[4], "extract_bits", int_type, int_type, |
| 9513 | SPIRType::UInt, SPIRType::UInt); |
| 9514 | break; |
| 9515 | } |
| 9516 | |
| 9517 | case OpBitFieldUExtract: |
| 9518 | { |
| 9519 | emit_trinary_func_op_bitextract(ops[0], ops[1], ops[2], ops[3], ops[4], "extract_bits", uint_type, uint_type, |
| 9520 | SPIRType::UInt, SPIRType::UInt); |
| 9521 | break; |
| 9522 | } |
| 9523 | |
| 9524 | case OpBitReverse: |
| 9525 | // BitReverse does not have issues with sign since result type must match input type. |
| 9526 | MSL_UFOP(reverse_bits); |
| 9527 | break; |
| 9528 | |
| 9529 | case OpBitCount: |
| 9530 | { |
| 9531 | auto basetype = expression_type(ops[2]).basetype; |
| 9532 | emit_unary_func_op_cast(ops[0], ops[1], ops[2], "popcount", basetype, basetype); |
| 9533 | break; |
| 9534 | } |
| 9535 | |
| 9536 | case OpSMod: |
| 9537 | MSL_BFOP(spvSMod); |
| 9538 | break; |
| 9539 | |
| 9540 | case OpFRem: |
| 9541 | MSL_BFOP(fmod); |
| 9542 | break; |
| 9543 | |
| 9544 | case OpFMul: |
| 9545 | if (msl_options.invariant_float_math || has_decoration(ops[1], DecorationNoContraction)) |
| 9546 | MSL_BFOP(spvFMul); |
| 9547 | else |
| 9548 | MSL_BOP(*); |
| 9549 | break; |
| 9550 | |
| 9551 | case OpFAdd: |
| 9552 | if (msl_options.invariant_float_math || has_decoration(ops[1], DecorationNoContraction)) |
| 9553 | MSL_BFOP(spvFAdd); |
| 9554 | else |
| 9555 | MSL_BOP(+); |
| 9556 | break; |
| 9557 | |
| 9558 | case OpFSub: |
| 9559 | if (msl_options.invariant_float_math || has_decoration(ops[1], DecorationNoContraction)) |
| 9560 | MSL_BFOP(spvFSub); |
| 9561 | else |
| 9562 | MSL_BOP(-); |
| 9563 | break; |
| 9564 | |
| 9565 | // Atomics |
| 9566 | case OpAtomicExchange: |
| 9567 | { |
| 9568 | uint32_t result_type = ops[0]; |
| 9569 | uint32_t id = ops[1]; |
| 9570 | uint32_t ptr = ops[2]; |
| 9571 | uint32_t mem_sem = ops[4]; |
| 9572 | uint32_t val = ops[5]; |
| 9573 | emit_atomic_func_op(result_type, id, "atomic_exchange", opcode, mem_sem, mem_sem, false, ptr, val); |
| 9574 | break; |
| 9575 | } |
| 9576 | |
| 9577 | case OpAtomicCompareExchange: |
| 9578 | { |
| 9579 | uint32_t result_type = ops[0]; |
| 9580 | uint32_t id = ops[1]; |
| 9581 | uint32_t ptr = ops[2]; |
| 9582 | uint32_t mem_sem_pass = ops[4]; |
| 9583 | uint32_t mem_sem_fail = ops[5]; |
| 9584 | uint32_t val = ops[6]; |
| 9585 | uint32_t comp = ops[7]; |
| 9586 | emit_atomic_func_op(result_type, id, "atomic_compare_exchange_weak", opcode, |
| 9587 | mem_sem_pass, mem_sem_fail, true, |
| 9588 | ptr, comp, true, false, val); |
| 9589 | break; |
| 9590 | } |
| 9591 | |
| 9592 | case OpAtomicCompareExchangeWeak: |
| 9593 | SPIRV_CROSS_THROW("OpAtomicCompareExchangeWeak is only supported in kernel profile."); |
| 9594 | |
| 9595 | case OpAtomicLoad: |
| 9596 | { |
| 9597 | uint32_t result_type = ops[0]; |
| 9598 | uint32_t id = ops[1]; |
| 9599 | uint32_t ptr = ops[2]; |
| 9600 | uint32_t mem_sem = ops[4]; |
| 9601 | check_atomic_image(ptr); |
| 9602 | emit_atomic_func_op(result_type, id, "atomic_load", opcode, mem_sem, mem_sem, false, ptr, 0); |
| 9603 | break; |
| 9604 | } |
| 9605 | |
| 9606 | case OpAtomicStore: |
| 9607 | { |
| 9608 | uint32_t result_type = expression_type(ops[0]).self; |
| 9609 | uint32_t id = ops[0]; |
| 9610 | uint32_t ptr = ops[0]; |
| 9611 | uint32_t mem_sem = ops[2]; |
| 9612 | uint32_t val = ops[3]; |
| 9613 | check_atomic_image(ptr); |
| 9614 | emit_atomic_func_op(result_type, id, "atomic_store", opcode, mem_sem, mem_sem, false, ptr, val); |
| 9615 | break; |
| 9616 | } |
| 9617 | |
| 9618 | #define MSL_AFMO_IMPL(op, valsrc, valconst) \ |
| 9619 | do \ |
| 9620 | { \ |
| 9621 | uint32_t result_type = ops[0]; \ |
| 9622 | uint32_t id = ops[1]; \ |
| 9623 | uint32_t ptr = ops[2]; \ |
| 9624 | uint32_t mem_sem = ops[4]; \ |
| 9625 | uint32_t val = valsrc; \ |
| 9626 | emit_atomic_func_op(result_type, id, "atomic_fetch_" #op, opcode, \ |
| 9627 | mem_sem, mem_sem, false, ptr, val, \ |
| 9628 | false, valconst); \ |
| 9629 | } while (false) |
| 9630 | |
| 9631 | #define MSL_AFMO(op) MSL_AFMO_IMPL(op, ops[5], false) |
| 9632 | #define MSL_AFMIO(op) MSL_AFMO_IMPL(op, 1, true) |
| 9633 | |
| 9634 | case OpAtomicIIncrement: |
| 9635 | MSL_AFMIO(add); |
| 9636 | break; |
| 9637 | |
| 9638 | case OpAtomicIDecrement: |
| 9639 | MSL_AFMIO(sub); |
| 9640 | break; |
| 9641 | |
| 9642 | case OpAtomicIAdd: |
| 9643 | case OpAtomicFAddEXT: |
| 9644 | MSL_AFMO(add); |
| 9645 | break; |
| 9646 | |
| 9647 | case OpAtomicISub: |
| 9648 | MSL_AFMO(sub); |
| 9649 | break; |
| 9650 | |
| 9651 | case OpAtomicSMin: |
| 9652 | case OpAtomicUMin: |
| 9653 | MSL_AFMO(min); |
| 9654 | break; |
| 9655 | |
| 9656 | case OpAtomicSMax: |
| 9657 | case OpAtomicUMax: |
| 9658 | MSL_AFMO(max); |
| 9659 | break; |
| 9660 | |
| 9661 | case OpAtomicAnd: |
| 9662 | MSL_AFMO(and); |
| 9663 | break; |
| 9664 | |
| 9665 | case OpAtomicOr: |
| 9666 | MSL_AFMO(or); |
| 9667 | break; |
| 9668 | |
| 9669 | case OpAtomicXor: |
| 9670 | MSL_AFMO(xor); |
| 9671 | break; |
| 9672 | |
| 9673 | // Images |
| 9674 | |
| 9675 | // Reads == Fetches in Metal |
| 9676 | case OpImageRead: |
| 9677 | { |
| 9678 | // Mark that this shader reads from this image |
| 9679 | uint32_t img_id = ops[2]; |
| 9680 | auto &type = expression_type(img_id); |
| 9681 | auto *p_var = maybe_get_backing_variable(img_id); |
| 9682 | if (type.image.dim != DimSubpassData) |
| 9683 | { |
| 9684 | if (p_var && has_decoration(p_var->self, DecorationNonReadable)) |
| 9685 | { |
| 9686 | unset_decoration(p_var->self, DecorationNonReadable); |
| 9687 | force_recompile(); |
| 9688 | } |
| 9689 | } |
| 9690 | |
| 9691 | // Metal requires explicit fences to break up RAW hazards, even within the same shader invocation |
| 9692 | if (msl_options.readwrite_texture_fences && p_var && !has_decoration(p_var->self, DecorationNonWritable)) |
| 9693 | { |
| 9694 | add_spv_func_and_recompile(SPVFuncImplImageFence); |
| 9695 | // Need to wrap this with a value type, |
| 9696 | // since the Metal headers are broken and do not consider case when the image is a reference. |
| 9697 | statement("spvImageFence(", to_expression(img_id), ");"); |
| 9698 | } |
| 9699 | |
| 9700 | emit_texture_op(instruction, false); |
| 9701 | break; |
| 9702 | } |
| 9703 | |
| 9704 | // Emulate texture2D atomic operations |
| 9705 | case OpImageTexelPointer: |
| 9706 | { |
| 9707 | // When using the pointer, we need to know which variable it is actually loaded from. |
| 9708 | auto *var = maybe_get_backing_variable(ops[2]); |
| 9709 | if (var && atomic_image_vars_emulated.count(var->self)) |
| 9710 | { |
| 9711 | uint32_t result_type = ops[0]; |
| 9712 | uint32_t id = ops[1]; |
| 9713 | |
| 9714 | std::string coord = to_expression(ops[3]); |
| 9715 | auto &type = expression_type(ops[2]); |
| 9716 | if (type.image.dim == Dim2D) |
| 9717 | { |
| 9718 | coord = join("spvImage2DAtomicCoord(", coord, ", ", to_expression(ops[2]), ")"); |
| 9719 | } |
| 9720 | |
| 9721 | auto &e = set<SPIRExpression>(id, join(to_expression(ops[2]), "_atomic[", coord, "]"), result_type, true); |
| 9722 | e.loaded_from = var ? var->self : ID(0); |
| 9723 | inherit_expression_dependencies(id, ops[3]); |
| 9724 | } |
| 9725 | else |
| 9726 | { |
| 9727 | uint32_t result_type = ops[0]; |
| 9728 | uint32_t id = ops[1]; |
| 9729 | |
| 9730 | // Virtual expression. Split this up in the actual image atomic. |
| 9731 | // In GLSL and HLSL we are able to resolve the dereference inline, but MSL has |
| 9732 | // image.op(coord, ...) syntax. |
| 9733 | auto &e = |
| 9734 | set<SPIRExpression>(id, join(to_expression(ops[2]), "@", |
| 9735 | bitcast_expression(SPIRType::UInt, ops[3])), |
| 9736 | result_type, true); |
| 9737 | |
| 9738 | // When using the pointer, we need to know which variable it is actually loaded from. |
| 9739 | e.loaded_from = var ? var->self : ID(0); |
| 9740 | inherit_expression_dependencies(id, ops[3]); |
| 9741 | } |
| 9742 | break; |
| 9743 | } |
| 9744 | |
| 9745 | case OpImageWrite: |
| 9746 | { |
| 9747 | uint32_t img_id = ops[0]; |
| 9748 | uint32_t coord_id = ops[1]; |
| 9749 | uint32_t texel_id = ops[2]; |
| 9750 | const uint32_t *opt = &ops[3]; |
| 9751 | uint32_t length = instruction.length - 3; |
| 9752 | |
| 9753 | // Bypass pointers because we need the real image struct |
| 9754 | auto &type = expression_type(img_id); |
| 9755 | auto &img_type = get<SPIRType>(type.self); |
| 9756 | |
| 9757 | // Ensure this image has been marked as being written to and force a |
| 9758 | // recommpile so that the image type output will include write access |
| 9759 | auto *p_var = maybe_get_backing_variable(img_id); |
| 9760 | if (p_var && has_decoration(p_var->self, DecorationNonWritable)) |
| 9761 | { |
| 9762 | unset_decoration(p_var->self, DecorationNonWritable); |
| 9763 | force_recompile(); |
| 9764 | } |
| 9765 | |
| 9766 | bool forward = false; |
| 9767 | uint32_t bias = 0; |
| 9768 | uint32_t lod = 0; |
| 9769 | uint32_t flags = 0; |
| 9770 | |
| 9771 | if (length) |
| 9772 | { |
| 9773 | flags = *opt++; |
| 9774 | length--; |
| 9775 | } |
| 9776 | |
| 9777 | auto test = [&](uint32_t &v, uint32_t flag) { |
| 9778 | if (length && (flags & flag)) |
| 9779 | { |
| 9780 | v = *opt++; |
| 9781 | length--; |
| 9782 | } |
| 9783 | }; |
| 9784 | |
| 9785 | test(bias, ImageOperandsBiasMask); |
| 9786 | test(lod, ImageOperandsLodMask); |
| 9787 | |
| 9788 | auto &texel_type = expression_type(texel_id); |
| 9789 | auto store_type = texel_type; |
| 9790 | store_type.vecsize = 4; |
| 9791 | |
| 9792 | TextureFunctionArguments args = {}; |
| 9793 | args.base.img = img_id; |
| 9794 | args.base.imgtype = &img_type; |
| 9795 | args.base.is_fetch = true; |
| 9796 | args.coord = coord_id; |
| 9797 | args.lod = lod; |
| 9798 | |
| 9799 | string expr; |
| 9800 | if (needs_frag_discard_checks()) |
| 9801 | expr = join("(", builtin_to_glsl(BuiltInHelperInvocation, StorageClassInput), " ? ((void)0) : "); |
| 9802 | expr += join(to_expression(img_id), ".write(", |
| 9803 | remap_swizzle(store_type, texel_type.vecsize, to_expression(texel_id)), ", ", |
| 9804 | CompilerMSL::to_function_args(args, &forward), ")"); |
| 9805 | if (needs_frag_discard_checks()) |
| 9806 | expr += ")"; |
| 9807 | statement(expr, ";"); |
| 9808 | |
| 9809 | if (p_var && variable_storage_is_aliased(*p_var)) |
| 9810 | flush_all_aliased_variables(); |
| 9811 | |
| 9812 | break; |
| 9813 | } |
| 9814 | |
| 9815 | case OpImageQuerySize: |
| 9816 | case OpImageQuerySizeLod: |
| 9817 | { |
| 9818 | uint32_t rslt_type_id = ops[0]; |
| 9819 | auto &rslt_type = get<SPIRType>(rslt_type_id); |
| 9820 | |
| 9821 | uint32_t id = ops[1]; |
| 9822 | |
| 9823 | uint32_t img_id = ops[2]; |
| 9824 | string img_exp = to_expression(img_id); |
| 9825 | auto &img_type = expression_type(img_id); |
| 9826 | Dim img_dim = img_type.image.dim; |
| 9827 | bool img_is_array = img_type.image.arrayed; |
| 9828 | |
| 9829 | if (img_type.basetype != SPIRType::Image) |
| 9830 | SPIRV_CROSS_THROW("Invalid type for OpImageQuerySize."); |
| 9831 | |
| 9832 | string lod; |
| 9833 | if (opcode == OpImageQuerySizeLod) |
| 9834 | { |
| 9835 | // LOD index defaults to zero, so don't bother outputing level zero index |
| 9836 | string decl_lod = to_expression(ops[3]); |
| 9837 | if (decl_lod != "0") |
| 9838 | lod = decl_lod; |
| 9839 | } |
| 9840 | |
| 9841 | string expr = type_to_glsl(rslt_type) + "("; |
| 9842 | expr += img_exp + ".get_width(" + lod + ")"; |
| 9843 | |
| 9844 | if (img_dim == Dim2D || img_dim == DimCube || img_dim == Dim3D) |
| 9845 | expr += ", " + img_exp + ".get_height(" + lod + ")"; |
| 9846 | |
| 9847 | if (img_dim == Dim3D) |
| 9848 | expr += ", " + img_exp + ".get_depth(" + lod + ")"; |
| 9849 | |
| 9850 | if (img_is_array) |
| 9851 | { |
| 9852 | expr += ", " + img_exp + ".get_array_size()"; |
| 9853 | if (img_dim == DimCube && msl_options.emulate_cube_array) |
| 9854 | expr += " / 6"; |
| 9855 | } |
| 9856 | |
| 9857 | expr += ")"; |
| 9858 | |
| 9859 | emit_op(rslt_type_id, id, expr, should_forward(img_id)); |
| 9860 | |
| 9861 | break; |
| 9862 | } |
| 9863 | |
| 9864 | case OpImageQueryLod: |
| 9865 | { |
| 9866 | if (!msl_options.supports_msl_version(2, 2)) |
| 9867 | SPIRV_CROSS_THROW("ImageQueryLod is only supported on MSL 2.2 and up."); |
| 9868 | uint32_t result_type = ops[0]; |
| 9869 | uint32_t id = ops[1]; |
| 9870 | uint32_t image_id = ops[2]; |
| 9871 | uint32_t coord_id = ops[3]; |
| 9872 | emit_uninitialized_temporary_expression(result_type, id); |
| 9873 | |
| 9874 | std::string coord_expr = to_expression(coord_id); |
| 9875 | auto sampler_expr = to_sampler_expression(image_id); |
| 9876 | auto *combined = maybe_get<SPIRCombinedImageSampler>(image_id); |
| 9877 | auto image_expr = combined ? to_expression(combined->image) : to_expression(image_id); |
| 9878 | const SPIRType &image_type = expression_type(image_id); |
| 9879 | const SPIRType &coord_type = expression_type(coord_id); |
| 9880 | |
| 9881 | switch (image_type.image.dim) |
| 9882 | { |
| 9883 | case Dim1D: |
| 9884 | if (!msl_options.texture_1D_as_2D) |
| 9885 | SPIRV_CROSS_THROW("ImageQueryLod is not supported on 1D textures."); |
| 9886 | [[fallthrough]]; |
| 9887 | case Dim2D: |
| 9888 | if (coord_type.vecsize > 2) |
| 9889 | coord_expr = enclose_expression(coord_expr) + ".xy"; |
| 9890 | break; |
| 9891 | case DimCube: |
| 9892 | case Dim3D: |
| 9893 | if (coord_type.vecsize > 3) |
| 9894 | coord_expr = enclose_expression(coord_expr) + ".xyz"; |
| 9895 | break; |
| 9896 | default: |
| 9897 | SPIRV_CROSS_THROW("Bad image type given to OpImageQueryLod"); |
| 9898 | } |
| 9899 | |
| 9900 | // TODO: It is unclear if calculcate_clamped_lod also conditionally rounds |
| 9901 | // the reported LOD based on the sampler. NEAREST miplevel should |
| 9902 | // round the LOD, but LINEAR miplevel should not round. |
| 9903 | // Let's hope this does not become an issue ... |
| 9904 | statement(to_expression(id), ".x = ", image_expr, ".calculate_clamped_lod(", sampler_expr, ", ", |
| 9905 | coord_expr, ");"); |
| 9906 | statement(to_expression(id), ".y = ", image_expr, ".calculate_unclamped_lod(", sampler_expr, ", ", |
| 9907 | coord_expr, ");"); |
| 9908 | register_control_dependent_expression(id); |
| 9909 | break; |
| 9910 | } |
| 9911 | |
| 9912 | #define MSL_ImgQry(qrytype) \ |
| 9913 | do \ |
| 9914 | { \ |
| 9915 | uint32_t rslt_type_id = ops[0]; \ |
| 9916 | auto &rslt_type = get<SPIRType>(rslt_type_id); \ |
| 9917 | uint32_t id = ops[1]; \ |
| 9918 | uint32_t img_id = ops[2]; \ |
| 9919 | string img_exp = to_expression(img_id); \ |
| 9920 | string expr = type_to_glsl(rslt_type) + "(" + img_exp + ".get_num_" #qrytype "())"; \ |
| 9921 | emit_op(rslt_type_id, id, expr, should_forward(img_id)); \ |
| 9922 | } while (false) |
| 9923 | |
| 9924 | case OpImageQueryLevels: |
| 9925 | MSL_ImgQry(mip_levels); |
| 9926 | break; |
| 9927 | |
| 9928 | case OpImageQuerySamples: |
| 9929 | MSL_ImgQry(samples); |
| 9930 | break; |
| 9931 | |
| 9932 | case OpImage: |
| 9933 | { |
| 9934 | uint32_t result_type = ops[0]; |
| 9935 | uint32_t id = ops[1]; |
| 9936 | auto *combined = maybe_get<SPIRCombinedImageSampler>(ops[2]); |
| 9937 | |
| 9938 | if (combined) |
| 9939 | { |
| 9940 | auto &e = emit_op(result_type, id, to_expression(combined->image), true, true); |
| 9941 | auto *var = maybe_get_backing_variable(combined->image); |
| 9942 | if (var) |
| 9943 | e.loaded_from = var->self; |
| 9944 | } |
| 9945 | else |
| 9946 | { |
| 9947 | auto *var = maybe_get_backing_variable(ops[2]); |
| 9948 | SPIRExpression *e; |
| 9949 | if (var && has_extended_decoration(var->self, SPIRVCrossDecorationDynamicImageSampler)) |
| 9950 | e = &emit_op(result_type, id, join(to_expression(ops[2]), ".plane0"), true, true); |
| 9951 | else |
| 9952 | e = &emit_op(result_type, id, to_expression(ops[2]), true, true); |
| 9953 | if (var) |
| 9954 | e->loaded_from = var->self; |
| 9955 | } |
| 9956 | break; |
| 9957 | } |
| 9958 | |
| 9959 | // Casting |
| 9960 | case OpQuantizeToF16: |
| 9961 | { |
| 9962 | uint32_t result_type = ops[0]; |
| 9963 | uint32_t id = ops[1]; |
| 9964 | uint32_t arg = ops[2]; |
| 9965 | string exp = join("spvQuantizeToF16(", to_expression(arg), ")"); |
| 9966 | emit_op(result_type, id, exp, should_forward(arg)); |
| 9967 | break; |
| 9968 | } |
| 9969 | |
| 9970 | case OpInBoundsAccessChain: |
| 9971 | case OpAccessChain: |
| 9972 | case OpPtrAccessChain: |
| 9973 | if (is_tessellation_shader()) |
| 9974 | { |
| 9975 | if (!emit_tessellation_access_chain(ops, instruction.length)) |
| 9976 | CompilerGLSL::emit_instruction(instruction); |
| 9977 | } |
| 9978 | else |
| 9979 | CompilerGLSL::emit_instruction(instruction); |
| 9980 | fix_up_interpolant_access_chain(ops, instruction.length); |
| 9981 | break; |
| 9982 | |
| 9983 | case OpStore: |
| 9984 | { |
| 9985 | const auto &type = expression_type(ops[0]); |
| 9986 | |
| 9987 | if (is_out_of_bounds_tessellation_level(ops[0])) |
| 9988 | break; |
| 9989 | |
| 9990 | if (needs_frag_discard_checks() && |
| 9991 | (type.storage == StorageClassStorageBuffer || type.storage == StorageClassUniform)) |
| 9992 | { |
| 9993 | // If we're in a continue block, this kludge will make the block too complex |
| 9994 | // to emit normally. |
| 9995 | assert(current_emitting_block); |
| 9996 | auto cont_type = continue_block_type(*current_emitting_block); |
| 9997 | if (cont_type != SPIRBlock::ContinueNone && cont_type != SPIRBlock::ComplexLoop) |
| 9998 | { |
| 9999 | current_emitting_block->complex_continue = true; |
| 10000 | force_recompile(); |
| 10001 | } |
| 10002 | statement("if (!", builtin_to_glsl(BuiltInHelperInvocation, StorageClassInput), ")"); |
| 10003 | begin_scope(); |
| 10004 | } |
| 10005 | if (!maybe_emit_array_assignment(ops[0], ops[1])) |
| 10006 | CompilerGLSL::emit_instruction(instruction); |
| 10007 | if (needs_frag_discard_checks() && |
| 10008 | (type.storage == StorageClassStorageBuffer || type.storage == StorageClassUniform)) |
| 10009 | end_scope(); |
| 10010 | if (has_decoration(ops[0], DecorationBuiltIn) && get_decoration(ops[0], DecorationBuiltIn) == BuiltInPointSize) |
| 10011 | writes_to_point_size = true; |
| 10012 | |
| 10013 | break; |
| 10014 | } |
| 10015 | |
| 10016 | // Compute barriers |
| 10017 | case OpMemoryBarrier: |
| 10018 | emit_barrier(0, ops[0], ops[1]); |
| 10019 | break; |
| 10020 | |
| 10021 | case OpControlBarrier: |
| 10022 | // In GLSL a memory barrier is often followed by a control barrier. |
| 10023 | // But in MSL, memory barriers are also control barriers (before MSL 3.2), so don't |
| 10024 | // emit a simple control barrier if a memory barrier has just been emitted. |
| 10025 | if (previous_instruction_opcode != OpMemoryBarrier || msl_options.supports_msl_version(3, 2)) |
| 10026 | emit_barrier(ops[0], ops[1], ops[2]); |
| 10027 | break; |
| 10028 | |
| 10029 | case OpOuterProduct: |
| 10030 | { |
| 10031 | uint32_t result_type = ops[0]; |
| 10032 | uint32_t id = ops[1]; |
| 10033 | uint32_t a = ops[2]; |
| 10034 | uint32_t b = ops[3]; |
| 10035 | |
| 10036 | auto &type = get<SPIRType>(result_type); |
| 10037 | string expr = type_to_glsl_constructor(type); |
| 10038 | expr += "("; |
| 10039 | for (uint32_t col = 0; col < type.columns; col++) |
| 10040 | { |
| 10041 | expr += to_enclosed_unpacked_expression(a); |
| 10042 | expr += " * "; |
| 10043 | expr += to_extract_component_expression(b, col); |
| 10044 | if (col + 1 < type.columns) |
| 10045 | expr += ", "; |
| 10046 | } |
| 10047 | expr += ")"; |
| 10048 | emit_op(result_type, id, expr, should_forward(a) && should_forward(b)); |
| 10049 | inherit_expression_dependencies(id, a); |
| 10050 | inherit_expression_dependencies(id, b); |
| 10051 | break; |
| 10052 | } |
| 10053 | |
| 10054 | case OpVectorTimesMatrix: |
| 10055 | case OpMatrixTimesVector: |
| 10056 | { |
| 10057 | if (!msl_options.invariant_float_math && !has_decoration(ops[1], DecorationNoContraction)) |
| 10058 | { |
| 10059 | CompilerGLSL::emit_instruction(instruction); |
| 10060 | break; |
| 10061 | } |
| 10062 | |
| 10063 | // If the matrix needs transpose, just flip the multiply order. |
| 10064 | auto *e = maybe_get<SPIRExpression>(ops[opcode == OpMatrixTimesVector ? 2 : 3]); |
| 10065 | if (e && e->need_transpose) |
| 10066 | { |
| 10067 | e->need_transpose = false; |
| 10068 | string expr; |
| 10069 | |
| 10070 | if (opcode == OpMatrixTimesVector) |
| 10071 | { |
| 10072 | expr = join("spvFMulVectorMatrix(", to_enclosed_unpacked_expression(ops[3]), ", ", |
| 10073 | to_unpacked_row_major_matrix_expression(ops[2]), ")"); |
| 10074 | } |
| 10075 | else |
| 10076 | { |
| 10077 | expr = join("spvFMulMatrixVector(", to_unpacked_row_major_matrix_expression(ops[3]), ", ", |
| 10078 | to_enclosed_unpacked_expression(ops[2]), ")"); |
| 10079 | } |
| 10080 | |
| 10081 | bool forward = should_forward(ops[2]) && should_forward(ops[3]); |
| 10082 | emit_op(ops[0], ops[1], expr, forward); |
| 10083 | e->need_transpose = true; |
| 10084 | inherit_expression_dependencies(ops[1], ops[2]); |
| 10085 | inherit_expression_dependencies(ops[1], ops[3]); |
| 10086 | } |
| 10087 | else |
| 10088 | { |
| 10089 | if (opcode == OpMatrixTimesVector) |
| 10090 | MSL_BFOP(spvFMulMatrixVector); |
| 10091 | else |
| 10092 | MSL_BFOP(spvFMulVectorMatrix); |
| 10093 | } |
| 10094 | break; |
| 10095 | } |
| 10096 | |
| 10097 | case OpMatrixTimesMatrix: |
| 10098 | { |
| 10099 | if (!msl_options.invariant_float_math && !has_decoration(ops[1], DecorationNoContraction)) |
| 10100 | { |
| 10101 | CompilerGLSL::emit_instruction(instruction); |
| 10102 | break; |
| 10103 | } |
| 10104 | |
| 10105 | auto *a = maybe_get<SPIRExpression>(ops[2]); |
| 10106 | auto *b = maybe_get<SPIRExpression>(ops[3]); |
| 10107 | |
| 10108 | // If both matrices need transpose, we can multiply in flipped order and tag the expression as transposed. |
| 10109 | // a^T * b^T = (b * a)^T. |
| 10110 | if (a && b && a->need_transpose && b->need_transpose) |
| 10111 | { |
| 10112 | a->need_transpose = false; |
| 10113 | b->need_transpose = false; |
| 10114 | |
| 10115 | auto expr = |
| 10116 | join("spvFMulMatrixMatrix(", enclose_expression(to_unpacked_row_major_matrix_expression(ops[3])), ", ", |
| 10117 | enclose_expression(to_unpacked_row_major_matrix_expression(ops[2])), ")"); |
| 10118 | |
| 10119 | bool forward = should_forward(ops[2]) && should_forward(ops[3]); |
| 10120 | auto &e = emit_op(ops[0], ops[1], expr, forward); |
| 10121 | e.need_transpose = true; |
| 10122 | a->need_transpose = true; |
| 10123 | b->need_transpose = true; |
| 10124 | inherit_expression_dependencies(ops[1], ops[2]); |
| 10125 | inherit_expression_dependencies(ops[1], ops[3]); |
| 10126 | } |
| 10127 | else |
| 10128 | MSL_BFOP(spvFMulMatrixMatrix); |
| 10129 | |
| 10130 | break; |
| 10131 | } |
| 10132 | |
| 10133 | case OpIAddCarry: |
| 10134 | case OpISubBorrow: |
| 10135 | { |
| 10136 | uint32_t result_type = ops[0]; |
| 10137 | uint32_t result_id = ops[1]; |
| 10138 | uint32_t op0 = ops[2]; |
| 10139 | uint32_t op1 = ops[3]; |
| 10140 | auto &type = get<SPIRType>(result_type); |
| 10141 | emit_uninitialized_temporary_expression(result_type, result_id); |
| 10142 | |
| 10143 | auto &res_type = get<SPIRType>(type.member_types[1]); |
| 10144 | if (opcode == OpIAddCarry) |
| 10145 | { |
| 10146 | statement(to_expression(result_id), ".", to_member_name(type, 0), " = ", |
| 10147 | to_enclosed_unpacked_expression(op0), " + ", to_enclosed_unpacked_expression(op1), ";"); |
| 10148 | statement(to_expression(result_id), ".", to_member_name(type, 1), " = select(", type_to_glsl(res_type), |
| 10149 | "(1), ", type_to_glsl(res_type), "(0), ", to_unpacked_expression(result_id), ".", to_member_name(type, 0), |
| 10150 | " >= max(", to_unpacked_expression(op0), ", ", to_unpacked_expression(op1), "));"); |
| 10151 | } |
| 10152 | else |
| 10153 | { |
| 10154 | statement(to_expression(result_id), ".", to_member_name(type, 0), " = ", to_enclosed_unpacked_expression(op0), " - ", |
| 10155 | to_enclosed_unpacked_expression(op1), ";"); |
| 10156 | statement(to_expression(result_id), ".", to_member_name(type, 1), " = select(", type_to_glsl(res_type), |
| 10157 | "(1), ", type_to_glsl(res_type), "(0), ", to_enclosed_unpacked_expression(op0), |
| 10158 | " >= ", to_enclosed_unpacked_expression(op1), ");"); |
| 10159 | } |
| 10160 | break; |
| 10161 | } |
| 10162 | |
| 10163 | case OpUMulExtended: |
| 10164 | case OpSMulExtended: |
| 10165 | { |
| 10166 | uint32_t result_type = ops[0]; |
| 10167 | uint32_t result_id = ops[1]; |
| 10168 | uint32_t op0 = ops[2]; |
| 10169 | uint32_t op1 = ops[3]; |
| 10170 | auto &type = get<SPIRType>(result_type); |
| 10171 | auto &op_type = get<SPIRType>(type.member_types[0]); |
| 10172 | auto input_type = opcode == OpSMulExtended ? int_type : uint_type; |
| 10173 | string cast_op0, cast_op1; |
| 10174 | |
| 10175 | binary_op_bitcast_helper(cast_op0, cast_op1, input_type, op0, op1, false); |
| 10176 | auto expr = join("spvMulExtended<", type_to_glsl(type), ", ", type_to_glsl(op_type), ">(", cast_op0, ", ", cast_op1, ")"); |
| 10177 | emit_op(result_type, result_id, expr, true); |
| 10178 | break; |
| 10179 | } |
| 10180 | |
| 10181 | case OpArrayLength: |
| 10182 | { |
| 10183 | auto &type = expression_type(ops[2]); |
| 10184 | uint32_t offset = type_struct_member_offset(type, ops[3]); |
| 10185 | uint32_t stride = type_struct_member_array_stride(type, ops[3]); |
| 10186 | |
| 10187 | auto expr = join("(", to_buffer_size_expression(ops[2]), " - ", offset, ") / ", stride); |
| 10188 | emit_op(ops[0], ops[1], expr, true); |
| 10189 | break; |
| 10190 | } |
| 10191 | |
| 10192 | // Legacy sub-group stuff ... |
| 10193 | case OpSubgroupBallotKHR: |
| 10194 | case OpSubgroupFirstInvocationKHR: |
| 10195 | case OpSubgroupReadInvocationKHR: |
| 10196 | case OpSubgroupAllKHR: |
| 10197 | case OpSubgroupAnyKHR: |
| 10198 | case OpSubgroupAllEqualKHR: |
| 10199 | emit_subgroup_op(instruction); |
| 10200 | break; |
| 10201 | |
| 10202 | // SPV_INTEL_shader_integer_functions2 |
| 10203 | case OpUCountLeadingZerosINTEL: |
| 10204 | MSL_UFOP(clz); |
| 10205 | break; |
| 10206 | |
| 10207 | case OpUCountTrailingZerosINTEL: |
| 10208 | MSL_UFOP(ctz); |
| 10209 | break; |
| 10210 | |
| 10211 | case OpAbsISubINTEL: |
| 10212 | case OpAbsUSubINTEL: |
| 10213 | MSL_BFOP(absdiff); |
| 10214 | break; |
| 10215 | |
| 10216 | case OpIAddSatINTEL: |
| 10217 | case OpUAddSatINTEL: |
| 10218 | MSL_BFOP(addsat); |
| 10219 | break; |
| 10220 | |
| 10221 | case OpIAverageINTEL: |
| 10222 | case OpUAverageINTEL: |
| 10223 | MSL_BFOP(hadd); |
| 10224 | break; |
| 10225 | |
| 10226 | case OpIAverageRoundedINTEL: |
| 10227 | case OpUAverageRoundedINTEL: |
| 10228 | MSL_BFOP(rhadd); |
| 10229 | break; |
| 10230 | |
| 10231 | case OpISubSatINTEL: |
| 10232 | case OpUSubSatINTEL: |
| 10233 | MSL_BFOP(subsat); |
| 10234 | break; |
| 10235 | |
| 10236 | case OpIMul32x16INTEL: |
| 10237 | { |
| 10238 | uint32_t result_type = ops[0]; |
| 10239 | uint32_t id = ops[1]; |
| 10240 | uint32_t a = ops[2], b = ops[3]; |
| 10241 | bool forward = should_forward(a) && should_forward(b); |
| 10242 | emit_op(result_type, id, join("int(short(", to_unpacked_expression(a), ")) * int(short(", to_unpacked_expression(b), "))"), forward); |
| 10243 | inherit_expression_dependencies(id, a); |
| 10244 | inherit_expression_dependencies(id, b); |
| 10245 | break; |
| 10246 | } |
| 10247 | |
| 10248 | case OpUMul32x16INTEL: |
| 10249 | { |
| 10250 | uint32_t result_type = ops[0]; |
| 10251 | uint32_t id = ops[1]; |
| 10252 | uint32_t a = ops[2], b = ops[3]; |
| 10253 | bool forward = should_forward(a) && should_forward(b); |
| 10254 | emit_op(result_type, id, join("uint(ushort(", to_unpacked_expression(a), ")) * uint(ushort(", to_unpacked_expression(b), "))"), forward); |
| 10255 | inherit_expression_dependencies(id, a); |
| 10256 | inherit_expression_dependencies(id, b); |
| 10257 | break; |
| 10258 | } |
| 10259 | |
| 10260 | // SPV_EXT_demote_to_helper_invocation |
| 10261 | case OpDemoteToHelperInvocationEXT: |
| 10262 | if (!msl_options.supports_msl_version(2, 3)) |
| 10263 | SPIRV_CROSS_THROW("discard_fragment() does not formally have demote semantics until MSL 2.3."); |
| 10264 | CompilerGLSL::emit_instruction(instruction); |
| 10265 | break; |
| 10266 | |
| 10267 | case OpIsHelperInvocationEXT: |
| 10268 | if (msl_options.is_ios() && !msl_options.supports_msl_version(2, 3)) |
| 10269 | SPIRV_CROSS_THROW("simd_is_helper_thread() requires MSL 2.3 on iOS."); |
| 10270 | else if (msl_options.is_macos() && !msl_options.supports_msl_version(2, 1)) |
| 10271 | SPIRV_CROSS_THROW("simd_is_helper_thread() requires MSL 2.1 on macOS."); |
| 10272 | emit_op(ops[0], ops[1], |
| 10273 | needs_manual_helper_invocation_updates() ? builtin_to_glsl(BuiltInHelperInvocation, StorageClassInput) : |
| 10274 | "simd_is_helper_thread()", |
| 10275 | false); |
| 10276 | break; |
| 10277 | |
| 10278 | case OpBeginInvocationInterlockEXT: |
| 10279 | case OpEndInvocationInterlockEXT: |
| 10280 | if (!msl_options.supports_msl_version(2, 0)) |
| 10281 | SPIRV_CROSS_THROW("Raster order groups require MSL 2.0."); |
| 10282 | break; // Nothing to do in the body |
| 10283 | |
| 10284 | case OpConvertUToAccelerationStructureKHR: |
| 10285 | SPIRV_CROSS_THROW("ConvertUToAccelerationStructure is not supported in MSL."); |
| 10286 | case OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR: |
| 10287 | SPIRV_CROSS_THROW("BindingTableRecordOffset is not supported in MSL."); |
| 10288 | |
| 10289 | case OpRayQueryInitializeKHR: |
| 10290 | { |
| 10291 | flush_variable_declaration(ops[0]); |
| 10292 | register_write(ops[0]); |
| 10293 | add_spv_func_and_recompile(SPVFuncImplRayQueryIntersectionParams); |
| 10294 | |
| 10295 | statement(to_expression(ops[0]), ".reset(", "ray(", to_expression(ops[4]), ", ", to_expression(ops[6]), ", ", |
| 10296 | to_expression(ops[5]), ", ", to_expression(ops[7]), "), ", to_expression(ops[1]), ", ", to_expression(ops[3]), |
| 10297 | ", spvMakeIntersectionParams(", to_expression(ops[2]), "));"); |
| 10298 | break; |
| 10299 | } |
| 10300 | case OpRayQueryProceedKHR: |
| 10301 | { |
| 10302 | flush_variable_declaration(ops[0]); |
| 10303 | register_write(ops[2]); |
| 10304 | emit_op(ops[0], ops[1], join(to_expression(ops[2]), ".next()"), false); |
| 10305 | break; |
| 10306 | } |
| 10307 | #define MSL_RAY_QUERY_IS_CANDIDATE get<SPIRConstant>(ops[3]).scalar_i32() == 0 |
| 10308 | |
| 10309 | #define MSL_RAY_QUERY_GET_OP(op, msl_op) \ |
| 10310 | case OpRayQueryGet##op##KHR: \ |
| 10311 | flush_variable_declaration(ops[2]); \ |
| 10312 | emit_op(ops[0], ops[1], join(to_expression(ops[2]), ".get_" #msl_op "()"), false); \ |
| 10313 | break |
| 10314 | |
| 10315 | #define MSL_RAY_QUERY_OP_INNER2(op, msl_prefix, msl_op) \ |
| 10316 | case OpRayQueryGet##op##KHR: \ |
| 10317 | flush_variable_declaration(ops[2]); \ |
| 10318 | if (MSL_RAY_QUERY_IS_CANDIDATE) \ |
| 10319 | emit_op(ops[0], ops[1], join(to_expression(ops[2]), #msl_prefix "_candidate_" #msl_op "()"), false); \ |
| 10320 | else \ |
| 10321 | emit_op(ops[0], ops[1], join(to_expression(ops[2]), #msl_prefix "_committed_" #msl_op "()"), false); \ |
| 10322 | break |
| 10323 | |
| 10324 | #define MSL_RAY_QUERY_GET_OP2(op, msl_op) MSL_RAY_QUERY_OP_INNER2(op, .get, msl_op) |
| 10325 | #define MSL_RAY_QUERY_IS_OP2(op, msl_op) MSL_RAY_QUERY_OP_INNER2(op, .is, msl_op) |
| 10326 | |
| 10327 | MSL_RAY_QUERY_GET_OP(RayTMin, ray_min_distance); |
| 10328 | MSL_RAY_QUERY_GET_OP(WorldRayOrigin, world_space_ray_origin); |
| 10329 | MSL_RAY_QUERY_GET_OP(WorldRayDirection, world_space_ray_direction); |
| 10330 | MSL_RAY_QUERY_GET_OP2(IntersectionInstanceId, instance_id); |
| 10331 | MSL_RAY_QUERY_GET_OP2(IntersectionInstanceCustomIndex, user_instance_id); |
| 10332 | MSL_RAY_QUERY_GET_OP2(IntersectionBarycentrics, triangle_barycentric_coord); |
| 10333 | MSL_RAY_QUERY_GET_OP2(IntersectionPrimitiveIndex, primitive_id); |
| 10334 | MSL_RAY_QUERY_GET_OP2(IntersectionGeometryIndex, geometry_id); |
| 10335 | MSL_RAY_QUERY_GET_OP2(IntersectionObjectRayOrigin, ray_origin); |
| 10336 | MSL_RAY_QUERY_GET_OP2(IntersectionObjectRayDirection, ray_direction); |
| 10337 | MSL_RAY_QUERY_GET_OP2(IntersectionObjectToWorld, object_to_world_transform); |
| 10338 | MSL_RAY_QUERY_GET_OP2(IntersectionWorldToObject, world_to_object_transform); |
| 10339 | MSL_RAY_QUERY_IS_OP2(IntersectionFrontFace, triangle_front_facing); |
| 10340 | |
| 10341 | case OpRayQueryGetIntersectionTypeKHR: |
| 10342 | flush_variable_declaration(ops[2]); |
| 10343 | if (MSL_RAY_QUERY_IS_CANDIDATE) |
| 10344 | emit_op(ops[0], ops[1], join("uint(", to_expression(ops[2]), ".get_candidate_intersection_type()) - 1"), |
| 10345 | false); |
| 10346 | else |
| 10347 | emit_op(ops[0], ops[1], join("uint(", to_expression(ops[2]), ".get_committed_intersection_type())"), false); |
| 10348 | break; |
| 10349 | case OpRayQueryGetIntersectionTKHR: |
| 10350 | flush_variable_declaration(ops[2]); |
| 10351 | if (MSL_RAY_QUERY_IS_CANDIDATE) |
| 10352 | emit_op(ops[0], ops[1], join(to_expression(ops[2]), ".get_candidate_triangle_distance()"), false); |
| 10353 | else |
| 10354 | emit_op(ops[0], ops[1], join(to_expression(ops[2]), ".get_committed_distance()"), false); |
| 10355 | break; |
| 10356 | case OpRayQueryGetIntersectionCandidateAABBOpaqueKHR: |
| 10357 | { |
| 10358 | flush_variable_declaration(ops[0]); |
| 10359 | emit_op(ops[0], ops[1], join(to_expression(ops[2]), ".is_candidate_non_opaque_bounding_box()"), false); |
| 10360 | break; |
| 10361 | } |
| 10362 | case OpRayQueryConfirmIntersectionKHR: |
| 10363 | flush_variable_declaration(ops[0]); |
| 10364 | register_write(ops[0]); |
| 10365 | statement(to_expression(ops[0]), ".commit_triangle_intersection();"); |
| 10366 | break; |
| 10367 | case OpRayQueryGenerateIntersectionKHR: |
| 10368 | flush_variable_declaration(ops[0]); |
| 10369 | register_write(ops[0]); |
| 10370 | statement(to_expression(ops[0]), ".commit_bounding_box_intersection(", to_expression(ops[1]), ");"); |
| 10371 | break; |
| 10372 | case OpRayQueryTerminateKHR: |
| 10373 | flush_variable_declaration(ops[0]); |
| 10374 | register_write(ops[0]); |
| 10375 | statement(to_expression(ops[0]), ".abort();"); |
| 10376 | break; |
| 10377 | #undef MSL_RAY_QUERY_GET_OP |
| 10378 | #undef MSL_RAY_QUERY_IS_CANDIDATE |
| 10379 | #undef MSL_RAY_QUERY_IS_OP2 |
| 10380 | #undef MSL_RAY_QUERY_GET_OP2 |
| 10381 | #undef MSL_RAY_QUERY_OP_INNER2 |
| 10382 | |
| 10383 | case OpConvertPtrToU: |
| 10384 | case OpConvertUToPtr: |
| 10385 | case OpBitcast: |
| 10386 | { |
| 10387 | auto &type = get<SPIRType>(ops[0]); |
| 10388 | auto &input_type = expression_type(ops[2]); |
| 10389 | |
| 10390 | if (opcode != OpBitcast || is_pointer(type) || is_pointer(input_type)) |
| 10391 | { |
| 10392 | string op; |
| 10393 | |
| 10394 | if ((type.vecsize == 1 || is_pointer(type)) && (input_type.vecsize == 1 || is_pointer(input_type))) |
| 10395 | op = join("reinterpret_cast<", type_to_glsl(type), ">(", to_unpacked_expression(ops[2]), ")"); |
| 10396 | else if (input_type.vecsize == 2) |
| 10397 | op = join("reinterpret_cast<", type_to_glsl(type), ">(as_type<ulong>(", to_unpacked_expression(ops[2]), "))"); |
| 10398 | else |
| 10399 | op = join("as_type<", type_to_glsl(type), ">(reinterpret_cast<ulong>(", to_unpacked_expression(ops[2]), "))"); |
| 10400 | |
| 10401 | emit_op(ops[0], ops[1], op, should_forward(ops[2])); |
| 10402 | inherit_expression_dependencies(ops[1], ops[2]); |
| 10403 | } |
| 10404 | else |
| 10405 | CompilerGLSL::emit_instruction(instruction); |
| 10406 | |
| 10407 | break; |
| 10408 | } |
| 10409 | |
| 10410 | case OpSDot: |
| 10411 | case OpUDot: |
| 10412 | case OpSUDot: |
| 10413 | { |
| 10414 | uint32_t result_type = ops[0]; |
| 10415 | uint32_t id = ops[1]; |
| 10416 | uint32_t vec1 = ops[2]; |
| 10417 | uint32_t vec2 = ops[3]; |
| 10418 | |
| 10419 | auto &input_type1 = expression_type(vec1); |
| 10420 | auto &input_type2 = expression_type(vec2); |
| 10421 | |
| 10422 | string vec1input, vec2input; |
| 10423 | auto input_size = input_type1.vecsize; |
| 10424 | if (instruction.length == 5) |
| 10425 | { |
| 10426 | if (ops[4] == PackedVectorFormatPackedVectorFormat4x8Bit) |
| 10427 | { |
| 10428 | string type = opcode == OpSDot || opcode == OpSUDot ? "char4" : "uchar4"; |
| 10429 | vec1input = join("as_type<", type, ">(", to_expression(vec1), ")"); |
| 10430 | type = opcode == OpSDot ? "char4" : "uchar4"; |
| 10431 | vec2input = join("as_type<", type, ">(", to_expression(vec2), ")"); |
| 10432 | input_size = 4; |
| 10433 | } |
| 10434 | else |
| 10435 | SPIRV_CROSS_THROW("Packed vector formats other than 4x8Bit for integer dot product is not supported."); |
| 10436 | } |
| 10437 | else |
| 10438 | { |
| 10439 | // Inputs are sign or zero-extended to their target width. |
| 10440 | SPIRType::BaseType vec1_expected_type = |
| 10441 | opcode != OpUDot ? |
| 10442 | to_signed_basetype(input_type1.width) : |
| 10443 | to_unsigned_basetype(input_type1.width); |
| 10444 | |
| 10445 | SPIRType::BaseType vec2_expected_type = |
| 10446 | opcode != OpSDot ? |
| 10447 | to_unsigned_basetype(input_type2.width) : |
| 10448 | to_signed_basetype(input_type2.width); |
| 10449 | |
| 10450 | vec1input = bitcast_expression(vec1_expected_type, vec1); |
| 10451 | vec2input = bitcast_expression(vec2_expected_type, vec2); |
| 10452 | } |
| 10453 | |
| 10454 | auto &type = get<SPIRType>(result_type); |
| 10455 | |
| 10456 | // We'll get the appropriate sign-extend or zero-extend, no matter which type we cast to here. |
| 10457 | // The addition in reduce_add is sign-invariant. |
| 10458 | auto result_type_cast = join(type_to_glsl(type), input_size); |
| 10459 | |
| 10460 | string exp = join("reduce_add(", |
| 10461 | result_type_cast, "(", vec1input, ") * ", |
| 10462 | result_type_cast, "(", vec2input, "))"); |
| 10463 | |
| 10464 | emit_op(result_type, id, exp, should_forward(vec1) && should_forward(vec2)); |
| 10465 | inherit_expression_dependencies(id, vec1); |
| 10466 | inherit_expression_dependencies(id, vec2); |
| 10467 | break; |
| 10468 | } |
| 10469 | |
| 10470 | case OpSDotAccSat: |
| 10471 | case OpUDotAccSat: |
| 10472 | case OpSUDotAccSat: |
| 10473 | { |
| 10474 | uint32_t result_type = ops[0]; |
| 10475 | uint32_t id = ops[1]; |
| 10476 | uint32_t vec1 = ops[2]; |
| 10477 | uint32_t vec2 = ops[3]; |
| 10478 | uint32_t acc = ops[4]; |
| 10479 | |
| 10480 | auto input_type1 = expression_type(vec1); |
| 10481 | auto input_type2 = expression_type(vec2); |
| 10482 | |
| 10483 | string vec1input, vec2input; |
| 10484 | if (instruction.length == 6) |
| 10485 | { |
| 10486 | if (ops[5] == PackedVectorFormatPackedVectorFormat4x8Bit) |
| 10487 | { |
| 10488 | string type = opcode == OpSDotAccSat || opcode == OpSUDotAccSat ? "char4" : "uchar4"; |
| 10489 | vec1input = join("as_type<", type, ">(", to_expression(vec1), ")"); |
| 10490 | type = opcode == OpSDotAccSat ? "char4" : "uchar4"; |
| 10491 | vec2input = join("as_type<", type, ">(", to_expression(vec2), ")"); |
| 10492 | input_type1.vecsize = 4; |
| 10493 | input_type2.vecsize = 4; |
| 10494 | } |
| 10495 | else |
| 10496 | SPIRV_CROSS_THROW("Packed vector formats other than 4x8Bit for integer dot product is not supported."); |
| 10497 | } |
| 10498 | else |
| 10499 | { |
| 10500 | // Inputs are sign or zero-extended to their target width. |
| 10501 | SPIRType::BaseType vec1_expected_type = |
| 10502 | opcode != OpUDotAccSat ? |
| 10503 | to_signed_basetype(input_type1.width) : |
| 10504 | to_unsigned_basetype(input_type1.width); |
| 10505 | |
| 10506 | SPIRType::BaseType vec2_expected_type = |
| 10507 | opcode != OpSDotAccSat ? |
| 10508 | to_unsigned_basetype(input_type2.width) : |
| 10509 | to_signed_basetype(input_type2.width); |
| 10510 | |
| 10511 | vec1input = bitcast_expression(vec1_expected_type, vec1); |
| 10512 | vec2input = bitcast_expression(vec2_expected_type, vec2); |
| 10513 | } |
| 10514 | |
| 10515 | auto &type = get<SPIRType>(result_type); |
| 10516 | |
| 10517 | SPIRType::BaseType pre_saturate_type = |
| 10518 | opcode != OpUDotAccSat ? |
| 10519 | to_signed_basetype(type.width) : |
| 10520 | to_unsigned_basetype(type.width); |
| 10521 | |
| 10522 | input_type1.basetype = pre_saturate_type; |
| 10523 | input_type2.basetype = pre_saturate_type; |
| 10524 | |
| 10525 | string exp = join(type_to_glsl(type), "(addsat(reduce_add(", |
| 10526 | type_to_glsl(input_type1), "(", vec1input, ") * ", |
| 10527 | type_to_glsl(input_type2), "(", vec2input, ")), ", |
| 10528 | bitcast_expression(pre_saturate_type, acc), "))"); |
| 10529 | |
| 10530 | emit_op(result_type, id, exp, should_forward(vec1) && should_forward(vec2)); |
| 10531 | inherit_expression_dependencies(id, vec1); |
| 10532 | inherit_expression_dependencies(id, vec2); |
| 10533 | break; |
| 10534 | } |
| 10535 | |
| 10536 | case OpSetMeshOutputsEXT: |
| 10537 | { |
| 10538 | flush_variable_declaration(builtin_mesh_primitive_indices_id); |
| 10539 | add_spv_func_and_recompile(SPVFuncImplSetMeshOutputsEXT); |
| 10540 | statement("spvSetMeshOutputsEXT(gl_LocalInvocationIndex, spvMeshSizes, ", to_unpacked_expression(ops[0]), ", ", to_unpacked_expression(ops[1]), ");"); |
| 10541 | break; |
| 10542 | } |
| 10543 | |
| 10544 | case OpAssumeTrueKHR: |
| 10545 | { |
| 10546 | auto condition = ops[0]; |
| 10547 | statement(join("SPV_ASSUME(", to_unpacked_expression(condition), ")")); |
| 10548 | break; |
| 10549 | } |
| 10550 | |
| 10551 | case OpExpectKHR: |
| 10552 | { |
| 10553 | auto result_type = ops[0]; |
| 10554 | auto ret = ops[1]; |
| 10555 | auto value = ops[2]; |
| 10556 | auto exp_value = ops[3]; |
| 10557 | |
| 10558 | auto exp = join("SPV_EXPECT(", to_unpacked_expression(value), ", ", to_unpacked_expression(exp_value), ")"); |
| 10559 | emit_op(result_type, ret, exp, should_forward(value), should_forward(exp_value)); |
| 10560 | inherit_expression_dependencies(ret, value); |
| 10561 | inherit_expression_dependencies(ret, exp_value); |
| 10562 | break; |
| 10563 | } |
| 10564 | |
| 10565 | default: |
| 10566 | CompilerGLSL::emit_instruction(instruction); |
| 10567 | break; |
| 10568 | } |
| 10569 | |
| 10570 | previous_instruction_opcode = opcode; |
| 10571 | } |
| 10572 | |
| 10573 | void CompilerMSL::emit_texture_op(const Instruction &i, bool sparse) |
| 10574 | { |
| 10575 | if (sparse) |
| 10576 | SPIRV_CROSS_THROW("Sparse feedback not yet supported in MSL."); |
| 10577 | |
| 10578 | if (msl_options.use_framebuffer_fetch_subpasses) |
| 10579 | { |
| 10580 | auto *ops = stream(i); |
| 10581 | |
| 10582 | uint32_t result_type_id = ops[0]; |
| 10583 | uint32_t id = ops[1]; |
| 10584 | uint32_t img = ops[2]; |
| 10585 | |
| 10586 | auto &type = expression_type(img); |
| 10587 | auto &imgtype = get<SPIRType>(type.self); |
| 10588 | |
| 10589 | // Use Metal's native frame-buffer fetch API for subpass inputs. |
| 10590 | if (imgtype.image.dim == DimSubpassData) |
| 10591 | { |
| 10592 | // Subpass inputs cannot be invalidated, |
| 10593 | // so just forward the expression directly. |
| 10594 | string expr = to_expression(img); |
| 10595 | emit_op(result_type_id, id, expr, true); |
| 10596 | return; |
| 10597 | } |
| 10598 | } |
| 10599 | |
| 10600 | // Fallback to default implementation |
| 10601 | CompilerGLSL::emit_texture_op(i, sparse); |
| 10602 | } |
| 10603 | |
| 10604 | void CompilerMSL::emit_barrier(uint32_t id_exe_scope, uint32_t id_mem_scope, uint32_t id_mem_sem) |
| 10605 | { |
| 10606 | auto model = get_execution_model(); |
| 10607 | |
| 10608 | if (model != ExecutionModelGLCompute && model != ExecutionModelTaskEXT && |
| 10609 | model != ExecutionModelMeshEXT && !is_tesc_shader()) |
| 10610 | { |
| 10611 | return; |
| 10612 | } |
| 10613 | |
| 10614 | uint32_t exe_scope = id_exe_scope ? evaluate_constant_u32(id_exe_scope) : uint32_t(ScopeInvocation); |
| 10615 | uint32_t mem_scope = id_mem_scope ? evaluate_constant_u32(id_mem_scope) : uint32_t(ScopeInvocation); |
| 10616 | // Use the wider of the two scopes (smaller value) |
| 10617 | exe_scope = min(exe_scope, mem_scope); |
| 10618 | |
| 10619 | if (msl_options.emulate_subgroups && exe_scope >= ScopeSubgroup && !id_mem_sem) |
| 10620 | // In this case, we assume a "subgroup" size of 1. The barrier, then, is a noop. |
| 10621 | return; |
| 10622 | |
| 10623 | string bar_stmt; |
| 10624 | |
| 10625 | if (!id_exe_scope && msl_options.supports_msl_version(3, 2)) |
| 10626 | { |
| 10627 | // Just took 10 years to get a proper barrier, but hey! |
| 10628 | bar_stmt = "atomic_thread_fence"; |
| 10629 | } |
| 10630 | else |
| 10631 | { |
| 10632 | if ((msl_options.is_ios() && msl_options.supports_msl_version(1, 2)) || msl_options.supports_msl_version(2)) |
| 10633 | bar_stmt = exe_scope < ScopeSubgroup ? "threadgroup_barrier" : "simdgroup_barrier"; |
| 10634 | else |
| 10635 | bar_stmt = "threadgroup_barrier"; |
| 10636 | } |
| 10637 | |
| 10638 | bar_stmt += "("; |
| 10639 | |
| 10640 | uint32_t mem_sem = id_mem_sem ? evaluate_constant_u32(id_mem_sem) : uint32_t(MemorySemanticsMaskNone); |
| 10641 | |
| 10642 | // Use the | operator to combine flags if we can. |
| 10643 | if (msl_options.supports_msl_version(1, 2)) |
| 10644 | { |
| 10645 | string mem_flags; |
| 10646 | |
| 10647 | // For tesc shaders, this also affects objects in the Output storage class. |
| 10648 | // Since in Metal, these are placed in a device buffer, we have to sync device memory here. |
| 10649 | if (is_tesc_shader() || |
| 10650 | (mem_sem & (MemorySemanticsUniformMemoryMask | MemorySemanticsCrossWorkgroupMemoryMask))) |
| 10651 | mem_flags += "mem_flags::mem_device"; |
| 10652 | |
| 10653 | // Fix tessellation patch function processing |
| 10654 | if (is_tesc_shader() || (mem_sem & (MemorySemanticsSubgroupMemoryMask | MemorySemanticsWorkgroupMemoryMask))) |
| 10655 | { |
| 10656 | if (!mem_flags.empty()) |
| 10657 | mem_flags += " | "; |
| 10658 | mem_flags += "mem_flags::mem_threadgroup"; |
| 10659 | } |
| 10660 | if (mem_sem & MemorySemanticsImageMemoryMask) |
| 10661 | { |
| 10662 | if (!mem_flags.empty()) |
| 10663 | mem_flags += " | "; |
| 10664 | mem_flags += "mem_flags::mem_texture"; |
| 10665 | } |
| 10666 | |
| 10667 | if (mem_flags.empty()) |
| 10668 | mem_flags = "mem_flags::mem_none"; |
| 10669 | |
| 10670 | bar_stmt += mem_flags; |
| 10671 | } |
| 10672 | else |
| 10673 | { |
| 10674 | if ((mem_sem & (MemorySemanticsUniformMemoryMask | MemorySemanticsCrossWorkgroupMemoryMask)) && |
| 10675 | (mem_sem & (MemorySemanticsSubgroupMemoryMask | MemorySemanticsWorkgroupMemoryMask))) |
| 10676 | bar_stmt += "mem_flags::mem_device_and_threadgroup"; |
| 10677 | else if (mem_sem & (MemorySemanticsUniformMemoryMask | MemorySemanticsCrossWorkgroupMemoryMask)) |
| 10678 | bar_stmt += "mem_flags::mem_device"; |
| 10679 | else if (mem_sem & (MemorySemanticsSubgroupMemoryMask | MemorySemanticsWorkgroupMemoryMask)) |
| 10680 | bar_stmt += "mem_flags::mem_threadgroup"; |
| 10681 | else if (mem_sem & MemorySemanticsImageMemoryMask) |
| 10682 | bar_stmt += "mem_flags::mem_texture"; |
| 10683 | else |
| 10684 | bar_stmt += "mem_flags::mem_none"; |
| 10685 | } |
| 10686 | |
| 10687 | if (!id_exe_scope && msl_options.supports_msl_version(3, 2)) |
| 10688 | { |
| 10689 | // If there's no device-related memory in the barrier, demote to workgroup scope. |
| 10690 | // glslang seems to emit device scope even for memoryBarrierShared(). |
| 10691 | if (mem_scope == ScopeDevice && |
| 10692 | (mem_sem & (MemorySemanticsUniformMemoryMask | |
| 10693 | MemorySemanticsImageMemoryMask | |
| 10694 | MemorySemanticsCrossWorkgroupMemoryMask)) == 0) |
| 10695 | { |
| 10696 | mem_scope = ScopeWorkgroup; |
| 10697 | } |
| 10698 | |
| 10699 | // MSL 3.2 only supports seq_cst or relaxed. |
| 10700 | if (mem_sem & (MemorySemanticsAcquireReleaseMask | |
| 10701 | MemorySemanticsAcquireMask | |
| 10702 | MemorySemanticsReleaseMask | |
| 10703 | MemorySemanticsSequentiallyConsistentMask)) |
| 10704 | { |
| 10705 | bar_stmt += ", memory_order_seq_cst"; |
| 10706 | } |
| 10707 | else |
| 10708 | { |
| 10709 | bar_stmt += ", memory_order_relaxed"; |
| 10710 | } |
| 10711 | |
| 10712 | switch (mem_scope) |
| 10713 | { |
| 10714 | case ScopeDevice: |
| 10715 | bar_stmt += ", thread_scope_device"; |
| 10716 | break; |
| 10717 | |
| 10718 | case ScopeWorkgroup: |
| 10719 | bar_stmt += ", thread_scope_threadgroup"; |
| 10720 | break; |
| 10721 | |
| 10722 | case ScopeSubgroup: |
| 10723 | bar_stmt += ", thread_scope_subgroup"; |
| 10724 | break; |
| 10725 | |
| 10726 | case ScopeInvocation: |
| 10727 | bar_stmt += ", thread_scope_thread"; |
| 10728 | break; |
| 10729 | |
| 10730 | default: |
| 10731 | // The default argument is device, which is conservative. |
| 10732 | break; |
| 10733 | } |
| 10734 | } |
| 10735 | |
| 10736 | bar_stmt += ");"; |
| 10737 | |
| 10738 | statement(bar_stmt); |
| 10739 | |
| 10740 | assert(current_emitting_block); |
| 10741 | flush_control_dependent_expressions(current_emitting_block->self); |
| 10742 | flush_all_active_variables(); |
| 10743 | } |
| 10744 | |
| 10745 | static bool storage_class_array_is_thread(StorageClass storage) |
| 10746 | { |
| 10747 | switch (storage) |
| 10748 | { |
| 10749 | case StorageClassInput: |
| 10750 | case StorageClassOutput: |
| 10751 | case StorageClassGeneric: |
| 10752 | case StorageClassFunction: |
| 10753 | case StorageClassPrivate: |
| 10754 | return true; |
| 10755 | |
| 10756 | default: |
| 10757 | return false; |
| 10758 | } |
| 10759 | } |
| 10760 | |
| 10761 | bool CompilerMSL::emit_array_copy(const char *expr, uint32_t lhs_id, uint32_t rhs_id, |
| 10762 | StorageClass lhs_storage, StorageClass rhs_storage) |
| 10763 | { |
| 10764 | // Allow Metal to use the array<T> template to make arrays a value type. |
| 10765 | // This, however, cannot be used for threadgroup address specifiers, so consider the custom array copy as fallback. |
| 10766 | bool lhs_is_thread_storage = storage_class_array_is_thread(lhs_storage); |
| 10767 | bool rhs_is_thread_storage = storage_class_array_is_thread(rhs_storage); |
| 10768 | |
| 10769 | bool lhs_is_array_template = lhs_is_thread_storage || lhs_storage == StorageClassWorkgroup; |
| 10770 | bool rhs_is_array_template = rhs_is_thread_storage || rhs_storage == StorageClassWorkgroup; |
| 10771 | |
| 10772 | // Special considerations for stage IO variables. |
| 10773 | // If the variable is actually backed by non-user visible device storage, we use array templates for those. |
| 10774 | // |
| 10775 | // Another special consideration is given to thread local variables which happen to have Offset decorations |
| 10776 | // applied to them. Block-like types do not use array templates, so we need to force POD path if we detect |
| 10777 | // these scenarios. This check isn't perfect since it would be technically possible to mix and match these things, |
| 10778 | // and for a fully correct solution we might have to track array template state through access chains as well, |
| 10779 | // but for all reasonable use cases, this should suffice. |
| 10780 | // This special case should also only apply to Function/Private storage classes. |
| 10781 | // We should not check backing variable for temporaries. |
| 10782 | auto *lhs_var = maybe_get_backing_variable(lhs_id); |
| 10783 | if (lhs_var && lhs_storage == StorageClassStorageBuffer && storage_class_array_is_thread(lhs_var->storage)) |
| 10784 | lhs_is_array_template = true; |
| 10785 | else if (lhs_var && lhs_storage != StorageClassGeneric && type_is_block_like(get<SPIRType>(lhs_var->basetype))) |
| 10786 | lhs_is_array_template = false; |
| 10787 | |
| 10788 | auto *rhs_var = maybe_get_backing_variable(rhs_id); |
| 10789 | if (rhs_var && rhs_storage == StorageClassStorageBuffer && storage_class_array_is_thread(rhs_var->storage)) |
| 10790 | rhs_is_array_template = true; |
| 10791 | else if (rhs_var && rhs_storage != StorageClassGeneric && type_is_block_like(get<SPIRType>(rhs_var->basetype))) |
| 10792 | rhs_is_array_template = false; |
| 10793 | |
| 10794 | // If threadgroup storage qualifiers are *not* used: |
| 10795 | // Avoid spvCopy* wrapper functions; Otherwise, spvUnsafeArray<> template cannot be used with that storage qualifier. |
| 10796 | if (lhs_is_array_template && rhs_is_array_template && !using_builtin_array()) |
| 10797 | { |
| 10798 | // Fall back to normal copy path. |
| 10799 | return false; |
| 10800 | } |
| 10801 | else |
| 10802 | { |
| 10803 | // Ensure the LHS variable has been declared |
| 10804 | if (lhs_var) |
| 10805 | flush_variable_declaration(lhs_var->self); |
| 10806 | |
| 10807 | string lhs; |
| 10808 | if (expr) |
| 10809 | lhs = expr; |
| 10810 | else |
| 10811 | lhs = to_expression(lhs_id); |
| 10812 | |
| 10813 | // Assignment from an array initializer is fine. |
| 10814 | auto &type = expression_type(rhs_id); |
| 10815 | auto *var = maybe_get_backing_variable(rhs_id); |
| 10816 | |
| 10817 | // Unfortunately, we cannot template on address space in MSL, |
| 10818 | // so explicit address space redirection it is ... |
| 10819 | bool is_constant = false; |
| 10820 | if (ir.ids[rhs_id].get_type() == TypeConstant) |
| 10821 | { |
| 10822 | is_constant = true; |
| 10823 | } |
| 10824 | else if (var && var->remapped_variable && var->statically_assigned && |
| 10825 | ir.ids[var->static_expression].get_type() == TypeConstant) |
| 10826 | { |
| 10827 | is_constant = true; |
| 10828 | } |
| 10829 | else if (rhs_storage == StorageClassUniform || rhs_storage == StorageClassUniformConstant) |
| 10830 | { |
| 10831 | is_constant = true; |
| 10832 | } |
| 10833 | |
| 10834 | // For the case where we have OpLoad triggering an array copy, |
| 10835 | // we cannot easily detect this case ahead of time since it's |
| 10836 | // context dependent. We might have to force a recompile here |
| 10837 | // if this is the only use of array copies in our shader. |
| 10838 | add_spv_func_and_recompile(type.array.size() > 1 ? SPVFuncImplArrayCopyMultidim : SPVFuncImplArrayCopy); |
| 10839 | |
| 10840 | const char *tag = nullptr; |
| 10841 | if (lhs_is_thread_storage && is_constant) |
| 10842 | tag = "FromConstantToStack"; |
| 10843 | else if (lhs_storage == StorageClassWorkgroup && is_constant) |
| 10844 | tag = "FromConstantToThreadGroup"; |
| 10845 | else if (lhs_is_thread_storage && rhs_is_thread_storage) |
| 10846 | tag = "FromStackToStack"; |
| 10847 | else if (lhs_storage == StorageClassWorkgroup && rhs_is_thread_storage) |
| 10848 | tag = "FromStackToThreadGroup"; |
| 10849 | else if (lhs_is_thread_storage && rhs_storage == StorageClassWorkgroup) |
| 10850 | tag = "FromThreadGroupToStack"; |
| 10851 | else if (lhs_storage == StorageClassWorkgroup && rhs_storage == StorageClassWorkgroup) |
| 10852 | tag = "FromThreadGroupToThreadGroup"; |
| 10853 | else if (lhs_storage == StorageClassStorageBuffer && rhs_storage == StorageClassStorageBuffer) |
| 10854 | tag = "FromDeviceToDevice"; |
| 10855 | else if (lhs_storage == StorageClassStorageBuffer && is_constant) |
| 10856 | tag = "FromConstantToDevice"; |
| 10857 | else if (lhs_storage == StorageClassStorageBuffer && rhs_storage == StorageClassWorkgroup) |
| 10858 | tag = "FromThreadGroupToDevice"; |
| 10859 | else if (lhs_storage == StorageClassStorageBuffer && rhs_is_thread_storage) |
| 10860 | tag = "FromStackToDevice"; |
| 10861 | else if (lhs_storage == StorageClassWorkgroup && rhs_storage == StorageClassStorageBuffer) |
| 10862 | tag = "FromDeviceToThreadGroup"; |
| 10863 | else if (lhs_is_thread_storage && rhs_storage == StorageClassStorageBuffer) |
| 10864 | tag = "FromDeviceToStack"; |
| 10865 | else |
| 10866 | SPIRV_CROSS_THROW("Unknown storage class used for copying arrays."); |
| 10867 | |
| 10868 | // Pass internal array of spvUnsafeArray<> into wrapper functions |
| 10869 | if (lhs_is_array_template && rhs_is_array_template && !msl_options.force_native_arrays) |
| 10870 | statement("spvArrayCopy", tag, "(", lhs, ".elements, ", to_expression(rhs_id), ".elements);"); |
| 10871 | if (lhs_is_array_template && !msl_options.force_native_arrays) |
| 10872 | statement("spvArrayCopy", tag, "(", lhs, ".elements, ", to_expression(rhs_id), ");"); |
| 10873 | else if (rhs_is_array_template && !msl_options.force_native_arrays) |
| 10874 | statement("spvArrayCopy", tag, "(", lhs, ", ", to_expression(rhs_id), ".elements);"); |
| 10875 | else |
| 10876 | statement("spvArrayCopy", tag, "(", lhs, ", ", to_expression(rhs_id), ");"); |
| 10877 | } |
| 10878 | |
| 10879 | return true; |
| 10880 | } |
| 10881 | |
| 10882 | uint32_t CompilerMSL::get_physical_tess_level_array_size(spv::BuiltIn builtin) const |
| 10883 | { |
| 10884 | if (is_tessellating_triangles()) |
| 10885 | return builtin == BuiltInTessLevelInner ? 1 : 3; |
| 10886 | else |
| 10887 | return builtin == BuiltInTessLevelInner ? 2 : 4; |
| 10888 | } |
| 10889 | |
| 10890 | // Since MSL does not allow arrays to be copied via simple variable assignment, |
| 10891 | // if the LHS and RHS represent an assignment of an entire array, it must be |
| 10892 | // implemented by calling an array copy function. |
| 10893 | // Returns whether the struct assignment was emitted. |
| 10894 | bool CompilerMSL::maybe_emit_array_assignment(uint32_t id_lhs, uint32_t id_rhs) |
| 10895 | { |
| 10896 | // We only care about assignments of an entire array |
| 10897 | auto &type = expression_type(id_lhs); |
| 10898 | if (!is_array(get_pointee_type(type))) |
| 10899 | return false; |
| 10900 | |
| 10901 | auto *var = maybe_get<SPIRVariable>(id_lhs); |
| 10902 | |
| 10903 | // Is this a remapped, static constant? Don't do anything. |
| 10904 | if (var && var->remapped_variable && var->statically_assigned) |
| 10905 | return true; |
| 10906 | |
| 10907 | if (ir.ids[id_rhs].get_type() == TypeConstant && var && var->deferred_declaration) |
| 10908 | { |
| 10909 | // Special case, if we end up declaring a variable when assigning the constant array, |
| 10910 | // we can avoid the copy by directly assigning the constant expression. |
| 10911 | // This is likely necessary to be able to use a variable as a true look-up table, as it is unlikely |
| 10912 | // the compiler will be able to optimize the spvArrayCopy() into a constant LUT. |
| 10913 | // After a variable has been declared, we can no longer assign constant arrays in MSL unfortunately. |
| 10914 | statement(to_expression(id_lhs), " = ", constant_expression(get<SPIRConstant>(id_rhs)), ";"); |
| 10915 | return true; |
| 10916 | } |
| 10917 | |
| 10918 | if (is_tesc_shader() && has_decoration(id_lhs, DecorationBuiltIn)) |
| 10919 | { |
| 10920 | auto builtin = BuiltIn(get_decoration(id_lhs, DecorationBuiltIn)); |
| 10921 | // Need to manually unroll the array store. |
| 10922 | if (builtin == BuiltInTessLevelInner || builtin == BuiltInTessLevelOuter) |
| 10923 | { |
| 10924 | uint32_t array_size = get_physical_tess_level_array_size(builtin); |
| 10925 | if (array_size == 1) |
| 10926 | statement(to_expression(id_lhs), " = half(", to_expression(id_rhs), "[0]);"); |
| 10927 | else |
| 10928 | { |
| 10929 | for (uint32_t i = 0; i < array_size; i++) |
| 10930 | statement(to_expression(id_lhs), "[", i, "] = half(", to_expression(id_rhs), "[", i, "]);"); |
| 10931 | } |
| 10932 | return true; |
| 10933 | } |
| 10934 | } |
| 10935 | |
| 10936 | auto lhs_storage = get_expression_effective_storage_class(id_lhs); |
| 10937 | auto rhs_storage = get_expression_effective_storage_class(id_rhs); |
| 10938 | if (!emit_array_copy(nullptr, id_lhs, id_rhs, lhs_storage, rhs_storage)) |
| 10939 | return false; |
| 10940 | |
| 10941 | register_write(id_lhs); |
| 10942 | |
| 10943 | return true; |
| 10944 | } |
| 10945 | |
| 10946 | // Emits one of the atomic functions. In MSL, the atomic functions operate on pointers |
| 10947 | void CompilerMSL::emit_atomic_func_op(uint32_t result_type, uint32_t result_id, const char *op, Op opcode, |
| 10948 | uint32_t mem_order_1, uint32_t mem_order_2, bool has_mem_order_2, uint32_t obj, uint32_t op1, |
| 10949 | bool op1_is_pointer, bool op1_is_literal, uint32_t op2) |
| 10950 | { |
| 10951 | string exp; |
| 10952 | |
| 10953 | auto &ptr_type = expression_type(obj); |
| 10954 | auto &type = get_pointee_type(ptr_type); |
| 10955 | auto expected_type = type.basetype; |
| 10956 | if (opcode == OpAtomicUMax || opcode == OpAtomicUMin) |
| 10957 | expected_type = to_unsigned_basetype(type.width); |
| 10958 | else if (opcode == OpAtomicSMax || opcode == OpAtomicSMin) |
| 10959 | expected_type = to_signed_basetype(type.width); |
| 10960 | |
| 10961 | bool use_native_image_atomic; |
| 10962 | if (msl_options.supports_msl_version(3, 1)) |
| 10963 | use_native_image_atomic = check_atomic_image(obj); |
| 10964 | else |
| 10965 | use_native_image_atomic = false; |
| 10966 | |
| 10967 | if (type.width == 64) |
| 10968 | SPIRV_CROSS_THROW("MSL currently does not support 64-bit atomics."); |
| 10969 | |
| 10970 | auto remapped_type = type; |
| 10971 | remapped_type.basetype = expected_type; |
| 10972 | |
| 10973 | auto *var = maybe_get_backing_variable(obj); |
| 10974 | const auto *res_type = var ? &get<SPIRType>(var->basetype) : nullptr; |
| 10975 | assert(type.storage != StorageClassImage || res_type); |
| 10976 | |
| 10977 | bool is_atomic_compare_exchange_strong = op1_is_pointer && op1; |
| 10978 | |
| 10979 | bool check_discard = opcode != OpAtomicLoad && needs_frag_discard_checks() && |
| 10980 | ptr_type.storage != StorageClassWorkgroup; |
| 10981 | |
| 10982 | // Even compare exchange atomics are vec4 on metal for ... reasons :v |
| 10983 | uint32_t vec4_temporary_id = 0; |
| 10984 | if (use_native_image_atomic && is_atomic_compare_exchange_strong) |
| 10985 | { |
| 10986 | uint32_t &tmp_id = extra_sub_expressions[result_id]; |
| 10987 | if (!tmp_id) |
| 10988 | { |
| 10989 | tmp_id = ir.increase_bound_by(2); |
| 10990 | |
| 10991 | auto vec4_type = get<SPIRType>(result_type); |
| 10992 | vec4_type.vecsize = 4; |
| 10993 | set<SPIRType>(tmp_id + 1, vec4_type); |
| 10994 | } |
| 10995 | |
| 10996 | vec4_temporary_id = tmp_id; |
| 10997 | } |
| 10998 | |
| 10999 | if (check_discard) |
| 11000 | { |
| 11001 | if (is_atomic_compare_exchange_strong) |
| 11002 | { |
| 11003 | // We're already emitting a CAS loop here; a conditional won't hurt. |
| 11004 | emit_uninitialized_temporary_expression(result_type, result_id); |
| 11005 | if (vec4_temporary_id) |
| 11006 | emit_uninitialized_temporary_expression(vec4_temporary_id + 1, vec4_temporary_id); |
| 11007 | statement("if (!", builtin_to_glsl(BuiltInHelperInvocation, StorageClassInput), ")"); |
| 11008 | begin_scope(); |
| 11009 | } |
| 11010 | else |
| 11011 | exp = join("(!", builtin_to_glsl(BuiltInHelperInvocation, StorageClassInput), " ? "); |
| 11012 | } |
| 11013 | |
| 11014 | if (use_native_image_atomic) |
| 11015 | { |
| 11016 | auto obj_expression = to_expression(obj); |
| 11017 | auto split_index = obj_expression.find_first_of('@'); |
| 11018 | bool needs_reinterpret = opcode == OpAtomicUMax || opcode == OpAtomicUMin || opcode == OpAtomicSMax || opcode == OpAtomicSMin; |
| 11019 | needs_reinterpret &= type.basetype != expected_type; |
| 11020 | SPIRVariable *backing_var = nullptr; |
| 11021 | |
| 11022 | // Try to avoid waiting until not force recompile later mode to enable force recompile later |
| 11023 | if (needs_reinterpret && (backing_var = maybe_get_backing_variable(obj))) |
| 11024 | add_spv_func_and_recompile(SPVFuncImplTextureCast); |
| 11025 | |
| 11026 | // Will only be false if we're in "force recompile later" mode. |
| 11027 | if (split_index != string::npos) |
| 11028 | { |
| 11029 | auto coord = obj_expression.substr(split_index + 1); |
| 11030 | auto image_expr = obj_expression.substr(0, split_index); |
| 11031 | |
| 11032 | // Handle problem cases with sign where we need signed min/max on a uint image for example. |
| 11033 | // It seems to work to cast the texture type itself, even if it is probably wildly outside of spec, |
| 11034 | // but SPIR-V requires this to work. |
| 11035 | if (needs_reinterpret && backing_var) |
| 11036 | { |
| 11037 | assert(spv_function_implementations.count(SPVFuncImplTextureCast) && "Should have been added above"); |
| 11038 | |
| 11039 | const auto *backing_type = &get<SPIRType>(backing_var->basetype); |
| 11040 | while (backing_type->op != OpTypeImage) |
| 11041 | backing_type = &get<SPIRType>(backing_type->parent_type); |
| 11042 | |
| 11043 | auto img_type = *backing_type; |
| 11044 | auto tmp_type = type; |
| 11045 | tmp_type.basetype = expected_type; |
| 11046 | img_type.image.type = ir.increase_bound_by(1); |
| 11047 | set<SPIRType>(img_type.image.type, tmp_type); |
| 11048 | |
| 11049 | image_expr = join("spvTextureCast<", type_to_glsl(img_type, obj), ">(", image_expr, ")"); |
| 11050 | } |
| 11051 | |
| 11052 | exp += join(image_expr, ".", op, "("); |
| 11053 | if (ptr_type.storage == StorageClassImage && res_type->image.arrayed) |
| 11054 | { |
| 11055 | switch (res_type->image.dim) |
| 11056 | { |
| 11057 | case Dim1D: |
| 11058 | if (msl_options.texture_1D_as_2D) |
| 11059 | exp += join("uint2(", coord, ".x, 0), ", coord, ".y"); |
| 11060 | else |
| 11061 | exp += join(coord, ".x, ", coord, ".y"); |
| 11062 | |
| 11063 | break; |
| 11064 | case Dim2D: |
| 11065 | exp += join(coord, ".xy, ", coord, ".z"); |
| 11066 | break; |
| 11067 | default: |
| 11068 | SPIRV_CROSS_THROW("Cannot do atomics on Cube textures."); |
| 11069 | } |
| 11070 | } |
| 11071 | else if (ptr_type.storage == StorageClassImage && res_type->image.dim == Dim1D && msl_options.texture_1D_as_2D) |
| 11072 | exp += join("uint2(", coord, ", 0)"); |
| 11073 | else |
| 11074 | exp += coord; |
| 11075 | } |
| 11076 | else |
| 11077 | { |
| 11078 | exp += obj_expression; |
| 11079 | } |
| 11080 | } |
| 11081 | else |
| 11082 | { |
| 11083 | exp += string(op) + "_explicit("; |
| 11084 | exp += "("; |
| 11085 | // Emulate texture2D atomic operations |
| 11086 | if (ptr_type.storage == StorageClassImage) |
| 11087 | { |
| 11088 | auto &flags = ir.get_decoration_bitset(var->self); |
| 11089 | if (decoration_flags_signal_volatile(flags)) |
| 11090 | exp += "volatile "; |
| 11091 | exp += "device"; |
| 11092 | } |
| 11093 | else if (var && ptr_type.storage != StorageClassPhysicalStorageBuffer) |
| 11094 | { |
| 11095 | exp += get_argument_address_space(*var); |
| 11096 | } |
| 11097 | else |
| 11098 | { |
| 11099 | // Fallback scenario, could happen for raw pointers. |
| 11100 | exp += ptr_type.storage == StorageClassWorkgroup ? "threadgroup" : "device"; |
| 11101 | } |
| 11102 | |
| 11103 | exp += " atomic_"; |
| 11104 | // For signed and unsigned min/max, we can signal this through the pointer type. |
| 11105 | // There is no other way, since C++ does not have explicit signage for atomics. |
| 11106 | exp += type_to_glsl(remapped_type); |
| 11107 | exp += "*)"; |
| 11108 | |
| 11109 | exp += "&"; |
| 11110 | exp += to_enclosed_expression(obj); |
| 11111 | } |
| 11112 | |
| 11113 | if (is_atomic_compare_exchange_strong) |
| 11114 | { |
| 11115 | assert(strcmp(op, "atomic_compare_exchange_weak") == 0); |
| 11116 | assert(op2); |
| 11117 | assert(has_mem_order_2); |
| 11118 | exp += ", &"; |
| 11119 | exp += to_name(vec4_temporary_id ? vec4_temporary_id : result_id); |
| 11120 | exp += ", "; |
| 11121 | exp += to_expression(op2); |
| 11122 | |
| 11123 | if (!use_native_image_atomic) |
| 11124 | { |
| 11125 | exp += ", "; |
| 11126 | exp += get_memory_order(mem_order_1); |
| 11127 | exp += ", "; |
| 11128 | exp += get_memory_order(mem_order_2); |
| 11129 | } |
| 11130 | exp += ")"; |
| 11131 | |
| 11132 | // MSL only supports the weak atomic compare exchange, so emit a CAS loop here. |
| 11133 | // The MSL function returns false if the atomic write fails OR the comparison test fails, |
| 11134 | // so we must validate that it wasn't the comparison test that failed before continuing |
| 11135 | // the CAS loop, otherwise it will loop infinitely, with the comparison test always failing. |
| 11136 | // The function updates the comparator value from the memory value, so the additional |
| 11137 | // comparison test evaluates the memory value against the expected value. |
| 11138 | if (!check_discard) |
| 11139 | { |
| 11140 | emit_uninitialized_temporary_expression(result_type, result_id); |
| 11141 | if (vec4_temporary_id) |
| 11142 | emit_uninitialized_temporary_expression(vec4_temporary_id + 1, vec4_temporary_id); |
| 11143 | } |
| 11144 | |
| 11145 | statement("do"); |
| 11146 | begin_scope(); |
| 11147 | |
| 11148 | string scalar_expression; |
| 11149 | if (vec4_temporary_id) |
| 11150 | scalar_expression = join(to_expression(vec4_temporary_id), ".x"); |
| 11151 | else |
| 11152 | scalar_expression = to_expression(result_id); |
| 11153 | |
| 11154 | statement(scalar_expression, " = ", to_expression(op1), ";"); |
| 11155 | end_scope_decl(join("while (!", exp, " && ", scalar_expression, " == ", to_enclosed_expression(op1), ")")); |
| 11156 | if (vec4_temporary_id) |
| 11157 | statement(to_expression(result_id), " = ", scalar_expression, ";"); |
| 11158 | |
| 11159 | // Vulkan: (section 9.29: ... and values returned by atomic instructions in helper invocations are undefined) |
| 11160 | if (check_discard) |
| 11161 | { |
| 11162 | end_scope(); |
| 11163 | statement("else"); |
| 11164 | begin_scope(); |
| 11165 | statement(to_expression(result_id), " = {};"); |
| 11166 | end_scope(); |
| 11167 | } |
| 11168 | } |
| 11169 | else |
| 11170 | { |
| 11171 | assert(strcmp(op, "atomic_compare_exchange_weak") != 0); |
| 11172 | |
| 11173 | if (op1) |
| 11174 | { |
| 11175 | exp += ", "; |
| 11176 | if (op1_is_literal) |
| 11177 | exp += to_string(op1); |
| 11178 | else |
| 11179 | exp += bitcast_expression(expected_type, op1); |
| 11180 | } |
| 11181 | |
| 11182 | if (op2) |
| 11183 | exp += ", " + to_expression(op2); |
| 11184 | |
| 11185 | if (!use_native_image_atomic) |
| 11186 | { |
| 11187 | exp += string(", ") + get_memory_order(mem_order_1); |
| 11188 | if (has_mem_order_2) |
| 11189 | exp += string(", ") + get_memory_order(mem_order_2); |
| 11190 | } |
| 11191 | |
| 11192 | exp += ")"; |
| 11193 | |
| 11194 | // For some particular reason, atomics return vec4 in Metal ... |
| 11195 | if (use_native_image_atomic) |
| 11196 | exp += ".x"; |
| 11197 | |
| 11198 | // Vulkan: (section 9.29: ... and values returned by atomic instructions in helper invocations are undefined) |
| 11199 | if (check_discard) |
| 11200 | { |
| 11201 | exp += " : "; |
| 11202 | if (strcmp(op, "atomic_store") != 0) |
| 11203 | exp += join(type_to_glsl(get<SPIRType>(result_type)), "{}"); |
| 11204 | else |
| 11205 | exp += "((void)0)"; |
| 11206 | exp += ")"; |
| 11207 | } |
| 11208 | |
| 11209 | if (expected_type != type.basetype) |
| 11210 | exp = bitcast_expression(type, expected_type, exp); |
| 11211 | |
| 11212 | if (strcmp(op, "atomic_store") != 0) |
| 11213 | emit_op(result_type, result_id, exp, false); |
| 11214 | else |
| 11215 | statement(exp, ";"); |
| 11216 | } |
| 11217 | |
| 11218 | flush_all_atomic_capable_variables(); |
| 11219 | } |
| 11220 | |
| 11221 | // Metal only supports relaxed memory order for now |
| 11222 | const char *CompilerMSL::get_memory_order(uint32_t) |
| 11223 | { |
| 11224 | return "memory_order_relaxed"; |
| 11225 | } |
| 11226 | |
| 11227 | // Override for MSL-specific extension syntax instructions. |
| 11228 | // In some cases, deliberately select either the fast or precise versions of the MSL functions to match Vulkan math precision results. |
| 11229 | void CompilerMSL::emit_glsl_op(uint32_t result_type, uint32_t id, uint32_t eop, const uint32_t *args, uint32_t count) |
| 11230 | { |
| 11231 | auto op = static_cast<GLSLstd450>(eop); |
| 11232 | |
| 11233 | // If we need to do implicit bitcasts, make sure we do it with the correct type. |
| 11234 | uint32_t integer_width = get_integer_width_for_glsl_instruction(op, args, count); |
| 11235 | auto int_type = to_signed_basetype(integer_width); |
| 11236 | auto uint_type = to_unsigned_basetype(integer_width); |
| 11237 | |
| 11238 | op = get_remapped_glsl_op(op); |
| 11239 | |
| 11240 | auto &restype = get<SPIRType>(result_type); |
| 11241 | |
| 11242 | switch (op) |
| 11243 | { |
| 11244 | case GLSLstd450Sinh: |
| 11245 | if (restype.basetype == SPIRType::Half) |
| 11246 | { |
| 11247 | // MSL does not have overload for half. Force-cast back to half. |
| 11248 | auto expr = join("half(fast::sinh(", to_unpacked_expression(args[0]), "))"); |
| 11249 | emit_op(result_type, id, expr, should_forward(args[0])); |
| 11250 | inherit_expression_dependencies(id, args[0]); |
| 11251 | } |
| 11252 | else |
| 11253 | emit_unary_func_op(result_type, id, args[0], "fast::sinh"); |
| 11254 | break; |
| 11255 | case GLSLstd450Cosh: |
| 11256 | if (restype.basetype == SPIRType::Half) |
| 11257 | { |
| 11258 | // MSL does not have overload for half. Force-cast back to half. |
| 11259 | auto expr = join("half(fast::cosh(", to_unpacked_expression(args[0]), "))"); |
| 11260 | emit_op(result_type, id, expr, should_forward(args[0])); |
| 11261 | inherit_expression_dependencies(id, args[0]); |
| 11262 | } |
| 11263 | else |
| 11264 | emit_unary_func_op(result_type, id, args[0], "fast::cosh"); |
| 11265 | break; |
| 11266 | case GLSLstd450Tanh: |
| 11267 | if (restype.basetype == SPIRType::Half) |
| 11268 | { |
| 11269 | // MSL does not have overload for half. Force-cast back to half. |
| 11270 | auto expr = join("half(fast::tanh(", to_unpacked_expression(args[0]), "))"); |
| 11271 | emit_op(result_type, id, expr, should_forward(args[0])); |
| 11272 | inherit_expression_dependencies(id, args[0]); |
| 11273 | } |
| 11274 | else |
| 11275 | emit_unary_func_op(result_type, id, args[0], "precise::tanh"); |
| 11276 | break; |
| 11277 | case GLSLstd450Atan2: |
| 11278 | if (restype.basetype == SPIRType::Half) |
| 11279 | { |
| 11280 | // MSL does not have overload for half. Force-cast back to half. |
| 11281 | auto expr = join("half(fast::atan2(", to_unpacked_expression(args[0]), ", ", to_unpacked_expression(args[1]), "))"); |
| 11282 | emit_op(result_type, id, expr, should_forward(args[0]) && should_forward(args[1])); |
| 11283 | inherit_expression_dependencies(id, args[0]); |
| 11284 | inherit_expression_dependencies(id, args[1]); |
| 11285 | } |
| 11286 | else |
| 11287 | emit_binary_func_op(result_type, id, args[0], args[1], "precise::atan2"); |
| 11288 | break; |
| 11289 | case GLSLstd450InverseSqrt: |
| 11290 | emit_unary_func_op(result_type, id, args[0], "rsqrt"); |
| 11291 | break; |
| 11292 | case GLSLstd450RoundEven: |
| 11293 | emit_unary_func_op(result_type, id, args[0], "rint"); |
| 11294 | break; |
| 11295 | |
| 11296 | case GLSLstd450FindILsb: |
| 11297 | { |
| 11298 | // In this template version of findLSB, we return T. |
| 11299 | auto basetype = expression_type(args[0]).basetype; |
| 11300 | emit_unary_func_op_cast(result_type, id, args[0], "spvFindLSB", basetype, basetype); |
| 11301 | break; |
| 11302 | } |
| 11303 | |
| 11304 | case GLSLstd450FindSMsb: |
| 11305 | emit_unary_func_op_cast(result_type, id, args[0], "spvFindSMSB", int_type, int_type); |
| 11306 | break; |
| 11307 | |
| 11308 | case GLSLstd450FindUMsb: |
| 11309 | emit_unary_func_op_cast(result_type, id, args[0], "spvFindUMSB", uint_type, uint_type); |
| 11310 | break; |
| 11311 | |
| 11312 | case GLSLstd450PackSnorm4x8: |
| 11313 | emit_unary_func_op(result_type, id, args[0], "pack_float_to_snorm4x8"); |
| 11314 | break; |
| 11315 | case GLSLstd450PackUnorm4x8: |
| 11316 | emit_unary_func_op(result_type, id, args[0], "pack_float_to_unorm4x8"); |
| 11317 | break; |
| 11318 | case GLSLstd450PackSnorm2x16: |
| 11319 | emit_unary_func_op(result_type, id, args[0], "pack_float_to_snorm2x16"); |
| 11320 | break; |
| 11321 | case GLSLstd450PackUnorm2x16: |
| 11322 | emit_unary_func_op(result_type, id, args[0], "pack_float_to_unorm2x16"); |
| 11323 | break; |
| 11324 | |
| 11325 | case GLSLstd450PackHalf2x16: |
| 11326 | { |
| 11327 | auto expr = join("as_type<uint>(half2(", to_expression(args[0]), "))"); |
| 11328 | emit_op(result_type, id, expr, should_forward(args[0])); |
| 11329 | inherit_expression_dependencies(id, args[0]); |
| 11330 | break; |
| 11331 | } |
| 11332 | |
| 11333 | case GLSLstd450UnpackSnorm4x8: |
| 11334 | emit_unary_func_op(result_type, id, args[0], "unpack_snorm4x8_to_float"); |
| 11335 | break; |
| 11336 | case GLSLstd450UnpackUnorm4x8: |
| 11337 | emit_unary_func_op(result_type, id, args[0], "unpack_unorm4x8_to_float"); |
| 11338 | break; |
| 11339 | case GLSLstd450UnpackSnorm2x16: |
| 11340 | emit_unary_func_op(result_type, id, args[0], "unpack_snorm2x16_to_float"); |
| 11341 | break; |
| 11342 | case GLSLstd450UnpackUnorm2x16: |
| 11343 | emit_unary_func_op(result_type, id, args[0], "unpack_unorm2x16_to_float"); |
| 11344 | break; |
| 11345 | |
| 11346 | case GLSLstd450UnpackHalf2x16: |
| 11347 | { |
| 11348 | auto expr = join("float2(as_type<half2>(", to_expression(args[0]), "))"); |
| 11349 | emit_op(result_type, id, expr, should_forward(args[0])); |
| 11350 | inherit_expression_dependencies(id, args[0]); |
| 11351 | break; |
| 11352 | } |
| 11353 | |
| 11354 | case GLSLstd450PackDouble2x32: |
| 11355 | emit_unary_func_op(result_type, id, args[0], "unsupported_GLSLstd450PackDouble2x32"); // Currently unsupported |
| 11356 | break; |
| 11357 | case GLSLstd450UnpackDouble2x32: |
| 11358 | emit_unary_func_op(result_type, id, args[0], "unsupported_GLSLstd450UnpackDouble2x32"); // Currently unsupported |
| 11359 | break; |
| 11360 | |
| 11361 | case GLSLstd450MatrixInverse: |
| 11362 | { |
| 11363 | auto &mat_type = get<SPIRType>(result_type); |
| 11364 | switch (mat_type.columns) |
| 11365 | { |
| 11366 | case 2: |
| 11367 | emit_unary_func_op(result_type, id, args[0], "spvInverse2x2"); |
| 11368 | break; |
| 11369 | case 3: |
| 11370 | emit_unary_func_op(result_type, id, args[0], "spvInverse3x3"); |
| 11371 | break; |
| 11372 | case 4: |
| 11373 | emit_unary_func_op(result_type, id, args[0], "spvInverse4x4"); |
| 11374 | break; |
| 11375 | default: |
| 11376 | break; |
| 11377 | } |
| 11378 | break; |
| 11379 | } |
| 11380 | |
| 11381 | case GLSLstd450FMin: |
| 11382 | // If the result type isn't float, don't bother calling the specific |
| 11383 | // precise::/fast:: version. Metal doesn't have those for half and |
| 11384 | // double types. |
| 11385 | if (get<SPIRType>(result_type).basetype != SPIRType::Float) |
| 11386 | emit_binary_func_op(result_type, id, args[0], args[1], "min"); |
| 11387 | else |
| 11388 | emit_binary_func_op(result_type, id, args[0], args[1], "fast::min"); |
| 11389 | break; |
| 11390 | |
| 11391 | case GLSLstd450FMax: |
| 11392 | if (get<SPIRType>(result_type).basetype != SPIRType::Float) |
| 11393 | emit_binary_func_op(result_type, id, args[0], args[1], "max"); |
| 11394 | else |
| 11395 | emit_binary_func_op(result_type, id, args[0], args[1], "fast::max"); |
| 11396 | break; |
| 11397 | |
| 11398 | case GLSLstd450FClamp: |
| 11399 | // TODO: If args[1] is 0 and args[2] is 1, emit a saturate() call. |
| 11400 | if (get<SPIRType>(result_type).basetype != SPIRType::Float) |
| 11401 | emit_trinary_func_op(result_type, id, args[0], args[1], args[2], "clamp"); |
| 11402 | else |
| 11403 | emit_trinary_func_op(result_type, id, args[0], args[1], args[2], "fast::clamp"); |
| 11404 | break; |
| 11405 | |
| 11406 | case GLSLstd450NMin: |
| 11407 | if (get<SPIRType>(result_type).basetype != SPIRType::Float) |
| 11408 | emit_binary_func_op(result_type, id, args[0], args[1], "min"); |
| 11409 | else |
| 11410 | emit_binary_func_op(result_type, id, args[0], args[1], "precise::min"); |
| 11411 | break; |
| 11412 | |
| 11413 | case GLSLstd450NMax: |
| 11414 | if (get<SPIRType>(result_type).basetype != SPIRType::Float) |
| 11415 | emit_binary_func_op(result_type, id, args[0], args[1], "max"); |
| 11416 | else |
| 11417 | emit_binary_func_op(result_type, id, args[0], args[1], "precise::max"); |
| 11418 | break; |
| 11419 | |
| 11420 | case GLSLstd450NClamp: |
| 11421 | // TODO: If args[1] is 0 and args[2] is 1, emit a saturate() call. |
| 11422 | if (get<SPIRType>(result_type).basetype != SPIRType::Float) |
| 11423 | emit_trinary_func_op(result_type, id, args[0], args[1], args[2], "clamp"); |
| 11424 | else |
| 11425 | emit_trinary_func_op(result_type, id, args[0], args[1], args[2], "precise::clamp"); |
| 11426 | break; |
| 11427 | |
| 11428 | case GLSLstd450InterpolateAtCentroid: |
| 11429 | { |
| 11430 | // We can't just emit the expression normally, because the qualified name contains a call to the default |
| 11431 | // interpolate method, or refers to a local variable. We saved the interface index we need; use it to construct |
| 11432 | // the base for the method call. |
| 11433 | uint32_t interface_index = get_extended_decoration(args[0], SPIRVCrossDecorationInterfaceMemberIndex); |
| 11434 | string component; |
| 11435 | if (has_extended_decoration(args[0], SPIRVCrossDecorationInterpolantComponentExpr)) |
| 11436 | { |
| 11437 | uint32_t index_expr = get_extended_decoration(args[0], SPIRVCrossDecorationInterpolantComponentExpr); |
| 11438 | auto *c = maybe_get<SPIRConstant>(index_expr); |
| 11439 | if (!c || c->specialization) |
| 11440 | component = join("[", to_expression(index_expr), "]"); |
| 11441 | else |
| 11442 | component = join(".", index_to_swizzle(c->scalar())); |
| 11443 | } |
| 11444 | emit_op(result_type, id, |
| 11445 | join(to_name(stage_in_var_id), ".", to_member_name(get_stage_in_struct_type(), interface_index), |
| 11446 | ".interpolate_at_centroid()", component), |
| 11447 | should_forward(args[0])); |
| 11448 | break; |
| 11449 | } |
| 11450 | |
| 11451 | case GLSLstd450InterpolateAtSample: |
| 11452 | { |
| 11453 | uint32_t interface_index = get_extended_decoration(args[0], SPIRVCrossDecorationInterfaceMemberIndex); |
| 11454 | string component; |
| 11455 | if (has_extended_decoration(args[0], SPIRVCrossDecorationInterpolantComponentExpr)) |
| 11456 | { |
| 11457 | uint32_t index_expr = get_extended_decoration(args[0], SPIRVCrossDecorationInterpolantComponentExpr); |
| 11458 | auto *c = maybe_get<SPIRConstant>(index_expr); |
| 11459 | if (!c || c->specialization) |
| 11460 | component = join("[", to_expression(index_expr), "]"); |
| 11461 | else |
| 11462 | component = join(".", index_to_swizzle(c->scalar())); |
| 11463 | } |
| 11464 | emit_op(result_type, id, |
| 11465 | join(to_name(stage_in_var_id), ".", to_member_name(get_stage_in_struct_type(), interface_index), |
| 11466 | ".interpolate_at_sample(", to_expression(args[1]), ")", component), |
| 11467 | should_forward(args[0]) && should_forward(args[1])); |
| 11468 | break; |
| 11469 | } |
| 11470 | |
| 11471 | case GLSLstd450InterpolateAtOffset: |
| 11472 | { |
| 11473 | uint32_t interface_index = get_extended_decoration(args[0], SPIRVCrossDecorationInterfaceMemberIndex); |
| 11474 | string component; |
| 11475 | if (has_extended_decoration(args[0], SPIRVCrossDecorationInterpolantComponentExpr)) |
| 11476 | { |
| 11477 | uint32_t index_expr = get_extended_decoration(args[0], SPIRVCrossDecorationInterpolantComponentExpr); |
| 11478 | auto *c = maybe_get<SPIRConstant>(index_expr); |
| 11479 | if (!c || c->specialization) |
| 11480 | component = join("[", to_expression(index_expr), "]"); |
| 11481 | else |
| 11482 | component = join(".", index_to_swizzle(c->scalar())); |
| 11483 | } |
| 11484 | // Like Direct3D, Metal puts the (0, 0) at the upper-left corner, not the center as SPIR-V and GLSL do. |
| 11485 | // Offset the offset by (1/2 - 1/16), or 0.4375, to compensate for this. |
| 11486 | // It has to be (1/2 - 1/16) and not 1/2, or several CTS tests subtly break on Intel. |
| 11487 | emit_op(result_type, id, |
| 11488 | join(to_name(stage_in_var_id), ".", to_member_name(get_stage_in_struct_type(), interface_index), |
| 11489 | ".interpolate_at_offset(", to_expression(args[1]), " + 0.4375)", component), |
| 11490 | should_forward(args[0]) && should_forward(args[1])); |
| 11491 | break; |
| 11492 | } |
| 11493 | |
| 11494 | case GLSLstd450Distance: |
| 11495 | // MSL does not support scalar versions here. |
| 11496 | if (expression_type(args[0]).vecsize == 1) |
| 11497 | { |
| 11498 | // Equivalent to length(a - b) -> abs(a - b). |
| 11499 | emit_op(result_type, id, |
| 11500 | join("abs(", to_enclosed_unpacked_expression(args[0]), " - ", |
| 11501 | to_enclosed_unpacked_expression(args[1]), ")"), |
| 11502 | should_forward(args[0]) && should_forward(args[1])); |
| 11503 | inherit_expression_dependencies(id, args[0]); |
| 11504 | inherit_expression_dependencies(id, args[1]); |
| 11505 | } |
| 11506 | else |
| 11507 | CompilerGLSL::emit_glsl_op(result_type, id, eop, args, count); |
| 11508 | break; |
| 11509 | |
| 11510 | case GLSLstd450Length: |
| 11511 | // MSL does not support scalar versions, so use abs(). |
| 11512 | if (expression_type(args[0]).vecsize == 1) |
| 11513 | emit_unary_func_op(result_type, id, args[0], "abs"); |
| 11514 | else |
| 11515 | CompilerGLSL::emit_glsl_op(result_type, id, eop, args, count); |
| 11516 | break; |
| 11517 | |
| 11518 | case GLSLstd450Normalize: |
| 11519 | { |
| 11520 | auto &exp_type = expression_type(args[0]); |
| 11521 | // MSL does not support scalar versions here. |
| 11522 | // MSL has no implementation for normalize in the fast:: namespace for half2 and half3 |
| 11523 | // Returns -1 or 1 for valid input, sign() does the job. |
| 11524 | if (exp_type.vecsize == 1) |
| 11525 | emit_unary_func_op(result_type, id, args[0], "sign"); |
| 11526 | else if (exp_type.vecsize <= 3 && exp_type.basetype == SPIRType::Half) |
| 11527 | emit_unary_func_op(result_type, id, args[0], "normalize"); |
| 11528 | else |
| 11529 | emit_unary_func_op(result_type, id, args[0], "fast::normalize"); |
| 11530 | break; |
| 11531 | } |
| 11532 | case GLSLstd450Reflect: |
| 11533 | if (get<SPIRType>(result_type).vecsize == 1) |
| 11534 | emit_binary_func_op(result_type, id, args[0], args[1], "spvReflect"); |
| 11535 | else |
| 11536 | CompilerGLSL::emit_glsl_op(result_type, id, eop, args, count); |
| 11537 | break; |
| 11538 | |
| 11539 | case GLSLstd450Refract: |
| 11540 | if (get<SPIRType>(result_type).vecsize == 1) |
| 11541 | emit_trinary_func_op(result_type, id, args[0], args[1], args[2], "spvRefract"); |
| 11542 | else |
| 11543 | CompilerGLSL::emit_glsl_op(result_type, id, eop, args, count); |
| 11544 | break; |
| 11545 | |
| 11546 | case GLSLstd450FaceForward: |
| 11547 | if (get<SPIRType>(result_type).vecsize == 1) |
| 11548 | emit_trinary_func_op(result_type, id, args[0], args[1], args[2], "spvFaceForward"); |
| 11549 | else |
| 11550 | CompilerGLSL::emit_glsl_op(result_type, id, eop, args, count); |
| 11551 | break; |
| 11552 | |
| 11553 | case GLSLstd450Modf: |
| 11554 | case GLSLstd450Frexp: |
| 11555 | { |
| 11556 | // Special case. If the variable is a scalar access chain, we cannot use it directly. We have to emit a temporary. |
| 11557 | // Another special case is if the variable is in a storage class which is not thread. |
| 11558 | auto *ptr = maybe_get<SPIRExpression>(args[1]); |
| 11559 | auto &type = expression_type(args[1]); |
| 11560 | |
| 11561 | bool is_thread_storage = storage_class_array_is_thread(type.storage); |
| 11562 | if (type.storage == StorageClassOutput && capture_output_to_buffer) |
| 11563 | is_thread_storage = false; |
| 11564 | |
| 11565 | if (!is_thread_storage || |
| 11566 | (ptr && ptr->access_chain && is_scalar(expression_type(args[1])))) |
| 11567 | { |
| 11568 | register_call_out_argument(args[1]); |
| 11569 | forced_temporaries.insert(id); |
| 11570 | |
| 11571 | // Need to create temporaries and copy over to access chain after. |
| 11572 | // We cannot directly take the reference of a vector swizzle in MSL, even if it's scalar ... |
| 11573 | uint32_t &tmp_id = extra_sub_expressions[id]; |
| 11574 | if (!tmp_id) |
| 11575 | tmp_id = ir.increase_bound_by(1); |
| 11576 | |
| 11577 | uint32_t tmp_type_id = get_pointee_type_id(expression_type_id(args[1])); |
| 11578 | emit_uninitialized_temporary_expression(tmp_type_id, tmp_id); |
| 11579 | emit_binary_func_op(result_type, id, args[0], tmp_id, eop == GLSLstd450Modf ? "modf" : "frexp"); |
| 11580 | statement(to_expression(args[1]), " = ", to_expression(tmp_id), ";"); |
| 11581 | } |
| 11582 | else |
| 11583 | CompilerGLSL::emit_glsl_op(result_type, id, eop, args, count); |
| 11584 | break; |
| 11585 | } |
| 11586 | |
| 11587 | case GLSLstd450Pow: |
| 11588 | // powr makes x < 0.0 undefined, just like SPIR-V. |
| 11589 | emit_binary_func_op(result_type, id, args[0], args[1], "powr"); |
| 11590 | break; |
| 11591 | |
| 11592 | default: |
| 11593 | CompilerGLSL::emit_glsl_op(result_type, id, eop, args, count); |
| 11594 | break; |
| 11595 | } |
| 11596 | } |
| 11597 | |
| 11598 | void CompilerMSL::emit_spv_amd_shader_trinary_minmax_op(uint32_t result_type, uint32_t id, uint32_t eop, |
| 11599 | const uint32_t *args, uint32_t count) |
| 11600 | { |
| 11601 | enum AMDShaderTrinaryMinMax |
| 11602 | { |
| 11603 | FMin3AMD = 1, |
| 11604 | UMin3AMD = 2, |
| 11605 | SMin3AMD = 3, |
| 11606 | FMax3AMD = 4, |
| 11607 | UMax3AMD = 5, |
| 11608 | SMax3AMD = 6, |
| 11609 | FMid3AMD = 7, |
| 11610 | UMid3AMD = 8, |
| 11611 | SMid3AMD = 9 |
| 11612 | }; |
| 11613 | |
| 11614 | if (!msl_options.supports_msl_version(2, 1)) |
| 11615 | SPIRV_CROSS_THROW("Trinary min/max functions require MSL 2.1."); |
| 11616 | |
| 11617 | auto op = static_cast<AMDShaderTrinaryMinMax>(eop); |
| 11618 | |
| 11619 | switch (op) |
| 11620 | { |
| 11621 | case FMid3AMD: |
| 11622 | case UMid3AMD: |
| 11623 | case SMid3AMD: |
| 11624 | emit_trinary_func_op(result_type, id, args[0], args[1], args[2], "median3"); |
| 11625 | break; |
| 11626 | default: |
| 11627 | CompilerGLSL::emit_spv_amd_shader_trinary_minmax_op(result_type, id, eop, args, count); |
| 11628 | break; |
| 11629 | } |
| 11630 | } |
| 11631 | |
| 11632 | // Emit a structure declaration for the specified interface variable. |
| 11633 | void CompilerMSL::emit_interface_block(uint32_t ib_var_id) |
| 11634 | { |
| 11635 | if (ib_var_id) |
| 11636 | { |
| 11637 | auto &ib_var = get<SPIRVariable>(ib_var_id); |
| 11638 | auto &ib_type = get_variable_data_type(ib_var); |
| 11639 | //assert(ib_type.basetype == SPIRType::Struct && !ib_type.member_types.empty()); |
| 11640 | assert(ib_type.basetype == SPIRType::Struct); |
| 11641 | emit_struct(ib_type); |
| 11642 | } |
| 11643 | } |
| 11644 | |
| 11645 | // Emits the declaration signature of the specified function. |
| 11646 | // If this is the entry point function, Metal-specific return value and function arguments are added. |
| 11647 | void CompilerMSL::emit_function_prototype(SPIRFunction &func, const Bitset &) |
| 11648 | { |
| 11649 | if (func.self != ir.default_entry_point) |
| 11650 | add_function_overload(func); |
| 11651 | |
| 11652 | local_variable_names = resource_names; |
| 11653 | string decl; |
| 11654 | |
| 11655 | processing_entry_point = func.self == ir.default_entry_point; |
| 11656 | |
| 11657 | // Metal helper functions must be static force-inline otherwise they will cause problems when linked together in a single Metallib. |
| 11658 | if (!processing_entry_point) |
| 11659 | statement(force_inline); |
| 11660 | |
| 11661 | auto &type = get<SPIRType>(func.return_type); |
| 11662 | |
| 11663 | if (!type.array.empty() && msl_options.force_native_arrays) |
| 11664 | { |
| 11665 | // We cannot return native arrays in MSL, so "return" through an out variable. |
| 11666 | decl += "void"; |
| 11667 | } |
| 11668 | else |
| 11669 | { |
| 11670 | decl += func_type_decl(type); |
| 11671 | } |
| 11672 | |
| 11673 | decl += " "; |
| 11674 | decl += to_name(func.self); |
| 11675 | decl += "("; |
| 11676 | |
| 11677 | if (!type.array.empty() && msl_options.force_native_arrays) |
| 11678 | { |
| 11679 | // Fake arrays returns by writing to an out array instead. |
| 11680 | decl += "thread "; |
| 11681 | decl += type_to_glsl(type); |
| 11682 | decl += " (&spvReturnValue)"; |
| 11683 | decl += type_to_array_glsl(type, 0); |
| 11684 | if (!func.arguments.empty()) |
| 11685 | decl += ", "; |
| 11686 | } |
| 11687 | |
| 11688 | if (processing_entry_point) |
| 11689 | { |
| 11690 | if (msl_options.argument_buffers) |
| 11691 | decl += entry_point_args_argument_buffer(!func.arguments.empty()); |
| 11692 | else |
| 11693 | decl += entry_point_args_classic(!func.arguments.empty()); |
| 11694 | |
| 11695 | // append entry point args to avoid conflicts in local variable names. |
| 11696 | local_variable_names.insert(resource_names.begin(), resource_names.end()); |
| 11697 | |
| 11698 | // If entry point function has variables that require early declaration, |
| 11699 | // ensure they each have an empty initializer, creating one if needed. |
| 11700 | // This is done at this late stage because the initialization expression |
| 11701 | // is cleared after each compilation pass. |
| 11702 | for (auto var_id : vars_needing_early_declaration) |
| 11703 | { |
| 11704 | auto &ed_var = get<SPIRVariable>(var_id); |
| 11705 | ID &initializer = ed_var.initializer; |
| 11706 | if (!initializer) |
| 11707 | initializer = ir.increase_bound_by(1); |
| 11708 | |
| 11709 | // Do not override proper initializers. |
| 11710 | if (ir.ids[initializer].get_type() == TypeNone || ir.ids[initializer].get_type() == TypeExpression) |
| 11711 | set<SPIRExpression>(ed_var.initializer, "{}", ed_var.basetype, true); |
| 11712 | } |
| 11713 | |
| 11714 | // add `taskPayloadSharedEXT` variable to entry-point arguments |
| 11715 | for (auto &v : func.local_variables) |
| 11716 | { |
| 11717 | auto &var = get<SPIRVariable>(v); |
| 11718 | if (var.storage != StorageClassTaskPayloadWorkgroupEXT) |
| 11719 | continue; |
| 11720 | |
| 11721 | add_local_variable_name(v); |
| 11722 | SPIRFunction::Parameter arg = {}; |
| 11723 | arg.id = v; |
| 11724 | arg.type = var.basetype; |
| 11725 | arg.alias_global_variable = true; |
| 11726 | decl += join(", ", argument_decl(arg), " [[payload]]"); |
| 11727 | } |
| 11728 | } |
| 11729 | |
| 11730 | for (auto &arg : func.arguments) |
| 11731 | { |
| 11732 | uint32_t name_id = arg.id; |
| 11733 | |
| 11734 | auto *var = maybe_get<SPIRVariable>(arg.id); |
| 11735 | if (var) |
| 11736 | { |
| 11737 | // If we need to modify the name of the variable, make sure we modify the original variable. |
| 11738 | // Our alias is just a shadow variable. |
| 11739 | if (arg.alias_global_variable && var->basevariable) |
| 11740 | name_id = var->basevariable; |
| 11741 | |
| 11742 | var->parameter = &arg; // Hold a pointer to the parameter so we can invalidate the readonly field if needed. |
| 11743 | } |
| 11744 | |
| 11745 | add_local_variable_name(name_id); |
| 11746 | |
| 11747 | decl += argument_decl(arg); |
| 11748 | |
| 11749 | bool is_dynamic_img_sampler = has_extended_decoration(arg.id, SPIRVCrossDecorationDynamicImageSampler); |
| 11750 | |
| 11751 | auto &arg_type = get<SPIRType>(arg.type); |
| 11752 | if (arg_type.basetype == SPIRType::SampledImage && !is_dynamic_img_sampler) |
| 11753 | { |
| 11754 | // Manufacture automatic plane args for multiplanar texture |
| 11755 | uint32_t planes = 1; |
| 11756 | if (auto *constexpr_sampler = find_constexpr_sampler(name_id)) |
| 11757 | if (constexpr_sampler->ycbcr_conversion_enable) |
| 11758 | planes = constexpr_sampler->planes; |
| 11759 | for (uint32_t i = 1; i < planes; i++) |
| 11760 | decl += join(", ", argument_decl(arg), plane_name_suffix, i); |
| 11761 | |
| 11762 | // Manufacture automatic sampler arg for SampledImage texture |
| 11763 | if (arg_type.image.dim != DimBuffer) |
| 11764 | { |
| 11765 | if (arg_type.array.empty() || (var ? is_var_runtime_size_array(*var) : is_runtime_size_array(arg_type))) |
| 11766 | { |
| 11767 | decl += join(", ", sampler_type(arg_type, arg.id, false), " ", to_sampler_expression(name_id)); |
| 11768 | } |
| 11769 | else |
| 11770 | { |
| 11771 | const char *sampler_address_space = |
| 11772 | descriptor_address_space(name_id, |
| 11773 | StorageClassUniformConstant, |
| 11774 | "thread const"); |
| 11775 | decl += join(", ", sampler_address_space, " ", sampler_type(arg_type, name_id, false), "& ", |
| 11776 | to_sampler_expression(name_id)); |
| 11777 | } |
| 11778 | } |
| 11779 | } |
| 11780 | |
| 11781 | // Manufacture automatic swizzle arg. |
| 11782 | if (msl_options.swizzle_texture_samples && has_sampled_images && is_sampled_image_type(arg_type) && |
| 11783 | !is_dynamic_img_sampler) |
| 11784 | { |
| 11785 | bool arg_is_array = !arg_type.array.empty(); |
| 11786 | decl += join(", constant uint", arg_is_array ? "* " : "& ", to_swizzle_expression(name_id)); |
| 11787 | } |
| 11788 | |
| 11789 | if (buffer_requires_array_length(name_id)) |
| 11790 | { |
| 11791 | bool arg_is_array = !arg_type.array.empty(); |
| 11792 | decl += join(", constant uint", arg_is_array ? "* " : "& ", to_buffer_size_expression(name_id)); |
| 11793 | } |
| 11794 | |
| 11795 | if (&arg != &func.arguments.back()) |
| 11796 | decl += ", "; |
| 11797 | } |
| 11798 | |
| 11799 | decl += ")"; |
| 11800 | statement(decl); |
| 11801 | } |
| 11802 | |
| 11803 | static bool needs_chroma_reconstruction(const MSLConstexprSampler *constexpr_sampler) |
| 11804 | { |
| 11805 | // For now, only multiplanar images need explicit reconstruction. GBGR and BGRG images |
| 11806 | // use implicit reconstruction. |
| 11807 | return constexpr_sampler && constexpr_sampler->ycbcr_conversion_enable && constexpr_sampler->planes > 1; |
| 11808 | } |
| 11809 | |
| 11810 | // Returns the texture sampling function string for the specified image and sampling characteristics. |
| 11811 | string CompilerMSL::to_function_name(const TextureFunctionNameArguments &args) |
| 11812 | { |
| 11813 | VariableID img = args.base.img; |
| 11814 | const MSLConstexprSampler *constexpr_sampler = nullptr; |
| 11815 | bool is_dynamic_img_sampler = false; |
| 11816 | if (auto *var = maybe_get_backing_variable(img)) |
| 11817 | { |
| 11818 | constexpr_sampler = find_constexpr_sampler(var->basevariable ? var->basevariable : VariableID(var->self)); |
| 11819 | is_dynamic_img_sampler = has_extended_decoration(var->self, SPIRVCrossDecorationDynamicImageSampler); |
| 11820 | } |
| 11821 | |
| 11822 | // Special-case gather. We have to alter the component being looked up in the swizzle case. |
| 11823 | if (msl_options.swizzle_texture_samples && args.base.is_gather && !is_dynamic_img_sampler && |
| 11824 | (!constexpr_sampler || !constexpr_sampler->ycbcr_conversion_enable)) |
| 11825 | { |
| 11826 | bool is_compare = comparison_ids.count(img); |
| 11827 | add_spv_func_and_recompile(is_compare ? SPVFuncImplGatherCompareSwizzle : SPVFuncImplGatherSwizzle); |
| 11828 | return is_compare ? "spvGatherCompareSwizzle" : "spvGatherSwizzle"; |
| 11829 | } |
| 11830 | |
| 11831 | // Special-case gather with an array of offsets. We have to lower into 4 separate gathers. |
| 11832 | if (args.has_array_offsets && !is_dynamic_img_sampler && |
| 11833 | (!constexpr_sampler || !constexpr_sampler->ycbcr_conversion_enable)) |
| 11834 | { |
| 11835 | bool is_compare = comparison_ids.count(img); |
| 11836 | add_spv_func_and_recompile(is_compare ? SPVFuncImplGatherCompareConstOffsets : SPVFuncImplGatherConstOffsets); |
| 11837 | return is_compare ? "spvGatherCompareConstOffsets" : "spvGatherConstOffsets"; |
| 11838 | } |
| 11839 | |
| 11840 | auto *combined = maybe_get<SPIRCombinedImageSampler>(img); |
| 11841 | |
| 11842 | // Texture reference |
| 11843 | string fname; |
| 11844 | if (needs_chroma_reconstruction(constexpr_sampler) && !is_dynamic_img_sampler) |
| 11845 | { |
| 11846 | if (constexpr_sampler->planes != 2 && constexpr_sampler->planes != 3) |
| 11847 | SPIRV_CROSS_THROW("Unhandled number of color image planes!"); |
| 11848 | // 444 images aren't downsampled, so we don't need to do linear filtering. |
| 11849 | if (constexpr_sampler->resolution == MSL_FORMAT_RESOLUTION_444 || |
| 11850 | constexpr_sampler->chroma_filter == MSL_SAMPLER_FILTER_NEAREST) |
| 11851 | { |
| 11852 | if (constexpr_sampler->planes == 2) |
| 11853 | add_spv_func_and_recompile(SPVFuncImplChromaReconstructNearest2Plane); |
| 11854 | else |
| 11855 | add_spv_func_and_recompile(SPVFuncImplChromaReconstructNearest3Plane); |
| 11856 | fname = "spvChromaReconstructNearest"; |
| 11857 | } |
| 11858 | else // Linear with a downsampled format |
| 11859 | { |
| 11860 | fname = "spvChromaReconstructLinear"; |
| 11861 | switch (constexpr_sampler->resolution) |
| 11862 | { |
| 11863 | case MSL_FORMAT_RESOLUTION_444: |
| 11864 | assert(false); |
| 11865 | break; // not reached |
| 11866 | case MSL_FORMAT_RESOLUTION_422: |
| 11867 | switch (constexpr_sampler->x_chroma_offset) |
| 11868 | { |
| 11869 | case MSL_CHROMA_LOCATION_COSITED_EVEN: |
| 11870 | if (constexpr_sampler->planes == 2) |
| 11871 | add_spv_func_and_recompile(SPVFuncImplChromaReconstructLinear422CositedEven2Plane); |
| 11872 | else |
| 11873 | add_spv_func_and_recompile(SPVFuncImplChromaReconstructLinear422CositedEven3Plane); |
| 11874 | fname += "422CositedEven"; |
| 11875 | break; |
| 11876 | case MSL_CHROMA_LOCATION_MIDPOINT: |
| 11877 | if (constexpr_sampler->planes == 2) |
| 11878 | add_spv_func_and_recompile(SPVFuncImplChromaReconstructLinear422Midpoint2Plane); |
| 11879 | else |
| 11880 | add_spv_func_and_recompile(SPVFuncImplChromaReconstructLinear422Midpoint3Plane); |
| 11881 | fname += "422Midpoint"; |
| 11882 | break; |
| 11883 | default: |
| 11884 | SPIRV_CROSS_THROW("Invalid chroma location."); |
| 11885 | } |
| 11886 | break; |
| 11887 | case MSL_FORMAT_RESOLUTION_420: |
| 11888 | fname += "420"; |
| 11889 | switch (constexpr_sampler->x_chroma_offset) |
| 11890 | { |
| 11891 | case MSL_CHROMA_LOCATION_COSITED_EVEN: |
| 11892 | switch (constexpr_sampler->y_chroma_offset) |
| 11893 | { |
| 11894 | case MSL_CHROMA_LOCATION_COSITED_EVEN: |
| 11895 | if (constexpr_sampler->planes == 2) |
| 11896 | add_spv_func_and_recompile( |
| 11897 | SPVFuncImplChromaReconstructLinear420XCositedEvenYCositedEven2Plane); |
| 11898 | else |
| 11899 | add_spv_func_and_recompile( |
| 11900 | SPVFuncImplChromaReconstructLinear420XCositedEvenYCositedEven3Plane); |
| 11901 | fname += "XCositedEvenYCositedEven"; |
| 11902 | break; |
| 11903 | case MSL_CHROMA_LOCATION_MIDPOINT: |
| 11904 | if (constexpr_sampler->planes == 2) |
| 11905 | add_spv_func_and_recompile( |
| 11906 | SPVFuncImplChromaReconstructLinear420XCositedEvenYMidpoint2Plane); |
| 11907 | else |
| 11908 | add_spv_func_and_recompile( |
| 11909 | SPVFuncImplChromaReconstructLinear420XCositedEvenYMidpoint3Plane); |
| 11910 | fname += "XCositedEvenYMidpoint"; |
| 11911 | break; |
| 11912 | default: |
| 11913 | SPIRV_CROSS_THROW("Invalid Y chroma location."); |
| 11914 | } |
| 11915 | break; |
| 11916 | case MSL_CHROMA_LOCATION_MIDPOINT: |
| 11917 | switch (constexpr_sampler->y_chroma_offset) |
| 11918 | { |
| 11919 | case MSL_CHROMA_LOCATION_COSITED_EVEN: |
| 11920 | if (constexpr_sampler->planes == 2) |
| 11921 | add_spv_func_and_recompile( |
| 11922 | SPVFuncImplChromaReconstructLinear420XMidpointYCositedEven2Plane); |
| 11923 | else |
| 11924 | add_spv_func_and_recompile( |
| 11925 | SPVFuncImplChromaReconstructLinear420XMidpointYCositedEven3Plane); |
| 11926 | fname += "XMidpointYCositedEven"; |
| 11927 | break; |
| 11928 | case MSL_CHROMA_LOCATION_MIDPOINT: |
| 11929 | if (constexpr_sampler->planes == 2) |
| 11930 | add_spv_func_and_recompile(SPVFuncImplChromaReconstructLinear420XMidpointYMidpoint2Plane); |
| 11931 | else |
| 11932 | add_spv_func_and_recompile(SPVFuncImplChromaReconstructLinear420XMidpointYMidpoint3Plane); |
| 11933 | fname += "XMidpointYMidpoint"; |
| 11934 | break; |
| 11935 | default: |
| 11936 | SPIRV_CROSS_THROW("Invalid Y chroma location."); |
| 11937 | } |
| 11938 | break; |
| 11939 | default: |
| 11940 | SPIRV_CROSS_THROW("Invalid X chroma location."); |
| 11941 | } |
| 11942 | break; |
| 11943 | default: |
| 11944 | SPIRV_CROSS_THROW("Invalid format resolution."); |
| 11945 | } |
| 11946 | } |
| 11947 | } |
| 11948 | else |
| 11949 | { |
| 11950 | fname = to_expression(combined ? combined->image : img) + "."; |
| 11951 | |
| 11952 | // Texture function and sampler |
| 11953 | if (args.base.is_fetch) |
| 11954 | fname += "read"; |
| 11955 | else if (args.base.is_gather) |
| 11956 | fname += "gather"; |
| 11957 | else |
| 11958 | fname += "sample"; |
| 11959 | |
| 11960 | if (args.has_dref) |
| 11961 | fname += "_compare"; |
| 11962 | } |
| 11963 | |
| 11964 | return fname; |
| 11965 | } |
| 11966 | |
| 11967 | string CompilerMSL::convert_to_f32(const string &expr, uint32_t components) |
| 11968 | { |
| 11969 | SPIRType t { components > 1 ? OpTypeVector : OpTypeFloat }; |
| 11970 | t.basetype = SPIRType::Float; |
| 11971 | t.vecsize = components; |
| 11972 | t.columns = 1; |
| 11973 | return join(type_to_glsl_constructor(t), "(", expr, ")"); |
| 11974 | } |
| 11975 | |
| 11976 | static inline bool sampling_type_needs_f32_conversion(const SPIRType &type) |
| 11977 | { |
| 11978 | // Double is not supported to begin with, but doesn't hurt to check for completion. |
| 11979 | return type.basetype == SPIRType::Half || type.basetype == SPIRType::Double; |
| 11980 | } |
| 11981 | |
| 11982 | // Returns the function args for a texture sampling function for the specified image and sampling characteristics. |
| 11983 | string CompilerMSL::to_function_args(const TextureFunctionArguments &args, bool *p_forward) |
| 11984 | { |
| 11985 | VariableID img = args.base.img; |
| 11986 | auto &imgtype = *args.base.imgtype; |
| 11987 | uint32_t lod = args.lod; |
| 11988 | uint32_t grad_x = args.grad_x; |
| 11989 | uint32_t grad_y = args.grad_y; |
| 11990 | uint32_t bias = args.bias; |
| 11991 | |
| 11992 | const MSLConstexprSampler *constexpr_sampler = nullptr; |
| 11993 | bool is_dynamic_img_sampler = false; |
| 11994 | if (auto *var = maybe_get_backing_variable(img)) |
| 11995 | { |
| 11996 | constexpr_sampler = find_constexpr_sampler(var->basevariable ? var->basevariable : VariableID(var->self)); |
| 11997 | is_dynamic_img_sampler = has_extended_decoration(var->self, SPIRVCrossDecorationDynamicImageSampler); |
| 11998 | } |
| 11999 | |
| 12000 | string farg_str; |
| 12001 | bool forward = true; |
| 12002 | |
| 12003 | if (!is_dynamic_img_sampler) |
| 12004 | { |
| 12005 | // Texture reference (for some cases) |
| 12006 | if (needs_chroma_reconstruction(constexpr_sampler)) |
| 12007 | { |
| 12008 | // Multiplanar images need two or three textures. |
| 12009 | farg_str += to_expression(img); |
| 12010 | for (uint32_t i = 1; i < constexpr_sampler->planes; i++) |
| 12011 | farg_str += join(", ", to_expression(img), plane_name_suffix, i); |
| 12012 | } |
| 12013 | else if ((!constexpr_sampler || !constexpr_sampler->ycbcr_conversion_enable) && |
| 12014 | msl_options.swizzle_texture_samples && args.base.is_gather) |
| 12015 | { |
| 12016 | auto *combined = maybe_get<SPIRCombinedImageSampler>(img); |
| 12017 | farg_str += to_expression(combined ? combined->image : img); |
| 12018 | } |
| 12019 | |
| 12020 | // Gathers with constant offsets call a special function, so include the texture. |
| 12021 | if (args.has_array_offsets) |
| 12022 | farg_str += to_expression(img); |
| 12023 | |
| 12024 | // Sampler reference |
| 12025 | if (!args.base.is_fetch) |
| 12026 | { |
| 12027 | if (!farg_str.empty()) |
| 12028 | farg_str += ", "; |
| 12029 | farg_str += to_sampler_expression(img); |
| 12030 | } |
| 12031 | |
| 12032 | if ((!constexpr_sampler || !constexpr_sampler->ycbcr_conversion_enable) && |
| 12033 | msl_options.swizzle_texture_samples && args.base.is_gather) |
| 12034 | { |
| 12035 | // Add the swizzle constant from the swizzle buffer. |
| 12036 | farg_str += ", " + to_swizzle_expression(img); |
| 12037 | used_swizzle_buffer = true; |
| 12038 | } |
| 12039 | |
| 12040 | // Const offsets gather puts the const offsets before the other args. |
| 12041 | if (args.has_array_offsets) |
| 12042 | { |
| 12043 | forward = forward && should_forward(args.offset); |
| 12044 | farg_str += ", " + to_unpacked_expression(args.offset); |
| 12045 | } |
| 12046 | |
| 12047 | // Const offsets gather or swizzled gather puts the component before the other args. |
| 12048 | if (args.component && (args.has_array_offsets || msl_options.swizzle_texture_samples)) |
| 12049 | { |
| 12050 | forward = forward && should_forward(args.component); |
| 12051 | farg_str += ", " + to_component_argument(args.component); |
| 12052 | } |
| 12053 | } |
| 12054 | |
| 12055 | // Texture coordinates |
| 12056 | forward = forward && should_forward(args.coord); |
| 12057 | auto coord_expr = to_enclosed_unpacked_expression(args.coord); |
| 12058 | auto &coord_type = expression_type(args.coord); |
| 12059 | bool coord_is_fp = type_is_floating_point(coord_type); |
| 12060 | bool is_cube_fetch = false; |
| 12061 | |
| 12062 | string tex_coords = coord_expr; |
| 12063 | uint32_t alt_coord_component = 0; |
| 12064 | |
| 12065 | switch (imgtype.image.dim) |
| 12066 | { |
| 12067 | |
| 12068 | case Dim1D: |
| 12069 | if (coord_type.vecsize > 1) |
| 12070 | tex_coords = enclose_expression(tex_coords) + ".x"; |
| 12071 | |
| 12072 | if (args.base.is_fetch) |
| 12073 | tex_coords = "uint(" + round_fp_tex_coords(tex_coords, coord_is_fp) + ")"; |
| 12074 | else if (sampling_type_needs_f32_conversion(coord_type)) |
| 12075 | tex_coords = convert_to_f32(tex_coords, 1); |
| 12076 | |
| 12077 | if (msl_options.texture_1D_as_2D) |
| 12078 | { |
| 12079 | if (args.base.is_fetch) |
| 12080 | tex_coords = "uint2(" + tex_coords + ", 0)"; |
| 12081 | else |
| 12082 | tex_coords = "float2(" + tex_coords + ", 0.5)"; |
| 12083 | } |
| 12084 | |
| 12085 | alt_coord_component = 1; |
| 12086 | break; |
| 12087 | |
| 12088 | case DimBuffer: |
| 12089 | if (coord_type.vecsize > 1) |
| 12090 | tex_coords = enclose_expression(tex_coords) + ".x"; |
| 12091 | |
| 12092 | if (msl_options.texture_buffer_native) |
| 12093 | { |
| 12094 | tex_coords = "uint(" + round_fp_tex_coords(tex_coords, coord_is_fp) + ")"; |
| 12095 | } |
| 12096 | else |
| 12097 | { |
| 12098 | // Metal texel buffer textures are 2D, so convert 1D coord to 2D. |
| 12099 | // Support for Metal 2.1's new texture_buffer type. |
| 12100 | if (args.base.is_fetch) |
| 12101 | { |
| 12102 | if (msl_options.texel_buffer_texture_width > 0) |
| 12103 | { |
| 12104 | tex_coords = "spvTexelBufferCoord(" + round_fp_tex_coords(tex_coords, coord_is_fp) + ")"; |
| 12105 | } |
| 12106 | else |
| 12107 | { |
| 12108 | tex_coords = "spvTexelBufferCoord(" + round_fp_tex_coords(tex_coords, coord_is_fp) + ", " + |
| 12109 | to_expression(img) + ")"; |
| 12110 | } |
| 12111 | } |
| 12112 | } |
| 12113 | |
| 12114 | alt_coord_component = 1; |
| 12115 | break; |
| 12116 | |
| 12117 | case DimSubpassData: |
| 12118 | // If we're using Metal's native frame-buffer fetch API for subpass inputs, |
| 12119 | // this path will not be hit. |
| 12120 | tex_coords = "uint2(gl_FragCoord.xy)"; |
| 12121 | alt_coord_component = 2; |
| 12122 | break; |
| 12123 | |
| 12124 | case Dim2D: |
| 12125 | if (coord_type.vecsize > 2) |
| 12126 | tex_coords = enclose_expression(tex_coords) + ".xy"; |
| 12127 | |
| 12128 | if (args.base.is_fetch) |
| 12129 | tex_coords = "uint2(" + round_fp_tex_coords(tex_coords, coord_is_fp) + ")"; |
| 12130 | else if (sampling_type_needs_f32_conversion(coord_type)) |
| 12131 | tex_coords = convert_to_f32(tex_coords, 2); |
| 12132 | |
| 12133 | alt_coord_component = 2; |
| 12134 | break; |
| 12135 | |
| 12136 | case Dim3D: |
| 12137 | if (coord_type.vecsize > 3) |
| 12138 | tex_coords = enclose_expression(tex_coords) + ".xyz"; |
| 12139 | |
| 12140 | if (args.base.is_fetch) |
| 12141 | tex_coords = "uint3(" + round_fp_tex_coords(tex_coords, coord_is_fp) + ")"; |
| 12142 | else if (sampling_type_needs_f32_conversion(coord_type)) |
| 12143 | tex_coords = convert_to_f32(tex_coords, 3); |
| 12144 | |
| 12145 | alt_coord_component = 3; |
| 12146 | break; |
| 12147 | |
| 12148 | case DimCube: |
| 12149 | if (args.base.is_fetch) |
| 12150 | { |
| 12151 | is_cube_fetch = true; |
| 12152 | tex_coords += ".xy"; |
| 12153 | tex_coords = "uint2(" + round_fp_tex_coords(tex_coords, coord_is_fp) + ")"; |
| 12154 | } |
| 12155 | else |
| 12156 | { |
| 12157 | if (coord_type.vecsize > 3) |
| 12158 | tex_coords = enclose_expression(tex_coords) + ".xyz"; |
| 12159 | } |
| 12160 | |
| 12161 | if (sampling_type_needs_f32_conversion(coord_type)) |
| 12162 | tex_coords = convert_to_f32(tex_coords, 3); |
| 12163 | |
| 12164 | alt_coord_component = 3; |
| 12165 | break; |
| 12166 | |
| 12167 | default: |
| 12168 | break; |
| 12169 | } |
| 12170 | |
| 12171 | if (args.base.is_fetch && args.offset) |
| 12172 | { |
| 12173 | // Fetch offsets must be applied directly to the coordinate. |
| 12174 | forward = forward && should_forward(args.offset); |
| 12175 | auto &type = expression_type(args.offset); |
| 12176 | if (imgtype.image.dim == Dim1D && msl_options.texture_1D_as_2D) |
| 12177 | { |
| 12178 | if (type.basetype != SPIRType::UInt) |
| 12179 | tex_coords += join(" + uint2(", bitcast_expression(SPIRType::UInt, args.offset), ", 0)"); |
| 12180 | else |
| 12181 | tex_coords += join(" + uint2(", to_enclosed_unpacked_expression(args.offset), ", 0)"); |
| 12182 | } |
| 12183 | else |
| 12184 | { |
| 12185 | if (type.basetype != SPIRType::UInt) |
| 12186 | tex_coords += " + " + bitcast_expression(SPIRType::UInt, args.offset); |
| 12187 | else |
| 12188 | tex_coords += " + " + to_enclosed_unpacked_expression(args.offset); |
| 12189 | } |
| 12190 | } |
| 12191 | |
| 12192 | // If projection, use alt coord as divisor |
| 12193 | if (args.base.is_proj) |
| 12194 | { |
| 12195 | if (sampling_type_needs_f32_conversion(coord_type)) |
| 12196 | tex_coords += " / " + convert_to_f32(to_extract_component_expression(args.coord, alt_coord_component), 1); |
| 12197 | else |
| 12198 | tex_coords += " / " + to_extract_component_expression(args.coord, alt_coord_component); |
| 12199 | } |
| 12200 | |
| 12201 | if (!farg_str.empty()) |
| 12202 | farg_str += ", "; |
| 12203 | |
| 12204 | if (imgtype.image.dim == DimCube && imgtype.image.arrayed && msl_options.emulate_cube_array) |
| 12205 | { |
| 12206 | farg_str += "spvCubemapTo2DArrayFace(" + tex_coords + ").xy"; |
| 12207 | |
| 12208 | if (is_cube_fetch) |
| 12209 | farg_str += ", uint(" + to_extract_component_expression(args.coord, 2) + ")"; |
| 12210 | else |
| 12211 | farg_str += |
| 12212 | ", uint(spvCubemapTo2DArrayFace(" + tex_coords + ").z) + (uint(" + |
| 12213 | round_fp_tex_coords(to_extract_component_expression(args.coord, alt_coord_component), coord_is_fp) + |
| 12214 | ") * 6u)"; |
| 12215 | |
| 12216 | add_spv_func_and_recompile(SPVFuncImplCubemapTo2DArrayFace); |
| 12217 | } |
| 12218 | else |
| 12219 | { |
| 12220 | farg_str += tex_coords; |
| 12221 | |
| 12222 | // If fetch from cube, add face explicitly |
| 12223 | if (is_cube_fetch) |
| 12224 | { |
| 12225 | // Special case for cube arrays, face and layer are packed in one dimension. |
| 12226 | if (imgtype.image.arrayed) |
| 12227 | farg_str += ", uint(" + to_extract_component_expression(args.coord, 2) + ") % 6u"; |
| 12228 | else |
| 12229 | farg_str += |
| 12230 | ", uint(" + round_fp_tex_coords(to_extract_component_expression(args.coord, 2), coord_is_fp) + ")"; |
| 12231 | } |
| 12232 | |
| 12233 | // If array, use alt coord |
| 12234 | if (imgtype.image.arrayed) |
| 12235 | { |
| 12236 | // Special case for cube arrays, face and layer are packed in one dimension. |
| 12237 | if (imgtype.image.dim == DimCube && args.base.is_fetch) |
| 12238 | { |
| 12239 | farg_str += ", uint(" + to_extract_component_expression(args.coord, 2) + ") / 6u"; |
| 12240 | } |
| 12241 | else |
| 12242 | { |
| 12243 | farg_str += |
| 12244 | ", uint(" + |
| 12245 | round_fp_tex_coords(to_extract_component_expression(args.coord, alt_coord_component), coord_is_fp) + |
| 12246 | ")"; |
| 12247 | if (imgtype.image.dim == DimSubpassData) |
| 12248 | { |
| 12249 | if (msl_options.multiview) |
| 12250 | farg_str += " + gl_ViewIndex"; |
| 12251 | else if (msl_options.arrayed_subpass_input) |
| 12252 | farg_str += " + gl_Layer"; |
| 12253 | } |
| 12254 | } |
| 12255 | } |
| 12256 | else if (imgtype.image.dim == DimSubpassData) |
| 12257 | { |
| 12258 | if (msl_options.multiview) |
| 12259 | farg_str += ", gl_ViewIndex"; |
| 12260 | else if (msl_options.arrayed_subpass_input) |
| 12261 | farg_str += ", gl_Layer"; |
| 12262 | } |
| 12263 | } |
| 12264 | |
| 12265 | // Depth compare reference value |
| 12266 | if (args.dref) |
| 12267 | { |
| 12268 | forward = forward && should_forward(args.dref); |
| 12269 | farg_str += ", "; |
| 12270 | |
| 12271 | auto &dref_type = expression_type(args.dref); |
| 12272 | |
| 12273 | string dref_expr; |
| 12274 | if (args.base.is_proj) |
| 12275 | dref_expr = join(to_enclosed_unpacked_expression(args.dref), " / ", |
| 12276 | to_extract_component_expression(args.coord, alt_coord_component)); |
| 12277 | else |
| 12278 | dref_expr = to_unpacked_expression(args.dref); |
| 12279 | |
| 12280 | if (sampling_type_needs_f32_conversion(dref_type)) |
| 12281 | dref_expr = convert_to_f32(dref_expr, 1); |
| 12282 | |
| 12283 | farg_str += dref_expr; |
| 12284 | |
| 12285 | if (msl_options.is_macos() && (grad_x || grad_y)) |
| 12286 | { |
| 12287 | // For sample compare, MSL does not support gradient2d for all targets (only iOS apparently according to docs). |
| 12288 | // However, the most common case here is to have a constant gradient of 0, as that is the only way to express |
| 12289 | // LOD == 0 in GLSL with sampler2DArrayShadow (cascaded shadow mapping). |
| 12290 | // We will detect a compile-time constant 0 value for gradient and promote that to level(0) on MSL. |
| 12291 | bool constant_zero_x = !grad_x || expression_is_constant_null(grad_x); |
| 12292 | bool constant_zero_y = !grad_y || expression_is_constant_null(grad_y); |
| 12293 | if (constant_zero_x && constant_zero_y && |
| 12294 | (!imgtype.image.arrayed || !msl_options.sample_dref_lod_array_as_grad)) |
| 12295 | { |
| 12296 | lod = 0; |
| 12297 | grad_x = 0; |
| 12298 | grad_y = 0; |
| 12299 | farg_str += ", level(0)"; |
| 12300 | } |
| 12301 | else if (!msl_options.supports_msl_version(2, 3)) |
| 12302 | { |
| 12303 | SPIRV_CROSS_THROW("Using non-constant 0.0 gradient() qualifier for sample_compare. This is not " |
| 12304 | "supported on macOS prior to MSL 2.3."); |
| 12305 | } |
| 12306 | } |
| 12307 | |
| 12308 | if (msl_options.is_macos() && bias) |
| 12309 | { |
| 12310 | // Bias is not supported either on macOS with sample_compare. |
| 12311 | // Verify it is compile-time zero, and drop the argument. |
| 12312 | if (expression_is_constant_null(bias)) |
| 12313 | { |
| 12314 | bias = 0; |
| 12315 | } |
| 12316 | else if (!msl_options.supports_msl_version(2, 3)) |
| 12317 | { |
| 12318 | SPIRV_CROSS_THROW("Using non-constant 0.0 bias() qualifier for sample_compare. This is not supported " |
| 12319 | "on macOS prior to MSL 2.3."); |
| 12320 | } |
| 12321 | } |
| 12322 | } |
| 12323 | |
| 12324 | // LOD Options |
| 12325 | // Metal does not support LOD for 1D textures. |
| 12326 | if (bias && (imgtype.image.dim != Dim1D || msl_options.texture_1D_as_2D)) |
| 12327 | { |
| 12328 | forward = forward && should_forward(bias); |
| 12329 | farg_str += ", bias(" + to_unpacked_expression(bias) + ")"; |
| 12330 | } |
| 12331 | |
| 12332 | // Metal does not support LOD for 1D textures. |
| 12333 | if (lod && (imgtype.image.dim != Dim1D || msl_options.texture_1D_as_2D)) |
| 12334 | { |
| 12335 | forward = forward && should_forward(lod); |
| 12336 | if (args.base.is_fetch) |
| 12337 | { |
| 12338 | farg_str += ", " + to_unpacked_expression(lod); |
| 12339 | } |
| 12340 | else if (msl_options.sample_dref_lod_array_as_grad && args.dref && imgtype.image.arrayed) |
| 12341 | { |
| 12342 | if (msl_options.is_macos() && !msl_options.supports_msl_version(2, 3)) |
| 12343 | SPIRV_CROSS_THROW("Using non-constant 0.0 gradient() qualifier for sample_compare. This is not " |
| 12344 | "supported on macOS prior to MSL 2.3."); |
| 12345 | // Some Metal devices have a bug where the LoD is erroneously biased upward |
| 12346 | // when using a level() argument. Since this doesn't happen as much with gradient2d(), |
| 12347 | // if we perform the LoD calculation in reverse, we can pass a gradient |
| 12348 | // instead. |
| 12349 | // lod = log2(rhoMax/eta) -> exp2(lod) = rhoMax/eta |
| 12350 | // If we make all of the scale factors the same, eta will be 1 and |
| 12351 | // exp2(lod) = rho. |
| 12352 | // rhoX = dP/dx * extent; rhoY = dP/dy * extent |
| 12353 | // Therefore, dP/dx = dP/dy = exp2(lod)/extent. |
| 12354 | // (Subtracting 0.5 before exponentiation gives better results.) |
| 12355 | string grad_opt, extent, grad_coord; |
| 12356 | VariableID base_img = img; |
| 12357 | if (auto *combined = maybe_get<SPIRCombinedImageSampler>(img)) |
| 12358 | base_img = combined->image; |
| 12359 | switch (imgtype.image.dim) |
| 12360 | { |
| 12361 | case Dim1D: |
| 12362 | grad_opt = "gradient2d"; |
| 12363 | extent = join("float2(", to_expression(base_img), ".get_width(), 1.0)"); |
| 12364 | break; |
| 12365 | case Dim2D: |
| 12366 | grad_opt = "gradient2d"; |
| 12367 | extent = join("float2(", to_expression(base_img), ".get_width(), ", to_expression(base_img), ".get_height())"); |
| 12368 | break; |
| 12369 | case DimCube: |
| 12370 | if (imgtype.image.arrayed && msl_options.emulate_cube_array) |
| 12371 | { |
| 12372 | grad_opt = "gradient2d"; |
| 12373 | extent = join("float2(", to_expression(base_img), ".get_width())"); |
| 12374 | } |
| 12375 | else |
| 12376 | { |
| 12377 | if (msl_options.agx_manual_cube_grad_fixup) |
| 12378 | { |
| 12379 | add_spv_func_and_recompile(SPVFuncImplGradientCube); |
| 12380 | grad_opt = "spvGradientCube"; |
| 12381 | grad_coord = tex_coords + ", "; |
| 12382 | } |
| 12383 | else |
| 12384 | { |
| 12385 | grad_opt = "gradientcube"; |
| 12386 | } |
| 12387 | extent = join("float3(", to_expression(base_img), ".get_width())"); |
| 12388 | } |
| 12389 | break; |
| 12390 | default: |
| 12391 | grad_opt = "unsupported_gradient_dimension"; |
| 12392 | extent = "float3(1.0)"; |
| 12393 | break; |
| 12394 | } |
| 12395 | farg_str += join(", ", grad_opt, "(", grad_coord, "exp2(", to_unpacked_expression(lod), " - 0.5) / ", extent, |
| 12396 | ", exp2(", to_unpacked_expression(lod), " - 0.5) / ", extent, ")"); |
| 12397 | } |
| 12398 | else |
| 12399 | { |
| 12400 | farg_str += ", level(" + to_unpacked_expression(lod) + ")"; |
| 12401 | } |
| 12402 | } |
| 12403 | else if (args.base.is_fetch && !lod && (imgtype.image.dim != Dim1D || msl_options.texture_1D_as_2D) && |
| 12404 | imgtype.image.dim != DimBuffer && !imgtype.image.ms && imgtype.image.sampled != 2) |
| 12405 | { |
| 12406 | // Lod argument is optional in OpImageFetch, but we require a LOD value, pick 0 as the default. |
| 12407 | // Check for sampled type as well, because is_fetch is also used for OpImageRead in MSL. |
| 12408 | farg_str += ", 0"; |
| 12409 | } |
| 12410 | |
| 12411 | // Metal does not support LOD for 1D textures. |
| 12412 | if ((grad_x || grad_y) && (imgtype.image.dim != Dim1D || msl_options.texture_1D_as_2D)) |
| 12413 | { |
| 12414 | forward = forward && should_forward(grad_x); |
| 12415 | forward = forward && should_forward(grad_y); |
| 12416 | string grad_opt, grad_coord; |
| 12417 | switch (imgtype.image.dim) |
| 12418 | { |
| 12419 | case Dim1D: |
| 12420 | case Dim2D: |
| 12421 | grad_opt = "gradient2d"; |
| 12422 | break; |
| 12423 | case Dim3D: |
| 12424 | grad_opt = "gradient3d"; |
| 12425 | break; |
| 12426 | case DimCube: |
| 12427 | if (imgtype.image.arrayed && msl_options.emulate_cube_array) |
| 12428 | { |
| 12429 | grad_opt = "gradient2d"; |
| 12430 | } |
| 12431 | else if (msl_options.agx_manual_cube_grad_fixup) |
| 12432 | { |
| 12433 | add_spv_func_and_recompile(SPVFuncImplGradientCube); |
| 12434 | grad_opt = "spvGradientCube"; |
| 12435 | grad_coord = tex_coords + ", "; |
| 12436 | } |
| 12437 | else |
| 12438 | { |
| 12439 | grad_opt = "gradientcube"; |
| 12440 | } |
| 12441 | break; |
| 12442 | default: |
| 12443 | grad_opt = "unsupported_gradient_dimension"; |
| 12444 | break; |
| 12445 | } |
| 12446 | farg_str += join(", ", grad_opt, "(", grad_coord, to_unpacked_expression(grad_x), ", ", to_unpacked_expression(grad_y), ")"); |
| 12447 | } |
| 12448 | |
| 12449 | if (args.min_lod) |
| 12450 | { |
| 12451 | if (!msl_options.supports_msl_version(2, 2)) |
| 12452 | SPIRV_CROSS_THROW("min_lod_clamp() is only supported in MSL 2.2+ and up."); |
| 12453 | |
| 12454 | forward = forward && should_forward(args.min_lod); |
| 12455 | farg_str += ", min_lod_clamp(" + to_unpacked_expression(args.min_lod) + ")"; |
| 12456 | } |
| 12457 | |
| 12458 | // Add offsets |
| 12459 | string offset_expr; |
| 12460 | const SPIRType *offset_type = nullptr; |
| 12461 | if (args.offset && !args.base.is_fetch && !args.has_array_offsets) |
| 12462 | { |
| 12463 | forward = forward && should_forward(args.offset); |
| 12464 | offset_expr = to_unpacked_expression(args.offset); |
| 12465 | offset_type = &expression_type(args.offset); |
| 12466 | } |
| 12467 | |
| 12468 | if (!offset_expr.empty()) |
| 12469 | { |
| 12470 | switch (imgtype.image.dim) |
| 12471 | { |
| 12472 | case Dim1D: |
| 12473 | if (!msl_options.texture_1D_as_2D) |
| 12474 | break; |
| 12475 | if (offset_type->vecsize > 1) |
| 12476 | offset_expr = enclose_expression(offset_expr) + ".x"; |
| 12477 | |
| 12478 | farg_str += join(", int2(", offset_expr, ", 0)"); |
| 12479 | break; |
| 12480 | |
| 12481 | case Dim2D: |
| 12482 | if (offset_type->vecsize > 2) |
| 12483 | offset_expr = enclose_expression(offset_expr) + ".xy"; |
| 12484 | |
| 12485 | farg_str += ", " + offset_expr; |
| 12486 | break; |
| 12487 | |
| 12488 | case Dim3D: |
| 12489 | if (offset_type->vecsize > 3) |
| 12490 | offset_expr = enclose_expression(offset_expr) + ".xyz"; |
| 12491 | |
| 12492 | farg_str += ", " + offset_expr; |
| 12493 | break; |
| 12494 | |
| 12495 | default: |
| 12496 | break; |
| 12497 | } |
| 12498 | } |
| 12499 | |
| 12500 | if (args.component && !args.has_array_offsets) |
| 12501 | { |
| 12502 | // If 2D has gather component, ensure it also has an offset arg |
| 12503 | if (imgtype.image.dim == Dim2D && offset_expr.empty()) |
| 12504 | farg_str += ", int2(0)"; |
| 12505 | |
| 12506 | if (!msl_options.swizzle_texture_samples || is_dynamic_img_sampler) |
| 12507 | { |
| 12508 | forward = forward && should_forward(args.component); |
| 12509 | |
| 12510 | uint32_t image_var = 0; |
| 12511 | if (const auto *combined = maybe_get<SPIRCombinedImageSampler>(img)) |
| 12512 | { |
| 12513 | if (const auto *img_var = maybe_get_backing_variable(combined->image)) |
| 12514 | image_var = img_var->self; |
| 12515 | } |
| 12516 | else if (const auto *var = maybe_get_backing_variable(img)) |
| 12517 | { |
| 12518 | image_var = var->self; |
| 12519 | } |
| 12520 | |
| 12521 | if (image_var == 0 || !is_depth_image(expression_type(image_var), image_var)) |
| 12522 | farg_str += ", " + to_component_argument(args.component); |
| 12523 | } |
| 12524 | } |
| 12525 | |
| 12526 | if (args.sample) |
| 12527 | { |
| 12528 | forward = forward && should_forward(args.sample); |
| 12529 | farg_str += ", "; |
| 12530 | farg_str += to_unpacked_expression(args.sample); |
| 12531 | } |
| 12532 | |
| 12533 | *p_forward = forward; |
| 12534 | |
| 12535 | return farg_str; |
| 12536 | } |
| 12537 | |
| 12538 | // If the texture coordinates are floating point, invokes MSL round() function to round them. |
| 12539 | string CompilerMSL::round_fp_tex_coords(string tex_coords, bool coord_is_fp) |
| 12540 | { |
| 12541 | return coord_is_fp ? ("rint(" + tex_coords + ")") : tex_coords; |
| 12542 | } |
| 12543 | |
| 12544 | // Returns a string to use in an image sampling function argument. |
| 12545 | // The ID must be a scalar constant. |
| 12546 | string CompilerMSL::to_component_argument(uint32_t id) |
| 12547 | { |
| 12548 | uint32_t component_index = evaluate_constant_u32(id); |
| 12549 | switch (component_index) |
| 12550 | { |
| 12551 | case 0: |
| 12552 | return "component::x"; |
| 12553 | case 1: |
| 12554 | return "component::y"; |
| 12555 | case 2: |
| 12556 | return "component::z"; |
| 12557 | case 3: |
| 12558 | return "component::w"; |
| 12559 | |
| 12560 | default: |
| 12561 | SPIRV_CROSS_THROW("The value (" + to_string(component_index) + ") of OpConstant ID " + to_string(id) + |
| 12562 | " is not a valid Component index, which must be one of 0, 1, 2, or 3."); |
| 12563 | } |
| 12564 | } |
| 12565 | |
| 12566 | // Establish sampled image as expression object and assign the sampler to it. |
| 12567 | void CompilerMSL::emit_sampled_image_op(uint32_t result_type, uint32_t result_id, uint32_t image_id, uint32_t samp_id) |
| 12568 | { |
| 12569 | set<SPIRCombinedImageSampler>(result_id, result_type, image_id, samp_id); |
| 12570 | } |
| 12571 | |
| 12572 | string CompilerMSL::to_texture_op(const Instruction &i, bool sparse, bool *forward, |
| 12573 | SmallVector<uint32_t> &inherited_expressions) |
| 12574 | { |
| 12575 | auto *ops = stream(i); |
| 12576 | uint32_t result_type_id = ops[0]; |
| 12577 | uint32_t img = ops[2]; |
| 12578 | auto &result_type = get<SPIRType>(result_type_id); |
| 12579 | auto op = static_cast<Op>(i.op); |
| 12580 | bool is_gather = (op == OpImageGather || op == OpImageDrefGather); |
| 12581 | |
| 12582 | // Bypass pointers because we need the real image struct |
| 12583 | auto &type = expression_type(img); |
| 12584 | auto &imgtype = get<SPIRType>(type.self); |
| 12585 | |
| 12586 | const MSLConstexprSampler *constexpr_sampler = nullptr; |
| 12587 | bool is_dynamic_img_sampler = false; |
| 12588 | if (auto *var = maybe_get_backing_variable(img)) |
| 12589 | { |
| 12590 | constexpr_sampler = find_constexpr_sampler(var->basevariable ? var->basevariable : VariableID(var->self)); |
| 12591 | is_dynamic_img_sampler = has_extended_decoration(var->self, SPIRVCrossDecorationDynamicImageSampler); |
| 12592 | } |
| 12593 | |
| 12594 | string expr; |
| 12595 | if (constexpr_sampler && constexpr_sampler->ycbcr_conversion_enable && !is_dynamic_img_sampler) |
| 12596 | { |
| 12597 | // If this needs sampler Y'CbCr conversion, we need to do some additional |
| 12598 | // processing. |
| 12599 | switch (constexpr_sampler->ycbcr_model) |
| 12600 | { |
| 12601 | case MSL_SAMPLER_YCBCR_MODEL_CONVERSION_RGB_IDENTITY: |
| 12602 | case MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_IDENTITY: |
| 12603 | // Default |
| 12604 | break; |
| 12605 | case MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_BT_709: |
| 12606 | add_spv_func_and_recompile(SPVFuncImplConvertYCbCrBT709); |
| 12607 | expr += "spvConvertYCbCrBT709("; |
| 12608 | break; |
| 12609 | case MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_BT_601: |
| 12610 | add_spv_func_and_recompile(SPVFuncImplConvertYCbCrBT601); |
| 12611 | expr += "spvConvertYCbCrBT601("; |
| 12612 | break; |
| 12613 | case MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_BT_2020: |
| 12614 | add_spv_func_and_recompile(SPVFuncImplConvertYCbCrBT2020); |
| 12615 | expr += "spvConvertYCbCrBT2020("; |
| 12616 | break; |
| 12617 | default: |
| 12618 | SPIRV_CROSS_THROW("Invalid Y'CbCr model conversion."); |
| 12619 | } |
| 12620 | |
| 12621 | if (constexpr_sampler->ycbcr_model != MSL_SAMPLER_YCBCR_MODEL_CONVERSION_RGB_IDENTITY) |
| 12622 | { |
| 12623 | switch (constexpr_sampler->ycbcr_range) |
| 12624 | { |
| 12625 | case MSL_SAMPLER_YCBCR_RANGE_ITU_FULL: |
| 12626 | add_spv_func_and_recompile(SPVFuncImplExpandITUFullRange); |
| 12627 | expr += "spvExpandITUFullRange("; |
| 12628 | break; |
| 12629 | case MSL_SAMPLER_YCBCR_RANGE_ITU_NARROW: |
| 12630 | add_spv_func_and_recompile(SPVFuncImplExpandITUNarrowRange); |
| 12631 | expr += "spvExpandITUNarrowRange("; |
| 12632 | break; |
| 12633 | default: |
| 12634 | SPIRV_CROSS_THROW("Invalid Y'CbCr range."); |
| 12635 | } |
| 12636 | } |
| 12637 | } |
| 12638 | else if (msl_options.swizzle_texture_samples && !is_gather && is_sampled_image_type(imgtype) && |
| 12639 | !is_dynamic_img_sampler) |
| 12640 | { |
| 12641 | add_spv_func_and_recompile(SPVFuncImplTextureSwizzle); |
| 12642 | expr += "spvTextureSwizzle("; |
| 12643 | } |
| 12644 | |
| 12645 | string inner_expr = CompilerGLSL::to_texture_op(i, sparse, forward, inherited_expressions); |
| 12646 | |
| 12647 | if (constexpr_sampler && constexpr_sampler->ycbcr_conversion_enable && !is_dynamic_img_sampler) |
| 12648 | { |
| 12649 | if (!constexpr_sampler->swizzle_is_identity()) |
| 12650 | { |
| 12651 | static const char swizzle_names[] = "rgba"; |
| 12652 | if (!constexpr_sampler->swizzle_has_one_or_zero()) |
| 12653 | { |
| 12654 | // If we can, do it inline. |
| 12655 | expr += inner_expr + "."; |
| 12656 | for (uint32_t c = 0; c < 4; c++) |
| 12657 | { |
| 12658 | switch (constexpr_sampler->swizzle[c]) |
| 12659 | { |
| 12660 | case MSL_COMPONENT_SWIZZLE_IDENTITY: |
| 12661 | expr += swizzle_names[c]; |
| 12662 | break; |
| 12663 | case MSL_COMPONENT_SWIZZLE_R: |
| 12664 | case MSL_COMPONENT_SWIZZLE_G: |
| 12665 | case MSL_COMPONENT_SWIZZLE_B: |
| 12666 | case MSL_COMPONENT_SWIZZLE_A: |
| 12667 | expr += swizzle_names[constexpr_sampler->swizzle[c] - MSL_COMPONENT_SWIZZLE_R]; |
| 12668 | break; |
| 12669 | default: |
| 12670 | SPIRV_CROSS_THROW("Invalid component swizzle."); |
| 12671 | } |
| 12672 | } |
| 12673 | } |
| 12674 | else |
| 12675 | { |
| 12676 | // Otherwise, we need to emit a temporary and swizzle that. |
| 12677 | uint32_t temp_id = ir.increase_bound_by(1); |
| 12678 | emit_op(result_type_id, temp_id, inner_expr, false); |
| 12679 | for (auto &inherit : inherited_expressions) |
| 12680 | inherit_expression_dependencies(temp_id, inherit); |
| 12681 | inherited_expressions.clear(); |
| 12682 | inherited_expressions.push_back(temp_id); |
| 12683 | |
| 12684 | switch (op) |
| 12685 | { |
| 12686 | case OpImageSampleDrefImplicitLod: |
| 12687 | case OpImageSampleImplicitLod: |
| 12688 | case OpImageSampleProjImplicitLod: |
| 12689 | case OpImageSampleProjDrefImplicitLod: |
| 12690 | register_control_dependent_expression(temp_id); |
| 12691 | break; |
| 12692 | |
| 12693 | default: |
| 12694 | break; |
| 12695 | } |
| 12696 | expr += type_to_glsl(result_type) + "("; |
| 12697 | for (uint32_t c = 0; c < 4; c++) |
| 12698 | { |
| 12699 | switch (constexpr_sampler->swizzle[c]) |
| 12700 | { |
| 12701 | case MSL_COMPONENT_SWIZZLE_IDENTITY: |
| 12702 | expr += to_expression(temp_id) + "." + swizzle_names[c]; |
| 12703 | break; |
| 12704 | case MSL_COMPONENT_SWIZZLE_ZERO: |
| 12705 | expr += "0"; |
| 12706 | break; |
| 12707 | case MSL_COMPONENT_SWIZZLE_ONE: |
| 12708 | expr += "1"; |
| 12709 | break; |
| 12710 | case MSL_COMPONENT_SWIZZLE_R: |
| 12711 | case MSL_COMPONENT_SWIZZLE_G: |
| 12712 | case MSL_COMPONENT_SWIZZLE_B: |
| 12713 | case MSL_COMPONENT_SWIZZLE_A: |
| 12714 | expr += to_expression(temp_id) + "." + |
| 12715 | swizzle_names[constexpr_sampler->swizzle[c] - MSL_COMPONENT_SWIZZLE_R]; |
| 12716 | break; |
| 12717 | default: |
| 12718 | SPIRV_CROSS_THROW("Invalid component swizzle."); |
| 12719 | } |
| 12720 | if (c < 3) |
| 12721 | expr += ", "; |
| 12722 | } |
| 12723 | expr += ")"; |
| 12724 | } |
| 12725 | } |
| 12726 | else |
| 12727 | expr += inner_expr; |
| 12728 | if (constexpr_sampler->ycbcr_model != MSL_SAMPLER_YCBCR_MODEL_CONVERSION_RGB_IDENTITY) |
| 12729 | { |
| 12730 | expr += join(", ", constexpr_sampler->bpc, ")"); |
| 12731 | if (constexpr_sampler->ycbcr_model != MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_IDENTITY) |
| 12732 | expr += ")"; |
| 12733 | } |
| 12734 | } |
| 12735 | else |
| 12736 | { |
| 12737 | expr += inner_expr; |
| 12738 | if (msl_options.swizzle_texture_samples && !is_gather && is_sampled_image_type(imgtype) && |
| 12739 | !is_dynamic_img_sampler) |
| 12740 | { |
| 12741 | // Add the swizzle constant from the swizzle buffer. |
| 12742 | expr += ", " + to_swizzle_expression(img) + ")"; |
| 12743 | used_swizzle_buffer = true; |
| 12744 | } |
| 12745 | } |
| 12746 | |
| 12747 | return expr; |
| 12748 | } |
| 12749 | |
| 12750 | static string create_swizzle(MSLComponentSwizzle swizzle) |
| 12751 | { |
| 12752 | switch (swizzle) |
| 12753 | { |
| 12754 | case MSL_COMPONENT_SWIZZLE_IDENTITY: |
| 12755 | return "spvSwizzle::none"; |
| 12756 | case MSL_COMPONENT_SWIZZLE_ZERO: |
| 12757 | return "spvSwizzle::zero"; |
| 12758 | case MSL_COMPONENT_SWIZZLE_ONE: |
| 12759 | return "spvSwizzle::one"; |
| 12760 | case MSL_COMPONENT_SWIZZLE_R: |
| 12761 | return "spvSwizzle::red"; |
| 12762 | case MSL_COMPONENT_SWIZZLE_G: |
| 12763 | return "spvSwizzle::green"; |
| 12764 | case MSL_COMPONENT_SWIZZLE_B: |
| 12765 | return "spvSwizzle::blue"; |
| 12766 | case MSL_COMPONENT_SWIZZLE_A: |
| 12767 | return "spvSwizzle::alpha"; |
| 12768 | default: |
| 12769 | SPIRV_CROSS_THROW("Invalid component swizzle."); |
| 12770 | } |
| 12771 | } |
| 12772 | |
| 12773 | // Returns a string representation of the ID, usable as a function arg. |
| 12774 | // Manufacture automatic sampler arg for SampledImage texture. |
| 12775 | string CompilerMSL::to_func_call_arg(const SPIRFunction::Parameter &arg, uint32_t id) |
| 12776 | { |
| 12777 | string arg_str; |
| 12778 | |
| 12779 | auto &type = expression_type(id); |
| 12780 | bool is_dynamic_img_sampler = has_extended_decoration(arg.id, SPIRVCrossDecorationDynamicImageSampler); |
| 12781 | // If the argument *itself* is a "dynamic" combined-image sampler, then we can just pass that around. |
| 12782 | bool arg_is_dynamic_img_sampler = has_extended_decoration(id, SPIRVCrossDecorationDynamicImageSampler); |
| 12783 | if (is_dynamic_img_sampler && !arg_is_dynamic_img_sampler) |
| 12784 | arg_str = join("spvDynamicImageSampler<", type_to_glsl(get<SPIRType>(type.image.type)), ">("); |
| 12785 | |
| 12786 | auto *c = maybe_get<SPIRConstant>(id); |
| 12787 | if (msl_options.force_native_arrays && c && !get<SPIRType>(c->constant_type).array.empty()) |
| 12788 | { |
| 12789 | // If we are passing a constant array directly to a function for some reason, |
| 12790 | // the callee will expect an argument in thread const address space |
| 12791 | // (since we can only bind to arrays with references in MSL). |
| 12792 | // To resolve this, we must emit a copy in this address space. |
| 12793 | // This kind of code gen should be rare enough that performance is not a real concern. |
| 12794 | // Inline the SPIR-V to avoid this kind of suboptimal codegen. |
| 12795 | // |
| 12796 | // We risk calling this inside a continue block (invalid code), |
| 12797 | // so just create a thread local copy in the current function. |
| 12798 | arg_str = join("_", id, "_array_copy"); |
| 12799 | auto &constants = current_function->constant_arrays_needed_on_stack; |
| 12800 | auto itr = find(begin(constants), end(constants), ID(id)); |
| 12801 | if (itr == end(constants)) |
| 12802 | { |
| 12803 | force_recompile(); |
| 12804 | constants.push_back(id); |
| 12805 | } |
| 12806 | } |
| 12807 | // Dereference pointer variables where needed. |
| 12808 | // FIXME: This dereference is actually backwards. We should really just support passing pointer variables between functions. |
| 12809 | else if (should_dereference_caller_param(id)) |
| 12810 | arg_str += dereference_expression(type, CompilerGLSL::to_func_call_arg(arg, id)); |
| 12811 | else |
| 12812 | arg_str += CompilerGLSL::to_func_call_arg(arg, id); |
| 12813 | |
| 12814 | // Need to check the base variable in case we need to apply a qualified alias. |
| 12815 | uint32_t var_id = 0; |
| 12816 | auto *var = maybe_get<SPIRVariable>(id); |
| 12817 | if (var) |
| 12818 | var_id = var->basevariable; |
| 12819 | |
| 12820 | if (!arg_is_dynamic_img_sampler) |
| 12821 | { |
| 12822 | auto *constexpr_sampler = find_constexpr_sampler(var_id ? var_id : id); |
| 12823 | if (type.basetype == SPIRType::SampledImage) |
| 12824 | { |
| 12825 | // Manufacture automatic plane args for multiplanar texture |
| 12826 | uint32_t planes = 1; |
| 12827 | if (constexpr_sampler && constexpr_sampler->ycbcr_conversion_enable) |
| 12828 | { |
| 12829 | planes = constexpr_sampler->planes; |
| 12830 | // If this parameter isn't aliasing a global, then we need to use |
| 12831 | // the special "dynamic image-sampler" class to pass it--and we need |
| 12832 | // to use it for *every* non-alias parameter, in case a combined |
| 12833 | // image-sampler with a Y'CbCr conversion is passed. Hopefully, this |
| 12834 | // pathological case is so rare that it should never be hit in practice. |
| 12835 | if (!arg.alias_global_variable) |
| 12836 | add_spv_func_and_recompile(SPVFuncImplDynamicImageSampler); |
| 12837 | } |
| 12838 | for (uint32_t i = 1; i < planes; i++) |
| 12839 | arg_str += join(", ", CompilerGLSL::to_func_call_arg(arg, id), plane_name_suffix, i); |
| 12840 | // Manufacture automatic sampler arg if the arg is a SampledImage texture. |
| 12841 | if (type.image.dim != DimBuffer) |
| 12842 | arg_str += ", " + to_sampler_expression(var_id ? var_id : id); |
| 12843 | |
| 12844 | // Add sampler Y'CbCr conversion info if we have it |
| 12845 | if (is_dynamic_img_sampler && constexpr_sampler && constexpr_sampler->ycbcr_conversion_enable) |
| 12846 | { |
| 12847 | SmallVector<string> samp_args; |
| 12848 | |
| 12849 | switch (constexpr_sampler->resolution) |
| 12850 | { |
| 12851 | case MSL_FORMAT_RESOLUTION_444: |
| 12852 | // Default |
| 12853 | break; |
| 12854 | case MSL_FORMAT_RESOLUTION_422: |
| 12855 | samp_args.push_back("spvFormatResolution::_422"); |
| 12856 | break; |
| 12857 | case MSL_FORMAT_RESOLUTION_420: |
| 12858 | samp_args.push_back("spvFormatResolution::_420"); |
| 12859 | break; |
| 12860 | default: |
| 12861 | SPIRV_CROSS_THROW("Invalid format resolution."); |
| 12862 | } |
| 12863 | |
| 12864 | if (constexpr_sampler->chroma_filter != MSL_SAMPLER_FILTER_NEAREST) |
| 12865 | samp_args.push_back("spvChromaFilter::linear"); |
| 12866 | |
| 12867 | if (constexpr_sampler->x_chroma_offset != MSL_CHROMA_LOCATION_COSITED_EVEN) |
| 12868 | samp_args.push_back("spvXChromaLocation::midpoint"); |
| 12869 | if (constexpr_sampler->y_chroma_offset != MSL_CHROMA_LOCATION_COSITED_EVEN) |
| 12870 | samp_args.push_back("spvYChromaLocation::midpoint"); |
| 12871 | switch (constexpr_sampler->ycbcr_model) |
| 12872 | { |
| 12873 | case MSL_SAMPLER_YCBCR_MODEL_CONVERSION_RGB_IDENTITY: |
| 12874 | // Default |
| 12875 | break; |
| 12876 | case MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_IDENTITY: |
| 12877 | samp_args.push_back("spvYCbCrModelConversion::ycbcr_identity"); |
| 12878 | break; |
| 12879 | case MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_BT_709: |
| 12880 | samp_args.push_back("spvYCbCrModelConversion::ycbcr_bt_709"); |
| 12881 | break; |
| 12882 | case MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_BT_601: |
| 12883 | samp_args.push_back("spvYCbCrModelConversion::ycbcr_bt_601"); |
| 12884 | break; |
| 12885 | case MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_BT_2020: |
| 12886 | samp_args.push_back("spvYCbCrModelConversion::ycbcr_bt_2020"); |
| 12887 | break; |
| 12888 | default: |
| 12889 | SPIRV_CROSS_THROW("Invalid Y'CbCr model conversion."); |
| 12890 | } |
| 12891 | if (constexpr_sampler->ycbcr_range != MSL_SAMPLER_YCBCR_RANGE_ITU_FULL) |
| 12892 | samp_args.push_back("spvYCbCrRange::itu_narrow"); |
| 12893 | samp_args.push_back(join("spvComponentBits(", constexpr_sampler->bpc, ")")); |
| 12894 | arg_str += join(", spvYCbCrSampler(", merge(samp_args), ")"); |
| 12895 | } |
| 12896 | } |
| 12897 | |
| 12898 | if (is_dynamic_img_sampler && constexpr_sampler && constexpr_sampler->ycbcr_conversion_enable) |
| 12899 | arg_str += join(", (uint(", create_swizzle(constexpr_sampler->swizzle[3]), ") << 24) | (uint(", |
| 12900 | create_swizzle(constexpr_sampler->swizzle[2]), ") << 16) | (uint(", |
| 12901 | create_swizzle(constexpr_sampler->swizzle[1]), ") << 8) | uint(", |
| 12902 | create_swizzle(constexpr_sampler->swizzle[0]), ")"); |
| 12903 | else if (msl_options.swizzle_texture_samples && has_sampled_images && is_sampled_image_type(type)) |
| 12904 | arg_str += ", " + to_swizzle_expression(var_id ? var_id : id); |
| 12905 | |
| 12906 | if (buffer_requires_array_length(var_id)) |
| 12907 | arg_str += ", " + to_buffer_size_expression(var_id ? var_id : id); |
| 12908 | |
| 12909 | if (is_dynamic_img_sampler) |
| 12910 | arg_str += ")"; |
| 12911 | } |
| 12912 | |
| 12913 | // Emulate texture2D atomic operations |
| 12914 | auto *backing_var = maybe_get_backing_variable(var_id); |
| 12915 | if (backing_var && atomic_image_vars_emulated.count(backing_var->self)) |
| 12916 | { |
| 12917 | arg_str += ", " + to_expression(var_id) + "_atomic"; |
| 12918 | } |
| 12919 | |
| 12920 | return arg_str; |
| 12921 | } |
| 12922 | |
| 12923 | // If the ID represents a sampled image that has been assigned a sampler already, |
| 12924 | // generate an expression for the sampler, otherwise generate a fake sampler name |
| 12925 | // by appending a suffix to the expression constructed from the ID. |
| 12926 | string CompilerMSL::to_sampler_expression(uint32_t id) |
| 12927 | { |
| 12928 | auto *combined = maybe_get<SPIRCombinedImageSampler>(id); |
| 12929 | if (combined && combined->sampler) |
| 12930 | return to_expression(combined->sampler); |
| 12931 | |
| 12932 | uint32_t expr_id = combined ? uint32_t(combined->image) : id; |
| 12933 | |
| 12934 | // Constexpr samplers are declared as local variables, |
| 12935 | // so exclude any qualifier names on the image expression. |
| 12936 | if (auto *var = maybe_get_backing_variable(expr_id)) |
| 12937 | { |
| 12938 | uint32_t img_id = var->basevariable ? var->basevariable : VariableID(var->self); |
| 12939 | if (find_constexpr_sampler(img_id)) |
| 12940 | return Compiler::to_name(img_id) + sampler_name_suffix; |
| 12941 | } |
| 12942 | |
| 12943 | auto img_expr = to_expression(expr_id); |
| 12944 | auto index = img_expr.find_first_of('['); |
| 12945 | if (index == string::npos) |
| 12946 | return img_expr + sampler_name_suffix; |
| 12947 | else |
| 12948 | return img_expr.substr(0, index) + sampler_name_suffix + img_expr.substr(index); |
| 12949 | } |
| 12950 | |
| 12951 | string CompilerMSL::to_swizzle_expression(uint32_t id) |
| 12952 | { |
| 12953 | auto *combined = maybe_get<SPIRCombinedImageSampler>(id); |
| 12954 | |
| 12955 | auto expr = to_expression(combined ? combined->image : VariableID(id)); |
| 12956 | auto index = expr.find_first_of('['); |
| 12957 | |
| 12958 | // If an image is part of an argument buffer translate this to a legal identifier. |
| 12959 | string::size_type period = 0; |
| 12960 | while ((period = expr.find_first_of('.', period)) != string::npos && period < index) |
| 12961 | expr[period] = '_'; |
| 12962 | |
| 12963 | if (index == string::npos) |
| 12964 | return expr + swizzle_name_suffix; |
| 12965 | else |
| 12966 | { |
| 12967 | auto image_expr = expr.substr(0, index); |
| 12968 | auto array_expr = expr.substr(index); |
| 12969 | return image_expr + swizzle_name_suffix + array_expr; |
| 12970 | } |
| 12971 | } |
| 12972 | |
| 12973 | string CompilerMSL::to_buffer_size_expression(uint32_t id) |
| 12974 | { |
| 12975 | auto expr = to_expression(id); |
| 12976 | auto index = expr.find_first_of('['); |
| 12977 | |
| 12978 | // This is quite crude, but we need to translate the reference name (*spvDescriptorSetN.name) to |
| 12979 | // the pointer expression spvDescriptorSetN.name to make a reasonable expression here. |
| 12980 | // This only happens if we have argument buffers and we are using OpArrayLength on a lone SSBO in that set. |
| 12981 | if (expr.size() >= 3 && expr[0] == '(' && expr[1] == '*') |
| 12982 | expr = address_of_expression(expr); |
| 12983 | |
| 12984 | // If a buffer is part of an argument buffer translate this to a legal identifier. |
| 12985 | for (auto &c : expr) |
| 12986 | if (c == '.') |
| 12987 | c = '_'; |
| 12988 | |
| 12989 | if (index == string::npos) |
| 12990 | return expr + buffer_size_name_suffix; |
| 12991 | else |
| 12992 | { |
| 12993 | auto buffer_expr = expr.substr(0, index); |
| 12994 | auto array_expr = expr.substr(index); |
| 12995 | if (auto var = maybe_get_backing_variable(id)) |
| 12996 | { |
| 12997 | if (is_var_runtime_size_array(*var)) |
| 12998 | { |
| 12999 | if (!msl_options.runtime_array_rich_descriptor) |
| 13000 | SPIRV_CROSS_THROW("OpArrayLength requires rich descriptor format"); |
| 13001 | |
| 13002 | auto last_pos = array_expr.find_last_of(']'); |
| 13003 | if (last_pos != std::string::npos) |
| 13004 | return buffer_expr + ".length(" + array_expr.substr(1, last_pos - 1) + ")"; |
| 13005 | } |
| 13006 | } |
| 13007 | return buffer_expr + buffer_size_name_suffix + array_expr; |
| 13008 | } |
| 13009 | } |
| 13010 | |
| 13011 | // Checks whether the type is a Block all of whose members have DecorationPatch. |
| 13012 | bool CompilerMSL::is_patch_block(const SPIRType &type) |
| 13013 | { |
| 13014 | if (!has_decoration(type.self, DecorationBlock)) |
| 13015 | return false; |
| 13016 | |
| 13017 | for (uint32_t i = 0; i < type.member_types.size(); i++) |
| 13018 | { |
| 13019 | if (!has_member_decoration(type.self, i, DecorationPatch)) |
| 13020 | return false; |
| 13021 | } |
| 13022 | |
| 13023 | return true; |
| 13024 | } |
| 13025 | |
| 13026 | // Checks whether the ID is a row_major matrix that requires conversion before use |
| 13027 | bool CompilerMSL::is_non_native_row_major_matrix(uint32_t id) |
| 13028 | { |
| 13029 | auto *e = maybe_get<SPIRExpression>(id); |
| 13030 | if (e) |
| 13031 | return e->need_transpose; |
| 13032 | else |
| 13033 | return has_decoration(id, DecorationRowMajor); |
| 13034 | } |
| 13035 | |
| 13036 | // Checks whether the member is a row_major matrix that requires conversion before use |
| 13037 | bool CompilerMSL::member_is_non_native_row_major_matrix(const SPIRType &type, uint32_t index) |
| 13038 | { |
| 13039 | return has_member_decoration(type.self, index, DecorationRowMajor); |
| 13040 | } |
| 13041 | |
| 13042 | string CompilerMSL::convert_row_major_matrix(string exp_str, const SPIRType &exp_type, uint32_t physical_type_id, |
| 13043 | bool is_packed, bool relaxed) |
| 13044 | { |
| 13045 | if (!is_matrix(exp_type)) |
| 13046 | { |
| 13047 | return CompilerGLSL::convert_row_major_matrix(std::move(exp_str), exp_type, physical_type_id, is_packed, relaxed); |
| 13048 | } |
| 13049 | else |
| 13050 | { |
| 13051 | strip_enclosed_expression(exp_str); |
| 13052 | if (physical_type_id != 0 || is_packed) |
| 13053 | exp_str = unpack_expression_type(exp_str, exp_type, physical_type_id, is_packed, true); |
| 13054 | return join("transpose(", exp_str, ")"); |
| 13055 | } |
| 13056 | } |
| 13057 | |
| 13058 | // Called automatically at the end of the entry point function |
| 13059 | void CompilerMSL::emit_fixup() |
| 13060 | { |
| 13061 | if (is_vertex_like_shader() && stage_out_var_id && !qual_pos_var_name.empty() && !capture_output_to_buffer) |
| 13062 | { |
| 13063 | if (msl_options.enable_point_size_default && !writes_to_point_size) |
| 13064 | statement(builtin_to_glsl(BuiltInPointSize, StorageClassOutput), " = ", format_float(msl_options.default_point_size), ";"); |
| 13065 | |
| 13066 | if (options.vertex.fixup_clipspace) |
| 13067 | statement(qual_pos_var_name, ".z = (", qual_pos_var_name, ".z + ", qual_pos_var_name, |
| 13068 | ".w) * 0.5; // Adjust clip-space for Metal"); |
| 13069 | |
| 13070 | if (options.vertex.flip_vert_y) |
| 13071 | statement(qual_pos_var_name, ".y = -(", qual_pos_var_name, ".y);", " // Invert Y-axis for Metal"); |
| 13072 | } |
| 13073 | } |
| 13074 | |
| 13075 | // Return a string defining a structure member, with padding and packing. |
| 13076 | string CompilerMSL::to_struct_member(const SPIRType &type, uint32_t member_type_id, uint32_t index, |
| 13077 | const string &qualifier) |
| 13078 | { |
| 13079 | uint32_t orig_member_type_id = member_type_id; |
| 13080 | if (member_is_remapped_physical_type(type, index)) |
| 13081 | member_type_id = get_extended_member_decoration(type.self, index, SPIRVCrossDecorationPhysicalTypeID); |
| 13082 | auto &physical_type = get<SPIRType>(member_type_id); |
| 13083 | |
| 13084 | // If this member is packed, mark it as so. |
| 13085 | string pack_pfx; |
| 13086 | |
| 13087 | // Allow Metal to use the array<T> template to make arrays a value type |
| 13088 | uint32_t orig_id = 0; |
| 13089 | if (has_extended_member_decoration(type.self, index, SPIRVCrossDecorationInterfaceOrigID)) |
| 13090 | orig_id = get_extended_member_decoration(type.self, index, SPIRVCrossDecorationInterfaceOrigID); |
| 13091 | |
| 13092 | bool row_major = false; |
| 13093 | if (is_matrix(physical_type)) |
| 13094 | row_major = has_member_decoration(type.self, index, DecorationRowMajor); |
| 13095 | |
| 13096 | SPIRType row_major_physical_type { OpTypeMatrix }; |
| 13097 | const SPIRType *declared_type = &physical_type; |
| 13098 | |
| 13099 | // If a struct is being declared with physical layout, |
| 13100 | // do not use array<T> wrappers. |
| 13101 | // This avoids a lot of complicated cases with packed vectors and matrices, |
| 13102 | // and generally we cannot copy full arrays in and out of buffers into Function |
| 13103 | // address space. |
| 13104 | // Array of resources should also be declared as builtin arrays. |
| 13105 | if (has_member_decoration(type.self, index, DecorationOffset)) |
| 13106 | is_using_builtin_array = true; |
| 13107 | else if (has_extended_member_decoration(type.self, index, SPIRVCrossDecorationResourceIndexPrimary)) |
| 13108 | is_using_builtin_array = true; |
| 13109 | |
| 13110 | if (member_is_packed_physical_type(type, index)) |
| 13111 | { |
| 13112 | // If we're packing a matrix, output an appropriate typedef |
| 13113 | if (physical_type.basetype == SPIRType::Struct) |
| 13114 | { |
| 13115 | SPIRV_CROSS_THROW("Cannot emit a packed struct currently."); |
| 13116 | } |
| 13117 | else if (is_matrix(physical_type)) |
| 13118 | { |
| 13119 | uint32_t rows = physical_type.vecsize; |
| 13120 | uint32_t cols = physical_type.columns; |
| 13121 | pack_pfx = "packed_"; |
| 13122 | if (row_major) |
| 13123 | { |
| 13124 | // These are stored transposed. |
| 13125 | rows = physical_type.columns; |
| 13126 | cols = physical_type.vecsize; |
| 13127 | pack_pfx = "packed_rm_"; |
| 13128 | } |
| 13129 | string base_type = physical_type.width == 16 ? "half" : "float"; |
| 13130 | string td_line = "typedef "; |
| 13131 | td_line += "packed_" + base_type + to_string(rows); |
| 13132 | td_line += " " + pack_pfx; |
| 13133 | // Use the actual matrix size here. |
| 13134 | td_line += base_type + to_string(physical_type.columns) + "x" + to_string(physical_type.vecsize); |
| 13135 | td_line += "[" + to_string(cols) + "]"; |
| 13136 | td_line += ";"; |
| 13137 | add_typedef_line(td_line); |
| 13138 | } |
| 13139 | else if (!is_scalar(physical_type)) // scalar type is already packed. |
| 13140 | pack_pfx = "packed_"; |
| 13141 | } |
| 13142 | else if (is_matrix(physical_type)) |
| 13143 | { |
| 13144 | if (!msl_options.supports_msl_version(3, 0) && |
| 13145 | has_extended_decoration(type.self, SPIRVCrossDecorationWorkgroupStruct)) |
| 13146 | { |
| 13147 | pack_pfx = "spvStorage_"; |
| 13148 | add_spv_func_and_recompile(SPVFuncImplStorageMatrix); |
| 13149 | // The pack prefix causes problems with array<T> wrappers. |
| 13150 | is_using_builtin_array = true; |
| 13151 | } |
| 13152 | if (row_major) |
| 13153 | { |
| 13154 | // Need to declare type with flipped vecsize/columns. |
| 13155 | row_major_physical_type = physical_type; |
| 13156 | swap(row_major_physical_type.vecsize, row_major_physical_type.columns); |
| 13157 | declared_type = &row_major_physical_type; |
| 13158 | } |
| 13159 | } |
| 13160 | |
| 13161 | // iOS Tier 1 argument buffers do not support writable images. |
| 13162 | if (physical_type.basetype == SPIRType::Image && |
| 13163 | physical_type.image.sampled == 2 && |
| 13164 | msl_options.is_ios() && |
| 13165 | msl_options.argument_buffers_tier <= Options::ArgumentBuffersTier::Tier1 && |
| 13166 | !has_decoration(orig_id, DecorationNonWritable)) |
| 13167 | { |
| 13168 | SPIRV_CROSS_THROW("Writable images are not allowed on Tier1 argument buffers on iOS."); |
| 13169 | } |
| 13170 | |
| 13171 | // Array information is baked into these types. |
| 13172 | string array_type; |
| 13173 | if (physical_type.basetype != SPIRType::Image && physical_type.basetype != SPIRType::Sampler && |
| 13174 | physical_type.basetype != SPIRType::SampledImage) |
| 13175 | { |
| 13176 | BuiltIn builtin = BuiltInMax; |
| 13177 | |
| 13178 | // Special handling. In [[stage_out]] or [[stage_in]] blocks, |
| 13179 | // we need flat arrays, but if we're somehow declaring gl_PerVertex for constant array reasons, we want |
| 13180 | // template array types to be declared. |
| 13181 | bool is_ib_in_out = |
| 13182 | ((stage_out_var_id && get_stage_out_struct_type().self == type.self && |
| 13183 | variable_storage_requires_stage_io(StorageClassOutput)) || |
| 13184 | (stage_in_var_id && get_stage_in_struct_type().self == type.self && |
| 13185 | variable_storage_requires_stage_io(StorageClassInput))) || |
| 13186 | is_mesh_shader(); |
| 13187 | if (is_ib_in_out && is_member_builtin(type, index, &builtin)) |
| 13188 | is_using_builtin_array = true; |
| 13189 | array_type = type_to_array_glsl(physical_type, orig_id); |
| 13190 | } |
| 13191 | |
| 13192 | if (is_mesh_shader()) |
| 13193 | { |
| 13194 | BuiltIn builtin = BuiltInMax; |
| 13195 | if (is_member_builtin(type, index, &builtin)) |
| 13196 | { |
| 13197 | if (builtin == BuiltInPrimitiveShadingRateKHR) |
| 13198 | { |
| 13199 | // not supported in metal 3.0 |
| 13200 | is_using_builtin_array = false; |
| 13201 | return ""; |
| 13202 | } |
| 13203 | |
| 13204 | SPIRType metallic_type = *declared_type; |
| 13205 | if (builtin == BuiltInCullPrimitiveEXT) |
| 13206 | metallic_type.basetype = SPIRType::Boolean; |
| 13207 | else if (builtin == BuiltInPrimitiveId || builtin == BuiltInLayer || builtin == BuiltInViewportIndex) |
| 13208 | metallic_type.basetype = SPIRType::UInt; |
| 13209 | |
| 13210 | is_using_builtin_array = true; |
| 13211 | std::string result; |
| 13212 | if (has_member_decoration(type.self, orig_id, DecorationBuiltIn)) |
| 13213 | { |
| 13214 | // avoid '_RESERVED_IDENTIFIER_FIXUP_' in variable name |
| 13215 | result = join(type_to_glsl(metallic_type, orig_id, false), " ", qualifier, |
| 13216 | builtin_to_glsl(builtin, StorageClassOutput), member_attribute_qualifier(type, index), |
| 13217 | array_type, ";"); |
| 13218 | } |
| 13219 | else |
| 13220 | { |
| 13221 | result = join(type_to_glsl(metallic_type, orig_id, false), " ", qualifier, |
| 13222 | to_member_name(type, index), member_attribute_qualifier(type, index), array_type, ";"); |
| 13223 | } |
| 13224 | is_using_builtin_array = false; |
| 13225 | return result; |
| 13226 | } |
| 13227 | } |
| 13228 | |
| 13229 | if (orig_id) |
| 13230 | { |
| 13231 | auto *data_type = declared_type; |
| 13232 | if (is_pointer(*data_type)) |
| 13233 | data_type = &get_pointee_type(*data_type); |
| 13234 | |
| 13235 | if (is_array(*data_type) && get_resource_array_size(*data_type, orig_id) == 0) |
| 13236 | { |
| 13237 | // Hack for declaring unsized array of resources. Need to declare dummy sized array by value inline. |
| 13238 | // This can then be wrapped in spvDescriptorArray as usual. |
| 13239 | array_type = "[1] /* unsized array hack */"; |
| 13240 | } |
| 13241 | } |
| 13242 | |
| 13243 | string decl_type; |
| 13244 | if (declared_type->vecsize > 4) |
| 13245 | { |
| 13246 | auto orig_type = get<SPIRType>(orig_member_type_id); |
| 13247 | if (is_matrix(orig_type) && row_major) |
| 13248 | swap(orig_type.vecsize, orig_type.columns); |
| 13249 | orig_type.columns = 1; |
| 13250 | decl_type = type_to_glsl(orig_type, orig_id, true); |
| 13251 | |
| 13252 | if (declared_type->columns > 1) |
| 13253 | decl_type = join("spvPaddedStd140Matrix<", decl_type, ", ", declared_type->columns, ">"); |
| 13254 | else |
| 13255 | decl_type = join("spvPaddedStd140<", decl_type, ">"); |
| 13256 | } |
| 13257 | else |
| 13258 | decl_type = type_to_glsl(*declared_type, orig_id, true); |
| 13259 | |
| 13260 | const char *overlapping_binding_tag = |
| 13261 | has_extended_member_decoration(type.self, index, SPIRVCrossDecorationOverlappingBinding) ? |
| 13262 | "// Overlapping binding: " : ""; |
| 13263 | |
| 13264 | auto result = join(overlapping_binding_tag, pack_pfx, decl_type, " ", qualifier, |
| 13265 | to_member_name(type, index), member_attribute_qualifier(type, index), array_type, ";"); |
| 13266 | |
| 13267 | is_using_builtin_array = false; |
| 13268 | return result; |
| 13269 | } |
| 13270 | |
| 13271 | // Emit a structure member, padding and packing to maintain the correct memeber alignments. |
| 13272 | void CompilerMSL::emit_struct_member(const SPIRType &type, uint32_t member_type_id, uint32_t index, |
| 13273 | const string &qualifier, uint32_t) |
| 13274 | { |
| 13275 | // If this member requires padding to maintain its declared offset, emit a dummy padding member before it. |
| 13276 | if (has_extended_member_decoration(type.self, index, SPIRVCrossDecorationPaddingTarget)) |
| 13277 | { |
| 13278 | uint32_t pad_len = get_extended_member_decoration(type.self, index, SPIRVCrossDecorationPaddingTarget); |
| 13279 | statement("char _m", index, "_pad", "[", pad_len, "];"); |
| 13280 | } |
| 13281 | |
| 13282 | BuiltIn builtin = BuiltInMax; |
| 13283 | if (is_mesh_shader() && is_member_builtin(type, index, &builtin)) |
| 13284 | { |
| 13285 | if (!has_active_builtin(builtin, StorageClassOutput) && !has_active_builtin(builtin, StorageClassInput)) |
| 13286 | { |
| 13287 | // Do not emit unused builtins in mesh-output blocks |
| 13288 | return; |
| 13289 | } |
| 13290 | } |
| 13291 | |
| 13292 | // Handle HLSL-style 0-based vertex/instance index. |
| 13293 | builtin_declaration = true; |
| 13294 | statement(to_struct_member(type, member_type_id, index, qualifier)); |
| 13295 | builtin_declaration = false; |
| 13296 | } |
| 13297 | |
| 13298 | void CompilerMSL::emit_struct_padding_target(const SPIRType &type) |
| 13299 | { |
| 13300 | uint32_t struct_size = get_declared_struct_size_msl(type, true, true); |
| 13301 | uint32_t target_size = get_extended_decoration(type.self, SPIRVCrossDecorationPaddingTarget); |
| 13302 | if (target_size < struct_size) |
| 13303 | SPIRV_CROSS_THROW("Cannot pad with negative bytes."); |
| 13304 | else if (target_size > struct_size) |
| 13305 | statement("char _m0_final_padding[", target_size - struct_size, "];"); |
| 13306 | } |
| 13307 | |
| 13308 | // Return a MSL qualifier for the specified function attribute member |
| 13309 | string CompilerMSL::member_attribute_qualifier(const SPIRType &type, uint32_t index) |
| 13310 | { |
| 13311 | auto &execution = get_entry_point(); |
| 13312 | |
| 13313 | uint32_t mbr_type_id = type.member_types[index]; |
| 13314 | auto &mbr_type = get<SPIRType>(mbr_type_id); |
| 13315 | |
| 13316 | BuiltIn builtin = BuiltInMax; |
| 13317 | bool is_builtin = is_member_builtin(type, index, &builtin); |
| 13318 | |
| 13319 | if (has_extended_member_decoration(type.self, index, SPIRVCrossDecorationResourceIndexPrimary)) |
| 13320 | { |
| 13321 | string quals = join( |
| 13322 | " [[id(", get_extended_member_decoration(type.self, index, SPIRVCrossDecorationResourceIndexPrimary), ")"); |
| 13323 | if (interlocked_resources.count( |
| 13324 | get_extended_member_decoration(type.self, index, SPIRVCrossDecorationInterfaceOrigID))) |
| 13325 | quals += ", raster_order_group(0)"; |
| 13326 | quals += "]]"; |
| 13327 | return quals; |
| 13328 | } |
| 13329 | |
| 13330 | // Vertex function inputs |
| 13331 | if (execution.model == ExecutionModelVertex && type.storage == StorageClassInput) |
| 13332 | { |
| 13333 | if (is_builtin) |
| 13334 | { |
| 13335 | switch (builtin) |
| 13336 | { |
| 13337 | case BuiltInVertexId: |
| 13338 | case BuiltInVertexIndex: |
| 13339 | case BuiltInBaseVertex: |
| 13340 | case BuiltInInstanceId: |
| 13341 | case BuiltInInstanceIndex: |
| 13342 | case BuiltInBaseInstance: |
| 13343 | if (msl_options.vertex_for_tessellation) |
| 13344 | return ""; |
| 13345 | return string(" [[") + builtin_qualifier(builtin) + "]]"; |
| 13346 | |
| 13347 | case BuiltInDrawIndex: |
| 13348 | SPIRV_CROSS_THROW("DrawIndex is not supported in MSL."); |
| 13349 | |
| 13350 | default: |
| 13351 | return ""; |
| 13352 | } |
| 13353 | } |
| 13354 | |
| 13355 | uint32_t locn; |
| 13356 | if (is_builtin) |
| 13357 | locn = get_or_allocate_builtin_input_member_location(builtin, type.self, index); |
| 13358 | else |
| 13359 | locn = get_member_location(type.self, index); |
| 13360 | |
| 13361 | if (locn != k_unknown_location) |
| 13362 | return string(" [[attribute(") + convert_to_string(locn) + ")]]"; |
| 13363 | } |
| 13364 | |
| 13365 | bool use_semantic_stage_output = is_mesh_shader() || is_tese_shader() || |
| 13366 | (execution.model == ExecutionModelVertex && !msl_options.vertex_for_tessellation); |
| 13367 | |
| 13368 | // Vertex, mesh and tessellation evaluation function outputs |
| 13369 | if ((type.storage == StorageClassOutput || is_mesh_shader()) && use_semantic_stage_output) |
| 13370 | { |
| 13371 | if (is_builtin) |
| 13372 | { |
| 13373 | switch (builtin) |
| 13374 | { |
| 13375 | case BuiltInPointSize: |
| 13376 | // Only mark the PointSize builtin if really rendering points. |
| 13377 | // Some shaders may include a PointSize builtin even when used to render |
| 13378 | // non-point topologies, and Metal will reject this builtin when compiling |
| 13379 | // the shader into a render pipeline that uses a non-point topology. |
| 13380 | return msl_options.enable_point_size_builtin ? (string(" [[") + builtin_qualifier(builtin) + "]]") : ""; |
| 13381 | |
| 13382 | case BuiltInViewportIndex: |
| 13383 | if (!msl_options.supports_msl_version(2, 0)) |
| 13384 | SPIRV_CROSS_THROW("ViewportIndex requires Metal 2.0."); |
| 13385 | /* fallthrough */ |
| 13386 | case BuiltInPosition: |
| 13387 | case BuiltInLayer: |
| 13388 | case BuiltInCullPrimitiveEXT: |
| 13389 | case BuiltInPrimitiveShadingRateKHR: |
| 13390 | case BuiltInPrimitiveId: |
| 13391 | return string(" [[") + builtin_qualifier(builtin) + "]]" + (mbr_type.array.empty() ? "" : " "); |
| 13392 | |
| 13393 | case BuiltInClipDistance: |
| 13394 | if (has_member_decoration(type.self, index, DecorationIndex)) |
| 13395 | return join(" [[user(clip", get_member_decoration(type.self, index, DecorationIndex), ")]]"); |
| 13396 | else |
| 13397 | return string(" [[") + builtin_qualifier(builtin) + "]]" + (mbr_type.array.empty() ? "" : " "); |
| 13398 | |
| 13399 | case BuiltInCullDistance: |
| 13400 | if (has_member_decoration(type.self, index, DecorationIndex)) |
| 13401 | return join(" [[user(cull", get_member_decoration(type.self, index, DecorationIndex), ")]]"); |
| 13402 | else |
| 13403 | return string(" [[") + builtin_qualifier(builtin) + "]]" + (mbr_type.array.empty() ? "" : " "); |
| 13404 | |
| 13405 | default: |
| 13406 | return ""; |
| 13407 | } |
| 13408 | } |
| 13409 | string loc_qual = member_location_attribute_qualifier(type, index); |
| 13410 | if (!loc_qual.empty()) |
| 13411 | return join(" [[", loc_qual, "]]"); |
| 13412 | } |
| 13413 | |
| 13414 | if (execution.model == ExecutionModelVertex && msl_options.vertex_for_tessellation && type.storage == StorageClassOutput) |
| 13415 | { |
| 13416 | // For this type of shader, we always arrange for it to capture its |
| 13417 | // output to a buffer. For this reason, qualifiers are irrelevant here. |
| 13418 | if (is_builtin) |
| 13419 | // We still have to assign a location so the output struct will sort correctly. |
| 13420 | get_or_allocate_builtin_output_member_location(builtin, type.self, index); |
| 13421 | return ""; |
| 13422 | } |
| 13423 | |
| 13424 | // Tessellation control function inputs |
| 13425 | if (is_tesc_shader() && type.storage == StorageClassInput) |
| 13426 | { |
| 13427 | if (is_builtin) |
| 13428 | { |
| 13429 | switch (builtin) |
| 13430 | { |
| 13431 | case BuiltInInvocationId: |
| 13432 | case BuiltInPrimitiveId: |
| 13433 | if (msl_options.multi_patch_workgroup) |
| 13434 | return ""; |
| 13435 | return string(" [[") + builtin_qualifier(builtin) + "]]" + (mbr_type.array.empty() ? "" : " "); |
| 13436 | case BuiltInSubgroupLocalInvocationId: // FIXME: Should work in any stage |
| 13437 | case BuiltInSubgroupSize: // FIXME: Should work in any stage |
| 13438 | if (msl_options.emulate_subgroups) |
| 13439 | return ""; |
| 13440 | return string(" [[") + builtin_qualifier(builtin) + "]]" + (mbr_type.array.empty() ? "" : " "); |
| 13441 | case BuiltInPatchVertices: |
| 13442 | return ""; |
| 13443 | // Others come from stage input. |
| 13444 | default: |
| 13445 | break; |
| 13446 | } |
| 13447 | } |
| 13448 | if (msl_options.multi_patch_workgroup) |
| 13449 | return ""; |
| 13450 | |
| 13451 | uint32_t locn; |
| 13452 | if (is_builtin) |
| 13453 | locn = get_or_allocate_builtin_input_member_location(builtin, type.self, index); |
| 13454 | else |
| 13455 | locn = get_member_location(type.self, index); |
| 13456 | |
| 13457 | if (locn != k_unknown_location) |
| 13458 | return string(" [[attribute(") + convert_to_string(locn) + ")]]"; |
| 13459 | } |
| 13460 | |
| 13461 | // Tessellation control function outputs |
| 13462 | if (is_tesc_shader() && type.storage == StorageClassOutput) |
| 13463 | { |
| 13464 | // For this type of shader, we always arrange for it to capture its |
| 13465 | // output to a buffer. For this reason, qualifiers are irrelevant here. |
| 13466 | if (is_builtin) |
| 13467 | // We still have to assign a location so the output struct will sort correctly. |
| 13468 | get_or_allocate_builtin_output_member_location(builtin, type.self, index); |
| 13469 | return ""; |
| 13470 | } |
| 13471 | |
| 13472 | // Tessellation evaluation function inputs |
| 13473 | if (is_tese_shader() && type.storage == StorageClassInput) |
| 13474 | { |
| 13475 | if (is_builtin) |
| 13476 | { |
| 13477 | switch (builtin) |
| 13478 | { |
| 13479 | case BuiltInPrimitiveId: |
| 13480 | case BuiltInTessCoord: |
| 13481 | return string(" [[") + builtin_qualifier(builtin) + "]]"; |
| 13482 | case BuiltInPatchVertices: |
| 13483 | return ""; |
| 13484 | // Others come from stage input. |
| 13485 | default: |
| 13486 | break; |
| 13487 | } |
| 13488 | } |
| 13489 | |
| 13490 | if (msl_options.raw_buffer_tese_input) |
| 13491 | return ""; |
| 13492 | |
| 13493 | // The special control point array must not be marked with an attribute. |
| 13494 | if (get_type(type.member_types[index]).basetype == SPIRType::ControlPointArray) |
| 13495 | return ""; |
| 13496 | |
| 13497 | uint32_t locn; |
| 13498 | if (is_builtin) |
| 13499 | locn = get_or_allocate_builtin_input_member_location(builtin, type.self, index); |
| 13500 | else |
| 13501 | locn = get_member_location(type.self, index); |
| 13502 | |
| 13503 | if (locn != k_unknown_location) |
| 13504 | return string(" [[attribute(") + convert_to_string(locn) + ")]]"; |
| 13505 | } |
| 13506 | |
| 13507 | // Tessellation evaluation function outputs were handled above. |
| 13508 | |
| 13509 | // Fragment function inputs |
| 13510 | if (execution.model == ExecutionModelFragment && type.storage == StorageClassInput) |
| 13511 | { |
| 13512 | string quals; |
| 13513 | if (is_builtin) |
| 13514 | { |
| 13515 | switch (builtin) |
| 13516 | { |
| 13517 | case BuiltInViewIndex: |
| 13518 | if (!msl_options.multiview || !msl_options.multiview_layered_rendering) |
| 13519 | break; |
| 13520 | /* fallthrough */ |
| 13521 | case BuiltInFrontFacing: |
| 13522 | case BuiltInPointCoord: |
| 13523 | case BuiltInFragCoord: |
| 13524 | case BuiltInSampleId: |
| 13525 | case BuiltInSampleMask: |
| 13526 | case BuiltInLayer: |
| 13527 | case BuiltInBaryCoordKHR: |
| 13528 | case BuiltInBaryCoordNoPerspKHR: |
| 13529 | quals = builtin_qualifier(builtin); |
| 13530 | break; |
| 13531 | |
| 13532 | case BuiltInClipDistance: |
| 13533 | return join(" [[user(clip", get_member_decoration(type.self, index, DecorationIndex), ")]]"); |
| 13534 | case BuiltInCullDistance: |
| 13535 | return join(" [[user(cull", get_member_decoration(type.self, index, DecorationIndex), ")]]"); |
| 13536 | |
| 13537 | default: |
| 13538 | break; |
| 13539 | } |
| 13540 | } |
| 13541 | else |
| 13542 | quals = member_location_attribute_qualifier(type, index); |
| 13543 | |
| 13544 | if (builtin == BuiltInBaryCoordKHR && has_member_decoration(type.self, index, DecorationNoPerspective)) |
| 13545 | { |
| 13546 | // NoPerspective is baked into the builtin type. |
| 13547 | SPIRV_CROSS_THROW("NoPerspective decorations are not supported for BaryCoord inputs."); |
| 13548 | } |
| 13549 | |
| 13550 | // Don't bother decorating integers with the 'flat' attribute; it's |
| 13551 | // the default (in fact, the only option). Also don't bother with the |
| 13552 | // FragCoord builtin; it's always noperspective on Metal. |
| 13553 | if (!type_is_integral(mbr_type) && (!is_builtin || builtin != BuiltInFragCoord)) |
| 13554 | { |
| 13555 | if (has_member_decoration(type.self, index, DecorationFlat)) |
| 13556 | { |
| 13557 | if (!quals.empty()) |
| 13558 | quals += ", "; |
| 13559 | quals += "flat"; |
| 13560 | } |
| 13561 | else if (has_member_decoration(type.self, index, DecorationCentroid)) |
| 13562 | { |
| 13563 | if (!quals.empty()) |
| 13564 | quals += ", "; |
| 13565 | |
| 13566 | if (builtin == BuiltInBaryCoordNoPerspKHR || builtin == BuiltInBaryCoordKHR) |
| 13567 | SPIRV_CROSS_THROW("Centroid interpolation not supported for barycentrics in MSL."); |
| 13568 | |
| 13569 | if (has_member_decoration(type.self, index, DecorationNoPerspective)) |
| 13570 | quals += "centroid_no_perspective"; |
| 13571 | else |
| 13572 | quals += "centroid_perspective"; |
| 13573 | } |
| 13574 | else if (has_member_decoration(type.self, index, DecorationSample)) |
| 13575 | { |
| 13576 | if (!quals.empty()) |
| 13577 | quals += ", "; |
| 13578 | |
| 13579 | if (builtin == BuiltInBaryCoordNoPerspKHR || builtin == BuiltInBaryCoordKHR) |
| 13580 | SPIRV_CROSS_THROW("Sample interpolation not supported for barycentrics in MSL."); |
| 13581 | |
| 13582 | if (has_member_decoration(type.self, index, DecorationNoPerspective)) |
| 13583 | quals += "sample_no_perspective"; |
| 13584 | else |
| 13585 | quals += "sample_perspective"; |
| 13586 | } |
| 13587 | else if (has_member_decoration(type.self, index, DecorationNoPerspective) || builtin == BuiltInBaryCoordNoPerspKHR) |
| 13588 | { |
| 13589 | if (!quals.empty()) |
| 13590 | quals += ", "; |
| 13591 | quals += "center_no_perspective"; |
| 13592 | } |
| 13593 | else if (builtin == BuiltInBaryCoordKHR) |
| 13594 | { |
| 13595 | if (!quals.empty()) |
| 13596 | quals += ", "; |
| 13597 | quals += "center_perspective"; |
| 13598 | } |
| 13599 | } |
| 13600 | |
| 13601 | if (!quals.empty()) |
| 13602 | return " [[" + quals + "]]"; |
| 13603 | } |
| 13604 | |
| 13605 | // Fragment function outputs |
| 13606 | if (execution.model == ExecutionModelFragment && type.storage == StorageClassOutput) |
| 13607 | { |
| 13608 | if (is_builtin) |
| 13609 | { |
| 13610 | switch (builtin) |
| 13611 | { |
| 13612 | case BuiltInFragStencilRefEXT: |
| 13613 | // Similar to PointSize, only mark FragStencilRef if there's a stencil buffer. |
| 13614 | // Some shaders may include a FragStencilRef builtin even when used to render |
| 13615 | // without a stencil attachment, and Metal will reject this builtin |
| 13616 | // when compiling the shader into a render pipeline that does not set |
| 13617 | // stencilAttachmentPixelFormat. |
| 13618 | if (!msl_options.enable_frag_stencil_ref_builtin) |
| 13619 | return ""; |
| 13620 | if (!msl_options.supports_msl_version(2, 1)) |
| 13621 | SPIRV_CROSS_THROW("Stencil export only supported in MSL 2.1 and up."); |
| 13622 | return string(" [[") + builtin_qualifier(builtin) + "]]"; |
| 13623 | |
| 13624 | case BuiltInFragDepth: |
| 13625 | // Ditto FragDepth. |
| 13626 | if (!msl_options.enable_frag_depth_builtin) |
| 13627 | return ""; |
| 13628 | /* fallthrough */ |
| 13629 | case BuiltInSampleMask: |
| 13630 | return string(" [[") + builtin_qualifier(builtin) + "]]"; |
| 13631 | |
| 13632 | default: |
| 13633 | return ""; |
| 13634 | } |
| 13635 | } |
| 13636 | uint32_t locn = get_member_location(type.self, index); |
| 13637 | // Metal will likely complain about missing color attachments, too. |
| 13638 | if (locn != k_unknown_location && !(msl_options.enable_frag_output_mask & (1 << locn))) |
| 13639 | return ""; |
| 13640 | if (locn != k_unknown_location && has_member_decoration(type.self, index, DecorationIndex)) |
| 13641 | return join(" [[color(", locn, "), index(", get_member_decoration(type.self, index, DecorationIndex), |
| 13642 | ")]]"); |
| 13643 | else if (locn != k_unknown_location) |
| 13644 | return join(" [[color(", locn, ")]]"); |
| 13645 | else if (has_member_decoration(type.self, index, DecorationIndex)) |
| 13646 | return join(" [[index(", get_member_decoration(type.self, index, DecorationIndex), ")]]"); |
| 13647 | else |
| 13648 | return ""; |
| 13649 | } |
| 13650 | |
| 13651 | // Compute function inputs |
| 13652 | if (execution.model == ExecutionModelGLCompute && type.storage == StorageClassInput) |
| 13653 | { |
| 13654 | if (is_builtin) |
| 13655 | { |
| 13656 | switch (builtin) |
| 13657 | { |
| 13658 | case BuiltInNumSubgroups: |
| 13659 | case BuiltInSubgroupId: |
| 13660 | case BuiltInSubgroupLocalInvocationId: // FIXME: Should work in any stage |
| 13661 | case BuiltInSubgroupSize: // FIXME: Should work in any stage |
| 13662 | if (msl_options.emulate_subgroups) |
| 13663 | break; |
| 13664 | /* fallthrough */ |
| 13665 | case BuiltInGlobalInvocationId: |
| 13666 | case BuiltInWorkgroupId: |
| 13667 | case BuiltInNumWorkgroups: |
| 13668 | case BuiltInLocalInvocationId: |
| 13669 | case BuiltInLocalInvocationIndex: |
| 13670 | return string(" [[") + builtin_qualifier(builtin) + "]]"; |
| 13671 | |
| 13672 | default: |
| 13673 | return ""; |
| 13674 | } |
| 13675 | } |
| 13676 | } |
| 13677 | |
| 13678 | return ""; |
| 13679 | } |
| 13680 | |
| 13681 | // A user-defined output variable is considered to match an input variable in the subsequent |
| 13682 | // stage if the two variables are declared with the same Location and Component decoration and |
| 13683 | // match in type and decoration, except that interpolation decorations are not required to match. |
| 13684 | // For the purposes of interface matching, variables declared without a Component decoration are |
| 13685 | // considered to have a Component decoration of zero. |
| 13686 | string CompilerMSL::member_location_attribute_qualifier(const SPIRType &type, uint32_t index) |
| 13687 | { |
| 13688 | string quals; |
| 13689 | uint32_t comp; |
| 13690 | uint32_t locn = get_member_location(type.self, index, &comp); |
| 13691 | if (locn != k_unknown_location) |
| 13692 | { |
| 13693 | quals += "user(locn"; |
| 13694 | quals += convert_to_string(locn); |
| 13695 | if (comp != k_unknown_component && comp != 0) |
| 13696 | { |
| 13697 | quals += "_"; |
| 13698 | quals += convert_to_string(comp); |
| 13699 | } |
| 13700 | quals += ")"; |
| 13701 | } |
| 13702 | return quals; |
| 13703 | } |
| 13704 | |
| 13705 | // Returns the location decoration of the member with the specified index in the specified type. |
| 13706 | // If the location of the member has been explicitly set, that location is used. If not, this |
| 13707 | // function assumes the members are ordered in their location order, and simply returns the |
| 13708 | // index as the location. |
| 13709 | uint32_t CompilerMSL::get_member_location(uint32_t type_id, uint32_t index, uint32_t *comp) const |
| 13710 | { |
| 13711 | if (comp) |
| 13712 | { |
| 13713 | if (has_member_decoration(type_id, index, DecorationComponent)) |
| 13714 | *comp = get_member_decoration(type_id, index, DecorationComponent); |
| 13715 | else |
| 13716 | *comp = k_unknown_component; |
| 13717 | } |
| 13718 | |
| 13719 | if (has_member_decoration(type_id, index, DecorationLocation)) |
| 13720 | return get_member_decoration(type_id, index, DecorationLocation); |
| 13721 | else |
| 13722 | return k_unknown_location; |
| 13723 | } |
| 13724 | |
| 13725 | uint32_t CompilerMSL::get_or_allocate_builtin_input_member_location(spv::BuiltIn builtin, |
| 13726 | uint32_t type_id, uint32_t index, |
| 13727 | uint32_t *comp) |
| 13728 | { |
| 13729 | uint32_t loc = get_member_location(type_id, index, comp); |
| 13730 | if (loc != k_unknown_location) |
| 13731 | return loc; |
| 13732 | |
| 13733 | if (comp) |
| 13734 | *comp = k_unknown_component; |
| 13735 | |
| 13736 | // Late allocation. Find a location which is unused by the application. |
| 13737 | // This can happen for built-in inputs in tessellation which are mixed and matched with user inputs. |
| 13738 | auto &mbr_type = get<SPIRType>(get<SPIRType>(type_id).member_types[index]); |
| 13739 | uint32_t count = type_to_location_count(mbr_type); |
| 13740 | |
| 13741 | loc = 0; |
| 13742 | |
| 13743 | const auto location_range_in_use = [this](uint32_t location, uint32_t location_count) -> bool { |
| 13744 | for (uint32_t i = 0; i < location_count; i++) |
| 13745 | if (location_inputs_in_use.count(location + i) != 0) |
| 13746 | return true; |
| 13747 | return false; |
| 13748 | }; |
| 13749 | |
| 13750 | while (location_range_in_use(loc, count)) |
| 13751 | loc++; |
| 13752 | |
| 13753 | set_member_decoration(type_id, index, DecorationLocation, loc); |
| 13754 | |
| 13755 | // Triangle tess level inputs are shared in one packed float4, |
| 13756 | // mark both builtins as sharing one location. |
| 13757 | if (!msl_options.raw_buffer_tese_input && is_tessellating_triangles() && |
| 13758 | (builtin == BuiltInTessLevelInner || builtin == BuiltInTessLevelOuter)) |
| 13759 | { |
| 13760 | builtin_to_automatic_input_location[BuiltInTessLevelInner] = loc; |
| 13761 | builtin_to_automatic_input_location[BuiltInTessLevelOuter] = loc; |
| 13762 | } |
| 13763 | else |
| 13764 | builtin_to_automatic_input_location[builtin] = loc; |
| 13765 | |
| 13766 | mark_location_as_used_by_shader(loc, mbr_type, StorageClassInput, true); |
| 13767 | return loc; |
| 13768 | } |
| 13769 | |
| 13770 | uint32_t CompilerMSL::get_or_allocate_builtin_output_member_location(spv::BuiltIn builtin, |
| 13771 | uint32_t type_id, uint32_t index, |
| 13772 | uint32_t *comp) |
| 13773 | { |
| 13774 | uint32_t loc = get_member_location(type_id, index, comp); |
| 13775 | if (loc != k_unknown_location) |
| 13776 | return loc; |
| 13777 | loc = 0; |
| 13778 | |
| 13779 | if (comp) |
| 13780 | *comp = k_unknown_component; |
| 13781 | |
| 13782 | // Late allocation. Find a location which is unused by the application. |
| 13783 | // This can happen for built-in outputs in tessellation which are mixed and matched with user inputs. |
| 13784 | auto &mbr_type = get<SPIRType>(get<SPIRType>(type_id).member_types[index]); |
| 13785 | uint32_t count = type_to_location_count(mbr_type); |
| 13786 | |
| 13787 | const auto location_range_in_use = [this](uint32_t location, uint32_t location_count) -> bool { |
| 13788 | for (uint32_t i = 0; i < location_count; i++) |
| 13789 | if (location_outputs_in_use.count(location + i) != 0) |
| 13790 | return true; |
| 13791 | return false; |
| 13792 | }; |
| 13793 | |
| 13794 | while (location_range_in_use(loc, count)) |
| 13795 | loc++; |
| 13796 | |
| 13797 | set_member_decoration(type_id, index, DecorationLocation, loc); |
| 13798 | |
| 13799 | // Triangle tess level inputs are shared in one packed float4; |
| 13800 | // mark both builtins as sharing one location. |
| 13801 | if (is_tessellating_triangles() && (builtin == BuiltInTessLevelInner || builtin == BuiltInTessLevelOuter)) |
| 13802 | { |
| 13803 | builtin_to_automatic_output_location[BuiltInTessLevelInner] = loc; |
| 13804 | builtin_to_automatic_output_location[BuiltInTessLevelOuter] = loc; |
| 13805 | } |
| 13806 | else |
| 13807 | builtin_to_automatic_output_location[builtin] = loc; |
| 13808 | |
| 13809 | mark_location_as_used_by_shader(loc, mbr_type, StorageClassOutput, true); |
| 13810 | return loc; |
| 13811 | } |
| 13812 | |
| 13813 | // Returns the type declaration for a function, including the |
| 13814 | // entry type if the current function is the entry point function |
| 13815 | string CompilerMSL::func_type_decl(SPIRType &type) |
| 13816 | { |
| 13817 | // The regular function return type. If not processing the entry point function, that's all we need |
| 13818 | string return_type = type_to_glsl(type) + type_to_array_glsl(type, 0); |
| 13819 | if (!processing_entry_point) |
| 13820 | return return_type; |
| 13821 | |
| 13822 | // If an outgoing interface block has been defined, and it should be returned, override the entry point return type |
| 13823 | bool ep_should_return_output = !get_is_rasterization_disabled(); |
| 13824 | if (stage_out_var_id && ep_should_return_output) |
| 13825 | return_type = type_to_glsl(get_stage_out_struct_type()) + type_to_array_glsl(type, 0); |
| 13826 | |
| 13827 | // Prepend a entry type, based on the execution model |
| 13828 | string entry_type; |
| 13829 | auto &execution = get_entry_point(); |
| 13830 | switch (execution.model) |
| 13831 | { |
| 13832 | case ExecutionModelVertex: |
| 13833 | if (msl_options.vertex_for_tessellation && !msl_options.supports_msl_version(1, 2)) |
| 13834 | SPIRV_CROSS_THROW("Tessellation requires Metal 1.2."); |
| 13835 | entry_type = msl_options.vertex_for_tessellation ? "kernel" : "vertex"; |
| 13836 | break; |
| 13837 | case ExecutionModelTessellationEvaluation: |
| 13838 | if (!msl_options.supports_msl_version(1, 2)) |
| 13839 | SPIRV_CROSS_THROW("Tessellation requires Metal 1.2."); |
| 13840 | if (execution.flags.get(ExecutionModeIsolines)) |
| 13841 | SPIRV_CROSS_THROW("Metal does not support isoline tessellation."); |
| 13842 | if (msl_options.is_ios()) |
| 13843 | entry_type = join("[[ patch(", is_tessellating_triangles() ? "triangle" : "quad", ") ]] vertex"); |
| 13844 | else |
| 13845 | entry_type = join("[[ patch(", is_tessellating_triangles() ? "triangle" : "quad", ", ", |
| 13846 | execution.output_vertices, ") ]] vertex"); |
| 13847 | break; |
| 13848 | case ExecutionModelFragment: |
| 13849 | entry_type = uses_explicit_early_fragment_test() ? "[[ early_fragment_tests ]] fragment" : "fragment"; |
| 13850 | break; |
| 13851 | case ExecutionModelTessellationControl: |
| 13852 | if (!msl_options.supports_msl_version(1, 2)) |
| 13853 | SPIRV_CROSS_THROW("Tessellation requires Metal 1.2."); |
| 13854 | if (execution.flags.get(ExecutionModeIsolines)) |
| 13855 | SPIRV_CROSS_THROW("Metal does not support isoline tessellation."); |
| 13856 | /* fallthrough */ |
| 13857 | case ExecutionModelGLCompute: |
| 13858 | case ExecutionModelKernel: |
| 13859 | entry_type = "kernel"; |
| 13860 | break; |
| 13861 | case ExecutionModelMeshEXT: |
| 13862 | entry_type = "[[mesh]]"; |
| 13863 | break; |
| 13864 | case ExecutionModelTaskEXT: |
| 13865 | entry_type = "[[object]]"; |
| 13866 | break; |
| 13867 | default: |
| 13868 | entry_type = "unknown"; |
| 13869 | break; |
| 13870 | } |
| 13871 | |
| 13872 | return entry_type + " " + return_type; |
| 13873 | } |
| 13874 | |
| 13875 | bool CompilerMSL::is_tesc_shader() const |
| 13876 | { |
| 13877 | return get_execution_model() == ExecutionModelTessellationControl; |
| 13878 | } |
| 13879 | |
| 13880 | bool CompilerMSL::is_tese_shader() const |
| 13881 | { |
| 13882 | return get_execution_model() == ExecutionModelTessellationEvaluation; |
| 13883 | } |
| 13884 | |
| 13885 | bool CompilerMSL::is_mesh_shader() const |
| 13886 | { |
| 13887 | return get_execution_model() == spv::ExecutionModelMeshEXT; |
| 13888 | } |
| 13889 | |
| 13890 | bool CompilerMSL::uses_explicit_early_fragment_test() |
| 13891 | { |
| 13892 | auto &ep_flags = get_entry_point().flags; |
| 13893 | return ep_flags.get(ExecutionModeEarlyFragmentTests) || ep_flags.get(ExecutionModePostDepthCoverage); |
| 13894 | } |
| 13895 | |
| 13896 | // In MSL, address space qualifiers are required for all pointer or reference variables |
| 13897 | string CompilerMSL::get_argument_address_space(const SPIRVariable &argument) |
| 13898 | { |
| 13899 | const auto &type = get<SPIRType>(argument.basetype); |
| 13900 | // BDA is always passed around by value. There is no storage class for the argument itself. |
| 13901 | if (is_physical_pointer(type)) |
| 13902 | return ""; |
| 13903 | return get_type_address_space(type, argument.self, true); |
| 13904 | } |
| 13905 | |
| 13906 | bool CompilerMSL::decoration_flags_signal_volatile(const Bitset &flags) const |
| 13907 | { |
| 13908 | // Using volatile for coherent pre-3.2 is definitely not correct, but it's something. |
| 13909 | // MSL 3.2 adds actual coherent qualifiers. |
| 13910 | return flags.get(DecorationVolatile) || |
| 13911 | (flags.get(DecorationCoherent) && !msl_options.supports_msl_version(3, 2)); |
| 13912 | } |
| 13913 | |
| 13914 | bool CompilerMSL::decoration_flags_signal_coherent(const Bitset &flags) const |
| 13915 | { |
| 13916 | return flags.get(DecorationCoherent) && msl_options.supports_msl_version(3, 2); |
| 13917 | } |
| 13918 | |
| 13919 | string CompilerMSL::get_type_address_space(const SPIRType &type, uint32_t id, bool argument) |
| 13920 | { |
| 13921 | // This can be called for variable pointer contexts as well, so be very careful about which method we choose. |
| 13922 | Bitset flags; |
| 13923 | auto *var = maybe_get<SPIRVariable>(id); |
| 13924 | if (var && type.basetype == SPIRType::Struct && |
| 13925 | (has_decoration(type.self, DecorationBlock) || has_decoration(type.self, DecorationBufferBlock))) |
| 13926 | flags = get_buffer_block_flags(id); |
| 13927 | else |
| 13928 | { |
| 13929 | flags = get_decoration_bitset(id); |
| 13930 | |
| 13931 | if (type.basetype == SPIRType::Struct && |
| 13932 | (has_decoration(type.self, DecorationBlock) || |
| 13933 | has_decoration(type.self, DecorationBufferBlock))) |
| 13934 | { |
| 13935 | flags.merge_or(ir.get_buffer_block_type_flags(type)); |
| 13936 | } |
| 13937 | } |
| 13938 | |
| 13939 | const char *addr_space = nullptr; |
| 13940 | switch (type.storage) |
| 13941 | { |
| 13942 | case StorageClassWorkgroup: |
| 13943 | addr_space = "threadgroup"; |
| 13944 | break; |
| 13945 | |
| 13946 | case StorageClassStorageBuffer: |
| 13947 | { |
| 13948 | // For arguments from variable pointers, we use the write count deduction, so |
| 13949 | // we should not assume any constness here. Only for global SSBOs. |
| 13950 | bool readonly = false; |
| 13951 | if (!var || has_decoration(type.self, DecorationBlock)) |
| 13952 | readonly = flags.get(DecorationNonWritable); |
| 13953 | |
| 13954 | if (decoration_flags_signal_coherent(flags)) |
| 13955 | readonly = false; |
| 13956 | |
| 13957 | addr_space = readonly ? "const device" : "device"; |
| 13958 | break; |
| 13959 | } |
| 13960 | |
| 13961 | case StorageClassPhysicalStorageBuffer: |
| 13962 | // We cannot fully trust NonWritable coming from glslang due to a bug in buffer_reference handling. |
| 13963 | // There isn't much gain in emitting const in C++ languages anyway. |
| 13964 | addr_space = "device"; |
| 13965 | break; |
| 13966 | |
| 13967 | case StorageClassUniform: |
| 13968 | case StorageClassUniformConstant: |
| 13969 | case StorageClassPushConstant: |
| 13970 | if (type.basetype == SPIRType::Struct) |
| 13971 | { |
| 13972 | bool ssbo = has_decoration(type.self, DecorationBufferBlock); |
| 13973 | if (ssbo) |
| 13974 | addr_space = flags.get(DecorationNonWritable) ? "const device" : "device"; |
| 13975 | else |
| 13976 | addr_space = "constant"; |
| 13977 | } |
| 13978 | else if (!argument) |
| 13979 | { |
| 13980 | addr_space = "constant"; |
| 13981 | } |
| 13982 | else if (type_is_msl_framebuffer_fetch(type)) |
| 13983 | { |
| 13984 | // Subpass inputs are passed around by value. |
| 13985 | addr_space = ""; |
| 13986 | } |
| 13987 | break; |
| 13988 | |
| 13989 | case StorageClassFunction: |
| 13990 | case StorageClassGeneric: |
| 13991 | break; |
| 13992 | |
| 13993 | case StorageClassInput: |
| 13994 | if (is_tesc_shader() && var && var->basevariable == stage_in_ptr_var_id) |
| 13995 | addr_space = msl_options.multi_patch_workgroup ? "const device" : "threadgroup"; |
| 13996 | // Don't pass tessellation levels in the device AS; we load and convert them |
| 13997 | // to float manually. |
| 13998 | if (is_tese_shader() && msl_options.raw_buffer_tese_input && var) |
| 13999 | { |
| 14000 | bool is_stage_in = var->basevariable == stage_in_ptr_var_id; |
| 14001 | bool is_patch_stage_in = has_decoration(var->self, DecorationPatch); |
| 14002 | bool is_builtin = has_decoration(var->self, DecorationBuiltIn); |
| 14003 | BuiltIn builtin = (BuiltIn)get_decoration(var->self, DecorationBuiltIn); |
| 14004 | bool is_tess_level = is_builtin && (builtin == BuiltInTessLevelOuter || builtin == BuiltInTessLevelInner); |
| 14005 | if (is_stage_in || (is_patch_stage_in && !is_tess_level)) |
| 14006 | addr_space = "const device"; |
| 14007 | } |
| 14008 | if (get_execution_model() == ExecutionModelFragment && var && var->basevariable == stage_in_var_id) |
| 14009 | addr_space = "thread"; |
| 14010 | break; |
| 14011 | |
| 14012 | case StorageClassOutput: |
| 14013 | if (capture_output_to_buffer) |
| 14014 | { |
| 14015 | if (var && type.storage == StorageClassOutput) |
| 14016 | { |
| 14017 | bool is_masked = is_stage_output_variable_masked(*var); |
| 14018 | |
| 14019 | if (is_masked) |
| 14020 | { |
| 14021 | if (is_tessellation_shader()) |
| 14022 | addr_space = "threadgroup"; |
| 14023 | else |
| 14024 | addr_space = "thread"; |
| 14025 | } |
| 14026 | else if (variable_decl_is_remapped_storage(*var, StorageClassWorkgroup)) |
| 14027 | addr_space = "threadgroup"; |
| 14028 | } |
| 14029 | |
| 14030 | if (!addr_space) |
| 14031 | addr_space = "device"; |
| 14032 | } |
| 14033 | |
| 14034 | if (is_mesh_shader()) |
| 14035 | addr_space = "threadgroup"; |
| 14036 | break; |
| 14037 | |
| 14038 | case StorageClassTaskPayloadWorkgroupEXT: |
| 14039 | if (is_mesh_shader()) |
| 14040 | addr_space = "const object_data"; |
| 14041 | else |
| 14042 | addr_space = "object_data"; |
| 14043 | break; |
| 14044 | |
| 14045 | default: |
| 14046 | break; |
| 14047 | } |
| 14048 | |
| 14049 | if (!addr_space) |
| 14050 | { |
| 14051 | // No address space for plain values. |
| 14052 | addr_space = type.pointer || (argument && type.basetype == SPIRType::ControlPointArray) ? "thread" : ""; |
| 14053 | } |
| 14054 | |
| 14055 | if (decoration_flags_signal_coherent(flags) && strcmp(addr_space, "device") == 0) |
| 14056 | return join("coherent device"); |
| 14057 | else if (decoration_flags_signal_volatile(flags) && strcmp(addr_space, "thread") != 0) |
| 14058 | return join("volatile ", addr_space); |
| 14059 | else |
| 14060 | return addr_space; |
| 14061 | } |
| 14062 | |
| 14063 | const char *CompilerMSL::to_restrict(uint32_t id, bool space) |
| 14064 | { |
| 14065 | // This can be called for variable pointer contexts as well, so be very careful about which method we choose. |
| 14066 | Bitset flags; |
| 14067 | if (ir.ids[id].get_type() == TypeVariable) |
| 14068 | { |
| 14069 | uint32_t type_id = expression_type_id(id); |
| 14070 | auto &type = expression_type(id); |
| 14071 | if (type.basetype == SPIRType::Struct && |
| 14072 | (has_decoration(type_id, DecorationBlock) || has_decoration(type_id, DecorationBufferBlock))) |
| 14073 | flags = get_buffer_block_flags(id); |
| 14074 | else |
| 14075 | flags = get_decoration_bitset(id); |
| 14076 | } |
| 14077 | else |
| 14078 | flags = get_decoration_bitset(id); |
| 14079 | |
| 14080 | return flags.get(DecorationRestrict) || flags.get(DecorationRestrictPointerEXT) ? |
| 14081 | (space ? "__restrict " : "__restrict") : ""; |
| 14082 | } |
| 14083 | |
| 14084 | string CompilerMSL::entry_point_arg_stage_in() |
| 14085 | { |
| 14086 | string decl; |
| 14087 | |
| 14088 | if ((is_tesc_shader() && msl_options.multi_patch_workgroup) || |
| 14089 | (is_tese_shader() && msl_options.raw_buffer_tese_input)) |
| 14090 | return decl; |
| 14091 | |
| 14092 | // Stage-in structure |
| 14093 | uint32_t stage_in_id; |
| 14094 | if (is_tese_shader()) |
| 14095 | stage_in_id = patch_stage_in_var_id; |
| 14096 | else |
| 14097 | stage_in_id = stage_in_var_id; |
| 14098 | |
| 14099 | if (stage_in_id) |
| 14100 | { |
| 14101 | auto &var = get<SPIRVariable>(stage_in_id); |
| 14102 | auto &type = get_variable_data_type(var); |
| 14103 | |
| 14104 | add_resource_name(var.self); |
| 14105 | decl = join(type_to_glsl(type), " ", to_name(var.self), " [[stage_in]]"); |
| 14106 | } |
| 14107 | |
| 14108 | return decl; |
| 14109 | } |
| 14110 | |
| 14111 | // Returns true if this input builtin should be a direct parameter on a shader function parameter list, |
| 14112 | // and false for builtins that should be passed or calculated some other way. |
| 14113 | bool CompilerMSL::is_direct_input_builtin(BuiltIn bi_type) |
| 14114 | { |
| 14115 | switch (bi_type) |
| 14116 | { |
| 14117 | // Vertex function in |
| 14118 | case BuiltInVertexId: |
| 14119 | case BuiltInVertexIndex: |
| 14120 | case BuiltInBaseVertex: |
| 14121 | case BuiltInInstanceId: |
| 14122 | case BuiltInInstanceIndex: |
| 14123 | case BuiltInBaseInstance: |
| 14124 | return get_execution_model() != ExecutionModelVertex || !msl_options.vertex_for_tessellation; |
| 14125 | // Tess. control function in |
| 14126 | case BuiltInPosition: |
| 14127 | case BuiltInPointSize: |
| 14128 | case BuiltInClipDistance: |
| 14129 | case BuiltInCullDistance: |
| 14130 | case BuiltInPatchVertices: |
| 14131 | return false; |
| 14132 | case BuiltInInvocationId: |
| 14133 | case BuiltInPrimitiveId: |
| 14134 | return !is_tesc_shader() || !msl_options.multi_patch_workgroup; |
| 14135 | // Tess. evaluation function in |
| 14136 | case BuiltInTessLevelInner: |
| 14137 | case BuiltInTessLevelOuter: |
| 14138 | return false; |
| 14139 | // Fragment function in |
| 14140 | case BuiltInSamplePosition: |
| 14141 | case BuiltInHelperInvocation: |
| 14142 | case BuiltInBaryCoordKHR: |
| 14143 | case BuiltInBaryCoordNoPerspKHR: |
| 14144 | return false; |
| 14145 | case BuiltInViewIndex: |
| 14146 | return get_execution_model() == ExecutionModelFragment && msl_options.multiview && |
| 14147 | msl_options.multiview_layered_rendering; |
| 14148 | // Compute function in |
| 14149 | case BuiltInSubgroupId: |
| 14150 | case BuiltInNumSubgroups: |
| 14151 | return !msl_options.emulate_subgroups; |
| 14152 | // Any stage function in |
| 14153 | case BuiltInDeviceIndex: |
| 14154 | case BuiltInSubgroupEqMask: |
| 14155 | case BuiltInSubgroupGeMask: |
| 14156 | case BuiltInSubgroupGtMask: |
| 14157 | case BuiltInSubgroupLeMask: |
| 14158 | case BuiltInSubgroupLtMask: |
| 14159 | return false; |
| 14160 | case BuiltInSubgroupSize: |
| 14161 | if (msl_options.fixed_subgroup_size != 0) |
| 14162 | return false; |
| 14163 | /* fallthrough */ |
| 14164 | case BuiltInSubgroupLocalInvocationId: |
| 14165 | return !msl_options.emulate_subgroups; |
| 14166 | default: |
| 14167 | return true; |
| 14168 | } |
| 14169 | } |
| 14170 | |
| 14171 | // Returns true if this is a fragment shader that runs per sample, and false otherwise. |
| 14172 | bool CompilerMSL::is_sample_rate() const |
| 14173 | { |
| 14174 | auto &caps = get_declared_capabilities(); |
| 14175 | return get_execution_model() == ExecutionModelFragment && |
| 14176 | (msl_options.force_sample_rate_shading || |
| 14177 | std::find(caps.begin(), caps.end(), CapabilitySampleRateShading) != caps.end() || |
| 14178 | (msl_options.use_framebuffer_fetch_subpasses && need_subpass_input_ms)); |
| 14179 | } |
| 14180 | |
| 14181 | bool CompilerMSL::is_intersection_query() const |
| 14182 | { |
| 14183 | auto &caps = get_declared_capabilities(); |
| 14184 | return std::find(caps.begin(), caps.end(), CapabilityRayQueryKHR) != caps.end(); |
| 14185 | } |
| 14186 | |
| 14187 | void CompilerMSL::entry_point_args_builtin(string &ep_args) |
| 14188 | { |
| 14189 | // Builtin variables |
| 14190 | SmallVector<pair<SPIRVariable *, BuiltIn>, 8> active_builtins; |
| 14191 | ir.for_each_typed_id<SPIRVariable>([&](uint32_t var_id, SPIRVariable &var) { |
| 14192 | if (var.storage != StorageClassInput) |
| 14193 | return; |
| 14194 | |
| 14195 | auto bi_type = BuiltIn(get_decoration(var_id, DecorationBuiltIn)); |
| 14196 | |
| 14197 | // Don't emit SamplePosition as a separate parameter. In the entry |
| 14198 | // point, we get that by calling get_sample_position() on the sample ID. |
| 14199 | if (is_builtin_variable(var) && |
| 14200 | get_variable_data_type(var).basetype != SPIRType::Struct && |
| 14201 | get_variable_data_type(var).basetype != SPIRType::ControlPointArray) |
| 14202 | { |
| 14203 | // If the builtin is not part of the active input builtin set, don't emit it. |
| 14204 | // Relevant for multiple entry-point modules which might declare unused builtins. |
| 14205 | if (!active_input_builtins.get(bi_type) || !interface_variable_exists_in_entry_point(var_id)) |
| 14206 | return; |
| 14207 | |
| 14208 | // Remember this variable. We may need to correct its type. |
| 14209 | active_builtins.push_back(make_pair(&var, bi_type)); |
| 14210 | |
| 14211 | if (is_direct_input_builtin(bi_type)) |
| 14212 | { |
| 14213 | if (!ep_args.empty()) |
| 14214 | ep_args += ", "; |
| 14215 | |
| 14216 | // Handle HLSL-style 0-based vertex/instance index. |
| 14217 | builtin_declaration = true; |
| 14218 | |
| 14219 | // Handle different MSL gl_TessCoord types. (float2, float3) |
| 14220 | if (bi_type == BuiltInTessCoord && get_entry_point().flags.get(ExecutionModeQuads)) |
| 14221 | ep_args += "float2 " + to_expression(var_id) + "In"; |
| 14222 | else |
| 14223 | ep_args += builtin_type_decl(bi_type, var_id) + " " + to_expression(var_id); |
| 14224 | |
| 14225 | ep_args += string(" [[") + builtin_qualifier(bi_type); |
| 14226 | if (bi_type == BuiltInSampleMask && get_entry_point().flags.get(ExecutionModePostDepthCoverage)) |
| 14227 | { |
| 14228 | if (!msl_options.supports_msl_version(2)) |
| 14229 | SPIRV_CROSS_THROW("Post-depth coverage requires MSL 2.0."); |
| 14230 | if (msl_options.is_macos() && !msl_options.supports_msl_version(2, 3)) |
| 14231 | SPIRV_CROSS_THROW("Post-depth coverage on Mac requires MSL 2.3."); |
| 14232 | ep_args += ", post_depth_coverage"; |
| 14233 | } |
| 14234 | ep_args += "]]"; |
| 14235 | builtin_declaration = false; |
| 14236 | } |
| 14237 | } |
| 14238 | |
| 14239 | if (has_extended_decoration(var_id, SPIRVCrossDecorationBuiltInDispatchBase)) |
| 14240 | { |
| 14241 | // This is a special implicit builtin, not corresponding to any SPIR-V builtin, |
| 14242 | // which holds the base that was passed to vkCmdDispatchBase() or vkCmdDrawIndexed(). If it's present, |
| 14243 | // assume we emitted it for a good reason. |
| 14244 | assert(msl_options.supports_msl_version(1, 2)); |
| 14245 | if (!ep_args.empty()) |
| 14246 | ep_args += ", "; |
| 14247 | |
| 14248 | ep_args += type_to_glsl(get_variable_data_type(var)) + " " + to_expression(var_id) + " [[grid_origin]]"; |
| 14249 | } |
| 14250 | |
| 14251 | if (has_extended_decoration(var_id, SPIRVCrossDecorationBuiltInStageInputSize)) |
| 14252 | { |
| 14253 | // This is another special implicit builtin, not corresponding to any SPIR-V builtin, |
| 14254 | // which holds the number of vertices and instances to draw. If it's present, |
| 14255 | // assume we emitted it for a good reason. |
| 14256 | assert(msl_options.supports_msl_version(1, 2)); |
| 14257 | if (!ep_args.empty()) |
| 14258 | ep_args += ", "; |
| 14259 | |
| 14260 | ep_args += type_to_glsl(get_variable_data_type(var)) + " " + to_expression(var_id) + " [[grid_size]]"; |
| 14261 | } |
| 14262 | }); |
| 14263 | |
| 14264 | // Correct the types of all encountered active builtins. We couldn't do this before |
| 14265 | // because ensure_correct_builtin_type() may increase the bound, which isn't allowed |
| 14266 | // while iterating over IDs. |
| 14267 | for (auto &var : active_builtins) |
| 14268 | var.first->basetype = ensure_correct_builtin_type(var.first->basetype, var.second); |
| 14269 | |
| 14270 | // Handle HLSL-style 0-based vertex/instance index. |
| 14271 | if (needs_base_vertex_arg == TriState::Yes) |
| 14272 | ep_args += built_in_func_arg(BuiltInBaseVertex, !ep_args.empty()); |
| 14273 | |
| 14274 | if (needs_base_instance_arg == TriState::Yes) |
| 14275 | ep_args += built_in_func_arg(BuiltInBaseInstance, !ep_args.empty()); |
| 14276 | |
| 14277 | if (capture_output_to_buffer) |
| 14278 | { |
| 14279 | // Add parameters to hold the indirect draw parameters and the shader output. This has to be handled |
| 14280 | // specially because it needs to be a pointer, not a reference. |
| 14281 | if (stage_out_var_id) |
| 14282 | { |
| 14283 | if (!ep_args.empty()) |
| 14284 | ep_args += ", "; |
| 14285 | ep_args += join("device ", type_to_glsl(get_stage_out_struct_type()), "* ", output_buffer_var_name, |
| 14286 | " [[buffer(", msl_options.shader_output_buffer_index, ")]]"); |
| 14287 | } |
| 14288 | |
| 14289 | if (is_tesc_shader()) |
| 14290 | { |
| 14291 | if (!ep_args.empty()) |
| 14292 | ep_args += ", "; |
| 14293 | ep_args += |
| 14294 | join("constant uint* spvIndirectParams [[buffer(", msl_options.indirect_params_buffer_index, ")]]"); |
| 14295 | } |
| 14296 | else if (stage_out_var_id && |
| 14297 | !(get_execution_model() == ExecutionModelVertex && msl_options.vertex_for_tessellation)) |
| 14298 | { |
| 14299 | if (!ep_args.empty()) |
| 14300 | ep_args += ", "; |
| 14301 | ep_args += |
| 14302 | join("device uint* spvIndirectParams [[buffer(", msl_options.indirect_params_buffer_index, ")]]"); |
| 14303 | } |
| 14304 | |
| 14305 | if (get_execution_model() == ExecutionModelVertex && msl_options.vertex_for_tessellation && |
| 14306 | (active_input_builtins.get(BuiltInVertexIndex) || active_input_builtins.get(BuiltInVertexId)) && |
| 14307 | msl_options.vertex_index_type != Options::IndexType::None) |
| 14308 | { |
| 14309 | // Add the index buffer so we can set gl_VertexIndex correctly. |
| 14310 | if (!ep_args.empty()) |
| 14311 | ep_args += ", "; |
| 14312 | switch (msl_options.vertex_index_type) |
| 14313 | { |
| 14314 | case Options::IndexType::None: |
| 14315 | break; |
| 14316 | case Options::IndexType::UInt16: |
| 14317 | ep_args += join("const device ushort* ", index_buffer_var_name, " [[buffer(", |
| 14318 | msl_options.shader_index_buffer_index, ")]]"); |
| 14319 | break; |
| 14320 | case Options::IndexType::UInt32: |
| 14321 | ep_args += join("const device uint* ", index_buffer_var_name, " [[buffer(", |
| 14322 | msl_options.shader_index_buffer_index, ")]]"); |
| 14323 | break; |
| 14324 | } |
| 14325 | } |
| 14326 | |
| 14327 | // Tessellation control shaders get three additional parameters: |
| 14328 | // a buffer to hold the per-patch data, a buffer to hold the per-patch |
| 14329 | // tessellation levels, and a block of workgroup memory to hold the |
| 14330 | // input control point data. |
| 14331 | if (is_tesc_shader()) |
| 14332 | { |
| 14333 | if (patch_stage_out_var_id) |
| 14334 | { |
| 14335 | if (!ep_args.empty()) |
| 14336 | ep_args += ", "; |
| 14337 | ep_args += |
| 14338 | join("device ", type_to_glsl(get_patch_stage_out_struct_type()), "* ", patch_output_buffer_var_name, |
| 14339 | " [[buffer(", convert_to_string(msl_options.shader_patch_output_buffer_index), ")]]"); |
| 14340 | } |
| 14341 | if (!ep_args.empty()) |
| 14342 | ep_args += ", "; |
| 14343 | ep_args += join("device ", get_tess_factor_struct_name(), "* ", tess_factor_buffer_var_name, " [[buffer(", |
| 14344 | convert_to_string(msl_options.shader_tess_factor_buffer_index), ")]]"); |
| 14345 | |
| 14346 | // Initializer for tess factors must be handled specially since it's never declared as a normal variable. |
| 14347 | uint32_t outer_factor_initializer_id = 0; |
| 14348 | uint32_t inner_factor_initializer_id = 0; |
| 14349 | ir.for_each_typed_id<SPIRVariable>([&](uint32_t, SPIRVariable &var) { |
| 14350 | if (!has_decoration(var.self, DecorationBuiltIn) || var.storage != StorageClassOutput || !var.initializer) |
| 14351 | return; |
| 14352 | |
| 14353 | BuiltIn builtin = BuiltIn(get_decoration(var.self, DecorationBuiltIn)); |
| 14354 | if (builtin == BuiltInTessLevelInner) |
| 14355 | inner_factor_initializer_id = var.initializer; |
| 14356 | else if (builtin == BuiltInTessLevelOuter) |
| 14357 | outer_factor_initializer_id = var.initializer; |
| 14358 | }); |
| 14359 | |
| 14360 | const SPIRConstant *c = nullptr; |
| 14361 | |
| 14362 | if (outer_factor_initializer_id && (c = maybe_get<SPIRConstant>(outer_factor_initializer_id))) |
| 14363 | { |
| 14364 | auto &entry_func = get<SPIRFunction>(ir.default_entry_point); |
| 14365 | entry_func.fixup_hooks_in.push_back( |
| 14366 | [=]() |
| 14367 | { |
| 14368 | uint32_t components = is_tessellating_triangles() ? 3 : 4; |
| 14369 | for (uint32_t i = 0; i < components; i++) |
| 14370 | { |
| 14371 | statement(builtin_to_glsl(BuiltInTessLevelOuter, StorageClassOutput), "[", i, |
| 14372 | "] = ", "half(", to_expression(c->subconstants[i]), ");"); |
| 14373 | } |
| 14374 | }); |
| 14375 | } |
| 14376 | |
| 14377 | if (inner_factor_initializer_id && (c = maybe_get<SPIRConstant>(inner_factor_initializer_id))) |
| 14378 | { |
| 14379 | auto &entry_func = get<SPIRFunction>(ir.default_entry_point); |
| 14380 | if (is_tessellating_triangles()) |
| 14381 | { |
| 14382 | entry_func.fixup_hooks_in.push_back([=]() { |
| 14383 | statement(builtin_to_glsl(BuiltInTessLevelInner, StorageClassOutput), " = ", "half(", |
| 14384 | to_expression(c->subconstants[0]), ");"); |
| 14385 | }); |
| 14386 | } |
| 14387 | else |
| 14388 | { |
| 14389 | entry_func.fixup_hooks_in.push_back([=]() { |
| 14390 | for (uint32_t i = 0; i < 2; i++) |
| 14391 | { |
| 14392 | statement(builtin_to_glsl(BuiltInTessLevelInner, StorageClassOutput), "[", i, "] = ", |
| 14393 | "half(", to_expression(c->subconstants[i]), ");"); |
| 14394 | } |
| 14395 | }); |
| 14396 | } |
| 14397 | } |
| 14398 | |
| 14399 | if (stage_in_var_id) |
| 14400 | { |
| 14401 | if (!ep_args.empty()) |
| 14402 | ep_args += ", "; |
| 14403 | if (msl_options.multi_patch_workgroup) |
| 14404 | { |
| 14405 | ep_args += join("device ", type_to_glsl(get_stage_in_struct_type()), "* ", input_buffer_var_name, |
| 14406 | " [[buffer(", convert_to_string(msl_options.shader_input_buffer_index), ")]]"); |
| 14407 | } |
| 14408 | else |
| 14409 | { |
| 14410 | ep_args += join("threadgroup ", type_to_glsl(get_stage_in_struct_type()), "* ", input_wg_var_name, |
| 14411 | " [[threadgroup(", convert_to_string(msl_options.shader_input_wg_index), ")]]"); |
| 14412 | } |
| 14413 | } |
| 14414 | } |
| 14415 | } |
| 14416 | // Tessellation evaluation shaders get three additional parameters: |
| 14417 | // a buffer for the per-patch data, a buffer for the per-patch |
| 14418 | // tessellation levels, and a buffer for the control point data. |
| 14419 | if (is_tese_shader() && msl_options.raw_buffer_tese_input) |
| 14420 | { |
| 14421 | if (patch_stage_in_var_id) |
| 14422 | { |
| 14423 | if (!ep_args.empty()) |
| 14424 | ep_args += ", "; |
| 14425 | ep_args += |
| 14426 | join("const device ", type_to_glsl(get_patch_stage_in_struct_type()), "* ", patch_input_buffer_var_name, |
| 14427 | " [[buffer(", convert_to_string(msl_options.shader_patch_input_buffer_index), ")]]"); |
| 14428 | } |
| 14429 | |
| 14430 | if (tess_level_inner_var_id || tess_level_outer_var_id) |
| 14431 | { |
| 14432 | if (!ep_args.empty()) |
| 14433 | ep_args += ", "; |
| 14434 | ep_args += join("const device ", get_tess_factor_struct_name(), "* ", tess_factor_buffer_var_name, |
| 14435 | " [[buffer(", convert_to_string(msl_options.shader_tess_factor_buffer_index), ")]]"); |
| 14436 | } |
| 14437 | |
| 14438 | if (stage_in_var_id) |
| 14439 | { |
| 14440 | if (!ep_args.empty()) |
| 14441 | ep_args += ", "; |
| 14442 | ep_args += join("const device ", type_to_glsl(get_stage_in_struct_type()), "* ", input_buffer_var_name, |
| 14443 | " [[buffer(", convert_to_string(msl_options.shader_input_buffer_index), ")]]"); |
| 14444 | } |
| 14445 | } |
| 14446 | |
| 14447 | if (is_mesh_shader()) |
| 14448 | { |
| 14449 | if (!ep_args.empty()) |
| 14450 | ep_args += ", "; |
| 14451 | ep_args += join("spvMesh_t spvMesh"); |
| 14452 | } |
| 14453 | |
| 14454 | if (get_execution_model() == ExecutionModelTaskEXT) |
| 14455 | { |
| 14456 | if (!ep_args.empty()) |
| 14457 | ep_args += ", "; |
| 14458 | ep_args += join("mesh_grid_properties spvMgp"); |
| 14459 | } |
| 14460 | } |
| 14461 | |
| 14462 | string CompilerMSL::entry_point_args_argument_buffer(bool append_comma) |
| 14463 | { |
| 14464 | string ep_args = entry_point_arg_stage_in(); |
| 14465 | Bitset claimed_bindings; |
| 14466 | |
| 14467 | for (uint32_t i = 0; i < kMaxArgumentBuffers; i++) |
| 14468 | { |
| 14469 | uint32_t id = argument_buffer_ids[i]; |
| 14470 | if (id == 0) |
| 14471 | continue; |
| 14472 | |
| 14473 | add_resource_name(id); |
| 14474 | auto &var = get<SPIRVariable>(id); |
| 14475 | auto &type = get_variable_data_type(var); |
| 14476 | |
| 14477 | if (!ep_args.empty()) |
| 14478 | ep_args += ", "; |
| 14479 | |
| 14480 | // Check if the argument buffer binding itself has been remapped. |
| 14481 | uint32_t buffer_binding; |
| 14482 | auto itr = resource_bindings.find({ get_entry_point().model, i, kArgumentBufferBinding }); |
| 14483 | if (itr != end(resource_bindings)) |
| 14484 | { |
| 14485 | buffer_binding = itr->second.first.msl_buffer; |
| 14486 | itr->second.second = true; |
| 14487 | } |
| 14488 | else |
| 14489 | { |
| 14490 | // As a fallback, directly map desc set <-> binding. |
| 14491 | // If that was taken, take the next buffer binding. |
| 14492 | if (claimed_bindings.get(i)) |
| 14493 | buffer_binding = next_metal_resource_index_buffer; |
| 14494 | else |
| 14495 | buffer_binding = i; |
| 14496 | } |
| 14497 | |
| 14498 | claimed_bindings.set(buffer_binding); |
| 14499 | |
| 14500 | ep_args += get_argument_address_space(var) + " "; |
| 14501 | |
| 14502 | if (recursive_inputs.count(type.self)) |
| 14503 | ep_args += string("void* ") + to_restrict(id, true) + to_name(id) + "_vp"; |
| 14504 | else |
| 14505 | ep_args += type_to_glsl(type) + "& " + to_restrict(id, true) + to_name(id); |
| 14506 | |
| 14507 | ep_args += " [[buffer(" + convert_to_string(buffer_binding) + ")]]"; |
| 14508 | |
| 14509 | next_metal_resource_index_buffer = max(next_metal_resource_index_buffer, buffer_binding + 1); |
| 14510 | } |
| 14511 | |
| 14512 | entry_point_args_discrete_descriptors(ep_args); |
| 14513 | entry_point_args_builtin(ep_args); |
| 14514 | |
| 14515 | if (!ep_args.empty() && append_comma) |
| 14516 | ep_args += ", "; |
| 14517 | |
| 14518 | return ep_args; |
| 14519 | } |
| 14520 | |
| 14521 | const MSLConstexprSampler *CompilerMSL::find_constexpr_sampler(uint32_t id) const |
| 14522 | { |
| 14523 | // Try by ID. |
| 14524 | { |
| 14525 | auto itr = constexpr_samplers_by_id.find(id); |
| 14526 | if (itr != end(constexpr_samplers_by_id)) |
| 14527 | return &itr->second; |
| 14528 | } |
| 14529 | |
| 14530 | // Try by binding. |
| 14531 | { |
| 14532 | uint32_t desc_set = get_decoration(id, DecorationDescriptorSet); |
| 14533 | uint32_t binding = get_decoration(id, DecorationBinding); |
| 14534 | |
| 14535 | auto itr = constexpr_samplers_by_binding.find({ desc_set, binding }); |
| 14536 | if (itr != end(constexpr_samplers_by_binding)) |
| 14537 | return &itr->second; |
| 14538 | } |
| 14539 | |
| 14540 | return nullptr; |
| 14541 | } |
| 14542 | |
| 14543 | void CompilerMSL::entry_point_args_discrete_descriptors(string &ep_args) |
| 14544 | { |
| 14545 | // Output resources, sorted by resource index & type |
| 14546 | // We need to sort to work around a bug on macOS 10.13 with NVidia drivers where switching between shaders |
| 14547 | // with different order of buffers can result in issues with buffer assignments inside the driver. |
| 14548 | struct Resource |
| 14549 | { |
| 14550 | SPIRVariable *var; |
| 14551 | SPIRVariable *discrete_descriptor_alias; |
| 14552 | string name; |
| 14553 | SPIRType::BaseType basetype; |
| 14554 | uint32_t index; |
| 14555 | uint32_t plane; |
| 14556 | uint32_t secondary_index; |
| 14557 | }; |
| 14558 | |
| 14559 | SmallVector<Resource> resources; |
| 14560 | |
| 14561 | entry_point_bindings.clear(); |
| 14562 | ir.for_each_typed_id<SPIRVariable>([&](uint32_t var_id, SPIRVariable &var) { |
| 14563 | if ((var.storage == StorageClassUniform || var.storage == StorageClassUniformConstant || |
| 14564 | var.storage == StorageClassPushConstant || var.storage == StorageClassStorageBuffer) && |
| 14565 | !is_hidden_variable(var)) |
| 14566 | { |
| 14567 | auto &type = get_variable_data_type(var); |
| 14568 | uint32_t desc_set = get_decoration(var_id, DecorationDescriptorSet); |
| 14569 | |
| 14570 | if (is_supported_argument_buffer_type(type) && var.storage != StorageClassPushConstant) |
| 14571 | { |
| 14572 | if (descriptor_set_is_argument_buffer(desc_set)) |
| 14573 | { |
| 14574 | if (is_var_runtime_size_array(var)) |
| 14575 | { |
| 14576 | // Runtime arrays need to be wrapped in spvDescriptorArray from argument buffer payload. |
| 14577 | entry_point_bindings.push_back(&var); |
| 14578 | // We'll wrap this, so to_name() will always use non-qualified name. |
| 14579 | // We'll need the qualified name to create temporary variable instead. |
| 14580 | ir.meta[var_id].decoration.qualified_alias_explicit_override = true; |
| 14581 | } |
| 14582 | return; |
| 14583 | } |
| 14584 | } |
| 14585 | |
| 14586 | // Handle descriptor aliasing of simple discrete cases. |
| 14587 | // We can handle aliasing of buffers by casting pointers. |
| 14588 | // The amount of aliasing we can perform for discrete descriptors is very limited. |
| 14589 | // For fully mutable-style aliasing, we need argument buffers where we can exploit the fact |
| 14590 | // that descriptors are all 8 bytes. |
| 14591 | SPIRVariable *discrete_descriptor_alias = nullptr; |
| 14592 | if (var.storage == StorageClassUniform || var.storage == StorageClassStorageBuffer) |
| 14593 | { |
| 14594 | for (auto &resource : resources) |
| 14595 | { |
| 14596 | if (get_decoration(resource.var->self, DecorationDescriptorSet) == |
| 14597 | get_decoration(var_id, DecorationDescriptorSet) && |
| 14598 | get_decoration(resource.var->self, DecorationBinding) == |
| 14599 | get_decoration(var_id, DecorationBinding) && |
| 14600 | resource.basetype == SPIRType::Struct && type.basetype == SPIRType::Struct && |
| 14601 | (resource.var->storage == StorageClassUniform || |
| 14602 | resource.var->storage == StorageClassStorageBuffer)) |
| 14603 | { |
| 14604 | discrete_descriptor_alias = resource.var; |
| 14605 | // Self-reference marks that we should declare the resource, |
| 14606 | // and it's being used as an alias (so we can emit void* instead). |
| 14607 | resource.discrete_descriptor_alias = resource.var; |
| 14608 | // Need to promote interlocked usage so that the primary declaration is correct. |
| 14609 | if (interlocked_resources.count(var_id)) |
| 14610 | interlocked_resources.insert(resource.var->self); |
| 14611 | break; |
| 14612 | } |
| 14613 | } |
| 14614 | } |
| 14615 | |
| 14616 | const MSLConstexprSampler *constexpr_sampler = nullptr; |
| 14617 | if (type.basetype == SPIRType::SampledImage || type.basetype == SPIRType::Sampler) |
| 14618 | { |
| 14619 | constexpr_sampler = find_constexpr_sampler(var_id); |
| 14620 | if (constexpr_sampler) |
| 14621 | { |
| 14622 | // Mark this ID as a constexpr sampler for later in case it came from set/bindings. |
| 14623 | constexpr_samplers_by_id[var_id] = *constexpr_sampler; |
| 14624 | } |
| 14625 | } |
| 14626 | |
| 14627 | // Emulate texture2D atomic operations |
| 14628 | uint32_t secondary_index = 0; |
| 14629 | if (atomic_image_vars_emulated.count(var.self)) |
| 14630 | { |
| 14631 | secondary_index = get_metal_resource_index(var, SPIRType::AtomicCounter, 0); |
| 14632 | } |
| 14633 | |
| 14634 | if (type.basetype == SPIRType::SampledImage) |
| 14635 | { |
| 14636 | add_resource_name(var_id); |
| 14637 | |
| 14638 | uint32_t plane_count = 1; |
| 14639 | if (constexpr_sampler && constexpr_sampler->ycbcr_conversion_enable) |
| 14640 | plane_count = constexpr_sampler->planes; |
| 14641 | |
| 14642 | entry_point_bindings.push_back(&var); |
| 14643 | for (uint32_t i = 0; i < plane_count; i++) |
| 14644 | resources.push_back({&var, discrete_descriptor_alias, to_name(var_id), SPIRType::Image, |
| 14645 | get_metal_resource_index(var, SPIRType::Image, i), i, secondary_index }); |
| 14646 | |
| 14647 | if (type.image.dim != DimBuffer && !constexpr_sampler) |
| 14648 | { |
| 14649 | resources.push_back({&var, discrete_descriptor_alias, to_sampler_expression(var_id), SPIRType::Sampler, |
| 14650 | get_metal_resource_index(var, SPIRType::Sampler), 0, 0 }); |
| 14651 | } |
| 14652 | } |
| 14653 | else if (!constexpr_sampler) |
| 14654 | { |
| 14655 | // constexpr samplers are not declared as resources. |
| 14656 | add_resource_name(var_id); |
| 14657 | |
| 14658 | // Don't allocate resource indices for aliases. |
| 14659 | uint32_t resource_index = ~0u; |
| 14660 | if (!discrete_descriptor_alias) |
| 14661 | resource_index = get_metal_resource_index(var, type.basetype); |
| 14662 | |
| 14663 | entry_point_bindings.push_back(&var); |
| 14664 | resources.push_back({&var, discrete_descriptor_alias, to_name(var_id), type.basetype, |
| 14665 | resource_index, 0, secondary_index }); |
| 14666 | } |
| 14667 | } |
| 14668 | }); |
| 14669 | |
| 14670 | stable_sort(resources.begin(), resources.end(), |
| 14671 | [](const Resource &lhs, const Resource &rhs) |
| 14672 | { return tie(lhs.basetype, lhs.index) < tie(rhs.basetype, rhs.index); }); |
| 14673 | |
| 14674 | for (auto &r : resources) |
| 14675 | { |
| 14676 | auto &var = *r.var; |
| 14677 | auto &type = get_variable_data_type(var); |
| 14678 | |
| 14679 | uint32_t var_id = var.self; |
| 14680 | |
| 14681 | switch (r.basetype) |
| 14682 | { |
| 14683 | case SPIRType::Struct: |
| 14684 | { |
| 14685 | auto &m = ir.meta[type.self]; |
| 14686 | if (m.members.size() == 0) |
| 14687 | break; |
| 14688 | |
| 14689 | if (r.discrete_descriptor_alias) |
| 14690 | { |
| 14691 | if (r.var == r.discrete_descriptor_alias) |
| 14692 | { |
| 14693 | auto primary_name = join("spvBufferAliasSet", |
| 14694 | get_decoration(var_id, DecorationDescriptorSet), |
| 14695 | "Binding", |
| 14696 | get_decoration(var_id, DecorationBinding)); |
| 14697 | |
| 14698 | // Declare the primary alias as void* |
| 14699 | if (!ep_args.empty()) |
| 14700 | ep_args += ", "; |
| 14701 | ep_args += get_argument_address_space(var) + " void* " + primary_name; |
| 14702 | ep_args += " [[buffer(" + convert_to_string(r.index) + ")"; |
| 14703 | if (interlocked_resources.count(var_id)) |
| 14704 | ep_args += ", raster_order_group(0)"; |
| 14705 | ep_args += "]]"; |
| 14706 | } |
| 14707 | |
| 14708 | buffer_aliases_discrete.push_back(r.var->self); |
| 14709 | } |
| 14710 | else if (!type.array.empty()) |
| 14711 | { |
| 14712 | if (type.array.size() > 1) |
| 14713 | SPIRV_CROSS_THROW("Arrays of arrays of buffers are not supported."); |
| 14714 | |
| 14715 | is_using_builtin_array = true; |
| 14716 | if (is_var_runtime_size_array(var)) |
| 14717 | { |
| 14718 | add_spv_func_and_recompile(SPVFuncImplVariableDescriptorArray); |
| 14719 | if (!ep_args.empty()) |
| 14720 | ep_args += ", "; |
| 14721 | const bool ssbo = has_decoration(type.self, DecorationBufferBlock); |
| 14722 | if ((var.storage == spv::StorageClassStorageBuffer || ssbo) && |
| 14723 | msl_options.runtime_array_rich_descriptor) |
| 14724 | { |
| 14725 | add_spv_func_and_recompile(SPVFuncImplVariableSizedDescriptor); |
| 14726 | ep_args += "const device spvBufferDescriptor<" + get_argument_address_space(var) + " " + |
| 14727 | type_to_glsl(type) + "*>* "; |
| 14728 | } |
| 14729 | else |
| 14730 | { |
| 14731 | add_spv_func_and_recompile(SPVFuncImplVariableDescriptor); |
| 14732 | ep_args += "const device spvDescriptor<" + get_argument_address_space(var) + " " + |
| 14733 | type_to_glsl(type) + "*>* "; |
| 14734 | } |
| 14735 | ep_args += to_restrict(var_id, true) + r.name + "_"; |
| 14736 | ep_args += " [[buffer(" + convert_to_string(r.index) + ")"; |
| 14737 | if (interlocked_resources.count(var_id)) |
| 14738 | ep_args += ", raster_order_group(0)"; |
| 14739 | ep_args += "]]"; |
| 14740 | } |
| 14741 | else |
| 14742 | { |
| 14743 | uint32_t array_size = get_resource_array_size(type, var_id); |
| 14744 | for (uint32_t i = 0; i < array_size; ++i) |
| 14745 | { |
| 14746 | if (!ep_args.empty()) |
| 14747 | ep_args += ", "; |
| 14748 | ep_args += get_argument_address_space(var) + " " + type_to_glsl(type) + "* " + |
| 14749 | to_restrict(var_id, true) + r.name + "_" + convert_to_string(i); |
| 14750 | ep_args += " [[buffer(" + convert_to_string(r.index + i) + ")"; |
| 14751 | if (interlocked_resources.count(var_id)) |
| 14752 | ep_args += ", raster_order_group(0)"; |
| 14753 | ep_args += "]]"; |
| 14754 | } |
| 14755 | } |
| 14756 | is_using_builtin_array = false; |
| 14757 | } |
| 14758 | else |
| 14759 | { |
| 14760 | if (!ep_args.empty()) |
| 14761 | ep_args += ", "; |
| 14762 | ep_args += get_argument_address_space(var) + " "; |
| 14763 | |
| 14764 | if (recursive_inputs.count(type.self)) |
| 14765 | ep_args += string("void* ") + to_restrict(var_id, true) + r.name + "_vp"; |
| 14766 | else |
| 14767 | ep_args += type_to_glsl(type) + "& " + to_restrict(var_id, true) + r.name; |
| 14768 | |
| 14769 | ep_args += " [[buffer(" + convert_to_string(r.index) + ")"; |
| 14770 | if (interlocked_resources.count(var_id)) |
| 14771 | ep_args += ", raster_order_group(0)"; |
| 14772 | ep_args += "]]"; |
| 14773 | } |
| 14774 | break; |
| 14775 | } |
| 14776 | case SPIRType::Sampler: |
| 14777 | if (!ep_args.empty()) |
| 14778 | ep_args += ", "; |
| 14779 | ep_args += sampler_type(type, var_id, false) + " " + r.name; |
| 14780 | if (is_var_runtime_size_array(var)) |
| 14781 | ep_args += "_ [[buffer(" + convert_to_string(r.index) + ")]]"; |
| 14782 | else |
| 14783 | ep_args += " [[sampler(" + convert_to_string(r.index) + ")]]"; |
| 14784 | break; |
| 14785 | case SPIRType::Image: |
| 14786 | { |
| 14787 | if (!ep_args.empty()) |
| 14788 | ep_args += ", "; |
| 14789 | |
| 14790 | // Use Metal's native frame-buffer fetch API for subpass inputs. |
| 14791 | const auto &basetype = get<SPIRType>(var.basetype); |
| 14792 | if (!type_is_msl_framebuffer_fetch(basetype)) |
| 14793 | { |
| 14794 | ep_args += image_type_glsl(type, var_id, false) + " " + r.name; |
| 14795 | if (r.plane > 0) |
| 14796 | ep_args += join(plane_name_suffix, r.plane); |
| 14797 | |
| 14798 | if (is_var_runtime_size_array(var)) |
| 14799 | ep_args += "_ [[buffer(" + convert_to_string(r.index) + ")"; |
| 14800 | else |
| 14801 | ep_args += " [[texture(" + convert_to_string(r.index) + ")"; |
| 14802 | |
| 14803 | if (interlocked_resources.count(var_id)) |
| 14804 | ep_args += ", raster_order_group(0)"; |
| 14805 | ep_args += "]]"; |
| 14806 | } |
| 14807 | else |
| 14808 | { |
| 14809 | if (msl_options.is_macos() && !msl_options.supports_msl_version(2, 3)) |
| 14810 | SPIRV_CROSS_THROW("Framebuffer fetch on Mac is not supported before MSL 2.3."); |
| 14811 | ep_args += image_type_glsl(type, var_id, false) + " " + r.name; |
| 14812 | ep_args += " [[color(" + convert_to_string(r.index) + ")]]"; |
| 14813 | } |
| 14814 | |
| 14815 | // Emulate texture2D atomic operations |
| 14816 | if (atomic_image_vars_emulated.count(var.self)) |
| 14817 | { |
| 14818 | auto &flags = ir.get_decoration_bitset(var.self); |
| 14819 | const char *cv_flags = decoration_flags_signal_volatile(flags) ? "volatile " : ""; |
| 14820 | ep_args += join(", ", cv_flags, "device atomic_", type_to_glsl(get<SPIRType>(basetype.image.type), 0)); |
| 14821 | ep_args += "* " + r.name + "_atomic"; |
| 14822 | ep_args += " [[buffer(" + convert_to_string(r.secondary_index) + ")"; |
| 14823 | if (interlocked_resources.count(var_id)) |
| 14824 | ep_args += ", raster_order_group(0)"; |
| 14825 | ep_args += "]]"; |
| 14826 | } |
| 14827 | break; |
| 14828 | } |
| 14829 | case SPIRType::AccelerationStructure: |
| 14830 | { |
| 14831 | if (is_var_runtime_size_array(var)) |
| 14832 | { |
| 14833 | add_spv_func_and_recompile(SPVFuncImplVariableDescriptor); |
| 14834 | const auto &parent_type = get<SPIRType>(type.parent_type); |
| 14835 | if (!ep_args.empty()) |
| 14836 | ep_args += ", "; |
| 14837 | ep_args += "const device spvDescriptor<" + type_to_glsl(parent_type) + ">* " + |
| 14838 | to_restrict(var_id, true) + r.name + "_"; |
| 14839 | ep_args += " [[buffer(" + convert_to_string(r.index) + ")]]"; |
| 14840 | } |
| 14841 | else |
| 14842 | { |
| 14843 | if (!ep_args.empty()) |
| 14844 | ep_args += ", "; |
| 14845 | ep_args += type_to_glsl(type, var_id) + " " + r.name; |
| 14846 | ep_args += " [[buffer(" + convert_to_string(r.index) + ")]]"; |
| 14847 | } |
| 14848 | break; |
| 14849 | } |
| 14850 | default: |
| 14851 | if (!ep_args.empty()) |
| 14852 | ep_args += ", "; |
| 14853 | if (!type.pointer) |
| 14854 | ep_args += get_type_address_space(get<SPIRType>(var.basetype), var_id) + " " + |
| 14855 | type_to_glsl(type, var_id) + "& " + r.name; |
| 14856 | else |
| 14857 | ep_args += type_to_glsl(type, var_id) + " " + r.name; |
| 14858 | ep_args += " [[buffer(" + convert_to_string(r.index) + ")"; |
| 14859 | if (interlocked_resources.count(var_id)) |
| 14860 | ep_args += ", raster_order_group(0)"; |
| 14861 | ep_args += "]]"; |
| 14862 | break; |
| 14863 | } |
| 14864 | } |
| 14865 | } |
| 14866 | |
| 14867 | // Returns a string containing a comma-delimited list of args for the entry point function |
| 14868 | // This is the "classic" method of MSL 1 when we don't have argument buffer support. |
| 14869 | string CompilerMSL::entry_point_args_classic(bool append_comma) |
| 14870 | { |
| 14871 | string ep_args = entry_point_arg_stage_in(); |
| 14872 | entry_point_args_discrete_descriptors(ep_args); |
| 14873 | entry_point_args_builtin(ep_args); |
| 14874 | |
| 14875 | if (!ep_args.empty() && append_comma) |
| 14876 | ep_args += ", "; |
| 14877 | |
| 14878 | return ep_args; |
| 14879 | } |
| 14880 | |
| 14881 | void CompilerMSL::fix_up_shader_inputs_outputs() |
| 14882 | { |
| 14883 | auto &entry_func = this->get<SPIRFunction>(ir.default_entry_point); |
| 14884 | |
| 14885 | // Emit a guard to ensure we don't execute beyond the last vertex. |
| 14886 | // Vertex shaders shouldn't have the problems with barriers in non-uniform control flow that |
| 14887 | // tessellation control shaders do, so early returns should be OK. We may need to revisit this |
| 14888 | // if it ever becomes possible to use barriers from a vertex shader. |
| 14889 | if (get_execution_model() == ExecutionModelVertex && msl_options.vertex_for_tessellation) |
| 14890 | { |
| 14891 | entry_func.fixup_hooks_in.push_back([this]() { |
| 14892 | statement("if (any(", to_expression(builtin_invocation_id_id), |
| 14893 | " >= ", to_expression(builtin_stage_input_size_id), "))"); |
| 14894 | statement(" return;"); |
| 14895 | }); |
| 14896 | } |
| 14897 | |
| 14898 | if (is_mesh_shader()) |
| 14899 | { |
| 14900 | // If shader doesn't call SetMeshOutputsEXT, nothing should be rendered. |
| 14901 | // No need to barrier after this, because only thread 0 writes to this later. |
| 14902 | entry_func.fixup_hooks_in.push_back([this]() { statement("if (gl_LocalInvocationIndex == 0) spvMeshSizes.y = 0u;"); }); |
| 14903 | entry_func.fixup_hooks_out.push_back([this]() { emit_mesh_outputs(); }); |
| 14904 | } |
| 14905 | |
| 14906 | // Look for sampled images and buffer. Add hooks to set up the swizzle constants or array lengths. |
| 14907 | ir.for_each_typed_id<SPIRVariable>([&](uint32_t, SPIRVariable &var) { |
| 14908 | auto &type = get_variable_data_type(var); |
| 14909 | uint32_t var_id = var.self; |
| 14910 | bool ssbo = has_decoration(type.self, DecorationBufferBlock); |
| 14911 | |
| 14912 | if (var.storage == StorageClassUniformConstant && !is_hidden_variable(var)) |
| 14913 | { |
| 14914 | if (msl_options.swizzle_texture_samples && has_sampled_images && is_sampled_image_type(type)) |
| 14915 | { |
| 14916 | entry_func.fixup_hooks_in.push_back([this, &type, &var, var_id]() { |
| 14917 | bool is_array_type = !type.array.empty(); |
| 14918 | |
| 14919 | uint32_t desc_set = get_decoration(var_id, DecorationDescriptorSet); |
| 14920 | if (descriptor_set_is_argument_buffer(desc_set)) |
| 14921 | { |
| 14922 | statement("constant uint", is_array_type ? "* " : "& ", to_swizzle_expression(var_id), |
| 14923 | is_array_type ? " = &" : " = ", to_name(argument_buffer_ids[desc_set]), |
| 14924 | ".spvSwizzleConstants", "[", |
| 14925 | convert_to_string(get_metal_resource_index(var, SPIRType::Image)), "];"); |
| 14926 | } |
| 14927 | else |
| 14928 | { |
| 14929 | // If we have an array of images, we need to be able to index into it, so take a pointer instead. |
| 14930 | statement("constant uint", is_array_type ? "* " : "& ", to_swizzle_expression(var_id), |
| 14931 | is_array_type ? " = &" : " = ", to_name(swizzle_buffer_id), "[", |
| 14932 | convert_to_string(get_metal_resource_index(var, SPIRType::Image)), "];"); |
| 14933 | } |
| 14934 | }); |
| 14935 | } |
| 14936 | } |
| 14937 | else if ((var.storage == StorageClassStorageBuffer || (var.storage == StorageClassUniform && ssbo)) && |
| 14938 | !is_hidden_variable(var)) |
| 14939 | { |
| 14940 | if (buffer_requires_array_length(var.self)) |
| 14941 | { |
| 14942 | entry_func.fixup_hooks_in.push_back( |
| 14943 | [this, &type, &var, var_id]() |
| 14944 | { |
| 14945 | bool is_array_type = !type.array.empty() && !is_var_runtime_size_array(var); |
| 14946 | |
| 14947 | uint32_t desc_set = get_decoration(var_id, DecorationDescriptorSet); |
| 14948 | if (descriptor_set_is_argument_buffer(desc_set)) |
| 14949 | { |
| 14950 | statement("constant uint", is_array_type ? "* " : "& ", to_buffer_size_expression(var_id), |
| 14951 | is_array_type ? " = &" : " = ", to_name(argument_buffer_ids[desc_set]), |
| 14952 | ".spvBufferSizeConstants", "[", |
| 14953 | convert_to_string(get_metal_resource_index(var, SPIRType::UInt)), "];"); |
| 14954 | } |
| 14955 | else |
| 14956 | { |
| 14957 | // If we have an array of images, we need to be able to index into it, so take a pointer instead. |
| 14958 | statement("constant uint", is_array_type ? "* " : "& ", to_buffer_size_expression(var_id), |
| 14959 | is_array_type ? " = &" : " = ", to_name(buffer_size_buffer_id), "[", |
| 14960 | convert_to_string(get_metal_resource_index(var, type.basetype)), "];"); |
| 14961 | } |
| 14962 | }); |
| 14963 | } |
| 14964 | } |
| 14965 | |
| 14966 | if (!msl_options.argument_buffers && |
| 14967 | msl_options.replace_recursive_inputs && type_contains_recursion(type) && |
| 14968 | (var.storage == StorageClassUniform || var.storage == StorageClassUniformConstant || |
| 14969 | var.storage == StorageClassPushConstant || var.storage == StorageClassStorageBuffer)) |
| 14970 | { |
| 14971 | recursive_inputs.insert(type.self); |
| 14972 | entry_func.fixup_hooks_in.push_back([this, &type, &var, var_id]() { |
| 14973 | auto addr_space = get_argument_address_space(var); |
| 14974 | auto var_name = to_name(var_id); |
| 14975 | statement(addr_space, " auto& ", to_restrict(var_id, true), var_name, |
| 14976 | " = *(", addr_space, " ", type_to_glsl(type), "*)", var_name, "_vp;"); |
| 14977 | }); |
| 14978 | } |
| 14979 | }); |
| 14980 | |
| 14981 | // Builtin variables |
| 14982 | ir.for_each_typed_id<SPIRVariable>([this, &entry_func](uint32_t, SPIRVariable &var) { |
| 14983 | uint32_t var_id = var.self; |
| 14984 | BuiltIn bi_type = ir.meta[var_id].decoration.builtin_type; |
| 14985 | |
| 14986 | if (var.storage != StorageClassInput && var.storage != StorageClassOutput) |
| 14987 | return; |
| 14988 | if (!interface_variable_exists_in_entry_point(var.self)) |
| 14989 | return; |
| 14990 | |
| 14991 | if (var.storage == StorageClassInput && is_builtin_variable(var) && active_input_builtins.get(bi_type)) |
| 14992 | { |
| 14993 | switch (bi_type) |
| 14994 | { |
| 14995 | case BuiltInSamplePosition: |
| 14996 | entry_func.fixup_hooks_in.push_back([=]() { |
| 14997 | statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = get_sample_position(", |
| 14998 | to_expression(builtin_sample_id_id), ");"); |
| 14999 | }); |
| 15000 | break; |
| 15001 | case BuiltInFragCoord: |
| 15002 | if (is_sample_rate()) |
| 15003 | { |
| 15004 | entry_func.fixup_hooks_in.push_back([=]() { |
| 15005 | statement(to_expression(var_id), ".xy += get_sample_position(", |
| 15006 | to_expression(builtin_sample_id_id), ") - 0.5;"); |
| 15007 | }); |
| 15008 | } |
| 15009 | break; |
| 15010 | case BuiltInInvocationId: |
| 15011 | // This is direct-mapped without multi-patch workgroups. |
| 15012 | if (!is_tesc_shader() || !msl_options.multi_patch_workgroup) |
| 15013 | break; |
| 15014 | |
| 15015 | entry_func.fixup_hooks_in.push_back([=]() { |
| 15016 | statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ", |
| 15017 | to_expression(builtin_invocation_id_id), ".x % ", this->get_entry_point().output_vertices, |
| 15018 | ";"); |
| 15019 | }); |
| 15020 | break; |
| 15021 | case BuiltInPrimitiveId: |
| 15022 | // This is natively supported by fragment and tessellation evaluation shaders. |
| 15023 | // In tessellation control shaders, this is direct-mapped without multi-patch workgroups. |
| 15024 | if (!is_tesc_shader() || !msl_options.multi_patch_workgroup) |
| 15025 | break; |
| 15026 | |
| 15027 | entry_func.fixup_hooks_in.push_back([=]() { |
| 15028 | statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = min(", |
| 15029 | to_expression(builtin_invocation_id_id), ".x / ", this->get_entry_point().output_vertices, |
| 15030 | ", spvIndirectParams[1] - 1);"); |
| 15031 | }); |
| 15032 | break; |
| 15033 | case BuiltInPatchVertices: |
| 15034 | if (is_tese_shader()) |
| 15035 | { |
| 15036 | if (msl_options.raw_buffer_tese_input) |
| 15037 | { |
| 15038 | entry_func.fixup_hooks_in.push_back( |
| 15039 | [=]() { |
| 15040 | statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ", |
| 15041 | get_entry_point().output_vertices, ";"); |
| 15042 | }); |
| 15043 | } |
| 15044 | else |
| 15045 | { |
| 15046 | entry_func.fixup_hooks_in.push_back( |
| 15047 | [=]() |
| 15048 | { |
| 15049 | statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ", |
| 15050 | to_expression(patch_stage_in_var_id), ".gl_in.size();"); |
| 15051 | }); |
| 15052 | } |
| 15053 | } |
| 15054 | else |
| 15055 | { |
| 15056 | entry_func.fixup_hooks_in.push_back([=]() { |
| 15057 | statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = spvIndirectParams[0];"); |
| 15058 | }); |
| 15059 | } |
| 15060 | break; |
| 15061 | case BuiltInTessCoord: |
| 15062 | if (get_entry_point().flags.get(ExecutionModeQuads)) |
| 15063 | { |
| 15064 | // The entry point will only have a float2 TessCoord variable. |
| 15065 | // Pad to float3. |
| 15066 | entry_func.fixup_hooks_in.push_back([=]() { |
| 15067 | auto name = builtin_to_glsl(BuiltInTessCoord, StorageClassInput); |
| 15068 | statement("float3 " + name + " = float3(" + name + "In.x, " + name + "In.y, 0.0);"); |
| 15069 | }); |
| 15070 | } |
| 15071 | |
| 15072 | // Emit a fixup to account for the shifted domain. Don't do this for triangles; |
| 15073 | // MoltenVK will just reverse the winding order instead. |
| 15074 | if (msl_options.tess_domain_origin_lower_left && !is_tessellating_triangles()) |
| 15075 | { |
| 15076 | string tc = to_expression(var_id); |
| 15077 | entry_func.fixup_hooks_in.push_back([=]() { statement(tc, ".y = 1.0 - ", tc, ".y;"); }); |
| 15078 | } |
| 15079 | break; |
| 15080 | case BuiltInSubgroupId: |
| 15081 | if (!msl_options.emulate_subgroups) |
| 15082 | break; |
| 15083 | // For subgroup emulation, this is the same as the local invocation index. |
| 15084 | entry_func.fixup_hooks_in.push_back([=]() { |
| 15085 | statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ", |
| 15086 | to_expression(builtin_local_invocation_index_id), ";"); |
| 15087 | }); |
| 15088 | break; |
| 15089 | case BuiltInNumSubgroups: |
| 15090 | if (!msl_options.emulate_subgroups) |
| 15091 | break; |
| 15092 | // For subgroup emulation, this is the same as the workgroup size. |
| 15093 | entry_func.fixup_hooks_in.push_back([=]() { |
| 15094 | auto &type = expression_type(builtin_workgroup_size_id); |
| 15095 | string size_expr = to_expression(builtin_workgroup_size_id); |
| 15096 | if (type.vecsize >= 3) |
| 15097 | size_expr = join(size_expr, ".x * ", size_expr, ".y * ", size_expr, ".z"); |
| 15098 | else if (type.vecsize == 2) |
| 15099 | size_expr = join(size_expr, ".x * ", size_expr, ".y"); |
| 15100 | statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ", size_expr, ";"); |
| 15101 | }); |
| 15102 | break; |
| 15103 | case BuiltInSubgroupLocalInvocationId: |
| 15104 | if (!msl_options.emulate_subgroups) |
| 15105 | break; |
| 15106 | // For subgroup emulation, assume subgroups of size 1. |
| 15107 | entry_func.fixup_hooks_in.push_back( |
| 15108 | [=]() { statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = 0;"); }); |
| 15109 | break; |
| 15110 | case BuiltInSubgroupSize: |
| 15111 | if (msl_options.emulate_subgroups) |
| 15112 | { |
| 15113 | // For subgroup emulation, assume subgroups of size 1. |
| 15114 | entry_func.fixup_hooks_in.push_back( |
| 15115 | [=]() { statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = 1;"); }); |
| 15116 | } |
| 15117 | else if (msl_options.fixed_subgroup_size != 0) |
| 15118 | { |
| 15119 | entry_func.fixup_hooks_in.push_back([=]() { |
| 15120 | statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ", |
| 15121 | msl_options.fixed_subgroup_size, ";"); |
| 15122 | }); |
| 15123 | } |
| 15124 | break; |
| 15125 | case BuiltInSubgroupEqMask: |
| 15126 | if (msl_options.is_ios() && !msl_options.supports_msl_version(2, 2)) |
| 15127 | SPIRV_CROSS_THROW("Subgroup ballot functionality requires Metal 2.2 on iOS."); |
| 15128 | if (!msl_options.supports_msl_version(2, 1)) |
| 15129 | SPIRV_CROSS_THROW("Subgroup ballot functionality requires Metal 2.1."); |
| 15130 | entry_func.fixup_hooks_in.push_back([=]() { |
| 15131 | if (msl_options.is_ios()) |
| 15132 | { |
| 15133 | statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ", "uint4(1 << ", |
| 15134 | to_expression(builtin_subgroup_invocation_id_id), ", uint3(0));"); |
| 15135 | } |
| 15136 | else |
| 15137 | { |
| 15138 | statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ", |
| 15139 | to_expression(builtin_subgroup_invocation_id_id), " >= 32 ? uint4(0, (1 << (", |
| 15140 | to_expression(builtin_subgroup_invocation_id_id), " - 32)), uint2(0)) : uint4(1 << ", |
| 15141 | to_expression(builtin_subgroup_invocation_id_id), ", uint3(0));"); |
| 15142 | } |
| 15143 | }); |
| 15144 | break; |
| 15145 | case BuiltInSubgroupGeMask: |
| 15146 | if (msl_options.is_ios() && !msl_options.supports_msl_version(2, 2)) |
| 15147 | SPIRV_CROSS_THROW("Subgroup ballot functionality requires Metal 2.2 on iOS."); |
| 15148 | if (!msl_options.supports_msl_version(2, 1)) |
| 15149 | SPIRV_CROSS_THROW("Subgroup ballot functionality requires Metal 2.1."); |
| 15150 | if (msl_options.fixed_subgroup_size != 0) |
| 15151 | add_spv_func_and_recompile(SPVFuncImplSubgroupBallot); |
| 15152 | entry_func.fixup_hooks_in.push_back([=]() { |
| 15153 | // Case where index < 32, size < 32: |
| 15154 | // mask0 = bfi(0, 0xFFFFFFFF, index, size - index); |
| 15155 | // mask1 = bfi(0, 0xFFFFFFFF, 0, 0); // Gives 0 |
| 15156 | // Case where index < 32 but size >= 32: |
| 15157 | // mask0 = bfi(0, 0xFFFFFFFF, index, 32 - index); |
| 15158 | // mask1 = bfi(0, 0xFFFFFFFF, 0, size - 32); |
| 15159 | // Case where index >= 32: |
| 15160 | // mask0 = bfi(0, 0xFFFFFFFF, 32, 0); // Gives 0 |
| 15161 | // mask1 = bfi(0, 0xFFFFFFFF, index - 32, size - index); |
| 15162 | // This is expressed without branches to avoid divergent |
| 15163 | // control flow--hence the complicated min/max expressions. |
| 15164 | // This is further complicated by the fact that if you attempt |
| 15165 | // to bfi/bfe out-of-bounds on Metal, undefined behavior is the |
| 15166 | // result. |
| 15167 | if (msl_options.fixed_subgroup_size > 32) |
| 15168 | { |
| 15169 | // Don't use the subgroup size variable with fixed subgroup sizes, |
| 15170 | // since the variables could be defined in the wrong order. |
| 15171 | statement(builtin_type_decl(bi_type), " ", to_expression(var_id), |
| 15172 | " = uint4(insert_bits(0u, 0xFFFFFFFF, min(", |
| 15173 | to_expression(builtin_subgroup_invocation_id_id), ", 32u), (uint)max(32 - (int)", |
| 15174 | to_expression(builtin_subgroup_invocation_id_id), |
| 15175 | ", 0)), insert_bits(0u, 0xFFFFFFFF," |
| 15176 | " (uint)max((int)", |
| 15177 | to_expression(builtin_subgroup_invocation_id_id), " - 32, 0), ", |
| 15178 | msl_options.fixed_subgroup_size, " - max(", |
| 15179 | to_expression(builtin_subgroup_invocation_id_id), |
| 15180 | ", 32u)), uint2(0));"); |
| 15181 | } |
| 15182 | else if (msl_options.fixed_subgroup_size != 0) |
| 15183 | { |
| 15184 | statement(builtin_type_decl(bi_type), " ", to_expression(var_id), |
| 15185 | " = uint4(insert_bits(0u, 0xFFFFFFFF, ", |
| 15186 | to_expression(builtin_subgroup_invocation_id_id), ", ", |
| 15187 | msl_options.fixed_subgroup_size, " - ", |
| 15188 | to_expression(builtin_subgroup_invocation_id_id), |
| 15189 | "), uint3(0));"); |
| 15190 | } |
| 15191 | else if (msl_options.is_ios()) |
| 15192 | { |
| 15193 | // On iOS, the SIMD-group size will currently never exceed 32. |
| 15194 | statement(builtin_type_decl(bi_type), " ", to_expression(var_id), |
| 15195 | " = uint4(insert_bits(0u, 0xFFFFFFFF, ", |
| 15196 | to_expression(builtin_subgroup_invocation_id_id), ", ", |
| 15197 | to_expression(builtin_subgroup_size_id), " - ", |
| 15198 | to_expression(builtin_subgroup_invocation_id_id), "), uint3(0));"); |
| 15199 | } |
| 15200 | else |
| 15201 | { |
| 15202 | statement(builtin_type_decl(bi_type), " ", to_expression(var_id), |
| 15203 | " = uint4(insert_bits(0u, 0xFFFFFFFF, min(", |
| 15204 | to_expression(builtin_subgroup_invocation_id_id), ", 32u), (uint)max(min((int)", |
| 15205 | to_expression(builtin_subgroup_size_id), ", 32) - (int)", |
| 15206 | to_expression(builtin_subgroup_invocation_id_id), |
| 15207 | ", 0)), insert_bits(0u, 0xFFFFFFFF, (uint)max((int)", |
| 15208 | to_expression(builtin_subgroup_invocation_id_id), " - 32, 0), (uint)max((int)", |
| 15209 | to_expression(builtin_subgroup_size_id), " - (int)max(", |
| 15210 | to_expression(builtin_subgroup_invocation_id_id), ", 32u), 0)), uint2(0));"); |
| 15211 | } |
| 15212 | }); |
| 15213 | break; |
| 15214 | case BuiltInSubgroupGtMask: |
| 15215 | if (msl_options.is_ios() && !msl_options.supports_msl_version(2, 2)) |
| 15216 | SPIRV_CROSS_THROW("Subgroup ballot functionality requires Metal 2.2 on iOS."); |
| 15217 | if (!msl_options.supports_msl_version(2, 1)) |
| 15218 | SPIRV_CROSS_THROW("Subgroup ballot functionality requires Metal 2.1."); |
| 15219 | add_spv_func_and_recompile(SPVFuncImplSubgroupBallot); |
| 15220 | entry_func.fixup_hooks_in.push_back([=]() { |
| 15221 | // The same logic applies here, except now the index is one |
| 15222 | // more than the subgroup invocation ID. |
| 15223 | if (msl_options.fixed_subgroup_size > 32) |
| 15224 | { |
| 15225 | statement(builtin_type_decl(bi_type), " ", to_expression(var_id), |
| 15226 | " = uint4(insert_bits(0u, 0xFFFFFFFF, min(", |
| 15227 | to_expression(builtin_subgroup_invocation_id_id), " + 1, 32u), (uint)max(32 - (int)", |
| 15228 | to_expression(builtin_subgroup_invocation_id_id), |
| 15229 | " - 1, 0)), insert_bits(0u, 0xFFFFFFFF, (uint)max((int)", |
| 15230 | to_expression(builtin_subgroup_invocation_id_id), " + 1 - 32, 0), ", |
| 15231 | msl_options.fixed_subgroup_size, " - max(", |
| 15232 | to_expression(builtin_subgroup_invocation_id_id), |
| 15233 | " + 1, 32u)), uint2(0));"); |
| 15234 | } |
| 15235 | else if (msl_options.fixed_subgroup_size != 0) |
| 15236 | { |
| 15237 | statement(builtin_type_decl(bi_type), " ", to_expression(var_id), |
| 15238 | " = uint4(insert_bits(0u, 0xFFFFFFFF, ", |
| 15239 | to_expression(builtin_subgroup_invocation_id_id), " + 1, ", |
| 15240 | msl_options.fixed_subgroup_size, " - ", |
| 15241 | to_expression(builtin_subgroup_invocation_id_id), |
| 15242 | " - 1), uint3(0));"); |
| 15243 | } |
| 15244 | else if (msl_options.is_ios()) |
| 15245 | { |
| 15246 | statement(builtin_type_decl(bi_type), " ", to_expression(var_id), |
| 15247 | " = uint4(insert_bits(0u, 0xFFFFFFFF, ", |
| 15248 | to_expression(builtin_subgroup_invocation_id_id), " + 1, ", |
| 15249 | to_expression(builtin_subgroup_size_id), " - ", |
| 15250 | to_expression(builtin_subgroup_invocation_id_id), " - 1), uint3(0));"); |
| 15251 | } |
| 15252 | else |
| 15253 | { |
| 15254 | statement(builtin_type_decl(bi_type), " ", to_expression(var_id), |
| 15255 | " = uint4(insert_bits(0u, 0xFFFFFFFF, min(", |
| 15256 | to_expression(builtin_subgroup_invocation_id_id), " + 1, 32u), (uint)max(min((int)", |
| 15257 | to_expression(builtin_subgroup_size_id), ", 32) - (int)", |
| 15258 | to_expression(builtin_subgroup_invocation_id_id), |
| 15259 | " - 1, 0)), insert_bits(0u, 0xFFFFFFFF, (uint)max((int)", |
| 15260 | to_expression(builtin_subgroup_invocation_id_id), " + 1 - 32, 0), (uint)max((int)", |
| 15261 | to_expression(builtin_subgroup_size_id), " - (int)max(", |
| 15262 | to_expression(builtin_subgroup_invocation_id_id), " + 1, 32u), 0)), uint2(0));"); |
| 15263 | } |
| 15264 | }); |
| 15265 | break; |
| 15266 | case BuiltInSubgroupLeMask: |
| 15267 | if (msl_options.is_ios() && !msl_options.supports_msl_version(2, 2)) |
| 15268 | SPIRV_CROSS_THROW("Subgroup ballot functionality requires Metal 2.2 on iOS."); |
| 15269 | if (!msl_options.supports_msl_version(2, 1)) |
| 15270 | SPIRV_CROSS_THROW("Subgroup ballot functionality requires Metal 2.1."); |
| 15271 | add_spv_func_and_recompile(SPVFuncImplSubgroupBallot); |
| 15272 | entry_func.fixup_hooks_in.push_back([=]() { |
| 15273 | if (msl_options.is_ios()) |
| 15274 | { |
| 15275 | statement(builtin_type_decl(bi_type), " ", to_expression(var_id), |
| 15276 | " = uint4(extract_bits(0xFFFFFFFF, 0, ", |
| 15277 | to_expression(builtin_subgroup_invocation_id_id), " + 1), uint3(0));"); |
| 15278 | } |
| 15279 | else |
| 15280 | { |
| 15281 | statement(builtin_type_decl(bi_type), " ", to_expression(var_id), |
| 15282 | " = uint4(extract_bits(0xFFFFFFFF, 0, min(", |
| 15283 | to_expression(builtin_subgroup_invocation_id_id), |
| 15284 | " + 1, 32u)), extract_bits(0xFFFFFFFF, 0, (uint)max((int)", |
| 15285 | to_expression(builtin_subgroup_invocation_id_id), " + 1 - 32, 0)), uint2(0));"); |
| 15286 | } |
| 15287 | }); |
| 15288 | break; |
| 15289 | case BuiltInSubgroupLtMask: |
| 15290 | if (msl_options.is_ios() && !msl_options.supports_msl_version(2, 2)) |
| 15291 | SPIRV_CROSS_THROW("Subgroup ballot functionality requires Metal 2.2 on iOS."); |
| 15292 | if (!msl_options.supports_msl_version(2, 1)) |
| 15293 | SPIRV_CROSS_THROW("Subgroup ballot functionality requires Metal 2.1."); |
| 15294 | add_spv_func_and_recompile(SPVFuncImplSubgroupBallot); |
| 15295 | entry_func.fixup_hooks_in.push_back([=]() { |
| 15296 | if (msl_options.is_ios()) |
| 15297 | { |
| 15298 | statement(builtin_type_decl(bi_type), " ", to_expression(var_id), |
| 15299 | " = uint4(extract_bits(0xFFFFFFFF, 0, ", |
| 15300 | to_expression(builtin_subgroup_invocation_id_id), "), uint3(0));"); |
| 15301 | } |
| 15302 | else |
| 15303 | { |
| 15304 | statement(builtin_type_decl(bi_type), " ", to_expression(var_id), |
| 15305 | " = uint4(extract_bits(0xFFFFFFFF, 0, min(", |
| 15306 | to_expression(builtin_subgroup_invocation_id_id), |
| 15307 | ", 32u)), extract_bits(0xFFFFFFFF, 0, (uint)max((int)", |
| 15308 | to_expression(builtin_subgroup_invocation_id_id), " - 32, 0)), uint2(0));"); |
| 15309 | } |
| 15310 | }); |
| 15311 | break; |
| 15312 | case BuiltInViewIndex: |
| 15313 | if (!msl_options.multiview) |
| 15314 | { |
| 15315 | // According to the Vulkan spec, when not running under a multiview |
| 15316 | // render pass, ViewIndex is 0. |
| 15317 | entry_func.fixup_hooks_in.push_back([=]() { |
| 15318 | statement("const ", builtin_type_decl(bi_type), " ", to_expression(var_id), " = 0;"); |
| 15319 | }); |
| 15320 | } |
| 15321 | else if (msl_options.view_index_from_device_index) |
| 15322 | { |
| 15323 | // In this case, we take the view index from that of the device we're running on. |
| 15324 | entry_func.fixup_hooks_in.push_back([=]() { |
| 15325 | statement("const ", builtin_type_decl(bi_type), " ", to_expression(var_id), " = ", |
| 15326 | msl_options.device_index, ";"); |
| 15327 | }); |
| 15328 | // We actually don't want to set the render_target_array_index here. |
| 15329 | // Since every physical device is rendering a different view, |
| 15330 | // there's no need for layered rendering here. |
| 15331 | } |
| 15332 | else if (!msl_options.multiview_layered_rendering) |
| 15333 | { |
| 15334 | // In this case, the views are rendered one at a time. The view index, then, |
| 15335 | // is just the first part of the "view mask". |
| 15336 | entry_func.fixup_hooks_in.push_back([=]() { |
| 15337 | statement("const ", builtin_type_decl(bi_type), " ", to_expression(var_id), " = ", |
| 15338 | to_expression(view_mask_buffer_id), "[0];"); |
| 15339 | }); |
| 15340 | } |
| 15341 | else if (get_execution_model() == ExecutionModelFragment) |
| 15342 | { |
| 15343 | // Because we adjusted the view index in the vertex shader, we have to |
| 15344 | // adjust it back here. |
| 15345 | entry_func.fixup_hooks_in.push_back([=]() { |
| 15346 | statement(to_expression(var_id), " += ", to_expression(view_mask_buffer_id), "[0];"); |
| 15347 | }); |
| 15348 | } |
| 15349 | else if (get_execution_model() == ExecutionModelVertex) |
| 15350 | { |
| 15351 | // Metal provides no special support for multiview, so we smuggle |
| 15352 | // the view index in the instance index. |
| 15353 | entry_func.fixup_hooks_in.push_back([=]() { |
| 15354 | statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ", |
| 15355 | to_expression(view_mask_buffer_id), "[0] + (", to_expression(builtin_instance_idx_id), |
| 15356 | " - ", to_expression(builtin_base_instance_id), ") % ", |
| 15357 | to_expression(view_mask_buffer_id), "[1];"); |
| 15358 | statement(to_expression(builtin_instance_idx_id), " = (", |
| 15359 | to_expression(builtin_instance_idx_id), " - ", |
| 15360 | to_expression(builtin_base_instance_id), ") / ", to_expression(view_mask_buffer_id), |
| 15361 | "[1] + ", to_expression(builtin_base_instance_id), ";"); |
| 15362 | }); |
| 15363 | // In addition to setting the variable itself, we also need to |
| 15364 | // set the render_target_array_index with it on output. We have to |
| 15365 | // offset this by the base view index, because Metal isn't in on |
| 15366 | // our little game here. |
| 15367 | entry_func.fixup_hooks_out.push_back([=]() { |
| 15368 | statement(to_expression(builtin_layer_id), " = ", to_expression(var_id), " - ", |
| 15369 | to_expression(view_mask_buffer_id), "[0];"); |
| 15370 | }); |
| 15371 | } |
| 15372 | break; |
| 15373 | case BuiltInDeviceIndex: |
| 15374 | // Metal pipelines belong to the devices which create them, so we'll |
| 15375 | // need to create a MTLPipelineState for every MTLDevice in a grouped |
| 15376 | // VkDevice. We can assume, then, that the device index is constant. |
| 15377 | entry_func.fixup_hooks_in.push_back([=]() { |
| 15378 | statement("const ", builtin_type_decl(bi_type), " ", to_expression(var_id), " = ", |
| 15379 | msl_options.device_index, ";"); |
| 15380 | }); |
| 15381 | break; |
| 15382 | case BuiltInWorkgroupId: |
| 15383 | if (!msl_options.dispatch_base || !active_input_builtins.get(BuiltInWorkgroupId)) |
| 15384 | break; |
| 15385 | |
| 15386 | // The vkCmdDispatchBase() command lets the client set the base value |
| 15387 | // of WorkgroupId. Metal has no direct equivalent; we must make this |
| 15388 | // adjustment ourselves. |
| 15389 | entry_func.fixup_hooks_in.push_back([=]() { |
| 15390 | statement(to_expression(var_id), " += ", to_dereferenced_expression(builtin_dispatch_base_id), ";"); |
| 15391 | }); |
| 15392 | break; |
| 15393 | case BuiltInGlobalInvocationId: |
| 15394 | if (!msl_options.dispatch_base || !active_input_builtins.get(BuiltInGlobalInvocationId)) |
| 15395 | break; |
| 15396 | |
| 15397 | // GlobalInvocationId is defined as LocalInvocationId + WorkgroupId * WorkgroupSize. |
| 15398 | // This needs to be adjusted too. |
| 15399 | entry_func.fixup_hooks_in.push_back([=]() { |
| 15400 | auto &execution = this->get_entry_point(); |
| 15401 | uint32_t workgroup_size_id = execution.workgroup_size.constant; |
| 15402 | if (workgroup_size_id) |
| 15403 | statement(to_expression(var_id), " += ", to_dereferenced_expression(builtin_dispatch_base_id), |
| 15404 | " * ", to_expression(workgroup_size_id), ";"); |
| 15405 | else |
| 15406 | statement(to_expression(var_id), " += ", to_dereferenced_expression(builtin_dispatch_base_id), |
| 15407 | " * uint3(", execution.workgroup_size.x, ", ", execution.workgroup_size.y, ", ", |
| 15408 | execution.workgroup_size.z, ");"); |
| 15409 | }); |
| 15410 | break; |
| 15411 | case BuiltInVertexId: |
| 15412 | case BuiltInVertexIndex: |
| 15413 | // This is direct-mapped normally. |
| 15414 | if (!msl_options.vertex_for_tessellation) |
| 15415 | break; |
| 15416 | |
| 15417 | entry_func.fixup_hooks_in.push_back([=]() { |
| 15418 | builtin_declaration = true; |
| 15419 | switch (msl_options.vertex_index_type) |
| 15420 | { |
| 15421 | case Options::IndexType::None: |
| 15422 | statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ", |
| 15423 | to_expression(builtin_invocation_id_id), ".x + ", |
| 15424 | to_expression(builtin_dispatch_base_id), ".x;"); |
| 15425 | break; |
| 15426 | case Options::IndexType::UInt16: |
| 15427 | case Options::IndexType::UInt32: |
| 15428 | statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ", index_buffer_var_name, |
| 15429 | "[", to_expression(builtin_invocation_id_id), ".x] + ", |
| 15430 | to_expression(builtin_dispatch_base_id), ".x;"); |
| 15431 | break; |
| 15432 | } |
| 15433 | builtin_declaration = false; |
| 15434 | }); |
| 15435 | break; |
| 15436 | case BuiltInBaseVertex: |
| 15437 | // This is direct-mapped normally. |
| 15438 | if (!msl_options.vertex_for_tessellation) |
| 15439 | break; |
| 15440 | |
| 15441 | entry_func.fixup_hooks_in.push_back([=]() { |
| 15442 | statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ", |
| 15443 | to_expression(builtin_dispatch_base_id), ".x;"); |
| 15444 | }); |
| 15445 | break; |
| 15446 | case BuiltInInstanceId: |
| 15447 | case BuiltInInstanceIndex: |
| 15448 | // This is direct-mapped normally. |
| 15449 | if (!msl_options.vertex_for_tessellation) |
| 15450 | break; |
| 15451 | |
| 15452 | entry_func.fixup_hooks_in.push_back([=]() { |
| 15453 | builtin_declaration = true; |
| 15454 | statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ", |
| 15455 | to_expression(builtin_invocation_id_id), ".y + ", to_expression(builtin_dispatch_base_id), |
| 15456 | ".y;"); |
| 15457 | builtin_declaration = false; |
| 15458 | }); |
| 15459 | break; |
| 15460 | case BuiltInBaseInstance: |
| 15461 | // This is direct-mapped normally. |
| 15462 | if (!msl_options.vertex_for_tessellation) |
| 15463 | break; |
| 15464 | |
| 15465 | entry_func.fixup_hooks_in.push_back([=]() { |
| 15466 | statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ", |
| 15467 | to_expression(builtin_dispatch_base_id), ".y;"); |
| 15468 | }); |
| 15469 | break; |
| 15470 | default: |
| 15471 | break; |
| 15472 | } |
| 15473 | } |
| 15474 | else if (var.storage == StorageClassOutput && get_execution_model() == ExecutionModelFragment && |
| 15475 | is_builtin_variable(var) && active_output_builtins.get(bi_type)) |
| 15476 | { |
| 15477 | switch (bi_type) |
| 15478 | { |
| 15479 | case BuiltInSampleMask: |
| 15480 | if (has_additional_fixed_sample_mask()) |
| 15481 | { |
| 15482 | // If the additional fixed sample mask was set, we need to adjust the sample_mask |
| 15483 | // output to reflect that. If the shader outputs the sample_mask itself too, we need |
| 15484 | // to AND the two masks to get the final one. |
| 15485 | string op_str = does_shader_write_sample_mask ? " &= " : " = "; |
| 15486 | entry_func.fixup_hooks_out.push_back([=]() { |
| 15487 | statement(to_expression(builtin_sample_mask_id), op_str, additional_fixed_sample_mask_str(), ";"); |
| 15488 | }); |
| 15489 | } |
| 15490 | break; |
| 15491 | case BuiltInFragDepth: |
| 15492 | if (msl_options.input_attachment_is_ds_attachment && !writes_to_depth) |
| 15493 | { |
| 15494 | entry_func.fixup_hooks_out.push_back([=]() { |
| 15495 | statement(to_expression(builtin_frag_depth_id), " = ", to_expression(builtin_frag_coord_id), ".z;"); |
| 15496 | }); |
| 15497 | } |
| 15498 | break; |
| 15499 | default: |
| 15500 | break; |
| 15501 | } |
| 15502 | } |
| 15503 | }); |
| 15504 | } |
| 15505 | |
| 15506 | // Returns the Metal index of the resource of the specified type as used by the specified variable. |
| 15507 | uint32_t CompilerMSL::get_metal_resource_index(SPIRVariable &var, SPIRType::BaseType basetype, uint32_t plane) |
| 15508 | { |
| 15509 | auto &execution = get_entry_point(); |
| 15510 | auto &var_dec = ir.meta[var.self].decoration; |
| 15511 | auto &var_type = get<SPIRType>(var.basetype); |
| 15512 | uint32_t var_desc_set = (var.storage == StorageClassPushConstant) ? kPushConstDescSet : var_dec.set; |
| 15513 | uint32_t var_binding = (var.storage == StorageClassPushConstant) ? kPushConstBinding : var_dec.binding; |
| 15514 | |
| 15515 | // If a matching binding has been specified, find and use it. |
| 15516 | auto itr = resource_bindings.find({ execution.model, var_desc_set, var_binding }); |
| 15517 | |
| 15518 | // Atomic helper buffers for image atomics need to use secondary bindings as well. |
| 15519 | bool use_secondary_binding = (var_type.basetype == SPIRType::SampledImage && basetype == SPIRType::Sampler) || |
| 15520 | basetype == SPIRType::AtomicCounter; |
| 15521 | |
| 15522 | auto resource_decoration = |
| 15523 | use_secondary_binding ? SPIRVCrossDecorationResourceIndexSecondary : SPIRVCrossDecorationResourceIndexPrimary; |
| 15524 | |
| 15525 | if (plane == 1) |
| 15526 | resource_decoration = SPIRVCrossDecorationResourceIndexTertiary; |
| 15527 | if (plane == 2) |
| 15528 | resource_decoration = SPIRVCrossDecorationResourceIndexQuaternary; |
| 15529 | |
| 15530 | if (itr != end(resource_bindings)) |
| 15531 | { |
| 15532 | auto &remap = itr->second; |
| 15533 | remap.second = true; |
| 15534 | switch (basetype) |
| 15535 | { |
| 15536 | case SPIRType::Image: |
| 15537 | set_extended_decoration(var.self, resource_decoration, remap.first.msl_texture + plane); |
| 15538 | return remap.first.msl_texture + plane; |
| 15539 | case SPIRType::Sampler: |
| 15540 | set_extended_decoration(var.self, resource_decoration, remap.first.msl_sampler); |
| 15541 | return remap.first.msl_sampler; |
| 15542 | default: |
| 15543 | set_extended_decoration(var.self, resource_decoration, remap.first.msl_buffer); |
| 15544 | return remap.first.msl_buffer; |
| 15545 | } |
| 15546 | } |
| 15547 | |
| 15548 | // If we have already allocated an index, keep using it. |
| 15549 | if (has_extended_decoration(var.self, resource_decoration)) |
| 15550 | return get_extended_decoration(var.self, resource_decoration); |
| 15551 | |
| 15552 | auto &type = get<SPIRType>(var.basetype); |
| 15553 | |
| 15554 | if (type_is_msl_framebuffer_fetch(type)) |
| 15555 | { |
| 15556 | // Frame-buffer fetch gets its fallback resource index from the input attachment index, |
| 15557 | // which is then treated as color index. |
| 15558 | return get_decoration(var.self, DecorationInputAttachmentIndex); |
| 15559 | } |
| 15560 | else if (msl_options.enable_decoration_binding) |
| 15561 | { |
| 15562 | // Allow user to enable decoration binding. |
| 15563 | // If there is no explicit mapping of bindings to MSL, use the declared binding as a fallback. |
| 15564 | if (has_decoration(var.self, DecorationBinding)) |
| 15565 | { |
| 15566 | var_binding = get_decoration(var.self, DecorationBinding); |
| 15567 | // Avoid emitting sentinel bindings. |
| 15568 | if (var_binding < 0x80000000u) |
| 15569 | return var_binding; |
| 15570 | } |
| 15571 | } |
| 15572 | |
| 15573 | // If we did not explicitly remap, allocate bindings on demand. |
| 15574 | // We cannot reliably use Binding decorations since SPIR-V and MSL's binding models are very different. |
| 15575 | |
| 15576 | bool allocate_argument_buffer_ids = false; |
| 15577 | |
| 15578 | if (var.storage != StorageClassPushConstant) |
| 15579 | allocate_argument_buffer_ids = descriptor_set_is_argument_buffer(var_desc_set); |
| 15580 | |
| 15581 | uint32_t binding_stride = 1; |
| 15582 | for (uint32_t i = 0; i < uint32_t(type.array.size()); i++) |
| 15583 | binding_stride *= to_array_size_literal(type, i); |
| 15584 | |
| 15585 | // If a binding has not been specified, revert to incrementing resource indices. |
| 15586 | uint32_t resource_index; |
| 15587 | |
| 15588 | if (allocate_argument_buffer_ids) |
| 15589 | { |
| 15590 | // Allocate from a flat ID binding space. |
| 15591 | resource_index = next_metal_resource_ids[var_desc_set]; |
| 15592 | next_metal_resource_ids[var_desc_set] += binding_stride; |
| 15593 | } |
| 15594 | else |
| 15595 | { |
| 15596 | if (is_var_runtime_size_array(var)) |
| 15597 | { |
| 15598 | basetype = SPIRType::Struct; |
| 15599 | binding_stride = 1; |
| 15600 | } |
| 15601 | // Allocate from plain bindings which are allocated per resource type. |
| 15602 | switch (basetype) |
| 15603 | { |
| 15604 | case SPIRType::Image: |
| 15605 | resource_index = next_metal_resource_index_texture; |
| 15606 | next_metal_resource_index_texture += binding_stride; |
| 15607 | break; |
| 15608 | case SPIRType::Sampler: |
| 15609 | resource_index = next_metal_resource_index_sampler; |
| 15610 | next_metal_resource_index_sampler += binding_stride; |
| 15611 | break; |
| 15612 | default: |
| 15613 | resource_index = next_metal_resource_index_buffer; |
| 15614 | next_metal_resource_index_buffer += binding_stride; |
| 15615 | break; |
| 15616 | } |
| 15617 | } |
| 15618 | |
| 15619 | set_extended_decoration(var.self, resource_decoration, resource_index); |
| 15620 | return resource_index; |
| 15621 | } |
| 15622 | |
| 15623 | bool CompilerMSL::type_is_msl_framebuffer_fetch(const SPIRType &type) const |
| 15624 | { |
| 15625 | return type.basetype == SPIRType::Image && type.image.dim == DimSubpassData && |
| 15626 | msl_options.use_framebuffer_fetch_subpasses; |
| 15627 | } |
| 15628 | |
| 15629 | const char *CompilerMSL::descriptor_address_space(uint32_t id, StorageClass storage, const char *plain_address_space) const |
| 15630 | { |
| 15631 | if (msl_options.argument_buffers) |
| 15632 | { |
| 15633 | bool storage_class_is_descriptor = storage == StorageClassUniform || |
| 15634 | storage == StorageClassStorageBuffer || |
| 15635 | storage == StorageClassUniformConstant; |
| 15636 | |
| 15637 | uint32_t desc_set = get_decoration(id, DecorationDescriptorSet); |
| 15638 | if (storage_class_is_descriptor && descriptor_set_is_argument_buffer(desc_set)) |
| 15639 | { |
| 15640 | // An awkward case where we need to emit *more* address space declarations (yay!). |
| 15641 | // An example is where we pass down an array of buffer pointers to leaf functions. |
| 15642 | // It's a constant array containing pointers to constants. |
| 15643 | // The pointer array is always constant however. E.g. |
| 15644 | // device SSBO * constant (&array)[N]. |
| 15645 | // const device SSBO * constant (&array)[N]. |
| 15646 | // constant SSBO * constant (&array)[N]. |
| 15647 | // However, this only matters for argument buffers, since for MSL 1.0 style codegen, |
| 15648 | // we emit the buffer array on stack instead, and that seems to work just fine apparently. |
| 15649 | |
| 15650 | // If the argument was marked as being in device address space, any pointer to member would |
| 15651 | // be const device, not constant. |
| 15652 | if (argument_buffer_device_storage_mask & (1u << desc_set)) |
| 15653 | return "const device"; |
| 15654 | else |
| 15655 | return "constant"; |
| 15656 | } |
| 15657 | } |
| 15658 | |
| 15659 | return plain_address_space; |
| 15660 | } |
| 15661 | |
| 15662 | string CompilerMSL::argument_decl(const SPIRFunction::Parameter &arg) |
| 15663 | { |
| 15664 | auto &var = get<SPIRVariable>(arg.id); |
| 15665 | auto &var_type = get<SPIRType>(arg.type); |
| 15666 | StorageClass type_storage = var_type.storage; |
| 15667 | |
| 15668 | // Physical pointer types are passed by pointer, not reference. |
| 15669 | auto &data_type = get_variable_data_type(var); |
| 15670 | bool passed_by_value = is_physical_pointer(var_type); |
| 15671 | auto &type = passed_by_value ? var_type : data_type; |
| 15672 | |
| 15673 | // If we need to modify the name of the variable, make sure we use the original variable. |
| 15674 | // Our alias is just a shadow variable. |
| 15675 | uint32_t name_id = var.self; |
| 15676 | if (arg.alias_global_variable && var.basevariable) |
| 15677 | name_id = var.basevariable; |
| 15678 | |
| 15679 | bool constref = !arg.alias_global_variable && !passed_by_value && is_pointer(var_type) && arg.write_count == 0; |
| 15680 | // Framebuffer fetch is plain value, const looks out of place, but it is not wrong. |
| 15681 | // readonly coming from glslang is not reliable in all cases. |
| 15682 | if (type_is_msl_framebuffer_fetch(type) || type_storage == StorageClassPhysicalStorageBuffer) |
| 15683 | constref = false; |
| 15684 | else if (type_storage == StorageClassUniformConstant) |
| 15685 | constref = true; |
| 15686 | |
| 15687 | bool type_is_image = type.basetype == SPIRType::Image || type.basetype == SPIRType::SampledImage || |
| 15688 | type.basetype == SPIRType::Sampler; |
| 15689 | bool type_is_tlas = type.basetype == SPIRType::AccelerationStructure; |
| 15690 | |
| 15691 | // For opaque types we handle const later due to descriptor address spaces. |
| 15692 | const char *cv_qualifier = (constref && !type_is_image) ? "const " : ""; |
| 15693 | string decl; |
| 15694 | |
| 15695 | // If this is a combined image-sampler for a 2D image with floating-point type, |
| 15696 | // we emitted the 'spvDynamicImageSampler' type, and this is *not* an alias parameter |
| 15697 | // for a global, then we need to emit a "dynamic" combined image-sampler. |
| 15698 | // Unfortunately, this is necessary to properly support passing around |
| 15699 | // combined image-samplers with Y'CbCr conversions on them. |
| 15700 | bool is_dynamic_img_sampler = !arg.alias_global_variable && type.basetype == SPIRType::SampledImage && |
| 15701 | type.image.dim == Dim2D && type_is_floating_point(get<SPIRType>(type.image.type)) && |
| 15702 | spv_function_implementations.count(SPVFuncImplDynamicImageSampler); |
| 15703 | |
| 15704 | // Allow Metal to use the array<T> template to make arrays a value type |
| 15705 | string address_space = get_argument_address_space(var); |
| 15706 | bool builtin = has_decoration(var.self, DecorationBuiltIn); |
| 15707 | auto builtin_type = BuiltIn(get_decoration(arg.id, DecorationBuiltIn)); |
| 15708 | |
| 15709 | if (var.basevariable && (var.basevariable == stage_in_ptr_var_id || var.basevariable == stage_out_ptr_var_id)) |
| 15710 | decl = join(cv_qualifier, type_to_glsl(type, arg.id)); |
| 15711 | else if (builtin && !is_mesh_shader()) |
| 15712 | { |
| 15713 | // Only use templated array for Clip/Cull distance when feasible. |
| 15714 | // In other scenarios, we need need to override array length for tess levels (if used as outputs), |
| 15715 | // or we need to emit the expected type for builtins (uint vs int). |
| 15716 | auto storage = get<SPIRType>(var.basetype).storage; |
| 15717 | |
| 15718 | if (storage == StorageClassInput && |
| 15719 | (builtin_type == BuiltInTessLevelInner || builtin_type == BuiltInTessLevelOuter)) |
| 15720 | { |
| 15721 | is_using_builtin_array = false; |
| 15722 | } |
| 15723 | else if (builtin_type != BuiltInClipDistance && builtin_type != BuiltInCullDistance) |
| 15724 | { |
| 15725 | is_using_builtin_array = true; |
| 15726 | } |
| 15727 | |
| 15728 | if (storage == StorageClassOutput && variable_storage_requires_stage_io(storage) && |
| 15729 | !is_stage_output_builtin_masked(builtin_type)) |
| 15730 | is_using_builtin_array = true; |
| 15731 | |
| 15732 | if (is_using_builtin_array) |
| 15733 | decl = join(cv_qualifier, builtin_type_decl(builtin_type, arg.id)); |
| 15734 | else |
| 15735 | decl = join(cv_qualifier, type_to_glsl(type, arg.id)); |
| 15736 | } |
| 15737 | else if (is_var_runtime_size_array(var)) |
| 15738 | { |
| 15739 | const auto *parent_type = &get<SPIRType>(type.parent_type); |
| 15740 | auto type_name = type_to_glsl(*parent_type, arg.id); |
| 15741 | if (type.basetype == SPIRType::AccelerationStructure) |
| 15742 | decl = join("spvDescriptorArray<", type_name, ">"); |
| 15743 | else if (type_is_image) |
| 15744 | decl = join("spvDescriptorArray<", cv_qualifier, type_name, ">"); |
| 15745 | else |
| 15746 | decl = join("spvDescriptorArray<", address_space, " ", type_name, "*>"); |
| 15747 | address_space = "const"; |
| 15748 | } |
| 15749 | else if ((type_storage == StorageClassUniform || type_storage == StorageClassStorageBuffer) && is_array(type)) |
| 15750 | { |
| 15751 | is_using_builtin_array = true; |
| 15752 | decl += join(cv_qualifier, type_to_glsl(type, arg.id), "*"); |
| 15753 | } |
| 15754 | else if (is_dynamic_img_sampler) |
| 15755 | { |
| 15756 | decl = join(cv_qualifier, "spvDynamicImageSampler<", type_to_glsl(get<SPIRType>(type.image.type)), ">"); |
| 15757 | // Mark the variable so that we can handle passing it to another function. |
| 15758 | set_extended_decoration(arg.id, SPIRVCrossDecorationDynamicImageSampler); |
| 15759 | } |
| 15760 | else |
| 15761 | { |
| 15762 | // The type is a pointer type we need to emit cv_qualifier late. |
| 15763 | if (is_pointer(data_type)) |
| 15764 | { |
| 15765 | decl = type_to_glsl(type, arg.id); |
| 15766 | if (*cv_qualifier != '\0') |
| 15767 | decl += join(" ", cv_qualifier); |
| 15768 | } |
| 15769 | else |
| 15770 | { |
| 15771 | decl = join(cv_qualifier, type_to_glsl(type, arg.id)); |
| 15772 | } |
| 15773 | } |
| 15774 | |
| 15775 | if (passed_by_value || (!builtin && !is_pointer(var_type) && |
| 15776 | (type_storage == StorageClassFunction || type_storage == StorageClassGeneric))) |
| 15777 | { |
| 15778 | // If the argument is a pure value and not an opaque type, we will pass by value. |
| 15779 | if (msl_options.force_native_arrays && is_array(type)) |
| 15780 | { |
| 15781 | // We are receiving an array by value. This is problematic. |
| 15782 | // We cannot be sure of the target address space since we are supposed to receive a copy, |
| 15783 | // but this is not possible with MSL without some extra work. |
| 15784 | // We will have to assume we're getting a reference in thread address space. |
| 15785 | // If we happen to get a reference in constant address space, the caller must emit a copy and pass that. |
| 15786 | // Thread const therefore becomes the only logical choice, since we cannot "create" a constant array from |
| 15787 | // non-constant arrays, but we can create thread const from constant. |
| 15788 | decl = string("thread const ") + decl; |
| 15789 | decl += " (&"; |
| 15790 | const char *restrict_kw = to_restrict(name_id, true); |
| 15791 | if (*restrict_kw) |
| 15792 | { |
| 15793 | decl += " "; |
| 15794 | decl += restrict_kw; |
| 15795 | } |
| 15796 | decl += to_expression(name_id); |
| 15797 | decl += ")"; |
| 15798 | decl += type_to_array_glsl(type, name_id); |
| 15799 | } |
| 15800 | else |
| 15801 | { |
| 15802 | if (!address_space.empty()) |
| 15803 | decl = join(address_space, " ", decl); |
| 15804 | decl += " "; |
| 15805 | decl += to_expression(name_id); |
| 15806 | } |
| 15807 | } |
| 15808 | else if (is_array(type) && !type_is_image) |
| 15809 | { |
| 15810 | // Arrays of opaque types are special cased. |
| 15811 | if (!address_space.empty()) |
| 15812 | decl = join(address_space, " ", decl); |
| 15813 | |
| 15814 | // spvDescriptorArray absorbs the address space inside the template. |
| 15815 | if (!is_var_runtime_size_array(var)) |
| 15816 | { |
| 15817 | const char *argument_buffer_space = descriptor_address_space(name_id, type_storage, nullptr); |
| 15818 | if (argument_buffer_space) |
| 15819 | { |
| 15820 | decl += " "; |
| 15821 | decl += argument_buffer_space; |
| 15822 | } |
| 15823 | } |
| 15824 | |
| 15825 | // Special case, need to override the array size here if we're using tess level as an argument. |
| 15826 | if (is_tesc_shader() && builtin && |
| 15827 | (builtin_type == BuiltInTessLevelInner || builtin_type == BuiltInTessLevelOuter)) |
| 15828 | { |
| 15829 | uint32_t array_size = get_physical_tess_level_array_size(builtin_type); |
| 15830 | if (array_size == 1) |
| 15831 | { |
| 15832 | decl += " &"; |
| 15833 | decl += to_expression(name_id); |
| 15834 | } |
| 15835 | else |
| 15836 | { |
| 15837 | decl += " (&"; |
| 15838 | decl += to_expression(name_id); |
| 15839 | decl += ")"; |
| 15840 | decl += join("[", array_size, "]"); |
| 15841 | } |
| 15842 | } |
| 15843 | else if (is_var_runtime_size_array(var)) |
| 15844 | { |
| 15845 | decl += " " + to_expression(name_id); |
| 15846 | } |
| 15847 | else |
| 15848 | { |
| 15849 | auto array_size_decl = type_to_array_glsl(type, name_id); |
| 15850 | if (array_size_decl.empty()) |
| 15851 | decl += "& "; |
| 15852 | else |
| 15853 | decl += " (&"; |
| 15854 | |
| 15855 | const char *restrict_kw = to_restrict(name_id, true); |
| 15856 | if (*restrict_kw) |
| 15857 | { |
| 15858 | decl += " "; |
| 15859 | decl += restrict_kw; |
| 15860 | } |
| 15861 | decl += to_expression(name_id); |
| 15862 | |
| 15863 | if (!array_size_decl.empty()) |
| 15864 | { |
| 15865 | decl += ")"; |
| 15866 | decl += array_size_decl; |
| 15867 | } |
| 15868 | } |
| 15869 | } |
| 15870 | else if (!type_is_image && !type_is_tlas && |
| 15871 | (!pull_model_inputs.count(var.basevariable) || type.basetype == SPIRType::Struct)) |
| 15872 | { |
| 15873 | // If this is going to be a reference to a variable pointer, the address space |
| 15874 | // for the reference has to go before the '&', but after the '*'. |
| 15875 | if (!address_space.empty()) |
| 15876 | { |
| 15877 | if (is_pointer(data_type)) |
| 15878 | { |
| 15879 | if (*cv_qualifier == '\0') |
| 15880 | decl += ' '; |
| 15881 | decl += join(address_space, " "); |
| 15882 | } |
| 15883 | else |
| 15884 | decl = join(address_space, " ", decl); |
| 15885 | } |
| 15886 | |
| 15887 | decl += "&"; |
| 15888 | decl += " "; |
| 15889 | decl += to_restrict(name_id, true); |
| 15890 | decl += to_expression(name_id); |
| 15891 | } |
| 15892 | else if (type_is_image || type_is_tlas) |
| 15893 | { |
| 15894 | if (is_var_runtime_size_array(var)) |
| 15895 | { |
| 15896 | decl = address_space + " " + decl + " " + to_expression(name_id); |
| 15897 | } |
| 15898 | else if (type.array.empty()) |
| 15899 | { |
| 15900 | // For non-arrayed types we can just pass opaque descriptors by value. |
| 15901 | // This fixes problems if descriptors are passed by value from argument buffers and plain descriptors |
| 15902 | // in same shader. |
| 15903 | // There is no address space we can actually use, but value will work. |
| 15904 | // This will break if applications attempt to pass down descriptor arrays as arguments, but |
| 15905 | // fortunately that is extremely unlikely ... |
| 15906 | decl += " "; |
| 15907 | decl += to_expression(name_id); |
| 15908 | } |
| 15909 | else |
| 15910 | { |
| 15911 | const char *img_address_space = descriptor_address_space(name_id, type_storage, "thread const"); |
| 15912 | decl = join(img_address_space, " ", decl); |
| 15913 | decl += "& "; |
| 15914 | decl += to_expression(name_id); |
| 15915 | } |
| 15916 | } |
| 15917 | else |
| 15918 | { |
| 15919 | if (!address_space.empty()) |
| 15920 | decl = join(address_space, " ", decl); |
| 15921 | decl += " "; |
| 15922 | decl += to_expression(name_id); |
| 15923 | } |
| 15924 | |
| 15925 | // Emulate texture2D atomic operations |
| 15926 | auto *backing_var = maybe_get_backing_variable(name_id); |
| 15927 | if (backing_var && atomic_image_vars_emulated.count(backing_var->self)) |
| 15928 | { |
| 15929 | auto &flags = ir.get_decoration_bitset(backing_var->self); |
| 15930 | const char *cv_flags = decoration_flags_signal_volatile(flags) ? "volatile " : ""; |
| 15931 | decl += join(", ", cv_flags, "device atomic_", type_to_glsl(get<SPIRType>(var_type.image.type), 0)); |
| 15932 | decl += "* " + to_expression(name_id) + "_atomic"; |
| 15933 | } |
| 15934 | |
| 15935 | is_using_builtin_array = false; |
| 15936 | |
| 15937 | return decl; |
| 15938 | } |
| 15939 | |
| 15940 | // If we're currently in the entry point function, and the object |
| 15941 | // has a qualified name, use it, otherwise use the standard name. |
| 15942 | string CompilerMSL::to_name(uint32_t id, bool allow_alias) const |
| 15943 | { |
| 15944 | if (current_function && (current_function->self == ir.default_entry_point)) |
| 15945 | { |
| 15946 | auto *m = ir.find_meta(id); |
| 15947 | if (m && !m->decoration.qualified_alias_explicit_override && !m->decoration.qualified_alias.empty()) |
| 15948 | return m->decoration.qualified_alias; |
| 15949 | } |
| 15950 | return Compiler::to_name(id, allow_alias); |
| 15951 | } |
| 15952 | |
| 15953 | // Appends the name of the member to the variable qualifier string, except for Builtins. |
| 15954 | string CompilerMSL::append_member_name(const string &qualifier, const SPIRType &type, uint32_t index) |
| 15955 | { |
| 15956 | // Don't qualify Builtin names because they are unique and are treated as such when building expressions |
| 15957 | BuiltIn builtin = BuiltInMax; |
| 15958 | if (is_member_builtin(type, index, &builtin)) |
| 15959 | return builtin_to_glsl(builtin, type.storage); |
| 15960 | |
| 15961 | // Strip any underscore prefix from member name |
| 15962 | string mbr_name = to_member_name(type, index); |
| 15963 | size_t startPos = mbr_name.find_first_not_of("_"); |
| 15964 | mbr_name = (startPos != string::npos) ? mbr_name.substr(startPos) : ""; |
| 15965 | return join(qualifier, "_", mbr_name); |
| 15966 | } |
| 15967 | |
| 15968 | // Ensures that the specified name is permanently usable by prepending a prefix |
| 15969 | // if the first chars are _ and a digit, which indicate a transient name. |
| 15970 | string CompilerMSL::ensure_valid_name(string name, string pfx) |
| 15971 | { |
| 15972 | return (name.size() >= 2 && name[0] == '_' && isdigit(name[1])) ? (pfx + name) : name; |
| 15973 | } |
| 15974 | |
| 15975 | const std::unordered_set<std::string> &CompilerMSL::get_reserved_keyword_set() |
| 15976 | { |
| 15977 | static const unordered_set<string> keywords = { |
| 15978 | "kernel", |
| 15979 | "vertex", |
| 15980 | "fragment", |
| 15981 | "compute", |
| 15982 | "constant", |
| 15983 | "device", |
| 15984 | "bias", |
| 15985 | "level", |
| 15986 | "gradient2d", |
| 15987 | "gradientcube", |
| 15988 | "gradient3d", |
| 15989 | "min_lod_clamp", |
| 15990 | "assert", |
| 15991 | "VARIABLE_TRACEPOINT", |
| 15992 | "STATIC_DATA_TRACEPOINT", |
| 15993 | "STATIC_DATA_TRACEPOINT_V", |
| 15994 | "METAL_ALIGN", |
| 15995 | "METAL_ASM", |
| 15996 | "METAL_CONST", |
| 15997 | "METAL_DEPRECATED", |
| 15998 | "METAL_ENABLE_IF", |
| 15999 | "METAL_FUNC", |
| 16000 | "METAL_INTERNAL", |
| 16001 | "METAL_NON_NULL_RETURN", |
| 16002 | "METAL_NORETURN", |
| 16003 | "METAL_NOTHROW", |
| 16004 | "METAL_PURE", |
| 16005 | "METAL_UNAVAILABLE", |
| 16006 | "METAL_IMPLICIT", |
| 16007 | "METAL_EXPLICIT", |
| 16008 | "METAL_CONST_ARG", |
| 16009 | "METAL_ARG_UNIFORM", |
| 16010 | "METAL_ZERO_ARG", |
| 16011 | "METAL_VALID_LOD_ARG", |
| 16012 | "METAL_VALID_LEVEL_ARG", |
| 16013 | "METAL_VALID_STORE_ORDER", |
| 16014 | "METAL_VALID_LOAD_ORDER", |
| 16015 | "METAL_VALID_COMPARE_EXCHANGE_FAILURE_ORDER", |
| 16016 | "METAL_COMPATIBLE_COMPARE_EXCHANGE_ORDERS", |
| 16017 | "METAL_VALID_RENDER_TARGET", |
| 16018 | "is_function_constant_defined", |
| 16019 | "CHAR_BIT", |
| 16020 | "SCHAR_MAX", |
| 16021 | "SCHAR_MIN", |
| 16022 | "UCHAR_MAX", |
| 16023 | "CHAR_MAX", |
| 16024 | "CHAR_MIN", |
| 16025 | "USHRT_MAX", |
| 16026 | "SHRT_MAX", |
| 16027 | "SHRT_MIN", |
| 16028 | "UINT_MAX", |
| 16029 | "INT_MAX", |
| 16030 | "INT_MIN", |
| 16031 | "FLT_DIG", |
| 16032 | "FLT_MANT_DIG", |
| 16033 | "FLT_MAX_10_EXP", |
| 16034 | "FLT_MAX_EXP", |
| 16035 | "FLT_MIN_10_EXP", |
| 16036 | "FLT_MIN_EXP", |
| 16037 | "FLT_RADIX", |
| 16038 | "FLT_MAX", |
| 16039 | "FLT_MIN", |
| 16040 | "FLT_EPSILON", |
| 16041 | "FP_ILOGB0", |
| 16042 | "FP_ILOGBNAN", |
| 16043 | "MAXFLOAT", |
| 16044 | "HUGE_VALF", |
| 16045 | "INFINITY", |
| 16046 | "NAN", |
| 16047 | "M_E_F", |
| 16048 | "M_LOG2E_F", |
| 16049 | "M_LOG10E_F", |
| 16050 | "M_LN2_F", |
| 16051 | "M_LN10_F", |
| 16052 | "M_PI_F", |
| 16053 | "M_PI_2_F", |
| 16054 | "M_PI_4_F", |
| 16055 | "M_1_PI_F", |
| 16056 | "M_2_PI_F", |
| 16057 | "M_2_SQRTPI_F", |
| 16058 | "M_SQRT2_F", |
| 16059 | "M_SQRT1_2_F", |
| 16060 | "HALF_DIG", |
| 16061 | "HALF_MANT_DIG", |
| 16062 | "HALF_MAX_10_EXP", |
| 16063 | "HALF_MAX_EXP", |
| 16064 | "HALF_MIN_10_EXP", |
| 16065 | "HALF_MIN_EXP", |
| 16066 | "HALF_RADIX", |
| 16067 | "HALF_MAX", |
| 16068 | "HALF_MIN", |
| 16069 | "HALF_EPSILON", |
| 16070 | "MAXHALF", |
| 16071 | "HUGE_VALH", |
| 16072 | "M_E_H", |
| 16073 | "M_LOG2E_H", |
| 16074 | "M_LOG10E_H", |
| 16075 | "M_LN2_H", |
| 16076 | "M_LN10_H", |
| 16077 | "M_PI_H", |
| 16078 | "M_PI_2_H", |
| 16079 | "M_PI_4_H", |
| 16080 | "M_1_PI_H", |
| 16081 | "M_2_PI_H", |
| 16082 | "M_2_SQRTPI_H", |
| 16083 | "M_SQRT2_H", |
| 16084 | "M_SQRT1_2_H", |
| 16085 | "DBL_DIG", |
| 16086 | "DBL_MANT_DIG", |
| 16087 | "DBL_MAX_10_EXP", |
| 16088 | "DBL_MAX_EXP", |
| 16089 | "DBL_MIN_10_EXP", |
| 16090 | "DBL_MIN_EXP", |
| 16091 | "DBL_RADIX", |
| 16092 | "DBL_MAX", |
| 16093 | "DBL_MIN", |
| 16094 | "DBL_EPSILON", |
| 16095 | "HUGE_VAL", |
| 16096 | "M_E", |
| 16097 | "M_LOG2E", |
| 16098 | "M_LOG10E", |
| 16099 | "M_LN2", |
| 16100 | "M_LN10", |
| 16101 | "M_PI", |
| 16102 | "M_PI_2", |
| 16103 | "M_PI_4", |
| 16104 | "M_1_PI", |
| 16105 | "M_2_PI", |
| 16106 | "M_2_SQRTPI", |
| 16107 | "M_SQRT2", |
| 16108 | "M_SQRT1_2", |
| 16109 | "quad_broadcast", |
| 16110 | "thread", |
| 16111 | "threadgroup", |
| 16112 | }; |
| 16113 | |
| 16114 | return keywords; |
| 16115 | } |
| 16116 | |
| 16117 | const std::unordered_set<std::string> &CompilerMSL::get_illegal_func_names() |
| 16118 | { |
| 16119 | static const unordered_set<string> illegal_func_names = { |
| 16120 | "main", |
| 16121 | "fragment", |
| 16122 | "vertex", |
| 16123 | "kernel", |
| 16124 | "saturate", |
| 16125 | "assert", |
| 16126 | "fmin3", |
| 16127 | "fmax3", |
| 16128 | "divide", |
| 16129 | "fmod", |
| 16130 | "median3", |
| 16131 | "VARIABLE_TRACEPOINT", |
| 16132 | "STATIC_DATA_TRACEPOINT", |
| 16133 | "STATIC_DATA_TRACEPOINT_V", |
| 16134 | "METAL_ALIGN", |
| 16135 | "METAL_ASM", |
| 16136 | "METAL_CONST", |
| 16137 | "METAL_DEPRECATED", |
| 16138 | "METAL_ENABLE_IF", |
| 16139 | "METAL_FUNC", |
| 16140 | "METAL_INTERNAL", |
| 16141 | "METAL_NON_NULL_RETURN", |
| 16142 | "METAL_NORETURN", |
| 16143 | "METAL_NOTHROW", |
| 16144 | "METAL_PURE", |
| 16145 | "METAL_UNAVAILABLE", |
| 16146 | "METAL_IMPLICIT", |
| 16147 | "METAL_EXPLICIT", |
| 16148 | "METAL_CONST_ARG", |
| 16149 | "METAL_ARG_UNIFORM", |
| 16150 | "METAL_ZERO_ARG", |
| 16151 | "METAL_VALID_LOD_ARG", |
| 16152 | "METAL_VALID_LEVEL_ARG", |
| 16153 | "METAL_VALID_STORE_ORDER", |
| 16154 | "METAL_VALID_LOAD_ORDER", |
| 16155 | "METAL_VALID_COMPARE_EXCHANGE_FAILURE_ORDER", |
| 16156 | "METAL_COMPATIBLE_COMPARE_EXCHANGE_ORDERS", |
| 16157 | "METAL_VALID_RENDER_TARGET", |
| 16158 | "is_function_constant_defined", |
| 16159 | "CHAR_BIT", |
| 16160 | "SCHAR_MAX", |
| 16161 | "SCHAR_MIN", |
| 16162 | "UCHAR_MAX", |
| 16163 | "CHAR_MAX", |
| 16164 | "CHAR_MIN", |
| 16165 | "USHRT_MAX", |
| 16166 | "SHRT_MAX", |
| 16167 | "SHRT_MIN", |
| 16168 | "UINT_MAX", |
| 16169 | "INT_MAX", |
| 16170 | "INT_MIN", |
| 16171 | "FLT_DIG", |
| 16172 | "FLT_MANT_DIG", |
| 16173 | "FLT_MAX_10_EXP", |
| 16174 | "FLT_MAX_EXP", |
| 16175 | "FLT_MIN_10_EXP", |
| 16176 | "FLT_MIN_EXP", |
| 16177 | "FLT_RADIX", |
| 16178 | "FLT_MAX", |
| 16179 | "FLT_MIN", |
| 16180 | "FLT_EPSILON", |
| 16181 | "FP_ILOGB0", |
| 16182 | "FP_ILOGBNAN", |
| 16183 | "MAXFLOAT", |
| 16184 | "HUGE_VALF", |
| 16185 | "INFINITY", |
| 16186 | "NAN", |
| 16187 | "M_E_F", |
| 16188 | "M_LOG2E_F", |
| 16189 | "M_LOG10E_F", |
| 16190 | "M_LN2_F", |
| 16191 | "M_LN10_F", |
| 16192 | "M_PI_F", |
| 16193 | "M_PI_2_F", |
| 16194 | "M_PI_4_F", |
| 16195 | "M_1_PI_F", |
| 16196 | "M_2_PI_F", |
| 16197 | "M_2_SQRTPI_F", |
| 16198 | "M_SQRT2_F", |
| 16199 | "M_SQRT1_2_F", |
| 16200 | "HALF_DIG", |
| 16201 | "HALF_MANT_DIG", |
| 16202 | "HALF_MAX_10_EXP", |
| 16203 | "HALF_MAX_EXP", |
| 16204 | "HALF_MIN_10_EXP", |
| 16205 | "HALF_MIN_EXP", |
| 16206 | "HALF_RADIX", |
| 16207 | "HALF_MAX", |
| 16208 | "HALF_MIN", |
| 16209 | "HALF_EPSILON", |
| 16210 | "MAXHALF", |
| 16211 | "HUGE_VALH", |
| 16212 | "M_E_H", |
| 16213 | "M_LOG2E_H", |
| 16214 | "M_LOG10E_H", |
| 16215 | "M_LN2_H", |
| 16216 | "M_LN10_H", |
| 16217 | "M_PI_H", |
| 16218 | "M_PI_2_H", |
| 16219 | "M_PI_4_H", |
| 16220 | "M_1_PI_H", |
| 16221 | "M_2_PI_H", |
| 16222 | "M_2_SQRTPI_H", |
| 16223 | "M_SQRT2_H", |
| 16224 | "M_SQRT1_2_H", |
| 16225 | "DBL_DIG", |
| 16226 | "DBL_MANT_DIG", |
| 16227 | "DBL_MAX_10_EXP", |
| 16228 | "DBL_MAX_EXP", |
| 16229 | "DBL_MIN_10_EXP", |
| 16230 | "DBL_MIN_EXP", |
| 16231 | "DBL_RADIX", |
| 16232 | "DBL_MAX", |
| 16233 | "DBL_MIN", |
| 16234 | "DBL_EPSILON", |
| 16235 | "HUGE_VAL", |
| 16236 | "M_E", |
| 16237 | "M_LOG2E", |
| 16238 | "M_LOG10E", |
| 16239 | "M_LN2", |
| 16240 | "M_LN10", |
| 16241 | "M_PI", |
| 16242 | "M_PI_2", |
| 16243 | "M_PI_4", |
| 16244 | "M_1_PI", |
| 16245 | "M_2_PI", |
| 16246 | "M_2_SQRTPI", |
| 16247 | "M_SQRT2", |
| 16248 | "M_SQRT1_2", |
| 16249 | }; |
| 16250 | |
| 16251 | return illegal_func_names; |
| 16252 | } |
| 16253 | |
| 16254 | // Replace all names that match MSL keywords or Metal Standard Library functions. |
| 16255 | void CompilerMSL::replace_illegal_names() |
| 16256 | { |
| 16257 | // FIXME: MSL and GLSL are doing two different things here. |
| 16258 | // Agree on convention and remove this override. |
| 16259 | auto &keywords = get_reserved_keyword_set(); |
| 16260 | auto &illegal_func_names = get_illegal_func_names(); |
| 16261 | |
| 16262 | ir.for_each_typed_id<SPIRVariable>([&](uint32_t self, SPIRVariable &) { |
| 16263 | auto *meta = ir.find_meta(self); |
| 16264 | if (!meta) |
| 16265 | return; |
| 16266 | |
| 16267 | auto &dec = meta->decoration; |
| 16268 | if (keywords.find(dec.alias) != end(keywords)) |
| 16269 | dec.alias += "0"; |
| 16270 | }); |
| 16271 | |
| 16272 | ir.for_each_typed_id<SPIRFunction>([&](uint32_t self, SPIRFunction &) { |
| 16273 | auto *meta = ir.find_meta(self); |
| 16274 | if (!meta) |
| 16275 | return; |
| 16276 | |
| 16277 | auto &dec = meta->decoration; |
| 16278 | if (illegal_func_names.find(dec.alias) != end(illegal_func_names)) |
| 16279 | dec.alias += "0"; |
| 16280 | }); |
| 16281 | |
| 16282 | ir.for_each_typed_id<SPIRType>([&](uint32_t self, SPIRType &) { |
| 16283 | auto *meta = ir.find_meta(self); |
| 16284 | if (!meta) |
| 16285 | return; |
| 16286 | |
| 16287 | for (auto &mbr_dec : meta->members) |
| 16288 | if (keywords.find(mbr_dec.alias) != end(keywords)) |
| 16289 | mbr_dec.alias += "0"; |
| 16290 | }); |
| 16291 | |
| 16292 | CompilerGLSL::replace_illegal_names(); |
| 16293 | } |
| 16294 | |
| 16295 | void CompilerMSL::replace_illegal_entry_point_names() |
| 16296 | { |
| 16297 | auto &illegal_func_names = get_illegal_func_names(); |
| 16298 | |
| 16299 | // It is important to this before we fixup identifiers, |
| 16300 | // since if ep_name is reserved, we will need to fix that up, |
| 16301 | // and then copy alias back into entry.name after the fixup. |
| 16302 | for (auto &entry : ir.entry_points) |
| 16303 | { |
| 16304 | // Change both the entry point name and the alias, to keep them synced. |
| 16305 | string &ep_name = entry.second.name; |
| 16306 | if (illegal_func_names.find(ep_name) != end(illegal_func_names)) |
| 16307 | ep_name += "0"; |
| 16308 | |
| 16309 | ir.meta[entry.first].decoration.alias = ep_name; |
| 16310 | } |
| 16311 | } |
| 16312 | |
| 16313 | void CompilerMSL::sync_entry_point_aliases_and_names() |
| 16314 | { |
| 16315 | for (auto &entry : ir.entry_points) |
| 16316 | entry.second.name = ir.meta[entry.first].decoration.alias; |
| 16317 | } |
| 16318 | |
| 16319 | string CompilerMSL::to_member_reference(uint32_t base, const SPIRType &type, uint32_t index, bool ptr_chain_is_resolved) |
| 16320 | { |
| 16321 | auto *var = maybe_get_backing_variable(base); |
| 16322 | // If this is a buffer array, we have to dereference the buffer pointers. |
| 16323 | // Otherwise, if this is a pointer expression, dereference it. |
| 16324 | |
| 16325 | bool declared_as_pointer = false; |
| 16326 | |
| 16327 | if (var) |
| 16328 | { |
| 16329 | // Only allow -> dereference for block types. This is so we get expressions like |
| 16330 | // buffer[i]->first_member.second_member, rather than buffer[i]->first->second. |
| 16331 | const bool is_block = |
| 16332 | has_decoration(type.self, DecorationBlock) || has_decoration(type.self, DecorationBufferBlock); |
| 16333 | |
| 16334 | bool is_buffer_variable = |
| 16335 | is_block && (var->storage == StorageClassUniform || var->storage == StorageClassStorageBuffer); |
| 16336 | declared_as_pointer = is_buffer_variable && is_array(get_pointee_type(var->basetype)); |
| 16337 | } |
| 16338 | |
| 16339 | if (declared_as_pointer || (!ptr_chain_is_resolved && should_dereference(base))) |
| 16340 | return join("->", to_member_name(type, index)); |
| 16341 | else |
| 16342 | return join(".", to_member_name(type, index)); |
| 16343 | } |
| 16344 | |
| 16345 | string CompilerMSL::to_qualifiers_glsl(uint32_t id) |
| 16346 | { |
| 16347 | string quals; |
| 16348 | |
| 16349 | auto *var = maybe_get<SPIRVariable>(id); |
| 16350 | auto &type = expression_type(id); |
| 16351 | |
| 16352 | if (type.storage == StorageClassTaskPayloadWorkgroupEXT) |
| 16353 | quals += "object_data "; |
| 16354 | |
| 16355 | if (type.storage == StorageClassWorkgroup || (var && variable_decl_is_remapped_storage(*var, StorageClassWorkgroup))) |
| 16356 | quals += "threadgroup "; |
| 16357 | |
| 16358 | return quals; |
| 16359 | } |
| 16360 | |
| 16361 | // The optional id parameter indicates the object whose type we are trying |
| 16362 | // to find the description for. It is optional. Most type descriptions do not |
| 16363 | // depend on a specific object's use of that type. |
| 16364 | string CompilerMSL::type_to_glsl(const SPIRType &type, uint32_t id, bool member) |
| 16365 | { |
| 16366 | string type_name; |
| 16367 | |
| 16368 | // Pointer? |
| 16369 | if (is_pointer(type) || type_is_array_of_pointers(type)) |
| 16370 | { |
| 16371 | assert(type.pointer_depth > 0); |
| 16372 | |
| 16373 | const char *restrict_kw; |
| 16374 | |
| 16375 | auto type_address_space = get_type_address_space(type, id); |
| 16376 | const auto *p_parent_type = &get<SPIRType>(type.parent_type); |
| 16377 | |
| 16378 | // If we're wrapping buffer descriptors in a spvDescriptorArray, we'll have to handle it as a special case. |
| 16379 | if (member && id) |
| 16380 | { |
| 16381 | auto &var = get<SPIRVariable>(id); |
| 16382 | if (is_var_runtime_size_array(var) && is_runtime_size_array(*p_parent_type)) |
| 16383 | { |
| 16384 | const bool ssbo = has_decoration(p_parent_type->self, DecorationBufferBlock); |
| 16385 | bool buffer_desc = |
| 16386 | (var.storage == StorageClassStorageBuffer || ssbo) && |
| 16387 | msl_options.runtime_array_rich_descriptor; |
| 16388 | |
| 16389 | const char *wrapper_type = buffer_desc ? "spvBufferDescriptor" : "spvDescriptor"; |
| 16390 | add_spv_func_and_recompile(SPVFuncImplVariableDescriptorArray); |
| 16391 | add_spv_func_and_recompile(buffer_desc ? SPVFuncImplVariableSizedDescriptor : SPVFuncImplVariableDescriptor); |
| 16392 | |
| 16393 | type_name = join(wrapper_type, "<", type_address_space, " ", type_to_glsl(*p_parent_type, id), " *>"); |
| 16394 | return type_name; |
| 16395 | } |
| 16396 | } |
| 16397 | |
| 16398 | // Work around C pointer qualifier rules. If glsl_type is a pointer type as well |
| 16399 | // we'll need to emit the address space to the right. |
| 16400 | // We could always go this route, but it makes the code unnatural. |
| 16401 | // Prefer emitting thread T *foo over T thread* foo since it's more readable, |
| 16402 | // but we'll have to emit thread T * thread * T constant bar; for example. |
| 16403 | if (is_pointer(type) && is_pointer(*p_parent_type)) |
| 16404 | type_name = join(type_to_glsl(*p_parent_type, id), " ", type_address_space, " "); |
| 16405 | else |
| 16406 | { |
| 16407 | // Since this is not a pointer-to-pointer, ensure we've dug down to the base type. |
| 16408 | // Some situations chain pointers even though they are not formally pointers-of-pointers. |
| 16409 | while (is_pointer(*p_parent_type)) |
| 16410 | p_parent_type = &get<SPIRType>(p_parent_type->parent_type); |
| 16411 | |
| 16412 | // If we're emitting BDA, just use the templated type. |
| 16413 | // Emitting builtin arrays need a lot of cooperation with other code to ensure |
| 16414 | // the C-style nesting works right. |
| 16415 | // FIXME: This is somewhat of a hack. |
| 16416 | bool old_is_using_builtin_array = is_using_builtin_array; |
| 16417 | if (is_physical_pointer(type)) |
| 16418 | is_using_builtin_array = false; |
| 16419 | |
| 16420 | type_name = join(type_address_space, " ", type_to_glsl(*p_parent_type, id)); |
| 16421 | |
| 16422 | is_using_builtin_array = old_is_using_builtin_array; |
| 16423 | } |
| 16424 | |
| 16425 | switch (type.basetype) |
| 16426 | { |
| 16427 | case SPIRType::Image: |
| 16428 | case SPIRType::SampledImage: |
| 16429 | case SPIRType::Sampler: |
| 16430 | // These are handles. |
| 16431 | break; |
| 16432 | default: |
| 16433 | // Anything else can be a raw pointer. |
| 16434 | type_name += "*"; |
| 16435 | restrict_kw = to_restrict(id, false); |
| 16436 | if (*restrict_kw) |
| 16437 | { |
| 16438 | type_name += " "; |
| 16439 | type_name += restrict_kw; |
| 16440 | } |
| 16441 | break; |
| 16442 | } |
| 16443 | return type_name; |
| 16444 | } |
| 16445 | |
| 16446 | switch (type.basetype) |
| 16447 | { |
| 16448 | case SPIRType::Struct: |
| 16449 | // Need OpName lookup here to get a "sensible" name for a struct. |
| 16450 | // Allow Metal to use the array<T> template to make arrays a value type |
| 16451 | type_name = to_name(type.self); |
| 16452 | break; |
| 16453 | |
| 16454 | case SPIRType::Image: |
| 16455 | case SPIRType::SampledImage: |
| 16456 | return image_type_glsl(type, id, member); |
| 16457 | |
| 16458 | case SPIRType::Sampler: |
| 16459 | return sampler_type(type, id, member); |
| 16460 | |
| 16461 | case SPIRType::Void: |
| 16462 | return "void"; |
| 16463 | |
| 16464 | case SPIRType::AtomicCounter: |
| 16465 | return "atomic_uint"; |
| 16466 | |
| 16467 | case SPIRType::ControlPointArray: |
| 16468 | return join("patch_control_point<", type_to_glsl(get<SPIRType>(type.parent_type), id), ">"); |
| 16469 | |
| 16470 | case SPIRType::Interpolant: |
| 16471 | return join("interpolant<", type_to_glsl(get<SPIRType>(type.parent_type), id), ", interpolation::", |
| 16472 | has_decoration(type.self, DecorationNoPerspective) ? "no_perspective" : "perspective", ">"); |
| 16473 | |
| 16474 | // Scalars |
| 16475 | case SPIRType::Boolean: |
| 16476 | { |
| 16477 | auto *var = maybe_get_backing_variable(id); |
| 16478 | if (var && var->basevariable) |
| 16479 | var = &get<SPIRVariable>(var->basevariable); |
| 16480 | |
| 16481 | // Need to special-case threadgroup booleans. They are supposed to be logical |
| 16482 | // storage, but MSL compilers will sometimes crash if you use threadgroup bool. |
| 16483 | // Workaround this by using 16-bit types instead and fixup on load-store to this data. |
| 16484 | if ((var && var->storage == StorageClassWorkgroup) || type.storage == StorageClassWorkgroup || member) |
| 16485 | type_name = "short"; |
| 16486 | else |
| 16487 | type_name = "bool"; |
| 16488 | break; |
| 16489 | } |
| 16490 | |
| 16491 | case SPIRType::Char: |
| 16492 | case SPIRType::SByte: |
| 16493 | type_name = "char"; |
| 16494 | break; |
| 16495 | case SPIRType::UByte: |
| 16496 | type_name = "uchar"; |
| 16497 | break; |
| 16498 | case SPIRType::Short: |
| 16499 | type_name = "short"; |
| 16500 | break; |
| 16501 | case SPIRType::UShort: |
| 16502 | type_name = "ushort"; |
| 16503 | break; |
| 16504 | case SPIRType::Int: |
| 16505 | type_name = "int"; |
| 16506 | break; |
| 16507 | case SPIRType::UInt: |
| 16508 | type_name = "uint"; |
| 16509 | break; |
| 16510 | case SPIRType::Int64: |
| 16511 | if (!msl_options.supports_msl_version(2, 2)) |
| 16512 | SPIRV_CROSS_THROW("64-bit integers are only supported in MSL 2.2 and above."); |
| 16513 | type_name = "long"; |
| 16514 | break; |
| 16515 | case SPIRType::UInt64: |
| 16516 | if (!msl_options.supports_msl_version(2, 2)) |
| 16517 | SPIRV_CROSS_THROW("64-bit integers are only supported in MSL 2.2 and above."); |
| 16518 | type_name = "ulong"; |
| 16519 | break; |
| 16520 | case SPIRType::Half: |
| 16521 | type_name = "half"; |
| 16522 | break; |
| 16523 | case SPIRType::Float: |
| 16524 | type_name = "float"; |
| 16525 | break; |
| 16526 | case SPIRType::Double: |
| 16527 | type_name = "double"; // Currently unsupported |
| 16528 | break; |
| 16529 | case SPIRType::AccelerationStructure: |
| 16530 | if (msl_options.supports_msl_version(2, 4)) |
| 16531 | type_name = "raytracing::acceleration_structure<raytracing::instancing>"; |
| 16532 | else if (msl_options.supports_msl_version(2, 3)) |
| 16533 | type_name = "raytracing::instance_acceleration_structure"; |
| 16534 | else |
| 16535 | SPIRV_CROSS_THROW("Acceleration Structure Type is supported in MSL 2.3 and above."); |
| 16536 | break; |
| 16537 | case SPIRType::RayQuery: |
| 16538 | return "raytracing::intersection_query<raytracing::instancing, raytracing::triangle_data>"; |
| 16539 | case SPIRType::MeshGridProperties: |
| 16540 | return "mesh_grid_properties"; |
| 16541 | |
| 16542 | default: |
| 16543 | return "unknown_type"; |
| 16544 | } |
| 16545 | |
| 16546 | // Matrix? |
| 16547 | if (type.columns > 1) |
| 16548 | { |
| 16549 | auto *var = maybe_get_backing_variable(id); |
| 16550 | if (var && var->basevariable) |
| 16551 | var = &get<SPIRVariable>(var->basevariable); |
| 16552 | |
| 16553 | // Need to special-case threadgroup matrices. Due to an oversight, Metal's |
| 16554 | // matrix struct prior to Metal 3 lacks constructors in the threadgroup AS, |
| 16555 | // preventing us from default-constructing or initializing matrices in threadgroup storage. |
| 16556 | // Work around this by using our own type as storage. |
| 16557 | if (((var && var->storage == StorageClassWorkgroup) || type.storage == StorageClassWorkgroup) && |
| 16558 | !msl_options.supports_msl_version(3, 0)) |
| 16559 | { |
| 16560 | add_spv_func_and_recompile(SPVFuncImplStorageMatrix); |
| 16561 | type_name = "spvStorage_" + type_name; |
| 16562 | } |
| 16563 | |
| 16564 | type_name += to_string(type.columns) + "x"; |
| 16565 | } |
| 16566 | |
| 16567 | // Vector or Matrix? |
| 16568 | if (type.vecsize > 1) |
| 16569 | type_name += to_string(type.vecsize); |
| 16570 | |
| 16571 | if (type.array.empty() || using_builtin_array()) |
| 16572 | { |
| 16573 | return type_name; |
| 16574 | } |
| 16575 | else |
| 16576 | { |
| 16577 | // Allow Metal to use the array<T> template to make arrays a value type |
| 16578 | add_spv_func_and_recompile(SPVFuncImplUnsafeArray); |
| 16579 | string res; |
| 16580 | string sizes; |
| 16581 | |
| 16582 | for (uint32_t i = 0; i < uint32_t(type.array.size()); i++) |
| 16583 | { |
| 16584 | res += "spvUnsafeArray<"; |
| 16585 | sizes += ", "; |
| 16586 | sizes += to_array_size(type, i); |
| 16587 | sizes += ">"; |
| 16588 | } |
| 16589 | |
| 16590 | res += type_name + sizes; |
| 16591 | return res; |
| 16592 | } |
| 16593 | } |
| 16594 | |
| 16595 | string CompilerMSL::type_to_glsl(const SPIRType &type, uint32_t id) |
| 16596 | { |
| 16597 | return type_to_glsl(type, id, false); |
| 16598 | } |
| 16599 | |
| 16600 | string CompilerMSL::type_to_array_glsl(const SPIRType &type, uint32_t variable_id) |
| 16601 | { |
| 16602 | // Allow Metal to use the array<T> template to make arrays a value type |
| 16603 | switch (type.basetype) |
| 16604 | { |
| 16605 | case SPIRType::AtomicCounter: |
| 16606 | case SPIRType::ControlPointArray: |
| 16607 | case SPIRType::RayQuery: |
| 16608 | return CompilerGLSL::type_to_array_glsl(type, variable_id); |
| 16609 | |
| 16610 | default: |
| 16611 | if (type_is_array_of_pointers(type) || using_builtin_array()) |
| 16612 | { |
| 16613 | const SPIRVariable *var = variable_id ? &get<SPIRVariable>(variable_id) : nullptr; |
| 16614 | if (var && (var->storage == StorageClassUniform || var->storage == StorageClassStorageBuffer) && |
| 16615 | is_array(get_variable_data_type(*var))) |
| 16616 | { |
| 16617 | return join("[", get_resource_array_size(type, variable_id), "]"); |
| 16618 | } |
| 16619 | else |
| 16620 | return CompilerGLSL::type_to_array_glsl(type, variable_id); |
| 16621 | } |
| 16622 | else |
| 16623 | return ""; |
| 16624 | } |
| 16625 | } |
| 16626 | |
| 16627 | string CompilerMSL::constant_op_expression(const SPIRConstantOp &cop) |
| 16628 | { |
| 16629 | switch (cop.opcode) |
| 16630 | { |
| 16631 | case OpSMod: |
| 16632 | add_spv_func_and_recompile(SPVFuncImplSMod); |
| 16633 | return join("spvSMod(", to_expression(cop.arguments[0]), ", ", to_expression(cop.arguments[1]), ")"); |
| 16634 | case OpQuantizeToF16: |
| 16635 | add_spv_func_and_recompile(SPVFuncImplQuantizeToF16); |
| 16636 | return join("spvQuantizeToF16(", to_expression(cop.arguments[0]), ")"); |
| 16637 | default: |
| 16638 | return CompilerGLSL::constant_op_expression(cop); |
| 16639 | } |
| 16640 | } |
| 16641 | |
| 16642 | bool CompilerMSL::variable_decl_is_remapped_storage(const SPIRVariable &variable, spv::StorageClass storage) const |
| 16643 | { |
| 16644 | if (variable.storage == storage) |
| 16645 | return true; |
| 16646 | |
| 16647 | if (storage == StorageClassWorkgroup) |
| 16648 | { |
| 16649 | // Specially masked IO block variable. |
| 16650 | // Normally, we will never access IO blocks directly here. |
| 16651 | // The only scenario which that should occur is with a masked IO block. |
| 16652 | if (is_tesc_shader() && variable.storage == StorageClassOutput && |
| 16653 | has_decoration(get<SPIRType>(variable.basetype).self, DecorationBlock)) |
| 16654 | { |
| 16655 | return true; |
| 16656 | } |
| 16657 | |
| 16658 | if (is_mesh_shader()) |
| 16659 | return variable.storage == StorageClassOutput; |
| 16660 | |
| 16661 | return variable.storage == StorageClassOutput && is_tesc_shader() && is_stage_output_variable_masked(variable); |
| 16662 | } |
| 16663 | else if (storage == StorageClassStorageBuffer) |
| 16664 | { |
| 16665 | // These builtins are passed directly; we don't want to use remapping |
| 16666 | // for them. |
| 16667 | auto builtin = (BuiltIn)get_decoration(variable.self, DecorationBuiltIn); |
| 16668 | if (is_tese_shader() && is_builtin_variable(variable) && (builtin == BuiltInTessCoord || builtin == BuiltInPrimitiveId)) |
| 16669 | return false; |
| 16670 | |
| 16671 | // We won't be able to catch writes to control point outputs here since variable |
| 16672 | // refers to a function local pointer. |
| 16673 | // This is fine, as there cannot be concurrent writers to that memory anyways, |
| 16674 | // so we just ignore that case. |
| 16675 | |
| 16676 | return (variable.storage == StorageClassOutput || variable.storage == StorageClassInput) && |
| 16677 | !variable_storage_requires_stage_io(variable.storage) && |
| 16678 | (variable.storage != StorageClassOutput || !is_stage_output_variable_masked(variable)); |
| 16679 | } |
| 16680 | else |
| 16681 | { |
| 16682 | return false; |
| 16683 | } |
| 16684 | } |
| 16685 | |
| 16686 | // GCC workaround of lambdas calling protected funcs |
| 16687 | std::string CompilerMSL::variable_decl(const SPIRType &type, const std::string &name, uint32_t id) |
| 16688 | { |
| 16689 | return CompilerGLSL::variable_decl(type, name, id); |
| 16690 | } |
| 16691 | |
| 16692 | std::string CompilerMSL::sampler_type(const SPIRType &type, uint32_t id, bool member) |
| 16693 | { |
| 16694 | auto *var = maybe_get<SPIRVariable>(id); |
| 16695 | if (var && var->basevariable) |
| 16696 | { |
| 16697 | // Check against the base variable, and not a fake ID which might have been generated for this variable. |
| 16698 | id = var->basevariable; |
| 16699 | } |
| 16700 | |
| 16701 | if (!type.array.empty()) |
| 16702 | { |
| 16703 | if (!msl_options.supports_msl_version(2)) |
| 16704 | SPIRV_CROSS_THROW("MSL 2.0 or greater is required for arrays of samplers."); |
| 16705 | |
| 16706 | if (type.array.size() > 1) |
| 16707 | SPIRV_CROSS_THROW("Arrays of arrays of samplers are not supported in MSL."); |
| 16708 | |
| 16709 | // Arrays of samplers in MSL must be declared with a special array<T, N> syntax ala C++11 std::array. |
| 16710 | // If we have a runtime array, it could be a variable-count descriptor set binding. |
| 16711 | auto &parent = get<SPIRType>(get_pointee_type(type).parent_type); |
| 16712 | uint32_t array_size = get_resource_array_size(type, id); |
| 16713 | |
| 16714 | if (array_size == 0) |
| 16715 | { |
| 16716 | add_spv_func_and_recompile(SPVFuncImplVariableDescriptor); |
| 16717 | add_spv_func_and_recompile(SPVFuncImplVariableDescriptorArray); |
| 16718 | |
| 16719 | const char *descriptor_wrapper = processing_entry_point ? "const device spvDescriptor" : "const spvDescriptorArray"; |
| 16720 | if (member) |
| 16721 | descriptor_wrapper = "spvDescriptor"; |
| 16722 | return join(descriptor_wrapper, "<", sampler_type(parent, id, false), ">", |
| 16723 | processing_entry_point ? "*" : ""); |
| 16724 | } |
| 16725 | else |
| 16726 | { |
| 16727 | return join("array<", sampler_type(parent, id, false), ", ", array_size, ">"); |
| 16728 | } |
| 16729 | } |
| 16730 | else |
| 16731 | return "sampler"; |
| 16732 | } |
| 16733 | |
| 16734 | // Returns an MSL string describing the SPIR-V image type |
| 16735 | string CompilerMSL::image_type_glsl(const SPIRType &type, uint32_t id, bool member) |
| 16736 | { |
| 16737 | auto *var = maybe_get<SPIRVariable>(id); |
| 16738 | if (var && var->basevariable) |
| 16739 | { |
| 16740 | // For comparison images, check against the base variable, |
| 16741 | // and not the fake ID which might have been generated for this variable. |
| 16742 | id = var->basevariable; |
| 16743 | } |
| 16744 | |
| 16745 | if (!type.array.empty()) |
| 16746 | { |
| 16747 | uint32_t major = 2, minor = 0; |
| 16748 | if (msl_options.is_ios()) |
| 16749 | { |
| 16750 | major = 1; |
| 16751 | minor = 2; |
| 16752 | } |
| 16753 | if (!msl_options.supports_msl_version(major, minor)) |
| 16754 | { |
| 16755 | if (msl_options.is_ios()) |
| 16756 | SPIRV_CROSS_THROW("MSL 1.2 or greater is required for arrays of textures."); |
| 16757 | else |
| 16758 | SPIRV_CROSS_THROW("MSL 2.0 or greater is required for arrays of textures."); |
| 16759 | } |
| 16760 | |
| 16761 | if (type.array.size() > 1) |
| 16762 | SPIRV_CROSS_THROW("Arrays of arrays of textures are not supported in MSL."); |
| 16763 | |
| 16764 | // Arrays of images in MSL must be declared with a special array<T, N> syntax ala C++11 std::array. |
| 16765 | // If we have a runtime array, it could be a variable-count descriptor set binding. |
| 16766 | auto &parent = get<SPIRType>(get_pointee_type(type).parent_type); |
| 16767 | uint32_t array_size = get_resource_array_size(type, id); |
| 16768 | |
| 16769 | if (array_size == 0) |
| 16770 | { |
| 16771 | add_spv_func_and_recompile(SPVFuncImplVariableDescriptor); |
| 16772 | add_spv_func_and_recompile(SPVFuncImplVariableDescriptorArray); |
| 16773 | const char *descriptor_wrapper = processing_entry_point ? "const device spvDescriptor" : "const spvDescriptorArray"; |
| 16774 | if (member) |
| 16775 | { |
| 16776 | descriptor_wrapper = "spvDescriptor"; |
| 16777 | // This requires a specialized wrapper type that packs image and sampler side by side. |
| 16778 | // It is possible in theory. |
| 16779 | if (type.basetype == SPIRType::SampledImage) |
| 16780 | SPIRV_CROSS_THROW("Argument buffer runtime array currently not supported for combined image sampler."); |
| 16781 | } |
| 16782 | return join(descriptor_wrapper, "<", image_type_glsl(parent, id, false), ">", |
| 16783 | processing_entry_point ? "*" : ""); |
| 16784 | } |
| 16785 | else |
| 16786 | { |
| 16787 | return join("array<", image_type_glsl(parent, id, false), ", ", array_size, ">"); |
| 16788 | } |
| 16789 | } |
| 16790 | |
| 16791 | string img_type_name; |
| 16792 | |
| 16793 | auto &img_type = type.image; |
| 16794 | |
| 16795 | if (is_depth_image(type, id)) |
| 16796 | { |
| 16797 | switch (img_type.dim) |
| 16798 | { |
| 16799 | case Dim1D: |
| 16800 | case Dim2D: |
| 16801 | if (img_type.dim == Dim1D && !msl_options.texture_1D_as_2D) |
| 16802 | { |
| 16803 | // Use a native Metal 1D texture |
| 16804 | img_type_name += "depth1d_unsupported_by_metal"; |
| 16805 | break; |
| 16806 | } |
| 16807 | |
| 16808 | if (img_type.ms && img_type.arrayed) |
| 16809 | { |
| 16810 | if (!msl_options.supports_msl_version(2, 1)) |
| 16811 | SPIRV_CROSS_THROW("Multisampled array textures are supported from 2.1."); |
| 16812 | img_type_name += "depth2d_ms_array"; |
| 16813 | } |
| 16814 | else if (img_type.ms) |
| 16815 | img_type_name += "depth2d_ms"; |
| 16816 | else if (img_type.arrayed) |
| 16817 | img_type_name += "depth2d_array"; |
| 16818 | else |
| 16819 | img_type_name += "depth2d"; |
| 16820 | break; |
| 16821 | case Dim3D: |
| 16822 | img_type_name += "depth3d_unsupported_by_metal"; |
| 16823 | break; |
| 16824 | case DimCube: |
| 16825 | if (!msl_options.emulate_cube_array) |
| 16826 | img_type_name += (img_type.arrayed ? "depthcube_array" : "depthcube"); |
| 16827 | else |
| 16828 | img_type_name += (img_type.arrayed ? "depth2d_array" : "depthcube"); |
| 16829 | break; |
| 16830 | default: |
| 16831 | img_type_name += "unknown_depth_texture_type"; |
| 16832 | break; |
| 16833 | } |
| 16834 | } |
| 16835 | else |
| 16836 | { |
| 16837 | switch (img_type.dim) |
| 16838 | { |
| 16839 | case DimBuffer: |
| 16840 | if (img_type.ms || img_type.arrayed) |
| 16841 | SPIRV_CROSS_THROW("Cannot use texel buffers with multisampling or array layers."); |
| 16842 | |
| 16843 | if (msl_options.texture_buffer_native) |
| 16844 | { |
| 16845 | if (!msl_options.supports_msl_version(2, 1)) |
| 16846 | SPIRV_CROSS_THROW("Native texture_buffer type is only supported in MSL 2.1."); |
| 16847 | img_type_name = "texture_buffer"; |
| 16848 | } |
| 16849 | else |
| 16850 | img_type_name += "texture2d"; |
| 16851 | break; |
| 16852 | case Dim1D: |
| 16853 | case Dim2D: |
| 16854 | case DimSubpassData: |
| 16855 | { |
| 16856 | bool subpass_array = |
| 16857 | img_type.dim == DimSubpassData && (msl_options.multiview || msl_options.arrayed_subpass_input); |
| 16858 | if (img_type.dim == Dim1D && !msl_options.texture_1D_as_2D) |
| 16859 | { |
| 16860 | // Use a native Metal 1D texture |
| 16861 | img_type_name += (img_type.arrayed ? "texture1d_array" : "texture1d"); |
| 16862 | break; |
| 16863 | } |
| 16864 | |
| 16865 | // Use Metal's native frame-buffer fetch API for subpass inputs. |
| 16866 | if (type_is_msl_framebuffer_fetch(type)) |
| 16867 | { |
| 16868 | auto img_type_4 = get<SPIRType>(img_type.type); |
| 16869 | img_type_4.vecsize = 4; |
| 16870 | return type_to_glsl(img_type_4); |
| 16871 | } |
| 16872 | if (img_type.ms && (img_type.arrayed || subpass_array)) |
| 16873 | { |
| 16874 | if (!msl_options.supports_msl_version(2, 1)) |
| 16875 | SPIRV_CROSS_THROW("Multisampled array textures are supported from 2.1."); |
| 16876 | img_type_name += "texture2d_ms_array"; |
| 16877 | } |
| 16878 | else if (img_type.ms) |
| 16879 | img_type_name += "texture2d_ms"; |
| 16880 | else if (img_type.arrayed || subpass_array) |
| 16881 | img_type_name += "texture2d_array"; |
| 16882 | else |
| 16883 | img_type_name += "texture2d"; |
| 16884 | break; |
| 16885 | } |
| 16886 | case Dim3D: |
| 16887 | img_type_name += "texture3d"; |
| 16888 | break; |
| 16889 | case DimCube: |
| 16890 | if (!msl_options.emulate_cube_array) |
| 16891 | img_type_name += (img_type.arrayed ? "texturecube_array" : "texturecube"); |
| 16892 | else |
| 16893 | img_type_name += (img_type.arrayed ? "texture2d_array" : "texturecube"); |
| 16894 | break; |
| 16895 | default: |
| 16896 | img_type_name += "unknown_texture_type"; |
| 16897 | break; |
| 16898 | } |
| 16899 | } |
| 16900 | |
| 16901 | // Append the pixel type |
| 16902 | img_type_name += "<"; |
| 16903 | img_type_name += type_to_glsl(get<SPIRType>(img_type.type)); |
| 16904 | |
| 16905 | // For unsampled images, append the sample/read/write access qualifier. |
| 16906 | // For kernel images, the access qualifier my be supplied directly by SPIR-V. |
| 16907 | // Otherwise it may be set based on whether the image is read from or written to within the shader. |
| 16908 | if (type.basetype == SPIRType::Image && type.image.sampled == 2 && type.image.dim != DimSubpassData) |
| 16909 | { |
| 16910 | auto *p_var = maybe_get_backing_variable(id); |
| 16911 | if (p_var && p_var->basevariable) |
| 16912 | p_var = maybe_get<SPIRVariable>(p_var->basevariable); |
| 16913 | |
| 16914 | bool has_access_qualifier = true; |
| 16915 | |
| 16916 | switch (img_type.access) |
| 16917 | { |
| 16918 | case AccessQualifierReadOnly: |
| 16919 | img_type_name += ", access::read"; |
| 16920 | break; |
| 16921 | |
| 16922 | case AccessQualifierWriteOnly: |
| 16923 | img_type_name += ", access::write"; |
| 16924 | break; |
| 16925 | |
| 16926 | case AccessQualifierReadWrite: |
| 16927 | img_type_name += ", access::read_write"; |
| 16928 | break; |
| 16929 | |
| 16930 | default: |
| 16931 | { |
| 16932 | if (p_var && !has_decoration(p_var->self, DecorationNonWritable)) |
| 16933 | { |
| 16934 | img_type_name += ", access::"; |
| 16935 | |
| 16936 | if (!has_decoration(p_var->self, DecorationNonReadable)) |
| 16937 | img_type_name += "read_"; |
| 16938 | |
| 16939 | img_type_name += "write"; |
| 16940 | } |
| 16941 | else |
| 16942 | { |
| 16943 | has_access_qualifier = false; |
| 16944 | } |
| 16945 | break; |
| 16946 | } |
| 16947 | } |
| 16948 | |
| 16949 | if (p_var && has_decoration(p_var->self, DecorationCoherent) && msl_options.supports_msl_version(3, 2)) |
| 16950 | { |
| 16951 | // Cannot declare memory_coherence_device without access qualifier. |
| 16952 | if (!has_access_qualifier) |
| 16953 | img_type_name += ", access::read"; |
| 16954 | img_type_name += ", memory_coherence_device"; |
| 16955 | } |
| 16956 | } |
| 16957 | |
| 16958 | img_type_name += ">"; |
| 16959 | |
| 16960 | return img_type_name; |
| 16961 | } |
| 16962 | |
| 16963 | void CompilerMSL::emit_subgroup_op(const Instruction &i) |
| 16964 | { |
| 16965 | const uint32_t *ops = stream(i); |
| 16966 | auto op = static_cast<Op>(i.op); |
| 16967 | |
| 16968 | if (msl_options.emulate_subgroups) |
| 16969 | { |
| 16970 | // In this mode, only the GroupNonUniform cap is supported. The only op |
| 16971 | // we need to handle, then, is OpGroupNonUniformElect. |
| 16972 | if (op != OpGroupNonUniformElect) |
| 16973 | SPIRV_CROSS_THROW("Subgroup emulation does not support operations other than Elect."); |
| 16974 | // In this mode, the subgroup size is assumed to be one, so every invocation |
| 16975 | // is elected. |
| 16976 | emit_op(ops[0], ops[1], "true", true); |
| 16977 | return; |
| 16978 | } |
| 16979 | |
| 16980 | // Metal 2.0 is required. iOS only supports quad ops on 11.0 (2.0), with |
| 16981 | // full support in 13.0 (2.2). macOS only supports broadcast and shuffle on |
| 16982 | // 10.13 (2.0), with full support in 10.14 (2.1). |
| 16983 | // Note that Apple GPUs before A13 make no distinction between a quad-group |
| 16984 | // and a SIMD-group; all SIMD-groups are quad-groups on those. |
| 16985 | if (!msl_options.supports_msl_version(2)) |
| 16986 | SPIRV_CROSS_THROW("Subgroups are only supported in Metal 2.0 and up."); |
| 16987 | |
| 16988 | // If we need to do implicit bitcasts, make sure we do it with the correct type. |
| 16989 | uint32_t integer_width = get_integer_width_for_instruction(i); |
| 16990 | auto int_type = to_signed_basetype(integer_width); |
| 16991 | auto uint_type = to_unsigned_basetype(integer_width); |
| 16992 | |
| 16993 | if (msl_options.is_ios() && (!msl_options.supports_msl_version(2, 3) || !msl_options.ios_use_simdgroup_functions)) |
| 16994 | { |
| 16995 | switch (op) |
| 16996 | { |
| 16997 | default: |
| 16998 | SPIRV_CROSS_THROW("Subgroup ops beyond broadcast, ballot, and shuffle on iOS require Metal 2.3 and up."); |
| 16999 | case OpGroupNonUniformBroadcastFirst: |
| 17000 | if (!msl_options.supports_msl_version(2, 2)) |
| 17001 | SPIRV_CROSS_THROW("BroadcastFirst on iOS requires Metal 2.2 and up."); |
| 17002 | break; |
| 17003 | case OpGroupNonUniformElect: |
| 17004 | if (!msl_options.supports_msl_version(2, 2)) |
| 17005 | SPIRV_CROSS_THROW("Elect on iOS requires Metal 2.2 and up."); |
| 17006 | break; |
| 17007 | case OpGroupNonUniformAny: |
| 17008 | case OpGroupNonUniformAll: |
| 17009 | case OpGroupNonUniformAllEqual: |
| 17010 | case OpGroupNonUniformBallot: |
| 17011 | case OpGroupNonUniformInverseBallot: |
| 17012 | case OpGroupNonUniformBallotBitExtract: |
| 17013 | case OpGroupNonUniformBallotFindLSB: |
| 17014 | case OpGroupNonUniformBallotFindMSB: |
| 17015 | case OpGroupNonUniformBallotBitCount: |
| 17016 | case OpSubgroupBallotKHR: |
| 17017 | case OpSubgroupAllKHR: |
| 17018 | case OpSubgroupAnyKHR: |
| 17019 | case OpSubgroupAllEqualKHR: |
| 17020 | if (!msl_options.supports_msl_version(2, 2)) |
| 17021 | SPIRV_CROSS_THROW("Ballot ops on iOS requires Metal 2.2 and up."); |
| 17022 | break; |
| 17023 | case OpGroupNonUniformRotateKHR: |
| 17024 | if (!msl_options.supports_msl_version(2, 2)) |
| 17025 | SPIRV_CROSS_THROW("Rotate on iOS requires Metal 2.2 and up."); |
| 17026 | break; |
| 17027 | case OpGroupNonUniformBroadcast: |
| 17028 | case OpGroupNonUniformShuffle: |
| 17029 | case OpGroupNonUniformShuffleXor: |
| 17030 | case OpGroupNonUniformShuffleUp: |
| 17031 | case OpGroupNonUniformShuffleDown: |
| 17032 | case OpGroupNonUniformQuadSwap: |
| 17033 | case OpGroupNonUniformQuadBroadcast: |
| 17034 | case OpSubgroupReadInvocationKHR: |
| 17035 | break; |
| 17036 | } |
| 17037 | } |
| 17038 | |
| 17039 | if (msl_options.is_macos() && !msl_options.supports_msl_version(2, 1)) |
| 17040 | { |
| 17041 | switch (op) |
| 17042 | { |
| 17043 | default: |
| 17044 | SPIRV_CROSS_THROW("Subgroup ops beyond broadcast and shuffle on macOS require Metal 2.1 and up."); |
| 17045 | case OpGroupNonUniformBroadcast: |
| 17046 | case OpGroupNonUniformShuffle: |
| 17047 | case OpGroupNonUniformShuffleXor: |
| 17048 | case OpGroupNonUniformShuffleUp: |
| 17049 | case OpGroupNonUniformShuffleDown: |
| 17050 | case OpSubgroupReadInvocationKHR: |
| 17051 | break; |
| 17052 | } |
| 17053 | } |
| 17054 | |
| 17055 | uint32_t op_idx = 0; |
| 17056 | uint32_t result_type = ops[op_idx++]; |
| 17057 | uint32_t id = ops[op_idx++]; |
| 17058 | |
| 17059 | Scope scope; |
| 17060 | switch (op) |
| 17061 | { |
| 17062 | // These earlier instructions don't have the scope operand. |
| 17063 | case OpSubgroupBallotKHR: |
| 17064 | case OpSubgroupFirstInvocationKHR: |
| 17065 | case OpSubgroupReadInvocationKHR: |
| 17066 | case OpSubgroupAllKHR: |
| 17067 | case OpSubgroupAnyKHR: |
| 17068 | case OpSubgroupAllEqualKHR: |
| 17069 | // These instructions are always quad-scoped and thus do not have a scope operand. |
| 17070 | case OpGroupNonUniformQuadAllKHR: |
| 17071 | case OpGroupNonUniformQuadAnyKHR: |
| 17072 | scope = ScopeSubgroup; |
| 17073 | break; |
| 17074 | default: |
| 17075 | scope = static_cast<Scope>(evaluate_constant_u32(ops[op_idx++])); |
| 17076 | break; |
| 17077 | } |
| 17078 | if (scope != ScopeSubgroup) |
| 17079 | SPIRV_CROSS_THROW("Only subgroup scope is supported."); |
| 17080 | |
| 17081 | switch (op) |
| 17082 | { |
| 17083 | case OpGroupNonUniformElect: |
| 17084 | if (msl_options.use_quadgroup_operation()) |
| 17085 | emit_op(result_type, id, "quad_is_first()", false); |
| 17086 | else |
| 17087 | emit_op(result_type, id, "simd_is_first()", false); |
| 17088 | break; |
| 17089 | |
| 17090 | case OpGroupNonUniformBroadcast: |
| 17091 | case OpSubgroupReadInvocationKHR: |
| 17092 | emit_binary_func_op(result_type, id, ops[op_idx], ops[op_idx + 1], "spvSubgroupBroadcast"); |
| 17093 | break; |
| 17094 | |
| 17095 | case OpGroupNonUniformBroadcastFirst: |
| 17096 | case OpSubgroupFirstInvocationKHR: |
| 17097 | emit_unary_func_op(result_type, id, ops[op_idx], "spvSubgroupBroadcastFirst"); |
| 17098 | break; |
| 17099 | |
| 17100 | case OpGroupNonUniformBallot: |
| 17101 | case OpSubgroupBallotKHR: |
| 17102 | emit_unary_func_op(result_type, id, ops[op_idx], "spvSubgroupBallot"); |
| 17103 | break; |
| 17104 | |
| 17105 | case OpGroupNonUniformInverseBallot: |
| 17106 | emit_binary_func_op(result_type, id, ops[op_idx], builtin_subgroup_invocation_id_id, "spvSubgroupBallotBitExtract"); |
| 17107 | break; |
| 17108 | |
| 17109 | case OpGroupNonUniformBallotBitExtract: |
| 17110 | emit_binary_func_op(result_type, id, ops[op_idx], ops[op_idx + 1], "spvSubgroupBallotBitExtract"); |
| 17111 | break; |
| 17112 | |
| 17113 | case OpGroupNonUniformBallotFindLSB: |
| 17114 | emit_binary_func_op(result_type, id, ops[op_idx], builtin_subgroup_size_id, "spvSubgroupBallotFindLSB"); |
| 17115 | break; |
| 17116 | |
| 17117 | case OpGroupNonUniformBallotFindMSB: |
| 17118 | emit_binary_func_op(result_type, id, ops[op_idx], builtin_subgroup_size_id, "spvSubgroupBallotFindMSB"); |
| 17119 | break; |
| 17120 | |
| 17121 | case OpGroupNonUniformBallotBitCount: |
| 17122 | { |
| 17123 | auto operation = static_cast<GroupOperation>(ops[op_idx++]); |
| 17124 | switch (operation) |
| 17125 | { |
| 17126 | case GroupOperationReduce: |
| 17127 | emit_binary_func_op(result_type, id, ops[op_idx], builtin_subgroup_size_id, "spvSubgroupBallotBitCount"); |
| 17128 | break; |
| 17129 | case GroupOperationInclusiveScan: |
| 17130 | emit_binary_func_op(result_type, id, ops[op_idx], builtin_subgroup_invocation_id_id, |
| 17131 | "spvSubgroupBallotInclusiveBitCount"); |
| 17132 | break; |
| 17133 | case GroupOperationExclusiveScan: |
| 17134 | emit_binary_func_op(result_type, id, ops[op_idx], builtin_subgroup_invocation_id_id, |
| 17135 | "spvSubgroupBallotExclusiveBitCount"); |
| 17136 | break; |
| 17137 | default: |
| 17138 | SPIRV_CROSS_THROW("Invalid BitCount operation."); |
| 17139 | } |
| 17140 | break; |
| 17141 | } |
| 17142 | |
| 17143 | case OpGroupNonUniformShuffle: |
| 17144 | emit_binary_func_op(result_type, id, ops[op_idx], ops[op_idx + 1], "spvSubgroupShuffle"); |
| 17145 | break; |
| 17146 | |
| 17147 | case OpGroupNonUniformShuffleXor: |
| 17148 | emit_binary_func_op(result_type, id, ops[op_idx], ops[op_idx + 1], "spvSubgroupShuffleXor"); |
| 17149 | break; |
| 17150 | |
| 17151 | case OpGroupNonUniformShuffleUp: |
| 17152 | emit_binary_func_op(result_type, id, ops[op_idx], ops[op_idx + 1], "spvSubgroupShuffleUp"); |
| 17153 | break; |
| 17154 | |
| 17155 | case OpGroupNonUniformShuffleDown: |
| 17156 | emit_binary_func_op(result_type, id, ops[op_idx], ops[op_idx + 1], "spvSubgroupShuffleDown"); |
| 17157 | break; |
| 17158 | |
| 17159 | case OpGroupNonUniformRotateKHR: |
| 17160 | { |
| 17161 | if (i.length > 5) |
| 17162 | { |
| 17163 | // MSL does not have a cluster size parameter, so calculate the invocation ID manually and using a shuffle. |
| 17164 | auto delta_expr = enclose_expression(to_unpacked_expression(ops[op_idx + 1])); |
| 17165 | auto cluster_size_minus_one = evaluate_constant_u32(ops[op_idx + 2]) - 1; |
| 17166 | auto local_id_expr = to_unpacked_expression(scope == ScopeSubgroup |
| 17167 | ? builtin_subgroup_invocation_id_id : builtin_local_invocation_index_id); |
| 17168 | auto shuffle_idx = join("((", local_id_expr, " + ", delta_expr, ")", " & ", std::to_string(cluster_size_minus_one), |
| 17169 | ") + (", local_id_expr, " & ", std::to_string(~cluster_size_minus_one), ")"); |
| 17170 | emit_op(result_type, id, join("spvSubgroupShuffle(", to_unpacked_expression(ops[op_idx]), ", ", shuffle_idx, ")"), false); |
| 17171 | } else |
| 17172 | emit_binary_func_op(result_type, id, ops[op_idx], ops[op_idx + 1], "spvSubgroupRotate"); |
| 17173 | break; |
| 17174 | } |
| 17175 | |
| 17176 | case OpGroupNonUniformAll: |
| 17177 | case OpSubgroupAllKHR: |
| 17178 | if (msl_options.use_quadgroup_operation()) |
| 17179 | emit_unary_func_op(result_type, id, ops[op_idx], "quad_all"); |
| 17180 | else |
| 17181 | emit_unary_func_op(result_type, id, ops[op_idx], "simd_all"); |
| 17182 | break; |
| 17183 | |
| 17184 | case OpGroupNonUniformAny: |
| 17185 | case OpSubgroupAnyKHR: |
| 17186 | if (msl_options.use_quadgroup_operation()) |
| 17187 | emit_unary_func_op(result_type, id, ops[op_idx], "quad_any"); |
| 17188 | else |
| 17189 | emit_unary_func_op(result_type, id, ops[op_idx], "simd_any"); |
| 17190 | break; |
| 17191 | |
| 17192 | case OpGroupNonUniformAllEqual: |
| 17193 | case OpSubgroupAllEqualKHR: |
| 17194 | emit_unary_func_op(result_type, id, ops[op_idx], "spvSubgroupAllEqual"); |
| 17195 | break; |
| 17196 | |
| 17197 | // clang-format off |
| 17198 | #define MSL_GROUP_OP(op, msl_op) \ |
| 17199 | case OpGroupNonUniform##op: \ |
| 17200 | { \ |
| 17201 | auto operation = static_cast<GroupOperation>(ops[op_idx++]); \ |
| 17202 | if (operation == GroupOperationReduce) \ |
| 17203 | emit_unary_func_op(result_type, id, ops[op_idx], "simd_" #msl_op); \ |
| 17204 | else if (operation == GroupOperationInclusiveScan) \ |
| 17205 | emit_unary_func_op(result_type, id, ops[op_idx], "simd_prefix_inclusive_" #msl_op); \ |
| 17206 | else if (operation == GroupOperationExclusiveScan) \ |
| 17207 | emit_unary_func_op(result_type, id, ops[op_idx], "simd_prefix_exclusive_" #msl_op); \ |
| 17208 | else if (operation == GroupOperationClusteredReduce) \ |
| 17209 | { \ |
| 17210 | uint32_t cluster_size = evaluate_constant_u32(ops[op_idx + 1]); \ |
| 17211 | if (get_execution_model() != ExecutionModelFragment || msl_options.supports_msl_version(2, 2)) \ |
| 17212 | add_spv_func_and_recompile(SPVFuncImplSubgroupClustered##op); \ |
| 17213 | emit_subgroup_cluster_op(result_type, id, cluster_size, ops[op_idx], #msl_op); \ |
| 17214 | } \ |
| 17215 | else \ |
| 17216 | SPIRV_CROSS_THROW("Invalid group operation."); \ |
| 17217 | break; \ |
| 17218 | } |
| 17219 | MSL_GROUP_OP(FAdd, sum) |
| 17220 | MSL_GROUP_OP(FMul, product) |
| 17221 | MSL_GROUP_OP(IAdd, sum) |
| 17222 | MSL_GROUP_OP(IMul, product) |
| 17223 | #undef MSL_GROUP_OP |
| 17224 | // The others, unfortunately, don't support InclusiveScan or ExclusiveScan. |
| 17225 | |
| 17226 | #define MSL_GROUP_OP(op, msl_op) \ |
| 17227 | case OpGroupNonUniform##op: \ |
| 17228 | { \ |
| 17229 | auto operation = static_cast<GroupOperation>(ops[op_idx++]); \ |
| 17230 | if (operation == GroupOperationReduce) \ |
| 17231 | emit_unary_func_op(result_type, id, ops[op_idx], "simd_" #msl_op); \ |
| 17232 | else if (operation == GroupOperationInclusiveScan) \ |
| 17233 | SPIRV_CROSS_THROW("Metal doesn't support InclusiveScan for OpGroupNonUniform" #op "."); \ |
| 17234 | else if (operation == GroupOperationExclusiveScan) \ |
| 17235 | SPIRV_CROSS_THROW("Metal doesn't support ExclusiveScan for OpGroupNonUniform" #op "."); \ |
| 17236 | else if (operation == GroupOperationClusteredReduce) \ |
| 17237 | { \ |
| 17238 | uint32_t cluster_size = evaluate_constant_u32(ops[op_idx + 1]); \ |
| 17239 | if (get_execution_model() != ExecutionModelFragment || msl_options.supports_msl_version(2, 2)) \ |
| 17240 | add_spv_func_and_recompile(SPVFuncImplSubgroupClustered##op); \ |
| 17241 | emit_subgroup_cluster_op(result_type, id, cluster_size, ops[op_idx], #msl_op); \ |
| 17242 | } \ |
| 17243 | else \ |
| 17244 | SPIRV_CROSS_THROW("Invalid group operation."); \ |
| 17245 | break; \ |
| 17246 | } |
| 17247 | |
| 17248 | #define MSL_GROUP_OP_CAST(op, msl_op, type) \ |
| 17249 | case OpGroupNonUniform##op: \ |
| 17250 | { \ |
| 17251 | auto operation = static_cast<GroupOperation>(ops[op_idx++]); \ |
| 17252 | if (operation == GroupOperationReduce) \ |
| 17253 | emit_unary_func_op_cast(result_type, id, ops[op_idx], "simd_" #msl_op, type, type); \ |
| 17254 | else if (operation == GroupOperationInclusiveScan) \ |
| 17255 | SPIRV_CROSS_THROW("Metal doesn't support InclusiveScan for OpGroupNonUniform" #op "."); \ |
| 17256 | else if (operation == GroupOperationExclusiveScan) \ |
| 17257 | SPIRV_CROSS_THROW("Metal doesn't support ExclusiveScan for OpGroupNonUniform" #op "."); \ |
| 17258 | else if (operation == GroupOperationClusteredReduce) \ |
| 17259 | { \ |
| 17260 | uint32_t cluster_size = evaluate_constant_u32(ops[op_idx + 1]); \ |
| 17261 | if (get_execution_model() != ExecutionModelFragment || msl_options.supports_msl_version(2, 2)) \ |
| 17262 | add_spv_func_and_recompile(SPVFuncImplSubgroupClustered##op); \ |
| 17263 | emit_subgroup_cluster_op_cast(result_type, id, cluster_size, ops[op_idx], #msl_op, type, type); \ |
| 17264 | } \ |
| 17265 | else \ |
| 17266 | SPIRV_CROSS_THROW("Invalid group operation."); \ |
| 17267 | break; \ |
| 17268 | } |
| 17269 | |
| 17270 | MSL_GROUP_OP(FMin, min) |
| 17271 | MSL_GROUP_OP(FMax, max) |
| 17272 | MSL_GROUP_OP_CAST(SMin, min, int_type) |
| 17273 | MSL_GROUP_OP_CAST(SMax, max, int_type) |
| 17274 | MSL_GROUP_OP_CAST(UMin, min, uint_type) |
| 17275 | MSL_GROUP_OP_CAST(UMax, max, uint_type) |
| 17276 | MSL_GROUP_OP(BitwiseAnd, and) |
| 17277 | MSL_GROUP_OP(BitwiseOr, or) |
| 17278 | MSL_GROUP_OP(BitwiseXor, xor) |
| 17279 | // Metal doesn't support boolean types in SIMD-group operations, so we |
| 17280 | // have to emit some casts. |
| 17281 | MSL_GROUP_OP_CAST(LogicalAnd, and, SPIRType::UShort) |
| 17282 | MSL_GROUP_OP_CAST(LogicalOr, or, SPIRType::UShort) |
| 17283 | MSL_GROUP_OP_CAST(LogicalXor, xor, SPIRType::UShort) |
| 17284 | // clang-format on |
| 17285 | #undef MSL_GROUP_OP |
| 17286 | #undef MSL_GROUP_OP_CAST |
| 17287 | |
| 17288 | case OpGroupNonUniformQuadSwap: |
| 17289 | emit_binary_func_op(result_type, id, ops[op_idx], ops[op_idx + 1], "spvQuadSwap"); |
| 17290 | break; |
| 17291 | |
| 17292 | case OpGroupNonUniformQuadBroadcast: |
| 17293 | emit_binary_func_op(result_type, id, ops[op_idx], ops[op_idx + 1], "spvQuadBroadcast"); |
| 17294 | break; |
| 17295 | |
| 17296 | case OpGroupNonUniformQuadAllKHR: |
| 17297 | emit_unary_func_op(result_type, id, ops[op_idx], "quad_all"); |
| 17298 | break; |
| 17299 | |
| 17300 | case OpGroupNonUniformQuadAnyKHR: |
| 17301 | emit_unary_func_op(result_type, id, ops[op_idx], "quad_any"); |
| 17302 | break; |
| 17303 | |
| 17304 | default: |
| 17305 | SPIRV_CROSS_THROW("Invalid opcode for subgroup."); |
| 17306 | } |
| 17307 | |
| 17308 | register_control_dependent_expression(id); |
| 17309 | } |
| 17310 | |
| 17311 | void CompilerMSL::emit_subgroup_cluster_op(uint32_t result_type, uint32_t result_id, uint32_t cluster_size, |
| 17312 | uint32_t op0, const char *op) |
| 17313 | { |
| 17314 | if (get_execution_model() == ExecutionModelFragment && !msl_options.supports_msl_version(2, 2)) |
| 17315 | { |
| 17316 | if (cluster_size == 4) |
| 17317 | { |
| 17318 | emit_unary_func_op(result_type, result_id, op0, join("quad_", op).c_str()); |
| 17319 | return; |
| 17320 | } |
| 17321 | SPIRV_CROSS_THROW("Cluster sizes other than 4 in fragment shaders require MSL 2.2."); |
| 17322 | } |
| 17323 | bool forward = should_forward(op0); |
| 17324 | emit_op(result_type, result_id, |
| 17325 | join("spvClustered_", op, "<", cluster_size, ">(", to_unpacked_expression(op0), ", ", |
| 17326 | to_expression(builtin_subgroup_invocation_id_id), ")"), |
| 17327 | forward); |
| 17328 | inherit_expression_dependencies(result_id, op0); |
| 17329 | } |
| 17330 | |
| 17331 | void CompilerMSL::emit_subgroup_cluster_op_cast(uint32_t result_type, uint32_t result_id, uint32_t cluster_size, |
| 17332 | uint32_t op0, const char *op, SPIRType::BaseType input_type, |
| 17333 | SPIRType::BaseType expected_result_type) |
| 17334 | { |
| 17335 | if (get_execution_model() == ExecutionModelFragment && !msl_options.supports_msl_version(2, 2)) |
| 17336 | { |
| 17337 | if (cluster_size == 4) |
| 17338 | { |
| 17339 | emit_unary_func_op_cast(result_type, result_id, op0, join("quad_", op).c_str(), input_type, |
| 17340 | expected_result_type); |
| 17341 | return; |
| 17342 | } |
| 17343 | SPIRV_CROSS_THROW("Cluster sizes other than 4 in fragment shaders require MSL 2.2."); |
| 17344 | } |
| 17345 | |
| 17346 | auto &out_type = get<SPIRType>(result_type); |
| 17347 | auto &expr_type = expression_type(op0); |
| 17348 | auto expected_type = out_type; |
| 17349 | |
| 17350 | // Bit-widths might be different in unary cases because we use it for SConvert/UConvert and friends. |
| 17351 | expected_type.basetype = input_type; |
| 17352 | expected_type.width = expr_type.width; |
| 17353 | |
| 17354 | string cast_op; |
| 17355 | if (expr_type.basetype != input_type) |
| 17356 | { |
| 17357 | if (expr_type.basetype == SPIRType::Boolean) |
| 17358 | cast_op = join(type_to_glsl(expected_type), "(", to_unpacked_expression(op0), ")"); |
| 17359 | else |
| 17360 | cast_op = bitcast_glsl(expected_type, op0); |
| 17361 | } |
| 17362 | else |
| 17363 | cast_op = to_unpacked_expression(op0); |
| 17364 | |
| 17365 | string sg_op = join("spvClustered_", op, "<", cluster_size, ">"); |
| 17366 | string expr; |
| 17367 | if (out_type.basetype != expected_result_type) |
| 17368 | { |
| 17369 | expected_type.basetype = expected_result_type; |
| 17370 | expected_type.width = out_type.width; |
| 17371 | if (out_type.basetype == SPIRType::Boolean) |
| 17372 | expr = type_to_glsl(out_type); |
| 17373 | else |
| 17374 | expr = bitcast_glsl_op(out_type, expected_type); |
| 17375 | expr += '('; |
| 17376 | expr += join(sg_op, "(", cast_op, ", ", to_expression(builtin_subgroup_invocation_id_id), ")"); |
| 17377 | expr += ')'; |
| 17378 | } |
| 17379 | else |
| 17380 | { |
| 17381 | expr += join(sg_op, "(", cast_op, ", ", to_expression(builtin_subgroup_invocation_id_id), ")"); |
| 17382 | } |
| 17383 | |
| 17384 | emit_op(result_type, result_id, expr, should_forward(op0)); |
| 17385 | inherit_expression_dependencies(result_id, op0); |
| 17386 | } |
| 17387 | |
| 17388 | string CompilerMSL::bitcast_glsl_op(const SPIRType &out_type, const SPIRType &in_type) |
| 17389 | { |
| 17390 | if (out_type.basetype == in_type.basetype) |
| 17391 | return ""; |
| 17392 | |
| 17393 | assert(out_type.basetype != SPIRType::Boolean); |
| 17394 | assert(in_type.basetype != SPIRType::Boolean); |
| 17395 | |
| 17396 | bool integral_cast = type_is_integral(out_type) && type_is_integral(in_type) && (out_type.vecsize == in_type.vecsize); |
| 17397 | bool same_size_cast = (out_type.width * out_type.vecsize) == (in_type.width * in_type.vecsize); |
| 17398 | |
| 17399 | // Bitcasting can only be used between types of the same overall size. |
| 17400 | // And always formally cast between integers, because it's trivial, and also |
| 17401 | // because Metal can internally cast the results of some integer ops to a larger |
| 17402 | // size (eg. short shift right becomes int), which means chaining integer ops |
| 17403 | // together may introduce size variations that SPIR-V doesn't know about. |
| 17404 | if (same_size_cast && !integral_cast) |
| 17405 | return "as_type<" + type_to_glsl(out_type) + ">"; |
| 17406 | else |
| 17407 | return type_to_glsl(out_type); |
| 17408 | } |
| 17409 | |
| 17410 | bool CompilerMSL::emit_complex_bitcast(uint32_t, uint32_t, uint32_t) |
| 17411 | { |
| 17412 | // This is handled from the outside where we deal with PtrToU/UToPtr and friends. |
| 17413 | return false; |
| 17414 | } |
| 17415 | |
| 17416 | // Returns an MSL string identifying the name of a SPIR-V builtin. |
| 17417 | // Output builtins are qualified with the name of the stage out structure. |
| 17418 | string CompilerMSL::builtin_to_glsl(BuiltIn builtin, StorageClass storage) |
| 17419 | { |
| 17420 | switch (builtin) |
| 17421 | { |
| 17422 | // Handle HLSL-style 0-based vertex/instance index. |
| 17423 | // Override GLSL compiler strictness |
| 17424 | case BuiltInVertexId: |
| 17425 | ensure_builtin(StorageClassInput, BuiltInVertexId); |
| 17426 | if (msl_options.enable_base_index_zero && msl_options.supports_msl_version(1, 1) && |
| 17427 | (msl_options.ios_support_base_vertex_instance || msl_options.is_macos())) |
| 17428 | { |
| 17429 | if (builtin_declaration) |
| 17430 | { |
| 17431 | if (needs_base_vertex_arg != TriState::No) |
| 17432 | needs_base_vertex_arg = TriState::Yes; |
| 17433 | return "gl_VertexID"; |
| 17434 | } |
| 17435 | else |
| 17436 | { |
| 17437 | ensure_builtin(StorageClassInput, BuiltInBaseVertex); |
| 17438 | return "(gl_VertexID - gl_BaseVertex)"; |
| 17439 | } |
| 17440 | } |
| 17441 | else |
| 17442 | { |
| 17443 | return "gl_VertexID"; |
| 17444 | } |
| 17445 | case BuiltInInstanceId: |
| 17446 | ensure_builtin(StorageClassInput, BuiltInInstanceId); |
| 17447 | if (msl_options.enable_base_index_zero && msl_options.supports_msl_version(1, 1) && |
| 17448 | (msl_options.ios_support_base_vertex_instance || msl_options.is_macos())) |
| 17449 | { |
| 17450 | if (builtin_declaration) |
| 17451 | { |
| 17452 | if (needs_base_instance_arg != TriState::No) |
| 17453 | needs_base_instance_arg = TriState::Yes; |
| 17454 | return "gl_InstanceID"; |
| 17455 | } |
| 17456 | else |
| 17457 | { |
| 17458 | ensure_builtin(StorageClassInput, BuiltInBaseInstance); |
| 17459 | return "(gl_InstanceID - gl_BaseInstance)"; |
| 17460 | } |
| 17461 | } |
| 17462 | else |
| 17463 | { |
| 17464 | return "gl_InstanceID"; |
| 17465 | } |
| 17466 | case BuiltInVertexIndex: |
| 17467 | ensure_builtin(StorageClassInput, BuiltInVertexIndex); |
| 17468 | if (msl_options.enable_base_index_zero && msl_options.supports_msl_version(1, 1) && |
| 17469 | (msl_options.ios_support_base_vertex_instance || msl_options.is_macos())) |
| 17470 | { |
| 17471 | if (builtin_declaration) |
| 17472 | { |
| 17473 | if (needs_base_vertex_arg != TriState::No) |
| 17474 | needs_base_vertex_arg = TriState::Yes; |
| 17475 | return "gl_VertexIndex"; |
| 17476 | } |
| 17477 | else |
| 17478 | { |
| 17479 | ensure_builtin(StorageClassInput, BuiltInBaseVertex); |
| 17480 | return "(gl_VertexIndex - gl_BaseVertex)"; |
| 17481 | } |
| 17482 | } |
| 17483 | else |
| 17484 | { |
| 17485 | return "gl_VertexIndex"; |
| 17486 | } |
| 17487 | case BuiltInInstanceIndex: |
| 17488 | ensure_builtin(StorageClassInput, BuiltInInstanceIndex); |
| 17489 | if (msl_options.enable_base_index_zero && msl_options.supports_msl_version(1, 1) && |
| 17490 | (msl_options.ios_support_base_vertex_instance || msl_options.is_macos())) |
| 17491 | { |
| 17492 | if (builtin_declaration) |
| 17493 | { |
| 17494 | if (needs_base_instance_arg != TriState::No) |
| 17495 | needs_base_instance_arg = TriState::Yes; |
| 17496 | return "gl_InstanceIndex"; |
| 17497 | } |
| 17498 | else |
| 17499 | { |
| 17500 | ensure_builtin(StorageClassInput, BuiltInBaseInstance); |
| 17501 | return "(gl_InstanceIndex - gl_BaseInstance)"; |
| 17502 | } |
| 17503 | } |
| 17504 | else |
| 17505 | { |
| 17506 | return "gl_InstanceIndex"; |
| 17507 | } |
| 17508 | case BuiltInBaseVertex: |
| 17509 | if (msl_options.supports_msl_version(1, 1) && |
| 17510 | (msl_options.ios_support_base_vertex_instance || msl_options.is_macos())) |
| 17511 | { |
| 17512 | needs_base_vertex_arg = TriState::No; |
| 17513 | return "gl_BaseVertex"; |
| 17514 | } |
| 17515 | else |
| 17516 | { |
| 17517 | SPIRV_CROSS_THROW("BaseVertex requires Metal 1.1 and Mac or Apple A9+ hardware."); |
| 17518 | } |
| 17519 | case BuiltInBaseInstance: |
| 17520 | if (msl_options.supports_msl_version(1, 1) && |
| 17521 | (msl_options.ios_support_base_vertex_instance || msl_options.is_macos())) |
| 17522 | { |
| 17523 | needs_base_instance_arg = TriState::No; |
| 17524 | return "gl_BaseInstance"; |
| 17525 | } |
| 17526 | else |
| 17527 | { |
| 17528 | SPIRV_CROSS_THROW("BaseInstance requires Metal 1.1 and Mac or Apple A9+ hardware."); |
| 17529 | } |
| 17530 | case BuiltInDrawIndex: |
| 17531 | SPIRV_CROSS_THROW("DrawIndex is not supported in MSL."); |
| 17532 | |
| 17533 | // When used in the entry function, output builtins are qualified with output struct name. |
| 17534 | // Test storage class as NOT Input, as output builtins might be part of generic type. |
| 17535 | // Also don't do this for tessellation control shaders. |
| 17536 | case BuiltInViewportIndex: |
| 17537 | if (!msl_options.supports_msl_version(2, 0)) |
| 17538 | SPIRV_CROSS_THROW("ViewportIndex requires Metal 2.0."); |
| 17539 | /* fallthrough */ |
| 17540 | case BuiltInFragDepth: |
| 17541 | case BuiltInFragStencilRefEXT: |
| 17542 | if ((builtin == BuiltInFragDepth && !msl_options.enable_frag_depth_builtin) || |
| 17543 | (builtin == BuiltInFragStencilRefEXT && !msl_options.enable_frag_stencil_ref_builtin)) |
| 17544 | break; |
| 17545 | /* fallthrough */ |
| 17546 | case BuiltInPosition: |
| 17547 | case BuiltInPointSize: |
| 17548 | case BuiltInClipDistance: |
| 17549 | case BuiltInCullDistance: |
| 17550 | case BuiltInLayer: |
| 17551 | if (is_tesc_shader()) |
| 17552 | break; |
| 17553 | if (is_mesh_shader()) |
| 17554 | break; |
| 17555 | if (storage != StorageClassInput && current_function && (current_function->self == ir.default_entry_point) && |
| 17556 | !is_stage_output_builtin_masked(builtin)) |
| 17557 | return stage_out_var_name + "." + CompilerGLSL::builtin_to_glsl(builtin, storage); |
| 17558 | break; |
| 17559 | |
| 17560 | case BuiltInSampleMask: |
| 17561 | if (storage == StorageClassInput && current_function && (current_function->self == ir.default_entry_point) && |
| 17562 | (has_additional_fixed_sample_mask() || needs_sample_id)) |
| 17563 | { |
| 17564 | string samp_mask_in; |
| 17565 | samp_mask_in += "(" + CompilerGLSL::builtin_to_glsl(builtin, storage); |
| 17566 | if (has_additional_fixed_sample_mask()) |
| 17567 | samp_mask_in += " & " + additional_fixed_sample_mask_str(); |
| 17568 | if (needs_sample_id) |
| 17569 | samp_mask_in += " & (1 << gl_SampleID)"; |
| 17570 | samp_mask_in += ")"; |
| 17571 | return samp_mask_in; |
| 17572 | } |
| 17573 | if (storage != StorageClassInput && current_function && (current_function->self == ir.default_entry_point) && |
| 17574 | !is_stage_output_builtin_masked(builtin)) |
| 17575 | return stage_out_var_name + "." + CompilerGLSL::builtin_to_glsl(builtin, storage); |
| 17576 | break; |
| 17577 | |
| 17578 | case BuiltInBaryCoordKHR: |
| 17579 | case BuiltInBaryCoordNoPerspKHR: |
| 17580 | if (storage == StorageClassInput && current_function && (current_function->self == ir.default_entry_point)) |
| 17581 | return stage_in_var_name + "." + CompilerGLSL::builtin_to_glsl(builtin, storage); |
| 17582 | break; |
| 17583 | |
| 17584 | case BuiltInTessLevelOuter: |
| 17585 | if (is_tesc_shader() && storage != StorageClassInput && current_function && |
| 17586 | (current_function->self == ir.default_entry_point)) |
| 17587 | { |
| 17588 | return join(tess_factor_buffer_var_name, "[", to_expression(builtin_primitive_id_id), |
| 17589 | "].edgeTessellationFactor"); |
| 17590 | } |
| 17591 | break; |
| 17592 | |
| 17593 | case BuiltInTessLevelInner: |
| 17594 | if (is_tesc_shader() && storage != StorageClassInput && current_function && |
| 17595 | (current_function->self == ir.default_entry_point)) |
| 17596 | { |
| 17597 | return join(tess_factor_buffer_var_name, "[", to_expression(builtin_primitive_id_id), |
| 17598 | "].insideTessellationFactor"); |
| 17599 | } |
| 17600 | break; |
| 17601 | |
| 17602 | case BuiltInHelperInvocation: |
| 17603 | if (needs_manual_helper_invocation_updates()) |
| 17604 | break; |
| 17605 | if (msl_options.is_ios() && !msl_options.supports_msl_version(2, 3)) |
| 17606 | SPIRV_CROSS_THROW("simd_is_helper_thread() requires version 2.3 on iOS."); |
| 17607 | else if (msl_options.is_macos() && !msl_options.supports_msl_version(2, 1)) |
| 17608 | SPIRV_CROSS_THROW("simd_is_helper_thread() requires version 2.1 on macOS."); |
| 17609 | // In SPIR-V 1.6 with Volatile HelperInvocation, we cannot emit a fixup early. |
| 17610 | return "simd_is_helper_thread()"; |
| 17611 | |
| 17612 | case BuiltInPrimitiveId: |
| 17613 | return "gl_PrimitiveID"; |
| 17614 | |
| 17615 | default: |
| 17616 | break; |
| 17617 | } |
| 17618 | |
| 17619 | return CompilerGLSL::builtin_to_glsl(builtin, storage); |
| 17620 | } |
| 17621 | |
| 17622 | // Returns an MSL string attribute qualifer for a SPIR-V builtin |
| 17623 | string CompilerMSL::builtin_qualifier(BuiltIn builtin) |
| 17624 | { |
| 17625 | auto &execution = get_entry_point(); |
| 17626 | |
| 17627 | switch (builtin) |
| 17628 | { |
| 17629 | // Vertex function in |
| 17630 | case BuiltInVertexId: |
| 17631 | return "vertex_id"; |
| 17632 | case BuiltInVertexIndex: |
| 17633 | return "vertex_id"; |
| 17634 | case BuiltInBaseVertex: |
| 17635 | return "base_vertex"; |
| 17636 | case BuiltInInstanceId: |
| 17637 | return "instance_id"; |
| 17638 | case BuiltInInstanceIndex: |
| 17639 | return "instance_id"; |
| 17640 | case BuiltInBaseInstance: |
| 17641 | return "base_instance"; |
| 17642 | case BuiltInDrawIndex: |
| 17643 | SPIRV_CROSS_THROW("DrawIndex is not supported in MSL."); |
| 17644 | |
| 17645 | // Vertex function out |
| 17646 | case BuiltInClipDistance: |
| 17647 | return "clip_distance"; |
| 17648 | case BuiltInCullDistance: |
| 17649 | return "cull_distance"; |
| 17650 | case BuiltInPointSize: |
| 17651 | return "point_size"; |
| 17652 | case BuiltInPosition: |
| 17653 | if (position_invariant) |
| 17654 | { |
| 17655 | if (!msl_options.supports_msl_version(2, 1)) |
| 17656 | SPIRV_CROSS_THROW("Invariant position is only supported on MSL 2.1 and up."); |
| 17657 | return "position, invariant"; |
| 17658 | } |
| 17659 | else |
| 17660 | return "position"; |
| 17661 | case BuiltInLayer: |
| 17662 | return "render_target_array_index"; |
| 17663 | case BuiltInViewportIndex: |
| 17664 | if (!msl_options.supports_msl_version(2, 0)) |
| 17665 | SPIRV_CROSS_THROW("ViewportIndex requires Metal 2.0."); |
| 17666 | return "viewport_array_index"; |
| 17667 | |
| 17668 | // Tess. control function in |
| 17669 | case BuiltInInvocationId: |
| 17670 | if (msl_options.multi_patch_workgroup) |
| 17671 | { |
| 17672 | // Shouldn't be reached. |
| 17673 | SPIRV_CROSS_THROW("InvocationId is computed manually with multi-patch workgroups in MSL."); |
| 17674 | } |
| 17675 | return "thread_index_in_threadgroup"; |
| 17676 | case BuiltInPatchVertices: |
| 17677 | // Shouldn't be reached. |
| 17678 | SPIRV_CROSS_THROW("PatchVertices is derived from the auxiliary buffer in MSL."); |
| 17679 | case BuiltInPrimitiveId: |
| 17680 | switch (execution.model) |
| 17681 | { |
| 17682 | case ExecutionModelTessellationControl: |
| 17683 | if (msl_options.multi_patch_workgroup) |
| 17684 | { |
| 17685 | // Shouldn't be reached. |
| 17686 | SPIRV_CROSS_THROW("PrimitiveId is computed manually with multi-patch workgroups in MSL."); |
| 17687 | } |
| 17688 | return "threadgroup_position_in_grid"; |
| 17689 | case ExecutionModelTessellationEvaluation: |
| 17690 | return "patch_id"; |
| 17691 | case ExecutionModelFragment: |
| 17692 | if (msl_options.is_ios() && !msl_options.supports_msl_version(2, 3)) |
| 17693 | SPIRV_CROSS_THROW("PrimitiveId on iOS requires MSL 2.3."); |
| 17694 | else if (msl_options.is_macos() && !msl_options.supports_msl_version(2, 2)) |
| 17695 | SPIRV_CROSS_THROW("PrimitiveId on macOS requires MSL 2.2."); |
| 17696 | return "primitive_id"; |
| 17697 | case ExecutionModelMeshEXT: |
| 17698 | return "primitive_id"; |
| 17699 | default: |
| 17700 | SPIRV_CROSS_THROW("PrimitiveId is not supported in this execution model."); |
| 17701 | } |
| 17702 | |
| 17703 | // Tess. control function out |
| 17704 | case BuiltInTessLevelOuter: |
| 17705 | case BuiltInTessLevelInner: |
| 17706 | // Shouldn't be reached. |
| 17707 | SPIRV_CROSS_THROW("Tessellation levels are handled specially in MSL."); |
| 17708 | |
| 17709 | // Tess. evaluation function in |
| 17710 | case BuiltInTessCoord: |
| 17711 | return "position_in_patch"; |
| 17712 | |
| 17713 | // Fragment function in |
| 17714 | case BuiltInFrontFacing: |
| 17715 | return "front_facing"; |
| 17716 | case BuiltInPointCoord: |
| 17717 | return "point_coord"; |
| 17718 | case BuiltInFragCoord: |
| 17719 | return "position"; |
| 17720 | case BuiltInSampleId: |
| 17721 | return "sample_id"; |
| 17722 | case BuiltInSampleMask: |
| 17723 | return "sample_mask"; |
| 17724 | case BuiltInSamplePosition: |
| 17725 | // Shouldn't be reached. |
| 17726 | SPIRV_CROSS_THROW("Sample position is retrieved by a function in MSL."); |
| 17727 | case BuiltInViewIndex: |
| 17728 | if (execution.model != ExecutionModelFragment && execution.model != ExecutionModelMeshEXT) |
| 17729 | SPIRV_CROSS_THROW("ViewIndex is handled specially outside fragment shaders."); |
| 17730 | // The ViewIndex was implicitly used in the prior stages to set the render_target_array_index, |
| 17731 | // so we can get it from there. |
| 17732 | return "render_target_array_index"; |
| 17733 | |
| 17734 | // Fragment function out |
| 17735 | case BuiltInFragDepth: |
| 17736 | if (execution.flags.get(ExecutionModeDepthGreater)) |
| 17737 | return "depth(greater)"; |
| 17738 | else if (execution.flags.get(ExecutionModeDepthLess)) |
| 17739 | return "depth(less)"; |
| 17740 | else |
| 17741 | return "depth(any)"; |
| 17742 | |
| 17743 | case BuiltInFragStencilRefEXT: |
| 17744 | return "stencil"; |
| 17745 | |
| 17746 | // Compute function in |
| 17747 | case BuiltInGlobalInvocationId: |
| 17748 | return "thread_position_in_grid"; |
| 17749 | |
| 17750 | case BuiltInWorkgroupSize: |
| 17751 | return "threads_per_threadgroup"; |
| 17752 | |
| 17753 | case BuiltInWorkgroupId: |
| 17754 | return "threadgroup_position_in_grid"; |
| 17755 | |
| 17756 | case BuiltInNumWorkgroups: |
| 17757 | return "threadgroups_per_grid"; |
| 17758 | |
| 17759 | case BuiltInLocalInvocationId: |
| 17760 | return "thread_position_in_threadgroup"; |
| 17761 | |
| 17762 | case BuiltInLocalInvocationIndex: |
| 17763 | return "thread_index_in_threadgroup"; |
| 17764 | |
| 17765 | case BuiltInSubgroupSize: |
| 17766 | if (msl_options.emulate_subgroups || msl_options.fixed_subgroup_size != 0) |
| 17767 | // Shouldn't be reached. |
| 17768 | SPIRV_CROSS_THROW("Emitting threads_per_simdgroup attribute with fixed subgroup size??"); |
| 17769 | if (execution.model == ExecutionModelFragment) |
| 17770 | { |
| 17771 | if (!msl_options.supports_msl_version(2, 2)) |
| 17772 | SPIRV_CROSS_THROW("threads_per_simdgroup requires Metal 2.2 in fragment shaders."); |
| 17773 | return "threads_per_simdgroup"; |
| 17774 | } |
| 17775 | else |
| 17776 | { |
| 17777 | // thread_execution_width is an alias for threads_per_simdgroup, and it's only available since 1.0, |
| 17778 | // but not in fragment. |
| 17779 | return "thread_execution_width"; |
| 17780 | } |
| 17781 | |
| 17782 | case BuiltInNumSubgroups: |
| 17783 | if (msl_options.emulate_subgroups) |
| 17784 | // Shouldn't be reached. |
| 17785 | SPIRV_CROSS_THROW("NumSubgroups is handled specially with emulation."); |
| 17786 | if (!msl_options.supports_msl_version(2)) |
| 17787 | SPIRV_CROSS_THROW("Subgroup builtins require Metal 2.0."); |
| 17788 | return msl_options.use_quadgroup_operation() ? "quadgroups_per_threadgroup" : "simdgroups_per_threadgroup"; |
| 17789 | |
| 17790 | case BuiltInSubgroupId: |
| 17791 | if (msl_options.emulate_subgroups) |
| 17792 | // Shouldn't be reached. |
| 17793 | SPIRV_CROSS_THROW("SubgroupId is handled specially with emulation."); |
| 17794 | if (!msl_options.supports_msl_version(2)) |
| 17795 | SPIRV_CROSS_THROW("Subgroup builtins require Metal 2.0."); |
| 17796 | return msl_options.use_quadgroup_operation() ? "quadgroup_index_in_threadgroup" : "simdgroup_index_in_threadgroup"; |
| 17797 | |
| 17798 | case BuiltInSubgroupLocalInvocationId: |
| 17799 | if (msl_options.emulate_subgroups) |
| 17800 | // Shouldn't be reached. |
| 17801 | SPIRV_CROSS_THROW("SubgroupLocalInvocationId is handled specially with emulation."); |
| 17802 | if (execution.model == ExecutionModelFragment) |
| 17803 | { |
| 17804 | if (!msl_options.supports_msl_version(2, 2)) |
| 17805 | SPIRV_CROSS_THROW("thread_index_in_simdgroup requires Metal 2.2 in fragment shaders."); |
| 17806 | return "thread_index_in_simdgroup"; |
| 17807 | } |
| 17808 | else if (execution.model == ExecutionModelKernel || execution.model == ExecutionModelGLCompute || |
| 17809 | execution.model == ExecutionModelTessellationControl || |
| 17810 | (execution.model == ExecutionModelVertex && msl_options.vertex_for_tessellation)) |
| 17811 | { |
| 17812 | // We are generating a Metal kernel function. |
| 17813 | if (!msl_options.supports_msl_version(2)) |
| 17814 | SPIRV_CROSS_THROW("Subgroup builtins in kernel functions require Metal 2.0."); |
| 17815 | return msl_options.use_quadgroup_operation() ? "thread_index_in_quadgroup" : "thread_index_in_simdgroup"; |
| 17816 | } |
| 17817 | else |
| 17818 | SPIRV_CROSS_THROW("Subgroup builtins are not available in this type of function."); |
| 17819 | |
| 17820 | case BuiltInSubgroupEqMask: |
| 17821 | case BuiltInSubgroupGeMask: |
| 17822 | case BuiltInSubgroupGtMask: |
| 17823 | case BuiltInSubgroupLeMask: |
| 17824 | case BuiltInSubgroupLtMask: |
| 17825 | // Shouldn't be reached. |
| 17826 | SPIRV_CROSS_THROW("Subgroup ballot masks are handled specially in MSL."); |
| 17827 | |
| 17828 | case BuiltInBaryCoordKHR: |
| 17829 | case BuiltInBaryCoordNoPerspKHR: |
| 17830 | if (msl_options.is_ios() && !msl_options.supports_msl_version(2, 3)) |
| 17831 | SPIRV_CROSS_THROW("Barycentrics are only supported in MSL 2.3 and above on iOS."); |
| 17832 | else if (!msl_options.supports_msl_version(2, 2)) |
| 17833 | SPIRV_CROSS_THROW("Barycentrics are only supported in MSL 2.2 and above on macOS."); |
| 17834 | return "barycentric_coord"; |
| 17835 | |
| 17836 | case BuiltInCullPrimitiveEXT: |
| 17837 | return "primitive_culled"; |
| 17838 | |
| 17839 | default: |
| 17840 | return "unsupported-built-in"; |
| 17841 | } |
| 17842 | } |
| 17843 | |
| 17844 | // Returns an MSL string type declaration for a SPIR-V builtin |
| 17845 | string CompilerMSL::builtin_type_decl(BuiltIn builtin, uint32_t id) |
| 17846 | { |
| 17847 | switch (builtin) |
| 17848 | { |
| 17849 | // Vertex function in |
| 17850 | case BuiltInVertexId: |
| 17851 | return "uint"; |
| 17852 | case BuiltInVertexIndex: |
| 17853 | return "uint"; |
| 17854 | case BuiltInBaseVertex: |
| 17855 | return "uint"; |
| 17856 | case BuiltInInstanceId: |
| 17857 | return "uint"; |
| 17858 | case BuiltInInstanceIndex: |
| 17859 | return "uint"; |
| 17860 | case BuiltInBaseInstance: |
| 17861 | return "uint"; |
| 17862 | case BuiltInDrawIndex: |
| 17863 | SPIRV_CROSS_THROW("DrawIndex is not supported in MSL."); |
| 17864 | |
| 17865 | // Vertex function out |
| 17866 | case BuiltInClipDistance: |
| 17867 | case BuiltInCullDistance: |
| 17868 | return "float"; |
| 17869 | case BuiltInPointSize: |
| 17870 | return "float"; |
| 17871 | case BuiltInPosition: |
| 17872 | return "float4"; |
| 17873 | case BuiltInLayer: |
| 17874 | return "uint"; |
| 17875 | case BuiltInViewportIndex: |
| 17876 | if (!msl_options.supports_msl_version(2, 0)) |
| 17877 | SPIRV_CROSS_THROW("ViewportIndex requires Metal 2.0."); |
| 17878 | return "uint"; |
| 17879 | |
| 17880 | // Tess. control function in |
| 17881 | case BuiltInInvocationId: |
| 17882 | return "uint"; |
| 17883 | case BuiltInPatchVertices: |
| 17884 | return "uint"; |
| 17885 | case BuiltInPrimitiveId: |
| 17886 | return "uint"; |
| 17887 | |
| 17888 | // Tess. control function out |
| 17889 | case BuiltInTessLevelInner: |
| 17890 | if (is_tese_shader()) |
| 17891 | return (msl_options.raw_buffer_tese_input || is_tessellating_triangles()) ? "float" : "float2"; |
| 17892 | return "half"; |
| 17893 | case BuiltInTessLevelOuter: |
| 17894 | if (is_tese_shader()) |
| 17895 | return (msl_options.raw_buffer_tese_input || is_tessellating_triangles()) ? "float" : "float4"; |
| 17896 | return "half"; |
| 17897 | |
| 17898 | // Tess. evaluation function in |
| 17899 | case BuiltInTessCoord: |
| 17900 | return "float3"; |
| 17901 | |
| 17902 | // Fragment function in |
| 17903 | case BuiltInFrontFacing: |
| 17904 | return "bool"; |
| 17905 | case BuiltInPointCoord: |
| 17906 | return "float2"; |
| 17907 | case BuiltInFragCoord: |
| 17908 | return "float4"; |
| 17909 | case BuiltInSampleId: |
| 17910 | return "uint"; |
| 17911 | case BuiltInSampleMask: |
| 17912 | return "uint"; |
| 17913 | case BuiltInSamplePosition: |
| 17914 | return "float2"; |
| 17915 | case BuiltInViewIndex: |
| 17916 | return "uint"; |
| 17917 | |
| 17918 | case BuiltInHelperInvocation: |
| 17919 | return "bool"; |
| 17920 | |
| 17921 | case BuiltInBaryCoordKHR: |
| 17922 | case BuiltInBaryCoordNoPerspKHR: |
| 17923 | // Use the type as declared, can be 1, 2 or 3 components. |
| 17924 | return type_to_glsl(get_variable_data_type(get<SPIRVariable>(id))); |
| 17925 | |
| 17926 | // Fragment function out |
| 17927 | case BuiltInFragDepth: |
| 17928 | return "float"; |
| 17929 | |
| 17930 | case BuiltInFragStencilRefEXT: |
| 17931 | return "uint"; |
| 17932 | |
| 17933 | // Compute function in |
| 17934 | case BuiltInGlobalInvocationId: |
| 17935 | case BuiltInLocalInvocationId: |
| 17936 | case BuiltInNumWorkgroups: |
| 17937 | case BuiltInWorkgroupId: |
| 17938 | case BuiltInWorkgroupSize: |
| 17939 | return "uint3"; |
| 17940 | case BuiltInLocalInvocationIndex: |
| 17941 | case BuiltInNumSubgroups: |
| 17942 | case BuiltInSubgroupId: |
| 17943 | case BuiltInSubgroupSize: |
| 17944 | case BuiltInSubgroupLocalInvocationId: |
| 17945 | return "uint"; |
| 17946 | case BuiltInSubgroupEqMask: |
| 17947 | case BuiltInSubgroupGeMask: |
| 17948 | case BuiltInSubgroupGtMask: |
| 17949 | case BuiltInSubgroupLeMask: |
| 17950 | case BuiltInSubgroupLtMask: |
| 17951 | return "uint4"; |
| 17952 | |
| 17953 | case BuiltInDeviceIndex: |
| 17954 | return "int"; |
| 17955 | |
| 17956 | case BuiltInPrimitivePointIndicesEXT: |
| 17957 | return "uint"; |
| 17958 | case BuiltInPrimitiveLineIndicesEXT: |
| 17959 | return "uint2"; |
| 17960 | case BuiltInPrimitiveTriangleIndicesEXT: |
| 17961 | return "uint3"; |
| 17962 | |
| 17963 | default: |
| 17964 | return "unsupported-built-in-type"; |
| 17965 | } |
| 17966 | } |
| 17967 | |
| 17968 | // Returns the declaration of a built-in argument to a function |
| 17969 | string CompilerMSL::built_in_func_arg(BuiltIn builtin, bool prefix_comma) |
| 17970 | { |
| 17971 | string bi_arg; |
| 17972 | if (prefix_comma) |
| 17973 | bi_arg += ", "; |
| 17974 | |
| 17975 | // Handle HLSL-style 0-based vertex/instance index. |
| 17976 | builtin_declaration = true; |
| 17977 | bi_arg += builtin_type_decl(builtin); |
| 17978 | bi_arg += string(" ") + builtin_to_glsl(builtin, StorageClassInput); |
| 17979 | bi_arg += string(" [[") + builtin_qualifier(builtin) + string("]]"); |
| 17980 | builtin_declaration = false; |
| 17981 | |
| 17982 | return bi_arg; |
| 17983 | } |
| 17984 | |
| 17985 | const SPIRType &CompilerMSL::get_physical_member_type(const SPIRType &type, uint32_t index) const |
| 17986 | { |
| 17987 | if (member_is_remapped_physical_type(type, index)) |
| 17988 | return get<SPIRType>(get_extended_member_decoration(type.self, index, SPIRVCrossDecorationPhysicalTypeID)); |
| 17989 | else |
| 17990 | return get<SPIRType>(type.member_types[index]); |
| 17991 | } |
| 17992 | |
| 17993 | SPIRType CompilerMSL::get_presumed_input_type(const SPIRType &ib_type, uint32_t index) const |
| 17994 | { |
| 17995 | SPIRType type = get_physical_member_type(ib_type, index); |
| 17996 | uint32_t loc = get_member_decoration(ib_type.self, index, DecorationLocation); |
| 17997 | uint32_t cmp = get_member_decoration(ib_type.self, index, DecorationComponent); |
| 17998 | auto p_va = inputs_by_location.find({loc, cmp}); |
| 17999 | if (p_va != end(inputs_by_location) && p_va->second.vecsize > type.vecsize) |
| 18000 | type.vecsize = p_va->second.vecsize; |
| 18001 | |
| 18002 | return type; |
| 18003 | } |
| 18004 | |
| 18005 | uint32_t CompilerMSL::get_declared_type_array_stride_msl(const SPIRType &type, bool is_packed, bool row_major) const |
| 18006 | { |
| 18007 | // Array stride in MSL is always size * array_size. sizeof(float3) == 16, |
| 18008 | // unlike GLSL and HLSL where array stride would be 16 and size 12. |
| 18009 | |
| 18010 | // We could use parent type here and recurse, but that makes creating physical type remappings |
| 18011 | // far more complicated. We'd rather just create the final type, and ignore having to create the entire type |
| 18012 | // hierarchy in order to compute this value, so make a temporary type on the stack. |
| 18013 | |
| 18014 | auto basic_type = type; |
| 18015 | basic_type.array.clear(); |
| 18016 | basic_type.array_size_literal.clear(); |
| 18017 | uint32_t value_size = get_declared_type_size_msl(basic_type, is_packed, row_major); |
| 18018 | |
| 18019 | uint32_t dimensions = uint32_t(type.array.size()); |
| 18020 | assert(dimensions > 0); |
| 18021 | dimensions--; |
| 18022 | |
| 18023 | // Multiply together every dimension, except the last one. |
| 18024 | for (uint32_t dim = 0; dim < dimensions; dim++) |
| 18025 | { |
| 18026 | uint32_t array_size = to_array_size_literal(type, dim); |
| 18027 | value_size *= max<uint32_t>(array_size, 1u); |
| 18028 | } |
| 18029 | |
| 18030 | return value_size; |
| 18031 | } |
| 18032 | |
| 18033 | uint32_t CompilerMSL::get_declared_struct_member_array_stride_msl(const SPIRType &type, uint32_t index) const |
| 18034 | { |
| 18035 | return get_declared_type_array_stride_msl(get_physical_member_type(type, index), |
| 18036 | member_is_packed_physical_type(type, index), |
| 18037 | has_member_decoration(type.self, index, DecorationRowMajor)); |
| 18038 | } |
| 18039 | |
| 18040 | uint32_t CompilerMSL::get_declared_input_array_stride_msl(const SPIRType &type, uint32_t index) const |
| 18041 | { |
| 18042 | return get_declared_type_array_stride_msl(get_presumed_input_type(type, index), false, |
| 18043 | has_member_decoration(type.self, index, DecorationRowMajor)); |
| 18044 | } |
| 18045 | |
| 18046 | uint32_t CompilerMSL::get_declared_type_matrix_stride_msl(const SPIRType &type, bool packed, bool row_major) const |
| 18047 | { |
| 18048 | // For packed matrices, we just use the size of the vector type. |
| 18049 | // Otherwise, MatrixStride == alignment, which is the size of the underlying vector type. |
| 18050 | if (packed) |
| 18051 | return (type.width / 8) * ((row_major && type.columns > 1) ? type.columns : type.vecsize); |
| 18052 | else |
| 18053 | return get_declared_type_alignment_msl(type, false, row_major); |
| 18054 | } |
| 18055 | |
| 18056 | uint32_t CompilerMSL::get_declared_struct_member_matrix_stride_msl(const SPIRType &type, uint32_t index) const |
| 18057 | { |
| 18058 | return get_declared_type_matrix_stride_msl(get_physical_member_type(type, index), |
| 18059 | member_is_packed_physical_type(type, index), |
| 18060 | has_member_decoration(type.self, index, DecorationRowMajor)); |
| 18061 | } |
| 18062 | |
| 18063 | uint32_t CompilerMSL::get_declared_input_matrix_stride_msl(const SPIRType &type, uint32_t index) const |
| 18064 | { |
| 18065 | return get_declared_type_matrix_stride_msl(get_presumed_input_type(type, index), false, |
| 18066 | has_member_decoration(type.self, index, DecorationRowMajor)); |
| 18067 | } |
| 18068 | |
| 18069 | uint32_t CompilerMSL::get_declared_struct_size_msl(const SPIRType &struct_type, bool ignore_alignment, |
| 18070 | bool ignore_padding) const |
| 18071 | { |
| 18072 | // If we have a target size, that is the declared size as well. |
| 18073 | if (!ignore_padding && has_extended_decoration(struct_type.self, SPIRVCrossDecorationPaddingTarget)) |
| 18074 | return get_extended_decoration(struct_type.self, SPIRVCrossDecorationPaddingTarget); |
| 18075 | |
| 18076 | if (struct_type.member_types.empty()) |
| 18077 | return 0; |
| 18078 | |
| 18079 | uint32_t mbr_cnt = uint32_t(struct_type.member_types.size()); |
| 18080 | |
| 18081 | // In MSL, a struct's alignment is equal to the maximum alignment of any of its members. |
| 18082 | uint32_t alignment = 1; |
| 18083 | |
| 18084 | if (!ignore_alignment) |
| 18085 | { |
| 18086 | for (uint32_t i = 0; i < mbr_cnt; i++) |
| 18087 | { |
| 18088 | uint32_t mbr_alignment = get_declared_struct_member_alignment_msl(struct_type, i); |
| 18089 | alignment = max(alignment, mbr_alignment); |
| 18090 | } |
| 18091 | } |
| 18092 | |
| 18093 | // Last member will always be matched to the final Offset decoration, but size of struct in MSL now depends |
| 18094 | // on physical size in MSL, and the size of the struct itself is then aligned to struct alignment. |
| 18095 | uint32_t spirv_offset = type_struct_member_offset(struct_type, mbr_cnt - 1); |
| 18096 | uint32_t msl_size = spirv_offset + get_declared_struct_member_size_msl(struct_type, mbr_cnt - 1); |
| 18097 | msl_size = (msl_size + alignment - 1) & ~(alignment - 1); |
| 18098 | return msl_size; |
| 18099 | } |
| 18100 | |
| 18101 | uint32_t CompilerMSL::get_physical_type_stride(const SPIRType &type) const |
| 18102 | { |
| 18103 | // This should only be relevant for plain types such as scalars and vectors? |
| 18104 | // If we're pointing to a struct, it will recursively pick up packed/row-major state. |
| 18105 | return get_declared_type_size_msl(type, false, false); |
| 18106 | } |
| 18107 | |
| 18108 | // Returns the byte size of a struct member. |
| 18109 | uint32_t CompilerMSL::get_declared_type_size_msl(const SPIRType &type, bool is_packed, bool row_major) const |
| 18110 | { |
| 18111 | // Pointers take 8 bytes each |
| 18112 | // Match both pointer and array-of-pointer here. |
| 18113 | if (type.pointer && type.storage == StorageClassPhysicalStorageBuffer) |
| 18114 | { |
| 18115 | uint32_t type_size = 8; |
| 18116 | |
| 18117 | // Work our way through potentially layered arrays, |
| 18118 | // stopping when we hit a pointer that is not also an array. |
| 18119 | int32_t dim_idx = (int32_t)type.array.size() - 1; |
| 18120 | auto *p_type = &type; |
| 18121 | while (!is_pointer(*p_type) && dim_idx >= 0) |
| 18122 | { |
| 18123 | type_size *= to_array_size_literal(*p_type, dim_idx); |
| 18124 | p_type = &get<SPIRType>(p_type->parent_type); |
| 18125 | dim_idx--; |
| 18126 | } |
| 18127 | |
| 18128 | return type_size; |
| 18129 | } |
| 18130 | |
| 18131 | switch (type.basetype) |
| 18132 | { |
| 18133 | case SPIRType::Unknown: |
| 18134 | case SPIRType::Void: |
| 18135 | case SPIRType::AtomicCounter: |
| 18136 | case SPIRType::Image: |
| 18137 | case SPIRType::SampledImage: |
| 18138 | case SPIRType::Sampler: |
| 18139 | SPIRV_CROSS_THROW("Querying size of opaque object."); |
| 18140 | |
| 18141 | default: |
| 18142 | { |
| 18143 | if (!type.array.empty()) |
| 18144 | { |
| 18145 | uint32_t array_size = to_array_size_literal(type); |
| 18146 | return get_declared_type_array_stride_msl(type, is_packed, row_major) * max<uint32_t>(array_size, 1u); |
| 18147 | } |
| 18148 | |
| 18149 | if (type.basetype == SPIRType::Struct) |
| 18150 | return get_declared_struct_size_msl(type); |
| 18151 | |
| 18152 | if (is_packed) |
| 18153 | { |
| 18154 | return type.vecsize * type.columns * (type.width / 8); |
| 18155 | } |
| 18156 | else |
| 18157 | { |
| 18158 | // An unpacked 3-element vector or matrix column is the same memory size as a 4-element. |
| 18159 | uint32_t vecsize = type.vecsize; |
| 18160 | uint32_t columns = type.columns; |
| 18161 | |
| 18162 | if (row_major && columns > 1) |
| 18163 | swap(vecsize, columns); |
| 18164 | |
| 18165 | if (vecsize == 3) |
| 18166 | vecsize = 4; |
| 18167 | |
| 18168 | return vecsize * columns * (type.width / 8); |
| 18169 | } |
| 18170 | } |
| 18171 | } |
| 18172 | } |
| 18173 | |
| 18174 | uint32_t CompilerMSL::get_declared_struct_member_size_msl(const SPIRType &type, uint32_t index) const |
| 18175 | { |
| 18176 | return get_declared_type_size_msl(get_physical_member_type(type, index), |
| 18177 | member_is_packed_physical_type(type, index), |
| 18178 | has_member_decoration(type.self, index, DecorationRowMajor)); |
| 18179 | } |
| 18180 | |
| 18181 | uint32_t CompilerMSL::get_declared_input_size_msl(const SPIRType &type, uint32_t index) const |
| 18182 | { |
| 18183 | return get_declared_type_size_msl(get_presumed_input_type(type, index), false, |
| 18184 | has_member_decoration(type.self, index, DecorationRowMajor)); |
| 18185 | } |
| 18186 | |
| 18187 | // Returns the byte alignment of a type. |
| 18188 | uint32_t CompilerMSL::get_declared_type_alignment_msl(const SPIRType &type, bool is_packed, bool row_major) const |
| 18189 | { |
| 18190 | // Pointers align on multiples of 8 bytes. |
| 18191 | // Deliberately ignore array-ness here. It's not relevant for alignment. |
| 18192 | if (type.pointer && type.storage == StorageClassPhysicalStorageBuffer) |
| 18193 | return 8; |
| 18194 | |
| 18195 | switch (type.basetype) |
| 18196 | { |
| 18197 | case SPIRType::Unknown: |
| 18198 | case SPIRType::Void: |
| 18199 | case SPIRType::AtomicCounter: |
| 18200 | case SPIRType::Image: |
| 18201 | case SPIRType::SampledImage: |
| 18202 | case SPIRType::Sampler: |
| 18203 | SPIRV_CROSS_THROW("Querying alignment of opaque object."); |
| 18204 | |
| 18205 | case SPIRType::Double: |
| 18206 | SPIRV_CROSS_THROW("double types are not supported in buffers in MSL."); |
| 18207 | |
| 18208 | case SPIRType::Struct: |
| 18209 | { |
| 18210 | // In MSL, a struct's alignment is equal to the maximum alignment of any of its members. |
| 18211 | uint32_t alignment = 1; |
| 18212 | for (uint32_t i = 0; i < type.member_types.size(); i++) |
| 18213 | alignment = max(alignment, uint32_t(get_declared_struct_member_alignment_msl(type, i))); |
| 18214 | return alignment; |
| 18215 | } |
| 18216 | |
| 18217 | default: |
| 18218 | { |
| 18219 | if (type.basetype == SPIRType::Int64 && !msl_options.supports_msl_version(2, 3)) |
| 18220 | SPIRV_CROSS_THROW("long types in buffers are only supported in MSL 2.3 and above."); |
| 18221 | if (type.basetype == SPIRType::UInt64 && !msl_options.supports_msl_version(2, 3)) |
| 18222 | SPIRV_CROSS_THROW("ulong types in buffers are only supported in MSL 2.3 and above."); |
| 18223 | // Alignment of packed type is the same as the underlying component or column size. |
| 18224 | // Alignment of unpacked type is the same as the vector size. |
| 18225 | // Alignment of 3-elements vector is the same as 4-elements (including packed using column). |
| 18226 | if (is_packed) |
| 18227 | { |
| 18228 | // If we have packed_T and friends, the alignment is always scalar. |
| 18229 | return type.width / 8; |
| 18230 | } |
| 18231 | else |
| 18232 | { |
| 18233 | // This is the general rule for MSL. Size == alignment. |
| 18234 | uint32_t vecsize = (row_major && type.columns > 1) ? type.columns : type.vecsize; |
| 18235 | return (type.width / 8) * (vecsize == 3 ? 4 : vecsize); |
| 18236 | } |
| 18237 | } |
| 18238 | } |
| 18239 | } |
| 18240 | |
| 18241 | uint32_t CompilerMSL::get_declared_struct_member_alignment_msl(const SPIRType &type, uint32_t index) const |
| 18242 | { |
| 18243 | return get_declared_type_alignment_msl(get_physical_member_type(type, index), |
| 18244 | member_is_packed_physical_type(type, index), |
| 18245 | has_member_decoration(type.self, index, DecorationRowMajor)); |
| 18246 | } |
| 18247 | |
| 18248 | uint32_t CompilerMSL::get_declared_input_alignment_msl(const SPIRType &type, uint32_t index) const |
| 18249 | { |
| 18250 | return get_declared_type_alignment_msl(get_presumed_input_type(type, index), false, |
| 18251 | has_member_decoration(type.self, index, DecorationRowMajor)); |
| 18252 | } |
| 18253 | |
| 18254 | bool CompilerMSL::skip_argument(uint32_t) const |
| 18255 | { |
| 18256 | return false; |
| 18257 | } |
| 18258 | |
| 18259 | void CompilerMSL::analyze_sampled_image_usage() |
| 18260 | { |
| 18261 | if (msl_options.swizzle_texture_samples) |
| 18262 | { |
| 18263 | SampledImageScanner scanner(*this); |
| 18264 | traverse_all_reachable_opcodes(get<SPIRFunction>(ir.default_entry_point), scanner); |
| 18265 | } |
| 18266 | } |
| 18267 | |
| 18268 | void CompilerMSL::analyze_workgroup_variables() |
| 18269 | { |
| 18270 | ir.for_each_typed_id<SPIRVariable>([&](uint32_t, SPIRVariable &var) { |
| 18271 | // If workgroup variables have initializer, it can only be ConstantNull (zero init) |
| 18272 | if (var.storage == StorageClassWorkgroup && var.initializer) |
| 18273 | { |
| 18274 | needs_workgroup_zero_init = true; |
| 18275 | |
| 18276 | // MSL compiler does not like the routine to initialize simple threadgroup variables, |
| 18277 | // falsely claiming it is "sometimes uninitialized". Suppress it. |
| 18278 | auto &type = get_variable_data_type(var); |
| 18279 | if (type.array.empty() && type.member_types.empty()) |
| 18280 | suppress_sometimes_unitialized = true; |
| 18281 | } |
| 18282 | }); |
| 18283 | } |
| 18284 | |
| 18285 | bool CompilerMSL::SampledImageScanner::handle(spv::Op opcode, const uint32_t *args, uint32_t length) |
| 18286 | { |
| 18287 | switch (opcode) |
| 18288 | { |
| 18289 | case OpLoad: |
| 18290 | case OpImage: |
| 18291 | case OpSampledImage: |
| 18292 | { |
| 18293 | if (length < 3) |
| 18294 | return false; |
| 18295 | |
| 18296 | uint32_t result_type = args[0]; |
| 18297 | auto &type = compiler.get<SPIRType>(result_type); |
| 18298 | if ((type.basetype != SPIRType::Image && type.basetype != SPIRType::SampledImage) || type.image.sampled != 1) |
| 18299 | return true; |
| 18300 | |
| 18301 | uint32_t id = args[1]; |
| 18302 | compiler.set<SPIRExpression>(id, "", result_type, true); |
| 18303 | break; |
| 18304 | } |
| 18305 | case OpImageSampleExplicitLod: |
| 18306 | case OpImageSampleProjExplicitLod: |
| 18307 | case OpImageSampleDrefExplicitLod: |
| 18308 | case OpImageSampleProjDrefExplicitLod: |
| 18309 | case OpImageSampleImplicitLod: |
| 18310 | case OpImageSampleProjImplicitLod: |
| 18311 | case OpImageSampleDrefImplicitLod: |
| 18312 | case OpImageSampleProjDrefImplicitLod: |
| 18313 | case OpImageFetch: |
| 18314 | case OpImageGather: |
| 18315 | case OpImageDrefGather: |
| 18316 | compiler.has_sampled_images = |
| 18317 | compiler.has_sampled_images || compiler.is_sampled_image_type(compiler.expression_type(args[2])); |
| 18318 | compiler.needs_swizzle_buffer_def = compiler.needs_swizzle_buffer_def || compiler.has_sampled_images; |
| 18319 | break; |
| 18320 | default: |
| 18321 | break; |
| 18322 | } |
| 18323 | return true; |
| 18324 | } |
| 18325 | |
| 18326 | // If a needed custom function wasn't added before, add it and force a recompile. |
| 18327 | void CompilerMSL::add_spv_func_and_recompile(SPVFuncImpl spv_func) |
| 18328 | { |
| 18329 | if (spv_function_implementations.count(spv_func) == 0) |
| 18330 | { |
| 18331 | spv_function_implementations.insert(spv_func); |
| 18332 | suppress_missing_prototypes = true; |
| 18333 | force_recompile(); |
| 18334 | } |
| 18335 | } |
| 18336 | |
| 18337 | bool CompilerMSL::OpCodePreprocessor::handle(Op opcode, const uint32_t *args, uint32_t length) |
| 18338 | { |
| 18339 | // Since MSL exists in a single execution scope, function prototype declarations are not |
| 18340 | // needed, and clutter the output. If secondary functions are output (either as a SPIR-V |
| 18341 | // function implementation or as indicated by the presence of OpFunctionCall), then set |
| 18342 | // suppress_missing_prototypes to suppress compiler warnings of missing function prototypes. |
| 18343 | |
| 18344 | // Mark if the input requires the implementation of an SPIR-V function that does not exist in Metal. |
| 18345 | SPVFuncImpl spv_func = get_spv_func_impl(opcode, args, length); |
| 18346 | if (spv_func != SPVFuncImplNone) |
| 18347 | { |
| 18348 | compiler.spv_function_implementations.insert(spv_func); |
| 18349 | suppress_missing_prototypes = true; |
| 18350 | } |
| 18351 | |
| 18352 | switch (opcode) |
| 18353 | { |
| 18354 | |
| 18355 | case OpFunctionCall: |
| 18356 | suppress_missing_prototypes = true; |
| 18357 | break; |
| 18358 | |
| 18359 | case OpDemoteToHelperInvocationEXT: |
| 18360 | uses_discard = true; |
| 18361 | break; |
| 18362 | |
| 18363 | // Emulate texture2D atomic operations |
| 18364 | case OpImageTexelPointer: |
| 18365 | { |
| 18366 | if (!compiler.msl_options.supports_msl_version(3, 1)) |
| 18367 | { |
| 18368 | auto *var = compiler.maybe_get_backing_variable(args[2]); |
| 18369 | image_pointers_emulated[args[1]] = var ? var->self : ID(0); |
| 18370 | } |
| 18371 | break; |
| 18372 | } |
| 18373 | |
| 18374 | case OpImageWrite: |
| 18375 | uses_image_write = true; |
| 18376 | break; |
| 18377 | |
| 18378 | case OpStore: |
| 18379 | check_resource_write(args[0]); |
| 18380 | break; |
| 18381 | |
| 18382 | // Emulate texture2D atomic operations |
| 18383 | case OpAtomicExchange: |
| 18384 | case OpAtomicCompareExchange: |
| 18385 | case OpAtomicCompareExchangeWeak: |
| 18386 | case OpAtomicIIncrement: |
| 18387 | case OpAtomicIDecrement: |
| 18388 | case OpAtomicIAdd: |
| 18389 | case OpAtomicFAddEXT: |
| 18390 | case OpAtomicISub: |
| 18391 | case OpAtomicSMin: |
| 18392 | case OpAtomicUMin: |
| 18393 | case OpAtomicSMax: |
| 18394 | case OpAtomicUMax: |
| 18395 | case OpAtomicAnd: |
| 18396 | case OpAtomicOr: |
| 18397 | case OpAtomicXor: |
| 18398 | { |
| 18399 | uses_atomics = true; |
| 18400 | auto it = image_pointers_emulated.find(args[2]); |
| 18401 | if (it != image_pointers_emulated.end()) |
| 18402 | { |
| 18403 | uses_image_write = true; |
| 18404 | compiler.atomic_image_vars_emulated.insert(it->second); |
| 18405 | } |
| 18406 | else |
| 18407 | check_resource_write(args[2]); |
| 18408 | break; |
| 18409 | } |
| 18410 | |
| 18411 | case OpAtomicStore: |
| 18412 | { |
| 18413 | uses_atomics = true; |
| 18414 | auto it = image_pointers_emulated.find(args[0]); |
| 18415 | if (it != image_pointers_emulated.end()) |
| 18416 | { |
| 18417 | compiler.atomic_image_vars_emulated.insert(it->second); |
| 18418 | uses_image_write = true; |
| 18419 | } |
| 18420 | else |
| 18421 | check_resource_write(args[0]); |
| 18422 | break; |
| 18423 | } |
| 18424 | |
| 18425 | case OpAtomicLoad: |
| 18426 | { |
| 18427 | uses_atomics = true; |
| 18428 | auto it = image_pointers_emulated.find(args[2]); |
| 18429 | if (it != image_pointers_emulated.end()) |
| 18430 | { |
| 18431 | compiler.atomic_image_vars_emulated.insert(it->second); |
| 18432 | } |
| 18433 | break; |
| 18434 | } |
| 18435 | |
| 18436 | case OpGroupNonUniformInverseBallot: |
| 18437 | needs_subgroup_invocation_id = true; |
| 18438 | break; |
| 18439 | |
| 18440 | case OpGroupNonUniformBallotFindLSB: |
| 18441 | case OpGroupNonUniformBallotFindMSB: |
| 18442 | needs_subgroup_size = true; |
| 18443 | break; |
| 18444 | |
| 18445 | case OpGroupNonUniformBallotBitCount: |
| 18446 | if (args[3] == GroupOperationReduce) |
| 18447 | needs_subgroup_size = true; |
| 18448 | else |
| 18449 | needs_subgroup_invocation_id = true; |
| 18450 | break; |
| 18451 | |
| 18452 | case OpGroupNonUniformRotateKHR: |
| 18453 | // Add the correct invocation ID for calculating clustered rotate case. |
| 18454 | if (length > 5) |
| 18455 | { |
| 18456 | if (static_cast<Scope>(compiler.evaluate_constant_u32(args[2])) == ScopeSubgroup) |
| 18457 | needs_subgroup_invocation_id = true; |
| 18458 | else |
| 18459 | needs_local_invocation_index = true; |
| 18460 | } |
| 18461 | break; |
| 18462 | |
| 18463 | case OpGroupNonUniformFAdd: |
| 18464 | case OpGroupNonUniformFMul: |
| 18465 | case OpGroupNonUniformFMin: |
| 18466 | case OpGroupNonUniformFMax: |
| 18467 | case OpGroupNonUniformIAdd: |
| 18468 | case OpGroupNonUniformIMul: |
| 18469 | case OpGroupNonUniformSMin: |
| 18470 | case OpGroupNonUniformSMax: |
| 18471 | case OpGroupNonUniformUMin: |
| 18472 | case OpGroupNonUniformUMax: |
| 18473 | case OpGroupNonUniformBitwiseAnd: |
| 18474 | case OpGroupNonUniformBitwiseOr: |
| 18475 | case OpGroupNonUniformBitwiseXor: |
| 18476 | case OpGroupNonUniformLogicalAnd: |
| 18477 | case OpGroupNonUniformLogicalOr: |
| 18478 | case OpGroupNonUniformLogicalXor: |
| 18479 | if ((compiler.get_execution_model() != ExecutionModelFragment || |
| 18480 | compiler.msl_options.supports_msl_version(2, 2)) && |
| 18481 | args[3] == GroupOperationClusteredReduce) |
| 18482 | needs_subgroup_invocation_id = true; |
| 18483 | break; |
| 18484 | |
| 18485 | case OpArrayLength: |
| 18486 | { |
| 18487 | auto *var = compiler.maybe_get_backing_variable(args[2]); |
| 18488 | if (var != nullptr) |
| 18489 | { |
| 18490 | if (!compiler.is_var_runtime_size_array(*var)) |
| 18491 | compiler.buffers_requiring_array_length.insert(var->self); |
| 18492 | } |
| 18493 | break; |
| 18494 | } |
| 18495 | |
| 18496 | case OpInBoundsAccessChain: |
| 18497 | case OpAccessChain: |
| 18498 | case OpPtrAccessChain: |
| 18499 | { |
| 18500 | // OpArrayLength might want to know if taking ArrayLength of an array of SSBOs. |
| 18501 | uint32_t result_type = args[0]; |
| 18502 | uint32_t id = args[1]; |
| 18503 | uint32_t ptr = args[2]; |
| 18504 | |
| 18505 | compiler.set<SPIRExpression>(id, "", result_type, true); |
| 18506 | compiler.register_read(id, ptr, true); |
| 18507 | compiler.ir.ids[id].set_allow_type_rewrite(); |
| 18508 | break; |
| 18509 | } |
| 18510 | |
| 18511 | case OpExtInst: |
| 18512 | { |
| 18513 | uint32_t extension_set = args[2]; |
| 18514 | SPIRExtension::Extension ext = compiler.get<SPIRExtension>(extension_set).ext; |
| 18515 | if (ext == SPIRExtension::GLSL) |
| 18516 | { |
| 18517 | auto op_450 = static_cast<GLSLstd450>(args[3]); |
| 18518 | switch (op_450) |
| 18519 | { |
| 18520 | case GLSLstd450InterpolateAtCentroid: |
| 18521 | case GLSLstd450InterpolateAtSample: |
| 18522 | case GLSLstd450InterpolateAtOffset: |
| 18523 | { |
| 18524 | if (!compiler.msl_options.supports_msl_version(2, 3)) |
| 18525 | SPIRV_CROSS_THROW("Pull-model interpolation requires MSL 2.3."); |
| 18526 | // Fragment varyings used with pull-model interpolation need special handling, |
| 18527 | // due to the way pull-model interpolation works in Metal. |
| 18528 | auto *var = compiler.maybe_get_backing_variable(args[4]); |
| 18529 | if (var) |
| 18530 | { |
| 18531 | compiler.pull_model_inputs.insert(var->self); |
| 18532 | auto &var_type = compiler.get_variable_element_type(*var); |
| 18533 | // In addition, if this variable has a 'Sample' decoration, we need the sample ID |
| 18534 | // in order to do default interpolation. |
| 18535 | if (compiler.has_decoration(var->self, DecorationSample)) |
| 18536 | { |
| 18537 | needs_sample_id = true; |
| 18538 | } |
| 18539 | else if (var_type.basetype == SPIRType::Struct) |
| 18540 | { |
| 18541 | // Now we need to check each member and see if it has this decoration. |
| 18542 | for (uint32_t i = 0; i < var_type.member_types.size(); ++i) |
| 18543 | { |
| 18544 | if (compiler.has_member_decoration(var_type.self, i, DecorationSample)) |
| 18545 | { |
| 18546 | needs_sample_id = true; |
| 18547 | break; |
| 18548 | } |
| 18549 | } |
| 18550 | } |
| 18551 | } |
| 18552 | break; |
| 18553 | } |
| 18554 | default: |
| 18555 | break; |
| 18556 | } |
| 18557 | } |
| 18558 | else if (ext == SPIRExtension::NonSemanticDebugPrintf) |
| 18559 | { |
| 18560 | // Operation 1 is printf. |
| 18561 | if (args[3] == 1 && !compiler.msl_options.supports_msl_version(3, 2)) |
| 18562 | SPIRV_CROSS_THROW("Debug printf requires MSL 3.2."); |
| 18563 | } |
| 18564 | break; |
| 18565 | } |
| 18566 | |
| 18567 | case OpIsHelperInvocationEXT: |
| 18568 | if (compiler.needs_manual_helper_invocation_updates()) |
| 18569 | needs_helper_invocation = true; |
| 18570 | break; |
| 18571 | |
| 18572 | default: |
| 18573 | break; |
| 18574 | } |
| 18575 | |
| 18576 | // If it has one, keep track of the instruction's result type, mapped by ID |
| 18577 | uint32_t result_type, result_id; |
| 18578 | if (compiler.instruction_to_result_type(result_type, result_id, opcode, args, length)) |
| 18579 | result_types[result_id] = result_type; |
| 18580 | |
| 18581 | return true; |
| 18582 | } |
| 18583 | |
| 18584 | // If the variable is a Uniform or StorageBuffer, mark that a resource has been written to. |
| 18585 | void CompilerMSL::OpCodePreprocessor::check_resource_write(uint32_t var_id) |
| 18586 | { |
| 18587 | auto *p_var = compiler.maybe_get_backing_variable(var_id); |
| 18588 | StorageClass sc = p_var ? p_var->storage : StorageClassMax; |
| 18589 | if (sc == StorageClassUniform || sc == StorageClassStorageBuffer) |
| 18590 | uses_buffer_write = true; |
| 18591 | } |
| 18592 | |
| 18593 | // Returns an enumeration of a SPIR-V function that needs to be output for certain Op codes. |
| 18594 | CompilerMSL::SPVFuncImpl CompilerMSL::OpCodePreprocessor::get_spv_func_impl(Op opcode, const uint32_t *args, uint32_t length) |
| 18595 | { |
| 18596 | switch (opcode) |
| 18597 | { |
| 18598 | case OpSMod: |
| 18599 | return SPVFuncImplSMod; |
| 18600 | |
| 18601 | case OpFMod: |
| 18602 | return SPVFuncImplMod; |
| 18603 | |
| 18604 | case OpFAdd: |
| 18605 | case OpFSub: |
| 18606 | if (compiler.msl_options.invariant_float_math || |
| 18607 | compiler.has_decoration(args[1], DecorationNoContraction)) |
| 18608 | { |
| 18609 | return opcode == OpFAdd ? SPVFuncImplFAdd : SPVFuncImplFSub; |
| 18610 | } |
| 18611 | break; |
| 18612 | |
| 18613 | case OpFMul: |
| 18614 | case OpOuterProduct: |
| 18615 | case OpMatrixTimesVector: |
| 18616 | case OpVectorTimesMatrix: |
| 18617 | case OpMatrixTimesMatrix: |
| 18618 | if (compiler.msl_options.invariant_float_math || |
| 18619 | compiler.has_decoration(args[1], DecorationNoContraction)) |
| 18620 | { |
| 18621 | return SPVFuncImplFMul; |
| 18622 | } |
| 18623 | break; |
| 18624 | |
| 18625 | case OpQuantizeToF16: |
| 18626 | return SPVFuncImplQuantizeToF16; |
| 18627 | |
| 18628 | case OpTypeArray: |
| 18629 | { |
| 18630 | // Allow Metal to use the array<T> template to make arrays a value type |
| 18631 | return SPVFuncImplUnsafeArray; |
| 18632 | } |
| 18633 | |
| 18634 | // Emulate texture2D atomic operations |
| 18635 | case OpAtomicExchange: |
| 18636 | case OpAtomicCompareExchange: |
| 18637 | case OpAtomicCompareExchangeWeak: |
| 18638 | case OpAtomicIIncrement: |
| 18639 | case OpAtomicIDecrement: |
| 18640 | case OpAtomicIAdd: |
| 18641 | case OpAtomicFAddEXT: |
| 18642 | case OpAtomicISub: |
| 18643 | case OpAtomicSMin: |
| 18644 | case OpAtomicUMin: |
| 18645 | case OpAtomicSMax: |
| 18646 | case OpAtomicUMax: |
| 18647 | case OpAtomicAnd: |
| 18648 | case OpAtomicOr: |
| 18649 | case OpAtomicXor: |
| 18650 | case OpAtomicLoad: |
| 18651 | case OpAtomicStore: |
| 18652 | { |
| 18653 | auto it = image_pointers_emulated.find(args[opcode == OpAtomicStore ? 0 : 2]); |
| 18654 | if (it != image_pointers_emulated.end()) |
| 18655 | { |
| 18656 | uint32_t tid = compiler.get<SPIRVariable>(it->second).basetype; |
| 18657 | if (tid && compiler.get<SPIRType>(tid).image.dim == Dim2D) |
| 18658 | return SPVFuncImplImage2DAtomicCoords; |
| 18659 | } |
| 18660 | break; |
| 18661 | } |
| 18662 | |
| 18663 | case OpImageFetch: |
| 18664 | case OpImageRead: |
| 18665 | case OpImageWrite: |
| 18666 | { |
| 18667 | // Retrieve the image type, and if it's a Buffer, emit a texel coordinate function |
| 18668 | uint32_t tid = result_types[args[opcode == OpImageWrite ? 0 : 2]]; |
| 18669 | if (tid && compiler.get<SPIRType>(tid).image.dim == DimBuffer && !compiler.msl_options.texture_buffer_native) |
| 18670 | return SPVFuncImplTexelBufferCoords; |
| 18671 | break; |
| 18672 | } |
| 18673 | |
| 18674 | case OpExtInst: |
| 18675 | { |
| 18676 | uint32_t extension_set = args[2]; |
| 18677 | if (compiler.get<SPIRExtension>(extension_set).ext == SPIRExtension::GLSL) |
| 18678 | { |
| 18679 | auto op_450 = static_cast<GLSLstd450>(args[3]); |
| 18680 | switch (op_450) |
| 18681 | { |
| 18682 | case GLSLstd450Radians: |
| 18683 | return SPVFuncImplRadians; |
| 18684 | case GLSLstd450Degrees: |
| 18685 | return SPVFuncImplDegrees; |
| 18686 | case GLSLstd450FindILsb: |
| 18687 | return SPVFuncImplFindILsb; |
| 18688 | case GLSLstd450FindSMsb: |
| 18689 | return SPVFuncImplFindSMsb; |
| 18690 | case GLSLstd450FindUMsb: |
| 18691 | return SPVFuncImplFindUMsb; |
| 18692 | case GLSLstd450SSign: |
| 18693 | return SPVFuncImplSSign; |
| 18694 | case GLSLstd450Reflect: |
| 18695 | { |
| 18696 | auto &type = compiler.get<SPIRType>(args[0]); |
| 18697 | if (type.vecsize == 1) |
| 18698 | return SPVFuncImplReflectScalar; |
| 18699 | break; |
| 18700 | } |
| 18701 | case GLSLstd450Refract: |
| 18702 | { |
| 18703 | auto &type = compiler.get<SPIRType>(args[0]); |
| 18704 | if (type.vecsize == 1) |
| 18705 | return SPVFuncImplRefractScalar; |
| 18706 | break; |
| 18707 | } |
| 18708 | case GLSLstd450FaceForward: |
| 18709 | { |
| 18710 | auto &type = compiler.get<SPIRType>(args[0]); |
| 18711 | if (type.vecsize == 1) |
| 18712 | return SPVFuncImplFaceForwardScalar; |
| 18713 | break; |
| 18714 | } |
| 18715 | case GLSLstd450MatrixInverse: |
| 18716 | { |
| 18717 | auto &mat_type = compiler.get<SPIRType>(args[0]); |
| 18718 | switch (mat_type.columns) |
| 18719 | { |
| 18720 | case 2: |
| 18721 | return SPVFuncImplInverse2x2; |
| 18722 | case 3: |
| 18723 | return SPVFuncImplInverse3x3; |
| 18724 | case 4: |
| 18725 | return SPVFuncImplInverse4x4; |
| 18726 | default: |
| 18727 | break; |
| 18728 | } |
| 18729 | break; |
| 18730 | } |
| 18731 | default: |
| 18732 | break; |
| 18733 | } |
| 18734 | } |
| 18735 | break; |
| 18736 | } |
| 18737 | |
| 18738 | case OpGroupNonUniformBroadcast: |
| 18739 | case OpSubgroupReadInvocationKHR: |
| 18740 | return SPVFuncImplSubgroupBroadcast; |
| 18741 | |
| 18742 | case OpGroupNonUniformBroadcastFirst: |
| 18743 | case OpSubgroupFirstInvocationKHR: |
| 18744 | return SPVFuncImplSubgroupBroadcastFirst; |
| 18745 | |
| 18746 | case OpGroupNonUniformBallot: |
| 18747 | case OpSubgroupBallotKHR: |
| 18748 | return SPVFuncImplSubgroupBallot; |
| 18749 | |
| 18750 | case OpGroupNonUniformInverseBallot: |
| 18751 | case OpGroupNonUniformBallotBitExtract: |
| 18752 | return SPVFuncImplSubgroupBallotBitExtract; |
| 18753 | |
| 18754 | case OpGroupNonUniformBallotFindLSB: |
| 18755 | return SPVFuncImplSubgroupBallotFindLSB; |
| 18756 | |
| 18757 | case OpGroupNonUniformBallotFindMSB: |
| 18758 | return SPVFuncImplSubgroupBallotFindMSB; |
| 18759 | |
| 18760 | case OpGroupNonUniformBallotBitCount: |
| 18761 | return SPVFuncImplSubgroupBallotBitCount; |
| 18762 | |
| 18763 | case OpGroupNonUniformAllEqual: |
| 18764 | case OpSubgroupAllEqualKHR: |
| 18765 | return SPVFuncImplSubgroupAllEqual; |
| 18766 | |
| 18767 | case OpGroupNonUniformShuffle: |
| 18768 | return SPVFuncImplSubgroupShuffle; |
| 18769 | |
| 18770 | case OpGroupNonUniformShuffleXor: |
| 18771 | return SPVFuncImplSubgroupShuffleXor; |
| 18772 | |
| 18773 | case OpGroupNonUniformShuffleUp: |
| 18774 | return SPVFuncImplSubgroupShuffleUp; |
| 18775 | |
| 18776 | case OpGroupNonUniformShuffleDown: |
| 18777 | return SPVFuncImplSubgroupShuffleDown; |
| 18778 | |
| 18779 | case OpGroupNonUniformRotateKHR: |
| 18780 | // Clustered rotate is performed using shuffle. |
| 18781 | if (length > 5) |
| 18782 | return SPVFuncImplSubgroupShuffle; |
| 18783 | return SPVFuncImplSubgroupRotate; |
| 18784 | |
| 18785 | case OpGroupNonUniformQuadBroadcast: |
| 18786 | return SPVFuncImplQuadBroadcast; |
| 18787 | |
| 18788 | case OpGroupNonUniformQuadSwap: |
| 18789 | return SPVFuncImplQuadSwap; |
| 18790 | |
| 18791 | case OpSDot: |
| 18792 | case OpUDot: |
| 18793 | case OpSUDot: |
| 18794 | case OpSDotAccSat: |
| 18795 | case OpUDotAccSat: |
| 18796 | case OpSUDotAccSat: |
| 18797 | return SPVFuncImplReduceAdd; |
| 18798 | |
| 18799 | case OpSMulExtended: |
| 18800 | case OpUMulExtended: |
| 18801 | return SPVFuncImplMulExtended; |
| 18802 | |
| 18803 | case OpAssumeTrueKHR: |
| 18804 | case OpExpectKHR: |
| 18805 | return SPVFuncImplAssume; |
| 18806 | |
| 18807 | default: |
| 18808 | break; |
| 18809 | } |
| 18810 | return SPVFuncImplNone; |
| 18811 | } |
| 18812 | |
| 18813 | // Sort both type and meta member content based on builtin status (put builtins at end), |
| 18814 | // then by the required sorting aspect. |
| 18815 | void CompilerMSL::MemberSorter::sort() |
| 18816 | { |
| 18817 | // Create a temporary array of consecutive member indices and sort it based on how |
| 18818 | // the members should be reordered, based on builtin and sorting aspect meta info. |
| 18819 | size_t mbr_cnt = type.member_types.size(); |
| 18820 | SmallVector<uint32_t> mbr_idxs(mbr_cnt); |
| 18821 | std::iota(mbr_idxs.begin(), mbr_idxs.end(), 0); // Fill with consecutive indices |
| 18822 | std::stable_sort(mbr_idxs.begin(), mbr_idxs.end(), *this); // Sort member indices based on sorting aspect |
| 18823 | |
| 18824 | bool sort_is_identity = true; |
| 18825 | for (uint32_t mbr_idx = 0; mbr_idx < mbr_cnt; mbr_idx++) |
| 18826 | { |
| 18827 | if (mbr_idx != mbr_idxs[mbr_idx]) |
| 18828 | { |
| 18829 | sort_is_identity = false; |
| 18830 | break; |
| 18831 | } |
| 18832 | } |
| 18833 | |
| 18834 | if (sort_is_identity) |
| 18835 | return; |
| 18836 | |
| 18837 | if (meta.members.size() < type.member_types.size()) |
| 18838 | { |
| 18839 | // This should never trigger in normal circumstances, but to be safe. |
| 18840 | meta.members.resize(type.member_types.size()); |
| 18841 | } |
| 18842 | |
| 18843 | // Move type and meta member info to the order defined by the sorted member indices. |
| 18844 | // This is done by creating temporary copies of both member types and meta, and then |
| 18845 | // copying back to the original content at the sorted indices. |
| 18846 | auto mbr_types_cpy = type.member_types; |
| 18847 | auto mbr_meta_cpy = meta.members; |
| 18848 | for (uint32_t mbr_idx = 0; mbr_idx < mbr_cnt; mbr_idx++) |
| 18849 | { |
| 18850 | type.member_types[mbr_idx] = mbr_types_cpy[mbr_idxs[mbr_idx]]; |
| 18851 | meta.members[mbr_idx] = mbr_meta_cpy[mbr_idxs[mbr_idx]]; |
| 18852 | } |
| 18853 | |
| 18854 | // If we're sorting by Offset, this might affect user code which accesses a buffer block. |
| 18855 | // We will need to redirect member indices from defined index to sorted index using reverse lookup. |
| 18856 | if (sort_aspect == SortAspect::Offset) |
| 18857 | { |
| 18858 | type.member_type_index_redirection.resize(mbr_cnt); |
| 18859 | for (uint32_t map_idx = 0; map_idx < mbr_cnt; map_idx++) |
| 18860 | type.member_type_index_redirection[mbr_idxs[map_idx]] = map_idx; |
| 18861 | } |
| 18862 | } |
| 18863 | |
| 18864 | bool CompilerMSL::MemberSorter::operator()(uint32_t mbr_idx1, uint32_t mbr_idx2) |
| 18865 | { |
| 18866 | auto &mbr_meta1 = meta.members[mbr_idx1]; |
| 18867 | auto &mbr_meta2 = meta.members[mbr_idx2]; |
| 18868 | |
| 18869 | if (sort_aspect == LocationThenBuiltInType) |
| 18870 | { |
| 18871 | // Sort first by builtin status (put builtins at end), then by the sorting aspect. |
| 18872 | if (mbr_meta1.builtin != mbr_meta2.builtin) |
| 18873 | return mbr_meta2.builtin; |
| 18874 | else if (mbr_meta1.builtin) |
| 18875 | return mbr_meta1.builtin_type < mbr_meta2.builtin_type; |
| 18876 | else if (mbr_meta1.location == mbr_meta2.location) |
| 18877 | return mbr_meta1.component < mbr_meta2.component; |
| 18878 | else |
| 18879 | return mbr_meta1.location < mbr_meta2.location; |
| 18880 | } |
| 18881 | else |
| 18882 | return mbr_meta1.offset < mbr_meta2.offset; |
| 18883 | } |
| 18884 | |
| 18885 | CompilerMSL::MemberSorter::MemberSorter(SPIRType &t, Meta &m, SortAspect sa) |
| 18886 | : type(t) |
| 18887 | , meta(m) |
| 18888 | , sort_aspect(sa) |
| 18889 | { |
| 18890 | // Ensure enough meta info is available |
| 18891 | meta.members.resize(max(type.member_types.size(), meta.members.size())); |
| 18892 | } |
| 18893 | |
| 18894 | void CompilerMSL::remap_constexpr_sampler(VariableID id, const MSLConstexprSampler &sampler) |
| 18895 | { |
| 18896 | auto &type = get<SPIRType>(get<SPIRVariable>(id).basetype); |
| 18897 | if (type.basetype != SPIRType::SampledImage && type.basetype != SPIRType::Sampler) |
| 18898 | SPIRV_CROSS_THROW("Can only remap SampledImage and Sampler type."); |
| 18899 | if (!type.array.empty()) |
| 18900 | SPIRV_CROSS_THROW("Can not remap array of samplers."); |
| 18901 | constexpr_samplers_by_id[id] = sampler; |
| 18902 | } |
| 18903 | |
| 18904 | void CompilerMSL::remap_constexpr_sampler_by_binding(uint32_t desc_set, uint32_t binding, |
| 18905 | const MSLConstexprSampler &sampler) |
| 18906 | { |
| 18907 | constexpr_samplers_by_binding[{ desc_set, binding }] = sampler; |
| 18908 | } |
| 18909 | |
| 18910 | void CompilerMSL::cast_from_variable_load(uint32_t source_id, std::string &expr, const SPIRType &expr_type) |
| 18911 | { |
| 18912 | bool is_packed = has_extended_decoration(source_id, SPIRVCrossDecorationPhysicalTypePacked); |
| 18913 | auto *source_expr = maybe_get<SPIRExpression>(source_id); |
| 18914 | auto *var = maybe_get_backing_variable(source_id); |
| 18915 | const SPIRType *var_type = nullptr, *phys_type = nullptr; |
| 18916 | |
| 18917 | if (uint32_t phys_id = get_extended_decoration(source_id, SPIRVCrossDecorationPhysicalTypeID)) |
| 18918 | phys_type = &get<SPIRType>(phys_id); |
| 18919 | else |
| 18920 | phys_type = &expr_type; |
| 18921 | |
| 18922 | if (var) |
| 18923 | { |
| 18924 | source_id = var->self; |
| 18925 | var_type = &get_variable_data_type(*var); |
| 18926 | } |
| 18927 | |
| 18928 | bool rewrite_boolean_load = |
| 18929 | expr_type.basetype == SPIRType::Boolean && |
| 18930 | (var && (var->storage == StorageClassWorkgroup || var_type->basetype == SPIRType::Struct)); |
| 18931 | |
| 18932 | // Type fixups for workgroup variables if they are booleans. |
| 18933 | if (rewrite_boolean_load) |
| 18934 | { |
| 18935 | if (is_array(expr_type)) |
| 18936 | expr = to_rerolled_array_expression(expr_type, expr, expr_type); |
| 18937 | else |
| 18938 | expr = join(type_to_glsl(expr_type), "(", expr, ")"); |
| 18939 | } |
| 18940 | |
| 18941 | // Type fixups for workgroup variables if they are matrices. |
| 18942 | // Don't do fixup for packed types; those are handled specially. |
| 18943 | // FIXME: Maybe use a type like spvStorageMatrix for packed matrices? |
| 18944 | if (!msl_options.supports_msl_version(3, 0) && var && |
| 18945 | (var->storage == StorageClassWorkgroup || |
| 18946 | (var_type->basetype == SPIRType::Struct && |
| 18947 | has_extended_decoration(var_type->self, SPIRVCrossDecorationWorkgroupStruct) && !is_packed)) && |
| 18948 | expr_type.columns > 1) |
| 18949 | { |
| 18950 | SPIRType matrix_type = *phys_type; |
| 18951 | if (source_expr && source_expr->need_transpose) |
| 18952 | swap(matrix_type.vecsize, matrix_type.columns); |
| 18953 | matrix_type.array.clear(); |
| 18954 | matrix_type.array_size_literal.clear(); |
| 18955 | expr = join(type_to_glsl(matrix_type), "(", expr, ")"); |
| 18956 | } |
| 18957 | |
| 18958 | // Only interested in standalone builtin variables in the switch below. |
| 18959 | if (!has_decoration(source_id, DecorationBuiltIn)) |
| 18960 | { |
| 18961 | // If the backing variable does not match our expected sign, we can fix it up here. |
| 18962 | // See ensure_correct_input_type(). |
| 18963 | if (var && var->storage == StorageClassInput) |
| 18964 | { |
| 18965 | auto &base_type = get<SPIRType>(var->basetype); |
| 18966 | if (base_type.basetype != SPIRType::Struct && expr_type.basetype != base_type.basetype) |
| 18967 | expr = join(type_to_glsl(expr_type), "(", expr, ")"); |
| 18968 | } |
| 18969 | return; |
| 18970 | } |
| 18971 | |
| 18972 | auto builtin = static_cast<BuiltIn>(get_decoration(source_id, DecorationBuiltIn)); |
| 18973 | auto expected_type = expr_type.basetype; |
| 18974 | auto expected_width = expr_type.width; |
| 18975 | switch (builtin) |
| 18976 | { |
| 18977 | case BuiltInGlobalInvocationId: |
| 18978 | case BuiltInLocalInvocationId: |
| 18979 | case BuiltInWorkgroupId: |
| 18980 | case BuiltInLocalInvocationIndex: |
| 18981 | case BuiltInWorkgroupSize: |
| 18982 | case BuiltInNumWorkgroups: |
| 18983 | case BuiltInLayer: |
| 18984 | case BuiltInViewportIndex: |
| 18985 | case BuiltInFragStencilRefEXT: |
| 18986 | case BuiltInPrimitiveId: |
| 18987 | case BuiltInSubgroupSize: |
| 18988 | case BuiltInSubgroupLocalInvocationId: |
| 18989 | case BuiltInViewIndex: |
| 18990 | case BuiltInVertexIndex: |
| 18991 | case BuiltInInstanceIndex: |
| 18992 | case BuiltInBaseInstance: |
| 18993 | case BuiltInBaseVertex: |
| 18994 | case BuiltInSampleMask: |
| 18995 | expected_type = SPIRType::UInt; |
| 18996 | expected_width = 32; |
| 18997 | break; |
| 18998 | |
| 18999 | case BuiltInTessLevelInner: |
| 19000 | case BuiltInTessLevelOuter: |
| 19001 | if (is_tesc_shader()) |
| 19002 | { |
| 19003 | expected_type = SPIRType::Half; |
| 19004 | expected_width = 16; |
| 19005 | } |
| 19006 | break; |
| 19007 | |
| 19008 | default: |
| 19009 | break; |
| 19010 | } |
| 19011 | |
| 19012 | if (is_array(expr_type) && builtin == BuiltInSampleMask) |
| 19013 | { |
| 19014 | // Needs special handling. |
| 19015 | auto wrap_expr = join(type_to_glsl(expr_type), "({ "); |
| 19016 | wrap_expr += join(type_to_glsl(get<SPIRType>(expr_type.parent_type)), "(", expr, ")"); |
| 19017 | wrap_expr += " })"; |
| 19018 | expr = std::move(wrap_expr); |
| 19019 | } |
| 19020 | else if (expected_type != expr_type.basetype) |
| 19021 | { |
| 19022 | if (is_array(expr_type) && (builtin == BuiltInTessLevelInner || builtin == BuiltInTessLevelOuter)) |
| 19023 | { |
| 19024 | // Triggers when loading TessLevel directly as an array. |
| 19025 | // Need explicit padding + cast. |
| 19026 | auto wrap_expr = join(type_to_glsl(expr_type), "({ "); |
| 19027 | |
| 19028 | uint32_t array_size = get_physical_tess_level_array_size(builtin); |
| 19029 | for (uint32_t i = 0; i < array_size; i++) |
| 19030 | { |
| 19031 | if (array_size > 1) |
| 19032 | wrap_expr += join("float(", expr, "[", i, "])"); |
| 19033 | else |
| 19034 | wrap_expr += join("float(", expr, ")"); |
| 19035 | if (i + 1 < array_size) |
| 19036 | wrap_expr += ", "; |
| 19037 | } |
| 19038 | |
| 19039 | if (is_tessellating_triangles()) |
| 19040 | wrap_expr += ", 0.0"; |
| 19041 | |
| 19042 | wrap_expr += " })"; |
| 19043 | expr = std::move(wrap_expr); |
| 19044 | } |
| 19045 | else |
| 19046 | { |
| 19047 | // These are of different widths, so we cannot do a straight bitcast. |
| 19048 | if (expected_width != expr_type.width) |
| 19049 | expr = join(type_to_glsl(expr_type), "(", expr, ")"); |
| 19050 | else |
| 19051 | expr = bitcast_expression(expr_type, expected_type, expr); |
| 19052 | } |
| 19053 | } |
| 19054 | } |
| 19055 | |
| 19056 | void CompilerMSL::cast_to_variable_store(uint32_t target_id, std::string &expr, const SPIRType &expr_type) |
| 19057 | { |
| 19058 | bool is_packed = has_extended_decoration(target_id, SPIRVCrossDecorationPhysicalTypePacked); |
| 19059 | auto *target_expr = maybe_get<SPIRExpression>(target_id); |
| 19060 | auto *var = maybe_get_backing_variable(target_id); |
| 19061 | const SPIRType *var_type = nullptr, *phys_type = nullptr; |
| 19062 | |
| 19063 | if (uint32_t phys_id = get_extended_decoration(target_id, SPIRVCrossDecorationPhysicalTypeID)) |
| 19064 | phys_type = &get<SPIRType>(phys_id); |
| 19065 | else |
| 19066 | phys_type = &expr_type; |
| 19067 | |
| 19068 | if (var) |
| 19069 | { |
| 19070 | target_id = var->self; |
| 19071 | var_type = &get_variable_data_type(*var); |
| 19072 | } |
| 19073 | |
| 19074 | bool rewrite_boolean_store = |
| 19075 | expr_type.basetype == SPIRType::Boolean && |
| 19076 | (var && (var->storage == StorageClassWorkgroup || var_type->basetype == SPIRType::Struct)); |
| 19077 | |
| 19078 | // Type fixups for workgroup variables or struct members if they are booleans. |
| 19079 | if (rewrite_boolean_store) |
| 19080 | { |
| 19081 | if (is_array(expr_type)) |
| 19082 | { |
| 19083 | expr = to_rerolled_array_expression(*var_type, expr, expr_type); |
| 19084 | } |
| 19085 | else |
| 19086 | { |
| 19087 | auto short_type = expr_type; |
| 19088 | short_type.basetype = SPIRType::Short; |
| 19089 | expr = join(type_to_glsl(short_type), "(", expr, ")"); |
| 19090 | } |
| 19091 | } |
| 19092 | |
| 19093 | // Type fixups for workgroup variables if they are matrices. |
| 19094 | // Don't do fixup for packed types; those are handled specially. |
| 19095 | // FIXME: Maybe use a type like spvStorageMatrix for packed matrices? |
| 19096 | if (!msl_options.supports_msl_version(3, 0) && var && |
| 19097 | (var->storage == StorageClassWorkgroup || |
| 19098 | (var_type->basetype == SPIRType::Struct && |
| 19099 | has_extended_decoration(var_type->self, SPIRVCrossDecorationWorkgroupStruct) && !is_packed)) && |
| 19100 | expr_type.columns > 1) |
| 19101 | { |
| 19102 | SPIRType matrix_type = *phys_type; |
| 19103 | if (target_expr && target_expr->need_transpose) |
| 19104 | swap(matrix_type.vecsize, matrix_type.columns); |
| 19105 | expr = join("spvStorage_", type_to_glsl(matrix_type), "(", expr, ")"); |
| 19106 | } |
| 19107 | |
| 19108 | // Only interested in standalone builtin variables. |
| 19109 | if (!has_decoration(target_id, DecorationBuiltIn)) |
| 19110 | return; |
| 19111 | |
| 19112 | auto builtin = static_cast<BuiltIn>(get_decoration(target_id, DecorationBuiltIn)); |
| 19113 | auto expected_type = expr_type.basetype; |
| 19114 | auto expected_width = expr_type.width; |
| 19115 | switch (builtin) |
| 19116 | { |
| 19117 | case BuiltInLayer: |
| 19118 | case BuiltInViewportIndex: |
| 19119 | case BuiltInFragStencilRefEXT: |
| 19120 | case BuiltInPrimitiveId: |
| 19121 | case BuiltInViewIndex: |
| 19122 | expected_type = SPIRType::UInt; |
| 19123 | expected_width = 32; |
| 19124 | break; |
| 19125 | |
| 19126 | case BuiltInTessLevelInner: |
| 19127 | case BuiltInTessLevelOuter: |
| 19128 | expected_type = SPIRType::Half; |
| 19129 | expected_width = 16; |
| 19130 | break; |
| 19131 | |
| 19132 | default: |
| 19133 | break; |
| 19134 | } |
| 19135 | |
| 19136 | if (expected_type != expr_type.basetype) |
| 19137 | { |
| 19138 | if (expected_width != expr_type.width) |
| 19139 | { |
| 19140 | // These are of different widths, so we cannot do a straight bitcast. |
| 19141 | auto type = expr_type; |
| 19142 | type.basetype = expected_type; |
| 19143 | type.width = expected_width; |
| 19144 | expr = join(type_to_glsl(type), "(", expr, ")"); |
| 19145 | } |
| 19146 | else |
| 19147 | { |
| 19148 | auto type = expr_type; |
| 19149 | type.basetype = expected_type; |
| 19150 | expr = bitcast_expression(type, expr_type.basetype, expr); |
| 19151 | } |
| 19152 | } |
| 19153 | } |
| 19154 | |
| 19155 | string CompilerMSL::to_initializer_expression(const SPIRVariable &var) |
| 19156 | { |
| 19157 | // We risk getting an array initializer here with MSL. If we have an array. |
| 19158 | // FIXME: We cannot handle non-constant arrays being initialized. |
| 19159 | // We will need to inject spvArrayCopy here somehow ... |
| 19160 | auto &type = get<SPIRType>(var.basetype); |
| 19161 | string expr; |
| 19162 | if (ir.ids[var.initializer].get_type() == TypeConstant && |
| 19163 | (!type.array.empty() || type.basetype == SPIRType::Struct)) |
| 19164 | expr = constant_expression(get<SPIRConstant>(var.initializer)); |
| 19165 | else |
| 19166 | expr = CompilerGLSL::to_initializer_expression(var); |
| 19167 | // If the initializer has more vector components than the variable, add a swizzle. |
| 19168 | // FIXME: This can't handle arrays or structs. |
| 19169 | auto &init_type = expression_type(var.initializer); |
| 19170 | if (type.array.empty() && type.basetype != SPIRType::Struct && init_type.vecsize > type.vecsize) |
| 19171 | expr = enclose_expression(expr + vector_swizzle(type.vecsize, 0)); |
| 19172 | return expr; |
| 19173 | } |
| 19174 | |
| 19175 | string CompilerMSL::to_zero_initialized_expression(uint32_t) |
| 19176 | { |
| 19177 | return "{}"; |
| 19178 | } |
| 19179 | |
| 19180 | bool CompilerMSL::descriptor_set_is_argument_buffer(uint32_t desc_set) const |
| 19181 | { |
| 19182 | if (!msl_options.argument_buffers) |
| 19183 | return false; |
| 19184 | if (desc_set >= kMaxArgumentBuffers) |
| 19185 | return false; |
| 19186 | |
| 19187 | return (argument_buffer_discrete_mask & (1u << desc_set)) == 0; |
| 19188 | } |
| 19189 | |
| 19190 | bool CompilerMSL::is_supported_argument_buffer_type(const SPIRType &type) const |
| 19191 | { |
| 19192 | // iOS Tier 1 argument buffers do not support writable images. |
| 19193 | // When the argument buffer is encoded, we don't know whether this image will have a |
| 19194 | // NonWritable decoration, so just use discrete arguments for all storage images on iOS. |
| 19195 | bool is_supported_type = !(type.basetype == SPIRType::Image && |
| 19196 | type.image.sampled == 2 && |
| 19197 | msl_options.is_ios() && |
| 19198 | msl_options.argument_buffers_tier <= Options::ArgumentBuffersTier::Tier1); |
| 19199 | return is_supported_type && !type_is_msl_framebuffer_fetch(type); |
| 19200 | } |
| 19201 | |
| 19202 | void CompilerMSL::emit_argument_buffer_aliased_descriptor(const SPIRVariable &aliased_var, |
| 19203 | const SPIRVariable &base_var) |
| 19204 | { |
| 19205 | // To deal with buffer <-> image aliasing, we need to perform an unholy UB ritual. |
| 19206 | // A texture type in Metal 3.0 is a pointer. However, we cannot simply cast a pointer to texture. |
| 19207 | // What we *can* do is to cast pointer-to-pointer to pointer-to-texture. |
| 19208 | |
| 19209 | // We need to explicitly reach into the descriptor buffer lvalue, not any spvDescriptorArray wrapper. |
| 19210 | auto *var_meta = ir.find_meta(base_var.self); |
| 19211 | bool old_explicit_qualifier = var_meta && var_meta->decoration.qualified_alias_explicit_override; |
| 19212 | if (var_meta) |
| 19213 | var_meta->decoration.qualified_alias_explicit_override = false; |
| 19214 | auto unqualified_name = to_name(base_var.self, false); |
| 19215 | if (var_meta) |
| 19216 | var_meta->decoration.qualified_alias_explicit_override = old_explicit_qualifier; |
| 19217 | |
| 19218 | // For non-arrayed buffers, we have already performed a de-reference. |
| 19219 | // We need a proper lvalue to cast, so strip away the de-reference. |
| 19220 | if (unqualified_name.size() > 2 && unqualified_name[0] == '(' && unqualified_name[1] == '*') |
| 19221 | { |
| 19222 | unqualified_name.erase(unqualified_name.begin(), unqualified_name.begin() + 2); |
| 19223 | unqualified_name.pop_back(); |
| 19224 | } |
| 19225 | |
| 19226 | string name; |
| 19227 | |
| 19228 | auto &var_type = get<SPIRType>(aliased_var.basetype); |
| 19229 | auto &data_type = get_variable_data_type(aliased_var); |
| 19230 | string descriptor_storage = descriptor_address_space(aliased_var.self, aliased_var.storage, ""); |
| 19231 | |
| 19232 | if (aliased_var.storage == StorageClassUniformConstant) |
| 19233 | { |
| 19234 | if (is_var_runtime_size_array(aliased_var)) |
| 19235 | { |
| 19236 | // This becomes a plain pointer to spvDescriptor. |
| 19237 | name = join("reinterpret_cast<", descriptor_storage, " ", |
| 19238 | type_to_glsl(get_variable_data_type(aliased_var), aliased_var.self, true), ">(&", |
| 19239 | unqualified_name, ")"); |
| 19240 | } |
| 19241 | else |
| 19242 | { |
| 19243 | name = join("reinterpret_cast<", descriptor_storage, " ", |
| 19244 | type_to_glsl(get_variable_data_type(aliased_var), aliased_var.self, true), " &>(", |
| 19245 | unqualified_name, ");"); |
| 19246 | } |
| 19247 | } |
| 19248 | else |
| 19249 | { |
| 19250 | // Buffer types. |
| 19251 | bool old_is_using_builtin_array = is_using_builtin_array; |
| 19252 | is_using_builtin_array = true; |
| 19253 | |
| 19254 | bool needs_post_cast_deref = !is_array(data_type); |
| 19255 | string ref_type = needs_post_cast_deref ? "&" : join("(&)", type_to_array_glsl(var_type, aliased_var.self)); |
| 19256 | |
| 19257 | if (is_var_runtime_size_array(aliased_var)) |
| 19258 | { |
| 19259 | name = join("reinterpret_cast<", |
| 19260 | type_to_glsl(var_type, aliased_var.self, true), " ", descriptor_storage, " *>(&", |
| 19261 | unqualified_name, ")"); |
| 19262 | } |
| 19263 | else |
| 19264 | { |
| 19265 | name = join(needs_post_cast_deref ? "*" : "", "reinterpret_cast<", |
| 19266 | type_to_glsl(var_type, aliased_var.self, true), " ", descriptor_storage, " ", |
| 19267 | ref_type, |
| 19268 | ">(", unqualified_name, ");"); |
| 19269 | } |
| 19270 | |
| 19271 | if (needs_post_cast_deref) |
| 19272 | descriptor_storage = get_type_address_space(var_type, aliased_var.self, false); |
| 19273 | |
| 19274 | // These kinds of ridiculous casts trigger warnings in compiler. Just ignore them. |
| 19275 | if (!suppress_incompatible_pointer_types_discard_qualifiers) |
| 19276 | { |
| 19277 | suppress_incompatible_pointer_types_discard_qualifiers = true; |
| 19278 | force_recompile_guarantee_forward_progress(); |
| 19279 | } |
| 19280 | |
| 19281 | is_using_builtin_array = old_is_using_builtin_array; |
| 19282 | } |
| 19283 | |
| 19284 | if (!is_var_runtime_size_array(aliased_var)) |
| 19285 | { |
| 19286 | // Lower to temporary, so drop the qualification. |
| 19287 | set_qualified_name(aliased_var.self, ""); |
| 19288 | statement(descriptor_storage, " auto &", to_name(aliased_var.self), " = ", name); |
| 19289 | } |
| 19290 | else |
| 19291 | { |
| 19292 | // This alias may have already been used to emit an entry point declaration. If there is a mismatch, we need a recompile. |
| 19293 | // Moving this code to be run earlier will also conflict, |
| 19294 | // because we need the qualified alias for the base resource, |
| 19295 | // so forcing recompile until things sync up is the least invasive method for now. |
| 19296 | if (ir.meta[aliased_var.self].decoration.qualified_alias != name) |
| 19297 | force_recompile(); |
| 19298 | |
| 19299 | // This will get wrapped in a separate temporary when a spvDescriptorArray wrapper is emitted. |
| 19300 | set_qualified_name(aliased_var.self, name); |
| 19301 | } |
| 19302 | } |
| 19303 | |
| 19304 | void CompilerMSL::analyze_argument_buffers() |
| 19305 | { |
| 19306 | // Gather all used resources and sort them out into argument buffers. |
| 19307 | // Each argument buffer corresponds to a descriptor set in SPIR-V. |
| 19308 | // The [[id(N)]] values used correspond to the resource mapping we have for MSL. |
| 19309 | // Otherwise, the binding number is used, but this is generally not safe some types like |
| 19310 | // combined image samplers and arrays of resources. Metal needs different indices here, |
| 19311 | // while SPIR-V can have one descriptor set binding. To use argument buffers in practice, |
| 19312 | // you will need to use the remapping from the API. |
| 19313 | for (auto &id : argument_buffer_ids) |
| 19314 | id = 0; |
| 19315 | |
| 19316 | // Output resources, sorted by resource index & type. |
| 19317 | struct Resource |
| 19318 | { |
| 19319 | SPIRVariable *var; |
| 19320 | string name; |
| 19321 | SPIRType::BaseType basetype; |
| 19322 | uint32_t index; |
| 19323 | uint32_t plane_count; |
| 19324 | uint32_t plane; |
| 19325 | uint32_t overlapping_var_id; |
| 19326 | }; |
| 19327 | SmallVector<Resource> resources_in_set[kMaxArgumentBuffers]; |
| 19328 | SmallVector<uint32_t> inline_block_vars; |
| 19329 | |
| 19330 | bool set_needs_swizzle_buffer[kMaxArgumentBuffers] = {}; |
| 19331 | bool set_needs_buffer_sizes[kMaxArgumentBuffers] = {}; |
| 19332 | bool needs_buffer_sizes = false; |
| 19333 | |
| 19334 | ir.for_each_typed_id<SPIRVariable>([&](uint32_t self, SPIRVariable &var) { |
| 19335 | if ((var.storage == StorageClassUniform || var.storage == StorageClassUniformConstant || |
| 19336 | var.storage == StorageClassStorageBuffer) && |
| 19337 | !is_hidden_variable(var)) |
| 19338 | { |
| 19339 | uint32_t desc_set = get_decoration(self, DecorationDescriptorSet); |
| 19340 | // Ignore if it's part of a push descriptor set. |
| 19341 | if (!descriptor_set_is_argument_buffer(desc_set)) |
| 19342 | return; |
| 19343 | |
| 19344 | uint32_t var_id = var.self; |
| 19345 | auto &type = get_variable_data_type(var); |
| 19346 | |
| 19347 | if (desc_set >= kMaxArgumentBuffers) |
| 19348 | SPIRV_CROSS_THROW("Descriptor set index is out of range."); |
| 19349 | |
| 19350 | const MSLConstexprSampler *constexpr_sampler = nullptr; |
| 19351 | if (type.basetype == SPIRType::SampledImage || type.basetype == SPIRType::Sampler) |
| 19352 | { |
| 19353 | constexpr_sampler = find_constexpr_sampler(var_id); |
| 19354 | if (constexpr_sampler) |
| 19355 | { |
| 19356 | // Mark this ID as a constexpr sampler for later in case it came from set/bindings. |
| 19357 | constexpr_samplers_by_id[var_id] = *constexpr_sampler; |
| 19358 | } |
| 19359 | } |
| 19360 | |
| 19361 | uint32_t binding = get_decoration(var_id, DecorationBinding); |
| 19362 | if (type.basetype == SPIRType::SampledImage) |
| 19363 | { |
| 19364 | add_resource_name(var_id); |
| 19365 | |
| 19366 | uint32_t plane_count = 1; |
| 19367 | if (constexpr_sampler && constexpr_sampler->ycbcr_conversion_enable) |
| 19368 | plane_count = constexpr_sampler->planes; |
| 19369 | |
| 19370 | for (uint32_t i = 0; i < plane_count; i++) |
| 19371 | { |
| 19372 | uint32_t image_resource_index = get_metal_resource_index(var, SPIRType::Image, i); |
| 19373 | resources_in_set[desc_set].push_back( |
| 19374 | { &var, to_name(var_id), SPIRType::Image, image_resource_index, plane_count, i, 0 }); |
| 19375 | } |
| 19376 | |
| 19377 | if (type.image.dim != DimBuffer && !constexpr_sampler) |
| 19378 | { |
| 19379 | uint32_t sampler_resource_index = get_metal_resource_index(var, SPIRType::Sampler); |
| 19380 | resources_in_set[desc_set].push_back( |
| 19381 | { &var, to_sampler_expression(var_id), SPIRType::Sampler, sampler_resource_index, 1, 0, 0 }); |
| 19382 | } |
| 19383 | } |
| 19384 | else if (inline_uniform_blocks.count(SetBindingPair{ desc_set, binding })) |
| 19385 | { |
| 19386 | inline_block_vars.push_back(var_id); |
| 19387 | } |
| 19388 | else if (!constexpr_sampler && is_supported_argument_buffer_type(type)) |
| 19389 | { |
| 19390 | // constexpr samplers are not declared as resources. |
| 19391 | // Inline uniform blocks are always emitted at the end. |
| 19392 | add_resource_name(var_id); |
| 19393 | |
| 19394 | uint32_t resource_index = get_metal_resource_index(var, type.basetype); |
| 19395 | |
| 19396 | resources_in_set[desc_set].push_back( |
| 19397 | { &var, to_name(var_id), type.basetype, resource_index, 1, 0, 0 }); |
| 19398 | |
| 19399 | // Emulate texture2D atomic operations |
| 19400 | if (atomic_image_vars_emulated.count(var.self)) |
| 19401 | { |
| 19402 | uint32_t buffer_resource_index = get_metal_resource_index(var, SPIRType::AtomicCounter, 0); |
| 19403 | resources_in_set[desc_set].push_back( |
| 19404 | { &var, to_name(var_id) + "_atomic", SPIRType::Struct, buffer_resource_index, 1, 0, 0 }); |
| 19405 | } |
| 19406 | } |
| 19407 | |
| 19408 | // Check if this descriptor set needs a swizzle buffer. |
| 19409 | if (needs_swizzle_buffer_def && is_sampled_image_type(type)) |
| 19410 | set_needs_swizzle_buffer[desc_set] = true; |
| 19411 | else if (buffer_requires_array_length(var_id)) |
| 19412 | { |
| 19413 | set_needs_buffer_sizes[desc_set] = true; |
| 19414 | needs_buffer_sizes = true; |
| 19415 | } |
| 19416 | } |
| 19417 | }); |
| 19418 | |
| 19419 | if (needs_swizzle_buffer_def || needs_buffer_sizes) |
| 19420 | { |
| 19421 | uint32_t uint_ptr_type_id = 0; |
| 19422 | |
| 19423 | // We might have to add a swizzle buffer resource to the set. |
| 19424 | for (uint32_t desc_set = 0; desc_set < kMaxArgumentBuffers; desc_set++) |
| 19425 | { |
| 19426 | if (!set_needs_swizzle_buffer[desc_set] && !set_needs_buffer_sizes[desc_set]) |
| 19427 | continue; |
| 19428 | |
| 19429 | if (uint_ptr_type_id == 0) |
| 19430 | { |
| 19431 | uint_ptr_type_id = ir.increase_bound_by(1); |
| 19432 | |
| 19433 | // Create a buffer to hold extra data, including the swizzle constants. |
| 19434 | SPIRType uint_type_pointer = get_uint_type(); |
| 19435 | uint_type_pointer.op = OpTypePointer; |
| 19436 | uint_type_pointer.pointer = true; |
| 19437 | uint_type_pointer.pointer_depth++; |
| 19438 | uint_type_pointer.parent_type = get_uint_type_id(); |
| 19439 | uint_type_pointer.storage = StorageClassUniform; |
| 19440 | set<SPIRType>(uint_ptr_type_id, uint_type_pointer); |
| 19441 | set_decoration(uint_ptr_type_id, DecorationArrayStride, 4); |
| 19442 | } |
| 19443 | |
| 19444 | if (set_needs_swizzle_buffer[desc_set]) |
| 19445 | { |
| 19446 | uint32_t var_id = ir.increase_bound_by(1); |
| 19447 | auto &var = set<SPIRVariable>(var_id, uint_ptr_type_id, StorageClassUniformConstant); |
| 19448 | set_name(var_id, "spvSwizzleConstants"); |
| 19449 | set_decoration(var_id, DecorationDescriptorSet, desc_set); |
| 19450 | set_decoration(var_id, DecorationBinding, kSwizzleBufferBinding); |
| 19451 | resources_in_set[desc_set].push_back( |
| 19452 | { &var, to_name(var_id), SPIRType::UInt, get_metal_resource_index(var, SPIRType::UInt), 1, 0, 0 }); |
| 19453 | } |
| 19454 | |
| 19455 | if (set_needs_buffer_sizes[desc_set]) |
| 19456 | { |
| 19457 | uint32_t var_id = ir.increase_bound_by(1); |
| 19458 | auto &var = set<SPIRVariable>(var_id, uint_ptr_type_id, StorageClassUniformConstant); |
| 19459 | set_name(var_id, "spvBufferSizeConstants"); |
| 19460 | set_decoration(var_id, DecorationDescriptorSet, desc_set); |
| 19461 | set_decoration(var_id, DecorationBinding, kBufferSizeBufferBinding); |
| 19462 | resources_in_set[desc_set].push_back( |
| 19463 | { &var, to_name(var_id), SPIRType::UInt, get_metal_resource_index(var, SPIRType::UInt), 1, 0, 0 }); |
| 19464 | } |
| 19465 | } |
| 19466 | } |
| 19467 | |
| 19468 | // Now add inline uniform blocks. |
| 19469 | for (uint32_t var_id : inline_block_vars) |
| 19470 | { |
| 19471 | auto &var = get<SPIRVariable>(var_id); |
| 19472 | uint32_t desc_set = get_decoration(var_id, DecorationDescriptorSet); |
| 19473 | add_resource_name(var_id); |
| 19474 | resources_in_set[desc_set].push_back( |
| 19475 | { &var, to_name(var_id), SPIRType::Struct, get_metal_resource_index(var, SPIRType::Struct), 1, 0, 0 }); |
| 19476 | } |
| 19477 | |
| 19478 | for (uint32_t desc_set = 0; desc_set < kMaxArgumentBuffers; desc_set++) |
| 19479 | { |
| 19480 | auto &resources = resources_in_set[desc_set]; |
| 19481 | if (resources.empty()) |
| 19482 | continue; |
| 19483 | |
| 19484 | assert(descriptor_set_is_argument_buffer(desc_set)); |
| 19485 | |
| 19486 | uint32_t next_id = ir.increase_bound_by(3); |
| 19487 | uint32_t type_id = next_id + 1; |
| 19488 | uint32_t ptr_type_id = next_id + 2; |
| 19489 | argument_buffer_ids[desc_set] = next_id; |
| 19490 | |
| 19491 | auto &buffer_type = set<SPIRType>(type_id, OpTypeStruct); |
| 19492 | |
| 19493 | buffer_type.basetype = SPIRType::Struct; |
| 19494 | |
| 19495 | if ((argument_buffer_device_storage_mask & (1u << desc_set)) != 0) |
| 19496 | { |
| 19497 | buffer_type.storage = StorageClassStorageBuffer; |
| 19498 | // Make sure the argument buffer gets marked as const device. |
| 19499 | set_decoration(next_id, DecorationNonWritable); |
| 19500 | // Need to mark the type as a Block to enable this. |
| 19501 | set_decoration(type_id, DecorationBlock); |
| 19502 | } |
| 19503 | else |
| 19504 | buffer_type.storage = StorageClassUniform; |
| 19505 | |
| 19506 | auto buffer_type_name = join("spvDescriptorSetBuffer", desc_set); |
| 19507 | set_name(type_id, buffer_type_name); |
| 19508 | |
| 19509 | auto &ptr_type = set<SPIRType>(ptr_type_id, OpTypePointer); |
| 19510 | ptr_type = buffer_type; |
| 19511 | ptr_type.op = spv::OpTypePointer; |
| 19512 | ptr_type.pointer = true; |
| 19513 | ptr_type.pointer_depth++; |
| 19514 | ptr_type.parent_type = type_id; |
| 19515 | |
| 19516 | uint32_t buffer_variable_id = next_id; |
| 19517 | auto &buffer_var = set<SPIRVariable>(buffer_variable_id, ptr_type_id, StorageClassUniform); |
| 19518 | auto buffer_name = join("spvDescriptorSet", desc_set); |
| 19519 | set_name(buffer_variable_id, buffer_name); |
| 19520 | |
| 19521 | // Ids must be emitted in ID order. |
| 19522 | stable_sort(begin(resources), end(resources), [&](const Resource &lhs, const Resource &rhs) -> bool { |
| 19523 | return tie(lhs.index, lhs.basetype) < tie(rhs.index, rhs.basetype); |
| 19524 | }); |
| 19525 | |
| 19526 | for (size_t i = 0; i < resources.size() - 1; i++) |
| 19527 | { |
| 19528 | auto &r1 = resources[i]; |
| 19529 | auto &r2 = resources[i + 1]; |
| 19530 | |
| 19531 | if (r1.index == r2.index) |
| 19532 | { |
| 19533 | if (r1.overlapping_var_id) |
| 19534 | r2.overlapping_var_id = r1.overlapping_var_id; |
| 19535 | else |
| 19536 | r2.overlapping_var_id = r1.var->self; |
| 19537 | |
| 19538 | set_extended_decoration(r2.var->self, SPIRVCrossDecorationOverlappingBinding, r2.overlapping_var_id); |
| 19539 | } |
| 19540 | } |
| 19541 | |
| 19542 | uint32_t member_index = 0; |
| 19543 | uint32_t next_arg_buff_index = 0; |
| 19544 | uint32_t prev_was_scalar_on_array_offset = 0; |
| 19545 | for (auto &resource : resources) |
| 19546 | { |
| 19547 | auto &var = *resource.var; |
| 19548 | auto &type = get_variable_data_type(var); |
| 19549 | |
| 19550 | if (is_var_runtime_size_array(var) && (argument_buffer_device_storage_mask & (1u << desc_set)) == 0) |
| 19551 | SPIRV_CROSS_THROW("Runtime sized variables must be in device storage argument buffers."); |
| 19552 | |
| 19553 | // If needed, synthesize and add padding members. |
| 19554 | // member_index and next_arg_buff_index are incremented when padding members are added. |
| 19555 | if (msl_options.pad_argument_buffer_resources && resource.plane == 0 && resource.overlapping_var_id == 0) |
| 19556 | { |
| 19557 | auto rez_bind = get_argument_buffer_resource(desc_set, next_arg_buff_index - prev_was_scalar_on_array_offset); |
| 19558 | rez_bind.count -= prev_was_scalar_on_array_offset; |
| 19559 | |
| 19560 | while (resource.index > next_arg_buff_index) |
| 19561 | { |
| 19562 | switch (rez_bind.basetype) |
| 19563 | { |
| 19564 | case SPIRType::Void: |
| 19565 | case SPIRType::Boolean: |
| 19566 | case SPIRType::SByte: |
| 19567 | case SPIRType::UByte: |
| 19568 | case SPIRType::Short: |
| 19569 | case SPIRType::UShort: |
| 19570 | case SPIRType::Int: |
| 19571 | case SPIRType::UInt: |
| 19572 | case SPIRType::Int64: |
| 19573 | case SPIRType::UInt64: |
| 19574 | case SPIRType::AtomicCounter: |
| 19575 | case SPIRType::Half: |
| 19576 | case SPIRType::Float: |
| 19577 | case SPIRType::Double: |
| 19578 | add_argument_buffer_padding_buffer_type(buffer_type, member_index, next_arg_buff_index, rez_bind); |
| 19579 | break; |
| 19580 | case SPIRType::Image: |
| 19581 | add_argument_buffer_padding_image_type(buffer_type, member_index, next_arg_buff_index, rez_bind); |
| 19582 | break; |
| 19583 | case SPIRType::Sampler: |
| 19584 | add_argument_buffer_padding_sampler_type(buffer_type, member_index, next_arg_buff_index, rez_bind); |
| 19585 | break; |
| 19586 | case SPIRType::SampledImage: |
| 19587 | if (next_arg_buff_index == rez_bind.msl_sampler) |
| 19588 | add_argument_buffer_padding_sampler_type(buffer_type, member_index, next_arg_buff_index, rez_bind); |
| 19589 | else |
| 19590 | add_argument_buffer_padding_image_type(buffer_type, member_index, next_arg_buff_index, rez_bind); |
| 19591 | break; |
| 19592 | default: |
| 19593 | break; |
| 19594 | } |
| 19595 | |
| 19596 | // After padding, retrieve the resource again. It will either be more padding, or the actual resource. |
| 19597 | rez_bind = get_argument_buffer_resource(desc_set, next_arg_buff_index); |
| 19598 | prev_was_scalar_on_array_offset = 0; |
| 19599 | } |
| 19600 | |
| 19601 | uint32_t count = rez_bind.count; |
| 19602 | |
| 19603 | // If the current resource is an array in the descriptor, but is a scalar |
| 19604 | // in the shader, only the first element will be consumed. The next pass |
| 19605 | // will add a padding member to consume the remaining array elements. |
| 19606 | if (count > 1 && type.array.empty()) |
| 19607 | count = prev_was_scalar_on_array_offset = 1; |
| 19608 | |
| 19609 | // Adjust the number of slots consumed by current member itself. |
| 19610 | next_arg_buff_index += resource.plane_count * count; |
| 19611 | } |
| 19612 | |
| 19613 | string mbr_name = ensure_valid_name(resource.name, "m"); |
| 19614 | if (resource.plane > 0) |
| 19615 | mbr_name += join(plane_name_suffix, resource.plane); |
| 19616 | set_member_name(buffer_type.self, member_index, mbr_name); |
| 19617 | |
| 19618 | if (resource.basetype == SPIRType::Sampler && type.basetype != SPIRType::Sampler) |
| 19619 | { |
| 19620 | // Have to synthesize a sampler type here. |
| 19621 | |
| 19622 | bool type_is_array = !type.array.empty(); |
| 19623 | uint32_t sampler_type_id = ir.increase_bound_by(type_is_array ? 2 : 1); |
| 19624 | auto &new_sampler_type = set<SPIRType>(sampler_type_id, OpTypeSampler); |
| 19625 | new_sampler_type.basetype = SPIRType::Sampler; |
| 19626 | new_sampler_type.storage = StorageClassUniformConstant; |
| 19627 | |
| 19628 | if (type_is_array) |
| 19629 | { |
| 19630 | uint32_t sampler_type_array_id = sampler_type_id + 1; |
| 19631 | auto &sampler_type_array = set<SPIRType>(sampler_type_array_id, OpTypeArray); |
| 19632 | sampler_type_array = new_sampler_type; |
| 19633 | sampler_type_array.array = type.array; |
| 19634 | sampler_type_array.array_size_literal = type.array_size_literal; |
| 19635 | sampler_type_array.parent_type = sampler_type_id; |
| 19636 | buffer_type.member_types.push_back(sampler_type_array_id); |
| 19637 | } |
| 19638 | else |
| 19639 | buffer_type.member_types.push_back(sampler_type_id); |
| 19640 | } |
| 19641 | else |
| 19642 | { |
| 19643 | uint32_t binding = get_decoration(var.self, DecorationBinding); |
| 19644 | SetBindingPair pair = { desc_set, binding }; |
| 19645 | |
| 19646 | if (resource.basetype == SPIRType::Image || resource.basetype == SPIRType::Sampler || |
| 19647 | resource.basetype == SPIRType::SampledImage || resource.basetype == SPIRType::AccelerationStructure) |
| 19648 | { |
| 19649 | // Drop pointer information when we emit the resources into a struct. |
| 19650 | buffer_type.member_types.push_back(get_variable_data_type_id(var)); |
| 19651 | if (has_extended_decoration(var.self, SPIRVCrossDecorationOverlappingBinding)) |
| 19652 | { |
| 19653 | if (!msl_options.supports_msl_version(3, 0)) |
| 19654 | SPIRV_CROSS_THROW("Full mutable aliasing of argument buffer descriptors only works on Metal 3+."); |
| 19655 | |
| 19656 | auto &entry_func = get<SPIRFunction>(ir.default_entry_point); |
| 19657 | entry_func.fixup_hooks_in.push_back([this, resource]() { |
| 19658 | emit_argument_buffer_aliased_descriptor(*resource.var, this->get<SPIRVariable>(resource.overlapping_var_id)); |
| 19659 | }); |
| 19660 | } |
| 19661 | else if (resource.plane == 0) |
| 19662 | { |
| 19663 | set_qualified_name(var.self, join(to_name(buffer_variable_id), ".", mbr_name)); |
| 19664 | } |
| 19665 | } |
| 19666 | else if (buffers_requiring_dynamic_offset.count(pair)) |
| 19667 | { |
| 19668 | // Don't set the qualified name here; we'll define a variable holding the corrected buffer address later. |
| 19669 | buffer_type.member_types.push_back(var.basetype); |
| 19670 | buffers_requiring_dynamic_offset[pair].second = var.self; |
| 19671 | } |
| 19672 | else if (inline_uniform_blocks.count(pair)) |
| 19673 | { |
| 19674 | // Put the buffer block itself into the argument buffer. |
| 19675 | buffer_type.member_types.push_back(get_variable_data_type_id(var)); |
| 19676 | set_qualified_name(var.self, join(to_name(buffer_variable_id), ".", mbr_name)); |
| 19677 | } |
| 19678 | else if (atomic_image_vars_emulated.count(var.self)) |
| 19679 | { |
| 19680 | // Emulate texture2D atomic operations. |
| 19681 | // Don't set the qualified name: it's already set for this variable, |
| 19682 | // and the code that references the buffer manually appends "_atomic" |
| 19683 | // to the name. |
| 19684 | uint32_t offset = ir.increase_bound_by(2); |
| 19685 | uint32_t atomic_type_id = offset; |
| 19686 | uint32_t type_ptr_id = offset + 1; |
| 19687 | |
| 19688 | SPIRType atomic_type { OpTypeInt }; |
| 19689 | atomic_type.basetype = SPIRType::AtomicCounter; |
| 19690 | atomic_type.width = 32; |
| 19691 | atomic_type.vecsize = 1; |
| 19692 | set<SPIRType>(atomic_type_id, atomic_type); |
| 19693 | |
| 19694 | atomic_type.op = OpTypePointer; |
| 19695 | atomic_type.pointer = true; |
| 19696 | atomic_type.pointer_depth++; |
| 19697 | atomic_type.parent_type = atomic_type_id; |
| 19698 | atomic_type.storage = StorageClassStorageBuffer; |
| 19699 | auto &atomic_ptr_type = set<SPIRType>(type_ptr_id, atomic_type); |
| 19700 | atomic_ptr_type.self = atomic_type_id; |
| 19701 | |
| 19702 | buffer_type.member_types.push_back(type_ptr_id); |
| 19703 | } |
| 19704 | else |
| 19705 | { |
| 19706 | buffer_type.member_types.push_back(var.basetype); |
| 19707 | if (has_extended_decoration(var.self, SPIRVCrossDecorationOverlappingBinding)) |
| 19708 | { |
| 19709 | // Casting raw pointers is fine since their ABI is fixed, but anything opaque is deeply questionable on Metal 2. |
| 19710 | if (get<SPIRVariable>(resource.overlapping_var_id).storage == StorageClassUniformConstant && |
| 19711 | !msl_options.supports_msl_version(3, 0)) |
| 19712 | { |
| 19713 | SPIRV_CROSS_THROW("Full mutable aliasing of argument buffer descriptors only works on Metal 3+."); |
| 19714 | } |
| 19715 | |
| 19716 | auto &entry_func = get<SPIRFunction>(ir.default_entry_point); |
| 19717 | |
| 19718 | entry_func.fixup_hooks_in.push_back([this, resource]() { |
| 19719 | emit_argument_buffer_aliased_descriptor(*resource.var, this->get<SPIRVariable>(resource.overlapping_var_id)); |
| 19720 | }); |
| 19721 | } |
| 19722 | else if (type.array.empty()) |
| 19723 | set_qualified_name(var.self, join("(*", to_name(buffer_variable_id), ".", mbr_name, ")")); |
| 19724 | else |
| 19725 | set_qualified_name(var.self, join(to_name(buffer_variable_id), ".", mbr_name)); |
| 19726 | } |
| 19727 | } |
| 19728 | |
| 19729 | set_extended_member_decoration(buffer_type.self, member_index, SPIRVCrossDecorationResourceIndexPrimary, |
| 19730 | resource.index); |
| 19731 | set_extended_member_decoration(buffer_type.self, member_index, SPIRVCrossDecorationInterfaceOrigID, |
| 19732 | var.self); |
| 19733 | if (has_extended_decoration(var.self, SPIRVCrossDecorationOverlappingBinding)) |
| 19734 | set_extended_member_decoration(buffer_type.self, member_index, SPIRVCrossDecorationOverlappingBinding); |
| 19735 | member_index++; |
| 19736 | } |
| 19737 | |
| 19738 | if (msl_options.replace_recursive_inputs && type_contains_recursion(buffer_type)) |
| 19739 | { |
| 19740 | recursive_inputs.insert(type_id); |
| 19741 | auto &entry_func = this->get<SPIRFunction>(ir.default_entry_point); |
| 19742 | auto addr_space = get_argument_address_space(buffer_var); |
| 19743 | entry_func.fixup_hooks_in.push_back([this, addr_space, buffer_name, buffer_type_name]() { |
| 19744 | statement(addr_space, " auto& ", buffer_name, " = *(", addr_space, " ", buffer_type_name, "*)", buffer_name, "_vp;"); |
| 19745 | }); |
| 19746 | } |
| 19747 | } |
| 19748 | } |
| 19749 | |
| 19750 | // Return the resource type of the app-provided resources for the descriptor set, |
| 19751 | // that matches the resource index of the argument buffer index. |
| 19752 | // This is a two-step lookup, first lookup the resource binding number from the argument buffer index, |
| 19753 | // then lookup the resource binding using the binding number. |
| 19754 | const MSLResourceBinding &CompilerMSL::get_argument_buffer_resource(uint32_t desc_set, uint32_t arg_idx) const |
| 19755 | { |
| 19756 | auto stage = get_entry_point().model; |
| 19757 | StageSetBinding arg_idx_tuple = { stage, desc_set, arg_idx }; |
| 19758 | auto arg_itr = resource_arg_buff_idx_to_binding_number.find(arg_idx_tuple); |
| 19759 | if (arg_itr != end(resource_arg_buff_idx_to_binding_number)) |
| 19760 | { |
| 19761 | StageSetBinding bind_tuple = { stage, desc_set, arg_itr->second }; |
| 19762 | auto bind_itr = resource_bindings.find(bind_tuple); |
| 19763 | if (bind_itr != end(resource_bindings)) |
| 19764 | return bind_itr->second.first; |
| 19765 | } |
| 19766 | SPIRV_CROSS_THROW("Argument buffer resource base type could not be determined. When padding argument buffer " |
| 19767 | "elements, all descriptor set resources must be supplied with a base type by the app."); |
| 19768 | } |
| 19769 | |
| 19770 | // Adds an argument buffer padding argument buffer type as one or more members of the struct type at the member index. |
| 19771 | // Metal does not support arrays of buffers, so these are emitted as multiple struct members. |
| 19772 | void CompilerMSL::add_argument_buffer_padding_buffer_type(SPIRType &struct_type, uint32_t &mbr_idx, |
| 19773 | uint32_t &arg_buff_index, MSLResourceBinding &rez_bind) |
| 19774 | { |
| 19775 | if (!argument_buffer_padding_buffer_type_id) |
| 19776 | { |
| 19777 | uint32_t buff_type_id = ir.increase_bound_by(2); |
| 19778 | auto &buff_type = set<SPIRType>(buff_type_id, OpNop); |
| 19779 | buff_type.basetype = rez_bind.basetype; |
| 19780 | buff_type.storage = StorageClassUniformConstant; |
| 19781 | |
| 19782 | uint32_t ptr_type_id = buff_type_id + 1; |
| 19783 | auto &ptr_type = set<SPIRType>(ptr_type_id, OpTypePointer); |
| 19784 | ptr_type = buff_type; |
| 19785 | ptr_type.op = spv::OpTypePointer; |
| 19786 | ptr_type.pointer = true; |
| 19787 | ptr_type.pointer_depth++; |
| 19788 | ptr_type.parent_type = buff_type_id; |
| 19789 | |
| 19790 | argument_buffer_padding_buffer_type_id = ptr_type_id; |
| 19791 | } |
| 19792 | |
| 19793 | add_argument_buffer_padding_type(argument_buffer_padding_buffer_type_id, struct_type, mbr_idx, arg_buff_index, rez_bind.count); |
| 19794 | } |
| 19795 | |
| 19796 | // Adds an argument buffer padding argument image type as a member of the struct type at the member index. |
| 19797 | void CompilerMSL::add_argument_buffer_padding_image_type(SPIRType &struct_type, uint32_t &mbr_idx, |
| 19798 | uint32_t &arg_buff_index, MSLResourceBinding &rez_bind) |
| 19799 | { |
| 19800 | if (!argument_buffer_padding_image_type_id) |
| 19801 | { |
| 19802 | uint32_t base_type_id = ir.increase_bound_by(2); |
| 19803 | auto &base_type = set<SPIRType>(base_type_id, OpTypeFloat); |
| 19804 | base_type.basetype = SPIRType::Float; |
| 19805 | base_type.width = 32; |
| 19806 | |
| 19807 | uint32_t img_type_id = base_type_id + 1; |
| 19808 | auto &img_type = set<SPIRType>(img_type_id, OpTypeImage); |
| 19809 | img_type.basetype = SPIRType::Image; |
| 19810 | img_type.storage = StorageClassUniformConstant; |
| 19811 | |
| 19812 | img_type.image.type = base_type_id; |
| 19813 | img_type.image.dim = Dim2D; |
| 19814 | img_type.image.depth = false; |
| 19815 | img_type.image.arrayed = false; |
| 19816 | img_type.image.ms = false; |
| 19817 | img_type.image.sampled = 1; |
| 19818 | img_type.image.format = ImageFormatUnknown; |
| 19819 | img_type.image.access = AccessQualifierMax; |
| 19820 | |
| 19821 | argument_buffer_padding_image_type_id = img_type_id; |
| 19822 | } |
| 19823 | |
| 19824 | add_argument_buffer_padding_type(argument_buffer_padding_image_type_id, struct_type, mbr_idx, arg_buff_index, rez_bind.count); |
| 19825 | } |
| 19826 | |
| 19827 | // Adds an argument buffer padding argument sampler type as a member of the struct type at the member index. |
| 19828 | void CompilerMSL::add_argument_buffer_padding_sampler_type(SPIRType &struct_type, uint32_t &mbr_idx, |
| 19829 | uint32_t &arg_buff_index, MSLResourceBinding &rez_bind) |
| 19830 | { |
| 19831 | if (!argument_buffer_padding_sampler_type_id) |
| 19832 | { |
| 19833 | uint32_t samp_type_id = ir.increase_bound_by(1); |
| 19834 | auto &samp_type = set<SPIRType>(samp_type_id, OpTypeSampler); |
| 19835 | samp_type.basetype = SPIRType::Sampler; |
| 19836 | samp_type.storage = StorageClassUniformConstant; |
| 19837 | |
| 19838 | argument_buffer_padding_sampler_type_id = samp_type_id; |
| 19839 | } |
| 19840 | |
| 19841 | add_argument_buffer_padding_type(argument_buffer_padding_sampler_type_id, struct_type, mbr_idx, arg_buff_index, rez_bind.count); |
| 19842 | } |
| 19843 | |
| 19844 | // Adds the argument buffer padding argument type as a member of the struct type at the member index. |
| 19845 | // Advances both arg_buff_index and mbr_idx to next argument slots. |
| 19846 | void CompilerMSL::add_argument_buffer_padding_type(uint32_t mbr_type_id, SPIRType &struct_type, uint32_t &mbr_idx, |
| 19847 | uint32_t &arg_buff_index, uint32_t count) |
| 19848 | { |
| 19849 | uint32_t type_id = mbr_type_id; |
| 19850 | if (count > 1) |
| 19851 | { |
| 19852 | uint32_t ary_type_id = ir.increase_bound_by(1); |
| 19853 | auto &ary_type = set<SPIRType>(ary_type_id, get<SPIRType>(type_id)); |
| 19854 | ary_type.op = OpTypeArray; |
| 19855 | ary_type.array.push_back(count); |
| 19856 | ary_type.array_size_literal.push_back(true); |
| 19857 | ary_type.parent_type = type_id; |
| 19858 | type_id = ary_type_id; |
| 19859 | } |
| 19860 | |
| 19861 | set_member_name(struct_type.self, mbr_idx, join("_m", arg_buff_index, "_pad")); |
| 19862 | set_extended_member_decoration(struct_type.self, mbr_idx, SPIRVCrossDecorationResourceIndexPrimary, arg_buff_index); |
| 19863 | struct_type.member_types.push_back(type_id); |
| 19864 | |
| 19865 | arg_buff_index += count; |
| 19866 | mbr_idx++; |
| 19867 | } |
| 19868 | |
| 19869 | void CompilerMSL::activate_argument_buffer_resources() |
| 19870 | { |
| 19871 | // For ABI compatibility, force-enable all resources which are part of argument buffers. |
| 19872 | ir.for_each_typed_id<SPIRVariable>([&](uint32_t self, const SPIRVariable &) { |
| 19873 | if (!has_decoration(self, DecorationDescriptorSet)) |
| 19874 | return; |
| 19875 | |
| 19876 | uint32_t desc_set = get_decoration(self, DecorationDescriptorSet); |
| 19877 | if (descriptor_set_is_argument_buffer(desc_set)) |
| 19878 | add_active_interface_variable(self); |
| 19879 | }); |
| 19880 | } |
| 19881 | |
| 19882 | bool CompilerMSL::using_builtin_array() const |
| 19883 | { |
| 19884 | return msl_options.force_native_arrays || is_using_builtin_array; |
| 19885 | } |
| 19886 | |
| 19887 | void CompilerMSL::set_combined_sampler_suffix(const char *suffix) |
| 19888 | { |
| 19889 | sampler_name_suffix = suffix; |
| 19890 | } |
| 19891 | |
| 19892 | const char *CompilerMSL::get_combined_sampler_suffix() const |
| 19893 | { |
| 19894 | return sampler_name_suffix.c_str(); |
| 19895 | } |
| 19896 | |
| 19897 | bool CompilerMSL::specialization_constant_is_macro(uint32_t const_id) const |
| 19898 | { |
| 19899 | return constant_macro_ids.find(const_id) != constant_macro_ids.end(); |
| 19900 | } |
| 19901 | |
| 19902 | // Start with all fast math flags enabled, and selectively disable based execution modes and float controls |
| 19903 | uint32_t CompilerMSL::get_fp_fast_math_flags(bool incl_ops) |
| 19904 | { |
| 19905 | uint32_t fp_flags = ~0; |
| 19906 | auto &ep = get_entry_point(); |
| 19907 | |
| 19908 | if (ep.flags.get(ExecutionModeSignedZeroInfNanPreserve)) |
| 19909 | fp_flags &= ~(FPFastMathModeNSZMask | FPFastMathModeNotInfMask | FPFastMathModeNotNaNMask); |
| 19910 | |
| 19911 | if (ep.flags.get(ExecutionModeContractionOff)) |
| 19912 | fp_flags &= ~(FPFastMathModeAllowContractMask); |
| 19913 | |
| 19914 | for (auto &fp_pair : ep.fp_fast_math_defaults) |
| 19915 | if (fp_pair.second) |
| 19916 | fp_flags &= get<SPIRConstant>(fp_pair.second).scalar(); |
| 19917 | |
| 19918 | if (incl_ops) |
| 19919 | for (auto &p_m : ir.meta) |
| 19920 | if (p_m.second.decoration.decoration_flags.get(DecorationFPFastMathMode)) |
| 19921 | fp_flags &= p_m.second.decoration.fp_fast_math_mode; |
| 19922 | |
| 19923 | return fp_flags; |
| 19924 | } |
| 19925 | |
| 19926 | void CompilerMSL::emit_block_hints(const SPIRBlock &) |
| 19927 | { |
| 19928 | } |
| 19929 | |
| 19930 | void CompilerMSL::emit_mesh_entry_point() |
| 19931 | { |
| 19932 | auto &ep = get_entry_point(); |
| 19933 | auto &f = get<SPIRFunction>(ir.default_entry_point); |
| 19934 | |
| 19935 | const uint32_t func_id = ir.increase_bound_by(3); |
| 19936 | const uint32_t block_id = func_id + 1; |
| 19937 | const uint32_t ret_id = func_id + 2; |
| 19938 | auto &wrapped_main = set<SPIRFunction>(func_id, f.return_type, f.function_type); |
| 19939 | |
| 19940 | wrapped_main.blocks.push_back(block_id); |
| 19941 | wrapped_main.entry_block = block_id; |
| 19942 | |
| 19943 | auto &wrapped_entry = set<SPIRBlock>(block_id); |
| 19944 | wrapped_entry.terminator = SPIRBlock::Return; |
| 19945 | |
| 19946 | // Push call to original 'main' |
| 19947 | Instruction ix = {}; |
| 19948 | ix.op = OpFunctionCall; |
| 19949 | ix.offset = uint32_t(ir.spirv.size()); |
| 19950 | ix.length = 3; |
| 19951 | |
| 19952 | ir.spirv.push_back(f.return_type); |
| 19953 | ir.spirv.push_back(ret_id); |
| 19954 | ir.spirv.push_back(ep.self); |
| 19955 | |
| 19956 | wrapped_entry.ops.push_back(ix); |
| 19957 | |
| 19958 | // relace entry-point for new one |
| 19959 | SPIREntryPoint proxy_ep = ep; |
| 19960 | proxy_ep.self = func_id; |
| 19961 | ir.entry_points.insert(std::make_pair(func_id, proxy_ep)); |
| 19962 | ir.meta[func_id] = ir.meta[ir.default_entry_point]; |
| 19963 | ir.meta[ir.default_entry_point].decoration.alias.clear(); |
| 19964 | |
| 19965 | ir.default_entry_point = func_id; |
| 19966 | } |
| 19967 | |
| 19968 | void CompilerMSL::emit_mesh_outputs() |
| 19969 | { |
| 19970 | auto &mode = get_entry_point(); |
| 19971 | |
| 19972 | // predefined thread count or zero, if specialization constant is in use |
| 19973 | uint32_t num_invocations = 0; |
| 19974 | if (mode.workgroup_size.id_x == 0 && mode.workgroup_size.id_y == 0 && mode.workgroup_size.id_z == 0) |
| 19975 | num_invocations = mode.workgroup_size.x * mode.workgroup_size.y * mode.workgroup_size.z; |
| 19976 | |
| 19977 | statement("threadgroup_barrier(mem_flags::mem_threadgroup);"); |
| 19978 | statement("if (spvMeshSizes.y == 0)"); |
| 19979 | begin_scope(); |
| 19980 | statement("return;"); |
| 19981 | end_scope(); |
| 19982 | statement("spvMesh.set_primitive_count(spvMeshSizes.y);"); |
| 19983 | |
| 19984 | statement("const uint spvThreadCount [[maybe_unused]] = (gl_WorkGroupSize.x * gl_WorkGroupSize.y * gl_WorkGroupSize.z);"); |
| 19985 | |
| 19986 | if (mesh_out_per_vertex != 0) |
| 19987 | { |
| 19988 | auto &type_vert = get<SPIRType>(mesh_out_per_vertex); |
| 19989 | |
| 19990 | if (num_invocations < mode.output_vertices) |
| 19991 | { |
| 19992 | statement("for (uint spvVI = gl_LocalInvocationIndex; spvVI < spvMeshSizes.x; spvVI += spvThreadCount)"); |
| 19993 | } |
| 19994 | else |
| 19995 | { |
| 19996 | statement("const uint spvVI = gl_LocalInvocationIndex;"); |
| 19997 | statement("if (gl_LocalInvocationIndex < spvMeshSizes.x)"); |
| 19998 | } |
| 19999 | |
| 20000 | begin_scope(); |
| 20001 | |
| 20002 | statement("spvPerVertex spvV = {};"); |
| 20003 | for (uint32_t index = 0; index < uint32_t(type_vert.member_types.size()); ++index) |
| 20004 | { |
| 20005 | uint32_t orig_var = get_extended_member_decoration(type_vert.self, index, SPIRVCrossDecorationInterfaceOrigID); |
| 20006 | uint32_t orig_id = get_extended_member_decoration(type_vert.self, index, SPIRVCrossDecorationInterfaceMemberIndex); |
| 20007 | |
| 20008 | // Clip/cull distances are special-case |
| 20009 | if (orig_var == 0 && orig_id == (~0u)) |
| 20010 | continue; |
| 20011 | |
| 20012 | auto &orig = get<SPIRVariable>(orig_var); |
| 20013 | auto &orig_type = get<SPIRType>(orig.basetype); |
| 20014 | |
| 20015 | // FIXME: Need to deal with complex composite IO types. These may need extra unroll, etc. |
| 20016 | |
| 20017 | BuiltIn builtin = BuiltInMax; |
| 20018 | std::string access; |
| 20019 | if (orig_type.basetype == SPIRType::Struct) |
| 20020 | { |
| 20021 | if (has_member_decoration(orig_type.self, orig_id, DecorationBuiltIn)) |
| 20022 | builtin = BuiltIn(get_member_decoration(orig_type.self, orig_id, DecorationBuiltIn)); |
| 20023 | |
| 20024 | switch (builtin) |
| 20025 | { |
| 20026 | case BuiltInPosition: |
| 20027 | case BuiltInPointSize: |
| 20028 | case BuiltInClipDistance: |
| 20029 | case BuiltInCullDistance: |
| 20030 | access = "." + builtin_to_glsl(builtin, StorageClassOutput); |
| 20031 | break; |
| 20032 | default: |
| 20033 | access = "." + to_member_name(orig_type, orig_id); |
| 20034 | break; |
| 20035 | } |
| 20036 | |
| 20037 | if (has_member_decoration(type_vert.self, index, DecorationIndex)) |
| 20038 | { |
| 20039 | // Declare the Clip/CullDistance as [[user(clip/cullN)]]. |
| 20040 | const uint32_t orig_index = get_member_decoration(type_vert.self, index, DecorationIndex); |
| 20041 | access += "[" + to_string(orig_index) + "]"; |
| 20042 | statement("spvV.", builtin_to_glsl(builtin, StorageClassOutput), "[", orig_index, "] = ", to_name(orig_var), "[spvVI]", access, ";"); |
| 20043 | } |
| 20044 | } |
| 20045 | |
| 20046 | statement("spvV.", to_member_name(type_vert, index), " = ", to_name(orig_var), "[spvVI]", access, ";"); |
| 20047 | if (options.vertex.flip_vert_y && builtin == BuiltInPosition) |
| 20048 | { |
| 20049 | statement("spvV.", to_member_name(type_vert, index), ".y = -(", "spvV.", |
| 20050 | to_member_name(type_vert, index), ".y);", " // Invert Y-axis for Metal"); |
| 20051 | } |
| 20052 | } |
| 20053 | statement("spvMesh.set_vertex(spvVI, spvV);"); |
| 20054 | end_scope(); |
| 20055 | } |
| 20056 | |
| 20057 | if (mesh_out_per_primitive != 0 || builtin_mesh_primitive_indices_id != 0) |
| 20058 | { |
| 20059 | if (num_invocations < mode.output_primitives) |
| 20060 | { |
| 20061 | statement("for (uint spvPI = gl_LocalInvocationIndex; spvPI < spvMeshSizes.y; spvPI += spvThreadCount)"); |
| 20062 | } |
| 20063 | else |
| 20064 | { |
| 20065 | statement("const uint spvPI = gl_LocalInvocationIndex;"); |
| 20066 | statement("if (gl_LocalInvocationIndex < spvMeshSizes.y)"); |
| 20067 | } |
| 20068 | |
| 20069 | // FIXME: Need to deal with complex composite IO types. These may need extra unroll, etc. |
| 20070 | |
| 20071 | begin_scope(); |
| 20072 | |
| 20073 | if (builtin_mesh_primitive_indices_id != 0) |
| 20074 | { |
| 20075 | if (mode.flags.get(ExecutionModeOutputTrianglesEXT)) |
| 20076 | { |
| 20077 | statement("spvMesh.set_index(spvPI * 3u + 0u, gl_PrimitiveTriangleIndicesEXT[spvPI].x);"); |
| 20078 | statement("spvMesh.set_index(spvPI * 3u + 1u, gl_PrimitiveTriangleIndicesEXT[spvPI].y);"); |
| 20079 | statement("spvMesh.set_index(spvPI * 3u + 2u, gl_PrimitiveTriangleIndicesEXT[spvPI].z);"); |
| 20080 | } |
| 20081 | else if (mode.flags.get(ExecutionModeOutputLinesEXT)) |
| 20082 | { |
| 20083 | statement("spvMesh.set_index(spvPI * 2u + 0u, gl_PrimitiveLineIndicesEXT[spvPI].x);"); |
| 20084 | statement("spvMesh.set_index(spvPI * 2u + 1u, gl_PrimitiveLineIndicesEXT[spvPI].y);"); |
| 20085 | } |
| 20086 | else |
| 20087 | { |
| 20088 | statement("spvMesh.set_index(spvPI, gl_PrimitivePointIndicesEXT[spvPI]);"); |
| 20089 | } |
| 20090 | } |
| 20091 | |
| 20092 | if (mesh_out_per_primitive != 0) |
| 20093 | { |
| 20094 | auto &type_prim = get<SPIRType>(mesh_out_per_primitive); |
| 20095 | statement("spvPerPrimitive spvP = {};"); |
| 20096 | for (uint32_t index = 0; index < uint32_t(type_prim.member_types.size()); ++index) |
| 20097 | { |
| 20098 | uint32_t orig_var = |
| 20099 | get_extended_member_decoration(type_prim.self, index, SPIRVCrossDecorationInterfaceOrigID); |
| 20100 | uint32_t orig_id = |
| 20101 | get_extended_member_decoration(type_prim.self, index, SPIRVCrossDecorationInterfaceMemberIndex); |
| 20102 | auto &orig = get<SPIRVariable>(orig_var); |
| 20103 | auto &orig_type = get<SPIRType>(orig.basetype); |
| 20104 | |
| 20105 | BuiltIn builtin = BuiltInMax; |
| 20106 | std::string access; |
| 20107 | if (orig_type.basetype == SPIRType::Struct) |
| 20108 | { |
| 20109 | if (has_member_decoration(orig_type.self, orig_id, DecorationBuiltIn)) |
| 20110 | builtin = BuiltIn(get_member_decoration(orig_type.self, orig_id, DecorationBuiltIn)); |
| 20111 | |
| 20112 | switch (builtin) |
| 20113 | { |
| 20114 | case BuiltInPrimitiveId: |
| 20115 | case BuiltInLayer: |
| 20116 | case BuiltInViewportIndex: |
| 20117 | case BuiltInCullPrimitiveEXT: |
| 20118 | case BuiltInPrimitiveShadingRateKHR: |
| 20119 | access = "." + builtin_to_glsl(builtin, StorageClassOutput); |
| 20120 | break; |
| 20121 | default: |
| 20122 | access = "." + to_member_name(orig_type, orig_id); |
| 20123 | } |
| 20124 | } |
| 20125 | statement("spvP.", to_member_name(type_prim, index), " = ", to_name(orig_var), "[spvPI]", access, ";"); |
| 20126 | } |
| 20127 | statement("spvMesh.set_primitive(spvPI, spvP);"); |
| 20128 | } |
| 20129 | |
| 20130 | end_scope(); |
| 20131 | } |
| 20132 | } |
| 20133 | |
| 20134 | void CompilerMSL::emit_mesh_tasks(SPIRBlock &block) |
| 20135 | { |
| 20136 | // GLSL: Once this instruction is called, the workgroup must be terminated immediately, and the mesh shaders are launched. |
| 20137 | // TODO: find relieble and clean of terminating shader. |
| 20138 | flush_variable_declaration(builtin_task_grid_id); |
| 20139 | statement("spvMgp.set_threadgroups_per_grid(uint3(", to_unpacked_expression(block.mesh.groups[0]), ", ", |
| 20140 | to_unpacked_expression(block.mesh.groups[1]), ", ", to_unpacked_expression(block.mesh.groups[2]), "));"); |
| 20141 | // This is correct if EmitMeshTasks is called in the entry function for shader. |
| 20142 | // Only viable solutions would be: |
| 20143 | // - Caller ensures the SPIR-V is inlined, then this always holds true. |
| 20144 | // - Pass down a "should terminate" bool to leaf functions and chain return (horrible and disgusting, let's not). |
| 20145 | statement("return;"); |
| 20146 | } |
| 20147 | |
| 20148 | void CompilerMSL::emit_workgroup_initialization(const SPIRVariable &var) |
| 20149 | { |
| 20150 | auto &type = get_variable_data_type(var); |
| 20151 | |
| 20152 | begin_scope(); |
| 20153 | |
| 20154 | if (type.array.empty() && type.member_types.empty()) |
| 20155 | { |
| 20156 | // For simple shared variables, we just initialize it in thread 0 of the block |
| 20157 | // We use short to represent bool for threadgroup variable to workaround compiler bug, |
| 20158 | // so we do a temporary fixup here. Alas. (see the type_to_glsl method) |
| 20159 | bool is_boolean = type.basetype == SPIRType::Boolean; |
| 20160 | if (is_boolean) |
| 20161 | type.basetype = SPIRType::Short; |
| 20162 | |
| 20163 | statement("if (gl_LocalInvocationIndex == 0)"); |
| 20164 | begin_scope(); |
| 20165 | statement(to_name(var.self), " = ", to_initializer_expression(var), ";"); |
| 20166 | end_scope(); |
| 20167 | |
| 20168 | if (is_boolean) |
| 20169 | type.basetype = SPIRType::Boolean; |
| 20170 | } |
| 20171 | else |
| 20172 | { |
| 20173 | // Otherwise, we use a loop to cooperatively initialize the memory within the group |
| 20174 | |
| 20175 | // First, we define a few variable names; |
| 20176 | string var_name = to_name(var.self); |
| 20177 | string var_ptr_name = join(var_name, "_ptr"); |
| 20178 | string var_size_name = join(var_name, "_sz"); |
| 20179 | string var_pos_name = join(var_name, "_pos"); |
| 20180 | string var_stride_name = join(var_name, "_stride"); |
| 20181 | string var_ptr2_name = join(var_name, "_ptr2"); |
| 20182 | |
| 20183 | statement("threadgroup uint *", var_ptr_name, " = (threadgroup uint *)&", var_name, ";"); |
| 20184 | statement("uint ", var_size_name, " = ", "sizeof(", var_name, ");"); |
| 20185 | statement("uint ", var_pos_name, " = gl_LocalInvocationIndex;"); |
| 20186 | statement("uint ", var_stride_name, " = gl_WorkGroupSize.x * gl_WorkGroupSize.y * gl_WorkGroupSize.z;"); |
| 20187 | |
| 20188 | statement("while (sizeof(uint) * ", var_pos_name, " < ", var_size_name, ")"); |
| 20189 | begin_scope(); |
| 20190 | statement(var_ptr_name, "[", var_pos_name, "] = 0u;"); |
| 20191 | statement(var_pos_name, " += ", var_stride_name, ";"); |
| 20192 | end_scope(); |
| 20193 | |
| 20194 | statement("if (gl_LocalInvocationIndex == 0)"); |
| 20195 | begin_scope(); |
| 20196 | statement(var_pos_name, " = (", var_size_name, " / sizeof(uint)) * sizeof(uint);"); |
| 20197 | statement("threadgroup uchar *", var_ptr2_name, " = (threadgroup uchar *)&", var_name, ";"); |
| 20198 | |
| 20199 | statement("while (", var_pos_name, " < ", var_size_name, ")"); |
| 20200 | begin_scope(); |
| 20201 | statement(var_ptr2_name, "[", var_pos_name, "] = '\\0';"); |
| 20202 | statement(var_pos_name, "++;"); |
| 20203 | end_scope(); |
| 20204 | end_scope(); |
| 20205 | } |
| 20206 | |
| 20207 | statement("threadgroup_barrier(mem_flags::mem_threadgroup);"); |
| 20208 | |
| 20209 | end_scope(); |
| 20210 | } |
| 20211 | |
| 20212 | string CompilerMSL::additional_fixed_sample_mask_str() const |
| 20213 | { |
| 20214 | char print_buffer[32]; |
| 20215 | #ifdef _MSC_VER |
| 20216 | // snprintf does not exist or is buggy on older MSVC versions, some of |
| 20217 | // them being used by MinGW. Use sprintf instead and disable |
| 20218 | // corresponding warning. |
| 20219 | #pragma warning(push) |
| 20220 | #pragma warning(disable : 4996) |
| 20221 | #endif |
| 20222 | #if _WIN32 |
| 20223 | sprintf(print_buffer, "0x%x", msl_options.additional_fixed_sample_mask); |
| 20224 | #else |
| 20225 | snprintf(print_buffer, sizeof(print_buffer), "0x%x", msl_options.additional_fixed_sample_mask); |
| 20226 | #endif |
| 20227 | #ifdef _MSC_VER |
| 20228 | #pragma warning(pop) |
| 20229 | #endif |
| 20230 | return print_buffer; |
| 20231 | } |