diff --git a/crates/metal2vulkan/src/bind/heap.rs b/crates/metal2vulkan/src/bind/heap.rs index dfaf90cc8..002f977ad 100644 --- a/crates/metal2vulkan/src/bind/heap.rs +++ b/crates/metal2vulkan/src/bind/heap.rs @@ -125,19 +125,16 @@ //! `NotImplemented(SamplerBicubicFilter)`. //! - **Function tables**. A visible-function table loaded from an argument buffer is searched by //! its resource id in the stage's function-table directory (`Synthetic(FunctionTableDirectory)`, -//! the handle table's layout over `BindState::function_tables`, flags 0) and read from the set-1 -//! function-table array (`HandleClass::FunctionTable`, a storage-buffer array). Both hold the -//! entries of the shape's capacity class (`FunctionTablesShape::entries`, at most the heap's -//! capacity): element `i + 1` is `WriteSource::FunctionTable` for listed table `i`, whose words -//! the consumer binds, and element 0 the zero buffer, the null table. A class whose least count -//! does not fit the capacity is [`BindError::HeapTooLarge`] at plan time, and a list longer than -//! the planned entries at instantiation. On a device without the array's features the stage reads -//! a function-table snapshot (`Synthetic(FunctionTableSnapshot)`) in its place, written -//! `WriteSource::FunctionTableSnapshot`, and the directory gives each listed id its record's word -//! offset there (`FunctionTableSnapshot` of the listed sizes) instead of an element; the capacity -//! is then the handle table's reach alone. Where the listed tables' words may pass +//! the handle table's layout over `BindState::function_tables`, flags 0), which holds the +//! entries of the shape's capacity class (`FunctionTablesShape::entries`, at most the handle +//! table's reach), and read from the stage's function-table snapshot +//! (`Synthetic(FunctionTableSnapshot)`), written `WriteSource::FunctionTableSnapshot`: the +//! directory gives each listed id its record's word offset there (`FunctionTableSnapshot` of the +//! listed sizes). A class whose least count does not fit the capacity is +//! [`BindError::HeapTooLarge`] at plan time, and a list longer than the planned entries at +//! instantiation. Where the listed tables' words may pass //! `maxStorageBufferRange` (`FunctionTablesShape::may_pass`), the variant that reads them through -//! their device addresses (`ResourceTemplate::function_table_addresses`) declares neither: the +//! their device addresses (`ResourceTemplate::function_table_addresses`) declares no snapshot: the //! directory's entry holds the table's address in its element and flags words, and a listed table //! without one cannot be represented. @@ -1068,14 +1065,13 @@ pub(crate) struct HeapPlanner<'a> { samplers: Option<(ArgumentSamplersShape, u32, SamplerAdmission)>, /// The function-table directories, `(stage, set, binding)`. directories: Vec<(Stage, u32, u32)>, - /// The function-table snapshots, `(stage, set, binding)`, of a device without the - /// function-table array's features. + /// The function-table snapshots, `(stage, set, binding)`. snapshots: Vec<(Stage, u32, u32)>, /// The pipeline reads its function tables through the addresses its directories hold /// (`VariantKey::addressed_function_tables`). addressed_tables: bool, - /// The function tables' shape and the entries of the function-table array and every - /// directory, when the pipeline has a directory. + /// The function tables' shape and the entries of every directory, when the pipeline has a + /// directory. function_tables: Option<(FunctionTablesShape, u32)>, /// The zero buffer's bytes: the null table's (`neutral::zero_buffer_bytes`). zero_bytes: u32, @@ -1221,7 +1217,6 @@ impl<'a> HeapPlanner<'a> { // An argument sampler's uses, a cube's explicit gradients included. let sampler_uses: Vec = classes.iter().filter_map(|c| c.sampler_use()).collect(); - let function_table_array = classes.contains(&HandleClass::FunctionTable); let images = classes .iter() .filter(|c| matches!(c, HandleClass::Image(_))) @@ -1232,19 +1227,15 @@ impl<'a> HeapPlanner<'a> { if !sampler_uses.is_empty() && sampler_tables.is_empty() { return Err(internal("a sampler array without a sampler table")); } - // Directories read the tables from the array, or from a snapshot on a device without - // the array's features, or at the addresses they hold: one of the three, never two. + // Directories read the tables from a snapshot, or at the addresses they hold: one of the + // two, never both. let addressed_tables = dependencies .iter() .any(|d| d.fact == RuntimeFact::FunctionTableRange { addressed: true }); - let homes = [ - function_table_array, - !snapshots.is_empty(), - addressed_tables, - ] - .into_iter() - .filter(|&h| h) - .count(); + let homes = [!snapshots.is_empty(), addressed_tables] + .into_iter() + .filter(|&h| h) + .count(); if homes != usize::from(!directories.is_empty()) { return Err(internal( "function-table directories without one home of the tables' words, or with two", @@ -1504,7 +1495,7 @@ impl<'a> HeapPlanner<'a> { Ok(WriteSource::FunctionTableSnapshot) } - /// The entries of the function-table array and every directory. + /// The entries of every function-table directory. fn function_table_entries(&self) -> Result { self.function_tables .as_ref() @@ -1512,43 +1503,6 @@ impl<'a> HeapPlanner<'a> { .ok_or_else(|| internal("function tables without a directory")) } - /// The writes of the function-table array `b` of set `set`: the zero buffer, the null table, at - /// element 0, and listed table `e - 1` at each element `e` of the class. - fn function_table_array( - &self, - set: u32, - b: &DescriptorBinding, - ) -> Result, BindError> { - if b.ty != vk::DescriptorType::STORAGE_BUFFER { - return Err(internal(format!("a function-table array as {:?}", b.ty))); - } - let entries = self.function_table_entries()?; - if entries > b.count { - return Err(internal("a function-table array shorter than its entries")); - } - let write = |element: u32, source: WriteSource| DescriptorWrite { - set, - binding: b.binding, - array_element: element, - ty: b.ty, - source, - }; - let mut out = Vec::with_capacity(entries as usize); - out.push(write( - NEUTRAL_ELEMENT, - WriteSource::Neutral(NeutralResource::ZeroBuffer { - min_bytes: self.zero_bytes, - }), - )); - for element in 1..entries { - out.push(write( - element, - WriteSource::FunctionTable { index: element - 1 }, - )); - } - Ok(out) - } - /// The entries of every sampler array and table. fn sampler_entries(&self) -> Result { self.samplers @@ -1605,7 +1559,7 @@ impl<'a> HeapPlanner<'a> { HandleClass::Sampler { compare, integer } => { return self.sampler_array(set, b, (compare, integer)) } - HandleClass::FunctionTable => return self.function_table_array(set, b), + HandleClass::FunctionTable => return Err(internal("a function-table heap array")), }; let expected = match (image.access, image.dim == ImageDim::Buffer) { (ImageAccess::Storage, false) => vk::DescriptorType::STORAGE_IMAGE, @@ -1923,7 +1877,6 @@ impl<'a> HeapPlanner<'a> { template.sampler_admission = admission; template.function_table_directories = self.planned_directories; template.function_tables = self.function_tables.map(|(shape, _)| shape); - template.function_table_snapshot = !self.snapshots.is_empty(); template.function_table_addresses = self.addressed_tables; diagnostics.extend(self.diagnostics); } @@ -2126,7 +2079,6 @@ pub(crate) fn table_bytes( out.extend(directory_bytes( shape, &template.function_table_directories, - template.function_table_snapshot, template.function_table_addresses, state, )?); @@ -2137,10 +2089,9 @@ pub(crate) fn table_bytes( } /// The bytes of the function-table directories `tables`, planned for the tables' `shape`, for -/// `state`: listed table `i` is element `i + 1` (or its resource ID's under -/// `HeapPlacement::ResourceId`), its flags 0; with `snapshot`, the word offset of its record in the -/// function-table snapshot of the listed sizes, whatever the placement; with `addresses`, the -/// device address of its words, low word as the element and high word as the flags. A state of +/// `state`: listed table `i` is the word offset of its record in the function-table snapshot of +/// the listed sizes, its flags 0, whatever the placement; with `addresses`, the device address of +/// its words, low word as the element and high word as the flags. A state of /// another shape is the plan's misuse; a list longer than the planned entries is /// [`BindError::HeapTooLarge`], a snapshot past `u32::MAX` words is not representable, and a listed /// nonzero id without an address, or an addressed directory that lists no table (whose null entry's @@ -2149,7 +2100,6 @@ pub(crate) fn table_bytes( fn directory_bytes( shape: &FunctionTablesShape, tables: &[PlannedHandleTable], - snapshot: bool, addresses: bool, state: &BindState, ) -> Result, BindError> { @@ -2158,21 +2108,19 @@ fn directory_bytes( "the bind state's shape differs from the plan's at its function tables", )); } - let offsets = match snapshot { - true => Some( + let offsets = match addresses { + true => None, + false => Some( FunctionTableSnapshot::of(state.function_tables.iter().map(|f| f.size)).ok_or( BindError::Unsupported(Unsupported::not_representable(Feature::DynamicCall)), )?, ), - false => None, }; - let element = |i: usize, id: u64| match &offsets { - Some(snapshot) => snapshot - .offsets() - .get(i) - .copied() - .ok_or_else(|| internal("a listed table without its snapshot record")), - None => placed(i, id, state.heap_placement), + let element = |i: usize| { + offsets + .as_ref() + .and_then(|snapshot| snapshot.offsets().get(i).copied()) + .ok_or_else(|| internal("a listed table without its snapshot record")) }; let count = state.function_tables.len() as u64 + 1; let mut out = Vec::with_capacity(tables.len()); @@ -2199,7 +2147,7 @@ fn directory_bytes( entries.push((f.resource_id, f.address as u32, (f.address >> 32) as u32)); continue; } - entries.push((f.resource_id, element(i, f.resource_id)?, 0)); + entries.push((f.resource_id, element(i)?, 0)); } // The null entry's loads take the last entry's address, a listed table's: a directory of // null entries alone gives them none. @@ -2349,17 +2297,14 @@ pub struct HeapElements { /// Under `ResourceId`, by planned element `e`: listed sampler `e - 1`'s element, else its /// resource ID. samplers: Vec>, - /// Under `ResourceId`, by planned element `e`: listed function table `e - 1`'s resource ID. - function_tables: Vec>, } impl HeapElements { /// The array element of `write`, one of the plan's descriptor writes: its own element for a /// write outside the heap set, the neutral element, and every write under `Planned`; under - /// `ResourceId`, the resource ID of the member or listed function table it holds, or the - /// listed sampler's element (its resource ID where it names none), or `None` where the - /// command needs no write (a member no handle names, a sampler or - /// table element past the list). + /// `ResourceId`, the resource ID of the member it holds, or the listed sampler's element (its + /// resource ID where it names none), or `None` where the command needs no write (a member no + /// handle names, a sampler element past the list). pub fn element(&self, write: &DescriptorWrite) -> Option { let e = write.array_element; if write.set != HEAP_SET || e == NEUTRAL_ELEMENT || self.placement == HeapPlacement::Planned @@ -2368,7 +2313,6 @@ impl HeapElements { } let held = match write.ty { vk::DescriptorType::SAMPLER => &self.samplers, - vk::DescriptorType::STORAGE_BUFFER => &self.function_tables, _ => &self.members, }; held.get(e as usize - 1).copied().flatten() @@ -2503,19 +2447,10 @@ fn heap_elements( .iter() .map(|s| element(Some(s.placed_at()))) .collect::>()?; - let function_tables = match template.function_tables { - Some(_) => state - .function_tables - .iter() - .map(|t| element(Some(t.resource_id))) - .collect::>()?, - None => Vec::new(), - }; Ok(HeapElements { placement, members, samplers, - function_tables, }) } diff --git a/crates/metal2vulkan/src/bind/mod.rs b/crates/metal2vulkan/src/bind/mod.rs index d0b7e969e..d763564ad 100644 --- a/crates/metal2vulkan/src/bind/mod.rs +++ b/crates/metal2vulkan/src/bind/mod.rs @@ -58,7 +58,7 @@ //! [`sampler_desc`] gives the Vulkan sampler a plan's sampler write needs, [`heap_classes`] the //! classes of the handle heap's arrays on a profile, [`FunctionTableWords`] the words of a //! visible-function table's buffer, and [`FunctionTableSnapshot`] the one buffer of a command's -//! tables' words on a device without the function-table array's features. A plan writes an +//! tables' words. A plan writes an //! acceleration structure as the top-level structure the consumer builds for it: //! [`instance_record`] gives each Metal instance's record, [`primitive_wrap`] the one instance over //! a bound primitive structure, and [`geometry_flags`] and [`geometry_table_offset`] a primitive diff --git a/crates/metal2vulkan/src/bind/plan.rs b/crates/metal2vulkan/src/bind/plan.rs index 21f2ce830..58c47a2c9 100644 --- a/crates/metal2vulkan/src/bind/plan.rs +++ b/crates/metal2vulkan/src/bind/plan.rs @@ -403,14 +403,9 @@ pub(crate) struct ResourceTemplate { /// Each stage's function-table directory. #[cfg_attr(feature = "serde", serde(default))] pub function_table_directories: Vec, - /// The tables' shape the function-table array and directories were planned for, when the - /// plan has one. + /// The tables' shape the function-table directories were planned for, when the plan has one. #[cfg_attr(feature = "serde", serde(default))] pub function_tables: Option, - /// The directories place each table in the function-table snapshot, not at an element of the - /// function-table array. - #[cfg_attr(feature = "serde", serde(default))] - pub function_table_snapshot: bool, /// The directories hold each table's device address, not an element or a snapshot offset: the /// pipeline reads the tables' words there. #[cfg_attr(feature = "serde", serde(default))] @@ -683,15 +678,6 @@ pub enum WriteSource { compare: bool, integer: bool, }, - /// Element `index + 1` of the set-1 function-table array: the words of - /// `BindState::function_tables[index]` (`pipeline::table`'s layout, as - /// [`FunctionTableWords`](crate::bind::FunctionTableWords) encodes them), a read-only - /// storage buffer the consumer binds whole, or the zero buffer - /// (`NeutralResource::ZeroBuffer`) where the state lists fewer tables: no directory entry - /// names that element then. The plan writes every element of its shape's capacity class - /// (`FunctionTablesShape::entries`), so the list may grow or shrink within the class without - /// a new plan; the consumer resolves each write against the state it binds. - FunctionTable { index: u32 }, /// A patch draw's patch index buffer (`DrawCall::Patches::patch_index`), a read-only storage /// buffer of the control stage over the draw's `DescriptorRange`. A draw without one has no range for it, and the consumer binds /// the zero buffer of `min_bytes` there (`NeutralResource::ZeroBuffer`'s), whose words the @@ -706,9 +692,8 @@ pub enum WriteSource { /// render area, each `SpecKey::TileThreadgroupLength` bytes), zeroed when the pass begins and /// kept across its tile dispatches, bound whole. TileMemory { bytes: u64 }, - /// The function-table snapshot (`SyntheticBinding::FunctionTableSnapshot`) of a device - /// without the set-1 function-table array's features: a read-only storage buffer of the - /// words of `BindState::function_tables`, laid out as + /// The function-table snapshot (`SyntheticBinding::FunctionTableSnapshot`): a read-only + /// storage buffer of the words of `BindState::function_tables`, laid out as /// [`FunctionTableSnapshot`](crate::bind::FunctionTableSnapshot) of the listed sizes gives /// them, bound whole. The consumer writes it as the command's command buffer commits: the /// command reads each table's entries as they stand then, where Metal reads them as they diff --git a/crates/metal2vulkan/src/bind/state.rs b/crates/metal2vulkan/src/bind/state.rs index 273e2ad99..480c7dca3 100644 --- a/crates/metal2vulkan/src/bind/state.rs +++ b/crates/metal2vulkan/src/bind/state.rs @@ -189,8 +189,7 @@ pub struct BindState { /// listed, resident or not. A function's table names the table of its id here, or misses and /// reads the null table. Only the capacity class of the list enters a plan /// ([`FunctionTablesShape`]); the ids and sizes are per command, and each table's words are the - /// consumer's (`WriteSource::FunctionTable`, or `WriteSource::FunctionTableSnapshot` on a - /// device without the function-table array's features, whose directory places each table by the + /// consumer's (`WriteSource::FunctionTableSnapshot`, whose directory places each table by the /// sizes before it). #[cfg_attr(feature = "serde", serde(default))] pub function_tables: Vec, @@ -1499,7 +1498,7 @@ pub struct BindShape { /// samplers' shapes. #[cfg_attr(feature = "serde", serde(default))] pub argument_samplers: ArgumentSamplersShape, - /// `BindState.function_tables`: the function-table array's and directories' length class. + /// `BindState.function_tables`: the function-table directories' length class. #[cfg_attr(feature = "serde", serde(default))] pub function_tables: FunctionTablesShape, /// `BindState.tile_threadgroup`: a tile function's threadgroup offsets and tile memory @@ -1654,8 +1653,8 @@ fn least_count(class: u8) -> u64 { /// The projection of `BindState::function_tables` that can change a plan: the capacity class of the /// list's length, as [`ArgumentSamplersShape`]'s. A plan holds [`FunctionTablesShape::entries`] -/// entries in each function-table directory and the function-table array, so a table made or -/// released changes the shape only when the count leaves its class. +/// entries in each function-table directory, so a table made or released changes the shape only +/// when the count leaves its class. #[non_exhaustive] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] diff --git a/crates/metal2vulkan/src/bind/table.rs b/crates/metal2vulkan/src/bind/table.rs index 80f71d630..e75016caa 100644 --- a/crates/metal2vulkan/src/bind/table.rs +++ b/crates/metal2vulkan/src/bind/table.rs @@ -113,9 +113,9 @@ impl FunctionTableWords { } } -/// The function-table snapshot: on a device without the set-1 function-table array's features, the -/// words of a command's listed tables (`BindState::function_tables`) in one read-only storage -/// buffer, which the consumer writes as the command's command buffer commits +/// The function-table snapshot: the words of a command's listed tables +/// (`BindState::function_tables`) in one read-only storage buffer, which the consumer writes as the +/// command's command buffer commits /// ([`WriteSource::FunctionTableSnapshot`](crate::bind::WriteSource::FunctionTableSnapshot)). /// /// Word 0 is the null table's record: a word count of 0. Listed table `i`'s record follows the diff --git a/crates/metal2vulkan/src/lower/access/function_table.rs b/crates/metal2vulkan/src/lower/access/function_table.rs index 93382807d..577c89c40 100644 --- a/crates/metal2vulkan/src/lower/access/function_table.rs +++ b/crates/metal2vulkan/src/lower/access/function_table.rs @@ -11,28 +11,20 @@ //! entry, searched by the module's one search of it (`handles::Lookup::Element`). Metal reads a //! table through an argument buffer without `useResource` (measured on an M3 Max and an M4), so //! the directory lists every live table of the state, resident or not. -//! - **The heap.** The element indexes the set-1 heap's function-table array -//! (`Heap(FunctionTable)`), a runtime array of read-only storage buffers `{ u32 words[]; }`, -//! each one table's words, `NonUniform`. Element 0 is the null table, the zero buffer: a null id -//! and every id the directory misses read 0 from every word, a null table of size 0 (Metal's -//! answer for a null id; an id of a released table, or of another state's, is undefined -//! there). -//! - **Containment.** A word past the table's buffer (an entry at or past its size) is undefined -//! in Metal. Where containment is in the shader (`contain::encoding`), the read is checked -//! against the element's length and yields 0 outside it (a null entry); elsewhere the device's -//! robustness keeps it inside the element. -//! - **Device needs.** The heap's array needs `runtimeDescriptorArray`, -//! `descriptorBindingPartiallyBound`, `shaderStorageBufferArrayNonUniformIndexing`, and -//! `descriptorBindingStorageBufferUpdateAfterBind`. -//! - **The snapshot**. On a device without one of the four, the read takes the tables' words from -//! the stage's function-table snapshot (`Synthetic(FunctionTableSnapshot)`) instead: one storage -//! buffer the binder writes per command as the command buffer commits +//! - **Containment.** A word past a table's words (an entry at or past its size) is undefined in +//! Metal; both forms below check every read and yield 0 outside the table (a null entry), +//! whatever the device's robustness. A null id and every id the directory misses read a null +//! table of size 0 (Metal's answer for a null id; an id of a released table, or of another +//! state's, is undefined there). +//! - **The snapshot**. The read takes the tables' words from the stage's function-table snapshot +//! (`Synthetic(FunctionTableSnapshot)`): one storage buffer the binder writes per command as the +//! command buffer commits //! (`bind::FunctionTableSnapshot`), word 0 the null table's record (a word count of 0) and then //! each listed table's record, its word count and its words. The directory gives each listed //! id its record's word offset `e` in place of an element, so a miss and the null id read the //! null table. Word `w` is checked against the record's count, always: `snapshot[e + 1 + w]` -//! below it and 0 at or past it (a null entry), so no read leaves the record, whatever the -//! device's robustness. It needs no feature past the directory's own storage buffer. +//! below it and 0 at or past it (a null entry), so no read leaves the record. It needs no +//! feature past the directory's own storage buffer, on every device. //! - **Addressed**. Under `LoweringInputs::addressed_function_tables`, the variant a shape whose //! listed tables may pass `maxStorageBufferRange` asks for, the directory's entry of an id holds //! the device address of the table's words in its element and flags words (low, then high), and @@ -41,8 +33,8 @@ //! against the table's size word (word 1): a header word, or an entry below the size, and 0 past //! it, so no read leaves the table's words, whatever their length. The null entry (address 0) //! reads 0, its loads taken at the directory's last entry's address (a listed table's) and -//! dropped, so no load takes the null address. It declares neither the array nor the snapshot, -//! and needs device addresses. +//! dropped, so no load takes the null address. It declares no snapshot, and needs device +//! addresses. use std::borrow::Cow; @@ -53,19 +45,16 @@ use crate::error::{Error, Feature, Unsupported}; use crate::lower::arith::legal; use crate::lower::emit::EmitCx; use crate::lower::select::{DescriptorCounts, Plan, SelectCx}; -use crate::memory::contain::{self, Check}; use crate::memory::handles::{self, EntryField}; use crate::memory::leaf::{k32, WordMem}; use crate::memory::views::{self, View}; use crate::pipeline::facts::RuntimeFact; -use crate::pipeline::sym::{HandleClass, ResourceKind, ResourceSlot, Stage, SyntheticBinding}; +use crate::pipeline::sym::{ResourceKind, ResourceSlot, Stage, SyntheticBinding}; use crate::spirv::builder::constructs::{ArmEnd, ArmFn}; use crate::spirv::builder::{FunctionBuilder, ModuleBuilder}; use crate::spirv::error::BResult; -use crate::spirv::ids::{FuncId, GlobalId}; -use crate::spirv::ir::{ - natural_layout, BinOp, ConvOp, LayoutRule, MemAccess, StorageClass, Type as SType, -}; +use crate::spirv::ids::FuncId; +use crate::spirv::ir::{BinOp, ConvOp, Type as SType}; use super::handle::HandleIds; use super::psb::{k64, PsbMem}; @@ -73,10 +62,7 @@ use super::psb::{k64, PsbMem}; /// Where a function's table reads find the tables' words. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum TableWords { - /// The heap's function-table array, at the element the directory gives an id. - Heap, - /// The stage's function-table snapshot, at the word offset the directory gives an id, on a - /// device without the array's features. + /// The stage's function-table snapshot, at the word offset the directory gives an id. Snapshot, /// The device address the directory's entry of an id holds, under /// `LoweringInputs::addressed_function_tables`. @@ -100,39 +86,31 @@ pub struct TableWord { pub id: ValueId, /// The `i32` word number. pub word: ValueId, - /// How the id is held and where the words are. + /// How the id is held and where the words are: a snapshot read is checked against its + /// record's count, an addressed read against its table's size word. pub reads: TableReads, - /// A heap read is checked against the element's length (in-shader containment); a snapshot read - /// is always checked against its record's count, and an addressed read against its table's size - /// word. - pub checked: bool, } impl TableWord { /// The census name. pub fn name(&self) -> Cow<'static, str> { - match (self.reads.words, self.checked) { - (TableWords::Snapshot, _) => "access.function_table.word.snapshot".into(), - (TableWords::Addressed, _) => "access.function_table.word.addressed".into(), - (TableWords::Heap, true) => "access.function_table.word.checked".into(), - (TableWords::Heap, false) => "access.function_table.word".into(), + match self.reads.words { + TableWords::Snapshot => "access.function_table.word.snapshot".into(), + TableWords::Addressed => "access.function_table.word.addressed".into(), } } - /// An upper estimate of the SPIR-V words one read emits: the id's two words, the search's call, - /// the element's and the word's access chains, and the load, plus the length and two selects of - /// a checked read; a snapshot read's two loads, its count's compare, two adds and two selects; - /// an addressed read's four entry fields (its entry's and the last entry's), the table's + /// An upper estimate of the SPIR-V words one read emits: the id's two words and the search's + /// call, then a snapshot read's two loads, its count's compare, two adds and two selects; or an + /// addressed read's four entry fields (its entry's and the last entry's), the table's /// length, the addresses' widening, tests and select, the branch around the reads, the size's /// and the word's loads at their address, and the checks' compares and selects. The search is /// the module's routine, counted once ([`routine_words`]). pub fn words(&self) -> u32 { let read = 64; - match (self.reads.words, self.checked) { - (TableWords::Snapshot, _) => read + 40, - (TableWords::Addressed, _) => read + 4 * handles::ENTRY_FIELD_WORDS + 160, - (TableWords::Heap, true) => read + 24, - (TableWords::Heap, false) => read, + match self.reads.words { + TableWords::Snapshot => read + 40, + TableWords::Addressed => read + 4 * handles::ENTRY_FIELD_WORDS + 160, } } } @@ -141,8 +119,8 @@ impl TableWord { /// words are. #[derive(Clone, Copy, Debug)] pub struct FunctionTables { - /// `fn(lo: u32, hi: u32) -> u32`, the heap element (or snapshot offset, or directory entry - /// of an addressed read) of a table's resource id ([`handles::define_lookup`]). + /// `fn(lo: u32, hi: u32) -> u32`, the snapshot offset (or the directory entry of an addressed + /// read) of a table's resource id ([`handles::define_lookup`]). pub lookup: FuncId, /// The tables' words. pub words: DeclaredWords, @@ -151,8 +129,6 @@ pub struct FunctionTables { /// The declared home of the tables' words. #[derive(Clone, Copy, Debug)] pub enum DeclaredWords { - /// The set-1 array of the tables' word buffers. - Heap(GlobalId), /// The stage's function-table snapshot, a word view. Snapshot(View), /// The directory itself, whose entries hold the tables' device addresses. @@ -177,32 +153,10 @@ pub fn snapshot_symbol(stage: Stage) -> ResourceSlot { } } -/// The binding symbol of the heap's function-table array as `stage` declares it. -pub fn heap_symbol(stage: Stage) -> ResourceSlot { - ResourceSlot { - stage, - kind: ResourceKind::Heap(HandleClass::FunctionTable), - index: 0, - } -} - -/// Whether `cx`'s profile has the four features the heap's function-table array needs: -/// `runtimeDescriptorArray`, `descriptorBindingPartiallyBound`, -/// `shaderStorageBufferArrayNonUniformIndexing`, and -/// `descriptorBindingStorageBufferUpdateAfterBind`. -fn has_array(cx: &SelectCx<'_>) -> bool { - let d = &cx.profile.fields().descriptors; - d.runtime_descriptor_array - && d.partially_bound - && d.non_uniform_storage_buffer - && d.update_after_bind_storage_buffer -} - /// Select the read of `inst` when it is a [`FunctionTable::Word`] call, `None` otherwise. The -/// first plans the stage's directory and heap array (one more storage descriptor of the stage; -/// the heap array is link's), or, on a device without the array's features, its directory and -/// snapshot (two), or under `LoweringInputs::addressed_function_tables` its directory alone, and -/// states `RuntimeFact::FunctionTableRange`. +/// first plans the stage's directory and snapshot (two storage descriptors of the stage), or under +/// `LoweringInputs::addressed_function_tables` its directory alone, and states +/// `RuntimeFact::FunctionTableRange`. pub fn select(cx: &mut SelectCx<'_>, inst: &Inst) -> Result, Error> { let InstKind::Call(call) = &inst.kind else { return Ok(None); @@ -229,10 +183,9 @@ pub fn select(cx: &mut SelectCx<'_>, inst: &Inst) -> Result, E ) .into()); } - let (words, storage_buffers) = match (addressed, has_array(cx)) { - (true, _) => (TableWords::Addressed, 1), - (false, true) => (TableWords::Heap, 1), - (false, false) => (TableWords::Snapshot, 2), + let (words, storage_buffers) = match addressed { + true => (TableWords::Addressed, 1), + false => (TableWords::Snapshot, 2), }; let reads = TableReads { ids, words }; if cx.families.access.function_tables.is_none() { @@ -253,7 +206,6 @@ pub fn select(cx: &mut SelectCx<'_>, inst: &Inst) -> Result, E id: value(id)?, word: value(word)?, reads, - checked: words != TableWords::Heap || contain::encoding(cx.profile) == Check::InShader, })) } @@ -270,18 +222,17 @@ pub fn routine_words(tables: Option) -> impl Iterator handles::Lookup { match reads.words { TableWords::Addressed => handles::Lookup::Entry, - TableWords::Heap | TableWords::Snapshot => handles::Lookup::Element, + TableWords::Snapshot => handles::Lookup::Element, } } /// Declare the stage's function-table directory (an entry array, or a word view on a profile -/// without `shaderInt64`), the module's search of it, and the heap's function-table array or -/// the stage's snapshot (neither for an addressed read), when the plan reads a table by its -/// resource id. +/// without `shaderInt64`), the module's search of it, and the stage's snapshot (none for an +/// addressed read), when the plan reads a table by its resource id. pub fn declare(mb: &mut ModuleBuilder, plan: &Plan) -> BResult> { let Some(reads) = plan.families.access.function_tables else { return Ok(None); @@ -298,40 +249,14 @@ pub fn declare(mb: &mut ModuleBuilder, plan: &Plan) -> BResult heap, + let w = match tables.words { DeclaredWords::Addressed(directory) => { let Some(w) = addressed_word(fb, directory, element, word)? else { return Err(cx.fail("an addressed table read without its merged word")); }; - cx.define(vid, w); - return Ok(()); + w } DeclaredWords::Snapshot(view) => { // The record's count, then its word `w` below it: every read stays in the record. @@ -383,26 +306,8 @@ pub fn emit( let at = fb.binary(BinOp::IAdd, first, word)?; let at = fb.select(inside, at, zero)?; let w = views::read_word(fb, view, at)?; - let w = fb.select(inside, w, zero)?; - cx.define(vid, w); - return Ok(()); - } - }; - let base = fb.module().global_value(heap)?; - let table = fb.access_chain_non_uniform(base, element)?; - let w = match s.checked { - true => { - let len = fb.array_length(table, 0)?; - let inside = fb.binary(BinOp::ULessThan, word, len)?; - let at = fb.select(inside, word, zero)?; - let p = fb.access_chain(table, &[zero, at])?; - let w = fb.load(p, MemAccess::default())?; fb.select(inside, w, zero)? } - false => { - let p = fb.access_chain(table, &[zero, word])?; - fb.load(p, MemAccess::default())? - } }; cx.define(vid, w); Ok(()) diff --git a/crates/metal2vulkan/src/lower/access/mod.rs b/crates/metal2vulkan/src/lower/access/mod.rs index 47e5659dc..0a8ae091c 100644 --- a/crates/metal2vulkan/src/lower/access/mod.rs +++ b/crates/metal2vulkan/src/lower/access/mod.rs @@ -811,8 +811,7 @@ pub struct AccessPlan { pub heap_alpha: bool, /// Some visible-function table is read by its resource id ([`function_table`]): the function /// reads the stage's function-table directory, one more storage descriptor, whose search reads - /// the ids as this states, and the heap's function-table array, or, on a device without the - /// array's features, the stage's function-table snapshot, one more again. + /// the ids as this states, and the stage's function-table snapshot, one more again. pub function_tables: Option, /// A heap texture's float write the function makes tests its texel class's index /// (`lower::texture::emit`): the handle-table search carries the index @@ -900,8 +899,8 @@ pub struct Declared { pub resolve: Option, /// A tile function's attachment images and render area ([`tile`]). pub tile: tile::TileDecl, - /// The stage's function-table directory and search and the heap's function-table array, - /// when a table is read by its resource id. + /// The stage's function-table directory and search and its snapshot, when a table is read by + /// its resource id. pub function_tables: Option, /// The stage's view of the command buffer's `ExecutionStatus` buffer, where it binds the /// buffer ([`absent::declare`]). diff --git a/crates/metal2vulkan/src/pipeline/facts.rs b/crates/metal2vulkan/src/pipeline/facts.rs index 13e2213fe..75f70612c 100644 --- a/crates/metal2vulkan/src/pipeline/facts.rs +++ b/crates/metal2vulkan/src/pipeline/facts.rs @@ -398,9 +398,9 @@ pub enum RuntimeFact { /// after the access, from `SpecKey::ConstantLanes`, which the binder sets from the bound /// texture's `MTLTexture.pixelFormat` and `swizzle` (0 where `isSparse` is false). ConstantLanes { slot: SlotRef }, - /// The function reads visible-function tables by their resource ids: a listed table whose words - /// pass `maxStorageBufferRange` cannot be the function-table array's element, nor the snapshot - /// hold every listed table's words, so the plan of a shape whose tables may pass it + /// The function reads visible-function tables by their resource ids: the snapshot cannot hold + /// a listed table whose words pass `maxStorageBufferRange`, so the plan of a shape whose tables + /// may pass it /// (`FunctionTablesShape::bytes_class`) asks for the variant that reads every table's words /// through its device address (`VariantKey::addressed_function_tables`). `addressed` states /// that this compile is that variant. diff --git a/crates/metal2vulkan/src/pipeline/link.rs b/crates/metal2vulkan/src/pipeline/link.rs index 47493dff5..51bbce535 100644 --- a/crates/metal2vulkan/src/pipeline/link.rs +++ b/crates/metal2vulkan/src/pipeline/link.rs @@ -22,10 +22,8 @@ //! `maxPerStageUpdateAfterBindResources`, each split evenly over the classes of its kind, with //! a fragment stage's eight color attachments reserved), at most the handle table's reach //! (`memory::handles::TABLE_CAPACITY`). The binder writes element 0 of each array with its -//! class's neutral and every resident texture at its own element. The function tables' array -//! (`HandleClass::FunctionTable`) is a storage-buffer array, which needs -//! `descriptorBindingStorageBufferUpdateAfterBind` and counts in the storage-buffer limits. A -//! texture buffer class's array is a uniform texel buffer array (sampled) or a storage texel +//! class's neutral and every resident texture at its own element. A texture buffer class's +//! array is a uniform texel buffer array (sampled) or a storage texel //! buffer array (storage), which needs the type's update-after-bind feature and counts in the //! sampled-image or the storage-image limits, as Vulkan counts texel buffers. //! - **Specialization ids** are numbered densely in [`SpecKey`] order over the pipeline; a key two @@ -1158,10 +1156,6 @@ fn heap_layout_lacks(p: &DeviceProfile, ty: vk::DescriptorType) -> Option ( - d.update_after_bind_storage_buffer, - VkFeature::DescriptorBindingStorageBufferUpdateAfterBind, - ), vk::DescriptorType::UNIFORM_TEXEL_BUFFER => ( d.update_after_bind_uniform_texel_buffer, VkFeature::DescriptorBindingUniformTexelBufferUpdateAfterBind, @@ -1242,7 +1236,6 @@ fn heap_capacity( let kind = |ty: vk::DescriptorType| match ty { vk::DescriptorType::SAMPLER => SAMPLERS, vk::DescriptorType::STORAGE_IMAGE | vk::DescriptorType::STORAGE_TEXEL_BUFFER => IMAGES, - vk::DescriptorType::STORAGE_BUFFER => STORAGE, _ => SAMPLED, }; let mut capacity = u64::from(crate::memory::handles::TABLE_CAPACITY); @@ -1313,7 +1306,7 @@ fn heap_capacity( } /// The kinds of heap arrays, in the order [`heap_capacity`] bounds them. -const HEAP_KINDS: [usize; 4] = [SAMPLERS, SAMPLED, IMAGES, STORAGE]; +const HEAP_KINDS: [usize; 3] = [SAMPLERS, SAMPLED, IMAGES]; /// The update-after-bind limits on `l` of heap arrays of kind `k`, one of [`HEAP_KINDS`]: the /// set's (`maxDescriptorSetUpdateAfterBind*`), then a stage's @@ -1340,7 +1333,7 @@ fn heap_limits(l: &crate::device::profile::Limits, k: usize) -> [(VkLimit, u32); l.max_per_stage_descriptor_update_after_bind_sampled_images, ), ], - IMAGES => [ + _ => [ ( VkLimit::MaxDescriptorSetUpdateAfterBindStorageImages, l.max_descriptor_set_update_after_bind_storage_images, @@ -1350,16 +1343,6 @@ fn heap_limits(l: &crate::device::profile::Limits, k: usize) -> [(VkLimit, u32); l.max_per_stage_descriptor_update_after_bind_storage_images, ), ], - _ => [ - ( - VkLimit::MaxDescriptorSetUpdateAfterBindStorageBuffers, - l.max_descriptor_set_update_after_bind_storage_buffers, - ), - ( - VkLimit::MaxPerStageDescriptorUpdateAfterBindStorageBuffers, - l.max_per_stage_descriptor_update_after_bind_storage_buffers, - ), - ], } } diff --git a/crates/metal2vulkan/src/pipeline/lower_inputs.rs b/crates/metal2vulkan/src/pipeline/lower_inputs.rs index a551c2670..197d89d75 100644 --- a/crates/metal2vulkan/src/pipeline/lower_inputs.rs +++ b/crates/metal2vulkan/src/pipeline/lower_inputs.rs @@ -541,8 +541,8 @@ pub struct LoweringInputs { /// table's device address (`VariantKey::addressed_function_tables`): the directory's entry /// of the id holds the address of the table's words in place of an element, and a read of /// word `w` is checked against the table's size word, so a table whose words pass - /// `maxStorageBufferRange` is read whole. It declares neither the function-table array nor - /// the snapshot, and states `RuntimeFact::FunctionTableRange` with `addressed`. It needs + /// `maxStorageBufferRange` is read whole. It declares no snapshot, and states + /// `RuntimeFact::FunctionTableRange` with `addressed`. It needs /// device addresses (`Unsupported{BufferRange}` without them). A function that reads no /// table by resource id compiles as without it. #[cfg_attr(feature = "serde", serde(default))] diff --git a/crates/metal2vulkan/src/pipeline/sym.rs b/crates/metal2vulkan/src/pipeline/sym.rs index 7f7fc2484..492db1db1 100644 --- a/crates/metal2vulkan/src/pipeline/sym.rs +++ b/crates/metal2vulkan/src/pipeline/sym.rs @@ -213,10 +213,9 @@ pub enum SyntheticBinding { /// `x + y ยท SpecKey::TileGridWidth`, which the pass keeps across its draws and tile /// dispatches and starts at zero (`RuntimeFact::TileThreadgroupMemory`). TileMemory, - /// The function-table snapshot of a device without the set-1 function-table array's - /// features: a read-only storage buffer of words the binder writes per command, holding a - /// null table's record at word 0 and then each listed table's record, its word count and - /// its words ([`FunctionTableSnapshot`](crate::bind::FunctionTableSnapshot)). The stage's + /// The function-table snapshot: a read-only storage buffer of words the binder writes per + /// command, holding a null table's record at word 0 and then each listed table's record, its + /// word count and its words ([`FunctionTableSnapshot`](crate::bind::FunctionTableSnapshot)). The stage's /// function-table directory gives each id the word offset of its table's record. FunctionTableSnapshot, } diff --git a/crates/metal2vulkan/src/spirv/interp/sched.rs b/crates/metal2vulkan/src/spirv/interp/sched.rs index e2d7fc50d..239bad6be 100644 --- a/crates/metal2vulkan/src/spirv/interp/sched.rs +++ b/crates/metal2vulkan/src/spirv/interp/sched.rs @@ -71,8 +71,8 @@ pub(super) struct Prog<'m> { /// The length of each runtime descriptor array of images (a set-1 heap array), by its first /// bound image: its consecutive images of the slot. image_arrays: HashMap, - /// The length of each descriptor array of buffers (a set-1 heap array of storage buffers), by - /// its first bound buffer: its consecutive buffers of the slot. + /// The length of each descriptor array of buffers, by its first bound buffer: its consecutive + /// buffers of the slot. buffer_arrays: HashMap, layout: FrameLayout, /// The encoded initializer of each `Private` global, by global, filled by the first diff --git a/crates/metal2vulkan/src/spirv/serialize/tests/families_image.rs b/crates/metal2vulkan/src/spirv/serialize/tests/families_image.rs index 84c584c0d..5dd1be940 100644 --- a/crates/metal2vulkan/src/spirv/serialize/tests/families_image.rs +++ b/crates/metal2vulkan/src/spirv/serialize/tests/families_image.rs @@ -863,8 +863,8 @@ fn non_uniform_elements_are_decorated_through_what_carries_them() { }); } -/// A non-uniform element of a storage-buffer array of blocks (the function-table heap): the -/// element's chain and the chain into it are decorated `NonUniform`, and the load, the store, and +/// A non-uniform element of a descriptor array of storage-buffer blocks: the element's chain and +/// the chain into it are decorated `NonUniform`, and the load, the store, and /// `OpArrayLength` read through them; a word loaded from it is data, undecorated, which a `select` /// may take. The module requires `ShaderNonUniform` and storage-buffer non-uniform indexing (not /// its dynamic one), and `spirv-val` accepts it. diff --git a/crates/metal2vulkan/src/tests/engine_argument_tables.rs b/crates/metal2vulkan/src/tests/engine_argument_tables.rs index a32b52a1a..5b9c9dc56 100644 --- a/crates/metal2vulkan/src/tests/engine_argument_tables.rs +++ b/crates/metal2vulkan/src/tests/engine_argument_tables.rs @@ -7,19 +7,14 @@ //! select of two members. The functions are `engine/visible_table_functions`'s, which the //! pipeline links. //! -//! - The kernels compile and pass L3 on every committed profile: they read the set-1 -//! function-table array where the profile has `runtimeDescriptorArray`, -//! `descriptorBindingPartiallyBound`, `shaderStorageBufferArrayNonUniformIndexing`, and -//! `descriptorBindingStorageBufferUpdateAfterBind`, and the stage's function-table snapshot -//! where it lacks one (the 2023 desktop baseline and the two Vulkan 1.2 floors). A call nothing -//! linked can answer compiles too: with no handle to hold, every entry is null. -//! - Through the public API, the plan writes the set-1 function-table array (the zero buffer at -//! element 0, `FunctionTable{index}` at every other element of the class) and the stage's -//! directory, whose bytes per dispatch list each listed table's nonzero id with its element; -//! on a device without the features, the snapshot (`FunctionTableSnapshot`) and the directory, -//! whose bytes give each id its record's word offset by the listed sizes. -//! - On the CPU interpreter, fed the binder's directory bytes and each listed table's words at -//! its element, or the snapshot of the tables' words, every profile's kernels compute what +//! - The kernels compile and pass L3 on every committed profile, reading the stage's +//! function-table snapshot beside its directory. A call nothing linked can answer compiles too: +//! with no handle to hold, every entry is null. +//! - Through the public API, the plan writes the snapshot (`FunctionTableSnapshot`) and the +//! stage's directory, whose bytes per dispatch give each listed table's nonzero id its record's +//! word offset by the listed sizes. +//! - On the CPU interpreter, fed the binder's directory bytes and the snapshot of the tables' +//! words, every profile's kernels compute what //! Metal does: the entry's function (zero for a function of another type), a null entry, an empty //! table, and a null table for the null id and for an id no listed table has. No GPU is used. //! @@ -29,22 +24,21 @@ use std::path::Path; use crate::bind::{ ArgumentFunctionTable, BindState, DescriptorBytes, Dispatch, FunctionTableSnapshot, - FunctionTableWords, HeapPlacement, NeutralResource, WriteSource, + FunctionTableWords, HeapPlacement, WriteSource, }; use crate::budget::{Budget, SPIRV_WORDS}; use crate::cache::VariantKey; use crate::device::profile::BufferAccess; -use crate::device::requirements::VkFeature; use crate::device::{Device, DeviceDescription, DevicePolicy, DeviceProfile}; -use crate::error::{Capability, Error, Feature}; +use crate::error::{Error, Feature}; use crate::library::{FunctionConstantValues, Library}; -use crate::lower::access::function_table::{directory_symbol, heap_symbol, snapshot_symbol}; +use crate::lower::access::function_table::{directory_symbol, snapshot_symbol}; use crate::lower::select::LowerInputs; use crate::memory::handles::TABLE_ENTRY_BYTES; use crate::pipeline::compile::{compile_bitcode_linked, EntryRef, LinkedSource}; use crate::pipeline::facts::RuntimeFact; use crate::pipeline::layout::BindingSource; -use crate::pipeline::sym::{HandleClass, ResourceKind, ResourceSlot, Stage, SyntheticBinding}; +use crate::pipeline::sym::{ResourceKind, ResourceSlot, Stage, SyntheticBinding}; use crate::pipeline::testing::{ engine_dir, link_and_validate, llvm_assemble, meter, typed_module_linked, AssembleError, }; @@ -120,55 +114,8 @@ fn compile( ) } -/// The features of the four a table read by its id needs that `p` lacks. -fn missing(p: &DeviceProfile) -> Vec { - let d = &p.fields().descriptors; - [ - ( - d.runtime_descriptor_array, - VkFeature::RuntimeDescriptorArray, - ), - ( - d.partially_bound, - VkFeature::DescriptorBindingPartiallyBound, - ), - ( - d.non_uniform_storage_buffer, - VkFeature::ShaderStorageBufferArrayNonUniformIndexing, - ), - ( - d.update_after_bind_storage_buffer, - VkFeature::DescriptorBindingStorageBufferUpdateAfterBind, - ), - ] - .into_iter() - .filter(|(has, _)| !has) - .map(|(_, f)| Capability::Feature(f)) - .collect() -} - -/// Every committed profile that reads tables by id from the set-1 array. -pub(super) fn capable_profiles() -> Vec<(String, DeviceProfile)> { - committed_profiles() - .expect("profiles") - .into_iter() - .filter(|(_, p)| missing(p).is_empty()) - .collect() -} - -/// Every committed profile that reads tables by id from a snapshot. -fn snapshot_profiles() -> Vec<(String, DeviceProfile)> { - committed_profiles() - .expect("profiles") - .into_iter() - .filter(|(_, p)| !missing(p).is_empty()) - .collect() -} - -/// The kernels compile and validate on every committed profile: where the device has the four -/// features they declare the heap's function-table array and no snapshot, and where it lacks -/// one (the runtime's floor, without non-uniform storage-buffer indexing and storage-buffer -/// update-after-bind) the stage's snapshot and no array, beside the directory. +/// The kernels compile and validate on every committed profile, declaring the stage's snapshot +/// beside the directory. #[test] fn argument_tables_compile_on_every_profile() { let Some((caller, functions)) = fixtures() else { @@ -176,35 +123,21 @@ fn argument_tables_compile_on_every_profile() { }; let none = FunctionConstantValues::defaults(); let linked = sources(&functions, &none); - let mut snapshots = Vec::new(); for (stem, p) in committed_profiles().expect("profiles") { - let snapshot = !missing(&p).is_empty(); for entry in KERNELS { let a = compile(&caller, entry, &linked, &p) .unwrap_or_else(|e| panic!("{stem} {entry}: {e}")); link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{stem} {entry}: L3: {e}")); let declares = |slot| a.interface.descriptors.iter().any(|d| d.slot == slot); assert!(declares(directory_symbol(Stage::Kernel)), "{stem} {entry}"); - assert_eq!( - ( - declares(heap_symbol(Stage::Kernel)), - declares(snapshot_symbol(Stage::Kernel)) - ), - (!snapshot, snapshot), - "{stem} {entry}" - ); + assert!(declares(snapshot_symbol(Stage::Kernel)), "{stem} {entry}"); let census = &a.strategies.entries; - assert_eq!( + assert!( census.contains_key("access.function_table.word.snapshot"), - snapshot, "{stem} {entry}" ); } - if snapshot { - snapshots.push(stem); - } } - assert_eq!(snapshots, ["runtime-floor"]); } /// A call through a table loaded from an argument buffer that no linked function can answer @@ -294,22 +227,6 @@ pub(super) fn one_group() -> Dispatch { } } -/// The `(set, binding)` of the pipeline's set-1 function-table array and of its kernel -/// directory. -pub(super) fn table_layout(p: &ComputePipeline) -> ((u32, u32), (u32, u32)) { - let array = p.layout.sets[1] - .bindings - .iter() - .find(|b| b.source == BindingSource::Heap(HandleClass::FunctionTable)) - .map(|b| { - assert_eq!(b.ty, vk::DescriptorType::STORAGE_BUFFER); - assert_eq!(b.flags, super::engine_handles::heap_flags(&p.requirements)); - (1, b.binding) - }) - .expect("a function-table array"); - (array, directory_binding(p)) -} - /// The `(set, binding)` of the pipeline's kernel synthetic binding `binding`. fn synthetic(p: &ComputePipeline, binding: SyntheticBinding) -> Option<(u32, u32)> { p.layout.sets[0] @@ -325,7 +242,7 @@ fn synthetic(p: &ComputePipeline, binding: SyntheticBinding) -> Option<(u32, u32 } /// The `(set, binding)` of the pipeline's kernel function-table directory. -fn directory_binding(p: &ComputePipeline) -> (u32, u32) { +pub(super) fn directory_binding(p: &ComputePipeline) -> (u32, u32) { synthetic(p, SyntheticBinding::FunctionTableDirectory).expect("a function-table directory") } @@ -349,110 +266,18 @@ fn entries(bytes: &[u8]) -> Vec<(u64, u32, u32)> { .collect() } -/// The plan writes element 0 of the function-table array with the zero buffer (the null table) -/// and every other element of the class (16 entries for up to 15 tables) with the listed table -/// one before it; the directory is a handle table of as many entries, whose bytes per dispatch -/// are each listed nonzero id with its element, sorted after leading null entries. A table made -/// or released replans only when the count leaves the class, and a dispatch whose state lists -/// more tables than the plan's class holds is refused. -#[test] -fn the_plan_writes_the_tables_and_their_directory() { - let Some((caller, functions)) = fixtures() else { - return; - }; - let dev = device("moltenvk-m3"); - let pipe = pipeline(&dev, &caller, &functions, ONE); - let (array, directory) = table_layout(&pipe); - let mut state = state(); - // A table without an id is listed but named by nothing. - state.function_tables.push(ArgumentFunctionTable::new(0, 0)); - let plan = pipe.plan(&dev, &state.shape()).expect("plan"); - let mut writes: Vec<_> = plan - .descriptors - .iter() - .filter(|d| (d.set, d.binding) == array) - .collect(); - writes.sort_by_key(|d| d.array_element); - assert_eq!(writes.len(), 16); - for (e, w) in writes.iter().enumerate() { - assert_eq!(w.array_element as usize, e, "one write per element"); - assert_eq!(w.ty, vk::DescriptorType::STORAGE_BUFFER); - match e { - 0 => assert!(matches!( - w.source, - WriteSource::Neutral(NeutralResource::ZeroBuffer { .. }) - )), - _ => assert_eq!( - w.source, - WriteSource::FunctionTable { - index: e as u32 - 1 - } - ), - } - } - let dir = plan - .descriptors - .iter() - .find(|d| (d.set, d.binding) == directory) - .expect("the directory's write"); - assert_eq!( - dir.source, - WriteSource::HandleTable { - stage: Stage::Kernel, - bytes_len: 16 * TABLE_ENTRY_BYTES, - } - ); - let cmds = plan - .instantiate_dispatch(&state, &one_group()) - .expect("dispatch"); - let mut want = vec![(0, 0, 0); 13]; - want.extend([(U, 2, 0), (E, 3, 0), (T, 1, 0)]); - assert_eq!(entries(bytes_at(&cmds.descriptor_bytes, directory)), want); - - // Up to 15 tables keep the class; a 16th leaves it. - let mut fifteen = state.clone(); - fifteen - .function_tables - .extend((0..11).map(|i| ArgumentFunctionTable::new(0x100 + i, 1))); - assert_eq!(fifteen.shape(), state.shape()); - assert!(plan.instantiate_dispatch(&fifteen, &one_group()).is_ok()); - let mut sixteen = fifteen.clone(); - sixteen - .function_tables - .push(ArgumentFunctionTable::new(0x200, 1)); - assert_ne!(sixteen.shape(), state.shape()); - assert!(plan.instantiate_dispatch(&sixteen, &one_group()).is_err()); - let wider = pipe.plan(&dev, &sixteen.shape()).expect("plan"); - assert_eq!( - wider - .descriptors - .iter() - .filter(|d| (d.set, d.binding) == array) - .count(), - 32 - ); -} - -/// On a device without the array's features the plan writes no function-table array: the kernel's -/// snapshot is `FunctionTableSnapshot`, and its directory, a handle table of the class's entries, -/// gives each listed nonzero id its record's word offset in the snapshot of the listed sizes, -/// whatever the heap placement. A 16th table leaves the class as it does with the array. +/// On every device the kernel's snapshot is `FunctionTableSnapshot`, and its directory, a handle +/// table of the class's entries, gives each listed nonzero id its record's word offset in the +/// snapshot of the listed sizes, whatever the heap placement. Up to 15 listed tables keep the +/// class; a 16th leaves it, and a dispatch of the old plan over it is refused. #[test] fn the_plan_writes_the_snapshot_and_its_directory() { let Some((caller, functions)) = fixtures() else { return; }; - for stem in ["runtime-floor"] { + for stem in ["runtime-floor", "moltenvk-m3"] { let dev = device(stem); let pipe = pipeline(&dev, &caller, &functions, ONE); - assert!( - pipe.layout - .sets - .iter() - .flat_map(|s| &s.bindings) - .all(|b| b.source != BindingSource::Heap(HandleClass::FunctionTable)), - "{stem}: a function-table array" - ); let snapshot = synthetic(&pipe, SyntheticBinding::FunctionTableSnapshot).expect("a snapshot"); let directory = directory_binding(&pipe); @@ -512,8 +337,6 @@ fn the_plan_writes_the_snapshot_and_its_directory() { /// Where a dispatch's tables' words are. #[derive(Clone, Copy)] enum Words<'a> { - /// The heap's function-table array holds the zero buffer, then these at elements 1, 2, ... - Heap(&'a [Vec]), /// The stage's function-table snapshot holds these bytes. Snapshot(&'a [u8]), /// These words lie at these device addresses. @@ -545,14 +368,6 @@ fn dispatch( buffer(directory_symbol(Stage::Kernel), directory.to_vec()), ]; match words { - Words::Heap(tables) => { - buffers.push(buffer(heap_symbol(Stage::Kernel), vec![0; 16])); - buffers.extend( - tables - .iter() - .map(|t| buffer(heap_symbol(Stage::Kernel), t.clone())), - ); - } Words::Snapshot(bytes) => { buffers.push(buffer(snapshot_symbol(Stage::Kernel), bytes.to_vec())); } @@ -621,11 +436,10 @@ fn directory_of(stem: &str, caller: &[u8], functions: &[u8]) -> Vec { bytes_at(&cmds.descriptor_bytes, directory).to_vec() } -/// On every capable profile, each kernel calls the entry the table its argument buffer names -/// holds, with the binder's directory bytes: a listed table by its id (the high word too), a null -/// entry, an empty table, and a null table for the null id and for an id no listed table has. On -/// every profile without the array's features, the same through the snapshot of the tables' -/// words and the directory of their offsets there. +/// On every committed profile, each kernel calls the entry the table its argument buffer names +/// holds, through the snapshot of the tables' words and the binder's directory of their offsets +/// there: a listed table by its id (the high word too), a null entry, an empty table, and a null +/// table for the null id and for an id no listed table has. #[test] fn an_argument_table_call_calls_the_entry_its_table_holds() { let Some((caller, functions)) = fixtures() else { @@ -637,8 +451,6 @@ fn an_argument_table_call_calls_the_entry_its_table_holds() { table_bytes(&h, &U_ENTRIES), table_bytes(&h, &[]), ]; - let heap = directory_of("moltenvk-m3", &caller, &functions); - let snapshot_directory = directory_of("runtime-floor", &caller, &functions); let snapshot = FunctionTableSnapshot::of(state().function_tables.iter().map(|f| f.size)) .expect("snapshot") .bytes(tables.iter().map(Vec::as_slice)) @@ -646,15 +458,9 @@ fn an_argument_table_call_calls_the_entry_its_table_holds() { let none = FunctionConstantValues::defaults(); let linked = sources(&functions, &none); const N: u32 = 40; - let profiles = capable_profiles() - .into_iter() - .map(|(stem, p)| (stem, p, &heap, Words::Heap(&tables))) - .chain( - snapshot_profiles() - .into_iter() - .map(|(stem, p)| (stem, p, &snapshot_directory, Words::Snapshot(&snapshot))), - ); - for (stem, p, directory, words) in profiles { + let words = Words::Snapshot(&snapshot); + for (stem, p) in committed_profiles().expect("profiles") { + let directory = &directory_of(&stem, &caller, &functions); let module = |entry| { typed_module_linked(&caller, entry, &p, &linked) .unwrap_or_else(|e| panic!("{stem} {entry}: {e}")) @@ -708,7 +514,7 @@ fn without_listed_tables_every_id_reads_the_null_table() { }; let dev = device("moltenvk-m3"); let pipe = pipeline(&dev, &caller, &functions, ONE); - let (_, directory) = table_layout(&pipe); + let directory = directory_binding(&pipe); let state = BindState::default(); let plan = pipe.plan(&dev, &state.shape()).expect("plan"); let cmds = plan @@ -721,9 +527,13 @@ fn without_listed_tables_every_id_reads_the_null_table() { let p = crate::pipeline::testing::profile("moltenvk-m3", DevicePolicy::RESIDENT_TABLES) .expect("profile"); let (_, one) = typed_module_linked(&caller, ONE, &p, &linked).expect("module"); + let null = FunctionTableSnapshot::of([]) + .expect("snapshot") + .bytes([]) + .expect("snapshot bytes"); for id in [T, 0] { assert_eq!( - dispatch(&one, 4, ids(&[id]), &directory, Words::Heap(&[])), + dispatch(&one, 4, ids(&[id]), &directory, Words::Snapshot(&null)), [0xffff_ffff; 4], "{id:#x}" ); @@ -781,8 +591,7 @@ fn needs_device_addresses(e: &Error) -> bool { /// A shape whose listed tables may pass the device's `maxStorageBufferRange` (lavapipe's 128 MiB) /// asks for the variant that reads them at their device addresses, on a device with device /// addresses; tables below 128 MiB, which every device's range reaches, ask for none, nor do they -/// where the range is 4 GiB. The variant declares the directory alone (no function-table array, no -/// snapshot) and states `FunctionTableRange` with `addressed`; its plan keeps the key whatever the +/// where the range is 4 GiB. The variant declares the directory alone (no snapshot) and states `FunctionTableRange` with `addressed`; its plan keeps the key whatever the /// shape, and writes each listed table's address into the directory, low word as the element and /// high word as the flags. A listed table without an address is refused, as is a directory that /// lists no table (its null entry's loads take a listed table's address). Without device addresses @@ -819,15 +628,6 @@ fn tables_past_the_storage_range_are_read_at_their_addresses() { continue; } let compiled = compiled.unwrap_or_else(|e| panic!("{stem}: {e}")); - assert!( - compiled - .layout - .sets - .iter() - .flat_map(|s| &s.bindings) - .all(|b| b.source != BindingSource::Heap(HandleClass::FunctionTable)), - "{stem}: a function-table array" - ); assert_eq!( synthetic(&compiled, SyntheticBinding::FunctionTableSnapshot), None, diff --git a/crates/metal2vulkan/src/tests/engine_recursion.rs b/crates/metal2vulkan/src/tests/engine_recursion.rs index 778f0d547..fd4dc7c56 100644 --- a/crates/metal2vulkan/src/tests/engine_recursion.rs +++ b/crates/metal2vulkan/src/tests/engine_recursion.rs @@ -36,13 +36,13 @@ //! //! `llvm-as` assembles the module; a missing tool skips visibly. -use super::engine_argument_tables::{bytes_at, capable_profiles, device, one_group, table_layout}; -use crate::bind::{ArgumentFunctionTable, BindState, FunctionTableWords}; +use super::engine_argument_tables::{bytes_at, device, directory_binding, one_group}; +use crate::bind::{ArgumentFunctionTable, BindState, FunctionTableSnapshot, FunctionTableWords}; use crate::budget::{Budget, SPIRV_WORDS}; use crate::device::VkLimit; use crate::error::{Capability, DescriptorError, Error, Feature, Limit, Unsupported}; use crate::library::{FunctionConstantValues, Library}; -use crate::lower::access::function_table::{directory_symbol, heap_symbol}; +use crate::lower::access::function_table::{directory_symbol, snapshot_symbol}; use crate::lower::select::LowerInputs; use crate::metal::PixelFormat; use crate::pipeline::artifact::PrecisionNote; @@ -589,11 +589,11 @@ fn pipeline(bitcode: &[u8], entry: &str, k: u32) -> (ComputePipeline, Vec (Vec, Vec) { let dev = device("moltenvk-m3"); - let (_, directory) = table_layout(pipe); + let directory = directory_binding(pipe); let state = BindState { function_tables: vec![ArgumentFunctionTable::new(T, handles.len() as u32)], ..Default::default() @@ -607,7 +607,11 @@ fn table_inputs(pipe: &ComputePipeline, handles: &[FunctionHandle]) -> (Vec, for (i, h) in handles.iter().enumerate() { assert!(table.set(i as u32, Some(*h))); } - (directory, table.to_bytes()) + let snapshot = FunctionTableSnapshot::of(state.function_tables.iter().map(|f| f.size)) + .expect("snapshot") + .bytes([table.to_bytes().as_slice()]) + .expect("snapshot bytes"); + (directory, snapshot) } /// Kernel buffer `index`. @@ -629,8 +633,8 @@ pub(super) fn buffer(slot: ResourceSlot, bytes: Vec) -> Buffer { } /// Run `m` with one thread per entry of `depths` (buffer 2), `out_words` output words a thread -/// (buffer 0), and, for a table kernel, `tables`: the directory's bytes and table [`T`]'s, with -/// [`T`]'s id at buffer 1. The words it writes. +/// (buffer 0), and, for a table kernel, `tables`: the directory's bytes and the snapshot of table +/// [`T`], with [`T`]'s id at buffer 1. The words it writes. fn dispatch( m: &TypedModule, depths: &[u32], @@ -645,12 +649,11 @@ fn dispatch( depths.iter().flat_map(|d| d.to_le_bytes()).collect(), ), ]; - if let Some((directory, table)) = tables { + if let Some((directory, snapshot)) = tables { buffers.extend([ buffer(slot(1), T.to_le_bytes().to_vec()), buffer(directory_symbol(Stage::Kernel), directory.clone()), - buffer(heap_symbol(Stage::Kernel), vec![0; 16]), - buffer(heap_symbol(Stage::Kernel), table.clone()), + buffer(snapshot_symbol(Stage::Kernel), snapshot.clone()), ]); } let res = Resources { @@ -820,7 +823,7 @@ fn recursive_kernels_validate_and_agree_on_every_profile() { } let ds = depths(24); let want: Vec = ds.iter().flat_map(|&d| [sum(d, 24), even(d, 24)]).collect(); - for (stem, p) in capable_profiles() { + for (stem, p) in committed_profiles().expect("profiles") { for entry in [TABLE, BIG] { check(&stem, entry, &p); } diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index f06d9f235..14dcb075b 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -9814,7 +9814,6 @@ variant metal2vulkan::bind::WriteSource::CombinedImageSampler CombinedImageSampl variant metal2vulkan::bind::WriteSource::ConstantBlob ConstantBlob { stage: Stage } variant metal2vulkan::bind::WriteSource::ControlPointIndices ControlPointIndices variant metal2vulkan::bind::WriteSource::ExecutionStatus ExecutionStatus -variant metal2vulkan::bind::WriteSource::FunctionTable FunctionTable { index: u32 } variant metal2vulkan::bind::WriteSource::FunctionTableSnapshot FunctionTableSnapshot variant metal2vulkan::bind::WriteSource::HandleTable HandleTable { stage: Stage, bytes_len: u32 } variant metal2vulkan::bind::WriteSource::HeapEntry HeapEntry { class: HandleClass, element: u32, source: HeapSource, view: ImageViewDesc }