From 27ed85dfc2dde339d3bcca3eb336c0b8a62beee2 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Sat, 14 Nov 2026 04:42:19 -0800 Subject: [PATCH] SEMANTICS 2109 / RUNTIME 2287: an 8-byte leaf at a proven 8-aligned offset moves as one uvec2 A buffer slot's 8-byte leaf (half4, float2, long, a chunked uchar8) whose AIR alignment is at least 8 and whose offset is proven a multiple of 8 (MemoryPlan::proven_align) is now one element of a StorageBuffer { uvec2[] } view at the slot's binding, as a 16-byte leaf at a proven 16-aligned offset already is one uvec4. Elsewhere it stays two words. Why: under robustBufferAccess2 RADV's load/store vectorizer does not merge two word loads it cannot prove 8-aligned, so a half4 read was two buffer_load_b32 where a native kernel reading f16vec4[] has one buffer_load_b64 (780M Geekbench kernels run ~1.4x native's GPU time per job). - Path::Vec2 beside Path::Vec4, Units::vec2, UnitViews::vec2; WordMem's vector read/write take the lane count; views::declare_vec declares either width. Uniform views get no uvec2 view (std140 stride 16); device addresses and the threadgroup arena keep no vector unit. - Exact under rule 1: the same bytes move. Descriptor bases are 16-aligned and a bound range is a whole number of 16-byte units, so the word view's containment check is the unit's. - The dynamic-views self-check module declares a uvec2 variable too (RUNTIME bump). - docs/FAST-PATHS.md, multi-variable dynamic binding row: "narrow, uvec2 or uvec4 unit view". No switch, Degradation kind, refusal or public type change. Verified (codegen): ISA compile-only gfx1103 RADV 26.2.6 (amdgpu noop drm-shim) on our own half4 column convolution: the loop's read and store are buffer_load_b64 / buffer_store_b64 as the native twin's; VMEM 5 -> 2 (native 2), instructions 88 -> 83 (native 56). msi m3-max-28997 at ae8ac29436: clippy -D warnings all targets/features (translator, runtime) 0; touched tests 292/292 (engine_access incl. eight_byte_leaves_move_as_one_uvec2: views, OpStore counts, exact bytes on the CPU interpreter at every residual, both encodings, every tested profile); metal2vulkan suite 3578 passed, 1 expected failure golden_hashes_match_the_table (re-blessed on development next). --- crates/metal2vulkan/src/bind/dynamic_views.rs | 13 +- crates/metal2vulkan/src/bind/plan/compute.rs | 9 +- crates/metal2vulkan/src/cache/mod.rs | 4 +- crates/metal2vulkan/src/lower/access/emit.rs | 46 +++-- crates/metal2vulkan/src/lower/access/mod.rs | 10 +- crates/metal2vulkan/src/lower/access/psb.rs | 6 +- crates/metal2vulkan/src/memory/leaf.rs | 180 +++++++++++------- crates/metal2vulkan/src/memory/views.rs | 115 +++++++---- .../metal2vulkan/src/tests/engine_access.rs | 142 ++++++++++---- docs/FAST-PATHS.md | 2 +- 10 files changed, 341 insertions(+), 186 deletions(-) diff --git a/crates/metal2vulkan/src/bind/dynamic_views.rs b/crates/metal2vulkan/src/bind/dynamic_views.rs index a478bc356..a700ac829 100644 --- a/crates/metal2vulkan/src/bind/dynamic_views.rs +++ b/crates/metal2vulkan/src/bind/dynamic_views.rs @@ -1,8 +1,8 @@ //! The device self-check module: a storage-buffer binding one entry point uses through **several //! variables**. //! -//! A plan's slot declares one variable per view at its binding -- a word view, and the narrow and -//! `uvec4` unit views an access of it needs (`memory::views`, all of them at the one +//! A plan's slot declares one variable per view at its binding -- a word view, and the narrow, +//! `uvec2` and `uvec4` unit views an access of it needs (`memory::views`, all of them at the one //! binding, so the stage counts one descriptor). A consumer that binds such a descriptor //! *dynamically* (`VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC`, the offset given as the set is //! bound) lets commands that differ only in that offset share one descriptor set; a consumer that @@ -103,9 +103,12 @@ fn typed_module(units: Units) -> BResult { let block = block_of(&mut b, narrow, stride)?; views.push(b.resource_view(VIEWS, StorageClass::StorageBuffer, block)?); } - if units.vec4 { - let uvec4 = b.ty(Type::Vector { elem: u32_, len: 4 })?; - let block = block_of(&mut b, uvec4, 16)?; + for (declared, len) in [(units.vec2, 2u8), (units.vec4, 4)] { + if !declared { + continue; + } + let uvec = b.ty(Type::Vector { elem: u32_, len })?; + let block = block_of(&mut b, uvec, 4 * u32::from(len))?; views.push(b.resource_view(VIEWS, StorageClass::StorageBuffer, block)?); } let void = b.ty(Type::Void)?; diff --git a/crates/metal2vulkan/src/bind/plan/compute.rs b/crates/metal2vulkan/src/bind/plan/compute.rs index 7aea30a7d..1b5033188 100644 --- a/crates/metal2vulkan/src/bind/plan/compute.rs +++ b/crates/metal2vulkan/src/bind/plan/compute.rs @@ -204,10 +204,11 @@ impl TileMemoryPlan { /// outside its array, as the end of an argument that ends past the tile's memory already is: that /// switch gives up Metal's answer for every out-of-range access, not this one alone. /// -/// A 4-byte-aligned base is exact here because the threadgroup arena has no 16-byte unit -/// (`memory::arena::ArenaMem` declares no `Units`), so a 16-byte access takes `Path::Vec4`'s -/// fallback to four words at `off / 4` rather than a `uvec4` index at `off / 16` -/// (`memory::leaf`): no access to the arena claims an alignment the base does not hold. +/// A 4-byte-aligned base is exact here because the threadgroup arena has no 8- or 16-byte unit +/// (`memory::arena::ArenaMem` declares no `Units`), so an 8- or 16-byte access takes `Path::Vec2`'s +/// or `Path::Vec4`'s fallback to its words at `off / 4` rather than a `uvec2` index at `off / 8` or +/// a `uvec4` index at `off / 16` (`memory::leaf`): no access to the arena claims an alignment the +/// base does not hold. fn tile_argument_offset(offset: u32) -> u32 { offset - offset % TG_FLOOR } diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index a8e45a0b2..a14908195 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 = 2108; +pub const SEMANTICS_VERSION: u32 = 2109; /// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the /// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another @@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 522; /// changes no behaviour, and then updates that hash alone with the commit saying why, or changes /// behaviour and also bumps this version. The commit that bumps it says what changed; this comment /// keeps no history. -pub const RUNTIME_VERSION: u32 = 2286; +pub const RUNTIME_VERSION: u32 = 2287; /// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex, /// of the manifest, the build script, and exactly the files the crate roots' module tree compiles diff --git a/crates/metal2vulkan/src/lower/access/emit.rs b/crates/metal2vulkan/src/lower/access/emit.rs index 1a07858b6..e94bd00ff 100644 --- a/crates/metal2vulkan/src/lower/access/emit.rs +++ b/crates/metal2vulkan/src/lower/access/emit.rs @@ -24,8 +24,8 @@ use super::{ /// The word memory of one descriptor view, loaded and stored with memory operands (a coherence, /// and `Volatile`; a uniform view's read-only words stay plain: no agent writes them while the /// dispatch runs). Sub-word stores are two relaxed device-scope word atomics, except where the -/// slot's narrow views hold the leaf's units; a 16-byte aligned leaf is one `uvec4` where the slot -/// has that view. +/// slot's narrow views hold the leaf's units; a 16-byte (8-byte) leaf at an offset proven a +/// multiple of its size is one `uvec4` (`uvec2`) where the slot has that view. #[derive(Clone, Copy, Debug)] pub(super) struct ViewMem(pub(super) View, pub(super) WordOps, pub(super) UnitViews); @@ -35,9 +35,9 @@ impl ViewMem { self.2.of(bytes).ok_or(self.missing()) } - /// The `uvec4` view: present whenever [`WordMem::units`] says so. - fn vec4(&self) -> BResult { - self.2.vec4.ok_or(self.missing()) + /// The vector view of `lanes`-word units: present whenever [`WordMem::units`] says so. + fn vec(&self, lanes: u32) -> BResult { + self.2.vec(lanes).ok_or(self.missing()) } fn missing(&self) -> crate::spirv::error::BuildError { @@ -48,25 +48,31 @@ impl ViewMem { } impl WordMem for ViewMem { - fn read_vec4(&mut self, fb: &mut FunctionBuilder<'_>, index: SValue) -> BResult { - let view = self.vec4()?; + fn read_vec( + &mut self, + fb: &mut FunctionBuilder<'_>, + lanes: u32, + index: SValue, + ) -> BResult { + let view = self.vec(lanes)?; // A uniform view's read-only vectors are read plainly, as its words are. let access = match view.class { crate::spirv::ir::StorageClass::Uniform => MemAccess::default(), _ => self.1.access(fb, MemAccess::default(), false)?, }; - views::read_vec4(fb, view, index, access) + views::read_vec(fb, view, index, access) } - fn write_vec4( + fn write_vec( &mut self, fb: &mut FunctionBuilder<'_>, + lanes: u32, index: SValue, value: SValue, ) -> BResult<()> { - let view = self.vec4()?; + let view = self.vec(lanes)?; let access = self.1.access(fb, MemAccess::default(), true)?; - views::write_vec4(fb, view, index, value, access) + views::write_vec(fb, view, index, value, access) } fn units(&self) -> Units { @@ -190,22 +196,28 @@ impl WordMem for Mem { } } - fn read_vec4(&mut self, fb: &mut FunctionBuilder<'_>, index: SValue) -> BResult { + fn read_vec( + &mut self, + fb: &mut FunctionBuilder<'_>, + lanes: u32, + index: SValue, + ) -> BResult { match self { - Mem::View(m) => m.read_vec4(fb, index), - Mem::Psb(m) => m.read_vec4(fb, index), + Mem::View(m) => m.read_vec(fb, lanes, index), + Mem::Psb(m) => m.read_vec(fb, lanes, index), } } - fn write_vec4( + fn write_vec( &mut self, fb: &mut FunctionBuilder<'_>, + lanes: u32, index: SValue, value: SValue, ) -> BResult<()> { match self { - Mem::View(m) => m.write_vec4(fb, index, value), - Mem::Psb(m) => m.write_vec4(fb, index, value), + Mem::View(m) => m.write_vec(fb, lanes, index, value), + Mem::Psb(m) => m.write_vec(fb, lanes, index, value), } } diff --git a/crates/metal2vulkan/src/lower/access/mod.rs b/crates/metal2vulkan/src/lower/access/mod.rs index 9689900ab..8704a28b9 100644 --- a/crates/metal2vulkan/src/lower/access/mod.rs +++ b/crates/metal2vulkan/src/lower/access/mod.rs @@ -752,8 +752,8 @@ pub struct AccessPlan { /// as read-only memory (on RADV a uniform read is a scalar load). pub unwritten: BTreeSet, /// The units ([`Units`]) the static-root accesses of each slot read or write whole, by - /// memory-plan slot index: narrow units whose storage access the profile has, and `uvec4` - /// units. The slot gets a view of each that its final view kind holds + /// memory-plan slot index: narrow units whose storage access the profile has, and `uvec2` + /// and `uvec4` units. The slot gets a view of each that its final view kind holds /// (`views::UnitViews::declare`). pub units: BTreeMap, /// A tile function's attachments and the ones it stages ([`tile`]). @@ -2091,8 +2091,8 @@ fn place_targets(cx: &mut SelectCx<'_>, targets: &mut [Target], write: bool) -> } /// Give each slot of `targets` the unit views that read or write `leaf` (a store when `write`) -/// in whole units ([`leaf::leaf_units`]): a storage slot the narrow views the profile can access, -/// and any slot a `uvec4` view. +/// in whole units ([`leaf::leaf_units`]): a storage slot the narrow views the profile can access +/// and a `uvec2` view, and any slot a `uvec4` view. fn note_units( cx: &mut SelectCx<'_>, targets: &[Target], @@ -2111,7 +2111,7 @@ fn note_units( .ok_or_else(|| cx.invariant("a target names a missing slot"))?; let units = match view_kind(cx.profile, plan) { ViewKind::Storage => units, - // A uniform view has no narrow view. + // A uniform view has no narrow or `uvec2` view. ViewKind::UniformWords { .. } | ViewKind::UniformVec4 { .. } => Units { vec4: units.vec4, ..Units::NONE diff --git a/crates/metal2vulkan/src/lower/access/psb.rs b/crates/metal2vulkan/src/lower/access/psb.rs index 98d818172..6caef83d2 100644 --- a/crates/metal2vulkan/src/lower/access/psb.rs +++ b/crates/metal2vulkan/src/lower/access/psb.rs @@ -165,10 +165,11 @@ pub fn prepare( } /// The narrow units a device-address memory loads and stores directly on profile `p`: the 1- and -/// 2-byte units of [`Units::storage_on`] (the width's storage access and integer type). No `uvec4` -/// unit: a device address below an access is only 4-byte aligned. +/// 2-byte units of [`Units::storage_on`] (the width's storage access and integer type). No `uvec2` +/// or `uvec4` unit: a device address below an access is only 4-byte aligned. pub fn narrow_units(p: &DeviceProfile) -> Units { Units { + vec2: false, vec4: false, ..Units::storage_on(p) } @@ -205,6 +206,7 @@ impl PsbMem { pub fn with_units(self, units: Units) -> PsbMem { PsbMem { units: Units { + vec2: false, vec4: false, ..units }, diff --git a/crates/metal2vulkan/src/memory/leaf.rs b/crates/metal2vulkan/src/memory/leaf.rs index 4a657d736..ae0fa7304 100644 --- a/crates/metal2vulkan/src/memory/leaf.rs +++ b/crates/metal2vulkan/src/memory/leaf.rs @@ -17,12 +17,15 @@ //! and the register value goes chunk by chunk. //! //! No narrow storage type is used: a leaf is composed from the 32-bit words covering it. The -//! **path** depends only on the access's alignment `a` and, for a 16-byte leaf, the alignment its -//! offset is proven to have ([`Path`]): +//! **path** depends only on the access's alignment `a` and, for an 8- or 16-byte leaf, the alignment +//! its offset is proven to have ([`Path`]): //! //! - [`Path::Vec4`] (`n == 16`, `a >= 16`, and the offset proven a multiple of 16): the leaf is //! `uvec4` unit `off/16` where the memory has one ([`Units::vec4`]), else [`Path::Aligned`]'s //! four words. +//! - [`Path::Vec2`] (`n == 8`, `a >= 8`, and the offset proven a multiple of 8): the leaf is +//! `uvec2` unit `off/8` where the memory has one ([`Units::vec2`]), else [`Path::Aligned`]'s two +//! words. //! - [`Path::Aligned`] (`a >= 4`): the offset is a multiple of 4, so the leaf is words //! `off/4 .. off/4 + ceil(n/4)`. //! - [`Path::OneWord`] (`n <= 2` and `a >= n`): the leaf lies inside one word at a dynamic byte @@ -65,13 +68,17 @@ //! performs each atomic as one read-modify-write; the model does not promise that, and no device //! run has measured it. //! -//! **`uvec4` units**. A word memory may also load and store 16-byte units through a typed `uvec4` -//! view ([`WordMem::read_vec4`]; a descriptor slot's `{ uvec4[] }` view, or its uniform view's own -//! vectors, `memory::views`). There a [`Path::Vec4`] leaf is one unit at index `off / 16`, its -//! register value one bitcast of the vector (four 32-bit lanes or two 64-bit ones) or the -//! composition of its four words: one load or store where the aligned path moves four words. The -//! unit holds exactly the leaf's bytes, so no byte outside the leaf is read or written, as on the -//! word path. +//! **Vector units**. A word memory may also load and store 16-byte units through a typed `uvec4` +//! view and 8-byte units through a typed `uvec2` view ([`WordMem::read_vec`]; a descriptor slot's +//! `{ uvec4[] }` and `{ uvec2[] }` views, or its uniform view's own vectors, `memory::views`). +//! There a [`Path::Vec4`] leaf is one unit at index `off / 16` and a [`Path::Vec2`] leaf one at +//! `off / 8`, its register value one bitcast of the vector (32-bit lanes, or 64-bit ones) or the +//! composition of its words: one load or store where the aligned path moves four or two words. A +//! device that merges neighbouring word accesses only where it can prove the wider alignment +//! (RADV under `robustBufferAccess2`, Mesa 26.2.6) then moves the leaf in one access, not two or +//! four. +//! The unit holds exactly the leaf's bytes, so no byte outside the leaf is read or written, as on +//! the word path. //! //! **Volatile**. A volatile access is the same leaf through a word memory whose [`WordOps`] carry //! `volatile`: every word or unit it loads or stores has the `Volatile` memory operand. @@ -94,10 +101,10 @@ //! carries to the offset in a word memory, because every word memory's base is 4-byte aligned in //! the Metal address space (the binder's descriptor bases are): the words at `off/4` are those //! Metal reads, for each row of the table. A `uvec4` unit at `off/16` is exact only where `off` is -//! a multiple of 16, which the access's `align` does not say, so it is taken only where the offset -//! is proven one (`MemoryPlan::proven_align`: the structure of the pointer's offset and its roots' -//! bases, a buffer's from its argument's alignment); elsewhere the leaf is the four words at -//! `off/4`. +//! a multiple of 16, and a `uvec2` unit at `off/8` only where it is a multiple of 8, which the +//! access's `align` does not say (the `half4` row), so each is taken only where the offset is +//! proven one (`MemoryPlan::proven_align`: the structure of the pointer's offset and its roots' +//! bases, a buffer's from its argument's alignment); elsewhere the leaf is its words at `off/4`. use crate::air::ir::{Type, TypeId as AirTypeId, TypeLayouts}; use crate::air::Entry; @@ -211,6 +218,9 @@ pub enum Path { /// A 16-byte leaf at an offset proven a multiple of 16: one `uvec4` unit where the memory /// has one ([`Units::vec4`]), else [`Path::Aligned`]'s four words. Vec4, + /// An 8-byte leaf at an offset proven a multiple of 8: one `uvec2` unit where the memory has + /// one ([`Units::vec2`]), else [`Path::Aligned`]'s two words. + Vec2, /// The offset is a multiple of 4. Aligned, /// A 1- or 2-byte leaf inside one word. @@ -258,7 +268,7 @@ impl Leaf { bytes: u32::from(k) * lane, // A chunk is shorter than the vector: its words start on a word. path: match self.path { - Path::Vec4 => Path::Aligned, + Path::Vec4 | Path::Vec2 => Path::Aligned, p => p, }, }; @@ -271,7 +281,7 @@ impl Leaf { /// per instruction, with a sub-word store's two atomics on every word. pub fn cost(&self) -> u32 { let per = match self.path { - Path::Vec4 | Path::Aligned => 48 * self.words(), + Path::Vec4 | Path::Vec2 | Path::Aligned => 48 * self.words(), Path::OneWord => 96, Path::Bytes => 96 * self.bytes, }; @@ -355,6 +365,8 @@ pub fn leaf_of( } let path = if bytes == 16 && align >= 16 && proven >= 16 { Path::Vec4 + } else if bytes == 8 && align >= 8 && proven >= 8 { + Path::Vec2 } else if align >= 4 { Path::Aligned } else if bytes <= 2 && u64::from(bytes) <= align { @@ -365,14 +377,16 @@ pub fn leaf_of( Ok(Leaf { form, bytes, path }) } -/// The units a word memory also loads and stores directly: narrow 1- and 2-byte units and 16-byte -/// `uvec4` units. +/// The units a word memory also loads and stores directly: narrow 1- and 2-byte units, 8-byte +/// `uvec2` units and 16-byte `uvec4` units. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub struct Units { /// 2-byte units (a `u16` view). pub u16: bool, /// 1-byte units (a `u8` view). pub u8: bool, + /// 8-byte units (a `uvec2` view). + pub vec2: bool, /// 16-byte units (a `uvec4` view). pub vec4: bool, } @@ -382,14 +396,16 @@ impl Units { pub const NONE: Units = Units { u16: false, u8: false, + vec2: false, vec4: false, }; - /// Whether `bytes`-byte units (1, 2, or 16) are available. + /// Whether `bytes`-byte units (1, 2, 8, or 16) are available. pub fn has(self, bytes: u32) -> bool { match bytes { 1 => self.u8, 2 => self.u16, + 8 => self.vec2, 16 => self.vec4, _ => false, } @@ -400,6 +416,7 @@ impl Units { Units { u16: self.u16 || other.u16, u8: self.u8 || other.u8, + vec2: self.vec2 || other.vec2, vec4: self.vec4 || other.vec4, } } @@ -409,50 +426,57 @@ impl Units { Units { u16: self.u16 && other.u16, u8: self.u8 && other.u8, + vec2: self.vec2 && other.vec2, vec4: self.vec4 && other.vec4, } } /// Whether no unit is set. pub fn is_empty(self) -> bool { - !self.u16 && !self.u8 && !self.vec4 + !self.u16 && !self.u8 && !self.vec2 && !self.vec4 } /// The units profile `p` can declare as storage-buffer views: a narrow width needs its /// storage access and, since requirement derivation asks a declared 8- or 16-bit integer type - /// for its arithmetic capability (`spirv::requirements`), its integer feature; a `uvec4` view - /// needs nothing. + /// for its arithmetic capability (`spirv::requirements`), its integer feature; a `uvec2` or + /// `uvec4` view needs nothing. pub fn storage_on(p: &DeviceProfile) -> Units { let l = &p.fields().leaf; Units { u16: l.storage_buffer_16bit && l.int16, u8: l.storage_buffer_8bit && l.int8, + vec2: true, vec4: true, } } } /// The units an access of `leaf` (a `store` or a load) uses where its memory has them: a -/// [`Path::Vec4`] leaf's `uvec4` unit, a [`Path::OneWord`] leaf's one narrow unit of its size, and -/// an aligned store's partial last word's 2-byte and 1-byte parts. A load of an aligned leaf reads -/// whole words, and a [`Path::Bytes`] leaf joins words, so neither uses one. +/// [`Path::Vec4`] leaf's `uvec4` unit, a [`Path::Vec2`] leaf's `uvec2` unit, a [`Path::OneWord`] +/// leaf's one narrow unit of its size, and an aligned store's partial last word's 2-byte and 1-byte +/// parts. A load of an aligned leaf reads whole words, and a [`Path::Bytes`] leaf joins words, so +/// neither uses one. pub fn leaf_units(leaf: &Leaf, store: bool) -> Units { match leaf.path { Path::Vec4 => Units { vec4: true, ..Units::NONE }, + Path::Vec2 => Units { + vec2: true, + ..Units::NONE + }, Path::OneWord => Units { u16: leaf.bytes == 2, u8: leaf.bytes == 1, - vec4: false, + ..Units::NONE }, Path::Aligned if store => { let tail = leaf.bytes % 4; Units { u16: tail >= 2, u8: tail % 2 == 1, - vec4: false, + ..Units::NONE } } Path::Aligned | Path::Bytes => Units::NONE, @@ -500,16 +524,23 @@ pub trait WordMem { ) -> BResult<()> { Err(dangling()) } - /// Load the `uvec4` unit `index` (a `u32` index of 16-byte units): the four little-endian - /// words of its bytes. Called only where [`WordMem::units`] has `vec4`. - fn read_vec4(&mut self, _fb: &mut FunctionBuilder<'_>, _index: Value) -> BResult { - Err(dangling()) - } - /// Store the `uvec4` `value` to the 16-byte unit `index`. Called only where [`WordMem::units`] - /// has `vec4`. - fn write_vec4( + /// Load the `uvecN` unit `index` of `N = lanes` words (2 or 4; a `u32` index of `4N`-byte + /// units): the little-endian words of its bytes. Called only where [`WordMem::units`] has + /// units of `4N` bytes. + fn read_vec( &mut self, _fb: &mut FunctionBuilder<'_>, + _lanes: u32, + _index: Value, + ) -> BResult { + Err(dangling()) + } + /// Store the `uvecN` `value` (`N = lanes`, 2 or 4) to the `4N`-byte unit `index`. Called only + /// where [`WordMem::units`] has units of `4N` bytes. + fn write_vec( + &mut self, + _fb: &mut FunctionBuilder<'_>, + _lanes: u32, _index: Value, _value: Value, ) -> BResult<()> { @@ -1027,25 +1058,26 @@ fn vector_words( })) } -/// Whether a 16-byte leaf's register value is one `uvec4`'s bits: four 32-bit lanes or two -/// 64-bit ones, held natively (not chunked, nor as word pairs). -fn vec4_bits(leaf: &Leaf) -> bool { +/// Whether a vector unit's leaf (8 or 16 bytes) has a register value of the `uvecN`'s bits: +/// 32-bit lanes, or 64-bit ones, filling its bytes, held natively (not chunked, nor as word pairs). +fn vec_bits(leaf: &Leaf) -> bool { let form = leaf.form; + let lanes = u32::from(form.lanes); !leaf.chunked() && !form.is_wide() - && matches!( - (form.held, form.lanes), - ( - Held::Int { - bits: 32, - container: 32 - } | Held::Float(FloatFmt::F32), - 4 - ) | ( - Held::Int { container: 64, .. } | Held::Float(FloatFmt::F64), - 2 - ) - ) + && match form.held { + Held::Int { + bits: 32, + container: 32, + } + | Held::Float(FloatFmt::F32) => 4 * lanes == leaf.bytes, + Held::Int { + bits: 64, + container: 64, + } + | Held::Float(FloatFmt::F64) => 8 * lanes == leaf.bytes, + _ => false, + } } /// `v` as type `to` of the same bits: itself, or one bitcast. @@ -1056,25 +1088,27 @@ fn as_bits(fb: &mut FunctionBuilder<'_>, v: Value, to: TypeId) -> BResult fb.convert(ConvOp::Bitcast, v, to) } -/// The register value of 16-byte `leaf` from `v`, the `uvec4` of its little-endian words: one -/// bitcast where its bits are the vector's ([`vec4_bits`]), else [`value_of`] of the four words. -fn value_of_vec4(fb: &mut FunctionBuilder<'_>, leaf: &Leaf, v: Value) -> BResult { - if vec4_bits(leaf) { +/// The register value of 8- or 16-byte `leaf` from `v`, the `uvec2` or `uvec4` of its +/// little-endian words: one bitcast where its bits are the vector's ([`vec_bits`]), else +/// [`value_of`] of the words. +fn value_of_vec(fb: &mut FunctionBuilder<'_>, leaf: &Leaf, v: Value) -> BResult { + if vec_bits(leaf) { let ty = ops::ty(fb, leaf.form)?; return as_bits(fb, v, ty); } - let mut words = Vec::with_capacity(4); - for i in 0..4 { + let mut words = Vec::with_capacity(leaf.words() as usize); + for i in 0..leaf.words() { words.push(fb.composite_extract(v, &[i])?); } value_of(fb, leaf, &words) } -/// The `uvec4` of 16-byte `leaf`'s register value `v`, its little-endian words: one bitcast where -/// its bits are the vector's ([`vec4_bits`]), else [`words_of`] gathered. -fn vec4_of(fb: &mut FunctionBuilder<'_>, leaf: &Leaf, v: Value) -> BResult { - let ty = uvec_ty(fb, 4)?; - if vec4_bits(leaf) { +/// The `uvec2` or `uvec4` of 8- or 16-byte `leaf`'s register value `v`, its little-endian words: +/// one bitcast where its bits are the vector's ([`vec_bits`]), else [`words_of`] gathered. +fn vec_of(fb: &mut FunctionBuilder<'_>, leaf: &Leaf, v: Value) -> BResult { + let lanes = u8::try_from(leaf.words()).map_err(|_| dangling())?; + let ty = uvec_ty(fb, lanes)?; + if vec_bits(leaf) { return as_bits(fb, v, ty); } let words = words_of(fb, leaf, v)?; @@ -1178,13 +1212,13 @@ pub fn load( off: Value, ) -> BResult { let words = match leaf.path { - // The leaf's one `uvec4` unit, at `off / 16`. - Path::Vec4 if mem.units().vec4 => { - let index = shr(fb, off, 4)?; - let v = mem.read_vec4(fb, index)?; - return value_of_vec4(fb, leaf, v); + // The leaf's one `uvec4` unit at `off / 16`, or `uvec2` unit at `off / 8`. + Path::Vec4 | Path::Vec2 if mem.units().has(leaf.bytes) => { + let index = shr(fb, off, leaf.bytes.trailing_zeros())?; + let v = mem.read_vec(fb, leaf.words(), index)?; + return value_of_vec(fb, leaf, v); } - Path::Vec4 | Path::Aligned => { + Path::Vec4 | Path::Vec2 | Path::Aligned => { let two = k32(fb, 2)?; let w = u32_op(fb, BinOp::ShiftRightLogical, off, two)?; let mut words = Vec::with_capacity(leaf.words() as usize); @@ -1250,17 +1284,17 @@ pub fn store( off: Value, v: Value, ) -> BResult { - // The leaf's one `uvec4` unit, at `off / 16`. - if leaf.path == Path::Vec4 && mem.units().vec4 { - let x = vec4_of(fb, leaf, v)?; - let index = shr(fb, off, 4)?; - mem.write_vec4(fb, index, x)?; + // The leaf's one `uvec4` unit at `off / 16`, or `uvec2` unit at `off / 8`. + if matches!(leaf.path, Path::Vec4 | Path::Vec2) && mem.units().has(leaf.bytes) { + let x = vec_of(fb, leaf, v)?; + let index = shr(fb, off, leaf.bytes.trailing_zeros())?; + mem.write_vec(fb, leaf.words(), index, x)?; return Ok(false); } let mut merged = false; let words = words_of(fb, leaf, v)?; match leaf.path { - Path::Vec4 | Path::Aligned => { + Path::Vec4 | Path::Vec2 | Path::Aligned => { let two = k32(fb, 2)?; let w = u32_op(fb, BinOp::ShiftRightLogical, off, two)?; let units = mem.units().intersect(leaf_units(leaf, true)); diff --git a/crates/metal2vulkan/src/memory/views.rs b/crates/metal2vulkan/src/memory/views.rs index f2fc29795..a8813d26d 100644 --- a/crates/metal2vulkan/src/memory/views.rs +++ b/crates/metal2vulkan/src/memory/views.rs @@ -28,15 +28,17 @@ //! alignment of 1 or 2 to the unit index, and the word view's `OpArrayLength` still contains every //! access. //! -//! A storage or uniform slot may also have a **`uvec4` view** ([`Vec4View`]): `StorageBuffer { +//! A storage or uniform slot may also have a **`uvec4` view** ([`VecView`]): `StorageBuffer { //! uvec4[] }` or `Uniform { uvec4[N] }` at the slot's binding, declared where an access of the slot //! moves a 16-byte leaf whose AIR alignment is at least 16 at an offset `residual + m` proven a //! multiple of 16 (`memory::leaf`'s placement: the residual's alignment is the bind offset's, and -//! `m`'s is its structure's; a `UniformVec4` word view is its own). The binder's 16-byte-aligned -//! descriptor bases carry that alignment to the unit index `(residual + m) / 16`, and a 16-aligned -//! 16-byte leaf lies wholly inside or wholly outside a bound range (every range is a whole number -//! of 16-byte units), so the word view's containment check of the leaf's 16 bytes is the unit's. -//! `u64[]` views are not declared. +//! `m`'s is its structure's; a `UniformVec4` word view is its own). A storage slot may likewise +//! have a **`uvec2` view**, `StorageBuffer { uvec2[] }`, where an access moves an 8-byte leaf whose +//! AIR alignment is at least 8 at an offset proven a multiple of 8 (a uniform slot has none: a +//! std140 array's stride is 16). The binder's 16-byte-aligned descriptor bases carry that alignment +//! to the unit index `(residual + m) / 16` or `/ 8`, and such a leaf lies wholly inside or wholly +//! outside a bound range (every range is a whole number of 16-byte units), so the word view's +//! containment check of the leaf's bytes is the unit's. `u64[]` views are not declared. use crate::pipeline::sym::{ResourceKind, ResourceSlot, SlotRef}; use crate::spirv::builder::{FunctionBuilder, ModuleBuilder}; @@ -229,23 +231,24 @@ pub struct NarrowView { pub u32_ty: TypeId, } -/// A `uvec4` view of a descriptor slot: `StorageBuffer { uvec4[] }` or `Uniform { uvec4[N] }` at -/// the slot's binding beside its word view, or a `UniformVec4` word view itself. A unit is `uvec4` -/// element `index` of member 0. +/// A `uvec4` or `uvec2` view of a descriptor slot: `StorageBuffer { uvec4[] }`, `StorageBuffer { +/// uvec2[] }` or `Uniform { uvec4[N] }` at the slot's binding beside its word view, or a +/// `UniformVec4` word view itself. A unit is vector element `index` of member 0. #[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct Vec4View { +pub struct VecView { pub global: GlobalId, /// The view's storage class: a uniform view's vectors are read-only, read plainly. pub class: StorageClass, } -/// The unit views of a descriptor slot beside its word view: a storage slot's narrow views -/// and a storage or uniform slot's `uvec4` view. +/// The unit views of a descriptor slot beside its word view: a storage slot's narrow and `uvec2` +/// views and a storage or uniform slot's `uvec4` view. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct UnitViews { pub u16: Option, pub u8: Option, - pub vec4: Option, + pub vec2: Option, + pub vec4: Option, } impl UnitViews { @@ -253,6 +256,7 @@ impl UnitViews { pub const NONE: UnitViews = UnitViews { u16: None, u8: None, + vec2: None, vec4: None, }; @@ -261,10 +265,20 @@ impl UnitViews { crate::memory::leaf::Units { u16: self.u16.is_some(), u8: self.u8.is_some(), + vec2: self.vec2.is_some(), vec4: self.vec4.is_some(), } } + /// The vector view of `lanes`-word units (2 or 4). + pub fn vec(&self, lanes: u32) -> Option { + match lanes { + 2 => self.vec2, + 4 => self.vec4, + _ => None, + } + } + /// The view of `bytes`-byte units (1 or 2). pub fn of(&self, bytes: u32) -> Option { match bytes { @@ -275,9 +289,9 @@ impl UnitViews { } /// Declare the unit views of `units` for `slot`, whose word view [`declare`] declared as - /// `view`: a storage view's narrow and `uvec4` views, a `UniformWords` view's `uvec4` view; a - /// `UniformVec4` view is its own `uvec4` view, declared or not. A uniform slot has no narrow - /// view. + /// `view`: a storage view's narrow, `uvec2` and `uvec4` views, a `UniformWords` view's `uvec4` + /// view; a `UniformVec4` view is its own `uvec4` view, declared or not. A uniform slot has no + /// narrow or `uvec2` view. pub fn declare( mb: &mut ModuleBuilder, slot: SlotRef, @@ -296,40 +310,54 @@ impl UnitViews { } else { None }, + vec2: if storage && units.vec2 { + Some(declare_vec(mb, slot, view, 2)?) + } else { + None + }, vec4: match view.kind { - ViewKind::UniformVec4 { .. } => Some(Vec4View { + ViewKind::UniformVec4 { .. } => Some(VecView { global: view.global, class: StorageClass::Uniform, }), - _ if units.vec4 => Some(declare_vec4(mb, slot, view)?), + _ if units.vec4 => Some(declare_vec(mb, slot, view, 4)?), _ => None, }, }) } } -/// Declare the `uvec4` view of `slot`, whose word view [`declare`] declared as `view`: -/// `StorageBuffer { uvec4[] }` (std430) beside a storage view, or `Uniform { uvec4[words / 4] }` -/// (std140, valid without `uniformBufferStandardLayout`) beside a `UniformWords` view, whose size -/// is a multiple of 16 bytes ([`uniform_range`]). Both have `ArrayStride` 16, and the serializer -/// decorates the storage one `Aliased` as every storage view of a Metal buffer. -pub fn declare_vec4(mb: &mut ModuleBuilder, slot: SlotRef, view: View) -> BResult { +/// Declare the `uvecN` view (`N = lanes`, 2 or 4) of `slot`, whose word view [`declare`] declared +/// as `view`: `StorageBuffer { uvecN[] }` (std430, `ArrayStride` `4N`) beside a storage view, or +/// `Uniform { uvec4[words / 4] }` (std140, valid without `uniformBufferStandardLayout`) beside a +/// `UniformWords` view, whose size is a multiple of 16 bytes ([`uniform_range`]). The serializer +/// decorates a storage one `Aliased` as every storage view of a Metal buffer. A uniform view has no +/// `uvec2` view: a std140 array's stride is 16. +pub fn declare_vec( + mb: &mut ModuleBuilder, + slot: SlotRef, + view: View, + lanes: u32, +) -> BResult { let sym = binding_symbol(slot); let u32_ty = u32_type(mb)?; - let v4 = mb.ty(Type::Vector { - elem: u32_ty, - len: 4, - })?; + let len = u8::try_from(lanes) + .ok() + .filter(|&l| matches!(l, 2 | 4)) + .ok_or(crate::spirv::error::BuildError::Global( + crate::spirv::error::GlobalRule::ResourceType, + ))?; + let vec = mb.ty(Type::Vector { elem: u32_ty, len })?; let (class, rule, member) = match view.kind { ViewKind::Storage => ( StorageClass::StorageBuffer, LayoutRule::Std430, mb.ty(Type::RuntimeArray { - elem: v4, - stride: Some(16), + elem: vec, + stride: Some(4 * lanes), })?, ), - ViewKind::UniformWords { words } => { + ViewKind::UniformWords { words } if lanes == 4 => { let len = mb.constant(Constant::Scalar { ty: u32_ty, bits: ConstBits(u64::from(words / 4)), @@ -338,19 +366,24 @@ pub fn declare_vec4(mb: &mut ModuleBuilder, slot: SlotRef, view: View) -> BResul StorageClass::Uniform, LayoutRule::Std140, mb.ty(Type::Array { - elem: v4, + elem: vec, len, stride: Some(16), })?, ) } // The word view is already one. - ViewKind::UniformVec4 { .. } => { - return Ok(Vec4View { + ViewKind::UniformVec4 { .. } if lanes == 4 => { + return Ok(VecView { global: view.global, class: StorageClass::Uniform, }) } + ViewKind::UniformWords { .. } | ViewKind::UniformVec4 { .. } => { + return Err(crate::spirv::error::BuildError::Global( + crate::spirv::error::GlobalRule::ResourceType, + )) + } }; let layout = natural_layout(mb.types(), rule, true, &[member])?; let block = mb.ty(Type::Struct { @@ -358,13 +391,13 @@ pub fn declare_vec4(mb: &mut ModuleBuilder, slot: SlotRef, view: View) -> BResul layout: Some(layout), })?; let global = mb.resource_view(sym, class, block)?; - Ok(Vec4View { global, class }) + Ok(VecView { global, class }) } -/// Load `uvec4` unit `index` of `view` with memory operands `ops`. -pub fn read_vec4( +/// Load vector unit `index` of `view` with memory operands `ops`. +pub fn read_vec( fb: &mut FunctionBuilder<'_>, - view: Vec4View, + view: VecView, index: Value, ops: MemAccess, ) -> BResult { @@ -374,10 +407,10 @@ pub fn read_vec4( fb.load(p, ops) } -/// Store the `uvec4` `value` to unit `index` of storage view `view` with memory operands `ops`. -pub fn write_vec4( +/// Store the vector `value` to unit `index` of storage view `view` with memory operands `ops`. +pub fn write_vec( fb: &mut FunctionBuilder<'_>, - view: Vec4View, + view: VecView, index: Value, value: Value, ops: MemAccess, diff --git a/crates/metal2vulkan/src/tests/engine_access.rs b/crates/metal2vulkan/src/tests/engine_access.rs index 479227576..595f81e70 100644 --- a/crates/metal2vulkan/src/tests/engine_access.rs +++ b/crates/metal2vulkan/src/tests/engine_access.rs @@ -21,7 +21,8 @@ //! window longer than 2³² is refused. //! - Constant GEP indices whose products exceed 128 bits wrap to the offset's low word. //! - A 16-byte leaf is one element of its slot's `uvec4` view only at an offset proven a multiple -//! of 16; a `float4` whose offset is a multiple of 4 and not of 16 is read and written at that +//! of 16, and an 8-byte leaf one element of its `uvec2` view only at an offset proven a multiple +//! of 8; a `float4` whose offset is a multiple of 4 and not of 16 is read and written at that //! offset, as Metal does, whatever the `align 16` its AIR states. //! //! `llvm-as` assembles the fixtures; without it the tests skip visibly. @@ -498,10 +499,11 @@ fn leaf_kernel(k: &LeafKernel) -> String { ) } -/// [`leaf_kernel`] with its offset proven a multiple of 16: `params[0]` counts 16-byte units -/// (a GEP over `<4 x i32>`), and `data` and `out` are `uint4` buffers (`air.arg_type_align_size` -/// 16, so Metal binds them at multiples of 16). -fn leaf_kernel_in_units(k: &LeafKernel) -> String { +/// [`leaf_kernel`] with its offset proven a multiple of `unit` (8 or 16): `params[0]` counts +/// `unit`-byte units (a GEP over ``), and `data` and `out` are `uint2` or `uint4` +/// buffers (`air.arg_type_align_size` `unit`, so Metal binds them at multiples of `unit`). +fn leaf_kernel_in(k: &LeafKernel, unit: u32) -> String { + let lanes = unit / 4; let name = k.name; let ty = k.ty; let a = k.align; @@ -513,10 +515,10 @@ fn leaf_kernel_in_units(k: &LeafKernel) -> String { }; let meta = meta(name).replace( "!\"air.arg_type_size\", i32 1, !\"air.arg_type_align_size\", i32 1, !\"air.arg_type_name\", !\"uchar\"", - "!\"air.arg_type_size\", i32 16, !\"air.arg_type_align_size\", i32 16, !\"air.arg_type_name\", !\"uint4\"", + &format!("!\"air.arg_type_size\", i32 {unit}, !\"air.arg_type_align_size\", i32 {unit}, !\"air.arg_type_name\", !\"uint{lanes}\""), ); format!( - "{HEADER}define void @{name}(ptr addrspace(1) noundef \"air-buffer-no-alias\" %0, ptr addrspace(1) noundef \"air-buffer-no-alias\" %1, ptr addrspace(1) noundef \"air-buffer-no-alias\" %2) {{\nentry:\n %o = load i32, ptr addrspace(1) %2, align 4\n %p = getelementptr <4 x i32>, ptr addrspace(1) %0, i32 %o\n{body} ret void\n}}\n\n{meta}" + "{HEADER}define void @{name}(ptr addrspace(1) noundef \"air-buffer-no-alias\" %0, ptr addrspace(1) noundef \"air-buffer-no-alias\" %1, ptr addrspace(1) noundef \"air-buffer-no-alias\" %2) {{\nentry:\n %o = load i32, ptr addrspace(1) %2, align 4\n %p = getelementptr <{lanes} x i32>, ptr addrspace(1) %0, i32 %o\n{body} ret void\n}}\n\n{meta}" ) } @@ -2208,8 +2210,12 @@ fn an_unaliased_unwritten_buffer_is_non_writable() { /// wrapped. const VEC4_RESIDUALS: [u32; 6] = [0, 4, 12, 16, 36, 0xFFFF_FFF0]; +/// The residuals the 8-byte leaves are checked at: zero, below 8, a multiple of 8 and not of 16, a +/// multiple of 16, past 32, and wrapped. +const VEC2_RESIDUALS: [u32; 7] = [0, 4, 8, 16, 24, 36, 0xFFFF_FFF8]; + /// A 16-byte leaf whose alignment is at least 16 at an offset proven a multiple of 16 -/// ([`leaf_kernel_in_units`]) is one element of the slot's `uvec4` view (declared beside the word +/// ([`leaf_kernel_in`] over `uint4` buffers) is one element of the slot's `uvec4` view (declared beside the word /// view, and stored with one `OpStore`), in both encodings, on every tested profile; aligned to 4, /// or at an offset nothing proves a multiple of 16 ([`leaf_kernel`]'s byte offset from a buffer, /// whatever its `align`), it moves word by word (four stores, no `uvec4` view of the slot it stores @@ -2219,20 +2225,87 @@ const VEC4_RESIDUALS: [u32; 6] = [0, 4, 12, 16, 36, 0xFFFF_FFF0]; /// with the in-shader check the offset past the range reads 0 and writes nothing. #[test] fn sixteen_byte_leaves_move_as_one_uvec4() { - const OP_STORE: u16 = 62; let kernels = leaf_kernels(); - let sixteen: Vec<&LeafKernel> = kernels - .iter() + let sixteen: Vec = kernels + .into_iter() .filter(|k| k.bytes == 16 && k.align >= 4) .collect(); assert_eq!(sixteen.len(), 13, "the aligned 16-byte leaf kernels"); + leaves_move_as_one_vector(&sixteen, 16, &VEC4_RESIDUALS); +} + +/// An 8-byte leaf whose alignment is at least 8 at an offset proven a multiple of 8 +/// ([`leaf_kernel_in`] over `uint2` buffers) is one element of the slot's `uvec2` view (declared +/// beside the word view, and stored with one `OpStore`): two 32-bit lanes and one 64-bit lane by +/// one bitcast, `half4` and a chunked `uchar8` through their words. Aligned to 4, or at an offset +/// nothing proves a multiple of 8, it moves word by word (two stores, no `uvec2` view of the slot +/// it stores to). At every residual its buffer's alignment allows, the leaf's 8 bytes of a 48-byte +/// range are read and written exactly, in both encodings, on every tested profile, and with the +/// in-shader check the offset past the range reads 0 and writes nothing. +#[test] +fn eight_byte_leaves_move_as_one_uvec2() { + let mut eight: Vec = leaf_kernels() + .into_iter() + .filter(|k| k.bytes == 8 && k.align >= 4) + .collect(); + let k = |name, ty, align| LeafKernel { + name, + ty, + bytes: 8, + align, + store: None, + }; + let s = |name, ty, align, c, b: &[u8]| LeafKernel { + name, + ty, + bytes: 8, + align, + store: Some((c, b.to_vec())), + }; + let float2 = [1.5f32.to_le_bytes(), (-2.0f32).to_le_bytes()].concat(); + eight.extend([ + k("load_float2", "<2 x float>", 8), + k("load_long", "i64", 8), + k("load_float2_word_aligned", "<2 x float>", 4), + s( + "store_float2", + "<2 x float>", + 8, + "", + &float2, + ), + s( + "store_long", + "i64", + 8, + "-81985529216486896", + &(-81_985_529_216_486_896i64).to_le_bytes(), + ), + s( + "store_float2_word_aligned", + "<2 x float>", + 4, + "", + &float2, + ), + ]); + assert_eq!(eight.len(), 9, "the aligned 8-byte leaf kernels"); + leaves_move_as_one_vector(&eight, 8, &VEC2_RESIDUALS); +} + +/// The check of [`sixteen_byte_leaves_move_as_one_uvec4`] and +/// [`eight_byte_leaves_move_as_one_uvec2`] over `kernels`, all `unit` bytes (8 or 16), at +/// `residuals`. +fn leaves_move_as_one_vector(kernels: &[LeafKernel], unit: u32, residuals: &[u32]) { + const OP_STORE: u16 = 62; + let words = (unit / 4) as usize; for (what, p) in encodings() { let robust = what.ends_with("robust=true"); - for k in &sixteen { + for k in kernels { for units in [true, false] { let what = format!("{what} {} units={units}", k.name); let text = if units { - leaf_kernel_in_units(k) + leaf_kernel_in(k, unit) } else { leaf_kernel(k) }; @@ -2242,12 +2315,13 @@ fn sixteen_byte_leaves_move_as_one_uvec4() { check_l3(&bc, k.name, &p, &what); let (plan, m) = typed_module(&bc, k.name, &p).unwrap_or_else(|e| panic!("{what}: {e}")); - let vec4 = units && k.align >= 16; + let vec = units && k.align >= unit; // A load kernel stores the loaded leaf to `out` at alignment 16, at offset 0 of a - // buffer whose bind offset is a multiple of 16 where it is a `uint4` buffer. + // buffer whose bind offset is a multiple of `unit` where it is a `uint2` or + // `uint4` buffer. assert_eq!( views_of(&m, 0), - if vec4 { 2 } else { 1 }, + if vec { 2 } else { 1 }, "{what}: views of data" ); assert_eq!( @@ -2266,24 +2340,23 @@ fn sixteen_byte_leaves_move_as_one_uvec4() { .filter(|o| **o == OP_STORE) .count(); let want = match (&k.store, units) { - (Some(_), _) if !vec4 => 4, - (None, false) => 4, + (Some(_), _) if !vec => words, + (None, false) => words, _ => 1, }; assert_eq!(stores, want, "{what}: stores"); let data = pattern(48); - // A `uint4` buffer is bound at a multiple of 16. - let residuals = VEC4_RESIDUALS.iter().filter(|r| !units || *r % 16 == 0); + // A `uint2` or `uint4` buffer is bound at a multiple of its size. + let residuals = residuals.iter().filter(|r| !units || *r % unit == 0); for &r in residuals { // The interpreter models no robustness: robust encodings run in bounds only. - let descs: &[u32] = if robust { - &[0, 16, 32] - } else { - &[0, 16, 32, 48] - }; - for &desc in descs { + let descs: Vec = (0..=48 / unit) + .map(|i| i * unit) + .filter(|d| !robust || d + unit <= 48) + .collect(); + for desc in descs { let o = desc.wrapping_sub(r); - let o = if units { o / 16 } else { o }; + let o = if units { o / unit } else { o }; let mut params = vec![0u8; 16]; params[..4].copy_from_slice(&o.to_le_bytes()); let res = Resources { @@ -2302,24 +2375,21 @@ fn sixteen_byte_leaves_move_as_one_uvec4() { let out = run(&m, &Config::default(), res) .unwrap_or_else(|e| panic!("{what} r={r:#x} desc={desc}: {e:?}")); let at = desc as usize; - let inb = at + 16 <= data.len(); + let n = unit as usize; + let inb = at + n <= data.len(); match &k.store { None => { let want: Vec = if inb { - data[at..at + 16].to_vec() + data[at..at + n].to_vec() } else { - vec![0; 16] + vec![0; n] }; - assert_eq!( - out.buffers[1][..16], - want[..], - "{what} r={r:#x} {desc}" - ); + assert_eq!(out.buffers[1][..n], want[..], "{what} r={r:#x} {desc}"); } Some((_, bytes)) => { let mut want = data.clone(); if inb { - want[at..at + 16].copy_from_slice(bytes); + want[at..at + n].copy_from_slice(bytes); } if native_halves { assert!( diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index 872387389..7e598b9d3 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -107,7 +107,7 @@ known. The rest of the differences are docs/API.md section 9's precision notes. | On MoltenVK a no-copy buffer or heap released with no keep-alive while batches are in flight runs its deallocator once the batches submitted before its release completed, and the program's own submissions through `CommandQueue::with_vk_queue` before it, where Metal runs it at the release. | MoltenVK 1.4.1 fails pending work that reads device addresses where memory a device-address buffer lay in is freed (`RuntimeDriverDefect::FreedAddressMemoryFailsPendingWork`), so freed memory waits for the batches in flight (`WorkCounts::freed_memory_parked`). | `HostDeallocatorDelayed` (`host-deallocator-delayed`) | | On MoltenVK a `Shared` or `Managed` texture whose format packs more than one texel into a block (every block-compressed family) keeps its image out of host-transfer memory, so its CPU copies take submissions where another driver's take none. The stored texels are Metal's either way; what changes is the work, in `WorkCounts::command_buffers_begun_batch_work` and the `command_buffers_begun` and `command_buffers_submitted` that carry it (`bc1-rgba`, four 16 x 16 `BC1_RGBA` levels: `command_buffers_begun` 8 on the bind-time path and 15 off it; `fresh-texture-bc1-rgba-managed`: 3 and 5). A `replaceRegion` of such a texture stages its bytes for the device's next submission and waits for none (`texture/first_move.rs`). Its CPU **reads** come out of a host shadow of the image's texels, made at the first read of the texture by the submission that read waits for either way and read from by every read after it: exact (it holds the image's own bytes, and a CPU write writes both), bounded (`host_shadow::SHADOW_BYTES`, past which a read takes the submission path), and lazy, so a texture nobody reads back holds nothing. It is dropped wherever anything but a CPU write may have written the texels: every commit of the program's, its own Vulkan submissions, another `VkImage`, a detach, or the program taking the image's handle (`texture/host_shadow.rs`; `WorkCounts::texel_shadows_made`, `texel_shadow_reads`, `texel_shadows_dropped`). Measured on an M3 Max: `compressed-moves-bc1-rgba` reads `internal_submissions` 5 where it read 56 and `command_buffers_begun` 30 where it read 81, for 1,168 bytes of shadow over its five textures and 56 reads out of them. | MoltenVK 1.4.2 binds such an image through a `flushToDevice` that `replaceRegion:`s every subresource at one block's bytes a row instead of the row of blocks, tripping AGX's `bytes_per_row >= used_bytes_per_row` assertion (`RuntimeDriverDefect::HostTransferImagesCopiedAtBind`). The copy is the driver's own and no call of the program's asks for it, so the only way not to provoke it is not to ask for the image; every other driver keeps the host-transfer path, as does a device without `VK_EXT_host_image_copy`. A write cannot leave the GPU's copy of the texels unwritten, so only reads come off the host shadow. | None (cost only, and exact) | | On a GPU without unified memory whose types for host-transfer images lie in a heap with no room left, a `Shared` or `Managed` texture made then takes no host-transfer usage: its image lies in device-local memory where that image has room, and its CPU copies take submissions where those of a texture made while the heap had room take none (`memory::host_image_types`, `texture/host_copy.rs`). An RTX 3090 without resizable BAR (NVIDIA 620.70.06) places such images in its 246 MiB BAR heap alone, which every process's devices share, beside a device-local heap of 24 GiB; a color texture there copies on NVIDIA's staging queue where its image has both transfer usages (`texture/staging_copy.rs`), so this reaches its depth and stencil textures and the color textures it does not stage. The texels are Metal's either way. | The heap's size is the device's (resizable BAR is the platform's setting). The other memory with room is system memory, where the GPU would reach the image across the bus for as long as it lives (`device-memory-overflow`) to spare the CPU copies their submissions. | None (cost only, and exact) | -| On a driver that does not take a set-0 buffer binding whose entry point uses it through several variables as a **dynamic** descriptor, a draw or dispatch of such a variant that binds it at another offset than its predecessor did allocates and writes a descriptor set of its own, where a dynamic binding would let it bind its predecessor's set again at its own offset. That saving needs the binding's range to stay as its offset moves (`bind::instantiate::descriptor_range`): a slot read to its buffer's end has a range that moves with its offset, so its commands write a set each in either form. Such a binding is a slot reached through its word view and a narrow or `uvec4` unit view (`memory::views`), as `record_stride_not_a_multiple_of_four`'s `recs` is. The stored values are the same either way; what changes is the set a command allocates and writes (`WorkCounts::set_zero_sets_reused` counts none of them). The device answers for itself, by creating one pipeline of exactly that shape and destroying it (`pipeline::objects::takes_multi_variable_dynamic`, `bind::DynamicViewsModule`, asked once and only where a layout has such a binding), so a driver without the defect pays nothing. A binding the device takes still turns dynamic only while the layout's dynamic-buffer budget lasts (`maxDescriptorSetUniformBuffersDynamic`, `maxDescriptorSetStorageBuffersDynamic`), spent in binding order: on a Radeon 780M (RADV, Mesa 26.2.4, eight dynamic storage buffers) a layout's storage bindings past the eighth get none, so commands that bind them at moving offsets keep a set each wherever set 0 is not pushed. A device whose set 0 is pushed (`VK_KHR_push_descriptor` with an eligible layout) never reaches the choice. | Nothing in Vulkan bounds the variables at a binding, dynamic or not, so there is no exact form to switch to: the driver either compiles the shape or does not. MoltenVK's SPIRV-Cross declares one variable's local alone -- read in 1.4.1's source and measured on 1.4.2 (`driverVersion` 10402) on an Apple M3 Max, where `vkCreateComputePipelines` answers `VK_ERROR_INITIALIZATION_FAILED` for a kernel of three and of four variables at one dynamic binding. The check proves the driver compiles the shape, not that it applies the dynamic offset to every variable at it; no device is measured to get that wrong, and RADV (Mesa 26.2.4, Radeon 780M, at offset 0) and lavapipe (Mesa, arm64, at moving offsets) are measured to get it right, `record_stride_not_a_multiple_of_four` answering Metal's `sizeof` and both its narrow stores with its three-variable binding dynamic. | None (cost only, and exact) | +| On a driver that does not take a set-0 buffer binding whose entry point uses it through several variables as a **dynamic** descriptor, a draw or dispatch of such a variant that binds it at another offset than its predecessor did allocates and writes a descriptor set of its own, where a dynamic binding would let it bind its predecessor's set again at its own offset. That saving needs the binding's range to stay as its offset moves (`bind::instantiate::descriptor_range`): a slot read to its buffer's end has a range that moves with its offset, so its commands write a set each in either form. Such a binding is a slot reached through its word view and a narrow, `uvec2` or `uvec4` unit view (`memory::views`), as `record_stride_not_a_multiple_of_four`'s `recs` is. The stored values are the same either way; what changes is the set a command allocates and writes (`WorkCounts::set_zero_sets_reused` counts none of them). The device answers for itself, by creating one pipeline of exactly that shape and destroying it (`pipeline::objects::takes_multi_variable_dynamic`, `bind::DynamicViewsModule`, asked once and only where a layout has such a binding), so a driver without the defect pays nothing. A binding the device takes still turns dynamic only while the layout's dynamic-buffer budget lasts (`maxDescriptorSetUniformBuffersDynamic`, `maxDescriptorSetStorageBuffersDynamic`), spent in binding order: on a Radeon 780M (RADV, Mesa 26.2.4, eight dynamic storage buffers) a layout's storage bindings past the eighth get none, so commands that bind them at moving offsets keep a set each wherever set 0 is not pushed. A device whose set 0 is pushed (`VK_KHR_push_descriptor` with an eligible layout) never reaches the choice. | Nothing in Vulkan bounds the variables at a binding, dynamic or not, so there is no exact form to switch to: the driver either compiles the shape or does not. MoltenVK's SPIRV-Cross declares one variable's local alone -- read in 1.4.1's source and measured on 1.4.2 (`driverVersion` 10402) on an Apple M3 Max, where `vkCreateComputePipelines` answers `VK_ERROR_INITIALIZATION_FAILED` for a kernel of three and of four variables at one dynamic binding. The check proves the driver compiles the shape, not that it applies the dynamic offset to every variable at it; no device is measured to get that wrong, and RADV (Mesa 26.2.4, Radeon 780M, at offset 0) and lavapipe (Mesa, arm64, at moving offsets) are measured to get it right, `record_stride_not_a_multiple_of_four` answering Metal's `sizeof` and both its narrow stores with its three-variable binding dynamic. | None (cost only, and exact) | ## Accuracy switches whose default is Metal's