From 8e95e84d0cb9be7af7e13bf8546338db1d8b3d1b Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Thu, 20 Aug 2026 08:31:42 +0300 Subject: [PATCH] Close specialization and descriptor audit gaps Distinguish image descriptors from texel buffers, scope synthesized binding occupancy by descriptor set, and decouple the Metal texture source limit from configurable descriptor ranges. Centralize retry finalization and runtime sampler projection so layout and specialization contracts cannot drift across paths. Refresh consumer documentation and add adversarial descriptor tests. --- docs/ARCHITECTURE.md | 4 +- docs/HOWTO.md | 12 +- docs/REFLECTION.md | 36 +++-- src/emit_sidecar.rs | 6 + src/lib.rs | 191 ++++++++--------------- src/native/psb.rs | 18 +-- src/passes/resources/bindings.rs | 132 ++++++++++++---- src/passes/resources/buffer_addresses.rs | 14 +- src/primary_retry.rs | 120 ++++---------- src/reflect/mod.rs | 31 ++-- src/reflect/tests.rs | 31 +++- src/retry.rs | 25 ++- src/spirv_module.rs | 50 +++++- validation/src/candidate.rs | 18 +-- 14 files changed, 350 insertions(+), 338 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 63e6d5ac6..cfa7678ce 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -62,8 +62,8 @@ module, a read-only analyzer derives conservative buffer byte footprints from th Public `translate_*_reflected` entry points return `(Vec, reflect::ShaderReflection)` with **bytes identical** to the non-reflected call. -Descriptor ABI ranges (buffers `0..32`, sampled textures `32..160`, samplers `160..192`, colors -`192..200`, and storage textures `480..608`, set 0) live in +The default descriptor ABI ranges (buffers `0..32`, sampled textures `32..160`, samplers +`160..192`, colors `192..200`, and storage textures `480..608`, set 0) live in `reflect` and are consumed by the resource pass so decorated bindings and reported reflection share one checked contract. A final module audit rejects descriptor classes outside their bands. Start with the integration [how-to](HOWTO.md); the complete schema and ABI contract is in diff --git a/docs/HOWTO.md b/docs/HOWTO.md index 39d8e79e9..95d5721da 100644 --- a/docs/HOWTO.md +++ b/docs/HOWTO.md @@ -112,10 +112,10 @@ The latter two are single storage-image descriptors in the effective set. For an | `ResourceBinding.kind` | Vulkan descriptor type | |---|---| | `Buffer`, `KernelStageInput`, `AccelerationStructureShadow`, `PrimitiveAccelerationStructure`, `BufferAddressTable` | Storage buffer | -| `Texture`, `EmbeddedArgBufferTexture` | Sampled image | -| `TextureArray` with `access: Sampled` | Sampled-image array | -| `TextureArray` with `access: Storage` | Storage-image array | -| `StorageImage` | Storage image | +| `Texture`, `EmbeddedArgBufferTexture` | Sampled image; a `Texture` whose reflected dimension is `Buffer` uses a uniform texel buffer | +| `TextureArray` with `access: Sampled` | Sampled-image array; reflected dimension `Buffer` uses a uniform texel-buffer array | +| `TextureArray` with `access: Storage` | Storage-image array; reflected dimension `Buffer` uses a storage texel-buffer array | +| `StorageImage` | Storage image; reflected dimension `Buffer` uses a storage texel buffer | | `Sampler`, `StaticSampler` | Sampler | | `ColorInput` | Input attachment | @@ -128,8 +128,8 @@ Static samplers are ordinary Vulkan sampler descriptors whose creation state com `static_sampler`. Dynamically bound samplers whose pipeline state affects shader legality must be translated with `TransformOptions::with_runtime_sampler`; create their descriptors from the matching `runtime_sampler_specializations` entries returned with the executable module. Never substitute the -Vulkan binding (`160 + n`) for the API's Metal sampler index `n`. Embedded argument-buffer textures -use `embedded_source` to identify their owner, field offset, and Metal argument-encoder index. +default Vulkan binding (`160 + n`) for the API's Metal sampler index `n`. Embedded argument-buffer +textures use `embedded_source` to identify their owner, field offset, and Metal argument-encoder index. Embedded buffers use matching entries in `argument_buffer_fields`; write the Vulkan device address into the reflected owner field rather than allocating a separate descriptor. diff --git a/docs/REFLECTION.md b/docs/REFLECTION.md index 04d063208..ca4de34d0 100644 --- a/docs/REFLECTION.md +++ b/docs/REFLECTION.md @@ -95,12 +95,12 @@ By default, every descriptor-backed Metal-facing resource uses **descriptor set | `[[color(n)]]` (framebuffer fetch) | `ColorInput` | `COLOR_INPUT_BINDING_BASE + n` → **`192 + n`** (color band `192`–`199`) | | Implicit imageblock attachment `n`, data rate `r` | `implicit_imageblock_attachments` | `IMAGEBLOCK_BINDING_BASE + 3*n + r` → **`200 + 3*n + r`** | | Custom fragment imageblock master member `n` | `fragment_imageblock.members[n]` | `FRAGMENT_IMAGEBLOCK_BINDING_BASE + n` → **`224 + n`** when projected | -| Acceleration-structure shadow buffer | `AccelerationStructureShadow` | Metal buffer index `n` (set 0) | -| Primitive acceleration structure | `PrimitiveAccelerationStructure` | Metal buffer index `n` (set 0); descriptor only when AIR intersection lowering consumes its geometry shadow | +| Acceleration-structure shadow buffer | `AccelerationStructureShadow` | selected buffer range at Metal index `n` | +| Primitive acceleration structure | `PrimitiveAccelerationStructure` | selected buffer range at Metal index `n`; descriptor only when AIR intersection lowering consumes its geometry shadow | | Authored visible/intersection function table | `VisibleFunctionTable` / `IntersectionFunctionTable` | **no descriptor** (`descriptor: None`); `metal_index` and `param_index` identify static linkage | -| Texture embedded in argument buffer | `EmbeddedArgBufferTexture` | `32 + synthetic_index` | +| Texture embedded in argument buffer | `EmbeddedArgBufferTexture` | selected sampled- or storage-texture range at `synthetic_index` | | Device buffer embedded in argument buffer | `EmbeddedArgBufferBuffer` | **no descriptor**; owner field contains its Vulkan device address | -| Synthesized direct-buffer address table | `BufferAddressTable` | translator-selected binding at or above `SYNTHETIC_BINDING_BASE` (`640`); one `u64` address per Metal buffer slot | +| Synthesized direct-buffer address table | `BufferAddressTable` | first free binding in the selected synthetic range (default starts at `640`); one `u64` address per Metal buffer slot | Constants live in `metal2vulkan::reflect`: @@ -137,10 +137,10 @@ Descriptor types for `bindings`: | Kind | Vulkan descriptor type | |---|---| | `Buffer`, `KernelStageInput`, `AccelerationStructureShadow`, `PrimitiveAccelerationStructure`, `BufferAddressTable` | Storage buffer | -| `Texture` | Sampled image | -| `EmbeddedArgBufferTexture` | Sampled image or storage image according to `access` | -| `TextureArray` | Sampled-image or storage-image array according to `access` | -| `StorageImage` | Storage image | +| `Texture` | Sampled image, or uniform texel buffer when `texture_shape.dimension` is `Buffer` | +| `EmbeddedArgBufferTexture` | Sampled image or storage image according to `access`; a reflected `Buffer` dimension uses the corresponding texel-buffer type | +| `TextureArray` | Sampled-image or storage-image array according to `access`; a reflected `Buffer` dimension uses the corresponding texel-buffer type | +| `StorageImage` | Storage image, or storage texel buffer when `texture_shape.dimension` is `Buffer` | | `Sampler`, `StaticSampler` | Sampler | | `ColorInput` | Input attachment | @@ -326,7 +326,8 @@ let options = TransformOptions::default().with_runtime_sampler( )?; ``` -The index is the Metal `[[sampler(n)]]` index, not the Vulkan descriptor binding (`160 + n`). A +The index is the Metal `[[sampler(n)]]` index, not the Vulkan descriptor binding (by default, +`160 + n`). A successful reflected translation copies every applied state into `runtime_sampler_specializations`; consumers should create the descriptor sampler from that same state. Pixel-coordinate operations are rewritten to texel fetches and shader-side filtering and @@ -359,8 +360,8 @@ let options = TransformOptions::default().with_runtime_storage_image( )?; ``` -For a top-level binding, the index is the Metal `[[texture(n)]]` index, not the Vulkan binding -(`480 + n`). For an `EmbeddedArgBufferTexture`, pass that binding's reflected `metal_index`; this is +For a top-level binding, the index is the Metal `[[texture(n)]]` index, not the default Vulkan +binding (`480 + n`). For an `EmbeddedArgBufferTexture`, pass that binding's reflected `metal_index`; this is a translator-assigned synthetic index, so consumers must not reconstruct it from argument-buffer field positions. Translation selects the compatible explicit SPIR-V image format and independently specializes bindings that previously shared an AIR image type. When the runtime format has no exact @@ -380,14 +381,16 @@ choice. Create the image view and descriptor from the same runtime state used fo 1. Call `translate_reflected` (or a serde-enabled CLI with `--emit-meta`). 2. Cache `(spv_bytes, reflection)` keyed by input hash + `reflection_version` + translator version. 3. Create a Vulkan pipeline with entry point `"main"`. -4. Build the ordinary portion of set 0 from every `bindings` entry with `Some(descriptor)`: +4. Build the ordinary portion of the effective `descriptor_layout.set` from every `bindings` entry + with `Some(descriptor)`: - Map `kind` → descriptor type. - Write `set` / `binding` from `descriptor`. - Use `metal_index` to pick the host resource that was bound as Metal slot `n`. - For buffers, narrow staging from `footprint` only when `has_unbounded_access` is false; bound every strided term from the current draw/dispatch before taking the union. -5. Add one set-0 storage-image descriptor for every `implicit_imageblock_attachments` entry and - every projected `fragment_imageblock` member, using their reported `binding` values. +5. Add one storage-image descriptor in that same effective set for every + `implicit_imageblock_attachments` entry and every projected `fragment_imageblock` member, using + their reported `binding` values. 6. Populate runtime storage images, static samplers, and argument-buffer fields from their reflected state/coordinates; resources with `descriptor: None` require no descriptor write. 7. For `ThreadgroupBuffer` / `imageblock_layouts`, allocate Workgroup / tile storage from @@ -409,8 +412,9 @@ choice. Create the image view and descriptor from the same runtime state used fo | `metal2vulkan::specialize_function_constants` | Specialize FC values on sanitized IR (when needed) | | `metal2vulkan::specialize_function_constant_bytes` | Specialize exact-width scalar/vector FC payloads | -Unit coverage for binding numbers lives in `src/reflect/tests.rs` (ABI contract: set 0, bases -0/32/160/192/200/224/480, with translator-owned descriptors at 640 or above). +Unit coverage for binding numbers lives in `src/reflect/tests.rs` (the default ABI uses set 0, bases +0/32/160/192/200/224/480, and a synthetic range beginning at 640; configurable layouts are covered +separately). ## What reflection is *not* diff --git a/src/emit_sidecar.rs b/src/emit_sidecar.rs index 8ceb1820d..84098f0e3 100644 --- a/src/emit_sidecar.rs +++ b/src/emit_sidecar.rs @@ -61,6 +61,12 @@ pub(crate) enum AirStructLayoutMappingStatus { NonIncreasingOffsets, } +impl AirStructLayoutMappingStatus { + pub(crate) const fn is_mapped(self) -> bool { + matches!(self, Self::MappedNatural | Self::MappedExplicit) + } +} + #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct BufferAddressWord { pub(crate) id: Word, diff --git a/src/lib.rs b/src/lib.rs index 8a18dcb73..87d3c883b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -682,88 +682,63 @@ pub fn translate_native_primary_validated( if let Some(primary) = primary_storage_buffer_raw_feed_if_needed(&validation_error, &retry) { return Ok(primary); } - Ok(primary_primitive_phi_metadata_if_needed( - &validation_error, - san_ll, - stage, - stage_meta.frag.as_ref(), - stage_meta.vert.as_ref(), - stage_meta.kern.as_ref(), - stage_meta.entry_name.as_deref(), - tmp, - passes::TransformOptions::default(), + Ok( + primary_primitive_phi_metadata_if_needed(&validation_error, &retry) + .or_else(|| primary_pointer_typing_raw_if_needed(&validation_error, &retry)) + .or_else(|| { + primary_pointer_typing_wide_raw_guard_chain_if_needed( + &validation_error, + &primary, + &primary_module, + &retry, + ) + }) + .or_else(|| primary_other_prune_if_needed(&validation_error, &primary, tmp)) + .or_else(|| { + primary_wide_raw_store_guard_cfg_chain_if_needed( + &validation_error, + &primary, + &primary_module, + &retry, + ) + }) + .or_else(|| primary_construct_tree_if_needed(&validation_error, &retry)) + // Plain relooper before prune-then-relooper: the latter deliberately declines when the ordinary + // relooper already validates (so the full retry cascade keeps the `val-cfg:relooper` tier label). + // Primary-validated has no later relooper step, so adopt it here for the residual CFG class + // production already ships via relooper (notably banked `09/de938adc`). + .or_else(|| primary_relooper_if_needed(&validation_error, &primary, tmp)) + .or_else(|| primary_cfg_prune_then_relooper_if_needed(&validation_error, &primary, tmp)) + // When the primary bytes are too broken for an in-place relooper rewrite (e.g. undefined-id SSA + // order after an over-admitted structured emit), re-emit through the production raw→relooper→PSB + // composition so primary-validated tracks the shipped cascade for frontier cross-arm residuals. + .or_else(|| { + let original = finished + .original_module + .as_ref() + .map(assemble_finished_module) + .unwrap_or_else(|| primary.clone()); + primary_cfg_raw_then_relooper_if_needed(&validation_error, &original, &retry) + }) + .or_else(|| { + primary_dynamic_struct_index_inline_sroa_relooper_if_needed( + &validation_error, + &retry, + ) + }) + .or_else(|| { + primary_logical_pointer_inline_sroa_raw_if_needed(&validation_error, &retry) + }) + .or_else(|| { + primary_opaque_image_select_module_if_needed( + &validation_error, + &primary_module, + &primary, + tmp, + ) + }) + .unwrap_or(primary), ) - .or_else(|| primary_pointer_typing_raw_if_needed(&validation_error, &retry)) - .or_else(|| { - primary_pointer_typing_wide_raw_guard_chain_if_needed( - &validation_error, - &primary, - &primary_module, - &retry, - ) - }) - .or_else(|| primary_other_prune_if_needed(&validation_error, &primary, tmp)) - .or_else(|| { - primary_wide_raw_store_guard_cfg_chain_if_needed( - &validation_error, - &primary, - &primary_module, - &retry, - ) - }) - .or_else(|| primary_construct_tree_if_needed(&validation_error, &retry)) - // Plain relooper before prune-then-relooper: the latter deliberately declines when the ordinary - // relooper already validates (so the full retry cascade keeps the `val-cfg:relooper` tier label). - // Primary-validated has no later relooper step, so adopt it here for the residual CFG class - // production already ships via relooper (notably banked `09/de938adc`). - .or_else(|| primary_relooper_if_needed(&validation_error, &primary, tmp)) - .or_else(|| primary_cfg_prune_then_relooper_if_needed(&validation_error, &primary, tmp)) - // When the primary bytes are too broken for an in-place relooper rewrite (e.g. undefined-id SSA - // order after an over-admitted structured emit), re-emit through the production raw→relooper→PSB - // composition so primary-validated tracks the shipped cascade for frontier cross-arm residuals. - .or_else(|| { - let original = finished - .original_module - .as_ref() - .map(assemble_finished_module) - .unwrap_or_else(|| primary.clone()); - primary_cfg_raw_then_relooper_if_needed(&validation_error, &original, &retry) - }) - .or_else(|| { - primary_dynamic_struct_index_inline_sroa_relooper_if_needed( - &validation_error, - san_ll, - stage, - stage_meta.frag.as_ref(), - stage_meta.vert.as_ref(), - stage_meta.kern.as_ref(), - stage_meta.entry_name.as_deref(), - tmp, - passes::TransformOptions::default(), - ) - }) - .or_else(|| { - primary_logical_pointer_inline_sroa_raw_if_needed( - &validation_error, - san_ll, - stage, - stage_meta.frag.as_ref(), - stage_meta.vert.as_ref(), - stage_meta.kern.as_ref(), - stage_meta.entry_name.as_deref(), - tmp, - passes::TransformOptions::default(), - ) - }) - .or_else(|| { - primary_opaque_image_select_module_if_needed( - &validation_error, - &primary_module, - &primary, - tmp, - ) - }) - .unwrap_or(primary)) } /// Run the interface+lowering passes on emitted SPIR-V bytes and assemble to a canonical byte @@ -1138,26 +1113,15 @@ fn translate_sanitized_with_meta( } let retry_debug_on = rc.retry_debug_on; let has_device_address_pointer = has_device_address_pointer_load(san_ll); - let translated = match tools::emit_vulkan_spirv_with_sidecar( + let primary_finished = tools::emit_vulkan_spirv_with_sidecar( san_ll, tmp, rc.kern, rc.entry_name, stage_buffer_layouts(rc.stage, rc.frag, rc.vert, rc.kern), ) - .and_then(|b| { - finish_module( - b, - rc.stage, - rc.frag, - rc.vert, - rc.kern, - rc.entry_name, - rc.air_data_layout.as_ref(), - rc.options, - FinishRewrites::Primary, - ) - }) { + .and_then(|emitted| rc.finish_primary_carrier(emitted)); + let translated = match primary_finished { Ok(finished) => { // `finish_module` applies the in-process primary rewrites before assembly. Try the // phi-only PSB candidate only if spirv-val identifies its cross-binding pointer rule. @@ -1214,17 +1178,9 @@ fn translate_sanitized_with_meta( primary_storage_buffer_raw_feed_if_needed(&validation_error, &rc) { Ok(primary) - } else if let Some(primary) = primary_primitive_phi_metadata_if_needed( - &validation_error, - san_ll, - rc.stage, - rc.frag, - rc.vert, - rc.kern, - rc.entry_name, - tmp, - rc.options, - ) { + } else if let Some(primary) = + primary_primitive_phi_metadata_if_needed(&validation_error, &rc) + { Ok(primary) } else if let Some(primary) = primary_pointer_typing_raw_if_needed(&validation_error, &rc) @@ -1263,28 +1219,13 @@ fn translate_sanitized_with_meta( } else if let Some(primary) = primary_dynamic_struct_index_inline_sroa_relooper_if_needed( &validation_error, - san_ll, - rc.stage, - rc.frag, - rc.vert, - rc.kern, - rc.entry_name, - tmp, - rc.options, + &rc, ) { Ok(primary) - } else if let Some(primary) = primary_logical_pointer_inline_sroa_raw_if_needed( - &validation_error, - san_ll, - rc.stage, - rc.frag, - rc.vert, - rc.kern, - rc.entry_name, - tmp, - rc.options, - ) { + } else if let Some(primary) = + primary_logical_pointer_inline_sroa_raw_if_needed(&validation_error, &rc) + { Ok(primary) } else if let Some(primary) = primary_opaque_image_select_module_if_needed( &validation_error, diff --git a/src/native/psb.rs b/src/native/psb.rs index 0b0623735..b9ca36cbb 100644 --- a/src/native/psb.rs +++ b/src/native/psb.rs @@ -13,7 +13,7 @@ //! ext `SPV_KHR_physical_storage_buffer`; //! - each leaf access chain (zero-offset into a buffer variable) → `OpConvertUToPtr` of the buffer's //! 64-bit device address, loaded from a synthesized address-table descriptor (`{ runtimearray u64 }` -//! in the translator-owned binding range in set 0) indexed by the buffer's OWN descriptor Binding — so the executor +//! in the selected translator-owned binding range and descriptor set) indexed by the buffer's OWN descriptor Binding — so the executor //! fills `table[binding] = vkGetBufferDeviceAddress(buffer_at_binding)` directly from the bound //! resources, no side-channel slot→binding map needed (the consumer's //! `buffer_device_address` ABI fills the same table); @@ -900,21 +900,7 @@ fn rewrite_cross_binding_pointer_merges_inner( vec![Operand::StorageClass(StorageClass::StorageBuffer)], )); // Allocate the translator-owned address table within the selected synthetic band. - let occupied = module - .annotations - .iter() - .filter(|i| { - i.class.opcode == Op::Decorate - && matches!( - i.operands.get(1), - Some(Operand::Decoration(Decoration::Binding)) - ) - }) - .filter_map(|i| match i.operands.get(2) { - Some(Operand::LiteralBit32(b)) => Some(*b), - _ => None, - }) - .collect::>(); + let occupied = crate::spirv_module::descriptor_bindings_in_set(module, layout.set); let Some(address_table_binding) = (layout.synthetic.start..layout.synthetic.end).find(|binding| !occupied.contains(binding)) else { diff --git a/src/passes/resources/bindings.rs b/src/passes/resources/bindings.rs index 54e2b4663..aa450f1dd 100644 --- a/src/passes/resources/bindings.rs +++ b/src/passes/resources/bindings.rs @@ -52,18 +52,7 @@ pub(in crate::passes) fn allocate_static_sampler_binding( module: &Module, layout: DescriptorLayout, ) -> Option { - let occupied = module - .annotations - .iter() - .filter(|instruction| { - instruction.class.opcode == Op::Decorate - && instruction.operands.get(1) == Some(&Operand::Decoration(Decoration::Binding)) - }) - .filter_map(|instruction| match instruction.operands.get(2) { - Some(Operand::LiteralBit32(binding)) => Some(*binding), - _ => None, - }) - .collect::>(); + let occupied = crate::spirv_module::descriptor_bindings_in_set(module, layout.set); (layout.samplers.start..layout.samplers.end).find(|binding| !occupied.contains(binding)) } @@ -73,18 +62,7 @@ pub(in crate::passes) fn allocate_default_texture_binding( module: &Module, layout: DescriptorLayout, ) -> Option { - let occupied = module - .annotations - .iter() - .filter(|instruction| { - instruction.class.opcode == Op::Decorate - && instruction.operands.get(1) == Some(&Operand::Decoration(Decoration::Binding)) - }) - .filter_map(|instruction| match instruction.operands.get(2) { - Some(Operand::LiteralBit32(binding)) => Some(*binding), - _ => None, - }) - .collect::>(); + let occupied = crate::spirv_module::descriptor_bindings_in_set(module, layout.set); (layout.sampled_textures.start..layout.sampled_textures.end) .find(|binding| !occupied.contains(binding)) } @@ -140,8 +118,10 @@ enum DescriptorClass { UniformBuffer, Sampler, SampledImage, + UniformTexelBuffer, CombinedImageSampler, StorageImage, + StorageTexelBuffer, InputAttachment, AccelerationStructure, } @@ -245,9 +225,15 @@ pub(in crate::passes) fn validate_descriptor_binding_classes( Op::TypeSampler => Some(DescriptorClass::Sampler), Op::TypeSampledImage => Some(DescriptorClass::CombinedImageSampler), Op::TypeImage => { - if definition.operands.get(1) == Some(&Operand::Dim(spirv::Dim::DimSubpassData)) { + let dimension = definition.operands.get(1); + let storage = definition.operands.get(5) == Some(&Operand::LiteralBit32(2)); + if dimension == Some(&Operand::Dim(spirv::Dim::DimSubpassData)) { Some(DescriptorClass::InputAttachment) - } else if definition.operands.get(5) == Some(&Operand::LiteralBit32(2)) { + } else if dimension == Some(&Operand::Dim(spirv::Dim::DimBuffer)) && storage { + Some(DescriptorClass::StorageTexelBuffer) + } else if dimension == Some(&Operand::Dim(spirv::Dim::DimBuffer)) { + Some(DescriptorClass::UniformTexelBuffer) + } else if storage { Some(DescriptorClass::StorageImage) } else { Some(DescriptorClass::SampledImage) @@ -294,10 +280,10 @@ pub(in crate::passes) fn validate_descriptor_binding_classes( layout.buffers.contains(binding) || layout.synthetic.contains(binding) } DescriptorClass::Sampler => layout.samplers.contains(binding), - DescriptorClass::SampledImage | DescriptorClass::CombinedImageSampler => { - layout.sampled_textures.contains(binding) - } - DescriptorClass::StorageImage => { + DescriptorClass::SampledImage + | DescriptorClass::UniformTexelBuffer + | DescriptorClass::CombinedImageSampler => layout.sampled_textures.contains(binding), + DescriptorClass::StorageImage | DescriptorClass::StorageTexelBuffer => { layout.storage_textures.contains(binding) || layout.imageblocks.contains(binding) || layout.fragment_imageblocks.contains(binding) @@ -326,6 +312,44 @@ pub(in crate::passes) fn validate_descriptor_binding_classes( mod tests { use super::*; + fn image_variable(module: &mut Module, id: Word, dimension: spirv::Dim, storage: bool) { + let scalar = id + 100; + let image = id + 200; + let pointer = id + 300; + module.types_global_values.push(type_inst( + Op::TypeFloat, + scalar, + vec![Operand::LiteralBit32(32)], + )); + module.types_global_values.push(type_inst( + Op::TypeImage, + image, + vec![ + Operand::IdRef(scalar), + Operand::Dim(dimension), + Operand::LiteralBit32(0), + Operand::LiteralBit32(0), + Operand::LiteralBit32(0), + Operand::LiteralBit32(if storage { 2 } else { 1 }), + Operand::ImageFormat(spirv::ImageFormat::Unknown), + ], + )); + module.types_global_values.push(type_inst( + Op::TypePointer, + pointer, + vec![ + Operand::StorageClass(StorageClass::UniformConstant), + Operand::IdRef(image), + ], + )); + module.types_global_values.push(Instruction::new( + Op::Variable, + Some(pointer), + Some(id), + vec![Operand::StorageClass(StorageClass::UniformConstant)], + )); + } + #[test] fn static_sampler_allocator_is_bounded_by_its_descriptor_band() { let mut module = Module::new(); @@ -365,4 +389,52 @@ mod tests { } assert_eq!(allocate_default_texture_binding(&module, layout), None); } + + #[test] + fn synthesized_allocators_scope_occupied_bindings_by_descriptor_set() { + let mut module = Module::new(); + let layout = DescriptorLayout { + set: 3, + ..DescriptorLayout::default() + }; + decorate_binding(&mut module, 1, 0, layout.samplers.start); + decorate_binding(&mut module, 2, layout.set, layout.samplers.start + 1); + decorate_binding(&mut module, 3, 0, layout.sampled_textures.start); + decorate_binding( + &mut module, + 4, + layout.set, + layout.sampled_textures.start + 1, + ); + + assert_eq!( + allocate_static_sampler_binding(&module, layout), + Some(layout.samplers.start) + ); + assert_eq!( + allocate_default_texture_binding(&module, layout), + Some(layout.sampled_textures.start) + ); + } + + #[test] + fn descriptor_collision_oracle_distinguishes_images_from_texel_buffers() { + for storage in [false, true] { + let mut module = Module::new(); + image_variable(&mut module, 1, spirv::Dim::Dim2D, storage); + image_variable(&mut module, 2, spirv::Dim::DimBuffer, storage); + let layout = DescriptorLayout::default(); + let binding = if storage { + layout.storage_textures.start + } else { + layout.sampled_textures.start + }; + decorate_binding(&mut module, 1, layout.set, binding); + decorate_binding(&mut module, 2, layout.set, binding); + + let error = validate_descriptor_binding_classes(&module, layout) + .expect_err("image and texel-buffer descriptors cannot alias"); + assert!(error.contains("is shared by"), "{error}"); + } + } } diff --git a/src/passes/resources/buffer_addresses.rs b/src/passes/resources/buffer_addresses.rs index 047fc67c0..ddaeaba95 100644 --- a/src/passes/resources/buffer_addresses.rs +++ b/src/passes/resources/buffer_addresses.rs @@ -86,19 +86,7 @@ pub(in crate::passes) fn lower_buffer_address_facts( vec![Operand::StorageClass(StorageClass::StorageBuffer)], )); let layout = ctx.descriptor_layout; - let occupied = ctx - .module - .annotations - .iter() - .filter(|inst| { - inst.class.opcode == Op::Decorate - && inst.operands.get(1) == Some(&Operand::Decoration(Decoration::Binding)) - }) - .filter_map(|inst| match inst.operands.get(2) { - Some(Operand::LiteralBit32(binding)) => Some(*binding), - _ => None, - }) - .collect::>(); + let occupied = crate::spirv_module::descriptor_bindings_in_set(&ctx.module, layout.set); let binding = (layout.synthetic.start..layout.synthetic.end) .find(|binding| !occupied.contains(binding)) .ok_or_else(|| "descriptor binding space exhausted for buffer-address table".to_string())?; diff --git a/src/primary_retry.rs b/src/primary_retry.rs index 633e605a4..3a4392fdd 100644 --- a/src/primary_retry.rs +++ b/src/primary_retry.rs @@ -168,52 +168,32 @@ pub(crate) fn primary_xbind_phi_psb_for_validation_error( /// parser mode requires an exact primitive metadata type, a matching post-phi GEP source type, and /// the declared byte extent; the re-emission is still adopted only when it validates (or its /// cross-binding pointer phi validates after the physical address lowering). -#[allow(clippy::too_many_arguments)] pub(crate) fn primary_primitive_phi_metadata_if_needed( validation_error: &str, - san_ll: &str, - stage: passes::Stage, - frag: Option<&meta::FragMeta>, - vert: Option<&meta::VertMeta>, - kern: Option<&meta::KernMeta>, - entry_name: Option<&str>, - tmp: &Path, - options: passes::TransformOptions, + retry: &retry::RetryCtx<'_>, ) -> Option> { if native::classify_validation_error(validation_error) != native::ValidationClass::PointerTyping { return None; } let emitted = native::emit_vulkan_spirv_with_primitive_phi_metadata_sidecar( - san_ll, - kern, - entry_name, - stage_buffer_layouts(stage, frag, vert, kern), + retry.san_ll, + retry.kern, + retry.entry_name, + stage_buffer_layouts(retry.stage, retry.frag, retry.vert, retry.kern), ) .ok()?; - let air_data_layout = crate::layout::AirDataLayout::from_ir(san_ll).ok().flatten(); - let finished = finish_module( - emitted, - stage, - frag, - vert, - kern, - entry_name, - air_data_layout.as_ref(), - options, - FinishRewrites::Primary, - ) - .ok()?; - let primary_module = finished.module; - let primary = finished.bytes; - match tools::spirv_val_bytes(&primary, tmp) { + let primary = retry.finish_primary_carrier(emitted).ok()?; + let primary_module = primary.module; + let primary = primary.bytes; + match tools::spirv_val_bytes(&primary, retry.tmp) { Ok(()) => Some(primary), Err(error) => primary_xbind_phi_psb_for_validation_error( &primary_module, &primary, &error, - tmp, - options.descriptor_layout, + retry.tmp, + retry.options.descriptor_layout, ), } } @@ -445,17 +425,9 @@ pub(crate) fn primary_construct_tree_if_needed( /// existing inline pass removes the caller-owned local byte view, and the existing relooper /// restructures the resulting otherwise-valid CFG. Any other first or second validation class /// declines. -#[allow(clippy::too_many_arguments)] pub(crate) fn primary_dynamic_struct_index_inline_sroa_relooper_if_needed( validation_error: &str, - san_ll: &str, - stage: passes::Stage, - frag: Option<&meta::FragMeta>, - vert: Option<&meta::VertMeta>, - kern: Option<&meta::KernMeta>, - entry_name: Option<&str>, - tmp: &Path, - options: passes::TransformOptions, + retry: &retry::RetryCtx<'_>, ) -> Option> { if native::classify_validation_error(validation_error) != native::ValidationClass::Other || !native::is_dynamic_struct_index_error(validation_error) @@ -463,29 +435,15 @@ pub(crate) fn primary_dynamic_struct_index_inline_sroa_relooper_if_needed( return None; } let inlined = tools::emit_vulkan_spirv_inline_sroa_with_sidecar( - san_ll, - tmp, - kern, - entry_name, - stage_buffer_layouts(stage, frag, vert, kern), + retry.san_ll, + retry.tmp, + retry.kern, + retry.entry_name, + stage_buffer_layouts(retry.stage, retry.frag, retry.vert, retry.kern), ) - .and_then(|spv| { - let air_data_layout = crate::layout::AirDataLayout::from_ir(san_ll)?; - finish_module( - spv, - stage, - frag, - vert, - kern, - entry_name, - air_data_layout.as_ref(), - options, - FinishRewrites::Plain, - ) - }) - .map(|finished| finished.bytes) + .and_then(|spv| retry.finish(spv)) .ok()?; - match tools::spirv_val_bytes(&inlined, tmp) { + match tools::spirv_val_bytes(&inlined, retry.tmp) { Ok(()) => return Some(inlined), Err(inline_error) if native::classify_validation_error(&inline_error) @@ -493,7 +451,7 @@ pub(crate) fn primary_dynamic_struct_index_inline_sroa_relooper_if_needed( Err(_) => return None, } let primary = relooper_candidate(&inlined)?; - tools::spirv_val_bytes(&primary, tmp) + tools::spirv_val_bytes(&primary, retry.tmp) .is_ok() .then_some(primary) } @@ -502,17 +460,9 @@ pub(crate) fn primary_dynamic_struct_index_inline_sroa_relooper_if_needed( /// illegal Logical pointer operand. Inlining exposes the float-CAS helper's pointer at the caller and /// raw addressing represents its `float`/`i32` reinterpret without `OpBitcast`; the candidate is /// adopted only after its own validation. The no-retry byte baseline remains on the original emission. -#[allow(clippy::too_many_arguments)] pub(crate) fn primary_logical_pointer_inline_sroa_raw_if_needed( validation_error: &str, - san_ll: &str, - stage: passes::Stage, - frag: Option<&meta::FragMeta>, - vert: Option<&meta::VertMeta>, - kern: Option<&meta::KernMeta>, - entry_name: Option<&str>, - tmp: &Path, - options: passes::TransformOptions, + retry: &retry::RetryCtx<'_>, ) -> Option> { if native::classify_validation_error(validation_error) != native::ValidationClass::Other || !native::is_logical_pointer_operand_error(validation_error) @@ -520,29 +470,15 @@ pub(crate) fn primary_logical_pointer_inline_sroa_raw_if_needed( return None; } let primary = tools::emit_vulkan_spirv_inline_sroa_raw_with_sidecar( - san_ll, - tmp, - kern, - entry_name, - stage_buffer_layouts(stage, frag, vert, kern), + retry.san_ll, + retry.tmp, + retry.kern, + retry.entry_name, + stage_buffer_layouts(retry.stage, retry.frag, retry.vert, retry.kern), ) - .and_then(|spv| { - let air_data_layout = crate::layout::AirDataLayout::from_ir(san_ll)?; - finish_module( - spv, - stage, - frag, - vert, - kern, - entry_name, - air_data_layout.as_ref(), - options, - FinishRewrites::Plain, - ) - }) - .map(|finished| finished.bytes) + .and_then(|spv| retry.finish(spv)) .ok()?; - tools::spirv_val_bytes(&primary, tmp) + tools::spirv_val_bytes(&primary, retry.tmp) .is_ok() .then_some(primary) } diff --git a/src/reflect/mod.rs b/src/reflect/mod.rs index 758ef86bb..0d03290ce 100644 --- a/src/reflect/mod.rs +++ b/src/reflect/mod.rs @@ -119,9 +119,13 @@ pub const BUFFER_BINDING_RANGE: DescriptorBindingRange = DescriptorBindingRange { start: 0, end: 32 }; /// Descriptor binding base for `[[texture(n)]]` resources: binding = `TEXTURE_BINDING_BASE + n`. pub const TEXTURE_BINDING_BASE: u32 = 32; +/// Number of texture argument-table entries exposed by the Metal ABI. This source limit is +/// independent of the selected descriptor layout's capacity. +pub const TEXTURE_ARGUMENT_COUNT: u32 = 128; +pub const TEXTURE_ARGUMENT_COUNT_USIZE: usize = TEXTURE_ARGUMENT_COUNT as usize; pub const TEXTURE_BINDING_RANGE: DescriptorBindingRange = DescriptorBindingRange { start: TEXTURE_BINDING_BASE, - end: 160, + end: TEXTURE_BINDING_BASE + TEXTURE_ARGUMENT_COUNT, }; /// Descriptor binding base for `[[sampler(n)]]` resources: binding = `SAMPLER_BINDING_BASE + n`. pub const SAMPLER_BINDING_BASE: u32 = TEXTURE_BINDING_RANGE.end; @@ -162,13 +166,10 @@ pub const FRAGMENT_IMAGEBLOCK_BINDING_RANGE: DescriptorBindingRange = Descriptor pub const STORAGE_TEXTURE_BINDING_BASE: u32 = FRAGMENT_IMAGEBLOCK_BINDING_RANGE.end; pub const STORAGE_TEXTURE_BINDING_RANGE: DescriptorBindingRange = DescriptorBindingRange { start: STORAGE_TEXTURE_BINDING_BASE, - end: 608, + end: STORAGE_TEXTURE_BINDING_BASE + TEXTURE_ARGUMENT_COUNT, }; -/// Number of Metal texture argument-table entries that can be specialized independently. -pub const TEXTURE_ARGUMENT_COUNT_USIZE: usize = - (TEXTURE_BINDING_RANGE.end - TEXTURE_BINDING_RANGE.start) as usize; -/// Translator-owned descriptors (currently direct-buffer address tables) are allocated at or above -/// this base, after every fixed Metal-facing band. +/// Start of the default translator-owned descriptor range (currently direct-buffer address tables), +/// after every fixed Metal-facing band. pub const SYNTHETIC_BINDING_BASE: u32 = 640; /// Complete descriptor layout selected for one independently translated stage. @@ -769,7 +770,10 @@ impl RuntimeSamplerState { Ok(()) } - pub(crate) fn lowering_state(self) -> StaticSamplerState { + /// Project pipeline-provided state into the sampler-lowering representation shared by the + /// translator and consumers that create the matching Vulkan sampler. `raw_words` is zeroed + /// because runtime state has no AIR constexpr encoding. + pub fn lowering_state(self) -> StaticSamplerState { StaticSamplerState { min_filter: self.min_filter, mag_filter: self.mag_filter, @@ -1428,7 +1432,9 @@ impl ShaderReflection { enum DescriptorClass { StorageBuffer, SampledImage, + UniformTexelBuffer, StorageImage, + StorageTexelBuffer, Sampler, InputAttachment, } @@ -1468,6 +1474,9 @@ impl ShaderReflection { resource.kind, ResourceKind::TextureArray | ResourceKind::EmbeddedArgBufferTexture ) && resource.access == Some(ResourceAccess::Storage); + let texel_buffer = resource + .texture_shape + .is_some_and(|shape| shape.dimension == TextureDimension::Buffer); let class = match resource.kind { ResourceKind::Buffer | ResourceKind::KernelStageInput @@ -1478,8 +1487,12 @@ impl ShaderReflection { | ResourceKind::TextureArray | ResourceKind::StorageImage | ResourceKind::EmbeddedArgBufferTexture => { - if storage_texture { + if storage_texture && texel_buffer { + DescriptorClass::StorageTexelBuffer + } else if storage_texture { DescriptorClass::StorageImage + } else if texel_buffer { + DescriptorClass::UniformTexelBuffer } else { DescriptorClass::SampledImage } diff --git a/src/reflect/tests.rs b/src/reflect/tests.rs index 9a5616a3f..8721fcc4d 100644 --- a/src/reflect/tests.rs +++ b/src/reflect/tests.rs @@ -2,7 +2,7 @@ //! [`ShaderReflection`], and assert the exported binding numbers match the ABI convention the //! interface pass decorates (buffers = index, sampled textures = 32+n, samplers = 160+n, colors = //! 192+n, implicit imageblock attachment planes = 200+3*attachment+data-rate, storage textures = -//! 480+n, all in descriptor set 0). +//! 480+n, all in descriptor set 0 under the default layout). use super::*; use crate::meta::{ @@ -64,7 +64,7 @@ fn fragment_reflection_matches_abi_convention() { // fixture) instead of being dropped, so a consumer never re-parses the AIR arg metadata. assert_eq!(buf.declared_size, Some(32)); - // Sampler(2) -> set 0, binding 66. + // Sampler(2) -> set 0, binding 162. let smp = r.binding_at(ResourceKind::Sampler, 2).expect("sampler 2"); assert_eq!( smp.descriptor, @@ -1505,6 +1505,12 @@ fn abi_base_constants_are_the_contract() { assert_eq!(FRAGMENT_IMAGEBLOCK_BINDING_BASE, 224); assert_eq!(STORAGE_TEXTURE_BINDING_BASE, 480); assert_eq!(SYNTHETIC_BINDING_BASE, 640); + assert_eq!(TEXTURE_ARGUMENT_COUNT, 128); + assert_eq!(TEXTURE_BINDING_RANGE.len(), Some(TEXTURE_ARGUMENT_COUNT)); + assert_eq!( + STORAGE_TEXTURE_BINDING_RANGE.len(), + Some(TEXTURE_ARGUMENT_COUNT) + ); assert_eq!(buffer_resource_binding(31), Some(31)); assert_eq!(buffer_resource_binding(32), None); @@ -1569,6 +1575,27 @@ fn descriptor_layout_rejects_overlap_reversal_version_and_overflow_with_typed_er ); } +#[test] +fn descriptor_abi_distinguishes_images_from_texel_buffers() { + for (ordinary, texel) in [ + ("texture2d", "texture_buffer"), + ("texture2d", "texture_buffer"), + ] { + let mut meta = KernMeta { + roles: vec![(0, KernRole::Texture(0)), (1, KernRole::Texture(0))], + ..Default::default() + }; + meta.texture_type_names.insert(0, ordinary.to_string()); + meta.texture_type_names.insert(1, texel.to_string()); + let reflection = ShaderReflection::from_kernel(&meta, Some("k"), [1, 1, 1]); + + let error = reflection + .validate_descriptor_abi() + .expect_err("image and texel-buffer descriptors cannot alias"); + assert!(error.contains("shared incompatibly"), "{error}"); + } +} + #[test] fn function_tables_are_reflected_as_descriptor_free_link_resources() { let meta = KernMeta { diff --git a/src/retry.rs b/src/retry.rs index 8219d89bb..850a0f3b8 100644 --- a/src/retry.rs +++ b/src/retry.rs @@ -318,6 +318,14 @@ impl<'a> RetryCtx<'a> { fn finish_carrier( &self, emitted: crate::emit_sidecar::EmittedSpirv, + ) -> Result { + self.finish_carrier_with_rewrites(emitted, FinishRewrites::Plain) + } + + fn finish_carrier_with_rewrites( + &self, + emitted: crate::emit_sidecar::EmittedSpirv, + rewrites: FinishRewrites, ) -> Result { finish_module( emitted, @@ -328,10 +336,17 @@ impl<'a> RetryCtx<'a> { self.entry_name, self.air_data_layout.as_ref(), self.options, - FinishRewrites::Plain, + rewrites, ) } + pub(crate) fn finish_primary_carrier( + &self, + emitted: crate::emit_sidecar::EmittedSpirv, + ) -> Result { + self.finish_carrier_with_rewrites(emitted, FinishRewrites::Primary) + } + /// True iff `bytes` independently passes spirv-val — the adopt-if-VALIDATES gate every tier uses. fn validates(&self, bytes: &[u8]) -> bool { tools::spirv_val_bytes(bytes, self.tmp).is_ok() @@ -1051,13 +1066,7 @@ impl<'a> RetryCtx<'a> { let mapped_layouts = sidecar .air_struct_layout_mappings .iter() - .filter(|mapping| { - matches!( - mapping.status, - crate::emit_sidecar::AirStructLayoutMappingStatus::MappedNatural - | crate::emit_sidecar::AirStructLayoutMappingStatus::MappedExplicit - ) - }) + .filter(|mapping| mapping.status.is_mapped()) .count(); let unmapped_layouts = sidecar.air_struct_layout_mappings.len() - mapped_layouts; eprintln!( diff --git a/src/spirv_module.rs b/src/spirv_module.rs index 1fd18c775..34f0fb4b1 100644 --- a/src/spirv_module.rs +++ b/src/spirv_module.rs @@ -5,12 +5,58 @@ //! tests. use crate::spirv_binary::{self, Error as ParseError}; -use spirv::{Op, Word}; -use std::collections::HashMap; +use spirv::{Decoration, Op, Word}; +use std::collections::{HashMap, HashSet}; pub(crate) use crate::spirv_operand::Operand; use crate::spirv_operand::{Assemble, Disassemble}; +/// Descriptor binding numbers occupied in one descriptor set. +/// +/// Binding numbers are scoped by descriptor set. Synthesized-resource allocators must therefore +/// pair the two decorations by target id instead of treating every `Binding` decoration in the +/// module as global occupancy. +pub(crate) fn descriptor_bindings_in_set(module: &Module, set: u32) -> HashSet { + let targets = module + .annotations + .iter() + .filter_map(|instruction| { + if instruction.class.opcode != Op::Decorate + || instruction.operands.get(1) + != Some(&Operand::Decoration(Decoration::DescriptorSet)) + || instruction.operands.get(2) != Some(&Operand::LiteralBit32(set)) + { + return None; + } + match instruction.operands.first() { + Some(Operand::IdRef(target)) => Some(*target), + _ => None, + } + }) + .collect::>(); + module + .annotations + .iter() + .filter_map(|instruction| { + if instruction.class.opcode != Op::Decorate + || instruction.operands.get(1) != Some(&Operand::Decoration(Decoration::Binding)) + { + return None; + } + let Some(Operand::IdRef(target)) = instruction.operands.first() else { + return None; + }; + if !targets.contains(target) { + return None; + } + match instruction.operands.get(2) { + Some(Operand::LiteralBit32(binding)) => Some(*binding), + _ => None, + } + }) + .collect() +} + fn is_location_debug(opcode: Op) -> bool { matches!(opcode, Op::Line | Op::NoLine) } diff --git a/validation/src/candidate.rs b/validation/src/candidate.rs index c298ed7d9..15671aecc 100644 --- a/validation/src/candidate.rs +++ b/validation/src/candidate.rs @@ -4628,23 +4628,7 @@ mod platform { max_sampler_anisotropy: f32, ) -> Result, String> { sampler_info_from_static( - &metal2vulkan::reflect::StaticSamplerState { - min_filter: state.min_filter, - mag_filter: state.mag_filter, - mip_filter: state.mip_filter, - address_mode_s: state.address_mode_s, - address_mode_t: state.address_mode_t, - address_mode_r: state.address_mode_r, - coordinates: state.coordinates, - compare_function: state.compare_function, - max_anisotropy: state.max_anisotropy, - lod_min_clamp: state.lod_min_clamp, - lod_max_clamp: state.lod_max_clamp, - border_color: state.border_color, - reduction: state.reduction, - lod_bias: state.lod_bias, - raw_words: [0; 2], - }, + &state.lowering_state(), sampler_anisotropy, max_sampler_anisotropy, )