//! Visible-function tables and function handles (`MTLVisibleFunctionTable`,
//! `MTLFunctionHandle`).
//!
//! - **A table is a buffer of words.** The translation reads a `visible_function_table` as a
//! read-only buffer of `pipeline::table`'s words at its Metal buffer index: 1 for a bound table,
//! its size, then one word per entry, 0 for a null entry and else a handle's. A table is one
//! runtime buffer of those words, `Shared`, written through its mapping, so a dispatch reads
//! the entries as they are when it runs: as on Metal (measured on an M3 Max and an M4), an
//! entry set after the dispatch was encoded and before the commit is the one it calls. The
//! encoder binds the table's buffer at the table's index (`set_visible_function_table`); an
//! unbound index reads the zero-filled neutral, a null table of size 0, Metal's plain answer.
//! - **Handles are the pipeline's.** `function_handle` is the word `pipeline::table` numbers the
//! function by among the kernel's linked functions (`functions`, then `binary_functions`):
//! one per function, none for a private function, an unlinked one or the kernel, as Metal
//! answers. A handle belongs to the state that gave it, and a table to the state that made it.
//! Metal's validation stops a handle of another state in `set_function`; plain Metal's table
//! then calls its own state's function at the position the handle has in its state, which a
//! table of a compute pipeline's kernel takes here (`metal_numbering`). A table of another state
//! bound to a dispatch is read by that dispatch's numbering; Apple calls tables and handles
//! specific to their pipeline (WWDC21 "Discover compilation workflows in Metal"), and Metal's own
//! numbering there differs (it counts private functions first), so nothing defines that run.
//! - **Metal's answers.** A table is a `Shared`, tracked resource (options 512) outside any heap,
//! with `allocatedSize` 256 bytes and 8 per entry, whole 16-KiB pages past 16 KiB; its
//! purgeable state is always non-volatile; its resource ID is the lowest free one of a space of
//! its own, from 1. A table holds as many entries as one buffer of the device's
//! `max_buffer_length` holds words, and at most `u32::MAX` (its size word). Metal makes larger
//! ones on an M3 Max and ends the process on an M4 (from 2^31 entries); a larger one is refused
//! here, naming the limit.
//! - **Render states' tables**. A render pipeline state gives handles and makes tables per stage
//! (`functionHandleWithFunction:stage:`, `newVisibleFunctionTableWithDescriptor:stage:`): a
//! drawing state's vertex or fragment function's, numbered among the functions that function
//! links, and a tile state's tile function's, which are its kernel state's. A table takes the
//! handles of its own state and stage alone, and the render encoder binds it at a stage's buffer
//! index (`set_vertex_visible_function_table` and the rest); a draw lists every live table of its
//! state, whatever the stage, for its argument buffers.
//! - **Tables in argument buffers**. An argument buffer holds a table as its resource ID, and Metal
//! reads it there without `useResource` (measured on an M3 Max and an M4). The device keeps every
//! live table by ID, and a dispatch lists the live tables its pipeline state made
//! (`BindState::function_tables`): the binder searches the ID in its directory and reads the
//! table's words from the heap's function-table array, at the element of its ID. The command
//! buffer retains every listed table until it completes, so an ID it wrote names one table
//! until then. A table of another state, or an ID of none, reads as the null table.
//! - **The snapshot**. A device without the array's features (`runtimeDescriptorArray`,
//! `descriptorBindingPartiallyBound`, `shaderStorageBufferArrayNonUniformIndexing`,
//! `descriptorBindingStorageBufferUpdateAfterBind`) reads the listed tables' words from one
//! snapshot per command (`bind::FunctionTableSnapshot`) in the command buffer's upload arena,
//! which the command buffer writes again as it commits: an entry set after the command was
//! encoded and before the commit is the one it calls, as on Metal. An entry set after the commit,
//! while the GPU may run the command, is read by Metal if the command had not run yet and not
//! here, a race of the program's on Metal.
use super::address::AddressPlacement;
use super::buffer::{Buffer, Modes};
use super::device::lock;
use super::error::{internal, invalid, nil, Error, Problem, RuntimeGap};
use super::library::Function;
use super::memory::MemoryClass;
use super::pipeline::{ComputePipelineState, GraphicsState, RenderPipelineState, RenderStateKind};
use super::resource_ids::{IdHold, IdPlacement, IdSpace, ResourceId};
use super::upload::Upload;
use super::{
CpuCacheMode, Device, HazardTrackingMode, PurgeableState, ResourceOptions, StorageMode,
};
use metal2vulkan::bind::{ArgumentFunctionTable, FunctionTableSnapshot, FunctionTableWords};
use metal2vulkan::error::{Feature, Unsupported};
use metal2vulkan::metal::RenderStages;
use metal2vulkan::pipeline::{LinkedFunction, LinkedFunctions, Stage};
use std::sync::{Arc, Mutex};
/// A table's options: `Shared`, the default CPU cache mode, tracked (Metal's 512).
fn table_options() -> ResourceOptions {
ResourceOptions::new(
StorageMode::Shared,
CpuCacheMode::DefaultCache,
HazardTrackingMode::Tracked,
)
}
/// `MTLVisibleFunctionTableDescriptor`.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct VisibleFunctionTableDescriptor {
/// `functionCount` (0 by default).
pub function_count: u64,
}
impl VisibleFunctionTableDescriptor {
/// A descriptor of `function_count` entries.
pub fn new(function_count: u64) -> VisibleFunctionTableDescriptor {
VisibleFunctionTableDescriptor { function_count }
}
}
/// What a visible-function table call did wrong (`Problem::FunctionTable`).
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FunctionTableProblem {
/// `set_function` with a handle of another pipeline state than the table's (Metal's
/// validation: "The function handle ... was not created from the pipeline state that created
/// this function table"), where plain Metal's answer was not measured: a compute state's
/// handle in a render state's table or the reverse, a tile pipeline's, an object or mesh
/// stage's, another stage's, a state that lists a private function more than once, in a
/// numbered list too, or in a group, and a position that names a private function of the
/// table's state; and so too a handle of a function added without the support flag to the
/// table's own stage where that stage's numbering was not measured or its other functions
/// are all private. Plain Metal's table
/// calls its own state's function at the handle's position (its last one past them), as the
/// runtime's does for two compute pipelines' kernels and two drawing states' vertex or
/// fragment functions.
///
/// Basis: unknown (Metal's validation stops the handle, and plain Metal's own answer was not
/// measured).
HandleOfAnotherState,
/// A command whose function writes a buffer, or reads an intersection function table, at
/// `index`, where a visible-function table is bound: plain Metal's answer was not measured
/// (ray tracing's tables are out of scope). A visible-function table where a function only
/// reads a buffer reads as an unbound buffer, zeros, as plain Metal's read where its
/// validation stops the command ("incorrect Buffer binding").
///
/// Basis: unknown (plain Metal's answer was not measured, and ray tracing's tables are out of
/// scope).
TableAtBufferIndex {
/// The buffer index.
index: u32,
},
/// A render pipeline state's `function_handle` or `new_visible_function_table` for `stage`,
/// which is not one stage: empty, or more than one. Metal's validation stops each ("stage
/// invalid"); plain Metal answers the handle nil, and the table of more than one stage (an
/// [`Error::Nil`](crate::Error::Nil)), and faults on a table of no stage (an
/// [`Error::Invalid`](crate::Error::Invalid); an M4 under macOS 27.0.1). One
/// stage the state has no function of answers no handle and makes a table, as plain Metal's.
///
/// Basis: metal-measured (an M4, macOS 27.0.1: plain Metal answers the handle nil and the table
/// of more than one stage nil, and faults on a table of no stage).
StageWithoutFunction {
/// The stage asked for.
stage: RenderStages,
},
}
/// `MTLFunctionHandle`: a function a pipeline state can place in its tables. Two handles are
/// equal when one state gave both for one function, as Metal gives that state's one object.
#[derive(Clone)]
pub struct FunctionHandle {
state: Maker,
handle: metal2vulkan::pipeline::FunctionHandle,
name: String,
}
/// The pipeline state that gives a handle or makes a table, and which of its functions' linked
/// functions number the handles: a compute state's kernel's (a tile state's, its tile
/// function's), or a drawing state's function of one stage; or a render state's stage it has no
/// function of, which numbers none, on its device.
#[derive(Clone)]
enum Maker {
Compute(ComputePipelineState),
Render(GraphicsState, Stage),
Unlinked(Device),
}
impl Maker {
/// Whether `other` is this state, and for a drawing state this stage.
fn is(&self, other: &Maker) -> bool {
match (self, other) {
(Maker::Compute(a), Maker::Compute(b)) => a == b,
(Maker::Render(a, x), Maker::Render(b, y)) => a.is(b) && x == y,
// No handle comes from a stage without a function.
_ => false,
}
}
/// The state's device.
fn device(&self) -> &Device {
match self {
Maker::Compute(state) => state.device(),
Maker::Render(state, _) => state.device(),
Maker::Unlinked(device) => device,
}
}
/// The functions that number its handles: none for a stage whose function links nothing more
/// (`GraphicsState::linked_functions`).
fn linked_functions(&self) -> Option<&LinkedFunctions> {
match self {
Maker::Compute(state) => Some(state.linked_functions()),
Maker::Render(state, stage) => state.linked_functions(*stage),
Maker::Unlinked(_) => None,
}
}
/// The handle of `function`, or `None` where Metal answers nil: a function the stage does not
/// link in `functions` or `binary_functions`. A function of another device is refused
/// (`Invalid(ForeignObject)`).
fn function_handle(self, function: &Function) -> Result