diff --git a/crates/metal2vulkan-rt/src/tests/draw.rs b/crates/metal2vulkan-rt/src/tests/draw.rs index 6774df3c2..3bc3ed501 100644 --- a/crates/metal2vulkan-rt/src/tests/draw.rs +++ b/crates/metal2vulkan-rt/src/tests/draw.rs @@ -96,7 +96,9 @@ mod on_device { use metal2vulkan::pipeline::{ VertexAttributeDescriptor, VertexBufferLayoutDescriptor, VertexDescriptor, }; - use metal2vulkan_devtools::{engine_dir, fixtures_dir, llvm_assemble, AssembleError}; + use metal2vulkan_devtools::{ + engine_dir, fixtures_dir, llvm_assemble, llvm_assemble_text, AssembleError, + }; use std::path::Path; /// The side of the targets. @@ -565,6 +567,106 @@ mod on_device { }); } + /// A fragment function that reads the texture `t`, which the boolean constant 0 gates, at + /// (0, 0) on its one path, and returns the texel plus (0, 1, 0, 0). + const ABSENT_READ: &str = r#"target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32" +target triple = "air64_v28-apple-macosx26.0.0" + +@has_t.MTL_FC_INIT_0_b = linkonce_odr hidden local_unnamed_addr addrspace(2) externally_initialized constant i8 undef, section "air.fc_initializer", align 1 +@__metal_implicit_fc_pred_0 = internal addrspace(2) global i8 0, align 1 +@llvm.global_ctors = appending global [1 x { i32, ptr, ptr }] [{ i32, ptr, ptr } { i32 65535, ptr @_GLOBAL__sub_I_, ptr null }] + +define <4 x float> @absent_read_fragment(ptr addrspace(1) %t) { + %s = tail call ptr addrspace(2) @air.get_read_sampler() + %r = tail call { <4 x float>, i8 } @air.read_texture_2d.v4f32(ptr addrspace(1) %t, ptr addrspace(2) %s, <2 x i32> zeroinitializer, <2 x i32> zeroinitializer, i32 0, i32 1) + %v = extractvalue { <4 x float>, i8 } %r, 0 + %c = fadd <4 x float> %v, + ret <4 x float> %c +} + +declare ptr addrspace(2) @air.get_read_sampler() +declare { <4 x float>, i8 } @air.read_texture_2d.v4f32(ptr addrspace(1), ptr addrspace(2), <2 x i32>, <2 x i32>, i32, i32) +declare i8 @air.normalize_function_constant_predicate.i8(i8) + +define internal void @_GLOBAL__sub_I_() section "air.static_init" { + %1 = load i8, ptr addrspace(2) @has_t.MTL_FC_INIT_0_b, align 1 + %2 = tail call i8 @air.normalize_function_constant_predicate.i8(i8 %1) + store i8 %2, ptr addrspace(2) @__metal_implicit_fc_pred_0, align 1 + ret void +} + +!air.fragment = !{!0} +!air.function_constants = !{!10} +!air.version = !{!20} +!air.language_version = !{!21} + +!0 = !{ptr @absent_read_fragment, !1, !3} +!1 = !{!2} +!2 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"float4", !"air.arg_name", !"color"} +!3 = !{!4} +!4 = !{i32 0, !"air.function_constant", !5, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.read", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"t"} +!5 = !{ptr addrspace(2) @__metal_implicit_fc_pred_0, !"bool", !"has_t"} +!10 = !{ptr addrspace(2) @has_t.MTL_FC_INIT_0_b, !"bool", !"has_t", i32 0} +!20 = !{i32 2, i32 8, i32 0} +!21 = !{!"Metal", i32 4, i32 0, i32 0} +"#; + + /// A fragment function's read of a texture its function constants removed takes zero and + /// marks no status: the pipeline builds, every pixel is the function's (0, 1, 0, 0), and the + /// command buffer completes with no error. + #[test] + fn every_device_draws_zero_for_a_fragment_s_read_of_a_removed_texture() { + let Some(examples) = examples() else { + return; + }; + let bitcode = match llvm_assemble_text(ABSENT_READ) { + Ok(bitcode) => bitcode, + Err(AssembleError::Missing(why)) => { + eprintln!("SKIPPED: {why}"); + return; + } + Err(error) => panic!("the fragment: {error:?}"), + }; + let library = Library::from_air(&bitcode).expect("the library"); + let mut fragment = FunctionDescriptor::new( + library + .function("absent_read_fragment") + .expect("the function"), + ); + fragment.constants = FunctionConstantValues::defaults() + .with_index(0, FunctionConstantValue::new(DataType::Bool, [0])); + fragment.specialized = true; + let mut d = RenderPipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new( + examples.function("colored_vertex").expect("the function"), + ))); + d.fragment = Some(StageSource::Function(fragment)); + d.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm)); + each_device("draw_absent_read", |name, _, device| { + let state = state(name, &device, &d); + let mut buffers = Buffers::new(&device); + let (positions, colors) = vertices(&device, &mut buffers); + let color = target( + &device, + PixelFormat::RGBA8Unorm, + TextureUsage::RENDER_TARGET, + ); + let queue = device.new_command_queue(4).expect("a queue"); + let command_buffer = queue.command_buffer().expect("a command buffer"); + let mut encoder = (command_buffer.render_command_encoder(&pass(&color, None))) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let draw = |result: Result<(), Error>| result.unwrap_or_else(|e| panic!("{name}: {e}")); + draw(encoder.set_render_pipeline_state(&state)); + draw(encoder.set_vertex_buffer(Some(&positions), 0, 0)); + draw(encoder.set_vertex_buffer(Some(&colors), 0, 1)); + draw(encoder.draw_primitives(PrimitiveType::Triangle, 3, 3, 1, 0)); + encoder.end_encoding(); + run(name, &command_buffer); + let want = texels(|_, _| [0.0, 1.0, 0.0, 0.0]); + assert_eq!(read(&color, 4), want, "{name}: the texels"); + println!("{name}: the removed texture's read took zero in every pixel"); + }); + } + /// `[[stage_in]]` attributes come from a vertex buffer, and from `set_vertex_bytes`' copy. #[test] fn every_device_fetches_vertex_attributes_from_vertex_buffers_and_bytes() { diff --git a/crates/metal2vulkan-rt/src/tests/translate.rs b/crates/metal2vulkan-rt/src/tests/translate.rs index 8d0d195e8..01bcb9e8c 100644 --- a/crates/metal2vulkan-rt/src/tests/translate.rs +++ b/crates/metal2vulkan-rt/src/tests/translate.rs @@ -8,7 +8,7 @@ //! first-use wait the counters record. Vector accesses through pointers cast from a `uint` //! buffer land at their own addresses, 4, 8 or 12 bytes past a multiple of 16, as Metal places them. //! An access through a buffer argument at 2 GiB and past lands there, on every device that can -//! allocate the buffer. +//! allocate the buffer. A read of a texture the kernel's function constants removed takes zero. //! //! `llvm-as` assembles the kernels; without it a test skips visibly. @@ -1714,6 +1714,109 @@ mod on_device { }); } + /// A kernel whose one texture `t`, which the boolean constant 0 gates, it reads at (0, 0) on + /// its one path, storing the texel and `t`'s width into words 0 to 4 of `out`. + const ABSENT_READ: &str = r#"target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32" +target triple = "air64_v28-apple-macosx26.0.0" + +@has_t.MTL_FC_INIT_0_b = linkonce_odr hidden local_unnamed_addr addrspace(2) externally_initialized constant i8 undef, section "air.fc_initializer", align 1 +@__metal_implicit_fc_pred_0 = internal addrspace(2) global i8 0, align 1 +@llvm.global_ctors = appending global [1 x { i32, ptr, ptr }] [{ i32, ptr, ptr } { i32 65535, ptr @_GLOBAL__sub_I_, ptr null }] + +define void @absent_read_kernel(ptr addrspace(1) %t, ptr addrspace(1) %out) { + %s = tail call ptr addrspace(2) @air.get_read_sampler() + %r = tail call { <4 x float>, i8 } @air.read_texture_2d.v4f32(ptr addrspace(1) %t, ptr addrspace(2) %s, <2 x i32> zeroinitializer, <2 x i32> zeroinitializer, i32 0, i32 1) + %v = extractvalue { <4 x float>, i8 } %r, 0 + store <4 x float> %v, ptr addrspace(1) %out, align 4 + %w = tail call i32 @air.get_width_texture_2d(ptr addrspace(1) %t, i32 0) + %o = getelementptr inbounds i32, ptr addrspace(1) %out, i64 4 + store i32 %w, ptr addrspace(1) %o, align 4 + ret void +} + +declare ptr addrspace(2) @air.get_read_sampler() +declare { <4 x float>, i8 } @air.read_texture_2d.v4f32(ptr addrspace(1), ptr addrspace(2), <2 x i32>, <2 x i32>, i32, i32) +declare i32 @air.get_width_texture_2d(ptr addrspace(1), i32) +declare i8 @air.normalize_function_constant_predicate.i8(i8) + +define internal void @_GLOBAL__sub_I_() section "air.static_init" { + %1 = load i8, ptr addrspace(2) @has_t.MTL_FC_INIT_0_b, align 1 + %2 = tail call i8 @air.normalize_function_constant_predicate.i8(i8 %1) + store i8 %2, ptr addrspace(2) @__metal_implicit_fc_pred_0, align 1 + ret void +} + +!air.kernel = !{!0} +!air.function_constants = !{!10} +!air.version = !{!20} +!air.language_version = !{!21} + +!0 = !{ptr @absent_read_kernel, !1, !2} +!1 = !{} +!2 = !{!3, !4} +!3 = !{i32 0, !"air.function_constant", !5, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.read", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"t"} +!4 = !{i32 1, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"out"} +!5 = !{ptr addrspace(2) @__metal_implicit_fc_pred_0, !"bool", !"has_t"} +!10 = !{ptr addrspace(2) @has_t.MTL_FC_INIT_0_b, !"bool", !"has_t", i32 0} +!20 = !{i32 2, i32 8, i32 0} +!21 = !{!"Metal", i32 4, i32 0, i32 0} +"#; + + /// A kernel's read of a texture its function constants removed takes zero and marks no + /// status, so the state is made and the dispatch runs: the read's texel and the texture's + /// width land as zeros over words that held 0xFFFF_FFFF, and the command buffer completes + /// with no error. + #[test] + fn every_device_dispatches_a_kernel_whose_read_of_a_removed_texture_takes_zero() { + let bitcode = match metal2vulkan_devtools::llvm_assemble_text(ABSENT_READ) { + Ok(bitcode) => bitcode, + Err(AssembleError::Missing(why)) => { + eprintln!("SKIPPED: {why}"); + return; + } + Err(error) => panic!("absent_read_kernel: {error:?}"), + }; + let library = Library::from_air(&bitcode).expect("the library"); + let mut function = + FunctionDescriptor::new(library.function("absent_read_kernel").expect("the kernel")); + function.constants = metal2vulkan::library::FunctionConstantValues::defaults().with_index( + 0, + metal2vulkan::library::FunctionConstantValue::new( + metal2vulkan::metal::DataType::Bool, + [0], + ), + ); + function.specialized = true; + let descriptor = ComputePipelineDescriptor::new(StageSource::Function(function)); + each_device("compute_absent_read", |name, _, device| { + let state = state(name, &device, &descriptor); + let mut buffers = Buffers::new(&device, 4096); + let out = buffers.buffer(32); + write(&out, 0, &le_bytes(&[u32::MAX; 8])); + let queue = device.new_command_queue(4).expect("a queue"); + let command_buffer = queue.command_buffer().expect("a command buffer"); + let mut encoder = command_buffer + .compute_command_encoder(DispatchType::Serial) + .expect("an encoder"); + encoder.set_compute_pipeline_state(&state).expect("a state"); + encoder.set_buffer(Some(&out), 0, 0).expect("a buffer"); + encoder + .dispatch_threadgroups([1, 1, 1], [1, 1, 1]) + .unwrap_or_else(|error| panic!("{name}: {error}")); + encoder.end_encoding(); + command_buffer.commit().expect("a commit"); + finished(name, &command_buffer); + assert_eq!(command_buffer.error(), None, "{name}"); + let want = [0, 0, 0, 0, 0, u32::MAX, u32::MAX, u32::MAX]; + assert_eq!( + words(&out, 0, 8), + want, + "{name}: the texel, the width, and the rest" + ); + println!("{name}: the removed texture's read and width took zero"); + }); + } + /// `vwp_vec16` takes its `float4 *` arguments' addresses to be multiples of 16 and `vwp_words` /// its `uint *` arguments' multiples of 4 (`RuntimeFact::AddressAlignment`). A dispatch with /// either argument bound off that alignment (`vwp_words`'s 1 and 3 bytes past each word phase, diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 0383cd261..5680fb78a 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -61,7 +61,7 @@ mod tests; /// unchanged version, and its bless records the version. Independent of the crate's version and of /// [`ARTIFACT_FORMAT_VERSION`]. The commit that bumps it says what changed; this comment keeps no /// history. -pub const SEMANTICS_VERSION: u32 = 2178; +pub const SEMANTICS_VERSION: u32 = 2179; /// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the /// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another diff --git a/crates/metal2vulkan/src/device/profile.rs b/crates/metal2vulkan/src/device/profile.rs index d846a386a..b6ebd640b 100644 --- a/crates/metal2vulkan/src/device/profile.rs +++ b/crates/metal2vulkan/src/device/profile.rs @@ -144,6 +144,12 @@ impl DeviceProfile { self.facts.deep_threadgroups } + /// What a read of an argument the pipeline's function constants removed does beside taking + /// zero. + pub(crate) fn absent_reads(&self) -> AbsentReads { + self.facts.absent_reads + } + /// The profile's fields: internal; the profile is opaque to consumers, who compare /// [`DeviceProfile::fingerprint`] and read its facts through the accessors. pub(crate) fn fields(&self) -> &ProfileFields { @@ -591,6 +597,9 @@ pub(crate) struct ProfileFacts { /// How a kernel whose workgroup is its threadgroup runs a deep threadgroup, and the /// threadgroup the device reports it runs. pub(crate) deep_threadgroups: DeepThreadgroups, + /// What a read of an argument the pipeline's function constants removed does beside taking + /// zero. + pub(crate) absent_reads: AbsentReads, } impl ProfileFacts { @@ -606,6 +615,7 @@ impl ProfileFacts { identity_region: IdentityRegion::Grid, oblivious_edge: ObliviousEdge::Partial, deep_threadgroups: DeepThreadgroups::Axes, + absent_reads: AbsentReads::Marked, }; /// `Device::from_queries`': each fact the same on every device. @@ -620,6 +630,7 @@ impl ProfileFacts { identity_region: IdentityRegion::Sized, oblivious_edge: ObliviousEdge::Grid, deep_threadgroups: DeepThreadgroups::OneRow, + absent_reads: AbsentReads::Nil, }; } @@ -682,6 +693,20 @@ pub(crate) enum ObliviousEdge { Grid, } +/// What a read of a texture, sampler or threadgroup memory argument the pipeline's function +/// constants removed does beside taking zero (`lower::access::absent`). Metal gives such a read +/// no value. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum AbsentReads { + /// Where the read runs it sets `StatusBits::ABSENT_ARGUMENT_READ` in the command buffer's + /// `ExecutionStatus` word, which the consumer reports as a failed execution: + /// `Device::new`'s profile. + Marked, + /// It takes zero and writes no status word, a read's zeros and a query's size of 0 being + /// what the nil texture, set 1's element 0, answers too: `Device::from_queries`' profile. + Nil, +} + /// How a kernel whose workgroup is its threadgroup (`lower::dispatch::LocalSizeForm::Spec`) runs /// a threadgroup deeper than the device's `maxComputeWorkGroupSize[2]`, and so what the device /// reports as Metal's `maxThreadsPerThreadgroup` (`MetalDeviceProperties`). diff --git a/crates/metal2vulkan/src/device/tests/profile.rs b/crates/metal2vulkan/src/device/tests/profile.rs index 2ad7c89ee..4afcbcada 100644 --- a/crates/metal2vulkan/src/device/tests/profile.rs +++ b/crates/metal2vulkan/src/device/tests/profile.rs @@ -1225,22 +1225,23 @@ fn large_module_defects_are_keyed_on_anv() { } } -/// The stage bound, two notes, the narrow wrap, the push window and the `half` fused multiply-add -/// are facts of the profile, on every committed profile: `Device::new` bounds a stage only where +/// The stage bound, two notes, the narrow wrap, the push window, the `half` fused multiply-add and +/// the absent read are facts of the profile, on every committed profile: `Device::new` bounds a stage only where /// its driver's identity names a stage-size defect (`StageBound::Defects`), notes the controlled /// `half` pair only where its driver fuses arithmetic into the narrowing (`HalfPairNote::Fused`), /// records implementation-defined reconvergence as the stage's field alone /// (`ReconvergenceNote::Field`), masks every narrow result (`NarrowWrap::Every`), pushes 128 bytes /// to a kernel (`PushWindow::Guaranteed`) and takes the 16-bit `Fma` only where its driver is -/// measured (`HalfFma::Measured`); `Device::from_queries` bounds every stage, notes every pair, -/// notes the reconvergence, masks only the narrow results a use reads, pushes 256 bytes and takes -/// the 16-bit `Fma` under the 16-bit float controls (`Every`, `Every`, `Noted`, `Read`, `Floor`, -/// `Native`). The facts key the fingerprint: a profile of the same fields with another fact is +/// measured (`HalfFma::Measured`), and marks an absent argument's read (`AbsentReads::Marked`); +/// `Device::from_queries` bounds every stage, notes every pair, notes the reconvergence, masks +/// only the narrow results a use reads, pushes 256 bytes, takes the 16-bit `Fma` under the 16-bit +/// float controls and reads an absent argument as zero alone (`Every`, `Every`, `Noted`, `Read`, +/// `Floor`, `Native`, `Nil`). The facts key the fingerprint: a profile of the same fields with another fact is /// another profile, the `half` fused multiply-add's included. #[test] fn the_profiles_facts_follow_its_constructor() { use crate::device::profile::{ - DeviceProfile, HalfFma, HalfPairNote, NarrowWrap, ProfileFacts, PushWindow, + AbsentReads, DeviceProfile, HalfFma, HalfPairNote, NarrowWrap, ProfileFacts, PushWindow, ReconvergenceNote, StageBound, }; for (stem, text) in committed_profiles() { @@ -1270,6 +1271,11 @@ fn the_profiles_facts_follow_its_constructor() { ); let fmas = (old.profile().half_fma(), queries.profile().half_fma()); assert_eq!(fmas, (HalfFma::Measured, HalfFma::Native), "{stem}"); + let reads = ( + old.profile().absent_reads(), + queries.profile().absent_reads(), + ); + assert_eq!(reads, (AbsentReads::Marked, AbsentReads::Nil), "{stem}"); let fields = queries.profile().fields().clone(); for facts in [ ProfileFacts { diff --git a/crates/metal2vulkan/src/lower/access/absent.rs b/crates/metal2vulkan/src/lower/access/absent.rs index d36902867..ae926efa8 100644 --- a/crates/metal2vulkan/src/lower/access/absent.rs +++ b/crates/metal2vulkan/src/lower/access/absent.rs @@ -12,24 +12,31 @@ //! is on the read's path only: a run that never reaches the read is Metal's exactly, and a module //! without one is unchanged. //! +//! On `Device::from_queries`' profile (`AbsentReads::Nil`) the read writes no status: it takes the +//! same zero of its result's type (a read's zeros and a query's size of 0, which the nil +//! texture, set 1's element 0, answers too) and fetches nothing, a write of a removed texture is +//! dropped, and the stage takes no `ExecutionStatus` buffer, push field or fact for it. +//! `Device::new`'s profile marks the status as above. +//! //! A load or atomic of threadgroup memory the constants removed is the same read //! ([`FunctionConstant::AbsentMemory`]), and so is a texture operation on a removed texture or //! sampler that lowering reaches through memory, an aggregate, a table, or a merge //! (`texture::AbsentArgument`), which shares [`require`] and [`mark`]. //! -//! The stage states [`RuntimeFact::AbsentArgumentRead`] and [`RuntimeFact::ExecutionStatus`]. It -//! reaches the buffer by its device address ([`PushField::ExecutionStatusAddress`]) where the -//! device addresses buffers (`bufferDeviceAddress` and `shaderInt64`), and through a storage-buffer -//! binding of its own (`SyntheticBinding::ExecutionStatus`, [`StatusBinding`]) where it does not, -//! one more storage descriptor of the stage: a stage past a per-stage limit with it is refused as -//! `DescriptorCount` (`lower::select`), naming the limit. A vertex or fragment function needs its -//! stage's stores and atomics; a device without them refuses the read as -//! `FunctionConstantArgument`, naming what it needs. +//! Where its reads mark, the stage states [`RuntimeFact::AbsentArgumentRead`] and +//! [`RuntimeFact::ExecutionStatus`]. It reaches the buffer by its device address +//! ([`PushField::ExecutionStatusAddress`]) where the device addresses buffers +//! (`bufferDeviceAddress` and `shaderInt64`), and through a storage-buffer binding of its own +//! (`SyntheticBinding::ExecutionStatus`, [`StatusBinding`]) where it does not, one more storage +//! descriptor of the stage: a stage past a per-stage limit with it is refused as `DescriptorCount` +//! (`lower::select`), naming the limit. A vertex or fragment function needs its stage's stores +//! and atomics; a device without them refuses the read as `FunctionConstantArgument`, naming what +//! it needs. use crate::air::intrinsics::{AirIntrinsic, FunctionConstant}; use crate::air::ir::{Callee, Inst, InstId, InstKind, Type, Value, ValueId}; use crate::bind::status::{StatusBits, StatusWord}; -use crate::device::profile::BufferAccess; +use crate::device::profile::{AbsentReads, BufferAccess}; use crate::device::requirements::VkFeature; use crate::error::{Capability, Error, Feature, Unsupported}; use crate::lower::emit::EmitCx; @@ -44,11 +51,13 @@ use crate::spirv::error::BResult; use crate::spirv::ids::DemoteTy; use crate::spirv::ir::{AtomicOp, BinOp, Constant, Scope, Semantics, Type as SType}; -/// An absent read ([`FunctionConstant::AbsentRead`]): the status write, then zero. +/// An absent read ([`FunctionConstant::AbsentRead`]): the status write where it marks, then zero. #[derive(Clone, Debug, PartialEq, Eq)] pub struct AbsentRead { /// The lowered representation of the read's result; `None` for a read of no result. pub result: Option, + /// Whether it sets the status bit (`AbsentReads::Marked`, [`require`]). + pub marks: bool, } impl AbsentRead { @@ -57,11 +66,15 @@ impl AbsentRead { "access.absent_read" } - /// An upper estimate of the SPIR-V words one read emits: the push field's load and the word's - /// address and pointer (or the binding's access chain), the bit, and the atomic `OR`; the zero - /// is a constant. + /// An upper estimate of the SPIR-V words one read emits: where it marks, the push field's load + /// and the word's address and pointer (or the binding's access chain), the bit, and the atomic + /// `OR`; the zero is a constant. pub fn words(&self) -> u32 { - 32 + if self.marks { + 32 + } else { + 0 + } } } @@ -82,19 +95,24 @@ pub fn select(cx: &mut SelectCx<'_>, at: InstId, inst: &Inst) -> Result None, _ => Some(cx.lowered_repr(Value::Inst(at), inst.ty)?), }; - Ok(Some(AbsentRead { result })) + Ok(Some(AbsentRead { result, marks })) } -/// What an absent read needs, stated for the stage: the `ExecutionStatus` buffer -/// ([`state_status`]), and the stage's stores and atomics; a device without them refuses the read -/// as `FunctionConstantArgument`, naming what it needs. The texture and sampler families' arms on -/// the absent handle need the same. -pub fn require(cx: &mut SelectCx<'_>) -> Result<(), Error> { +/// What an absent read needs, stated for the stage, and whether it marks the status: on a profile +/// whose absent reads mark it (`AbsentReads::Marked`), the `ExecutionStatus` buffer +/// ([`state_status`]) and the stage's stores and atomics, a device without them refusing the read +/// as `FunctionConstantArgument`, naming what it needs; on one whose absent reads read as nil +/// (`AbsentReads::Nil`), nothing, and the read does not mark. The texture and sampler families' +/// arms on the absent handle need the same. +pub fn require(cx: &mut SelectCx<'_>) -> Result { + if cx.profile.absent_reads() == AbsentReads::Nil { + return Ok(false); + } if let Some(StatusShort::Stores(f)) = status_short(cx) { return Err( Unsupported::needs(Feature::FunctionConstantArgument, Capability::Feature(f)).into(), @@ -103,7 +121,7 @@ pub fn require(cx: &mut SelectCx<'_>) -> Result<(), Error> { state_status(cx, StatusBinding::Required); cx.facts .insert(RuntimeFact::AbsentArgumentRead { stage: cx.stage }); - Ok(()) + Ok(true) } /// What the stage lacks to write the command buffer's `ExecutionStatus` words. Each refusal @@ -209,14 +227,17 @@ pub fn declare( } } -/// Emit absent read `s`, whose result is `vid`: set the bit, and define the result as zero. +/// Emit absent read `s`, whose result is `vid`: set the bit where it marks, and define the result +/// as zero. pub fn emit( cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, vid: ValueId, s: &AbsentRead, ) -> BResult<()> { - mark(cx, fb)?; + if s.marks { + mark(cx, fb)?; + } let Some(d) = &s.result else { return Ok(()); }; diff --git a/crates/metal2vulkan/src/lower/texture/mod.rs b/crates/metal2vulkan/src/lower/texture/mod.rs index 40f5a214a..929b53882 100644 --- a/crates/metal2vulkan/src/lower/texture/mod.rs +++ b/crates/metal2vulkan/src/lower/texture/mod.rs @@ -686,11 +686,12 @@ pub enum TextureStrategy { /// An operation on the absent handle, alone or as a switch-at-use's arm. Metal gives a read through /// a removed texture or sampler no value, so a read, query, sample, gather, atomic, or `is_null` is /// the absent read: it marks the command buffer's execution status where it runs -/// (`access::absent::mark`), and yields zero. A write or fence of a removed texture is dropped, as -/// Metal drops one, and marks nothing. +/// (`access::absent::mark`) on a profile whose absent reads mark it, and yields zero. A write or fence of a removed texture is dropped, as Metal drops one, and +/// marks nothing. #[derive(Clone, Debug, PartialEq, Eq)] pub struct AbsentArgument { - /// Whether the operation marks the status: every one but a write or a fence. + /// Whether the operation marks the status: every one but a write or a fence, on a profile + /// whose absent reads mark it (`access::absent::require`). pub marks: bool, /// What it yields: zero of its result's lowered type, or nothing. pub value: NullArm, @@ -708,10 +709,8 @@ impl AbsentArgument { inst: &Inst, t: &crate::air::intrinsics::Texture, ) -> Result { - let marks = !matches!(t.op, TexOp::Write | TexOp::Fence); - if marks { - crate::lower::access::absent::require(cx)?; - } + let marks = !matches!(t.op, TexOp::Write | TexOp::Fence) + && crate::lower::access::absent::require(cx)?; let value = match cx.entry.module.types().get(inst.ty) { Some(crate::air::ir::Type::Void) | None => NullArm::Nothing, _ => NullArm::Zero(cx.lowered_repr(Value::Inst(at), inst.ty)?), diff --git a/crates/metal2vulkan/src/pipeline/compile/tests.rs b/crates/metal2vulkan/src/pipeline/compile/tests.rs index 0aefdb680..db517cebb 100644 --- a/crates/metal2vulkan/src/pipeline/compile/tests.rs +++ b/crates/metal2vulkan/src/pipeline/compile/tests.rs @@ -1274,7 +1274,7 @@ fn the_old_render_descriptor_key_keeps_its_value() { let key = device("moltenvk-m3").render_descriptor_key(&d); let hex: String = key.digest().iter().map(|b| format!("{b:02x}")).collect(); assert_eq!( - hex, "64b84e0f84f29d6744821b2ffb58baf8f1e57b44f4c49e7787c26a42019d8de7", + hex, "16991cf7f184e94d810824b0672eba81c8fd390efc4abe2458c5f506f7ed7f3d", "the old runtime's key of the descriptor" ); } diff --git a/crates/metal2vulkan/src/tests/engine_function_constant_interface.rs b/crates/metal2vulkan/src/tests/engine_function_constant_interface.rs index a065466b1..676993cbf 100644 --- a/crates/metal2vulkan/src/tests/engine_function_constant_interface.rs +++ b/crates/metal2vulkan/src/tests/engine_function_constant_interface.rs @@ -17,6 +17,9 @@ //! aggregates and merges). A write to (or fence of) the gated-off texture itself is dropped, as //! Metal drops it on every device and layer measured. Gated on, the same kernels compile, without //! the fact. +//! - A fragment function's read of a gated-off texture is the same absent read on `Device::new`'s +//! profiles. On `Device::from_queries`' (`AbsentReads::Nil`) it and a kernel's take the same +//! zero and mark nothing: no fact, no status push field or binding. //! - A gated-off input that only feeds an output gated by the same constant is not observed (the //! return stores only declared outputs), so the entry compiles without either. //! - A gated-off value argument whose read nothing observes compiles (the read is `undef`); an @@ -40,8 +43,8 @@ use std::path::Path; use std::sync::Arc; use crate::budget::SPIRV_WORDS; -use crate::device::{DevicePolicy, DeviceProfile}; -use crate::error::{DescriptorError, Error, RuntimeInput}; +use crate::device::{Device, DevicePolicy, DeviceProfile}; +use crate::error::{DescriptorError, Error, Feature, RuntimeInput}; use crate::library::{FunctionArtifact, FunctionConstantValue, FunctionConstantValues}; use crate::metal::DataType; use crate::pipeline::artifact::PrecisionNote; @@ -54,8 +57,8 @@ use crate::pipeline::relocate::relocate; use crate::pipeline::stage_io::{IoRole, StageBuiltin}; use crate::pipeline::sym::{SlotClass, Stage}; use crate::pipeline::testing::{ - engine_dir, fixtures_dir, llvm_assemble, meter, profile, status_reach, status_reach_on, - AssembleError, Scratch, + description, engine_dir, fixtures_dir, llvm_assemble, llvm_assemble_text, meter, profile, + status_reach, status_reach_on, AssembleError, Scratch, StatusReach, }; use crate::spirv::testing::{check_words_valid, committed_profiles}; @@ -785,3 +788,137 @@ fn an_observed_element_of_an_absent_texture_table_is_an_absent_read() { absent_read(&bc, entry, &[(0, false)]); compiles(&bc, entry, &[(0, true)]); } + +/// Two functions whose one texture `t`, which the boolean constant 0 gates, each reads at (0, 0) +/// on its one path: a fragment function returning the texel plus (0, 1, 0, 0), and a kernel +/// storing the texel and `t`'s width into `out`. +const ABSENT_READS: &str = r#" +target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32" +target triple = "air64_v28-apple-macosx26.0.0" + +@has_t.MTL_FC_INIT_0_b = linkonce_odr hidden local_unnamed_addr addrspace(2) externally_initialized constant i8 undef, section "air.fc_initializer", align 1 +@__metal_implicit_fc_pred_0 = internal addrspace(2) global i8 0, align 1 +@llvm.global_ctors = appending global [1 x { i32, ptr, ptr }] [{ i32, ptr, ptr } { i32 65535, ptr @_GLOBAL__sub_I_, ptr null }] + +define <4 x float> @fc_fragment_absent_read(ptr addrspace(1) %t) { + %s = tail call ptr addrspace(2) @air.get_read_sampler() + %r = tail call { <4 x float>, i8 } @air.read_texture_2d.v4f32(ptr addrspace(1) %t, ptr addrspace(2) %s, <2 x i32> zeroinitializer, <2 x i32> zeroinitializer, i32 0, i32 1) + %v = extractvalue { <4 x float>, i8 } %r, 0 + %c = fadd <4 x float> %v, + ret <4 x float> %c +} + +define void @fc_kernel_absent_read(ptr addrspace(1) %t, ptr addrspace(1) %out) { + %s = tail call ptr addrspace(2) @air.get_read_sampler() + %r = tail call { <4 x float>, i8 } @air.read_texture_2d.v4f32(ptr addrspace(1) %t, ptr addrspace(2) %s, <2 x i32> zeroinitializer, <2 x i32> zeroinitializer, i32 0, i32 1) + %v = extractvalue { <4 x float>, i8 } %r, 0 + store <4 x float> %v, ptr addrspace(1) %out, align 4 + %w = tail call i32 @air.get_width_texture_2d(ptr addrspace(1) %t, i32 0) + %o = getelementptr inbounds i32, ptr addrspace(1) %out, i64 4 + store i32 %w, ptr addrspace(1) %o, align 4 + ret void +} + +declare ptr addrspace(2) @air.get_read_sampler() +declare { <4 x float>, i8 } @air.read_texture_2d.v4f32(ptr addrspace(1), ptr addrspace(2), <2 x i32>, <2 x i32>, i32, i32) +declare i32 @air.get_width_texture_2d(ptr addrspace(1), i32) +declare i8 @air.normalize_function_constant_predicate.i8(i8) + +define internal void @_GLOBAL__sub_I_() section "air.static_init" { + %1 = load i8, ptr addrspace(2) @has_t.MTL_FC_INIT_0_b, align 1 + %2 = tail call i8 @air.normalize_function_constant_predicate.i8(i8 %1) + store i8 %2, ptr addrspace(2) @__metal_implicit_fc_pred_0, align 1 + ret void +} + +!air.fragment = !{!0} +!air.kernel = !{!6} +!air.function_constants = !{!10} +!air.version = !{!20} +!air.language_version = !{!21} + +!0 = !{ptr @fc_fragment_absent_read, !1, !3} +!1 = !{!2} +!2 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"float4", !"air.arg_name", !"color"} +!3 = !{!4} +!4 = !{i32 0, !"air.function_constant", !5, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.read", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"t"} +!5 = !{ptr addrspace(2) @__metal_implicit_fc_pred_0, !"bool", !"has_t"} +!6 = !{ptr @fc_kernel_absent_read, !7, !8} +!7 = !{} +!8 = !{!4, !9} +!9 = !{i32 1, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"out"} +!10 = !{ptr addrspace(2) @has_t.MTL_FC_INIT_0_b, !"bool", !"has_t", i32 0} +!20 = !{i32 2, i32 8, i32 0} +!21 = !{!"Metal", i32 4, i32 0, i32 0} +"#; + +/// With `t` gated off, each of [`ABSENT_READS`]' reads is an absent read. On `Device::new`'s +/// profiles it marks the status: the fragment function and the kernel state the read and the +/// `ExecutionStatus` it marks, reached by address where the profile addresses buffers and through +/// the stage's binding of it elsewhere, or, without the stage's stores and atomics, are refused as +/// `FunctionConstantArgument`. On `Device::from_queries`' four drivers (`AbsentReads::Nil`) each +/// takes zero and marks nothing: no fact, no status push field or binding, and no texture slot. +/// Each module validates. +#[test] +fn an_absent_read_marks_through_device_new_and_takes_zero_alone_through_from_queries() { + let bc = match llvm_assemble_text(ABSENT_READS) { + Ok(b) => b, + Err(AssembleError::Missing(why)) => { + eprintln!("SKIPPED: {why}"); + return; + } + Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected the module: {why}"), + }; + let off = [(0, false)]; + let queried: Vec<(&str, Device)> = [ + "moltenvk-m3", + "lavapipe", + "amd-780m-radv", + "nvidia-rtx50-linux", + ] + .into_iter() + .map(|stem| { + let desc = description(stem).expect("description"); + let device = Device::from_queries(desc, DevicePolicy::default()).expect("device"); + (stem, device) + }) + .collect(); + for (entry, stage) in [ + ("fc_fragment_absent_read", Stage::Fragment), + ("fc_kernel_absent_read", Stage::Kernel), + ] { + let read = RuntimeFact::AbsentArgumentRead { stage }; + let mut marked = 0; + for (stem, p) in committed_profiles().expect("profiles") { + match compile_result(&bc, entry, &off, &p) { + Ok(a) => { + assert!(a.facts.contains(&read), "{stem} {entry}: {:?}", a.facts); + assert!( + a.facts.contains(&RuntimeFact::ExecutionStatus), + "{stem} {entry}: {:?}", + a.facts + ); + assert_eq!(status_reach(&a), status_reach_on(&p), "{stem} {entry}"); + validate(&a, &p); + marked += 1; + } + Err(Error::Unsupported(u)) if u.feature == Feature::FunctionConstantArgument => {} + Err(e) => panic!("{stem} {entry}: {e}"), + } + } + assert!(marked > 0, "{entry}: no committed profile marks the read"); + for (stem, device) in &queried { + let p = device.profile(); + let a = compile_result(&bc, entry, &off, p) + .unwrap_or_else(|e| panic!("{stem} {entry}: {e}")); + assert!( + !a.facts.contains(&read) && !a.facts.contains(&RuntimeFact::ExecutionStatus), + "{stem} {entry}: {:?}", + a.facts + ); + assert_eq!(status_reach(&a), StatusReach::None, "{stem} {entry}"); + assert_eq!(texture_slots(&a), Vec::::new(), "{stem} {entry}"); + validate(&a, p); + } + } +} diff --git a/docs/API.md b/docs/API.md index 4506b6c7a..9d8717199 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1516,9 +1516,9 @@ for dependency in &pipeline.dependencies { buffer view; a planned heap's members are textures with images, so only a heap set the consumer keeps for every command (each live texture at its resource ID) holds texture buffers. Push constants carry the values the binder writes per command. A stage that writes the command buffer's `ExecutionStatus` (an absent - argument's read, a `seq_cst` fence, an argument buffer's cubic sampler) reaches it by device - address, a push hole, where the device addresses buffers (`bufferDeviceAddress` and - `shaderInt64`), and through a set-0 storage buffer of its own + argument's read on `Device::new`'s profile, a `seq_cst` fence, an argument buffer's cubic + sampler) reaches it by device address, a push hole, where the device addresses buffers + (`bufferDeviceAddress` and `shaderInt64`), and through a set-0 storage buffer of its own (`SyntheticBinding::ExecutionStatus`) where it does not. That binding counts against the stage's storage-buffer limits: past one, an absent read or a fence is refused (`DescriptorCount`), and a stage that would bind it only to test its argument samplers for a @@ -3451,7 +3451,9 @@ bound. Metal gives no value: its compiler drops or folds such a read, and with its debug layer every such read is zero. Cost: such a read takes zero, Metal's answer under its debug layer, and the command buffer completes, its execution report stating the read (absent_argument_read); without the layer - Metal's compiler drops or folds the read instead. + Metal's compiler drops or folds the read instead. On `Device::from_queries`' profile the read + takes the same zero, a read's zeros and a query's size of 0 as the nil texture answers, but + writes no status and states no fact, so nothing reports it. - `metal2vulkan-degrade-mixed-depth-stencil-resolve` (precision). `MixedDepthStencilResolve`: A render pass whose one depth/stencil texture stores and resolves its depth (`StoreAndMultisampleResolve`) while it resolves its stencil alone (`MultisampleResolve`), which