diff --git a/docs/HOWTO.md b/docs/HOWTO.md index b27316356..2e7e998fd 100644 --- a/docs/HOWTO.md +++ b/docs/HOWTO.md @@ -132,6 +132,13 @@ use `embedded_source` to identify their owner, field offset, and Metal argument- 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. +Writable runtime textures must likewise be translated with +`TransformOptions::with_runtime_storage_image`, keyed by Metal texture index. Pass the bound format +and the device's per-format storage/atomic support plus enabled read/write-without-format features. +Use the returned `runtime_storage_image_specializations` entry to create the matching image view. +The reflected `spirv_format` and `texture_shape.storage_format` are `None` only when translation +proved that the shader's exact operations are covered by the supplied formatless features. + ## 5. Stage only the buffer bytes the shader can reach Successful reflected translation attaches `footprint` to descriptor-backed `Buffer`, diff --git a/docs/REFLECTION.md b/docs/REFLECTION.md index a4653bfe2..ca6d4fda1 100644 --- a/docs/REFLECTION.md +++ b/docs/REFLECTION.md @@ -69,7 +69,7 @@ metal2vulkan = { version = "0.1", features = ["serde"] } ``` `ShaderReflection` and its nested types derive `Serialize`/`Deserialize` under that feature. The -current `REFLECTION_VERSION` is `23`. Serialized Rust enums use serde's externally tagged default: +current `REFLECTION_VERSION` is `24`. Serialized Rust enums use serde's externally tagged default: unit variants are strings (for example `"Unbounded"`), while data variants are objects (for example `{ "Object": { "bytes": 288 } }`). Optional fields serialize as `null`. @@ -324,6 +324,45 @@ addressing where the translator has an exact model. State or operation combinati unknown derivative, mip, comparison, anisotropy, or dimensional behavior fail translation rather than emitting an invalid unnormalized-sampler instruction. +### Runtime storage-image specialization + +AIR fixes a storage texture's texel component class, but the pipeline chooses the concrete format +bound at runtime. Supply that format and the target device's format features before translation: + +```rust +use metal2vulkan::passes::TransformOptions; +use metal2vulkan::reflect::{ + RuntimeStorageImageCapabilities, RuntimeStorageImageFormat, RuntimeStorageImageState, +}; + +let options = TransformOptions::default().with_runtime_storage_image( + 0, + RuntimeStorageImageState { + format: RuntimeStorageImageFormat::Rgba8Unorm, + capabilities: RuntimeStorageImageCapabilities { + storage_image: true, + storage_image_atomic: false, + read_without_format: false, + write_without_format: false, + }, + }, +)?; +``` + +The index is the Metal `[[texture(n)]]` index, not the Vulkan binding (`480 + n`). 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 SPIR-V token, translation +uses `Unknown` only if the supplied device features cover every operation the final shader +performs; it declares only the required read-without-format and/or write-without-format +capabilities. Atomics require a scalar 32-bit integer format and storage-image atomic support. +Component-class mismatches, absent bindings, missing format features, and unsupported atomic +formats fail visibly. + +Successful reflected translation records the applied states in +`runtime_storage_image_specializations`. Its `spirv_format` is `Some` for an explicit format and +`None` for `Unknown`; the corresponding binding's `texture_shape.storage_format` reports the same +choice. Create the image view and descriptor from the same runtime state used for translation. + ## Typical consumer flow 1. Call `translate_reflected` (or a serde-enabled CLI with `--emit-meta`). @@ -337,8 +376,8 @@ than emitting an invalid unnormalized-sampler instruction. 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. -6. Populate static samplers and argument-buffer fields from their reflected state/coordinates; - resources with `descriptor: None` require no descriptor write. +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 `declared_size` / `type_layout` (no descriptor write). 8. For vertex: bind attributes from `vertex_attributes` and respect `vertex_builtins`. diff --git a/src/lib.rs b/src/lib.rs index eefef63c8..9075dafb1 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -126,6 +126,7 @@ fn options_for_air( mut options: passes::TransformOptions, ) -> Result { options.validate_runtime_samplers()?; + options.validate_runtime_storage_images()?; if san_ll.contains("air.compile.denorms_disable") { options.denorm_flush_to_zero_f32 = true; } @@ -244,9 +245,62 @@ fn build_reflection( }) }) .collect(); + for (metal_index, state) in options + .runtime_storage_image_states + .iter() + .copied() + .enumerate() + .filter_map(|(metal_index, state)| Some((u32::try_from(metal_index).ok()?, state?))) + { + let binding = reflection.bindings.iter_mut().find(|binding| { + binding.metal_index == metal_index + && (binding.kind == reflect::ResourceKind::StorageImage + || binding.kind == reflect::ResourceKind::TextureArray + && binding.access == Some(reflect::ResourceAccess::Storage)) + }); + let Some(binding) = binding else { + continue; + }; + let spirv_format = state.format.explicit_format(); + if let Some(shape) = binding.texture_shape.as_mut() { + shape.storage_format = spirv_format; + } + reflection.runtime_storage_image_specializations.push( + reflect::RuntimeStorageImageSpecialization { + metal_index, + state, + spirv_format, + }, + ); + } reflection } +fn validate_reflected_runtime_storage_images( + reflection: &reflect::ShaderReflection, + options: &passes::TransformOptions, +) -> Result<(), String> { + for (metal_index, state) in options + .runtime_storage_image_states + .iter() + .copied() + .enumerate() + .filter_map(|(metal_index, state)| Some((u32::try_from(metal_index).ok()?, state?))) + { + if !reflection + .runtime_storage_image_specializations + .iter() + .any(|specialization| specialization.metal_index == metal_index) + { + return Err(format!( + "runtime storage image {metal_index}: no reflected storage-image binding exists for runtime format {:?}", + state.format + )); + } + } + Ok(()) +} + /// Diagnostic probe (used by `historical PSB dump probes`): run the exact production /// translate path but with the W1 PhysicalStorageBuffer64 retry tiers DISABLED, returning the /// pre-PSB emission the cascade would otherwise feed to the PSB rewrite. Lets the `--psb-dump` tool @@ -415,6 +469,7 @@ pub fn reflect_sanitized( stage_meta.entry_name.as_deref(), &options, ); + validate_reflected_runtime_storage_images(&reflection, &options)?; reflection.function_constants = meta::parse_function_constants(san_ll); reflection.refine_buffer_access_from_entry(san_ll); reflection.add_static_samplers(san_ll)?; @@ -456,6 +511,7 @@ fn translate_sanitized_native_reflected_with_layout( stage_meta.entry_name.as_deref(), &options, ); + validate_reflected_runtime_storage_images(&reflection, &options)?; reflection.function_constants = meta::parse_function_constants(san_ll); reflection.refine_buffer_access_from_entry(san_ll); reflection.add_static_samplers(san_ll)?; diff --git a/src/meta/textures.rs b/src/meta/textures.rs index f310267ba..f98dcb071 100644 --- a/src/meta/textures.rs +++ b/src/meta/textures.rs @@ -78,10 +78,16 @@ impl TextureComponent { #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub enum TextureFormat { + R8, + Rgba8, R16f, + R16ui, Rg16f, R32f, + R32i, R32ui, + Rgba32i, + Rgba32ui, Rgba32f, Rgba16f, Rgba8ui, @@ -93,10 +99,16 @@ impl TextureFormat { /// The SPIR-V `ImageFormat` the emitter decorates the storage image with. pub fn to_spirv_format(self) -> ImageFormat { match self { + TextureFormat::R8 => ImageFormat::R8, + TextureFormat::Rgba8 => ImageFormat::Rgba8, TextureFormat::R16f => ImageFormat::R16f, + TextureFormat::R16ui => ImageFormat::R16ui, TextureFormat::Rg16f => ImageFormat::Rg16f, TextureFormat::R32f => ImageFormat::R32f, + TextureFormat::R32i => ImageFormat::R32i, TextureFormat::R32ui => ImageFormat::R32ui, + TextureFormat::Rgba32i => ImageFormat::Rgba32i, + TextureFormat::Rgba32ui => ImageFormat::Rgba32ui, TextureFormat::Rgba32f => ImageFormat::Rgba32f, TextureFormat::Rgba16f => ImageFormat::Rgba16f, TextureFormat::Rgba8ui => ImageFormat::Rgba8ui, diff --git a/src/native/tests/textures.rs b/src/native/tests/textures.rs index fa9d881be..fe189610a 100644 --- a/src/native/tests/textures.rs +++ b/src/native/tests/textures.rs @@ -39,9 +39,64 @@ fn runtime_sampler_state( } } -#[test] -fn native_unsigned_texture_fetch_max_uses_scalar_atomic_image_format() { - let ll = r#" +fn runtime_storage_image_state( + format: crate::reflect::RuntimeStorageImageFormat, + read_without_format: bool, + write_without_format: bool, +) -> crate::reflect::RuntimeStorageImageState { + crate::reflect::RuntimeStorageImageState { + format, + capabilities: crate::reflect::RuntimeStorageImageCapabilities { + storage_image: true, + storage_image_atomic: false, + read_without_format, + write_without_format, + }, + } +} + +const RUNTIME_STORAGE_IMAGE_WRITE_PAIR_LL: &str = r#" +target triple = "spirv-unknown-vulkan1.3" +define void @k(ptr addrspace(1) %dst0, ptr addrspace(1) %dst1, <2 x i32> %tid) { +entry: + tail call void @air.write_texture_2d.v4f32(ptr addrspace(1) %dst0, <2 x i32> %tid, <4 x float> , i32 0, i32 2) + tail call void @air.write_texture_2d.v4f32(ptr addrspace(1) %dst1, <2 x i32> %tid, <4 x float> , i32 0, i32 2) + ret void +} + +declare void @air.write_texture_2d.v4f32(ptr addrspace(1), <2 x i32>, <4 x float>, i32, i32) + +!air.kernel = !{!0} +!0 = !{ptr @k, !1, !2} +!1 = !{} +!2 = !{!3, !4, !5} +!3 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.write", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"dst0"} +!4 = !{i32 1, !"air.texture", !"air.location_index", i32 1, i32 1, !"air.write", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"dst1"} +!5 = !{i32 2, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint2", !"air.arg_name", !"tid"} +"#; + +const RUNTIME_STORAGE_IMAGE_READ_LL: &str = r#" +target triple = "spirv-unknown-vulkan1.3" +define void @k(ptr addrspace(1) %src, ptr addrspace(1) %out, <2 x i32> %tid) { +entry: + %read = tail call { <4 x float>, i8 } @air.read_texture_2d.v4f32(ptr addrspace(1) %src, <2 x i32> %tid, i32 0, i32 3) + %color = extractvalue { <4 x float>, i8 } %read, 0 + store <4 x float> %color, ptr addrspace(1) %out, align 16 + ret void +} + +declare { <4 x float>, i8 } @air.read_texture_2d.v4f32(ptr addrspace(1), <2 x i32>, i32, i32) + +!air.kernel = !{!0} +!0 = !{ptr @k, !1, !2} +!1 = !{} +!2 = !{!3, !4, !5} +!3 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.read_write", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"src"} +!4 = !{i32 1, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.write", !"air.address_space", i32 1, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4*", !"air.arg_name", !"out"} +!5 = !{i32 2, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint2", !"air.arg_name", !"tid"} +"#; + +const UNSIGNED_TEXTURE_ATOMIC_LL: &str = r#" target triple = "spirv-unknown-vulkan1.3" define void @textureAtomic(<2 x i16> %coord, ptr addrspace(1) %image) { @@ -59,12 +114,16 @@ declare <4 x i32> @air.atomic_fetch_max_explicit_texture_2d.i16.u.v4i32(ptr addr !3 = !{i32 0, !"air.thread_position_in_grid", !"air.arg_type_name", !"ushort2", !"air.arg_name", !"coord"} !4 = !{i32 1, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.read_write", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"image"} "#; + +#[test] +fn native_unsigned_texture_fetch_max_uses_scalar_atomic_image_format() { let tmp = std::env::temp_dir().join(format!( "metal2vulkan_native_texture_atomic_{}", std::process::id() )); let _ = std::fs::create_dir_all(&tmp); - let spv = crate::translate_sanitized_native(ll, Stage::Kernel, &tmp).expect("translate"); + let spv = crate::translate_sanitized_native(UNSIGNED_TEXTURE_ATOMIC_LL, Stage::Kernel, &tmp) + .expect("translate"); let asm = disassemble(&spv).expect("disassemble"); assert!(asm.contains("R32ui"), "{asm}"); assert!(asm.contains("OpImageTexelPointer"), "{asm}"); @@ -78,6 +137,75 @@ declare <4 x i32> @air.atomic_fetch_max_explicit_texture_2d.i16.u.v4i32(ptr addr } } +#[test] +fn runtime_storage_image_atomic_requires_scalar_format_and_host_support() { + let tmp = std::env::temp_dir().join(format!( + "metal2vulkan_runtime_storage_atomic_{}", + std::process::id() + )); + let _ = std::fs::create_dir_all(&tmp); + let state = |format, storage_image_atomic| crate::reflect::RuntimeStorageImageState { + format, + capabilities: crate::reflect::RuntimeStorageImageCapabilities { + storage_image: true, + storage_image_atomic, + read_without_format: false, + write_without_format: false, + }, + }; + + let missing = crate::translate_sanitized_native_with_options( + UNSIGNED_TEXTURE_ATOMIC_LL, + Stage::Kernel, + &tmp, + passes::TransformOptions::default() + .with_runtime_storage_image( + 0, + state(crate::reflect::RuntimeStorageImageFormat::R32Uint, false), + ) + .unwrap(), + ) + .expect_err("atomic format without host atomic support"); + assert!( + missing.contains("lacks storage-image atomic support"), + "{missing}" + ); + + let vector = crate::translate_sanitized_native_with_options( + UNSIGNED_TEXTURE_ATOMIC_LL, + Stage::Kernel, + &tmp, + passes::TransformOptions::default() + .with_runtime_storage_image( + 0, + state(crate::reflect::RuntimeStorageImageFormat::Rgba32Uint, true), + ) + .unwrap(), + ) + .expect_err("vector storage formats cannot implement image atomics"); + assert!( + vector.contains("cannot implement storage-image atomics"), + "{vector}" + ); + + let spv = crate::translate_sanitized_native_with_options( + UNSIGNED_TEXTURE_ATOMIC_LL, + Stage::Kernel, + &tmp, + passes::TransformOptions::default() + .with_runtime_storage_image( + 0, + state(crate::reflect::RuntimeStorageImageFormat::R32Uint, true), + ) + .unwrap(), + ) + .expect("scalar atomic specialization"); + let asm = disassemble(&spv).expect("disassemble atomic specialization"); + assert!(asm.contains("R32ui"), "{asm}"); + assert!(asm.contains("OpAtomicUMax"), "{asm}"); + tools::spirv_val_bytes(&spv, &tmp).expect("atomic specialization spirv-val"); +} + #[test] fn native_array_ref_texture_lowers_to_descriptor_array() { // A runtime-indexed `array_ref` argument is a descriptor array, not a single image. @@ -2764,6 +2892,29 @@ declare { <4 x half>, i8 } @air.gather_texture_2d.v4f16(ptr addrspace(1), ptr ad assert!(asm.contains("OpImageQuerySize "), "{asm}"); assert!(!asm.contains("OpImageFetch"), "{asm}"); assert!(!asm.contains("OpImageQuerySizeLod"), "{asm}"); + let formatless = crate::translate_sanitized_native_with_options( + ll, + Stage::Kernel, + &tmp, + passes::TransformOptions::default() + .with_runtime_storage_image( + 0, + runtime_storage_image_state( + crate::reflect::RuntimeStorageImageFormat::Bgra8Unorm, + true, + false, + ), + ) + .unwrap(), + ) + .expect("pixel gather storage reads use the formatless read contract"); + let formatless_asm = disassemble(&formatless).expect("disassemble formatless gather"); + assert!( + formatless_asm.contains("OpCapability StorageImageReadWithoutFormat"), + "{formatless_asm}" + ); + assert!(!formatless_asm.contains("StorageImageWriteWithoutFormat")); + tools::spirv_val_bytes(&formatless, &tmp).expect("formatless pixel gather spirv-val"); if std::process::Command::new("spirv-val") .arg("--version") .output() @@ -3009,6 +3160,312 @@ declare void @air.write_texture_2d.u.v4i32(ptr addrspace(1), <2 x i32>, <4 x i32 } } +#[test] +fn runtime_storage_image_specialization_splits_shared_image_pointer_and_load_types() { + let tmp = std::env::temp_dir().join(format!( + "metal2vulkan_runtime_storage_split_{}", + std::process::id() + )); + let _ = std::fs::create_dir_all(&tmp); + let rgba8 = runtime_storage_image_state( + crate::reflect::RuntimeStorageImageFormat::Rgba8Unorm, + false, + false, + ); + let rgba32 = runtime_storage_image_state( + crate::reflect::RuntimeStorageImageFormat::Rgba32Float, + false, + false, + ); + let options = passes::TransformOptions::default() + .with_runtime_storage_image(0, rgba8) + .unwrap() + .with_runtime_storage_image(1, rgba32) + .unwrap(); + let (spv, reflection) = crate::translate_sanitized_native_reflected( + RUNTIME_STORAGE_IMAGE_WRITE_PAIR_LL, + Stage::Kernel, + &tmp, + options, + ) + .expect("runtime storage-image specialization"); + let asm = disassemble(&spv).expect("disassemble"); + assert!(asm.contains("Rgba8"), "{asm}"); + assert!(asm.contains("Rgba32f"), "{asm}"); + assert_eq!(asm.matches("OpImageWrite").count(), 2, "{asm}"); + + let module = load_bytes(&spv).expect("load specialized module"); + let defs = module + .types_global_values + .iter() + .filter_map(|instruction| instruction.result_id.map(|id| (id, instruction))) + .collect::>(); + let image_type_at_binding = |binding: u32| { + let variable = module + .annotations + .iter() + .find_map(|decoration| { + (decoration.class.opcode == Op::Decorate + && decoration.operands.get(1) + == Some(&Operand::Decoration(Decoration::Binding)) + && decoration.operands.get(2) == Some(&Operand::LiteralBit32(binding))) + .then(|| match decoration.operands.first() { + Some(Operand::IdRef(id)) => Some(*id), + _ => None, + }) + .flatten() + }) + .expect("storage-image variable"); + let variable_type = defs[&variable].result_type.expect("variable pointer type"); + let image_type = match defs[&variable_type].operands.get(1) { + Some(Operand::IdRef(image_type)) => *image_type, + other => panic!("storage-image pointer has no image pointee: {other:?}"), + }; + let load = module + .functions + .iter() + .flat_map(|function| &function.blocks) + .flat_map(|block| &block.instructions) + .find(|instruction| { + instruction.class.opcode == Op::Load + && instruction.operands.first() == Some(&Operand::IdRef(variable)) + }) + .expect("storage-image load"); + assert_eq!(load.result_type, Some(image_type)); + (image_type, defs[&image_type].operands.get(6).cloned()) + }; + let (rgba8_type, rgba8_format) = image_type_at_binding(480); + let (rgba32_type, rgba32_format) = image_type_at_binding(481); + assert_ne!(rgba8_type, rgba32_type, "differently specialized bindings"); + assert_eq!( + rgba8_format, + Some(Operand::ImageFormat(spirv::ImageFormat::Rgba8)) + ); + assert_eq!( + rgba32_format, + Some(Operand::ImageFormat(spirv::ImageFormat::Rgba32f)) + ); + + for (index, state, format) in [ + (0, rgba8, crate::meta::TextureFormat::Rgba8), + (1, rgba32, crate::meta::TextureFormat::Rgba32f), + ] { + let binding = reflection + .binding_at(crate::reflect::ResourceKind::StorageImage, index) + .expect("reflected storage image"); + assert_eq!( + binding.texture_shape.and_then(|shape| shape.storage_format), + Some(format) + ); + assert!(reflection.runtime_storage_image_specializations.contains( + &crate::reflect::RuntimeStorageImageSpecialization { + metal_index: index, + state, + spirv_format: Some(format), + } + )); + } + tools::spirv_val_bytes(&spv, &tmp).expect("specialized spirv-val"); +} + +#[test] +fn runtime_storage_image_formatless_capabilities_follow_actual_access() { + let tmp = std::env::temp_dir().join(format!( + "metal2vulkan_runtime_storage_formatless_{}", + std::process::id() + )); + let _ = std::fs::create_dir_all(&tmp); + let bgra_write = runtime_storage_image_state( + crate::reflect::RuntimeStorageImageFormat::Bgra8Unorm, + false, + true, + ); + let (write_spv, write_reflection) = crate::translate_sanitized_native_reflected( + RUNTIME_STORAGE_IMAGE_WRITE_PAIR_LL, + Stage::Kernel, + &tmp, + passes::TransformOptions::default() + .with_runtime_storage_image(0, bgra_write) + .unwrap(), + ) + .expect("formatless write specialization"); + let write_asm = disassemble(&write_spv).expect("disassemble write"); + assert!(write_asm.contains("OpCapability StorageImageWriteWithoutFormat")); + assert!(!write_asm.contains("OpCapability StorageImageReadWithoutFormat")); + assert!(write_asm.contains("Unknown"), "{write_asm}"); + assert_eq!( + write_reflection.runtime_storage_image_specializations, + [crate::reflect::RuntimeStorageImageSpecialization { + metal_index: 0, + state: bgra_write, + spirv_format: None, + }] + ); + assert_eq!( + write_reflection + .binding_at(crate::reflect::ResourceKind::StorageImage, 0) + .and_then(|binding| binding.texture_shape) + .and_then(|shape| shape.storage_format), + None + ); + tools::spirv_val_bytes(&write_spv, &tmp).expect("formatless write spirv-val"); + + let bgra_read = runtime_storage_image_state( + crate::reflect::RuntimeStorageImageFormat::Bgra8Unorm, + true, + false, + ); + let read_spv = crate::translate_sanitized_native_with_options( + RUNTIME_STORAGE_IMAGE_READ_LL, + Stage::Kernel, + &tmp, + passes::TransformOptions::default() + .with_runtime_storage_image(0, bgra_read) + .unwrap(), + ) + .expect("formatless read specialization"); + let read_asm = disassemble(&read_spv).expect("disassemble read"); + assert!(read_asm.contains("OpCapability StorageImageReadWithoutFormat")); + assert!(!read_asm.contains("OpCapability StorageImageWriteWithoutFormat")); + assert!(read_asm.contains("OpImageRead"), "{read_asm}"); + tools::spirv_val_bytes(&read_spv, &tmp).expect("formatless read spirv-val"); +} + +#[test] +fn runtime_storage_image_formatless_partial_write_requires_read_and_write_features() { + let ll = r#" +target triple = "spirv-unknown-vulkan1.3" +define void @k(ptr addrspace(1) %dst, <2 x i32> %tid) { +entry: + %texel = insertelement <4 x float> undef, float 1.000000e+00, i64 0 + tail call void @air.write_texture_2d.v4f32(ptr addrspace(1) %dst, <2 x i32> %tid, <4 x float> %texel, i32 0, i32 2) + ret void +} +declare void @air.write_texture_2d.v4f32(ptr addrspace(1), <2 x i32>, <4 x float>, i32, i32) +!air.kernel = !{!0} +!0 = !{ptr @k, !1, !2} +!1 = !{} +!2 = !{!3, !4} +!3 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.write", !"air.arg_type_name", !"texture2d"} +!4 = !{i32 1, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint2"} +"#; + let tmp = std::env::temp_dir().join(format!( + "metal2vulkan_runtime_storage_formatless_rmw_{}", + std::process::id() + )); + let _ = std::fs::create_dir_all(&tmp); + let both = runtime_storage_image_state( + crate::reflect::RuntimeStorageImageFormat::Bgra8Unorm, + true, + true, + ); + let spv = crate::translate_sanitized_native_with_options( + ll, + Stage::Kernel, + &tmp, + passes::TransformOptions::default() + .with_runtime_storage_image(0, both) + .unwrap(), + ) + .expect("formatless read-modify-write specialization"); + let asm = disassemble(&spv).expect("disassemble read-modify-write"); + assert!(asm.contains("OpCapability StorageImageReadWithoutFormat")); + assert!(asm.contains("OpCapability StorageImageWriteWithoutFormat")); + assert!(asm.contains("OpImageRead"), "{asm}"); + assert!(asm.contains("OpImageWrite"), "{asm}"); + tools::spirv_val_bytes(&spv, &tmp).expect("formatless read-modify-write spirv-val"); + + let write_only = runtime_storage_image_state( + crate::reflect::RuntimeStorageImageFormat::Bgra8Unorm, + false, + true, + ); + let error = crate::translate_sanitized_native_with_options( + ll, + Stage::Kernel, + &tmp, + passes::TransformOptions::default() + .with_runtime_storage_image(0, write_only) + .unwrap(), + ) + .expect_err("hidden preservation read requires read-without-format"); + assert!(error.contains("read-without-format"), "{error}"); +} + +#[test] +fn runtime_storage_image_specialization_refuses_incompatible_or_missing_contracts() { + let tmp = std::env::temp_dir().join(format!( + "metal2vulkan_runtime_storage_refusals_{}", + std::process::id() + )); + let _ = std::fs::create_dir_all(&tmp); + let uint_state = runtime_storage_image_state( + crate::reflect::RuntimeStorageImageFormat::Rgba8Uint, + false, + false, + ); + let incompatible = crate::translate_sanitized_native_with_options( + RUNTIME_STORAGE_IMAGE_WRITE_PAIR_LL, + Stage::Kernel, + &tmp, + passes::TransformOptions::default() + .with_runtime_storage_image(0, uint_state) + .unwrap(), + ) + .expect_err("float AIR texels cannot target an integer runtime format"); + assert!( + incompatible.contains("AIR texels are Float"), + "{incompatible}" + ); + + let bgra_missing_write = runtime_storage_image_state( + crate::reflect::RuntimeStorageImageFormat::Bgra8Unorm, + true, + false, + ); + let missing_feature = crate::translate_sanitized_native_with_options( + RUNTIME_STORAGE_IMAGE_WRITE_PAIR_LL, + Stage::Kernel, + &tmp, + passes::TransformOptions::default() + .with_runtime_storage_image(0, bgra_missing_write) + .unwrap(), + ) + .expect_err("formatless write without host feature"); + assert!( + missing_feature.contains("write-without-format"), + "{missing_feature}" + ); + + let rgba8 = runtime_storage_image_state( + crate::reflect::RuntimeStorageImageFormat::Rgba8Unorm, + false, + false, + ); + let missing_binding = crate::translate_sanitized_native_with_options( + RUNTIME_STORAGE_IMAGE_WRITE_PAIR_LL, + Stage::Kernel, + &tmp, + passes::TransformOptions::default() + .with_runtime_storage_image(7, rgba8) + .unwrap(), + ) + .expect_err("specialization index must name a storage binding"); + assert!( + missing_binding.contains("no storage-image binding"), + "{missing_binding}" + ); + + let unsupported = crate::reflect::RuntimeStorageImageState { + format: crate::reflect::RuntimeStorageImageFormat::Rgba8Unorm, + capabilities: crate::reflect::RuntimeStorageImageCapabilities::default(), + }; + let missing_storage = passes::TransformOptions::default() + .with_runtime_storage_image(0, unsupported) + .expect_err("format must support storage usage"); + assert!(missing_storage.contains("lacks storage-image format support")); +} + #[test] fn native_kernel_helper_wrapped_write_texture_uses_single_storage_image() { let ll = r#" @@ -3324,6 +3781,49 @@ declare void @air.write_imageblock_slice_to_texture_2d.v4f16(ptr addrspace(1), p assert!(asm.contains("OpImageWrite"), "{asm}"); assert!(!asm.contains("air.imageblock"), "{asm}"); assert!(!asm.contains("OpFunctionCall"), "{asm}"); + let missing_formatless = crate::translate_sanitized_native_with_options( + ll, + Stage::Kernel, + &tmp, + passes::TransformOptions::default() + .with_runtime_storage_image( + 1, + runtime_storage_image_state( + crate::reflect::RuntimeStorageImageFormat::Bgra8Unorm, + false, + false, + ), + ) + .unwrap(), + ) + .expect_err("imageblock slice write must require formatless write support"); + assert!( + missing_formatless.contains("write-without-format"), + "{missing_formatless}" + ); + let formatless = crate::translate_sanitized_native_with_options( + ll, + Stage::Kernel, + &tmp, + passes::TransformOptions::default() + .with_runtime_storage_image( + 1, + runtime_storage_image_state( + crate::reflect::RuntimeStorageImageFormat::Bgra8Unorm, + false, + true, + ), + ) + .unwrap(), + ) + .expect("formatless imageblock slice write"); + let formatless_asm = disassemble(&formatless).expect("disassemble formatless imageblock write"); + assert!( + formatless_asm.contains("OpCapability StorageImageWriteWithoutFormat"), + "{formatless_asm}" + ); + assert!(formatless_asm.contains("Unknown"), "{formatless_asm}"); + tools::spirv_val_bytes(&formatless, &tmp).expect("formatless imageblock write spirv-val"); if std::process::Command::new("spirv-val") .arg("--version") .output() diff --git a/src/passes/air_calls/float_imageblock.rs b/src/passes/air_calls/float_imageblock.rs index d0097d055..a233d56bf 100644 --- a/src/passes/air_calls/float_imageblock.rs +++ b/src/passes/air_calls/float_imageblock.rs @@ -1151,6 +1151,7 @@ pub(in crate::passes) fn lower_imageblock_slice_write_texel( format!("air.write_imageblock_slice_to_texture on non-storage image id {img}") })?; } + ctx.require_runtime_storage_image_use(img, RuntimeStorageImageUse::Write)?; let (dim, arrayed) = ctx .image_dims .get(&img) diff --git a/src/passes/air_calls/images/atomic.rs b/src/passes/air_calls/images/atomic.rs index cb8a03d91..3ab7d560b 100644 --- a/src/passes/air_calls/images/atomic.rs +++ b/src/passes/air_calls/images/atomic.rs @@ -30,6 +30,7 @@ pub(in crate::passes) fn lower_atomic_texture_fetch_max( if comp != crate::passes::ImageComp::Uint { return Err(format!("{name} requires an unsigned integer storage image")); } + ctx.require_runtime_storage_image_use(image, RuntimeStorageImageUse::Atomic)?; let image_pointer = if value_is_pointer(ctx, image) { image } else { diff --git a/src/passes/air_calls/images/gather.rs b/src/passes/air_calls/images/gather.rs index ea3a61c60..a649fa066 100644 --- a/src/passes/air_calls/images/gather.rs +++ b/src/passes/air_calls/images/gather.rs @@ -311,7 +311,7 @@ pub(in crate::passes) fn lower_pixel_gather_2d( &mut out, )?; let color = ctx.module.fresh_id(); - push_image_read_or_fetch(ctx, &mut out, img, fetch.coord, Some(lod), sample_v4, color); + push_image_read_or_fetch(ctx, &mut out, img, fetch.coord, Some(lod), sample_v4, color)?; let mut selected = ctx.module.fresh_id(); out.push(Instruction::new( Op::CompositeExtract, diff --git a/src/passes/air_calls/images/mod.rs b/src/passes/air_calls/images/mod.rs index 9f12e0e5b..b3aa56c90 100644 --- a/src/passes/air_calls/images/mod.rs +++ b/src/passes/air_calls/images/mod.rs @@ -122,6 +122,9 @@ pub(in crate::passes) fn load_image_if_pointer( } if ctx.image_storage.contains(&image) || image_type_is_storage(ctx, pointee) { ctx.image_storage.insert(loaded); + if let Some((metal_index, state)) = ctx.runtime_storage_image_values.get(&image).copied() { + ctx.register_runtime_storage_image_value(loaded, metal_index, Some(state)); + } } loaded } diff --git a/src/passes/air_calls/images/query_offset.rs b/src/passes/air_calls/images/query_offset.rs index 67a5df996..7b94c7d8f 100644 --- a/src/passes/air_calls/images/query_offset.rs +++ b/src/passes/air_calls/images/query_offset.rs @@ -30,16 +30,17 @@ pub(in crate::passes) fn query_image_size( } pub(in crate::passes) fn push_image_read_or_fetch( - ctx: &Ctx, + ctx: &mut Ctx, out: &mut Vec, img: Word, coord: Word, lod: Option, result_ty: Word, result: Word, -) { +) -> Result<(), String> { let mut ops = vec![Operand::IdRef(img), Operand::IdRef(coord)]; let op = if image_is_storage(ctx, img) { + ctx.require_runtime_storage_image_use(img, RuntimeStorageImageUse::Read)?; Op::ImageRead } else { if let Some(lod) = lod { @@ -49,6 +50,7 @@ pub(in crate::passes) fn push_image_read_or_fetch( Op::ImageFetch }; out.push(Instruction::new(op, Some(result_ty), Some(result), ops)); + Ok(()) } pub(in crate::passes) fn image_size_component( diff --git a/src/passes/air_calls/images/sample.rs b/src/passes/air_calls/images/sample.rs index 805cbcd8d..23f85733a 100644 --- a/src/passes/air_calls/images/sample.rs +++ b/src/passes/air_calls/images/sample.rs @@ -111,7 +111,7 @@ pub(in crate::passes) fn lower_sample( &mut out, )?; let mut color = ctx.module.fresh_id(); - push_image_read_or_fetch(ctx, &mut out, img, fetch.coord, Some(lod), sample_v4, color); + push_image_read_or_fetch(ctx, &mut out, img, fetch.coord, Some(lod), sample_v4, color)?; if let Some(in_bounds) = fetch.in_bounds { let guarded = ctx.module.fresh_id(); let zero_color = const_null_of(ctx, sample_v4); @@ -192,7 +192,7 @@ pub(in crate::passes) fn lower_sample( Some(lod), sample_v4, color, - ); + )?; if let Some(in_bounds) = fetch.in_bounds { let guarded = ctx.module.fresh_id(); let zero_color = const_null_of(ctx, sample_v4); @@ -441,7 +441,7 @@ fn lower_pixel_bicubic_sample( Some(lod), sample_v4, fetched, - ); + )?; let color = if let Some(in_bounds) = tap_coord.in_bounds { let guarded = ctx.module.fresh_id(); out.push(Instruction::new( @@ -772,7 +772,7 @@ pub(in crate::passes) fn lower_pixel_linear_sample( Some(lod), sample_v4, fetched, - ); + )?; let color = if let Some(in_bounds) = tap_coord.in_bounds { let guarded = ctx.module.fresh_id(); out.push(Instruction::new( diff --git a/src/passes/air_calls/images/sample_depth.rs b/src/passes/air_calls/images/sample_depth.rs index b01e3fc4b..bf438fb8f 100644 --- a/src/passes/air_calls/images/sample_depth.rs +++ b/src/passes/air_calls/images/sample_depth.rs @@ -81,7 +81,7 @@ pub(in crate::passes) fn lower_sample_depth( &mut out, )?; let fetched = ctx.module.fresh_id(); - push_image_read_or_fetch(ctx, &mut out, img, fetch.coord, Some(lod), v4, fetched); + push_image_read_or_fetch(ctx, &mut out, img, fetch.coord, Some(lod), v4, fetched)?; if let Some(in_bounds) = fetch.in_bounds { let guarded = ctx.module.fresh_id(); let zero = const_null_of(ctx, v4); @@ -286,7 +286,7 @@ pub(in crate::passes) fn lower_sample_compare_depth( &mut out, )?; let fetched = ctx.module.fresh_id(); - push_image_read_or_fetch(ctx, &mut out, img, fetch.coord, Some(lod), v4, fetched); + push_image_read_or_fetch(ctx, &mut out, img, fetch.coord, Some(lod), v4, fetched)?; if let Some(in_bounds) = fetch.in_bounds { let guarded = ctx.module.fresh_id(); let zero_color = const_null_of(ctx, v4); diff --git a/src/passes/air_calls/images/write_read.rs b/src/passes/air_calls/images/write_read.rs index 9c3f3af01..1be7da177 100644 --- a/src/passes/air_calls/images/write_read.rs +++ b/src/passes/air_calls/images/write_read.rs @@ -32,6 +32,7 @@ pub(in crate::passes) fn lower_write( )); } } + ctx.require_runtime_storage_image_use(img, RuntimeStorageImageUse::Write)?; let mut out = vec![]; let (dim, arrayed) = ctx @@ -104,7 +105,7 @@ pub(in crate::passes) fn lower_write( } }; - let texel32 = preserve_defined_texel_lanes(ctx, &mut out, img, coord32, texel, texel32); + let texel32 = preserve_defined_texel_lanes(ctx, &mut out, img, coord32, texel, texel32)?; out.push(Instruction::new( Op::ImageWrite, @@ -126,19 +127,20 @@ fn preserve_defined_texel_lanes( coord32: Word, source_texel: Word, write_texel: Word, -) -> Word { +) -> Result { let undefined = (0..4) .map(|lane| texel_lane_is_statically_undef(ctx, out, source_texel, lane)) .collect::>(); if undefined.iter().all(|is_undef| !*is_undef) { - return write_texel; + return Ok(write_texel); } let Some(write_ty) = pending_or_module_result_type(ctx, out, write_texel) else { - return write_texel; + return Ok(write_texel); }; let lane_ty = element_type(ctx, write_ty); let current = ctx.module.fresh_id(); + ctx.require_runtime_storage_image_use(img, RuntimeStorageImageUse::Read)?; out.push(Instruction::new( Op::ImageRead, Some(write_ty), @@ -174,7 +176,7 @@ fn preserve_defined_texel_lanes( )); merged = next; } - merged + Ok(merged) } fn pending_or_module_result_type(ctx: &Ctx, pending: &[Instruction], value: Word) -> Option { @@ -283,6 +285,9 @@ pub(in crate::passes) fn lower_read( return lower_null_texture_result(ctx, res, rty); } } + if image_is_storage(ctx, img) { + ctx.require_runtime_storage_image_use(img, RuntimeStorageImageUse::Read)?; + } let (dim, arrayed) = ctx .image_dims .get(&img) diff --git a/src/passes/mod.rs b/src/passes/mod.rs index 9ae7457e0..55d231ad1 100644 --- a/src/passes/mod.rs +++ b/src/passes/mod.rs @@ -17,7 +17,10 @@ use crate::meta::{ AirScalar, AirType, FragMeta, FragRole, KernMeta, KernRole, VertMeta, VertOutRole, VertRole, }; -use crate::reflect::{RuntimeSamplerState, StaticSamplerState, SAMPLER_ARGUMENT_COUNT_USIZE}; +use crate::reflect::{ + RuntimeSamplerState, RuntimeStorageImageState, StaticSamplerState, + SAMPLER_ARGUMENT_COUNT_USIZE, TEXTURE_ARGUMENT_COUNT_USIZE, +}; use crate::spirv_module::{is_block_terminator, Block, Function, Instruction, Module, Operand}; use spirv::{ BuiltIn, Decoration, Dim, FunctionControl, ImageFormat, MemorySemantics, Op, Scope, @@ -59,6 +62,10 @@ pub struct TransformOptions { /// sampler state, but pixel-coordinate samplers require operation-aware shader specialization /// to remain legal in Vulkan. Unspecified slots retain ordinary runtime sampling. pub runtime_sampler_states: [Option; SAMPLER_ARGUMENT_COUNT_USIZE], + /// Runtime surface format and host features by Metal `[[texture(n)]]` index. Only storage-image + /// bindings consume these entries; sampled textures retain their AIR-derived image type. + pub runtime_storage_image_states: + [Option; TEXTURE_ARGUMENT_COUNT_USIZE], } impl Default for TransformOptions { @@ -70,6 +77,7 @@ impl Default for TransformOptions { denorm_flush_to_zero_f32: false, raster_sample_count: None, runtime_sampler_states: [None; SAMPLER_ARGUMENT_COUNT_USIZE], + runtime_storage_image_states: [None; TEXTURE_ARGUMENT_COUNT_USIZE], } } } @@ -106,6 +114,43 @@ impl TransformOptions { } Ok(()) } + + /// Specialize one dynamically bound Metal storage texture. The runtime format and host feature + /// facts are validated before translation mutates the module. + pub fn with_runtime_storage_image( + mut self, + metal_index: u32, + state: RuntimeStorageImageState, + ) -> Result { + state.validate()?; + let slot = usize::try_from(metal_index) + .ok() + .filter(|slot| *slot < TEXTURE_ARGUMENT_COUNT_USIZE) + .ok_or_else(|| { + format!( + "Metal texture index {metal_index} exceeds runtime storage-image specialization range 0..{}", + TEXTURE_ARGUMENT_COUNT_USIZE + ) + })?; + self.runtime_storage_image_states[slot] = Some(state); + Ok(self) + } + + pub(crate) fn validate_runtime_storage_images(self) -> Result<(), String> { + for (index, state) in self + .runtime_storage_image_states + .iter() + .copied() + .enumerate() + { + if let Some(state) = state { + state + .validate() + .map_err(|error| format!("runtime storage image {index}: {error}"))?; + } + } + Ok(()) + } } /// The sampled component type of a texture (the `OpTypeImage` "Sampled Type"). Metal integer @@ -119,6 +164,13 @@ pub enum ImageComp { Sint, } +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum RuntimeStorageImageUse { + Read, + Write, + Atomic, +} + #[derive(Clone, Copy, Debug, PartialEq, Eq)] struct FragmentImageblockFormat { image_format: ImageFormat, @@ -252,6 +304,11 @@ struct Ctx { /// Exact graphics-pipeline sample count used to lower `air.get_num_samples.i32`. raster_sample_count: Option, runtime_sampler_states: [Option; SAMPLER_ARGUMENT_COUNT_USIZE], + runtime_storage_image_states: [Option; TEXTURE_ARGUMENT_COUNT_USIZE], + /// Storage-image variable/load ids carrying caller-provided runtime format state. + runtime_storage_image_values: HashMap, + /// Metal texture indices whose storage-image binding consumed its specialization entry. + applied_runtime_storage_image_indices: HashSet, /// lazily-created default sampler variable id, for `air.get_read_sampler()` (a sampler-less /// `texture.read` still passes a sampler operand AIR-side; we synthesize one valid sampler). default_sampler_var: Option, @@ -329,6 +386,9 @@ impl Ctx { simd_cluster32: options.simd_cluster32, raster_sample_count: options.raster_sample_count, runtime_sampler_states: options.runtime_sampler_states, + runtime_storage_image_states: options.runtime_storage_image_states, + runtime_storage_image_values: HashMap::new(), + applied_runtime_storage_image_indices: HashSet::new(), default_sampler_var: None, sampler_states: HashMap::new(), specialized_runtime_sampler_values: HashSet::new(), @@ -341,6 +401,242 @@ impl Ctx { writes_frag_depth: false, } } + + fn add_capability(&mut self, capability: spirv::Capability) { + if self.module.capabilities.iter().any(|instruction| { + instruction.operands.first() == Some(&Operand::Capability(capability)) + }) { + return; + } + self.module.capabilities.push(Instruction::new( + Op::Capability, + None, + None, + vec![Operand::Capability(capability)], + )); + } + + fn specialize_storage_image_format( + &mut self, + metal_index: u32, + air_format: ImageFormat, + component: ImageComp, + ) -> Result<(ImageFormat, Option), String> { + let Some(state) = usize::try_from(metal_index) + .ok() + .and_then(|index| self.runtime_storage_image_states.get(index)) + .copied() + .flatten() + else { + return Ok((air_format, None)); + }; + let air_component = crate::meta::TextureComponent::from_image_comp(component); + let runtime_component = state.format.component(); + if air_component != runtime_component { + return Err(format!( + "runtime storage image {metal_index}: AIR texels are {air_component:?}, but runtime format {:?} is {runtime_component:?}", + state.format + )); + } + self.applied_runtime_storage_image_indices + .insert(metal_index); + let format = state + .format + .explicit_format() + .map(crate::meta::TextureFormat::to_spirv_format) + .unwrap_or(ImageFormat::Unknown); + if storage_image_format_needs_extended_capability(format) { + self.add_capability(spirv::Capability::StorageImageExtendedFormats); + } + Ok((format, Some(state))) + } + + fn register_runtime_storage_image_value( + &mut self, + value: Word, + metal_index: u32, + state: Option, + ) { + if let Some(state) = state { + self.runtime_storage_image_values + .insert(value, (metal_index, state)); + } + } + + fn require_runtime_storage_image_use( + &mut self, + image: Word, + usage: RuntimeStorageImageUse, + ) -> Result<(), String> { + let specializations = self.runtime_storage_image_origins(image); + if specializations.is_empty() { + return Ok(()); + } + let first_format = specializations[0].1.format.explicit_format(); + if specializations + .iter() + .any(|(_, state)| state.format.explicit_format() != first_format) + { + return Err( + "differently formatted runtime storage images cannot be selected into one image value" + .into(), + ); + } + for (metal_index, state) in specializations { + if usage == RuntimeStorageImageUse::Atomic { + if !state.format.supports_atomics() { + return Err(format!( + "runtime storage image {metal_index}: format {:?} cannot implement storage-image atomics", + state.format + )); + } + if !state.capabilities.storage_image_atomic { + return Err(format!( + "runtime storage image {metal_index}: format {:?} lacks storage-image atomic support", + state.format + )); + } + } + if state.format.explicit_format().is_some() { + continue; + } + let (supported, capability, operation) = match usage { + RuntimeStorageImageUse::Read => ( + state.capabilities.read_without_format, + spirv::Capability::StorageImageReadWithoutFormat, + "read", + ), + RuntimeStorageImageUse::Write => ( + state.capabilities.write_without_format, + spirv::Capability::StorageImageWriteWithoutFormat, + "write", + ), + RuntimeStorageImageUse::Atomic => { + return Err(format!( + "runtime storage image {metal_index}: formatless storage-image atomics are unsupported" + )); + } + }; + if !supported { + return Err(format!( + "runtime storage image {metal_index}: format {:?} requires host {operation}-without-format support", + state.format + )); + } + self.add_capability(capability); + } + Ok(()) + } + + fn runtime_storage_image_origins(&self, image: Word) -> Vec<(u32, RuntimeStorageImageState)> { + let mut pending = vec![image]; + let mut visited = HashSet::new(); + let mut origins = Vec::new(); + while let Some(value) = pending.pop() { + if !visited.insert(value) { + continue; + } + if let Some(origin) = self.runtime_storage_image_values.get(&value).copied() { + if !origins.contains(&origin) { + origins.push(origin); + } + continue; + } + let Some(instruction) = self + .module + .types_global_values + .iter() + .chain(self.new_globals.iter()) + .chain( + self.module + .functions + .iter() + .flat_map(|function| function.blocks.iter()) + .flat_map(|block| block.instructions.iter()), + ) + .find(|instruction| instruction.result_id == Some(value)) + else { + continue; + }; + match instruction.class.opcode { + Op::CopyObject | Op::Load => { + if let Some(Operand::IdRef(source)) = instruction.operands.first() { + pending.push(*source); + } + } + Op::Select => { + pending.extend(instruction.operands.iter().skip(1).filter_map(|operand| { + match operand { + Operand::IdRef(source) => Some(*source), + _ => None, + } + })) + } + Op::Phi => pending.extend(instruction.operands.iter().enumerate().filter_map( + |(index, operand)| match (index % 2, operand) { + (0, Operand::IdRef(source)) => Some(*source), + _ => None, + }, + )), + _ => {} + } + } + origins.sort_unstable_by_key(|(metal_index, _)| *metal_index); + origins + } + + fn validate_runtime_storage_image_bindings(&self) -> Result<(), String> { + for (metal_index, state) in self + .runtime_storage_image_states + .iter() + .copied() + .enumerate() + .filter_map(|(index, state)| Some((u32::try_from(index).ok()?, state?))) + { + if !self + .applied_runtime_storage_image_indices + .contains(&metal_index) + { + return Err(format!( + "runtime storage image {metal_index}: no storage-image binding exists for runtime format {:?}", + state.format + )); + } + } + Ok(()) + } +} + +fn storage_image_format_needs_extended_capability(format: ImageFormat) -> bool { + matches!( + format, + ImageFormat::Rg32f + | ImageFormat::Rg16f + | ImageFormat::R11fG11fB10f + | ImageFormat::R16f + | ImageFormat::Rgba16 + | ImageFormat::Rgb10A2 + | ImageFormat::Rg16 + | ImageFormat::Rg8 + | ImageFormat::R16 + | ImageFormat::R8 + | ImageFormat::Rgba16Snorm + | ImageFormat::Rg16Snorm + | ImageFormat::Rg8Snorm + | ImageFormat::R16Snorm + | ImageFormat::R8Snorm + | ImageFormat::Rg32i + | ImageFormat::Rg16i + | ImageFormat::Rg8i + | ImageFormat::R16i + | ImageFormat::R8i + | ImageFormat::Rgb10a2ui + | ImageFormat::Rg32ui + | ImageFormat::Rg16ui + | ImageFormat::Rg8ui + | ImageFormat::R16ui + | ImageFormat::R8ui + ) } /// A small helper to build a type/constant instruction and register it in the cache + new_globals. @@ -1931,6 +2227,7 @@ pub(crate) fn transform_with_options_and_sidecar( // 1a) decoded params -> stage-input/resource vars and entry-body replacements. Preserve the // original type snapshot for the immediately-following return rewrite. let input_defs = build_stage_input(&mut ctx, entry_idx, &stage, frag, vert, kern)?; + ctx.validate_runtime_storage_image_bindings()?; // 1b) return -> output vars. rewrite_return(&mut ctx, entry_idx, &stage, frag, vert, &input_defs)?; // Turn each runtime-indexed texture-array element handle load into an OpAccessChain+OpLoad diff --git a/src/passes/resources/collapse.rs b/src/passes/resources/collapse.rs index 8e19c73c7..8c053f09e 100644 --- a/src/passes/resources/collapse.rs +++ b/src/passes/resources/collapse.rs @@ -501,12 +501,16 @@ pub(in crate::passes) fn apply_bindings( dim, comp, multisampled, + runtime_specialization, } => { // Splice the param to the array VARIABLE (a pointer to `array`); the per-element // image is materialized at each use by `materialize_texture_array_loads` reading // `image_array_vars`. No function-top load: the array as a whole is never an operand. ctx.image_array_vars .insert(var, (elem_image_ty, dim, comp, multisampled)); + if let Some((metal_index, state)) = runtime_specialization { + ctx.register_runtime_storage_image_value(var, metal_index, Some(state)); + } remove_dead_local_image_array_memcpy(ctx, entry_idx, pid); resource_values.insert(var); splices.push((pid, var)); @@ -516,6 +520,7 @@ pub(in crate::passes) fn apply_bindings( image_ty, dim, comp, + runtime_specialization, } => { let lid = ctx.module.fresh_id(); loads.push(Instruction::new( @@ -527,6 +532,10 @@ pub(in crate::passes) fn apply_bindings( ctx.image_dims.insert(lid, dim); ctx.image_comp.insert(lid, comp); ctx.image_storage.insert(lid); + if let Some((metal_index, state)) = runtime_specialization { + ctx.register_runtime_storage_image_value(var, metal_index, Some(state)); + ctx.register_runtime_storage_image_value(lid, metal_index, Some(state)); + } resource_values.insert(lid); splices.push((pid, lid)); } diff --git a/src/passes/resources/discovery.rs b/src/passes/resources/discovery.rs index 6a7c4e477..39f1b2e9c 100644 --- a/src/passes/resources/discovery.rs +++ b/src/passes/resources/discovery.rs @@ -547,6 +547,45 @@ fn write_texture_operands( out } +/// Metadata-declared storage textures used by direct texel reads, with any parameter also consumed +/// by a sampled-image operation or query removed. This distinguishes `read_texture` (legal as +/// `OpImageRead`) from the other calls that make `texture_dims` require a Sampled=1 binding. +pub(in crate::passes) fn storage_texel_read_operands(ctx: &Ctx, entry_idx: usize) -> HashSet { + let names = air_names(&ctx.module); + let mut reads = HashSet::new(); + let mut sampled_or_queried = HashSet::new(); + for instruction in ctx.module.functions[entry_idx] + .blocks + .iter() + .flat_map(|block| &block.instructions) + .filter(|instruction| instruction.class.opcode == Op::FunctionCall) + { + let callee = match instruction.operands.first() { + Some(Operand::IdRef(callee)) => *callee, + _ => continue, + }; + let Some(name) = names.get(&callee) else { + continue; + }; + let Some(Operand::IdRef(texture)) = instruction.operands.get(1) else { + continue; + }; + if name.starts_with("air.read_texture") || name.starts_with("air.read_depth") { + reads.insert(*texture); + } else if name.starts_with("air.sample_texture") + || name.starts_with("air.sample_depth") + || name.starts_with("air.is_null_texture") + || is_size_query(name) + || name.starts_with("air.get_num_mip_levels_") + || name.starts_with("air.get_num_samples_texture") + { + sampled_or_queried.insert(*texture); + } + } + reads.retain(|texture| !sampled_or_queried.contains(texture)); + reads +} + fn is_size_query(name: &str) -> bool { name.starts_with("air.get_width_texture") || name.starts_with("air.get_height_texture") diff --git a/src/passes/resources/texture_array.rs b/src/passes/resources/texture_array.rs index 0f6f4f830..51d949e1d 100644 --- a/src/passes/resources/texture_array.rs +++ b/src/passes/resources/texture_array.rs @@ -230,6 +230,11 @@ pub(crate) fn materialize_texture_array_loads(ctx: &mut Ctx, entry_idx: usize) { } if image_type_is_storage(ctx, elem_image_ty) { ctx.image_storage.insert(handle); + if let Some((metal_index, state)) = + ctx.runtime_storage_image_values.get(&arrayvar).copied() + { + ctx.register_runtime_storage_image_value(handle, metal_index, Some(state)); + } } // The original load's pointer operand becomes dead; record its id for the sweep. if let Some(load) = defs.get(&handle) { @@ -290,6 +295,11 @@ pub(crate) fn materialize_texture_array_loads(ctx: &mut Ctx, entry_idx: usize) { } if image_type_is_storage(ctx, image_ty) { ctx.image_storage.insert(image); + if let Some((metal_index, state)) = + ctx.runtime_storage_image_values.get(&arrayvar).copied() + { + ctx.register_runtime_storage_image_value(image, metal_index, Some(state)); + } } placeholder_uses.insert((block_idx, inst_idx), (chain, load, image)); } diff --git a/src/passes/stage_input/mod.rs b/src/passes/stage_input/mod.rs index 96d63c7f9..1a8c0a014 100644 --- a/src/passes/stage_input/mod.rs +++ b/src/passes/stage_input/mod.rs @@ -148,6 +148,7 @@ pub(in crate::passes) enum ParamBinding { dim: (Dim, bool), comp: ImageComp, multisampled: bool, + runtime_specialization: Option<(u32, crate::reflect::RuntimeStorageImageState)>, }, /// A write-only storage-image variable (`OpTypeImage Sampled=2` + ImageFormat): param uses are the /// `air.write_texture_*` texture operand; replace the param id with an OpLoad of the storage image. @@ -157,6 +158,7 @@ pub(in crate::passes) enum ParamBinding { image_ty: Word, dim: (Dim, bool), comp: ImageComp, + runtime_specialization: Option<(u32, crate::reflect::RuntimeStorageImageState)>, }, /// A framebuffer-fetch `[[color(n)]]` input. Vulkan exposes these as subpass input attachments, /// read with `OpImageRead` at the current fragment location. @@ -276,9 +278,10 @@ pub(super) fn build_stage_input( wtex_candidates.entry(pid).or_insert(shape); } } + let storage_texel_reads = storage_texel_read_operands(ctx, entry_idx); let wtex_dims: HashMap = wtex_candidates .into_iter() - .filter(|(pid, _)| !tex_dims.contains_key(pid)) + .filter(|(pid, _)| !tex_dims.contains_key(pid) || storage_texel_reads.contains(pid)) .collect(); // Plan a binding for each parameter, allocating descriptor bindings and locations in role order. @@ -419,6 +422,20 @@ pub(super) fn build_stage_input( _ => None, }, }; + let metal_texture_index = match stage { + Stage::Fragment => frag.and_then(|meta| match meta.role_of(idx) { + Some(FragRole::Texture(index)) => Some(*index), + _ => None, + }), + Stage::Vertex => vert.and_then(|meta| match meta.role_of(idx) { + Some(VertRole::Texture(index)) => Some(*index), + _ => None, + }), + Stage::Kernel => kern.and_then(|meta| match meta.role_of(idx) { + Some(KernRole::Texture(index)) => Some(*index), + _ => None, + }), + }; let is_threadgroup_buffer = matches!(stage, Stage::Kernel) && role_is("buffer") @@ -475,14 +492,19 @@ pub(super) fn build_stage_input( )); buffer_structs.push((var, block_ty)); } else if role_is("texture") && is_array_texture { - let (elem_image_ty, dim, arrayed, comp, multisampled) = + let (elem_image_ty, dim, arrayed, comp, multisampled, runtime_specialization) = if let Some((dim, arrayed, fmt, comp)) = wtex_dims.get(pid).copied() { + let metal_index = metal_texture_index + .ok_or("storage texture array has no Metal texture index")?; + let (fmt, state) = + ctx.specialize_storage_image_format(metal_index, fmt, comp)?; ( ctx.ty_storage_image(dim, arrayed, fmt, comp), dim, arrayed, comp, false, + state.map(|state| (metal_index, state)), ) } else { let shape = tex_dims @@ -501,6 +523,7 @@ pub(super) fn build_stage_input( shape.arrayed, shape.comp, shape.multisampled, + None, ) }; // The array length is a runtime function constant (`nImagesFC`), not a compile-time value, @@ -538,6 +561,7 @@ pub(super) fn build_stage_input( dim: (dim, arrayed), comp, multisampled, + runtime_specialization, }, )); } else if role_is("texture") && wtex_dims.contains_key(pid) { @@ -546,6 +570,10 @@ pub(super) fn build_stage_input( .get(pid) .copied() .ok_or("write-texture dims missing for bound param")?; + let metal_index = + metal_texture_index.ok_or("storage texture has no Metal texture index")?; + let (fmt, runtime_state) = + ctx.specialize_storage_image_format(metal_index, fmt, comp)?; let image_ty = ctx.ty_storage_image(dim, arrayed, fmt, comp); let pptr = ctx.ty_ptr(StorageClass::UniformConstant, image_ty); let var = ctx.module.fresh_id(); @@ -565,6 +593,7 @@ pub(super) fn build_stage_input( image_ty, dim: (dim, arrayed), comp, + runtime_specialization: runtime_state.map(|state| (metal_index, state)), }, )); } else if role_is("texture") { diff --git a/src/reflect/mod.rs b/src/reflect/mod.rs index 0c7ebfcd5..84fbe36cb 100644 --- a/src/reflect/mod.rs +++ b/src/reflect/mod.rs @@ -54,7 +54,9 @@ mod footprint; /// /// v22 replaces the overlapping 32-wide descriptor bases with checked, non-overlapping resource /// bands and reserves a separate high range for translator-owned descriptors. -pub const REFLECTION_VERSION: u32 = 23; +/// v24 records caller-provided runtime storage-image format specialization and the exact explicit +/// SPIR-V format (or formatless `Unknown`) emitted for each Metal texture index. +pub const REFLECTION_VERSION: u32 = 24; /// The single descriptor set every Metal-facing resource is bound in. The interface pass hardcodes /// `DescriptorSet 0` for every resource (buffers, textures, samplers, color inputs). @@ -138,6 +140,9 @@ pub const STORAGE_TEXTURE_BINDING_RANGE: DescriptorBindingRange = DescriptorBind start: STORAGE_TEXTURE_BINDING_BASE, end: 608, }; +/// 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. pub const SYNTHETIC_BINDING_BASE: u32 = 640; @@ -590,6 +595,124 @@ pub struct RuntimeSamplerSpecialization { pub state: RuntimeSamplerState, } +/// Concrete storage-image format supplied by the pipeline for a dynamically bound Metal texture. +/// +/// Most formats have an exact SPIR-V `ImageFormat`. `Bgra8Unorm` deliberately does not: SPIR-V has +/// no BGRA storage-image format token, so it can be used only through `ImageFormat::Unknown` when the +/// host exposes the operation-specific formatless storage-image features. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub enum RuntimeStorageImageFormat { + R8Unorm, + Rgba8Unorm, + Bgra8Unorm, + R16Float, + Rg16Float, + Rgba16Float, + R32Float, + Rgba32Float, + R16Uint, + R32Uint, + Rgba8Uint, + Rgba16Uint, + Rgba32Uint, + R32Sint, + Rgba8Sint, + Rgba32Sint, +} + +impl RuntimeStorageImageFormat { + pub(crate) fn component(self) -> crate::meta::TextureComponent { + use crate::meta::TextureComponent; + match self { + Self::R8Unorm + | Self::Rgba8Unorm + | Self::Bgra8Unorm + | Self::R16Float + | Self::Rg16Float + | Self::Rgba16Float + | Self::R32Float + | Self::Rgba32Float => TextureComponent::Float, + Self::R16Uint + | Self::R32Uint + | Self::Rgba8Uint + | Self::Rgba16Uint + | Self::Rgba32Uint => TextureComponent::Uint, + Self::R32Sint | Self::Rgba8Sint | Self::Rgba32Sint => TextureComponent::Sint, + } + } + + pub(crate) fn explicit_format(self) -> Option { + use crate::meta::TextureFormat; + match self { + Self::R8Unorm => Some(TextureFormat::R8), + Self::Rgba8Unorm => Some(TextureFormat::Rgba8), + Self::R16Float => Some(TextureFormat::R16f), + Self::Rg16Float => Some(TextureFormat::Rg16f), + Self::Rgba16Float => Some(TextureFormat::Rgba16f), + Self::R32Float => Some(TextureFormat::R32f), + Self::Rgba32Float => Some(TextureFormat::Rgba32f), + Self::R16Uint => Some(TextureFormat::R16ui), + Self::R32Uint => Some(TextureFormat::R32ui), + Self::Rgba8Uint => Some(TextureFormat::Rgba8ui), + Self::Rgba16Uint => Some(TextureFormat::Rgba16ui), + Self::Rgba32Uint => Some(TextureFormat::Rgba32ui), + Self::R32Sint => Some(TextureFormat::R32i), + Self::Rgba8Sint => Some(TextureFormat::Rgba8i), + Self::Rgba32Sint => Some(TextureFormat::Rgba32i), + Self::Bgra8Unorm => None, + } + } + + pub(crate) fn supports_atomics(self) -> bool { + matches!(self, Self::R32Uint | Self::R32Sint) + } +} + +/// Host features relevant to one runtime storage-image specialization. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct RuntimeStorageImageCapabilities { + /// The runtime format supports Vulkan storage-image usage. + pub storage_image: bool, + /// The runtime format supports storage-image atomics. + pub storage_image_atomic: bool, + /// `shaderStorageImageReadWithoutFormat` is enabled on the target device. + pub read_without_format: bool, + /// `shaderStorageImageWriteWithoutFormat` is enabled on the target device. + pub write_without_format: bool, +} + +/// Pipeline-provided state for one dynamically bound Metal storage texture. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct RuntimeStorageImageState { + pub format: RuntimeStorageImageFormat, + pub capabilities: RuntimeStorageImageCapabilities, +} + +impl RuntimeStorageImageState { + pub(crate) fn validate(self) -> Result<(), String> { + if !self.capabilities.storage_image { + return Err(format!( + "runtime format {:?} lacks storage-image format support", + self.format + )); + } + Ok(()) + } +} + +/// One runtime storage-image specialization reflected alongside the executable SPIR-V. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct RuntimeStorageImageSpecialization { + pub metal_index: u32, + pub state: RuntimeStorageImageState, + /// Exact explicit SPIR-V format, or `None` when the emitted `OpTypeImage` uses `Unknown`. + pub spirv_format: Option, +} + impl StaticSamplerState { pub(crate) fn from_air_words(words: [u64; 2]) -> Result { let word = words[0]; @@ -992,6 +1115,11 @@ pub struct ShaderReflection { /// that index and describes the executable SPIR-V returned with this reflection. #[cfg_attr(feature = "serde", serde(default))] pub runtime_sampler_specializations: Vec, + /// Pipeline-provided storage-image formats used to specialize dynamically bound Metal + /// textures. The explicit/formatless choice matches the executable SPIR-V returned alongside + /// this reflection. + #[cfg_attr(feature = "serde", serde(default))] + pub runtime_storage_image_specializations: Vec, /// Metal `[[function_constant(N)]]` inventory (index/name/type), so a consumer can discover the /// module's spec-ids without scanning SPIR-V. Populated by the reflected translate paths; empty /// when reflection is built directly from meta (the `from_*` builders do not scan IR). @@ -1442,6 +1570,7 @@ impl ShaderReflection { }), datalayout: None, runtime_sampler_specializations: Vec::new(), + runtime_storage_image_specializations: Vec::new(), function_constants: Vec::new(), } } @@ -1599,6 +1728,7 @@ impl ShaderReflection { fragment_imageblock: None, datalayout: None, runtime_sampler_specializations: Vec::new(), + runtime_storage_image_specializations: Vec::new(), function_constants: Vec::new(), } } @@ -1791,6 +1921,7 @@ impl ShaderReflection { fragment_imageblock: None, datalayout: None, runtime_sampler_specializations: Vec::new(), + runtime_storage_image_specializations: Vec::new(), function_constants: Vec::new(), } } diff --git a/src/reflect/tests.rs b/src/reflect/tests.rs index ff5dc952e..8949f9f12 100644 --- a/src/reflect/tests.rs +++ b/src/reflect/tests.rs @@ -1374,6 +1374,19 @@ fn reflection_serde_covers_every_reflection_field() { lod_bias: 0.0, }, }], + runtime_storage_image_specializations: vec![RuntimeStorageImageSpecialization { + metal_index: 1, + state: RuntimeStorageImageState { + format: RuntimeStorageImageFormat::Rgba8Unorm, + capabilities: RuntimeStorageImageCapabilities { + storage_image: true, + storage_image_atomic: false, + read_without_format: false, + write_without_format: false, + }, + }, + spirv_format: Some(crate::meta::TextureFormat::Rgba8), + }], function_constants: vec![FunctionConstant { index: 0, name: "myConst".to_string(), @@ -1484,3 +1497,34 @@ fn function_tables_are_reflected_as_descriptor_free_link_resources() { && binding.descriptor.is_none() })); } + +#[test] +fn runtime_storage_formats_have_complete_component_and_spirv_mappings() { + use crate::meta::{TextureComponent as C, TextureFormat as F}; + use RuntimeStorageImageFormat as R; + + for (runtime, component, explicit) in [ + (R::R8Unorm, C::Float, Some(F::R8)), + (R::Rgba8Unorm, C::Float, Some(F::Rgba8)), + (R::Bgra8Unorm, C::Float, None), + (R::R16Float, C::Float, Some(F::R16f)), + (R::Rg16Float, C::Float, Some(F::Rg16f)), + (R::Rgba16Float, C::Float, Some(F::Rgba16f)), + (R::R32Float, C::Float, Some(F::R32f)), + (R::Rgba32Float, C::Float, Some(F::Rgba32f)), + (R::R16Uint, C::Uint, Some(F::R16ui)), + (R::R32Uint, C::Uint, Some(F::R32ui)), + (R::Rgba8Uint, C::Uint, Some(F::Rgba8ui)), + (R::Rgba16Uint, C::Uint, Some(F::Rgba16ui)), + (R::Rgba32Uint, C::Uint, Some(F::Rgba32ui)), + (R::R32Sint, C::Sint, Some(F::R32i)), + (R::Rgba8Sint, C::Sint, Some(F::Rgba8i)), + (R::Rgba32Sint, C::Sint, Some(F::Rgba32i)), + ] { + assert_eq!(runtime.component(), component, "{runtime:?}"); + assert_eq!(runtime.explicit_format(), explicit, "{runtime:?}"); + } + assert!(R::R32Uint.supports_atomics()); + assert!(R::R32Sint.supports_atomics()); + assert!(!R::Rgba32Uint.supports_atomics()); +} diff --git a/validation/src/candidate.rs b/validation/src/candidate.rs index f19e5cc47..0da2bcf25 100644 --- a/validation/src/candidate.rs +++ b/validation/src/candidate.rs @@ -13,7 +13,7 @@ use base64::Engine as _; use metal2vulkan::reflect::ShaderReflection; use std::path::Path; -pub const EXECUTOR_ABI: &str = "vulkan-literal-resources-v27"; +pub const EXECUTOR_ABI: &str = "vulkan-literal-resources-v28"; pub fn execute_case( root: &Path, diff --git a/validation/src/case.rs b/validation/src/case.rs index fcd110f37..411e7d762 100644 --- a/validation/src/case.rs +++ b/validation/src/case.rs @@ -713,6 +713,43 @@ impl TextureFormat { Self::Depth32Float => 4, } } + + fn runtime_storage_specialization( + self, + ) -> Result { + use metal2vulkan::reflect::{ + RuntimeStorageImageCapabilities, RuntimeStorageImageFormat, RuntimeStorageImageState, + }; + let format = match self { + Self::R8Unorm => RuntimeStorageImageFormat::R8Unorm, + Self::Rgba8Unorm => RuntimeStorageImageFormat::Rgba8Unorm, + Self::Rgba8Uint => RuntimeStorageImageFormat::Rgba8Uint, + Self::Rgba8Sint => RuntimeStorageImageFormat::Rgba8Sint, + Self::R16Float => RuntimeStorageImageFormat::R16Float, + Self::R16Uint => RuntimeStorageImageFormat::R16Uint, + Self::Rg16Float => RuntimeStorageImageFormat::Rg16Float, + Self::Rgba16Float => RuntimeStorageImageFormat::Rgba16Float, + Self::Rgba16Uint => RuntimeStorageImageFormat::Rgba16Uint, + Self::R32Uint => RuntimeStorageImageFormat::R32Uint, + Self::R32Sint => RuntimeStorageImageFormat::R32Sint, + Self::R32Float => RuntimeStorageImageFormat::R32Float, + Self::Rgba32Uint => RuntimeStorageImageFormat::Rgba32Uint, + Self::Rgba32Sint => RuntimeStorageImageFormat::Rgba32Sint, + Self::Rgba32Float => RuntimeStorageImageFormat::Rgba32Float, + Self::Depth32Float => { + return Err("depth formats cannot specialize a storage image".into()); + } + }; + Ok(RuntimeStorageImageState { + format, + capabilities: RuntimeStorageImageCapabilities { + storage_image: true, + storage_image_atomic: matches!(self, Self::R32Uint | Self::R32Sint), + read_without_format: false, + write_without_format: false, + }, + }) + } } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] @@ -793,6 +830,22 @@ pub(crate) fn product_transform_options( options = options.with_runtime_sampler(sampler.binding, sampler.runtime_specialization())?; } + for texture in &case.textures { + if texture.role != ResourceRole::Input { + options = options.with_runtime_storage_image( + texture.binding, + texture.format.runtime_storage_specialization()?, + )?; + } + } + for texture in &case.texture_arrays { + if texture.role != ResourceRole::Input { + options = options.with_runtime_storage_image( + texture.binding, + texture.format.runtime_storage_specialization()?, + )?; + } + } Ok(options) } @@ -2797,6 +2850,47 @@ mod tests { assert!(error.contains("mixed min/mag"), "{error}"); } + #[test] + fn authored_storage_texture_format_is_the_product_specialization_input() { + let mut case = example(); + case.textures.push(TextureResource { + binding: 4, + role: ResourceRole::Output, + texture_type: TextureType::D2, + format: TextureFormat::Rgba8Unorm, + dimensions: [2, 2, 1], + sample_count: 1, + bytes_b64: None, + initial_bytes_b64: None, + }); + case.texture_arrays.push(TextureArrayResource { + binding: 6, + role: ResourceRole::InOut, + texture_type: TextureType::D2, + format: TextureFormat::R32Uint, + sample_count: 1, + elements: vec![TextureArrayElement { + dimensions: [1, 1, 1], + bytes_b64: None, + initial_bytes_b64: Some("AAAAAA==".into()), + }], + }); + + let options = product_transform_options(&case).expect("authored storage specialization"); + assert_eq!( + options.runtime_storage_image_states[4] + .expect("single storage texture") + .format, + metal2vulkan::reflect::RuntimeStorageImageFormat::Rgba8Unorm + ); + let array = options.runtime_storage_image_states[6].expect("storage texture array"); + assert_eq!( + array.format, + metal2vulkan::reflect::RuntimeStorageImageFormat::R32Uint + ); + assert!(array.capabilities.storage_image_atomic); + } + #[test] fn fragment_depth_stencil_attachment_has_exact_aspect_bytes_and_selection() { let mut case = example(); diff --git a/validation/src/check.rs b/validation/src/check.rs index 37ed2a3e6..157f12035 100644 --- a/validation/src/check.rs +++ b/validation/src/check.rs @@ -917,10 +917,16 @@ fn validate_texture_shape( } let exact_storage_format = shape.storage_format.map(|format| match format { + ReflectedFormat::R8 => TextureFormat::R8Unorm, + ReflectedFormat::Rgba8 => TextureFormat::Rgba8Unorm, ReflectedFormat::R16f => TextureFormat::R16Float, + ReflectedFormat::R16ui => TextureFormat::R16Uint, ReflectedFormat::Rg16f => TextureFormat::Rg16Float, ReflectedFormat::R32f => TextureFormat::R32Float, + ReflectedFormat::R32i => TextureFormat::R32Sint, ReflectedFormat::R32ui => TextureFormat::R32Uint, + ReflectedFormat::Rgba32i => TextureFormat::Rgba32Sint, + ReflectedFormat::Rgba32ui => TextureFormat::Rgba32Uint, ReflectedFormat::Rgba32f => TextureFormat::Rgba32Float, ReflectedFormat::Rgba16f => TextureFormat::Rgba16Float, ReflectedFormat::Rgba8ui => TextureFormat::Rgba8Uint, diff --git a/validation/src/executor_contract.rs b/validation/src/executor_contract.rs index fc2c8ef9b..36f507504 100644 --- a/validation/src/executor_contract.rs +++ b/validation/src/executor_contract.rs @@ -149,7 +149,16 @@ pub fn unsupported_reflection_requirements( if shape.storage_format.is_some_and(|format| { !matches!( format, - ReflectedTextureFormat::R32f + ReflectedTextureFormat::R8 + | ReflectedTextureFormat::Rgba8 + | ReflectedTextureFormat::R16f + | ReflectedTextureFormat::R16ui + | ReflectedTextureFormat::Rg16f + | ReflectedTextureFormat::R32i + | ReflectedTextureFormat::R32f + | ReflectedTextureFormat::R32ui + | ReflectedTextureFormat::Rgba32i + | ReflectedTextureFormat::Rgba32ui | ReflectedTextureFormat::Rgba32f | ReflectedTextureFormat::Rgba16f | ReflectedTextureFormat::Rgba8ui