From 6c1dff3f09d88210579fe796d3a628af0d3db80d Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Sat, 21 Nov 2026 17:15:11 -0800 Subject: [PATCH] Translator: under the identity domains, constexpr samplers a lane chooses among beside an argument buffer's texture are one sample through the set-1 sampler array (SEMANTICS 2265) Some kernels sample a texture their argument buffer holds through a sampler that the run picks among constexpr samplers with consecutive handles: a program-scope table of samplers read at an index only the run knows. Under the identity domains, the runtime's, each such sampling was a switch over the candidates: one arm per candidate, each a NonUniform sample of the heap element through that candidate's set-1 sampler, and a null arm. RADV wraps each NonUniform sample in its own waterfall loop (read_first_invocation). The 780M library's heaviest kernel holds 284 such switches of eight arms, so 2,272 samples and 2,272 driver loops. Its cold create on a 780M peaked at 7.8 GiB. select_heap_array now takes the identity domains too. Where every candidate is a constexpr sampler, their handles are consecutive, the use is not tangled (no fragment implicit level), and every candidate's sampling is the same but for its sampler, the sampling is one sample. It reads the set-1 sampler array of its use, NonUniform, at the pushed index (PushField::ConstexprSampler) of the candidate the handle names. emit::identity_element selects that index among the candidates' at run time. A handle outside the array still reads zero. finish pushes each candidate's index and records the use in SamplerPlan::heap_array_identity in place of a binding. Sampling::words counts each candidate's selection (Source::HeapArray::pushed, 0 outside the identity domains, so the resident-table domains' weights are unchanged). Under the identity domains the switch stays where the sampling compares, reads an integer class, or reads pixel coordinates. Metal's bicubic filter on an argument buffer's texture is refused before this (bicubic::check). Raw-texel states do not arise here, because the element is read in its declared class. The resident-table domains keep their form unchanged. One form for every device: the runtime's floor requires shaderSampledImageArrayNonUniformIndexing (floor.rs), every committed profile reports it, and a heap image sampled at all already needs it (texture/slot.rs). The form is ported from 4b7d9d48ef (steelbrain/privarena-sampler-b, unlanded) and narrowed to the ruled domain. SEMANTICS_VERSION 2264 -> 2265. The golden table and the old render descriptor key get re-blessed at the pin: m3-max-65203 shows "bless due" with exactly 16 cells changed, all engine/sampler_table.ll sampler_table_held, one per committed profile. Tests: - engine_identity's chosen_constexpr_samplers_beside_an_argument_buffer_texture_are_one_sample_where_alike (replaces ..._is_a_switch_over_them). On every committed profile under the identity domains, a kernel's float sample through three chosen constexpr samplers is one sample: one sampled image, no switch, one ConstexprSampler pushed per candidate, and L3 passes. The switch stays, with a sampled image per candidate, for pixel coordinates (two linear pixel samplers that differ only in their border color), an integer texture, a comparison and a fragment's implicit level. The resident-table domains take their set-0 array for all but the fragment case, which shows the candidates' samplings are alike and only the identity domains' rule keeps the switch. - argument_sampling's every_device_samples_an_argument_buffers_texture_through_a_table_of_constexpr_samplers now reads the module the device's translator gives sampler_table_held, asserts 1 sample and 0 switches, and prints that, then compares each of the 20 texels with Metal's answer as measured on an Apple M3 Max. The fixture has four candidates. The form is the same for any count of two or more, so it covers the eight-arm sites, and its texels are M3-measured. Verified: - Compile: m3-max-65200 (fmt, signatures, refusal surface, clippy plain / m2v_gpu / m2v_cpu_icd, workspace Rustdoc -D warnings), m3-max-65203 (translator suite 3210 passed, lavapipe runtime suite 625 passed). - The execution test passed on llvmpipe (65203), RTX 3090 (65223), RX 7900 XTX (65224) and Iris Xe (65225). - Rows: development 21baf79e79 against this tree, one runner (probe 7faf595d33 / 88125605ae, its probe variable choosing the arm), every run cold, validation layer off, arms A B B A in one exclusive job per card: - ec13339c (780M library, 284 sampler switches) on a Radeon 780M, RADV, job m3-max-65216: helper peak 7,772 / 7,773 MiB -> 816 / 819 MiB (89.5% less), driver compile 63.39 / 62.34 s -> 21.94 / 21.55 s (65.4% less). Final NIR (RADV_DEBUG=nir): loops 2,571 -> 583, read_first_invocation 2,272 -> 568, blocks 34,289 -> 17,533, phis 27,537 -> 13,526. - The same kernel on an RTX 3090, job m3-max-65238: 2,447 / 2,443 MiB -> 1,975 / 1,976 MiB (19.2% less), 57.72 / 57.70 s -> 51.88 / 51.85 s (10.1% less). - d45af8b7 (780M library, 70 sampler switches) on an Iris Xe, ANV, job m3-max-65240: 4,528 / 4,530 MiB -> 2,622 / 2,622 MiB (42.1% less), 135.54 / 136.55 s -> 67.17 / 67.28 s (50.6% less). - Our module for ec13339c on the 780M's profile (job m3-max-65215): blocks 22,746 -> 19,906, explicit-level samples 2,272 -> 284, OpSwitch 625 -> 341, spirv-val clean. - The ledger over both libraries' 252 rows, plain and partial, both arms (job m3-max-65215): every row translates on both arms, none past 20 s, slowest 5.19 s, k12 unchanged at 440.2 MiB, and no rise. 20 rows of 10 kernels change, all of the 780M library. The Iris library's kernels sample through the program's own switches, one constexpr sampler per case, so no lane chooses a sampler there and its modules are byte-equal (probes m3-max-65233, 65241, 65246). --- .../src/tests/argument_sampling.rs | 34 ++- crates/metal2vulkan/src/cache/mod.rs | 2 +- crates/metal2vulkan/src/lower/sampler/emit.rs | 73 +++++ crates/metal2vulkan/src/lower/sampler/mod.rs | 55 +++- .../metal2vulkan/src/lower/sampler/select.rs | 48 ++-- crates/metal2vulkan/src/lower/select.rs | 5 +- .../metal2vulkan/src/tests/engine_handles.rs | 12 +- .../metal2vulkan/src/tests/engine_identity.rs | 267 ++++++++++++++++-- docs/API.md | 10 +- 9 files changed, 433 insertions(+), 73 deletions(-) diff --git a/crates/metal2vulkan-runtime/src/tests/argument_sampling.rs b/crates/metal2vulkan-runtime/src/tests/argument_sampling.rs index 8a4ebaf9b..adead76cc 100644 --- a/crates/metal2vulkan-runtime/src/tests/argument_sampling.rs +++ b/crates/metal2vulkan-runtime/src/tests/argument_sampling.rs @@ -24,6 +24,27 @@ mod on_device { }; use metal2vulkan_devtools::{fixtures_dir, llvm_assemble, AssembleError}; + /// The SPIR-V opcodes `OpImageSampleExplicitLod` and `OpSwitch`. + const OP_IMAGE_SAMPLE_EXPLICIT_LOD: u32 = 88; + const OP_SWITCH: u32 = 251; + + /// How many samples at an explicit level and how many switches the module holds that + /// `device`'s translator gives the kernel of `descriptor`. + fn samples_and_switches( + name: &str, + device: &Device, + descriptor: &ComputePipelineDescriptor, + ) -> (usize, usize) { + let pipeline = (device.translator()) + .compile_compute_pipeline(descriptor, &metal2vulkan::Budget::standard()) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let ops: Vec = (crate::tests::spirv_instructions(&pipeline.stage.spirv).iter()) + .map(|inst| inst[0] & 0xffff) + .collect(); + let of = |op: u32| ops.iter().filter(|o| **o == op).count(); + (of(OP_IMAGE_SAMPLE_EXPLICIT_LOD), of(OP_SWITCH)) + } + /// The side of each texture: one texel per thread of a 2 by 2 grid. const SIDE: u32 = 2; /// The constexpr sampler's index the test gives `hs_sample`. @@ -406,9 +427,10 @@ mod on_device { /// the 4 by 1 texture its argument buffer holds (red, green, blue, white) at `x = xs[i]` /// through `samplers[which[i]]`, a program-scope table of four constexpr nearest samplers /// (repeat, clamp to edge, mirrored repeat, clamp to zero) read at the index `which[i] = s` - /// only the run knows, and writes the texel. Under the identity domains the four candidates - /// are a switch over them, each arm sampling through its constexpr sampler's index. The - /// answers are Metal's, measured on an Apple M3 Max under macOS 27.0.1 + /// only the run knows, and writes the texel. The four candidates differ only in the sampler, so + /// the device's translator gives the kernel one sample, through the set-1 sampler array at the + /// pushed index of the candidate `which[i]` names, and no switch, which the test reads from the + /// module and prints. The answers are Metal's, measured on an Apple M3 Max under macOS 27.0.1 /// (`metal2vulkan-conformance/probes/sampler_table.m`): by coordinate (texel units -0.5, 4.5, /// -1.5, 2.5 and 5.5), through the four samplers in order, white, red, red, zero; red, white, /// white, zero; blue, red, green, zero; blue four times; green, white, blue, zero. @@ -444,6 +466,8 @@ mod on_device { let descriptor = ComputePipelineDescriptor::new(StageSource::Function( FunctionDescriptor::new(function), )); + let form = samples_and_switches(name, &device, &descriptor); + assert_eq!(form, (1, 0), "{name}: the module's samples and switches"); let state = (device.new_compute_pipeline_state(&descriptor, |samplers| { assert_eq!(samplers.len(), 4, "{name}: {samplers:?}"); Ok((1..=4).collect()) @@ -501,7 +525,9 @@ mod on_device { } drop((command_buffer, queue, state, t)); println!( - "{name}: an argument buffer's texture sampled through a table of constexpr samplers" + "{name}: an argument buffer's texture sampled through a table of constexpr samplers \ + as one sample through the sampler array ({} sample, {} switches)", + form.0, form.1 ); }); } diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 9bf4ed08f..e8bfc020d 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 = 2264; +pub const SEMANTICS_VERSION: u32 = 2265; /// 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/lower/sampler/emit.rs b/crates/metal2vulkan/src/lower/sampler/emit.rs index 0bbf87fac..587afccd9 100644 --- a/crates/metal2vulkan/src/lower/sampler/emit.rs +++ b/crates/metal2vulkan/src/lower/sampler/emit.rs @@ -694,10 +694,43 @@ pub(super) fn sampled_image( }; Ok((si, image, element.live)) } + // Under the identity domains the heap element through the set-1 sampler array's element + // at the pushed index of the candidate the handle names. Source::HeapArray { handle, sampler, key, + .. + } if cx.plan.families.access.identity => { + let Some(use_) = (cx.plan.families.sampler.heap_array_identity) + .get(&key) + .copied() + else { + return Err(cx.fail(format!( + "constexpr sampler array {key:?} has no identity use" + ))); + }; + let Some(g) = cx.decl.families.sampler.identity.get(&use_).copied() else { + return Err(cx.fail(format!("the sampler array of {use_:?} is not declared"))); + }; + let element = heap_element(cx, fb, key.group, handle)?; + let index = identity_element(cx, fb, sampler, key, use_)?; + let base = fb.module().global_value(g)?; + let p = fb.access_chain_non_uniform(base, index)?; + let sampler = fb.load(p, MemAccess::default())?; + let si = fb.sampled_image(element.img, sampler)?; + let image = CombinedImage { + plane: super::plane_of(element.decl.dim), + arrayed: element.decl.arrayed, + texel: element.decl.texel, + }; + Ok((si, image, element.live)) + } + Source::HeapArray { + handle, + sampler, + key, + .. } => { let Some(g) = cx.decl.families.sampler.heap_arrays.get(&key).copied() else { return Err(cx.fail(format!("constexpr sampler array {key:?} is not declared"))); @@ -749,6 +782,46 @@ pub(super) fn array_element( Ok((fb.select(named, i, zero)?, named)) } +/// Under the identity domains, the index in the set-1 sampler array of `use_` of the candidate of +/// constexpr sampler array `key` that sampler handle `sampler` names: that candidate's pushed index +/// (`PushField::ConstexprSampler`), selected among the candidates' at run time, the first's where +/// the handle names none (whose result `sampling_value` makes zero). +fn identity_element( + cx: &mut EmitCx<'_>, + fb: &mut FunctionBuilder<'_>, + sampler: ValueId, + key: super::HeapArrayKey, + use_: SamplerUse, +) -> BResult { + let samplers = usize::try_from(key.array) + .ok() + .and_then(|a| cx.plan.families.sampler.arrays.get(a)) + .map(|a| a.samplers.clone()); + let Some(samplers) = samplers else { + return Err(cx.fail(format!("constexpr sampler array {key:?} is not planned"))); + }; + let (element, _) = array_element(cx, fb, sampler, key)?; + let mut index = None; + for (k, words) in (0u32..).zip(samplers) { + let c = CombinedSampler::new( + SamplerRef::Constexpr(words), + use_.compare, + use_.integer_texture, + ); + let pushed = cx.push_field(fb, crate::pipeline::sym::PushField::ConstexprSampler(c))?; + index = Some(match index { + None => pushed, + Some(v) => { + let k = fb.u32_const(k)?; + let k = fb.module().const_value(k)?; + let is = fb.binary(BinOp::IEqual, element, k)?; + fb.select(is, pushed, v)? + } + }); + } + index.ok_or_else(|| cx.fail("a sampler array without samplers")) +} + /// The word (`metal::sampler::SamplerWord`) of the constexpr sampler at the element of sampling /// `s`'s constexpr sampler array its sampler handle names (`Source::HeapArray`): /// `ConstexprArray::words` selected at run time, element 0's where the handle names none (whose diff --git a/crates/metal2vulkan/src/lower/sampler/mod.rs b/crates/metal2vulkan/src/lower/sampler/mod.rs index fa9b23e83..2e88d5592 100644 --- a/crates/metal2vulkan/src/lower/sampler/mod.rs +++ b/crates/metal2vulkan/src/lower/sampler/mod.rs @@ -19,15 +19,17 @@ //! sampler, is one sampling through a set-0 array of their samplers (`ResourceKind::SamplerArray`, //! one immutable sampler per candidate, its element `NonUniform` and at the handle's distance from //! the first candidate's; a handle outside it reads zero), where the device indexes a sampler array -//! by a value that may differ between invocations (`shaderSampledImageArrayNonUniformIndexing`), -//! outside the identity domains. Any other sampler of several static candidates beside a heap -//! image is a switch-at-use over them, one arm per candidate, each the heap element through that -//! candidate's heap sampler. Under the identity domains a heap image has no heap sampler binding: -//! its runtime or constexpr sampler is the element of the set-1 sampler array of its use that a -//! texture slot's sampling reads there ([`IdentitySampling`]), at the index the sampler slot's -//! pushed resource ID holds or at the constexpr sampler's pushed index -//! (`PushField::ConstexprSampler`), and a sampler of several constexpr candidates is the switch -//! over them. +//! by a value that may differ between invocations (`shaderSampledImageArrayNonUniformIndexing`). +//! Any other sampler of several static candidates beside a heap image is a switch-at-use over +//! them, one arm per candidate, each the heap element through that candidate's heap sampler. Under +//! the identity domains a heap image has no heap sampler binding: its runtime or constexpr sampler +//! is the element of the set-1 sampler array of its use that a texture slot's sampling reads there +//! ([`IdentitySampling`]), at the index the sampler slot's pushed resource ID holds or at the +//! constexpr sampler's pushed index (`PushField::ConstexprSampler`). There a constexpr sampler +//! array is no binding: its sampling reads the set-1 array's element, `NonUniform`, at the pushed +//! index of the candidate the handle names, selected among the candidates' +//! (`emit::identity_element`), where it reads a float class without comparison and in normalized +//! coordinates; the switch over the candidates stays for the rest. //! //! **Argument buffers' samplers** (the sampler half). A heap image sampled through a sampler loaded //! from an argument buffer reads `OpSampledImage` of its heap element and of the heap sampler's @@ -313,6 +315,11 @@ pub(crate) const ELEMENT_WORDS: u32 = 5 + 5 + 6; /// result or zero (a handle outside the array is the switch's null arm) with its constant. pub(crate) const ARRAY_WORDS: u32 = 2 * ELEMENT_WORDS + 3 * 4 + 5 + 4 + 6 + 4; +/// The SPIR-V words the identity domains' selection of a constexpr sampler array's element adds +/// for each candidate (`emit::identity_element`): its pushed index's read, and its comparison and +/// select with their constants. +pub(crate) const IDENTITY_ELEMENT_WORDS: u32 = 12 + TABLE_ELEMENT_WORDS; + /// An upper estimate of the SPIR-V words of an argument-buffer sampler's cubic test past its /// entry's word: the mask, the test, the selection construct, and the status mark (the push field's /// load, the address, the pointer, the bit, and the atomic `OR`). @@ -341,6 +348,9 @@ pub enum Source { handle: ValueId, sampler: ValueId, key: HeapArrayKey, + /// Under the identity domains the candidates whose pushed indices the element's selection + /// reads one by one (`emit::identity_element`); 0 outside them. + pushed: u32, }, } @@ -1005,7 +1015,9 @@ impl Sampling { let heap = match self.source { Source::Combined(_) => 0, Source::Heap { .. } => 32, - Source::HeapArray { .. } => 32 + ARRAY_WORDS, + Source::HeapArray { pushed, .. } => { + 32 + ARRAY_WORDS + pushed.saturating_mul(IDENTITY_ELEMENT_WORDS) + } Source::HeapSampler { .. } => 56 + 2 * ENTRY_FIELD_WORDS + CUBIC_REACH_WORDS, }; let residency = if self.residency { @@ -1200,6 +1212,9 @@ pub struct SamplerPlan { /// The use each one's binding is made for, set by [`finish`]: one binding per distinct array /// and use. pub heap_array_decls: BTreeMap, + /// Under the identity domains, the set-1 sampler array's use each one reads, set by + /// [`finish`] in place of its binding, each candidate's index pushed. + pub heap_array_identity: BTreeMap, /// The texture slots a bicubic sample reads, each with its `BicubicTexels` specialization, /// or under the identity domains its `PushField::BicubicTexels` field. pub bicubic: BTreeSet, @@ -1426,6 +1441,7 @@ pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> { // One constexpr sampler array binding per distinct array and use (`declare`), each element a // sampler of the stage. let mut heap_array_decls = BTreeMap::new(); + let mut heap_array_identity = BTreeMap::new(); for key in &cx.families.sampler.heap_arrays { let h = cx .families @@ -1443,6 +1459,21 @@ pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> { for words in &array.samplers { constexpr_desc(*words, use_, cx.profile)?; } + // Under the identity domains no binding: each candidate is the set-1 sampler array's + // element at its pushed index, as a constexpr sampler beside a heap image is. + if crate::lower::access::identity(cx.profile) { + for &words in &array.samplers { + let c = CombinedSampler::new( + SamplerRef::Constexpr(words), + key.compare, + use_.integer_texture, + ); + cx.push + .insert(crate::pipeline::sym::PushField::ConstexprSampler(c)); + } + heap_array_identity.insert(*key, use_); + continue; + } heap_array_decls.insert(*key, use_); } let array_bindings: BTreeSet<(u32, SamplerUse)> = heap_array_decls @@ -1543,6 +1574,7 @@ pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> { cx.families.sampler.heap_identity = heap_identity; cx.families.sampler.heap_sampler_decls = heap_sampler_decls; cx.families.sampler.heap_array_decls = heap_array_decls; + cx.families.sampler.heap_array_identity = heap_array_identity; cx.descriptors = cx.descriptors.plus(&counts); Ok(()) } @@ -1736,7 +1768,8 @@ pub fn declare( // heap element's, and a slot's word is its pushed resource ID's (`emit::sampler_word`). let sampling = &plan.families.sampler; let slot_uses = sampling.identity.values().map(|i| i.use_); - for use_ in slot_uses.chain(sampling.heap_identity.values().copied()) { + let heap_uses = (sampling.heap_identity.values()).chain(sampling.heap_array_identity.values()); + for use_ in slot_uses.chain(heap_uses.copied()) { if d.identity.contains_key(&use_) { continue; } diff --git a/crates/metal2vulkan/src/lower/sampler/select.rs b/crates/metal2vulkan/src/lower/sampler/select.rs index 87c04143f..883b185a0 100644 --- a/crates/metal2vulkan/src/lower/sampler/select.rs +++ b/crates/metal2vulkan/src/lower/sampler/select.rs @@ -556,9 +556,13 @@ fn select_heap_switch( /// value that may differ between invocations (`shaderSampledImageArrayNonUniformIndexing`, which /// the heap's own image array already needs); the use is not tangled; and each candidate's /// sampling is the same but for its sampler and the state its raw emulation follows. `None` -/// otherwise, and under the identity domains, whose constexpr sampler is the set-1 sampler array's -/// element at its pushed index (`PushField::ConstexprSampler`) and no set-0 array holds: the -/// switch over the candidates stays, each arm through its own. +/// otherwise. Under the identity domains no set-0 array holds: the sampling reads the set-1 +/// sampler array of its use at the pushed index (`PushField::ConstexprSampler`) of the candidate +/// the handle names (`emit::identity_element`), and only where the sampling reads a float class, +/// without comparison and in normalized coordinates; the switch over the candidates stays for the +/// rest. No raw emulation arises there (the element is read in the class the shader declares, +/// [`select_heap_raw`]), and none through Metal's bicubic filter, which an argument buffer's +/// texture refuses (`bicubic::check`). fn select_heap_array( cx: &mut SelectCx<'_>, call: Call<'_>, @@ -568,10 +572,7 @@ fn select_heap_array( m: &mut Meter, ) -> Result, Error> { use super::heap_raw::State; - if cands.len() < 2 - || !cx.profile.fields().descriptors.non_uniform_sampled_image - || crate::lower::access::identity(cx.profile) - { + if cands.len() < 2 || !cx.profile.fields().descriptors.non_uniform_sampled_image { return Ok(None); } if !cands @@ -635,6 +636,16 @@ fn select_heap_array( if arms.iter().any(|x| shape(x).as_ref() != Some(&one)) { return Ok(None); } + let identity = crate::lower::access::identity(cx.profile); + if identity { + let compare = matches!(one.source, Source::Heap { key, .. } if key.compare); + let float = float_class(cx, call.t, heap.0)?; + let pixel = + !matches!(one.pixel, Pixel::None) || matches!(one.op, SampleOp::PixelFetch { .. }); + if compare || !float || pixel { + return Ok(None); + } + } let mut samplers = Vec::with_capacity(arms.len()); for x in &arms { match x.source { @@ -681,6 +692,7 @@ fn select_heap_array( handle, sampler: smp_handle, key, + pushed: if identity { elements } else { 0 }, }; cx.families.sampler.heap = before; cx.families.sampler.heap_arrays.insert(key); @@ -709,16 +721,7 @@ fn select_heap_raw( return Ok(None); } let shape = call.t.image; - let float = match call.t.texel { - Some(_) => texel(call.t, 4)?.1 == TexelClass::Float, - None => cx - .families - .texture - .heap - .get(&group) - .and_then(|h| h.texel) - .is_none_or(|c| c == TexelClass::Float), - }; + let float = float_class(cx, call.t, group)?; if shape.ms || shape.depth || shape.dim == ImageDim::Buffer || !float { return Ok(None); } @@ -742,6 +745,17 @@ fn select_heap_raw( Ok(raw) } +/// Whether heap sampling call `t` of heap group `group` reads a float class: its texel's, or +/// where it reads none (a level query) the group's, where an access states one. +fn float_class(cx: &SelectCx<'_>, t: &Texture, group: u32) -> Result { + Ok(match t.texel { + Some(_) => texel(t, 4)?.1 == TexelClass::Float, + None => (cx.families.texture.heap.get(&group)) + .and_then(|h| h.texel) + .is_none_or(|c| c == TexelClass::Float), + }) +} + /// The emulation of [`select_heap_raw`]'s call, where it is built as a slot's extended-range /// sample is ([`select_extended`]): a 2D texture's sample or gradient sample without /// comparison, or gather of a component without comparison, with a `float` or `half` result, a diff --git a/crates/metal2vulkan/src/lower/select.rs b/crates/metal2vulkan/src/lower/select.rs index b2a72abde..0e8f9c6ee 100644 --- a/crates/metal2vulkan/src/lower/select.rs +++ b/crates/metal2vulkan/src/lower/select.rs @@ -1978,8 +1978,9 @@ fn identity_refusal(plan: &Plan) -> Option { // resource ID, and a 2D texture slot's bicubic sample at normalized coordinates, the bound // format's treatment read from its push field (`PushField::BicubicTexels`): no bicubic sample // at pixel coordinates, bicubic sample of a 1D texture (`Routine::Line`), or specialization of - // a slot's state. Constexpr samplers a lane chooses among are a switch over them, never an - // array of their samplers (`sampler::select::select_heap_array`). A two-plane texture's + // a slot's state. Constexpr samplers a lane chooses among beside an argument buffer's texture + // read the set-1 sampler array at the chosen candidate's pushed index + // (`SamplerPlan::heap_array_identity`) or are a switch over them. A two-plane texture's // sample read in place (`Routine::Quad`) never reaches here: its slot's // `PushField::YCbCrInPlace` is refused first, as an encoder value the identity domains do not // source. diff --git a/crates/metal2vulkan/src/tests/engine_handles.rs b/crates/metal2vulkan/src/tests/engine_handles.rs index 86379ae94..b7fb79953 100644 --- a/crates/metal2vulkan/src/tests/engine_handles.rs +++ b/crates/metal2vulkan/src/tests/engine_handles.rs @@ -140,7 +140,7 @@ fn insts(words: &[u32]) -> Vec<(u16, usize)> { out } -fn count(a: &FunctionArtifact, op: u16) -> usize { +pub(super) fn count(a: &FunctionArtifact, op: u16) -> usize { insts(&a.module.words) .iter() .filter(|(o, _)| *o == op) @@ -198,17 +198,17 @@ fn texture_slots(a: &FunctionArtifact) -> Vec { .collect() } -fn uses(a: &FunctionArtifact, name: &str) -> u32 { +pub(super) fn uses(a: &FunctionArtifact, name: &str) -> u32 { a.strategies.entries.get(name).map_or(0, |u| u.uses) } -const OP_SWITCH: u16 = 251; +pub(super) const OP_SWITCH: u16 = 251; const OP_SELECTION_MERGE: u16 = 247; const OP_LABEL: u16 = 248; const OP_DPDX: u16 = 207; const OP_DPDY: u16 = 208; const OP_IMAGE_SAMPLE_IMPLICIT_LOD: u16 = 87; -const OP_IMAGE_SAMPLE_EXPLICIT_LOD: u16 = 88; +pub(super) const OP_IMAGE_SAMPLE_EXPLICIT_LOD: u16 = 88; const OP_IMAGE_QUERY_LOD: u16 = 105; /// Every handle entry compiles, links, and validates on every committed profile. @@ -2672,7 +2672,7 @@ fn an_imageblock_slice_writes_an_argument_buffer_texture() { assert_eq!(u.needs, Needs::NotImplemented); } -const OP_IMAGE_SAMPLE_DREF_EXPLICIT_LOD: u16 = 90; +pub(super) const OP_IMAGE_SAMPLE_DREF_EXPLICIT_LOD: u16 = 90; const OP_IMAGE_GATHER: u16 = 96; const OP_IMAGE_DREF_GATHER: u16 = 97; @@ -2885,7 +2885,7 @@ fn an_argument_buffer_depth_texture_compares_through_the_depth_comparison_class( assert!(compiled > 0, "no committed profile has the sampled heap"); } -const OP_SAMPLED_IMAGE: u16 = 86; +pub(super) const OP_SAMPLED_IMAGE: u16 = 86; const OP_IMAGE_FETCH: u16 = 95; /// A constexpr sampler's words: linear filters, no mip filter, normalized coordinates clamped to diff --git a/crates/metal2vulkan/src/tests/engine_identity.rs b/crates/metal2vulkan/src/tests/engine_identity.rs index cc84c235e..b16b7cc4e 100644 --- a/crates/metal2vulkan/src/tests/engine_identity.rs +++ b/crates/metal2vulkan/src/tests/engine_identity.rs @@ -1079,36 +1079,245 @@ fn an_argument_buffer_textures_sample_takes_its_sampler_from_the_identity_arrays } } -/// Under the identity domains constexpr samplers a lane chooses among beside an argument buffer's -/// texture (`engine_handles::chosen_sampler_kernel`) are a switch over the candidates on every -/// profile, each arm sampling as through that sampler alone at its pushed index -/// (`PushField::ConstexprSampler`, one for each candidate), never an array of their samplers: each -/// compiles and passes L3, and the resident-table domains compile them as before. -#[test] -fn an_argument_buffer_texture_through_chosen_constexpr_samplers_is_a_switch_over_them() { - use super::engine_handles::{chosen_sampler_kernel, CHOSEN_SAMPLERS}; - let chosen = format!( - "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\"\n\ -target triple = \"air64_v28-apple-macosx26.0.0\"\n\n{}", - chosen_sampler_kernel(&[0, 1, 2], None) - ); - let Some(chosen) = assemble_text("chosen", &chosen) else { - return; +/// What [`chosen_heap`] does with the texture its argument buffer holds, through the constexpr +/// sampler its lane chooses. +#[derive(Clone, Copy, Debug)] +enum Chosen { + /// A kernel's sample of a `texture2d` at level 0. + Float, + /// A kernel's sample of a `texture2d` at level 0. + Integer, + /// A kernel's `sample_compare` of a `depth2d` against 0.5 at level 0. + Compare, + /// A fragment's sample of a `texture2d` at its implicit level, at its position over 16, + /// its lane its position's `x`. + Fragment, +} + +/// A function `chosen` that does `chosen` with the texture its argument buffer (buffer 0) holds, +/// at `(1.375, 0.5)` in a kernel, through the constexpr sampler of words `words[lane % n]` (each a +/// constexpr sampler of the module, listed in order, so their handles are consecutive), and +/// writes the result to buffer 1's lane (a kernel's `float4` or `uint4`) or its color attachment. +fn chosen_heap(words: &[u64], chosen: Chosen) -> String { + let n = words.len(); + let mut choose = format!(" %sel = urem i32 %lane, {n}\n"); + let mut sampler = format!("@s{}", n - 1); + for k in (0..n - 1).rev() { + choose += &format!( + " %c{k} = icmp eq i32 %sel, {k}\n %p{k} = select i1 %c{k}, ptr addrspace(2) @s{k}, ptr addrspace(2) {sampler}\n" + ); + sampler = format!("%p{k}"); + } + let globals: String = (words.iter().enumerate()) + .map(|(i, w)| { + format!("@s{i} = internal addrspace(2) constant [2 x i64] [i64 {w}, i64 0], align 8\n") + }) + .collect(); + let list: Vec = (0..n).map(|i| format!("!{}", 20 + i)).collect(); + let states: String = (0..n) + .map(|i| { + format!( + "!{} = !{{!\"air.sampler_state\", ptr addrspace(2) @s{i}}}\n", + 20 + i + ) + }) + .collect(); + let at_zero = "<2 x float> , i1 true, <2 x i32> zeroinitializer, i1 true, float 0.0, float 0.0, i32 0"; + let float = "declare { <4 x float>, i8 } @air.sample_texture_2d.v4f32(ptr addrspace(1), ptr addrspace(2), <2 x float>, i1, <2 x i32>, i1, float, float, i32)"; + let (texture, elem, sample, declare) = match chosen { + Chosen::Float => ( + "texture2d", + ("float", "float"), + format!( + " %r = call {{ <4 x float>, i8 }} @air.sample_texture_2d.v4f32(ptr addrspace(1) %t, ptr addrspace(2) {sampler}, {at_zero})\n %v = extractvalue {{ <4 x float>, i8 }} %r, 0\n" + ), + float, + ), + Chosen::Integer => ( + "texture2d", + ("i32", "uint"), + format!( + " %r = call {{ <4 x i32>, i8 }} @air.sample_texture_2d.u.v4i32(ptr addrspace(1) %t, ptr addrspace(2) {sampler}, {at_zero})\n %v = extractvalue {{ <4 x i32>, i8 }} %r, 0\n" + ), + "declare { <4 x i32>, i8 } @air.sample_texture_2d.u.v4i32(ptr addrspace(1), ptr addrspace(2), <2 x float>, i1, <2 x i32>, i1, float, float, i32)", + ), + Chosen::Compare => ( + "depth2d", + ("float", "float"), + format!( + " %r = call {{ float, i8 }} @air.sample_compare_depth_2d.f32(ptr addrspace(1) %t, ptr addrspace(2) {sampler}, i32 1, <2 x float> , float 0.5, i1 true, <2 x i32> zeroinitializer, i1 true, float 0.0, float 0.0, i32 0)\n %x = extractvalue {{ float, i8 }} %r, 0\n %v = insertelement <4 x float> zeroinitializer, float %x, i64 0\n" + ), + "declare { float, i8 } @air.sample_compare_depth_2d.f32(ptr addrspace(1), ptr addrspace(2), i32, <2 x float>, float, i1, <2 x i32>, i1, float, float, i32)", + ), + Chosen::Fragment => ( + "texture2d", + ("float", "float"), + format!( + " %xy = shufflevector <4 x float> %pos, <4 x float> poison, <2 x i32> \n %uv = fmul <2 x float> %xy, splat (float 6.250000e-02)\n %r = call {{ <4 x float>, i8 }} @air.sample_texture_2d.v4f32(ptr addrspace(1) %t, ptr addrspace(2) {sampler}, <2 x float> %uv, i1 true, <2 x i32> zeroinitializer, i1 false, float 0.0, float 0.0, i32 0)\n %v = extractvalue {{ <4 x float>, i8 }} %r, 0\n" + ), + float, + ), }; - for stem in PROFILES { - let default = - profile(stem, DevicePolicy::RESIDENT_TABLES).unwrap_or_else(|e| panic!("{e}")); - let p = profile(stem, identity()).unwrap_or_else(|e| panic!("{e}")); - let what = format!("{stem}: chosen"); - compile(&chosen, "chosen", &default) - .unwrap_or_else(|e| panic!("{what}: resident-table domains: {e}")); - let (a, plan, _) = - compile_kept(&chosen, "chosen", &p).unwrap_or_else(|e| panic!("{what}: {e}")); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); - let pushed = (plan.push.fields.iter()) - .filter(|f| matches!(f.field, PushField::ConstexprSampler(_))) - .count(); - assert_eq!(pushed, CHOSEN_SAMPLERS.len(), "{what}"); + let held = format!( + r#"!3 = !{{i32 {index}, !"air.indirect_buffer", !"air.buffer_size", i32 8, !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.struct_type_info", !4, !"air.arg_type_size", i32 8, !"air.arg_type_align_size", i32 8, !"air.arg_type_name", !"M", !"air.arg_name", !"m"}} +!4 = !{{i32 0, i32 8, i32 0, !"{texture}", !"t", !"air.indirect_argument", !5}} +!5 = !{{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.sample", !"air.arg_type_name", !"{texture}", !"air.arg_name", !"t"}}"#, + index = u32::from(matches!(chosen, Chosen::Fragment)), + ); + let (ty, msl) = elem; + let (function, stage) = match chosen { + Chosen::Fragment => ( + format!( + r#"define <4 x float> @chosen(<4 x float> %pos, ptr addrspace(2) %m) {{ + %x0 = extractelement <4 x float> %pos, i64 0 + %lane = fptoui float %x0 to i32 + %pt = getelementptr inbounds %struct.M, ptr addrspace(2) %m, i64 0, i32 0 + %t = load ptr addrspace(1), ptr addrspace(2) %pt, align 8 +{choose}{sample} ret <4 x float> %v +}}"# + ), + r#"!air.fragment = !{!0} +!0 = !{ptr @chosen, !1, !2} +!1 = !{!9} +!2 = !{!8, !3} +!8 = !{i32 0, !"air.position", !"air.center", !"air.no_perspective", !"air.arg_type_name", !"float4", !"air.arg_name", !"pos"} +!9 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"float4"}"# + .to_owned(), + ), + _ => ( + format!( + r#"define void @chosen(ptr addrspace(2) %m, ptr addrspace(1) %out, i32 %lane) {{ + %pt = getelementptr inbounds %struct.M, ptr addrspace(2) %m, i64 0, i32 0 + %t = load ptr addrspace(1), ptr addrspace(2) %pt, align 8 +{choose}{sample} %o = getelementptr inbounds <4 x {ty}>, ptr addrspace(1) %out, i32 %lane + store <4 x {ty}> %v, ptr addrspace(1) %o, align 16 + ret void +}}"# + ), + format!( + r#"!air.kernel = !{{!0}} +!0 = !{{ptr @chosen, !1, !2}} +!1 = !{{}} +!2 = !{{!3, !6, !8}} +!6 = !{{i32 1, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"{msl}4", !"air.arg_name", !"out"}} +!8 = !{{i32 2, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"lane"}}"# + ), + ), + }; + format!( + 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" + +%struct.M = type {{ ptr addrspace(1) }} +{globals} +{function} +{declare} +{stage} +!air.version = !{{!11}} +!air.language_version = !{{!12}} +!air.sampler_states = !{{{}}} +{held} +!11 = !{{i32 2, i32 8, i32 0}} +!12 = !{{!"Metal", i32 4, i32 0, i32 0}} +{states}"#, + list.join(", ") + ) +} + +/// Under the identity domains constexpr samplers of consecutive handles that a lane chooses among +/// beside an argument buffer's texture ([`chosen_heap`]) are one sample where their samplings +/// differ only in the sampler: a kernel's sample of a float class through [`CHOSEN_SAMPLERS`] +/// (`engine_handles`) reads the set-1 sampler array of its use, `NonUniform`, at the pushed index +/// of the candidate the handle names (`sampler.sampler_array.sample`): one sampled image and one +/// sample, no switch, one `PushField::ConstexprSampler` per candidate. The switch over the +/// candidates stays, a sampled image per candidate, for pixel coordinates (two linear pixel +/// samplers that differ in their border color), an integer texture, a comparison and a fragment's +/// implicit level. The resident-table domains take their set-0 array for all but the fragment's, +/// so the candidates' samplings are alike there and only the identity domains' rule keeps the +/// switch. Each compiles and passes L3 on every committed profile. +#[test] +fn chosen_constexpr_samplers_beside_an_argument_buffer_texture_are_one_sample_where_alike() { + use super::engine_handles::{ + chosen_sampler, count, uses, CHOSEN_SAMPLERS, OP_IMAGE_SAMPLE_DREF_EXPLICIT_LOD, + OP_IMAGE_SAMPLE_EXPLICIT_LOD, OP_SAMPLED_IMAGE, OP_SWITCH, + }; + use crate::spirv::testing::committed_profiles_with; + const PIXEL: u64 = 1 << 15; + const OPAQUE_WHITE: u64 = 2 << 56; + // `less` in place of the words' `never`. + let compare = |w: u64| (w & !(0xf << 16)) | 1 << 16; + let nearest = [ + chosen_sampler(1, 0), + chosen_sampler(2, 0), + chosen_sampler(3, 0), + ]; + // Each case: its name, what it samples, its candidates, and whether it is one sample. + let cases: [(&str, Chosen, Vec, bool); 5] = [ + ("float", Chosen::Float, CHOSEN_SAMPLERS.to_vec(), true), + ( + "pixel", + Chosen::Float, + vec![ + chosen_sampler(0, 1) | PIXEL, + chosen_sampler(0, 1) | PIXEL | OPAQUE_WHITE, + ], + false, + ), + ("integer", Chosen::Integer, nearest.to_vec(), false), + ( + "compare", + Chosen::Compare, + nearest.iter().map(|w| compare(*w)).collect(), + false, + ), + ( + "fragment", + Chosen::Fragment, + CHOSEN_SAMPLERS.to_vec(), + false, + ), + ]; + let profiles = committed_profiles_with(DevicePolicy::default()).expect("profiles"); + for (name, chosen, words, one) in cases { + let Some(bc) = assemble_text(name, &chosen_heap(&words, chosen)) else { + return; + }; + let n = words.len(); + let sample = match chosen { + Chosen::Compare => OP_IMAGE_SAMPLE_DREF_EXPLICIT_LOD, + _ => OP_IMAGE_SAMPLE_EXPLICIT_LOD, + }; + for stem in PROFILES { + let default = + profile(stem, DevicePolicy::RESIDENT_TABLES).unwrap_or_else(|e| panic!("{e}")); + let a = compile(&bc, "chosen", &default) + .unwrap_or_else(|e| panic!("{stem}: {name}: resident-table domains: {e}")); + let array = !matches!(chosen, Chosen::Fragment); + assert_eq!( + uses(&a, "sampler.sampler_array.sample"), + u32::from(array), + "{stem}: {name}: resident-table domains" + ); + } + for (stem, p) in &profiles { + let what = format!("{stem}: {name}"); + let (a, plan, _) = + compile_kept(&bc, "chosen", p).unwrap_or_else(|e| panic!("{what}: {e}")); + link_and_validate(&a, p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); + let pushed = (plan.push.fields.iter()) + .filter(|f| matches!(f.field, PushField::ConstexprSampler(_))) + .count(); + assert_eq!(pushed, n, "{what}"); + let arrays = uses(&a, "sampler.sampler_array.sample"); + let (images, switches) = (count(&a, OP_SAMPLED_IMAGE), count(&a, OP_SWITCH)); + if one { + assert_eq!((arrays, images, switches), (1, 1, 0), "{what}"); + assert_eq!(count(&a, sample), 1, "{what}"); + } else { + assert_eq!((arrays, images), (0, n), "{what}"); + assert!(switches > 0, "{what}"); + } + } } } diff --git a/docs/API.md b/docs/API.md index 6721b6220..2b8e1e35d 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1144,9 +1144,13 @@ for dependency in &pipeline.dependencies { array's constexpr samplers by its slot. The module takes this form where the candidates' handles are consecutive, each candidate's sampling is the same but for its sampler, and the device indexes a sampler array by a value that may differ between invocations - (`shaderSampledImageArrayNonUniformIndexing`, which heap textures already need); otherwise, and - always under the identity domains (whose stages bind no set-0 sampler), it switches over the - candidates, one sampling per candidate, each through the constexpr sampler the consumer pushes. + (`shaderSampledImageArrayNonUniformIndexing`, which heap textures already need); otherwise it + switches over the candidates, one sampling per candidate. Under the identity domains, whose + stages bind no set-0 sampler, the same form samples once through the set-1 sampler array of the + use, at the index the consumer pushes for the candidate the handle names (one + `PushField::ConstexprSampler` per candidate), where the sampling also reads a float class + without comparison and in normalized coordinates; otherwise it switches over the candidates, + each through the constexpr sampler the consumer pushes. - Each binding's `variables` is the most variables one stage's entry point uses at it (those its `OpEntryPoint` lists): a function that reaches a buffer through several types uses a variable of each type at the buffer's binding. A set-0 uniform or storage buffer binding may be created as its dynamic type