From 20ae73f152fcef17a6b71ac3ac5160e34a2e6542 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Sat, 21 Nov 2026 02:59:36 -0800 Subject: [PATCH] Translator: the resident-table domains' encoder-operation lowering goes; object words stay What: lower/access/encode.rs goes. It lowered a function's indirect-command encoder operations under the resident-table domains, writing the binder's records and their written flags. What it held that is still used moves to lower/access/object.rs: - an argument buffer's command-buffer or pipeline-state member read as its word (ObjectWord); - the plan that admits such a load only as an encoder operand. Every encoder operation is now refused, `Unsupported{GpuEncodedIndirectCommands, NotImplemented}`, except those the identity domains' icb.rs lowers: a render command's buffer setters, its indexed triangle draw and a reset. icb.rs is selected first, as before. The other deletions follow from that: - indirect_commands.rs drops CommandEncoderOperation's per-operation policy table; - lower/access/dynamic.rs drops the resident-set search and address helpers only encode.rs called (plan_search, plan_address, search_start, plain_base); - the error doc of the depth-stencil argument names the setters' refusal; - engine_indirect_commands.rs keeps two tests: every encoder operation refused under the resident-table domains on every committed profile and Profile F, and a depth-stencil member compiled unread and refused read. engine_handles.rs expects the refusal where a pipeline-state member is a command's operand; - the command-writes interface test now takes icbcut's indexed kernel (icb_indexed_16) under the identity domains, plus the template that takes no command buffer; - the authored census integration test expects the encoding case's refusal on both forms; - docs/API.md's indirect-command section says which domain refuses what; - docs/REFUSALS.md is regenerated. Why: rule 4 (small) and rule 2 (one form). The runtime compiles under the identity domains, where this lowering never ran. Under the resident-table domains, the validation executor's alone, it was a second form of GPU-encoded commands that no consumer path takes. No public item changes (indirect_commands is pub(crate); api_signatures.tsv is unchanged). Versions: SEMANTICS_VERSION 2255 -> 2256 (a placeholder; the landing sets the number), because the resident-table domains refuse what they lowered. Under the identity domains no output changes. Verified (jobs at this commit's tree less the runtime README edit below it, 4606692494, or at the next commit's, the runtime-sources pin, 4e9e857f8c): - m3-max-63058 at the pin: fmt, clippy, clippy --cfg m2v_gpu, clippy --cfg m2v_cpu_icd, Rustdoc -D warnings and scripts/api-docs, all rc 0 (peak 7.5 GiB); - m3-max-63040, the validation suite at this commit: 1359 of 1360 passed, the one failure the runtime guard, which the next commit pins; - m3-max-63057, the metal2vulkan and metal2vulkan-runtime suites and doctests at the pin: 3349 of 3360 passed. The failures are the render key, the AIR printout and the golden table (bless due at development's next pin) and the engine inventory's 8 parts: 2,142 cells moved, 0 rows new or gone, of which 1,342 are the storage forms' removal below this commit (ilock, m3-max-63032) and 800 are this commit's, the resident-table encoder operations now refused: m3-max-63151, the parts with every difference printed, names them as 50 entries on all 16 profiles, each ok -> Unsupported{GpuEncodedIndirectCommands; NotImplemented}, in 31 fixtures, every entry a kernel that encodes indirect commands (26 engine/icb_* and 3 kernel_icb_* fixtures, resident_draws.ll's rd_encode and mesh_commands.ll's six enc_* kernels); the other 1,342 are ilock's, class for class. The inventory compiles under RESIDENT_TABLES (spirv::testing::committed_profiles), and its bless runs on macOS only (bless_engine_inventory refuses without every assembler, m3-max-63084); - docs/REFUSALS.md regenerated by scripts/refusal-surface/refusal_surface.py; - no states-only play: the runtime compiles under the identity domains, whose output this commit is expected not to change. That is read from the code: icb.rs, the identity lowering, is untouched and still selected first. It is not measured, because the golden table's every cell is re-keyed until development's bless. ilock and this commit report the same staleness: 29,792 cells, m3-max-63032 and 63057. --- .../src/canon/command_writes.rs | 3 +- .../src/metal/command_guard/encoding.rs | 11 +- .../integration/authored_compile_census.rs | 29 +- .../src/bind/indirect_commands.rs | 11 +- crates/metal2vulkan/src/bind/replay.rs | 3 +- crates/metal2vulkan/src/bind/replay/draws.rs | 6 +- crates/metal2vulkan/src/cache/mod.rs | 2 +- crates/metal2vulkan/src/error/mod.rs | 13 +- crates/metal2vulkan/src/indirect_commands.rs | 169 +- .../metal2vulkan/src/lower/access/dynamic.rs | 74 +- crates/metal2vulkan/src/lower/access/emit.rs | 2 +- .../metal2vulkan/src/lower/access/encode.rs | 1399 ---------- crates/metal2vulkan/src/lower/access/icb.rs | 2 +- crates/metal2vulkan/src/lower/access/mod.rs | 20 +- .../metal2vulkan/src/lower/access/object.rs | 199 ++ crates/metal2vulkan/src/lower/select.rs | 4 +- .../src/pipeline/compile/tests.rs | 48 +- .../metal2vulkan/src/tests/engine_handles.rs | 38 +- .../src/tests/engine_indirect_commands.rs | 2319 +---------------- docs/API.md | 20 +- docs/REFUSALS.md | 14 +- 21 files changed, 419 insertions(+), 3967 deletions(-) delete mode 100644 crates/metal2vulkan/src/lower/access/encode.rs create mode 100644 crates/metal2vulkan/src/lower/access/object.rs diff --git a/crates/metal2vulkan-air/src/canon/command_writes.rs b/crates/metal2vulkan-air/src/canon/command_writes.rs index 8a4c13ea9..4c5ba0e61 100644 --- a/crates/metal2vulkan-air/src/canon/command_writes.rs +++ b/crates/metal2vulkan-air/src/canon/command_writes.rs @@ -24,8 +24,7 @@ use crate::ir::{Call, Callee, Const, FuncId, InstKind, Module, ModuleParts, Valu /// A draw's primitive type (`draw_primitives` and `draw_indexed_primitives`) counts as the value /// its operand holds where that is a constant of Metal's five (`MTLPrimitiveType`'s raw values, /// bit `n` for value `n`), as a point draw where it is a constant past them (Metal's encoding -/// writes one so: the translator's `lower::access::encode`), and as all five where it is anything -/// else. A call the walk cannot see +/// writes one so), and as all five where it is anything else. A call the walk cannot see /// into (an indirect call, an intrinsic outside the closed set, a call to a declaration other /// than the entry's control-point functions) may write anything: [`CommandWrites::ANY`]. /// Records the function does not write are not its own fact: a command buffer's other writers diff --git a/crates/metal2vulkan-validation/src/metal/command_guard/encoding.rs b/crates/metal2vulkan-validation/src/metal/command_guard/encoding.rs index 0e6c062d4..0941db526 100644 --- a/crates/metal2vulkan-validation/src/metal/command_guard/encoding.rs +++ b/crates/metal2vulkan-validation/src/metal/command_guard/encoding.rs @@ -112,8 +112,7 @@ impl CommandEncoderOperation { // A draw needs a render descriptor whose records hold its kind: primitives every render // buffer's, indexed draws an indexed or a patch buffer's, patch and indexed patch draws a // patch buffer's, mesh draws a buffer of either mesh kind's. A draw of primitives on a - // buffer of mesh draws alone writes too: Metal draws nothing for it, and the product's - // lowering drops it (`dropped_on`). + // buffer of mesh draws alone writes too: Metal draws nothing for it. let patch_records = DRAW_PATCHES | DRAW_INDEXED_PATCHES; let mesh_records = DRAW_MESH_THREADGROUPS | DRAW_MESH_THREADS; let draw = |any| Policy { @@ -267,15 +266,15 @@ fn header_field_of(body: &mut String, records: &str, name: &str, word: usize, ty .unwrap(); } -/// A copy's checks beyond the destination's policy, as the product's lowering makes them -/// (`lower::access::encode`), into `%valid4` from `valid`: the source command (`%source_command`) -/// is below the capacity of the source's header (`%source_records`), and either the two headers +/// A copy's checks beyond the destination's policy, into `%valid4` from `valid`: the source +/// command (`%source_command`) is below the capacity of the source's header (`%source_records`), +/// and either the two headers /// are of equal descriptors (policy bits and binding counts), or the destination inherits its /// pipeline and buffers from a source that inherits neither, of the same descriptor otherwise, /// the destination binding no kernel buffer, onto a command other than 0. Metal's copy between /// any other descriptors depends on its private record layout, and its copy onto an inheriting /// buffer's command 0 runs that command with zero grid sizes (M3 Max and M4), so the guard faults -/// them as the lowering does. +/// them. fn emit_copy_checks(body: &mut String, typed: bool, valid: &str) { use std::fmt::Write; let pointer = if typed { diff --git a/crates/metal2vulkan-validation/tests/integration/authored_compile_census.rs b/crates/metal2vulkan-validation/tests/integration/authored_compile_census.rs index f2bcedabd..f2e66040e 100644 --- a/crates/metal2vulkan-validation/tests/integration/authored_compile_census.rs +++ b/crates/metal2vulkan-validation/tests/integration/authored_compile_census.rs @@ -262,11 +262,12 @@ fn corpus_with_templates(name: &str) -> (ScratchDir, metal2vulkan_validation::ca } /// The executor's requests for a case whose executed compute command buffer the device replay -/// runs: on a profile with device addresses, the case's pipeline and each registered variant -/// compile in the worker; on one without, the command buffer is host-replayed and only the case's -/// own pipeline is compiled. A render command buffer is always host-replayed. Both devices take -/// the resident-table domains, the executor's own context's, which run the command buffers the -/// identity domains refuse. +/// runs: on a profile with device addresses, the case's pipeline and each registered variant; on +/// one without, the command buffer is host-replayed and only the case's own pipeline. A render +/// command buffer is always host-replayed. Both devices take the resident-table domains, the +/// executor's own context's, which runs the command buffers. The case's kernel encodes commands, +/// which no device lowers (`GpuEncodedIndirectCommands`), so its cell is that refusal on both, with +/// no digest. #[test] fn case_compiles_lists_the_replay_variants_where_the_device_replay_runs() { use metal2vulkan_validation::authored_compile::compile_prepared; @@ -320,23 +321,17 @@ fn case_compiles_lists_the_replay_variants_where_the_device_replay_runs() { assert!(on_device.compiles[1..] .iter() .all(|compile| matches!(compile.subject, CompileSubject::ReplayVariant { .. }))); + let refused = Ok(CellOutcome::Refused( + "not_supported{unsupported:not_implemented GpuEncodedIndirectCommands}".into(), + )); let cell = compile_prepared(&compute, &worker, &lavapipe); - assert_eq!(cell.outcome, Ok(CellOutcome::Compiled), "{cell:?}"); - assert_eq!(cell.compiles, on_device.compiles.len()); - // What a run executes there is digested: the case, each variant, and the preprocess module; the - // same compiles digest the same. - let digest = cell - .artifact - .clone() - .expect("a device-replayed case's digest"); - let again = compile_prepared(&compute, &worker, &lavapipe); - assert_eq!(again.artifact, Some(digest)); + assert_eq!(cell.outcome, refused, "{cell:?}"); + assert_eq!(cell.artifact, None, "{cell:?}"); let on_host = case_compiles(&compute, &floor).unwrap(); assert_eq!(on_host.host_replayed, 1); assert_eq!(on_host.compiles.len(), 1); - // Where the host replay runs a command buffer, the census compiles less than the run does: - // no digest. let host = compile_prepared(&compute, &worker, &floor); + assert_eq!(host.outcome, refused, "{host:?}"); assert_eq!(host.artifact, None, "{host:?}"); let (scratch, case) = diff --git a/crates/metal2vulkan/src/bind/indirect_commands.rs b/crates/metal2vulkan/src/bind/indirect_commands.rs index 54b2c5abe..741574afe 100644 --- a/crates/metal2vulkan/src/bind/indirect_commands.rs +++ b/crates/metal2vulkan/src/bind/indirect_commands.rs @@ -1,18 +1,19 @@ -//! The indirect-command record format: what a translated kernel's command encoders -//! (`compute_command`, `render_command`) write into an indirect command buffer's storage, and what -//! a CPU encoder writes, a header and one fixed-size record per command. +//! The indirect-command record format: what a CPU encoder writes into an indirect command +//! buffer's storage, a header and one fixed-size record per command. No translated function +//! writes it: a function's command encoders (`compute_command`, `render_command`) are refused, +//! `Unsupported{GpuEncodedIndirectCommands, NotImplemented}`. //! //! A consumer that runs its own runtime on the compile layer needs it to execute and read back //! indirect command buffers: [`CommandBuffer::initialize`] writes the header a //! [`CommandDescriptor`] and an [`Inheritance`] fix and resets every record, //! [`CommandRecord::encode_into`] writes one command as the CPU's encoder sets it, and -//! [`CommandBuffer::decode`] checks storage a kernel wrote (its sticky encoding fault, the header, +//! [`CommandBuffer::decode`] checks the storage (its sticky encoding fault, the header, //! every record against the descriptor) before [`CommandBuffer::records`] reads a range back as //! [`CommandRecord`]s. [`CommandRecord::resolve_bindings`] picks each command's pipeline and //! buffers from itself or from the executing encoder, and [`BufferBinding::resolve_buffer`] finds //! the [`RegisteredBuffer`] whose interval holds a buffer's address. The device replay (`replay_preprocess`) //! reads the same records on the GPU. Storage may hold a written flag per command past the -//! records ([`written_flag_offset`]), which a kernel's writes of a record set, so a reset need +//! records ([`written_flag_offset`]), which the consumer's writes of a record set, so a reset need //! touch only the flagged records. pub use crate::indirect_commands::records_address; diff --git a/crates/metal2vulkan/src/bind/replay.rs b/crates/metal2vulkan/src/bind/replay.rs index 91a99fc9b..0fc4aec2f 100644 --- a/crates/metal2vulkan/src/bind/replay.rs +++ b/crates/metal2vulkan/src/bind/replay.rs @@ -1511,8 +1511,7 @@ pub fn typed_module(limits: [u32; 3]) -> BResult { // A command that sets any buffer while inheriting buffers: a slot no setter set holds an // address and a stride of 0. Only its kernel buffers below the descriptor's count are read // (the header's byte 0, `layout::COUNTS`): every other binding of a compute record is zero, - // as the storage is made zero, an encoder's write past the count faults and writes nothing - // (`lower::access::encode`), the CPU's setter refuses one, a compute command has no other + // as the storage is made zero, the CPU's setter refuses one, a compute command has no other // stage's setter, and a copy takes a source of the same descriptor. So a command reads the // bindings its descriptor counts, not the record's 128, 2 KiB. let counts_at = at(fb, records, layout::COUNTS)?; diff --git a/crates/metal2vulkan/src/bind/replay/draws.rs b/crates/metal2vulkan/src/bind/replay/draws.rs index 4bc75c1b3..6335608c4 100644 --- a/crates/metal2vulkan/src/bind/replay/draws.rs +++ b/crates/metal2vulkan/src/bind/replay/draws.rs @@ -1116,9 +1116,9 @@ pub fn typed_module() -> BResult { // fragment and object stages): one bound with a dynamic stride where the descriptor allows // none or the stage takes none (fragment, object) is a record the host's validation refuses; // one set while the commands inherit buffers refuses the command. A binding past its stage's - // count is not read. It is zero in every record: the storage is made zero, an encoder's write - // past the count faults and writes nothing (`lower::access::encode`), the CPU's setter refuses - // one, and a copy takes a source of the same descriptor. So the host's refusal of a binding set + // count is not read. It is zero in every record: the storage is made zero, the CPU's setter + // refuses one, and a copy takes a source of the same descriptor. So the host's refusal of a + // binding set // there never applies, and a command's reads of the record's 128 bindings, 2 KiB, shrink to // those its descriptor counts. let inherit_bit = k32(fb, INHERIT_BUFFERS)?; diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index b31ffa1e7..47d19c03f 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 = 2255; +pub const SEMANTICS_VERSION: u32 = 2256; /// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the /// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another diff --git a/crates/metal2vulkan/src/error/mod.rs b/crates/metal2vulkan/src/error/mod.rs index 9f5203114..c49ff72d6 100644 --- a/crates/metal2vulkan/src/error/mod.rs +++ b/crates/metal2vulkan/src/error/mod.rs @@ -953,13 +953,12 @@ pub enum Feature { /// (`Capability::Limit` names `MaxFramebufferWidth`, `MaxFramebufferHeight` or /// `MaxFramebufferLayers`). Metal renders passes up to 16384 pixels a side and 2048 layers. RenderTargetSize, - /// A render state a function sets on an indirect render command - /// (`render_command::set_cull_mode`, `set_front_facing_winding`, `set_triangle_fill_mode`, - /// `set_depth_bias`, `set_depth_clip_mode`, `set_depth_stencil_state`), or a - /// `depth_stencil_state` it reads from an argument buffer: the record holds no render state. - /// Metal's Apple10 family alone lists the feature, and Metal's compiler refuses such a - /// function on an Apple9 GPU, so the runtime answers it as that compiler does on a device that - /// does not claim Apple10 ([`Needs::MetalGpuFamily`]). + /// A `depth_stencil_state` a function reads from an argument buffer or takes as a parameter, + /// the state of an indirect render command, which no record holds. (A render command's state + /// setters, `render_command::set_cull_mode` and the rest, are `GpuEncodedIndirectCommands`, as + /// every encoder operation is.) Metal's Apple10 family alone lists the feature, and Metal's + /// compiler refuses such a function on an Apple9 GPU, so the runtime answers it as that + /// compiler does on a device that does not claim Apple10 ([`Needs::MetalGpuFamily`]). IndirectRenderState, /// A fragment function's read of a Metal 3.1 program-scope built-in variable that Metal does /// not lower there: a global `thread_index_in_quadgroup` (`air.get_thread_index_in_quadgroup`), diff --git a/crates/metal2vulkan/src/indirect_commands.rs b/crates/metal2vulkan/src/indirect_commands.rs index 2c4752d59..fc152acd2 100644 --- a/crates/metal2vulkan/src/indirect_commands.rs +++ b/crates/metal2vulkan/src/indirect_commands.rs @@ -1,5 +1,7 @@ -//! The indirect-command record format: what a translated kernel's command encoders write, what the -//! CPU's do, and what a replay reads (`bind::indirect_commands` is the public path). +//! The indirect-command record format: what the CPU's command encoders write and what a replay +//! reads (`bind::indirect_commands` is the public path). No translated function writes it: every +//! encoder operation is `Unsupported{GpuEncodedIndirectCommands, NotImplemented}` +//! (`lower::access::object`). //! //! The records are ordinary buffer storage, a header and one fixed-size record per command; they //! are not Vulkan command buffers or device-generated-command tokens. @@ -25,52 +27,6 @@ pub enum BufferStage { Mesh, } -/// Recognized command-encoder operation; recognition does not establish lowering support. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum CommandEncoderOperation { - Buffer { - stage: BufferStage, - address_space: u32, - }, - Dispatch { - exact_threads: bool, - }, - Pipeline { - render: bool, - }, - Barrier { - render: bool, - enabled: bool, - }, - ThreadgroupMemory, - Draw, - /// `set_stage_in_region`: the six words of the region. - StageInRegion, - /// `set_imageblock_size`: the two `u16`s of the size. - ImageblockSize, - /// `reset`: the record restored to [`CommandRecord::default`], of a render command where - /// `render`, else a compute command. - Reset { - render: bool, - }, - /// `draw_indexed_primitives`: an indexed draw's arguments. - DrawIndexed, - /// `draw_patches`: a patch draw's arguments. - DrawPatches, - /// `copy_command`: a compute command's record from a source command, whose buffer's header - /// the lowering checks against the destination's (`lower::access::encode`). - Copy, - /// `draw_indexed_patches`: an indexed patch draw's arguments, a patch draw's and its - /// control-point index buffer's address ([`Action::DrawIndexedPatches`]). - DrawIndexedPatches, - /// `draw_mesh_threadgroups` (`threads` false) or `draw_mesh_threads`: a mesh draw's grid and - /// its object and mesh threadgroups' threads ([`Action::DrawMeshThreadgroups`], - /// [`Action::DrawMeshThreads`]). - DrawMesh { - threads: bool, - }, -} - /// Number of buffer slots represented in a command. pub const BINDING_COUNT: usize = 32; /// Number of threadgroup-buffer argument-table entries exposed by the Metal ABI @@ -96,13 +52,10 @@ pub const COMMAND_BUFFER_HEADER_BYTES: usize = 16; pub const WRITTEN_FLAG_BYTES: usize = 4; /// The byte offset of command `index`'s written flag in the storage of a buffer of `capacity` -/// commands: the flags follow the records, one `u32` a command. Each encoder operation that -/// writes a command's record (one the header's policy takes, `lower::access::encode`) stores 1 -/// at its flag, contained as the record's fields are: storage that ends at its records takes no -/// flag, and its records are written as before. A consumer whose storage holds the flags, and -/// whose own writes of the records set them as well, knows a record whose flag is clear to hold -/// what it last reset it to, and may reset only the flagged ones, clearing each flag with its -/// record. +/// commands: the flags follow the records, one `u32` a command. No translated function writes a +/// record or its flag. A consumer whose storage holds the flags, and whose own writes of the +/// records set them, knows a record whose flag is clear to hold what it last reset it to, and may +/// reset only the flagged ones, clearing each flag with its record. pub const fn written_flag_offset(capacity: u32, index: u32) -> u64 { COMMAND_BUFFER_HEADER_BYTES as u64 + capacity as u64 * COMMAND_BYTES as u64 @@ -114,8 +67,7 @@ pub const fn written_flag_offset(capacity: u32, index: u32) -> u64 { pub const RECORDS_ADDRESS_BASE: u64 = 1 << 63; /// How far an indirect command buffer's resource ID is shifted to give the guest address its /// records start at past [`RECORDS_ADDRESS_BASE`] ([`records_address`]): 2^31 bytes from one ID's -/// start to the next's. Records of more bytes run past the next IDs' starts, which a search for -/// those IDs' records still tells apart: it finds an ID's records only at their start. +/// start to the next's. Records of more bytes run past the next IDs' starts. pub(crate) const RECORDS_ADDRESS_SHIFT: u32 = 31; /// The first resource ID whose records [`records_address`] cannot place, 2^31: the IDs of indirect /// command buffers run from 1 below it, as Metal's do (on an M3 Max, a reservation of 2^31 - 2 @@ -127,19 +79,18 @@ pub const RECORDS_ID_LIMIT: u64 = 1 << 31; /// [`RECORDS_ID_LIMIT`]) start at: `2^63 + id * 2^31`. An argument buffer's command-buffer member /// holds the ID, as Metal's `gpuResourceID` and `setIndirectCommandBuffer:atIndex:` give it (small /// integers from 1, measured on an M3 Max and an M4, or the IDs a reservation leaves next, up to -/// 2^31 - 1 on an M3 Max), and a translated kernel that encodes through it reaches the records -/// that start at this address in its resident set, and no other: records of more than 2^31 bytes -/// run past the next IDs' starts, and the resident set keeps each records range whole -/// (`ResidentSet`). So a consumer that makes an indirect command buffer with ID `id` makes its -/// record buffer resident at `records_address(id)`, a range no Metal buffer reaches (each lies -/// below 2^63). The null ID 0 gives an address no records start at, so an encoder operation -/// through it is contained as one through an ID whose records are not resident is. +/// 2^31 - 1 on an M3 Max). Records of more than 2^31 bytes run past the next IDs' starts, and the +/// resident set keeps each records range whole (`ResidentSet`). So a consumer that makes an +/// indirect command buffer with ID `id` makes its record buffer resident at `records_address(id)`, +/// a range no Metal buffer reaches (each lies below 2^63). The null ID 0 gives an address no +/// records start at. No translated function reaches the records through it: every encoder +/// operation is refused (`GpuEncodedIndirectCommands`). pub const fn records_address(id: u64) -> u64 { RECORDS_ADDRESS_BASE | (id << RECORDS_ADDRESS_SHIFT) } -/// The byte offsets the lowering of the encoder operations writes through device addresses -/// (`lower::access::encode`), with the header checks of [`Policy`]. +/// The byte offsets of the header's and a record's fields, which the CPU's encoder writes and the +/// device replay reads (`bind::replay`). pub(crate) mod layout { use super::{ BufferStage, BINDING_COUNT, BUFFER_STAGES, BUFFER_WORDS, HEADER_WORDS, THREADGROUP_COUNT, @@ -156,8 +107,6 @@ pub(crate) mod layout { /// kernel buffers in byte 0 and threadgroup lengths in byte 3; a render descriptor's object, /// vertex, fragment and mesh buffers in bytes 0 to 3. pub(crate) const COUNTS: u64 = 12; - /// The first record. - pub(crate) const RECORDS: u64 = super::COMMAND_BUFFER_HEADER_BYTES as u64; /// Bytes of one record. pub(crate) const RECORD: u64 = super::COMMAND_BYTES as u64; /// A record's action tag (`u32`). @@ -220,30 +169,6 @@ pub(crate) mod layout { pub(crate) const STATE_BITS: u32 = RETAINED | KERNEL_PIPELINE; } -/// The descriptor policy an encoder operation's write requires of the record header: its -/// policy bits masked with `required | forbidden` equal `required`, and hold one of `any` where -/// `any` is not 0, the command index is below the capacity, a binding index is below its count, -/// and a dynamic stride is all ones unless the descriptor enables dynamic strides. A write that -/// fails any of them sets the fault flag instead and writes nothing, but a draw on a buffer of -/// `dropped_on` alone, which writes nothing and sets no fault. A threadgroup length is kept as -/// set, a multiple of 16 or not, as Metal keeps it. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) struct Policy { - pub(crate) required: u32, - pub(crate) forbidden: u32, - /// The kinds of which the descriptor must allow one (0: no such check): those whose Metal - /// record holds the operation's draw ([`DrawKind::holders`]). - pub(crate) any: u32, - /// The byte of the header's packed counts that bounds the operation's binding index, where - /// it binds one. - pub(crate) binding: Option, - pub(crate) dynamic_stride: bool, - /// The kinds on a buffer of which, allowing none of `any`, a draw that is otherwise valid is - /// dropped: it writes nothing and sets no fault (0: none). A kernel's draw of primitives on - /// a buffer of mesh draws alone draws nothing on Metal, without a fault (a Metal probe). - pub(crate) dropped_on: u32, -} - /// A draw's kind, as the command types Metal's records are made for order them: a buffer's /// records hold a draw of a kind its types allow, or of a kind whose record a kind it allows /// holds. Draws of primitives fit every render buffer's records but those of mesh draws alone, @@ -276,7 +201,7 @@ impl DrawKind { } // The header's policy bits, which a command-buffer descriptor sets at initialization and the -// encoder operations' lowering checks ([`Policy`]). +// device replay reads. pub(crate) const COMPUTE: u32 = 1; pub(crate) const RENDER: u32 = 2; pub(crate) const GROUPS: u32 = 4; @@ -1082,63 +1007,5 @@ fn arguments(words: [u32; N]) -> [u32; layout::DRAW_ARGUMENT_WOR all } -impl CommandEncoderOperation { - /// The descriptor policy this operation's write requires of the header ([`Policy`]). - pub(crate) fn policy(self) -> Policy { - let family = |render: bool| if render { RENDER } else { COMPUTE }; - let plain = |required| Policy { - required, - forbidden: 0, - any: 0, - binding: None, - dynamic_stride: false, - dropped_on: 0, - }; - // A draw needs a render descriptor whose records hold its kind. - let draw = |kind: DrawKind| Policy { - any: kind.holders(), - ..plain(RENDER) - }; - match self { - Self::Buffer { stage, .. } => Policy { - required: family(stage != BufferStage::Kernel), - forbidden: INHERIT_BUFFERS, - any: 0, - binding: Some(match stage { - BufferStage::Kernel => 0, - BufferStage::Vertex => 1, - BufferStage::Fragment => 2, - // A render descriptor's object and mesh counts take the bytes of the kernel - // and threadgroup counts, which a compute descriptor's alone hold. - BufferStage::Object => 0, - BufferStage::Mesh => 3, - }), - dynamic_stride: matches!(stage, BufferStage::Kernel | BufferStage::Vertex), - dropped_on: 0, - }, - // Every compute descriptor allows a dispatch kind, and its records hold either. - Self::Dispatch { .. } => plain(COMPUTE), - Self::Pipeline { render } => Policy { - forbidden: INHERIT_PIPELINE, - ..plain(family(render)) - }, - Self::Barrier { render, .. } => plain(family(render)), - Self::ThreadgroupMemory => Policy { - binding: Some(3), - ..plain(COMPUTE) - }, - Self::Draw => Policy { - dropped_on: DRAW_MESH_THREADGROUPS | DRAW_MESH_THREADS, - ..draw(DrawKind::Primitives) - }, - Self::DrawIndexed => draw(DrawKind::Indexed), - Self::DrawPatches | Self::DrawIndexedPatches => draw(DrawKind::Patches), - Self::DrawMesh { .. } => draw(DrawKind::Mesh), - Self::Reset { render } => plain(family(render)), - Self::StageInRegion | Self::ImageblockSize | Self::Copy => plain(COMPUTE), - } - } -} - #[cfg(test)] mod tests; diff --git a/crates/metal2vulkan/src/lower/access/dynamic.rs b/crates/metal2vulkan/src/lower/access/dynamic.rs index 834291def..a19e0fef8 100644 --- a/crates/metal2vulkan/src/lower/access/dynamic.rs +++ b/crates/metal2vulkan/src/lower/access/dynamic.rs @@ -1572,7 +1572,7 @@ pub fn emit( /// Plan a load of the 8-byte word at buffer pointer `ptr` (of AIR type `ty`, aligned `align`) as /// data, a `u64`: through a static root (a descriptor view or a static device-address slot), or /// a wide pointer's root entry. An indirect-command object's handle load reads its field this -/// way (`access::encode`). +/// way (`access::object`). pub(super) fn plan_word( cx: &mut SelectCx<'_>, ptr: Value, @@ -1596,21 +1596,6 @@ pub(super) fn plan_word( }) } -/// Plan a resident-set search outside a pointer value (an encoder's record buffer): the function -/// reads the root table, searches it once more, and under isolation counts an access through -/// root 0. The caller checked the profile's device addresses and the stage's store feature. -pub(super) fn plan_search(cx: &mut SelectCx<'_>) -> Result<(), Error> { - require_addresses(cx)?; - plan_resolve(cx); - plan_misses(cx) -} - -/// Plan the guest address of buffer pointer `v` written as data: the null constant, or a wide -/// pointer (every root whose pointer escapes is wide on a profile with device addresses). -pub(super) fn plan_address(cx: &mut SelectCx<'_>, v: Value) -> Result { - stored(cx, v) -} - /// The 8-byte word `s` reads ([`plan_word`]), a `u64`. pub(super) fn emit_word( cx: &mut EmitCx<'_>, @@ -1628,60 +1613,3 @@ pub(super) fn emit_word( }; word.ok_or_else(|| cx.fail("an object word without a value")) } - -/// The wide pointer of the resident allocation that starts at guest address `guest` (a `u64`): -/// the resident-set search ([`resolve`]), its hit kept only at the allocation's start, any other -/// address a miss, `(0, guest)`. Indirect command buffers' records are searched so: records longer -/// than the distance between two IDs' starts run past the next IDs' starts -/// (`indirect_commands::records_address`), and an ID whose own records are not resident then -/// misses rather than reaching into another's. -pub(super) fn search_start( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - guest: SValue, -) -> BResult { - let p = resolve(cx, fb, guest)?; - let [root, off, host, size] = fields(fb, p)?; - let zero = k64(fb, 0)?; - let at_start = fb.binary(BinOp::IEqual, off, zero)?; - let root = fb.select(at_start, root, zero)?; - let off = fb.select(at_start, off, guest)?; - let host = fb.select(at_start, host, zero)?; - let size = fb.select(at_start, size, zero)?; - fat(fb, [root, off, host, size]) -} - -/// The allocation of wide pointer `p` resolved for plain accesses in the function's coherence, -/// an access through root 0 counted under isolation ([`wide_base`]). -pub(super) fn plain_base( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - p: SValue, -) -> BResult { - base_with(cx, fb, p, (None, false), None) -} - -/// A `PhysicalStorageBuffer` pointer to the `u32` at `d` bytes (a `u64`, 4-aligned past a -/// 4-aligned base) past `b`, contained: out of bounds, the sink's first word. -pub(super) fn word_place(fb: &mut FunctionBuilder<'_>, b: WideBase, d: SValue) -> BResult { - let at = fb.binary(BinOp::IAdd, b.at, d)?; - let mut addr = fb.binary(BinOp::IAdd, b.host, at)?; - if let Some((size, sink)) = b.bounds { - let inb = contain::in_bounds(fb, at, size, 4)?; - addr = fb.select(inb, addr, sink)?; - } - let u32_ = fb.module().ty(SType::Int { - width: 32, - signed: false, - })?; - fb.device_place(addr, u32_) -} - -/// The Metal address of `side` ([`plan_address`]): a wide pointer's guest address, or 0. -pub(super) fn address_of( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - side: Side, -) -> BResult { - metal_address(cx, fb, side) -} diff --git a/crates/metal2vulkan/src/lower/access/emit.rs b/crates/metal2vulkan/src/lower/access/emit.rs index beb363672..396328db6 100644 --- a/crates/metal2vulkan/src/lower/access/emit.rs +++ b/crates/metal2vulkan/src/lower/access/emit.rs @@ -698,7 +698,7 @@ pub fn emit( AccessStrategy::Value(p) => super::pointer::emit(cx, fb, vid, p), AccessStrategy::Cell(c) => super::cell::emit(cx, fb, vid, c), AccessStrategy::Imageblock(i) => super::imageblock::emit(cx, fb, vid, i), - AccessStrategy::Encode(e) => super::encode::emit(cx, fb, vid, e), + AccessStrategy::Object(o) => super::object::emit(cx, fb, vid, o), AccessStrategy::Commands(c) => super::icb::emit(cx, fb, c), AccessStrategy::FunctionTable(t) => super::function_table::emit(cx, fb, vid, t), AccessStrategy::AbsentRead(a) => super::absent::emit(cx, fb, vid, a), diff --git a/crates/metal2vulkan/src/lower/access/encode.rs b/crates/metal2vulkan/src/lower/access/encode.rs deleted file mode 100644 index e0c0c74cf..000000000 --- a/crates/metal2vulkan/src/lower/access/encode.rs +++ /dev/null @@ -1,1399 +0,0 @@ -//! GPU-encoded indirect commands: an encoder's operations write the host's command records -//! (`HostRecordsV1`, `crate::indirect_commands`) through device addresses. -//! -//! **Object words.** An argument buffer's command-buffer or pipeline-state member is an -//! indirect-command object. Its handle load (`memory::provenance::object_handle_load`) reads the -//! member's field, 8 bytes, as data ([`EncodeStrategy::Word`], a `u64`): a command buffer's word is -//! its resource ID, Metal's `gpuResourceID`, whose records lie at the guest address -//! `indirect_commands::records_address` of it, `2^63 + id * 2^31`; a pipeline state's word is the -//! template's host-registered token. A handle load is admitted only when every use of its value is -//! an encoder operand of its class ([`plan_objects`]): the command operand of an encoder operation, -//! or the pipeline operand of `air.set_pipeline_state_{compute,render}_command`. Any other use (an -//! integer, a compare, a store, a merge) leaves the load refused as before -//! (`ArgumentBufferObjects`, `pointer::select`), so no other instruction observes the word. -//! -//! **Operations** ([`EncodeStrategy::Command`]). The command word's records address is searched -//! in the resident set for the allocation that starts there (`dynamic::search_start`), and the -//! record buffer is accessed through its root entry, contained: an access through root 0 (an -//! address at which no resident allocation starts) is counted under isolation and lands in the -//! sink. Each operation reads the header's capacity, policy bits, -//! and binding counts; when the write is valid by the descriptor policy -//! (`indirect_commands::Policy`) it writes the command's fields, and otherwise it sets the header's -//! sticky fault flag (a relaxed atomic store of 1) and writes nothing, exactly as the old engine's -//! helpers do (`CommandEncoderOperation::helper`), so the host's `CommandBuffer::decode` fails the -//! run. A buffer setter writes its buffer's guest address (the pointer escapes, so it is wide) and, -//! for a kernel or vertex buffer, its attribute stride (a fragment, object or mesh buffer has -//! none; AIR 2.5's kernel or vertex setter takes none and writes the pipeline's own, all ones, as -//! the stride today's compiler spells MSL's plain setter with); a pipeline setter the pipeline -//! state's word; a dispatch its grid, local size, and action; -//! a draw its five arguments and action (on a buffer of mesh draws alone, nothing and no fault, as -//! a kernel's draw there draws nothing on Metal: `Policy::dropped_on`); a mesh draw its grid, its -//! object and mesh threadgroups' threads, and its action; an indexed draw its five arguments, its -//! index type (the overload's), its index buffer's guest address (wide, as a buffer setter's), and -//! its action; a patch draw its six arguments, its patch index and factor buffers' guest addresses -//! (0 for a null patch index buffer), its factor scale's `f32` bits, and its action; an indexed -//! patch draw a patch draw's fields and its control-point index buffer's guest address (0 for null) -//! where the record keeps it, under its own action; a barrier (of a compute or a render command) -//! its flag (set or cleared); a threadgroup-length setter the length at its binding, as set (a -//! multiple of 16 or not, as Metal keeps it); a stage-in region setter its six words; an imageblock -//! size setter its two `u16`s; and a reset (of a compute or render command) the record as -//! `CommandRecord::default` encodes it, in loops of `u64` stores over its command words, the -//! bindings below each stage's count in the header and the words past the bindings: a binding -//! past its count is zero in every record, as no write reaches one (`default_record`). A valid -//! operation (a copy too) -//! also stores 1 at its command's written flag past every record -//! (`indirect_commands::written_flag_offset`), contained as its fields are. -//! -//! **Copies** (`copy_command`). The source command buffer is an object word too, and its record -//! buffer is searched as the command's is. A copy is valid when the source index is below the -//! source's capacity and the two headers are of equal descriptors (policy bits and binding counts), -//! in which case it copies the whole record, `u64` by `u64` in a loop; or when the destination -//! inherits its pipeline and its buffers from a source that inherits neither and is otherwise of -//! the same descriptor (the destination binds no kernel buffer), in which case it copies every -//! `u64` but the pipeline's and the buffer bindings', the state the destination takes from the -//! encoder that executes it, as Metal's copy measured (M3 and M4). Any other copy's result depends -//! on Metal's private record layout (a copy between other descriptors, an index at either -//! capacity): it sets the destination's sticky fault and copies nothing. -//! -//! **Profile F** has no device addresses: every operation is `GpuEncodedIndirectCommands`, naming -//! what it lacks of `bufferDeviceAddress` and `shaderInt64`. A vertex or fragment function on a -//! device without the stage's store feature refuses an operation the same way, naming the -//! feature. - -use std::borrow::Cow; -use std::collections::{BTreeMap, BTreeSet}; - -use crate::air::intrinsics::{AirIntrinsic, CommandStage, IndirectCommand}; -use crate::air::ir::{AddrSpace, Callee, Inst, InstId, InstKind, Value, ValueId}; -use crate::budget::{tree_bytes, Meter}; -use crate::device::profile::BufferAccess; -use crate::device::requirements::VkFeature; -use crate::error::{Capability, Error, Feature, Unsupported}; -use crate::indirect_commands::{ - layout, BufferStage, CommandEncoderOperation, Policy, BINDING_COUNT, DYNAMIC_STRIDE, - INHERIT_BUFFERS, INHERIT_PIPELINE, RECORDS_ADDRESS_BASE, RECORDS_ADDRESS_SHIFT, - WRITTEN_FLAG_BYTES, -}; -use crate::lower::arith::{Form, Held}; -use crate::lower::emit::EmitCx; -use crate::lower::select::SelectCx; -use crate::memory::leaf::{Leaf, Path}; -use crate::memory::provenance::{self, HandleClass, Repr}; -use crate::memory::roots::k64; -use crate::pipeline::sym::Stage; -use crate::spirv::builder::constructs::{ArmEnd, ArmFn, LoopFn, LoopSpec}; -use crate::spirv::builder::FunctionBuilder; -use crate::spirv::error::BResult; -use crate::spirv::ids::{DemoteTy, ScalarTy, Value as SValue}; -use crate::spirv::ir::{ - BinOp, ConstBits, Constant, ConvOp, MemAccess, Scope, Semantics, Type as SType, UnOp, -}; - -use super::dynamic::{self, Side, Source}; -use super::{operand, refuse, AccessPlan}; - -/// The encoder strategies. -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum EncodeStrategy { - /// The handle load of an indirect-command object: its field's word, a `u64`. - Word(Source), - /// An encoder operation's record writes. - Command(Box), -} - -/// One encoder operation. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct Command { - /// The operation, in the host contract's terms (its policy and fields). - pub op: CommandEncoderOperation, - /// The command buffer's word: its resource ID, whose records lie at - /// `indirect_commands::records_address` of it. - pub command: ValueId, - /// The command's index (`i32`). - pub index: ValueId, - pub fields: Fields, -} - -/// What an operation writes into its command's record. -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum Fields { - /// A buffer's guest address at `binding`, and for a kernel or vertex buffer its attribute - /// stride (`i64`); a fragment, object or mesh buffer has none, nor has AIR 2.5's kernel or - /// vertex setter. - Buffer { - address: Side, - stride: Option, - binding: ValueId, - }, - /// The grid and local size (`<3 x i32>` each), and the action. - Dispatch { grid: ValueId, local: ValueId }, - /// The pipeline state's word. - Pipeline { word: ValueId }, - /// The barrier flag: 1 when `enabled`, else 0. - Barrier { enabled: bool }, - /// A threadgroup length at `binding` (`i32` each). - ThreadgroupLength { length: ValueId, binding: ValueId }, - /// The primitive type (written as Metal's encoding writes it: [`encoded_primitive_type`]), - /// vertex start, vertex count, instance count, and base instance (`i32` each), and the action. - Draw { arguments: [ValueId; 5] }, - /// The stage-in region's origin and size (`<3 x i32>` each). - StageInRegion { origin: ValueId, size: ValueId }, - /// The imageblock's width and height (`<2 x i16>`, each lane held zero-extended in a `u32`). - ImageblockSize { size: ValueId }, - /// The whole record, restored to its default. - Reset, - /// An indexed draw's primitive type (as [`Fields::Draw`]'s), index count, instance count, - /// base vertex and base instance (`i32` each), its `MTLIndexType` (0 for 16-bit indices, 1 - /// for 32-bit ones), the index buffer's guest address, and the action. - IndexedDraw { - arguments: [ValueId; 5], - index_type: u32, - address: Side, - }, - /// A patch draw's control points, patch start, patch count, instance count, base instance - /// and factors' instance stride (`i32` each), its patch index buffer's guest address (0 for - /// null) and its factor buffer's, its factor scale (`float`), and the action; an indexed - /// patch draw's control-point index buffer's guest address too (0 for null). - PatchDraw { - arguments: [ValueId; 6], - patch_indices: Side, - control_point_indices: Option, - factors: Side, - scale: ValueId, - }, - /// The record of command `source_index` (`i32`) of the source command buffer's word - /// `source`. - Copy { - source: ValueId, - source_index: ValueId, - }, - /// A mesh draw's grid, and the threads of an object and of a mesh threadgroup (`<3 x i32>` - /// each), and the action. - MeshDraw { - grid: ValueId, - object: ValueId, - mesh: ValueId, - }, -} - -impl EncodeStrategy { - /// The census name (`access.encode.`) in the finished plan `slots`: a word load - /// qualified by what the object's load reaches ([`super::SideReach`]). - pub fn name(&self, slots: &AccessPlan) -> Cow<'static, str> { - match self { - EncodeStrategy::Word(s) => s.reach(slots).qualify("access.encode.word"), - EncodeStrategy::Command(c) => match c.fields { - Fields::Buffer { .. } => "access.encode.buffer", - Fields::Dispatch { .. } => "access.encode.dispatch", - Fields::Pipeline { .. } => "access.encode.pipeline", - Fields::Barrier { .. } => "access.encode.barrier", - Fields::ThreadgroupLength { .. } => "access.encode.threadgroup_length", - Fields::Draw { .. } => "access.encode.draw", - Fields::StageInRegion { .. } => "access.encode.stage_in_region", - Fields::ImageblockSize { .. } => "access.encode.imageblock_size", - Fields::Reset => "access.encode.reset", - Fields::IndexedDraw { .. } => "access.encode.indexed_draw", - Fields::PatchDraw { - control_point_indices: None, - .. - } => "access.encode.patch_draw", - Fields::PatchDraw { - control_point_indices: Some(_), - .. - } => "access.encode.indexed_patch_draw", - Fields::Copy { .. } => "access.encode.copy", - Fields::MeshDraw { .. } => "access.encode.mesh_draw", - } - .into(), - } - } - - /// An upper estimate of the SPIR-V words one use emits: a word load is a leaf access; an - /// operation is a search call, the record's root entry, three header loads and the policy test, - /// and per field a contained store (a reset's loops: each its one store and the loop's own - /// words, and its counts' header load and each stage's count, `RESET_WORDS`; a copy's: its - /// load and store, the loop's words, and the source's search, header loads and tests, - /// `COPY_WORDS`). - pub fn words(&self) -> u32 { - match self { - EncodeStrategy::Word(s) => s.words(), - EncodeStrategy::Command(c) => { - let fields: u32 = match c.fields { - Fields::Buffer { stride, .. } => 1 + u32::from(stride.is_some()), - Fields::Dispatch { .. } => 7, - Fields::MeshDraw { .. } => 10, - Fields::Draw { .. } | Fields::StageInRegion { .. } => 6, - Fields::IndexedDraw { .. } => 8, - Fields::PatchDraw { - control_point_indices, - .. - } => 11 + u32::from(control_point_indices.is_some()), - Fields::Copy { .. } => 2, - Fields::Pipeline { .. } => 2, - Fields::Barrier { .. } - | Fields::ThreadgroupLength { .. } - | Fields::ImageblockSize { .. } - | Fields::Reset => 1, - }; - let reset = match c.fields { - Fields::Reset => RESET_WORDS, - Fields::Copy { .. } => COPY_WORDS, - _ => 0, - }; - COMMAND_WORDS - .saturating_add(FIELD_WORDS.saturating_mul(fields)) - .saturating_add(reset) - } - } - } -} - -/// SPIR-V words of an operation before its fields: the search call, the root entry, the header -/// loads, the policy test, the written flag's address and store, the fault store, and the -/// selection. -const COMMAND_WORDS: u32 = dynamic::BASE_WORDS + 40 + 4 * FIELD_WORDS + 160; -/// SPIR-V words of one contained field access. -const FIELD_WORDS: u32 = 72; -/// SPIR-V words of a loop over a record's `u64`s beyond its store: the counter, the exit test, the -/// stride test and its select, the loop's blocks, and a compute reset's retained pipeline (its -/// load, and the tests and selects that keep it). -const LOOP_WORDS: u32 = 96 + FIELD_WORDS + 48; -/// SPIR-V words of a reset beyond its store: its loops (the command's words, the words past the -/// bindings, and a render command's four stages' bindings), the counts' header load, and each -/// stage's count (its shift, mask, clamp and bounds). -const RESET_WORDS: u32 = 6 * LOOP_WORDS + FIELD_WORDS + 4 * 40; -/// SPIR-V words of a copy beyond its load and store: the source's search call, root entry, four -/// header loads, and its pipeline and state loads, the descriptor and pipeline tests, and the loop -/// with its kept-state test and selection. -const COPY_WORDS: u32 = dynamic::BASE_WORDS + 24 + 6 * FIELD_WORDS + 156 + LOOP_WORDS + 64; - -/// Whether `class` is an indirect-command object's. -fn object_class(class: HandleClass) -> bool { - matches!( - class, - HandleClass::Command | HandleClass::ComputePipelineState | HandleClass::RenderPipelineState - ) -} - -/// The encoder operation of call `call`, if it is one. -fn encoder(call: &crate::air::ir::Call) -> Option { - match call.callee { - Callee::Air { - op: AirIntrinsic::IndirectCommand(op), - .. - } => Some(op), - _ => None, - } -} - -/// Whether operand `i` of encoder `op` may be an object word of `class`: the command operand, -/// the pipeline operand of a compute or render pipeline setter, or a copy's source command -/// buffer. -fn encoder_operand(op: IndirectCommand, i: usize, class: HandleClass) -> bool { - match (i, class) { - (0, HandleClass::Command) => true, - (2, HandleClass::ComputePipelineState) => op == IndirectCommand::SetComputePipeline, - (2, HandleClass::RenderPipelineState) => op == IndirectCommand::SetRenderPipeline, - (2, HandleClass::Command) => op == IndirectCommand::CopyComputeCommand, - _ => false, - } -} - -/// Plan the function's object words, before any instruction is selected: each handle load of an -/// indirect-command object (`provenance::object_handle_load`) whose every use is an encoder operand -/// of its class (`encoder_operand`). -pub fn plan_objects(cx: &mut SelectCx<'_>, m: &mut Meter) -> Result<(), Error> { - let body = cx.body; - let entry = tree_bytes(1, std::mem::size_of::<(InstId, HandleClass)>()); - let mut words: BTreeMap = BTreeMap::new(); - for (id, inst) in body.insts.iter() { - m.tick(1)?; - let InstKind::Load { - ptr, - volatile: false, - atomic: None, - .. - } = &inst.kind - else { - continue; - }; - let Some(Repr::Handle { class, .. }) = cx.memory.repr(Value::Inst(id)) else { - continue; - }; - if !object_class(class) { - continue; - } - let (Some(roots), Some(range), Some(bytes)) = ( - cx.memory.roots_of(*ptr), - cx.memory.offset(*ptr), - cx.memory.layouts.store_size(inst.ty), - ) else { - continue; - }; - if provenance::object_handle_load(cx.entry, &cx.memory.abi, roots, range, bytes).is_some() { - m.charge(entry)?; - words.insert(id, class); - } - } - if words.is_empty() { - return Ok(()); - } - for (_, inst) in body.insts.iter() { - m.tick(1)?; - match &inst.kind { - InstKind::Call(call) if encoder(call).is_some() => { - let op = encoder(call).ok_or_else(|| cx.invariant("an encoder vanished"))?; - for (i, a) in call.args.iter().enumerate() { - if let Value::Inst(l) = a { - if words.get(l).is_some_and(|c| !encoder_operand(op, i, *c)) { - words.remove(l); - } - } - } - } - kind => kind.for_each_value(|v| { - if let Value::Inst(l) = v { - words.remove(&l); - } - }), - } - } - cx.families.access.objects = words.into_keys().collect::>(); - Ok(()) -} - -/// The lowered representation of an object word ([`plan_objects`]): a `u64`; `None` for any -/// other value. -pub fn lowered_pointer(cx: &SelectCx<'_>, v: Value) -> Option { - match v { - Value::Inst(i) if cx.families.access.objects.contains(&i) => { - Some(DemoteTy::Scalar(ScalarTy::Int { bits: 64 })) - } - _ => None, - } -} - -/// Select the encoder strategy of `inst`: an object word's handle load, or an encoder -/// operation; `None` for any other instruction. -pub fn select( - cx: &mut SelectCx<'_>, - at: InstId, - inst: &Inst, - m: &mut Meter, -) -> Result, Error> { - match &inst.kind { - InstKind::Load { - ptr, - align, - volatile: false, - atomic: None, - .. - } if cx.families.access.objects.contains(&at) => Ok(Some(EncodeStrategy::Word( - dynamic::plan_word(cx, *ptr, inst.ty, *align, m)?, - ))), - InstKind::Call(call) => match encoder(call) { - Some(op) => select_command(cx, op, call).map(|c| Some(EncodeStrategy::Command(c))), - None => Ok(None), - }, - _ => Ok(None), - } -} - -/// The refusal of an encoder operation on a device that cannot run it, or under the identity -/// domains, which lower none yet: an operation reaches its command buffer's records through the -/// resident set's root table and the execution status (`dynamic::plan_search`), which those -/// domains do not push (`Unsupported{GpuEncodedIndirectCommands, NotImplemented}`). -fn needs(cx: &SelectCx<'_>) -> Result<(), Error> { - if super::identity(cx.profile) { - return Err(Unsupported::not_implemented(Feature::GpuEncodedIndirectCommands).into()); - } - let f = cx.profile.fields(); - if f.buffer_access != BufferAccess::Addressed { - return Err(Unsupported::needs_any_of( - Feature::GpuEncodedIndirectCommands, - vec![cx.profile.addressed_needs()], - ) - .into()); - } - let store = match cx.stage { - Stage::Vertex if !f.leaf.vertex_stores_and_atomics => { - Some(VkFeature::VertexPipelineStoresAndAtomics) - } - Stage::Fragment if !f.leaf.fragment_stores_and_atomics => { - Some(VkFeature::FragmentStoresAndAtomics) - } - _ => None, - }; - if let Some(feature) = store { - return Err(Unsupported::needs( - Feature::GpuEncodedIndirectCommands, - Capability::Feature(feature), - ) - .into()); - } - Ok(()) -} - -/// A non-pointer operand: an instruction or parameter value, or a constant the arith family -/// materializes. -fn value(cx: &SelectCx<'_>, v: Value) -> Result { - if matches!(v, Value::Const(_)) && cx.constant(v).is_none() { - return Err(refuse()); - } - cx.values - .id(v) - .ok_or_else(|| cx.invariant("an encoder operand out of the value range")) -} - -fn select_command( - cx: &mut SelectCx<'_>, - op: IndirectCommand, - call: &crate::air::ir::Call, -) -> Result, Error> { - let arg = |i: usize| -> Result { - call.args.get(i).copied().ok_or_else(|| { - Error::Internal(crate::error::InternalError::new( - crate::error::InternalKind::Invariant, - "an encoder operation without its operands", - )) - }) - }; - // The command must be an object word: any other command handle is its family's refusal. - let command = arg(0)?; - if !matches!(command, Value::Inst(i) if cx.families.access.objects.contains(&i)) { - return Err(Unsupported::not_implemented(Feature::ArgumentBufferObjects).into()); - } - needs(cx)?; - dynamic::plan_search(cx)?; - // Each operation in the host contract's terms (its policy), and what it writes. - use CommandEncoderOperation as Op; - let (operation, fields) = match op { - IndirectCommand::SetBuffer { - stage, - space, - strided, - } => { - // A kernel or vertex buffer's setter takes a stride before the binding; a fragment, - // object or mesh buffer's takes none, nor does AIR 2.5's kernel or vertex setter, - // MSL's plain setter, which writes the pipeline's own stride as today's spelling of it - // (an `i64` of all ones) does. - let fields = Fields::Buffer { - address: dynamic::plan_address(cx, arg(2)?)?, - stride: match strided { - true => Some(value(cx, arg(3)?)?), - false => None, - }, - binding: value(cx, arg(if strided { 4 } else { 3 })?)?, - }; - let stage = match stage { - CommandStage::Kernel => BufferStage::Kernel, - CommandStage::Vertex => BufferStage::Vertex, - CommandStage::Fragment => BufferStage::Fragment, - CommandStage::Object => BufferStage::Object, - CommandStage::Mesh => BufferStage::Mesh, - }; - let address_space = if space == AddrSpace::Constant { 2 } else { 1 }; - ( - Op::Buffer { - stage, - address_space, - }, - fields, - ) - } - IndirectCommand::Dispatch { exact_threads } => ( - Op::Dispatch { exact_threads }, - Fields::Dispatch { - grid: value(cx, arg(2)?)?, - local: value(cx, arg(3)?)?, - }, - ), - IndirectCommand::SetComputePipeline | IndirectCommand::SetRenderPipeline => { - let pipeline = arg(2)?; - if !matches!(pipeline, Value::Inst(i) if cx.families.access.objects.contains(&i)) { - return Err(Unsupported::not_implemented(Feature::ArgumentBufferObjects).into()); - } - let word = operand(cx, pipeline)?; - let render = op == IndirectCommand::SetRenderPipeline; - (Op::Pipeline { render }, Fields::Pipeline { word }) - } - IndirectCommand::ComputeBarrier { enabled } => ( - Op::Barrier { - render: false, - enabled, - }, - Fields::Barrier { enabled }, - ), - IndirectCommand::RenderBarrier { enabled } => ( - Op::Barrier { - render: true, - enabled, - }, - Fields::Barrier { enabled }, - ), - IndirectCommand::DrawMesh { threads } => ( - Op::DrawMesh { threads }, - Fields::MeshDraw { - grid: value(cx, arg(2)?)?, - object: value(cx, arg(3)?)?, - mesh: value(cx, arg(4)?)?, - }, - ), - // An object threadgroup's memory length has no place in a render command's record yet: - // the record, its replay and the runtime's execution hold none of it. - IndirectCommand::SetObjectThreadgroupMemoryLength => { - return Err(Unsupported::not_implemented(Feature::GpuEncodedIndirectCommands).into()) - } - IndirectCommand::SetThreadgroupMemoryLength => ( - Op::ThreadgroupMemory, - Fields::ThreadgroupLength { - length: value(cx, arg(2)?)?, - binding: value(cx, arg(3)?)?, - }, - ), - IndirectCommand::DrawPrimitives => ( - Op::Draw, - Fields::Draw { - arguments: [ - value(cx, arg(2)?)?, - value(cx, arg(3)?)?, - value(cx, arg(4)?)?, - value(cx, arg(5)?)?, - value(cx, arg(6)?)?, - ], - }, - ), - IndirectCommand::SetStageInRegion => ( - Op::StageInRegion, - Fields::StageInRegion { - origin: value(cx, arg(2)?)?, - size: value(cx, arg(3)?)?, - }, - ), - IndirectCommand::SetImageblockSize => ( - Op::ImageblockSize, - Fields::ImageblockSize { - size: value(cx, arg(2)?)?, - }, - ), - IndirectCommand::ResetComputeCommand => (Op::Reset { render: false }, Fields::Reset), - IndirectCommand::ResetRenderCommand => (Op::Reset { render: true }, Fields::Reset), - // A render command's fixed-function state (cull mode, depth bias, depth clip mode, - // winding, fill mode, depth/stencil state) has no place in the record: the record, its - // replay and the runtime's execution hold none of it. Metal's Apple10 family alone runs - // these setters; its compiler refuses them on an M4. - IndirectCommand::SetRenderState(_) => { - return Err(Unsupported::not_implemented(Feature::IndirectRenderState).into()) - } - IndirectCommand::DrawPatches { .. } => ( - Op::DrawPatches, - Fields::PatchDraw { - arguments: [ - value(cx, arg(2)?)?, - value(cx, arg(3)?)?, - value(cx, arg(4)?)?, - value(cx, arg(6)?)?, - value(cx, arg(7)?)?, - value(cx, arg(9)?)?, - ], - patch_indices: dynamic::plan_address(cx, arg(5)?)?, - control_point_indices: None, - factors: dynamic::plan_address(cx, arg(8)?)?, - scale: value(cx, arg(10)?)?, - }, - ), - // A patch draw's operands, with the control-point index buffer after the patch indices. - IndirectCommand::DrawIndexedPatches { .. } => ( - Op::DrawIndexedPatches, - Fields::PatchDraw { - arguments: [ - value(cx, arg(2)?)?, - value(cx, arg(3)?)?, - value(cx, arg(4)?)?, - value(cx, arg(7)?)?, - value(cx, arg(8)?)?, - value(cx, arg(10)?)?, - ], - patch_indices: dynamic::plan_address(cx, arg(5)?)?, - control_point_indices: Some(dynamic::plan_address(cx, arg(6)?)?), - factors: dynamic::plan_address(cx, arg(9)?)?, - scale: value(cx, arg(11)?)?, - }, - ), - IndirectCommand::DrawIndexedPrimitives { wide, .. } => ( - Op::DrawIndexed, - Fields::IndexedDraw { - arguments: [ - value(cx, arg(2)?)?, - value(cx, arg(3)?)?, - value(cx, arg(5)?)?, - value(cx, arg(6)?)?, - value(cx, arg(7)?)?, - ], - index_type: u32::from(wide), - address: dynamic::plan_address(cx, arg(4)?)?, - }, - ), - IndirectCommand::CopyComputeCommand => { - // The source command buffer must be an object word too, and its record buffer is - // searched as the command's is. - let source = arg(2)?; - if !matches!(source, Value::Inst(i) if cx.families.access.objects.contains(&i)) { - return Err(Unsupported::not_implemented(Feature::ArgumentBufferObjects).into()); - } - dynamic::plan_search(cx)?; - ( - Op::Copy, - Fields::Copy { - source: operand(cx, source)?, - source_index: value(cx, arg(3)?)?, - }, - ) - } - }; - Ok(Box::new(Command { - op: operation, - command: operand(cx, command)?, - index: value(cx, arg(1)?)?, - fields, - })) -} - -// ---- Emission ---- - -/// A `u32` leaf at a 4-aligned offset. -const WORD: Leaf = Leaf { - form: Form { - held: Held::Int { - bits: 32, - container: 32, - }, - lanes: 1, - }, - bytes: 4, - path: Path::Aligned, -}; - -/// A `u64` leaf at an 8-aligned offset. -const DOUBLE: Leaf = Leaf { - form: Form { - held: Held::Int { - bits: 64, - container: 64, - }, - lanes: 1, - }, - bytes: 8, - path: Path::Aligned, -}; - -fn k32(fb: &mut FunctionBuilder<'_>, v: u32) -> BResult { - crate::memory::leaf::k32(fb, v) -} - -/// A draw's primitive type `operand` (a `u32`) as Metal's encoding writes it into the record: a -/// value past Metal's five (`MTLPrimitiveType`, 0 to 4) as 0, which draws points, as Metal's GPU -/// draws a kernel's draw of one (measured on the M3 Max, macOS 27.0.1: 5 to 12, 15, 16, 31, 63, -/// 255 to 257 and 65535, both draws). Its private types 5 to 9 are the CPU's alone. -fn encoded_primitive_type( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - operand: ValueId, -) -> BResult { - let x = cx.operand(fb, operand)?; - let five = k32(fb, 5)?; - let known = fb.binary(BinOp::ULessThan, x, five)?; - let point = k32(fb, 0)?; - fb.select(known, x, point) -} - -/// The guest address the records of the command buffer whose word (its resource ID, a `u64`) is -/// `word` start at: `indirect_commands::records_address`, the ID shifted up -/// `RECORDS_ADDRESS_SHIFT` bits past `RECORDS_ADDRESS_BASE`. No records start at the null ID's. -fn records(fb: &mut FunctionBuilder<'_>, word: SValue) -> BResult { - let shift = k64(fb, u64::from(RECORDS_ADDRESS_SHIFT))?; - let at = fb.binary(BinOp::ShiftLeftLogical, word, shift)?; - let base = k64(fb, RECORDS_ADDRESS_BASE)?; - fb.binary(BinOp::BitwiseOr, at, base) -} - -/// `x` (a `u32`) as a `u64`. -fn wide(fb: &mut FunctionBuilder<'_>, x: SValue) -> BResult { - let u64_ = fb.module().ty(SType::Int { - width: 64, - signed: false, - })?; - fb.convert(ConvOp::UConvert, x, u64_) -} - -/// `base + index * stride` in `u64`, for `index` a `u32`. -fn indexed(fb: &mut FunctionBuilder<'_>, base: u64, index: SValue, stride: u64) -> BResult { - let i = wide(fb, index)?; - let s = k64(fb, stride)?; - let scaled = fb.binary(BinOp::IMul, i, s)?; - let b = k64(fb, base)?; - fb.binary(BinOp::IAdd, b, scaled) -} - -/// Emit encoder strategy `s`, defining value `vid` (an object word). -pub fn emit( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - vid: ValueId, - s: &EncodeStrategy, -) -> BResult<()> { - match s { - EncodeStrategy::Word(source) => { - let word = dynamic::emit_word(cx, fb, source)?; - cx.define(vid, word); - Ok(()) - } - EncodeStrategy::Command(c) => emit_command(cx, fb, c), - } -} - -/// One field write: its displacement in the record buffer (a `u64`), its value, and its leaf. -type Write = (SValue, SValue, Leaf); - -/// What a copy reads: the source's record buffer, its record's displacement in it (a `u64`), -/// whether the copy is one into a buffer that inherits (a `bool`), which keeps the destination's -/// pipeline and buffer bindings, and whether the destination keeps its pipeline and its state -/// word (a `bool`: into a buffer that inherits, or from a source that reports no pipeline). -#[derive(Clone, Copy)] -struct CopyFrom { - base: dynamic::WideBase, - record: SValue, - into_inheriting: SValue, - keeps_pipeline: SValue, -} - -fn emit_command<'c>(cx: &mut EmitCx<'c>, fb: &mut FunctionBuilder<'_>, c: &Command) -> BResult<()> { - let Policy { - required, - forbidden, - any, - binding, - dynamic_stride, - dropped_on, - } = c.op.policy(); - let word = cx.operand(fb, c.command)?; - let at = records(fb, word)?; - let p = dynamic::search_start(cx, fb, at)?; - let b = dynamic::plain_base(cx, fb, p)?; - let capacity = header(cx, fb, b, layout::CAPACITY)?; - let policy = header(cx, fb, b, layout::POLICY)?; - let index = cx.operand(fb, c.index)?; - let mut valid = fb.binary(BinOp::ULessThan, index, capacity)?; - let mask = k32(fb, required | forbidden)?; - let bits = fb.binary(BinOp::BitwiseAnd, policy, mask)?; - let want = k32(fb, required)?; - let allowed = fb.binary(BinOp::IEqual, bits, want)?; - valid = fb.binary(BinOp::LogicalAnd, valid, allowed)?; - // A draw needs one of the kinds whose records hold it; on a buffer of `dropped_on` kinds - // that holds none, an otherwise valid draw is dropped without a fault. - let mut dropped = None; - if any != 0 { - let kinds = k32(fb, any)?; - let held = fb.binary(BinOp::BitwiseAnd, policy, kinds)?; - let zero = k32(fb, 0)?; - let holds = fb.binary(BinOp::INotEqual, held, zero)?; - if dropped_on != 0 { - let others = k32(fb, dropped_on)?; - let other = fb.binary(BinOp::BitwiseAnd, policy, others)?; - let other = fb.binary(BinOp::INotEqual, other, zero)?; - let lacks = fb.unary(UnOp::LogicalNot, holds)?; - let drop = fb.binary(BinOp::LogicalAnd, lacks, other)?; - dropped = Some(fb.binary(BinOp::LogicalAnd, valid, drop)?); - } - valid = fb.binary(BinOp::LogicalAnd, valid, holds)?; - } - let record = indexed(fb, layout::RECORDS, index, layout::RECORD)?; - let at = |fb: &mut FunctionBuilder<'_>, field: SValue| fb.binary(BinOp::IAdd, record, field); - let fixed = |fb: &mut FunctionBuilder<'_>, field: u64| -> BResult { - let f = k64(fb, field)?; - at(fb, f) - }; - let mut writes: Vec = Vec::new(); - let mut reset = None; - let mut copy = None; - match &c.fields { - Fields::Buffer { - address, - stride, - binding: slot, - } => { - let CommandEncoderOperation::Buffer { stage, .. } = c.op else { - return Err(cx.fail("a buffer setter of another operation")); - }; - let slot = cx.operand(fb, *slot)?; - let field = indexed(fb, layout::buffers(stage), slot, layout::BINDING)?; - let field = at(fb, field)?; - let address = dynamic::address_of(cx, fb, *address)?; - writes.push((field, address, DOUBLE)); - let eight = k64(fb, layout::STRIDE)?; - let to = fb.binary(BinOp::IAdd, field, eight)?; - match stride { - // The plain form writes the pipeline's stride, all ones, over a stride set - // before too, as Metal's kernel-side setter does. - None => { - let all = k64(fb, u64::MAX)?; - writes.push((to, all, DOUBLE)); - } - Some(stride) => { - let stride = cx.operand(fb, *stride)?; - writes.push((to, stride, DOUBLE)); - if dynamic_stride { - let dynamic = k32(fb, DYNAMIC_STRIDE)?; - let enabled = fb.binary(BinOp::BitwiseAnd, policy, dynamic)?; - let zero = k32(fb, 0)?; - let enabled = fb.binary(BinOp::INotEqual, enabled, zero)?; - let all = k64(fb, u64::MAX)?; - let fixed_stride = fb.binary(BinOp::IEqual, stride, all)?; - let ok = fb.binary(BinOp::LogicalOr, enabled, fixed_stride)?; - valid = fb.binary(BinOp::LogicalAnd, valid, ok)?; - } - } - } - valid = bound(cx, fb, b, valid, binding, slot)?; - } - Fields::Dispatch { grid, local } => { - let exact = matches!( - c.op, - CommandEncoderOperation::Dispatch { - exact_threads: true - } - ); - for (vector, first) in [(grid, 0u64), (local, 3)] { - let v = cx.operand(fb, *vector)?; - for component in 0..3u32 { - let x = fb.composite_extract(v, &[component])?; - let to = fixed(fb, layout::ARGUMENTS + 4 * (first + u64::from(component)))?; - writes.push((to, x, WORD)); - } - } - let to = fixed(fb, layout::ACTION)?; - let tag = k32(fb, if exact { 2 } else { 1 })?; - writes.push((to, tag, WORD)); - } - Fields::Pipeline { word } => { - let w = cx.operand(fb, *word)?; - let to = fixed(fb, layout::PIPELINE)?; - writes.push((to, w, DOUBLE)); - // A set pipeline is reported, it replaces one a reset retained, and the kernel wrote - // it (`layout::KERNEL_PIPELINE`), where it names one: the state word flags no word - // that holds none. - let to = fixed(fb, layout::STATE)?; - let none = k64(fb, 0)?; - let named = fb.binary(BinOp::INotEqual, w, none)?; - let kernel = k32(fb, layout::KERNEL_PIPELINE)?; - let unflagged = k32(fb, 0)?; - let state = fb.select(named, kernel, unflagged)?; - writes.push((to, state, WORD)); - } - Fields::Barrier { enabled } => { - let to = fixed(fb, layout::BARRIER)?; - let flag = k32(fb, u32::from(*enabled))?; - writes.push((to, flag, WORD)); - } - Fields::ThreadgroupLength { - length: n, - binding: slot, - } => { - let n = cx.operand(fb, *n)?; - let slot = cx.operand(fb, *slot)?; - let field = indexed(fb, layout::THREADGROUP, slot, 4)?; - let to = at(fb, field)?; - writes.push((to, n, WORD)); - valid = bound(cx, fb, b, valid, binding, slot)?; - } - Fields::Draw { arguments } => { - for (i, a) in arguments.iter().enumerate() { - let x = match i { - 0 => encoded_primitive_type(cx, fb, *a)?, - _ => cx.operand(fb, *a)?, - }; - let to = fixed(fb, layout::ARGUMENTS + 4 * i as u64)?; - writes.push((to, x, WORD)); - } - let to = fixed(fb, layout::ACTION)?; - let tag = k32(fb, 3)?; - writes.push((to, tag, WORD)); - } - Fields::MeshDraw { grid, object, mesh } => { - // The grid, then the object and the mesh threadgroups' threads, three words each - // (`indirect_commands::layout::DRAW_ARGUMENT_WORDS`); the action is 7 for a draw of - // threadgroups, 8 for one of threads. - for (vector, first) in [(grid, 0u64), (object, 3), (mesh, 6)] { - let v = cx.operand(fb, *vector)?; - for component in 0..3u32 { - let x = fb.composite_extract(v, &[component])?; - let to = fixed(fb, layout::ARGUMENTS + 4 * (first + u64::from(component)))?; - writes.push((to, x, WORD)); - } - } - let threads = matches!(c.op, CommandEncoderOperation::DrawMesh { threads: true }); - let to = fixed(fb, layout::ACTION)?; - let tag = k32(fb, if threads { 8 } else { 7 })?; - writes.push((to, tag, WORD)); - } - Fields::StageInRegion { origin, size } => { - for (vector, first) in [(origin, 0u64), (size, 3)] { - let v = cx.operand(fb, *vector)?; - for component in 0..3u32 { - let x = fb.composite_extract(v, &[component])?; - let to = fixed(fb, layout::STAGE_IN + 4 * (first + u64::from(component)))?; - writes.push((to, x, WORD)); - } - } - } - Fields::ImageblockSize { size } => { - // Each lane is held zero-extended in a `u32`: the width is the low half of the word. - let v = cx.operand(fb, *size)?; - let width = fb.composite_extract(v, &[0])?; - let height = fb.composite_extract(v, &[1])?; - let sixteen = k32(fb, 16)?; - let height = fb.binary(BinOp::ShiftLeftLogical, height, sixteen)?; - let word = fb.binary(BinOp::BitwiseOr, width, height)?; - let to = fixed(fb, layout::IMAGEBLOCK)?; - writes.push((to, word, WORD)); - } - Fields::Reset => { - // A compute command's reset keeps the pipeline it executes with, reported cleared; a - // render command's is unmeasured and clears it. - let retain = matches!(c.op, CommandEncoderOperation::Reset { render: false }); - let render = matches!(c.op, CommandEncoderOperation::Reset { render: true }); - // The bindings it clears are those the descriptor counts (`default_record`). - let counts = header(cx, fb, b, layout::COUNTS)?; - reset = Some((record, retain, render, counts)); - } - Fields::Copy { - source, - source_index, - } => { - let word = cx.operand(fb, *source)?; - let at = records(fb, word)?; - let p = dynamic::search_start(cx, fb, at)?; - let base = dynamic::plain_base(cx, fb, p)?; - let source_capacity = header(cx, fb, base, layout::CAPACITY)?; - let source_policy = header(cx, fb, base, layout::POLICY)?; - let source_counts = header(cx, fb, base, layout::COUNTS)?; - let counts = header(cx, fb, b, layout::COUNTS)?; - let source_index = cx.operand(fb, *source_index)?; - let present = fb.binary(BinOp::ULessThan, source_index, source_capacity)?; - valid = fb.binary(BinOp::LogicalAnd, valid, present)?; - // Equal descriptors: the same policy bits and binding counts. - let same_policy = fb.binary(BinOp::IEqual, source_policy, policy)?; - let same_counts = fb.binary(BinOp::IEqual, source_counts, counts)?; - let equal = fb.binary(BinOp::LogicalAnd, same_policy, same_counts)?; - // Into a buffer that inherits both from one that inherits neither, of the same - // descriptor otherwise, the destination binding no kernel buffer (count byte 0), at - // an index other than 0: Metal's copy onto an inheriting buffer's command 0 runs it - // with `threads_per_grid` and `threadgroups_per_grid` zero (M3 Max and M4), which the - // destination's documented semantics do not explain. - let zero = k32(fb, 0)?; - let inherits = k32(fb, INHERIT_PIPELINE | INHERIT_BUFFERS)?; - let source_inherits = fb.binary(BinOp::BitwiseAnd, source_policy, inherits)?; - let owned = fb.binary(BinOp::IEqual, source_inherits, zero)?; - let inheriting = fb.binary(BinOp::BitwiseOr, source_policy, inherits)?; - let inheriting = fb.binary(BinOp::IEqual, policy, inheriting)?; - let kernel = k32(fb, 0xff)?; - let kernel_buffers = fb.binary(BinOp::BitwiseAnd, counts, kernel)?; - let no_kernel_buffers = fb.binary(BinOp::IEqual, kernel_buffers, zero)?; - let others = k32(fb, !0xff)?; - let other_counts = fb.binary(BinOp::BitwiseAnd, counts, others)?; - let source_others = fb.binary(BinOp::BitwiseAnd, source_counts, others)?; - let same_others = fb.binary(BinOp::IEqual, other_counts, source_others)?; - let not_first = fb.binary(BinOp::INotEqual, index, zero)?; - let mut into_inheriting = fb.binary(BinOp::LogicalAnd, owned, inheriting)?; - for test in [no_kernel_buffers, same_others, not_first] { - into_inheriting = fb.binary(BinOp::LogicalAnd, into_inheriting, test)?; - } - let explained = fb.binary(BinOp::LogicalOr, equal, into_inheriting)?; - valid = fb.binary(BinOp::LogicalAnd, valid, explained)?; - // A source that reports no pipeline (none set, or one its reset retained) leaves the - // destination's pipeline and its state word as they are. - let source_record = indexed(fb, layout::RECORDS, source_index, layout::RECORD)?; - let field = k64(fb, layout::PIPELINE)?; - let at = fb.binary(BinOp::IAdd, source_record, field)?; - let Some(token) = dynamic::wide_at(fb, base, Some(at), &DOUBLE, None)? else { - return Err(cx.fail("a copied pipeline load without a value")); - }; - let field = k64(fb, layout::STATE)?; - let at = fb.binary(BinOp::IAdd, source_record, field)?; - let Some(state) = dynamic::wide_at(fb, base, Some(at), &WORD, None)? else { - return Err(cx.fail("a copied state load without a value")); - }; - let none = k64(fb, 0)?; - let named = fb.binary(BinOp::INotEqual, token, none)?; - // Retained, it is unreported; a kernel's write of it is reported, and copied with its - // state word (`layout::KERNEL_PIPELINE`). - let retained = k32(fb, layout::RETAINED)?; - let retained = fb.binary(BinOp::BitwiseAnd, state, retained)?; - let unreported = fb.binary(BinOp::INotEqual, retained, zero)?; - let unreported = fb.unary(UnOp::LogicalNot, unreported)?; - let reports = fb.binary(BinOp::LogicalAnd, named, unreported)?; - let reports = fb.unary(UnOp::LogicalNot, reports)?; - let keeps_pipeline = fb.binary(BinOp::LogicalOr, into_inheriting, reports)?; - copy = Some(CopyFrom { - base, - record: source_record, - into_inheriting, - keeps_pipeline, - }); - } - Fields::IndexedDraw { - arguments: [primitive_type, count, instances, base_vertex, base_instance], - index_type, - address, - } => { - // Primitive type, index count, index type, instances, the address (a `u64` over two - // words), base vertex, base instance (`indirect_commands::layout::DRAW_ARGUMENT_WORDS`). - let operands = [ - (0, *primitive_type), - (1, *count), - (3, *instances), - (6, *base_vertex), - (7, *base_instance), - ]; - for (word, operand) in operands { - let x = match word { - 0 => encoded_primitive_type(cx, fb, operand)?, - _ => cx.operand(fb, operand)?, - }; - let to = fixed(fb, layout::ARGUMENTS + 4 * word)?; - writes.push((to, x, WORD)); - } - let index_type = k32(fb, *index_type)?; - let to = fixed(fb, layout::ARGUMENTS + 8)?; - writes.push((to, index_type, WORD)); - let address = dynamic::address_of(cx, fb, *address)?; - let to = fixed(fb, layout::ARGUMENTS + 16)?; - writes.push((to, address, DOUBLE)); - let to = fixed(fb, layout::ACTION)?; - let tag = k32(fb, 4)?; - writes.push((to, tag, WORD)); - } - Fields::PatchDraw { - arguments: [control_points, start, count, instances, base_instance, stride], - patch_indices, - control_point_indices, - factors, - scale, - } => { - // Control points, patch start, patch count, instances, the patch index buffer's and - // the factor buffer's addresses (a `u64` over two words each), base instance, the - // factors' instance stride, the factor scale - // (`indirect_commands::layout::DRAW_ARGUMENT_WORDS`). - let operands = [ - (0, *control_points), - (1, *start), - (2, *count), - (3, *instances), - (8, *base_instance), - (9, *stride), - ]; - for (word, operand) in operands { - let x = cx.operand(fb, operand)?; - let to = fixed(fb, layout::ARGUMENTS + 4 * word)?; - writes.push((to, x, WORD)); - } - for (side, word) in [(patch_indices, 4), (factors, 6)] { - let address = dynamic::address_of(cx, fb, *side)?; - let to = fixed(fb, layout::ARGUMENTS + 4 * word)?; - writes.push((to, address, DOUBLE)); - } - // The factor scale's `f32` bits. - let scale = cx.operand(fb, *scale)?; - let u32_ = fb.module().ty(SType::Int { - width: 32, - signed: false, - })?; - let bits = fb.convert(ConvOp::Bitcast, scale, u32_)?; - let to = fixed(fb, layout::ARGUMENTS + 40)?; - writes.push((to, bits, WORD)); - // An indexed patch draw's control-point index buffer takes the first two threadgroup - // lengths' words (`indirect_commands::layout::CONTROL_POINT_INDICES`), and its action - // is 6; a patch draw's is 5. - let tag = match control_point_indices { - Some(side) => { - let address = dynamic::address_of(cx, fb, *side)?; - let to = fixed(fb, layout::CONTROL_POINT_INDICES)?; - writes.push((to, address, DOUBLE)); - 6 - } - None => 5, - }; - let to = fixed(fb, layout::ACTION)?; - let tag = k32(fb, tag)?; - writes.push((to, tag, WORD)); - } - } - // The command's written flag past every record (`indirect_commands::written_flag_offset`), - // set with its record. - let past = indexed(fb, layout::RECORDS, capacity, layout::RECORD)?; - let flag = indexed(fb, 0, index, WRITTEN_FLAG_BYTES as u64)?; - let flag = fb.binary(BinOp::IAdd, past, flag)?; - let one = k32(fb, 1)?; - writes.push((flag, one, WORD)); - let fault_at = k64(fb, layout::FAULT)?; - let fault = dynamic::word_place(fb, b, fault_at)?; - let write: ArmFn<'_, EmitCx<'c>> = Box::new(move |fb, cx| { - for (to, v, leaf) in writes { - dynamic::wide_at(fb, b, Some(to), &leaf, Some(v))?; - } - if let Some((record, retain, render, counts)) = reset { - default_record(cx, fb, b, (record, retain), (render, counts))?; - } - if let Some(from) = copy { - copy_record(cx, fb, b, record, from)?; - } - Ok(ArmEnd::FallThrough(Vec::new())) - }); - let faulted: ArmFn<'_, EmitCx<'c>> = Box::new(move |fb, cx| { - match dropped { - // A dropped draw sets no fault. - Some(dropped) => { - let faults = fb.unary(UnOp::LogicalNot, dropped)?; - let store: ArmFn<'_, EmitCx<'c>> = Box::new(move |fb, _| { - fb.atomic_store(fault, Scope::Device, Semantics::RELAXED, one)?; - Ok(ArmEnd::FallThrough(Vec::new())) - }); - fb.if_(cx, faults, store, None)?; - } - None => fb.atomic_store(fault, Scope::Device, Semantics::RELAXED, one)?, - } - Ok(ArmEnd::FallThrough(Vec::new())) - }); - fb.if_(cx, valid, write, Some(faulted))?; - Ok(()) -} - -/// The bindings' `u64`s of a record, from the first binding's address to past the last one's -/// stride. -const FIRST_BINDING: u32 = (layout::buffers(BufferStage::Kernel) / 8) as u32; -const PAST_BINDINGS: u32 = FIRST_BINDING + (layout::ALL_BINDINGS * layout::BINDING / 8) as u32; -/// The `u64`s of one binding: its address and its stride. -const BINDING_DOUBLES: u32 = (layout::BINDING / 8) as u32; -/// The record's pipeline `u64`, and the one its state word lies alone in. -const PIPELINE_DOUBLE: u32 = (layout::PIPELINE / 8) as u32; -const STATE_DOUBLE: u32 = (layout::STATE / 8) as u32; - -/// The `u64`s of a record. -const DOUBLES: u32 = (layout::RECORD / 8) as u32; - -/// Emit `each` for every `u64` of a record, its index `j` (a `u32`) counted in a loop. -fn each_double<'c, F>(cx: &mut EmitCx<'c>, fb: &mut FunctionBuilder<'_>, each: F) -> BResult<()> -where - F: FnOnce(&mut EmitCx<'c>, &mut FunctionBuilder<'_>, SValue) -> BResult<()>, -{ - let from = k32(fb, 0)?; - let to = k32(fb, DOUBLES)?; - each_double_in(cx, fb, (from, to), each) -} - -/// Emit `each` for the `u64`s of a record from index `from` to `to` (each a `u32`), its index `j` -/// counted in a loop. -fn each_double_in<'c, F>( - cx: &mut EmitCx<'c>, - fb: &mut FunctionBuilder<'_>, - (from, to): (SValue, SValue), - each: F, -) -> BResult<()> -where - F: FnOnce(&mut EmitCx<'c>, &mut FunctionBuilder<'_>, SValue) -> BResult<()>, -{ - let u32_ = fb.module().ty(SType::Int { - width: 32, - signed: false, - })?; - let zero = fb.module().constant(Constant::Scalar { - ty: u32_, - bits: ConstBits(0), - })?; - let var = fb.local_var(u32_, Some(zero))?; - let counter = fb.var_ptr(var)?; - // The variable is initialized once, at the function's entry: a loop over a record in a loop - // starts over. - fb.store(counter, from, MemAccess::default())?; - let body: LoopFn<'_, EmitCx<'c>> = Box::new(move |fb, cx, lc| { - let j = fb.load(counter, MemAccess::default())?; - let done = fb.binary(BinOp::UGreaterThanEqual, j, to)?; - let exit: ArmFn<'_, EmitCx<'c>> = Box::new(move |fb, _| { - lc.break_(fb)?; - Ok(ArmEnd::Exits) - }); - fb.if_(cx, done, exit, None)?; - let one = k32(fb, 1)?; - let next = fb.binary(BinOp::IAdd, j, one)?; - fb.store(counter, next, MemAccess::default())?; - each(cx, fb, j) - }); - fb.loop_(cx, LoopSpec::default(), body) -} - -/// Write the default record (`CommandRecord::default`'s encoding) at displacement `record` of the -/// record buffer `b`: zero in every `u64` of the record that a command may have set, a buffer -/// binding's address and stride too, as Metal's reset clears them, in loops: the command's words, -/// the bindings below each stage's count in the header's packed `counts` (`layout::COUNTS`: of a -/// `render` command's mesh, vertex, fragment and object stages, bytes 3, 1, 2 and 0; of a compute -/// command's kernel buffers, byte 0), and the words past the bindings (the threadgroup lengths, an -/// indexed patch draw's control-point indices, the imageblock size and the state word). A binding -/// past its stage's count is zero already, and is not written: the storage is made zero, an -/// encoder's write past the count faults and writes nothing, the CPU's setter refuses one, a -/// compute command has no other stage's setter, and a copy takes a source of the same descriptor. -/// So a reset writes the record's 64-byte head, 136-byte tail and 16 bytes a counted binding, -/// where it wrote all 2248 bytes. Where `retain`, a compute command's reset, the pipeline word -/// keeps the pipeline the command executes with, and the state word flags it retained when there -/// is one (`layout::RETAINED`), and keeps its flag of a kernel's write of it -/// (`layout::KERNEL_PIPELINE`): the retained pipeline is the one that write resolved, as the one -/// the command executes with on Metal. -fn default_record( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - b: dynamic::WideBase, - (record, retain): (SValue, bool), - (render, counts): (bool, SValue), -) -> BResult<()> { - let retained = if retain { - let field = k64(fb, layout::PIPELINE)?; - let at = fb.binary(BinOp::IAdd, record, field)?; - let Some(token) = dynamic::wide_at(fb, b, Some(at), &DOUBLE, None)? else { - return Err(cx.fail("a reset's pipeline load without a value")); - }; - let none = k64(fb, 0)?; - let named = fb.binary(BinOp::INotEqual, token, none)?; - // The state word lies alone in its `u64`, its bits in the low word. - let field = k64(fb, layout::STATE)?; - let at = fb.binary(BinOp::IAdd, record, field)?; - let Some(held) = dynamic::wide_at(fb, b, Some(at), &DOUBLE, None)? else { - return Err(cx.fail("a reset's state word load without a value")); - }; - let kernel = k64(fb, u64::from(layout::KERNEL_PIPELINE))?; - let kernel = fb.binary(BinOp::BitwiseAnd, held, kernel)?; - let flag = k64(fb, u64::from(layout::RETAINED))?; - let flag = fb.binary(BinOp::BitwiseOr, flag, kernel)?; - let state = fb.select(named, flag, none)?; - Some((token, state)) - } else { - None - }; - let clear = move |fb: &mut FunctionBuilder<'_>, j: SValue| -> BResult<()> { - let mut v = k64(fb, 0)?; - if let Some((token, state)) = retained { - let pipeline = k32(fb, PIPELINE_DOUBLE)?; - let pipeline = fb.binary(BinOp::IEqual, j, pipeline)?; - v = fb.select(pipeline, token, v)?; - let flags = k32(fb, STATE_DOUBLE)?; - let flags = fb.binary(BinOp::IEqual, j, flags)?; - v = fb.select(flags, state, v)?; - } - let to = indexed(fb, 0, j, 8)?; - let to = fb.binary(BinOp::IAdd, record, to)?; - dynamic::wide_at(fb, b, Some(to), &DOUBLE, Some(v))?; - Ok(()) - }; - // The command's words, then the words past the bindings. - for (from, to) in [(0, FIRST_BINDING), (PAST_BINDINGS, DOUBLES)] { - let from = k32(fb, from)?; - let to = k32(fb, to)?; - each_double_in(cx, fb, (from, to), move |_, fb, j| clear(fb, j))?; - } - // Each stage's bindings below its count (at most `BINDING_COUNT`), two `u64`s a binding. - let stages: &[(u32, u32)] = match render { - true => &[(0, 3), (1, 1), (2, 2), (3, 0)], - false => &[(0, 0)], - }; - for &(stage, byte) in stages { - let shift = k32(fb, 8 * byte)?; - let count = fb.binary(BinOp::ShiftRightLogical, counts, shift)?; - let mask = k32(fb, 0xff)?; - let count = fb.binary(BinOp::BitwiseAnd, count, mask)?; - let most = k32(fb, BINDING_COUNT as u32)?; - let over = fb.binary(BinOp::UGreaterThan, count, most)?; - let count = fb.select(over, most, count)?; - let per = k32(fb, BINDING_DOUBLES)?; - let doubles = fb.binary(BinOp::IMul, count, per)?; - let first = FIRST_BINDING + stage * BINDING_COUNT as u32 * BINDING_DOUBLES; - let from = k32(fb, first)?; - let to = fb.binary(BinOp::IAdd, from, doubles)?; - each_double_in(cx, fb, (from, to), move |_, fb, j| clear(fb, j))?; - } - Ok(()) -} - -/// Copy the source's record `from` onto the record at displacement `record` of the record buffer -/// `b`, `u64` by `u64` in a loop: every one but those the destination keeps: its pipeline's and -/// its state word's where `from.keeps_pipeline`, and its buffer bindings' for a copy into a buffer -/// that inherits. -fn copy_record<'c>( - cx: &mut EmitCx<'c>, - fb: &mut FunctionBuilder<'_>, - b: dynamic::WideBase, - record: SValue, - from: CopyFrom, -) -> BResult<()> { - each_double(cx, fb, move |cx, fb, j| { - let pipeline = k32(fb, PIPELINE_DOUBLE)?; - let pipeline = fb.binary(BinOp::IEqual, j, pipeline)?; - let flags = k32(fb, STATE_DOUBLE)?; - let flags = fb.binary(BinOp::IEqual, j, flags)?; - let pipeline = fb.binary(BinOp::LogicalOr, pipeline, flags)?; - let pipeline = fb.binary(BinOp::LogicalAnd, from.keeps_pipeline, pipeline)?; - let first = k32(fb, FIRST_BINDING)?; - let past = k32(fb, PAST_BINDINGS)?; - let after = fb.binary(BinOp::UGreaterThanEqual, j, first)?; - let below = fb.binary(BinOp::ULessThan, j, past)?; - let binding = fb.binary(BinOp::LogicalAnd, after, below)?; - let binding = fb.binary(BinOp::LogicalAnd, from.into_inheriting, binding)?; - let kept = fb.binary(BinOp::LogicalOr, pipeline, binding)?; - let taken = fb.unary(UnOp::LogicalNot, kept)?; - let d = indexed(fb, 0, j, 8)?; - let take: ArmFn<'_, EmitCx<'c>> = Box::new(move |fb, cx| { - let at = fb.binary(BinOp::IAdd, from.record, d)?; - let Some(v) = dynamic::wide_at(fb, from.base, Some(at), &DOUBLE, None)? else { - return Err(cx.fail("a copied record load without a value")); - }; - let to = fb.binary(BinOp::IAdd, record, d)?; - dynamic::wide_at(fb, b, Some(to), &DOUBLE, Some(v))?; - Ok(ArmEnd::FallThrough(Vec::new())) - }); - fb.if_(cx, taken, take, None)?; - Ok(()) - }) -} - -/// The header's `u32` at byte `at` of the record buffer `b`. -fn header( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - b: dynamic::WideBase, - at: u64, -) -> BResult { - let d = k64(fb, at)?; - match dynamic::wide_at(fb, b, Some(d), &WORD, None)? { - Some(v) => Ok(v), - None => Err(cx.fail("a record header load without a value")), - } -} - -/// `valid` and, when the operation's binding is bounded by a count, `slot` below it: byte -/// `count` of the header's packed counts. -fn bound( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - b: dynamic::WideBase, - valid: SValue, - count: Option, - slot: SValue, -) -> BResult { - let Some(n) = count else { - return Ok(valid); - }; - let counts = header(cx, fb, b, layout::COUNTS)?; - let shift = k32(fb, u32::from(n) * 8)?; - let shifted = fb.binary(BinOp::ShiftRightLogical, counts, shift)?; - let byte = k32(fb, 255)?; - let limit = fb.binary(BinOp::BitwiseAnd, shifted, byte)?; - let ok = fb.binary(BinOp::ULessThan, slot, limit)?; - fb.binary(BinOp::LogicalAnd, valid, ok) -} diff --git a/crates/metal2vulkan/src/lower/access/icb.rs b/crates/metal2vulkan/src/lower/access/icb.rs index f6750091c..ce66ac250 100644 --- a/crates/metal2vulkan/src/lower/access/icb.rs +++ b/crates/metal2vulkan/src/lower/access/icb.rs @@ -1,7 +1,7 @@ //! GPU-encoded indexed draws under the identity domains: a function's `render_command` buffer //! setters, indexed draw and reset write the records of an indirect command buffer //! (`pipeline::IndirectDrawLayout`) through its `gpuResourceID`, the records' device address, -//! which an argument buffer's `command_buffer` member holds (its handle load is `encode`'s object +//! which an argument buffer's `command_buffer` member holds (its handle load is `object`'s //! word, a `u64`). //! //! Each operation reads the header's capacity, slot counts and stride, and writes only where the diff --git a/crates/metal2vulkan/src/lower/access/mod.rs b/crates/metal2vulkan/src/lower/access/mod.rs index 601bb3502..8cdfd3d59 100644 --- a/crates/metal2vulkan/src/lower/access/mod.rs +++ b/crates/metal2vulkan/src/lower/access/mod.rs @@ -101,13 +101,13 @@ pub mod cell; pub mod copy; pub mod dynamic; mod emit; -pub mod encode; pub mod function_table; pub mod handle; pub mod icb; pub mod imageblock; pub mod index; pub mod local; +pub mod object; pub(crate) mod phis; pub mod pointer; pub(crate) mod psb; @@ -189,8 +189,8 @@ pub enum AccessStrategy { Cell(cell::CellStrategy), /// A kernel imageblock's cell pointer or extent. Imageblock(imageblock::ImageblockStrategy), - /// An indirect-command object's word, or an encoder operation's record writes. - Encode(encode::EncodeStrategy), + /// An indirect-command object's word. + Object(object::ObjectWord), /// An indirect-command operation's writes into its command's records under the identity /// domains. Commands(icb::Command), @@ -540,7 +540,7 @@ impl FamilyStrategy for AccessStrategy { AccessStrategy::Value(p) => p.name(slots), AccessStrategy::Cell(c) => c.name().into(), AccessStrategy::Imageblock(i) => i.name().into(), - AccessStrategy::Encode(e) => e.name(slots), + AccessStrategy::Object(o) => o.name(slots), AccessStrategy::Commands(c) => c.name(), AccessStrategy::FunctionTable(t) => t.name(), AccessStrategy::AbsentRead(a) => a.name().into(), @@ -565,7 +565,7 @@ impl FamilyStrategy for AccessStrategy { AccessStrategy::Value(p) => p.words(), AccessStrategy::Cell(c) => c.words(), AccessStrategy::Imageblock(i) => i.words(), - AccessStrategy::Encode(e) => e.words(), + AccessStrategy::Object(o) => o.words(), AccessStrategy::Commands(c) => c.words(), AccessStrategy::FunctionTable(t) => t.words(), AccessStrategy::AbsentRead(a) => a.words(), @@ -634,7 +634,7 @@ fn held(s: &root_sets::Statics, m: &mut Meter) -> Result, Error> { /// materializes (`pointer::phi_incoming`); any other constant incoming pointer, and a blob offset /// (which would need a conversion on its edge), is refused. pub fn lowered_pointer(cx: &SelectCx<'_>, v: Value) -> Result { - if let Some(d) = encode::lowered_pointer(cx, v) { + if let Some(d) = object::lowered_pointer(cx, v) { return Ok(d); } if let Some(d) = handle::lowered_pointer(cx, v)? { @@ -789,7 +789,7 @@ pub struct AccessPlan { /// A tile function's attachments and the ones it stages ([`tile`]). pub tile: Option, /// The handle loads of indirect-command objects whose every use is an encoder operand - /// ([`encode::plan_objects`]): each is its field's word, a `u64`. + /// ([`object::plan_objects`]): each is its field's word, a `u64`. pub objects: BTreeSet, /// The typed loads and stores whose access chain takes its defining `getelementptr`'s own /// index operands ([`local`]'s line-up rule), each with those operands: the access reads them @@ -2494,12 +2494,12 @@ pub fn select( return Ok(AccessStrategy::Imageblock(s)); } // Under the identity domains an indirect-command operation is `icb`'s; its object word's - // handle load stays `encode`'s. + // handle load stays `object`'s. if let Some(c) = icb::select(cx, inst, m)? { return Ok(AccessStrategy::Commands(c)); } - if let Some(s) = encode::select(cx, at, inst, m)? { - return Ok(AccessStrategy::Encode(s)); + if let Some(s) = object::select(cx, at, inst, m)? { + return Ok(AccessStrategy::Object(s)); } if let Some(s) = cell::select(cx, at, inst)? { return Ok(AccessStrategy::Cell(s)); diff --git a/crates/metal2vulkan/src/lower/access/object.rs b/crates/metal2vulkan/src/lower/access/object.rs new file mode 100644 index 000000000..5223fc9d6 --- /dev/null +++ b/crates/metal2vulkan/src/lower/access/object.rs @@ -0,0 +1,199 @@ +//! Indirect-command objects: an argument buffer's command-buffer or pipeline-state member, and the +//! encoder operations that take one. +//! +//! **Object words.** An object's handle load (`memory::provenance::object_handle_load`) reads the +//! member's field, 8 bytes, as data ([`ObjectWord`], a `u64`): a command buffer's word is its +//! resource ID, Metal's `gpuResourceID`; a pipeline state's word is the template's token. A handle +//! load is admitted only when every use of its value is an encoder operand of its class +//! ([`plan_objects`]): the command operand of an encoder operation, the pipeline operand of +//! `air.set_pipeline_state_{compute,render}_command`, or a copy's source command buffer. Any other +//! use (an integer, a compare, a store, a merge) leaves the load refused +//! (`ArgumentBufferObjects`, `pointer::select`), so no other instruction observes the word. +//! +//! **Encoder operations** ([`select`]). This module lowers none. Under the identity domains the +//! operations `icb` lowers (a render command's buffer setters, its indexed triangle draw and a +//! reset) are selected there, before this module; every other encoder operation, and every one +//! under the resident-table domains, is `Unsupported{GpuEncodedIndirectCommands, NotImplemented}`, +//! and one whose command is not an object word is `Unsupported{ArgumentBufferObjects, +//! NotImplemented}`. + +use std::borrow::Cow; +use std::collections::{BTreeMap, BTreeSet}; + +use crate::air::intrinsics::{AirIntrinsic, IndirectCommand}; +use crate::air::ir::{Callee, Inst, InstId, InstKind, Value, ValueId}; +use crate::budget::{tree_bytes, Meter}; +use crate::error::{Error, Feature, Unsupported}; +use crate::lower::emit::EmitCx; +use crate::lower::select::SelectCx; +use crate::memory::provenance::{self, HandleClass, Repr}; +use crate::spirv::builder::FunctionBuilder; +use crate::spirv::error::BResult; +use crate::spirv::ids::{DemoteTy, ScalarTy}; + +use super::dynamic::{self, Source}; +use super::AccessPlan; + +/// The handle load of an indirect-command object: its field's word, a `u64`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ObjectWord(pub Source); + +impl ObjectWord { + /// The census name (`access.object.word`) in the finished plan `slots`, qualified by what the + /// object's load reaches ([`super::SideReach`]). + pub fn name(&self, slots: &AccessPlan) -> Cow<'static, str> { + self.0.reach(slots).qualify("access.object.word") + } + + /// An upper estimate of the SPIR-V words one use emits: a leaf access. + pub fn words(&self) -> u32 { + self.0.words() + } +} + +/// Whether `class` is an indirect-command object's. +fn object_class(class: HandleClass) -> bool { + matches!( + class, + HandleClass::Command | HandleClass::ComputePipelineState | HandleClass::RenderPipelineState + ) +} + +/// The encoder operation of call `call`, if it is one. +fn encoder(call: &crate::air::ir::Call) -> Option { + match call.callee { + Callee::Air { + op: AirIntrinsic::IndirectCommand(op), + .. + } => Some(op), + _ => None, + } +} + +/// Whether operand `i` of encoder `op` may be an object word of `class`: the command operand, +/// the pipeline operand of a compute or render pipeline setter, or a copy's source command +/// buffer. +fn encoder_operand(op: IndirectCommand, i: usize, class: HandleClass) -> bool { + match (i, class) { + (0, HandleClass::Command) => true, + (2, HandleClass::ComputePipelineState) => op == IndirectCommand::SetComputePipeline, + (2, HandleClass::RenderPipelineState) => op == IndirectCommand::SetRenderPipeline, + (2, HandleClass::Command) => op == IndirectCommand::CopyComputeCommand, + _ => false, + } +} + +/// Plan the function's object words, before any instruction is selected: each handle load of an +/// indirect-command object (`provenance::object_handle_load`) whose every use is an encoder operand +/// of its class (`encoder_operand`). +pub fn plan_objects(cx: &mut SelectCx<'_>, m: &mut Meter) -> Result<(), Error> { + let body = cx.body; + let entry = tree_bytes(1, std::mem::size_of::<(InstId, HandleClass)>()); + let mut words: BTreeMap = BTreeMap::new(); + for (id, inst) in body.insts.iter() { + m.tick(1)?; + let InstKind::Load { + ptr, + volatile: false, + atomic: None, + .. + } = &inst.kind + else { + continue; + }; + let Some(Repr::Handle { class, .. }) = cx.memory.repr(Value::Inst(id)) else { + continue; + }; + if !object_class(class) { + continue; + } + let (Some(roots), Some(range), Some(bytes)) = ( + cx.memory.roots_of(*ptr), + cx.memory.offset(*ptr), + cx.memory.layouts.store_size(inst.ty), + ) else { + continue; + }; + if provenance::object_handle_load(cx.entry, &cx.memory.abi, roots, range, bytes).is_some() { + m.charge(entry)?; + words.insert(id, class); + } + } + if words.is_empty() { + return Ok(()); + } + for (_, inst) in body.insts.iter() { + m.tick(1)?; + match &inst.kind { + InstKind::Call(call) if encoder(call).is_some() => { + let op = encoder(call).ok_or_else(|| cx.invariant("an encoder vanished"))?; + for (i, a) in call.args.iter().enumerate() { + if let Value::Inst(l) = a { + if words.get(l).is_some_and(|c| !encoder_operand(op, i, *c)) { + words.remove(l); + } + } + } + } + kind => kind.for_each_value(|v| { + if let Value::Inst(l) = v { + words.remove(&l); + } + }), + } + } + cx.families.access.objects = words.into_keys().collect::>(); + Ok(()) +} + +/// The lowered representation of an object word ([`plan_objects`]): a `u64`; `None` for any +/// other value. +pub fn lowered_pointer(cx: &SelectCx<'_>, v: Value) -> Option { + match v { + Value::Inst(i) if cx.families.access.objects.contains(&i) => { + Some(DemoteTy::Scalar(ScalarTy::Int { bits: 64 })) + } + _ => None, + } +} + +/// Select the strategy of `inst`: an object word's handle load, or the refusal of an encoder +/// operation (see the module docs); `None` for any other instruction. +pub fn select( + cx: &mut SelectCx<'_>, + at: InstId, + inst: &Inst, + m: &mut Meter, +) -> Result, Error> { + match &inst.kind { + InstKind::Load { + ptr, + align, + volatile: false, + atomic: None, + .. + } if cx.families.access.objects.contains(&at) => Ok(Some(ObjectWord(dynamic::plan_word( + cx, *ptr, inst.ty, *align, m, + )?))), + InstKind::Call(call) if encoder(call).is_some() => { + let command = call.args.first(); + if !matches!(command, Some(Value::Inst(i)) if cx.families.access.objects.contains(i)) { + return Err(Unsupported::not_implemented(Feature::ArgumentBufferObjects).into()); + } + Err(Unsupported::not_implemented(Feature::GpuEncodedIndirectCommands).into()) + } + _ => Ok(None), + } +} + +/// Emit object word `w`, defining value `vid`. +pub fn emit( + cx: &mut EmitCx<'_>, + fb: &mut FunctionBuilder<'_>, + vid: ValueId, + w: &ObjectWord, +) -> BResult<()> { + let word = dynamic::emit_word(cx, fb, &w.0)?; + cx.define(vid, word); + Ok(()) +} diff --git a/crates/metal2vulkan/src/lower/select.rs b/crates/metal2vulkan/src/lower/select.rs index b1b78e7df..b2a72abde 100644 --- a/crates/metal2vulkan/src/lower/select.rs +++ b/crates/metal2vulkan/src/lower/select.rs @@ -872,7 +872,7 @@ fn route_air(cx: &SelectCx<'_>, op: &AirIntrinsic, decl: FuncId) -> Route { .into(), ), A::Tensor(_) => Route::Refuse(Unsupported::not_implemented(Feature::Tensors).into()), - // An encoder operation writes its command's record through device addresses. + // An encoder operation is the access family's (`access::object`). A::IndirectCommand(_) => Route::Family(LowerFamily::Access), A::Mesh(_) => Route::Family(LowerFamily::Mesh), // Canonicalization makes every vector data call its element accesses. @@ -1410,7 +1410,7 @@ fn select_body( // The spin reads, before any atomic is selected. access::atomic::spin::plan(cx, m)?; // The indirect-command object words, before any use of one is selected. - access::encode::plan_objects(cx, m)?; + access::object::plan_objects(cx, m)?; // The encodings each pointer-cell slot group's loads read, before any store. access::cell::plan_reads(cx, m)?; // The primitive-data stores nothing reads back, before any store. diff --git a/crates/metal2vulkan/src/pipeline/compile/tests.rs b/crates/metal2vulkan/src/pipeline/compile/tests.rs index 4deccff67..5daeef268 100644 --- a/crates/metal2vulkan/src/pipeline/compile/tests.rs +++ b/crates/metal2vulkan/src/pipeline/compile/tests.rs @@ -2873,9 +2873,9 @@ fn a_compute_pipeline_states_whether_its_kernel_writes_memory() { /// The interface states whether the function takes an indirect command buffer, from the AIR's /// metadata: an argument buffer's `command_buffer` member the kernel never encodes through -/// (`kernel_icb_declared_handle_is_inert`), and one it encodes compute commands through -/// (`icb_replay_encode`), count; a kernel that takes none (`icb_replay_template`, which a -/// command runs) does not. A pipeline's interface states it where one of its stages does. +/// (`kernel_icb_declared_handle_is_inert`) counts; a kernel that takes none +/// (`icb_replay_template`, which a command runs) does not. A pipeline's interface states it where +/// one of its stages does. #[test] fn the_interface_states_whether_the_function_takes_a_command_buffer() { let p = crate::pipeline::testing::profile("lavapipe", DevicePolicy::RESIDENT_TABLES) @@ -2888,7 +2888,6 @@ fn the_interface_states_whether_the_function_takes_a_command_buffer() { "kernel_icb_declared_handle_is_inert", true, ), - (&dirs[1], "icb_replay_encode", "icb_replay_encode", true), ( &dirs[1], "icb_replay_template", @@ -2918,44 +2917,33 @@ fn the_interface_states_whether_the_function_takes_a_command_buffer() { } /// The interface states what the function may write into indirect command buffers, from its -/// AIR: a kernel that encodes compute commands (`icb_replay_encode`) its operations' bits, no -/// primitive type and the compute kind; kernels that draw (`icb_render_replay_encode_draw_only`, -/// `icb_render_indexed_encode`) their draws' bits, the constant primitive type they pass -/// (points) and the render kind; a kernel that takes no command buffer (`icb_replay_template`) -/// nothing. A pipeline's interface holds its stages' together. +/// AIR: a kernel that binds each command's buffers and draws indexed triangles into it +/// (`icb_indexed_16`, under the identity domains, which lower such a kernel) its operations' +/// bits, the constant primitive type it passes (triangles) and the render kind; a kernel that +/// takes no command buffer (`icb_replay_template`) nothing. A pipeline's interface holds its +/// stages' together. #[test] fn the_interface_states_what_the_function_may_write_into_command_buffers() { use crate::pipeline::interface::CommandWrites as W; - let p = crate::pipeline::testing::profile("lavapipe", DevicePolicy::RESIDENT_TABLES) - .expect("profile"); - for (entry, operations, primitive_types, kinds) in [ + let p = + crate::pipeline::testing::profile("lavapipe", DevicePolicy::default()).expect("profile"); + for (fixture, entry, operations, primitive_types, kinds) in [ ( - "icb_replay_encode", - W::PIPELINE | W::BUFFER | W::THREADGROUP_MEMORY | W::DISPATCH | W::BARRIER, - 0, - W::COMPUTE_COMMANDS, - ), - ( - "icb_render_replay_encode_draw_only", - W::DRAW, - 0b1, + "icb_merged_indexed", + "icb_indexed_16", + W::BUFFER | W::DRAW_INDEXED, + 1 << 3, W::RENDER_COMMANDS, ), - ( - "icb_render_indexed_encode", - W::DRAW_INDEXED, - 0b1, - W::RENDER_COMMANDS, - ), - ("icb_replay_template", 0, 0, 0), + ("icb_replay_template", "icb_replay_template", 0, 0, 0), ] { - let bc = match llvm_assemble(&engine_dir().join(format!("{entry}.ll"))) { + let bc = match llvm_assemble(&engine_dir().join(format!("{fixture}.ll"))) { Ok(b) => b, Err(AssembleError::Missing(why)) => { eprintln!("SKIPPED: {why}"); return; } - Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected {entry}.ll: {why}"), + Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected {fixture}.ll: {why}"), }; let a = crate::pipeline::testing::compile(&bc, entry, &p) .unwrap_or_else(|e| panic!("{entry}: {e}")); diff --git a/crates/metal2vulkan/src/tests/engine_handles.rs b/crates/metal2vulkan/src/tests/engine_handles.rs index 07bc24f84..86379ae94 100644 --- a/crates/metal2vulkan/src/tests/engine_handles.rs +++ b/crates/metal2vulkan/src/tests/engine_handles.rs @@ -3444,10 +3444,9 @@ declare void @air.concurrent_dispatch_threadgroups_compute_command(ptr addrspace /// `air.set_pipeline_state_compute_command`'s pipeline operand is a `compute_pipeline_state` /// handle, the class of the argument-buffer member it is loaded from, so a GPU-encoded compute -/// command is no class conflict: with device addresses it translates (the member words are the -/// record buffer's guest address and the template's token), and without them it is its family's -/// refusal, `GpuEncodedIndirectCommands`, naming what the profile lacks. The same pipeline state -/// also read as bytes still conflicts: `HandleAsPointer`, not representable. +/// command is no class conflict: it is its family's refusal, `GpuEncodedIndirectCommands`, not +/// implemented, on every committed profile. The same pipeline state also read as bytes still +/// conflicts: `HandleAsPointer`, not representable. #[test] fn a_command_set_to_an_argument_buffer_pipeline_state_is_its_family_refusal() { let Some(bc) = assemble( @@ -3457,31 +3456,12 @@ fn a_command_set_to_an_argument_buffer_pipeline_state_is_its_family_refusal() { return; }; for (stem, p) in committed_profiles().expect("profiles") { - match compile(&bc, "set_pipeline", &p) { - Ok(a) => { - assert_eq!( - p.fields().buffer_access, - crate::device::profile::BufferAccess::Addressed, - "{stem}" - ); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{stem}: L3: {e}")); - } - Err(e) => { - let u = unsupported(e); - assert_eq!( - (u.feature, u.needs), - ( - Feature::GpuEncodedIndirectCommands, - Unsupported::needs_any_of( - Feature::GpuEncodedIndirectCommands, - vec![p.addressed_needs()] - ) - .needs - ), - "{stem}" - ); - } - } + let u = unsupported(compile(&bc, "set_pipeline", &p).expect_err(&stem)); + assert_eq!( + (u.feature, u.needs), + (Feature::GpuEncodedIndirectCommands, Needs::NotImplemented), + "{stem}" + ); } let Some(bc) = assemble( "icb_pipeline_bytes", diff --git a/crates/metal2vulkan/src/tests/engine_indirect_commands.rs b/crates/metal2vulkan/src/tests/engine_indirect_commands.rs index 9a4eb2029..64023406c 100644 --- a/crates/metal2vulkan/src/tests/engine_indirect_commands.rs +++ b/crates/metal2vulkan/src/tests/engine_indirect_commands.rs @@ -1,47 +1,21 @@ -//! GPU-encoded indirect commands through device addresses. +//! Indirect-command objects and the encoder operations that take them (`lower::access::object`). //! -//! An argument buffer's command-buffer member holds its resource ID, whose record buffer lies at -//! the guest address `records_address` of it, and a pipeline-state member its template's -//! host-registered token. On every committed profile with device addresses, a kernel that encodes -//! compute commands (buffer setters in the device and the constant space, a pipeline state, a -//! threadgroup length, a dispatch of threadgroups or threads, a barrier set or cleared, a stage-in -//! region, an imageblock size, a reset, a copy of another command) or render commands (vertex and -//! fragment buffers, a draw; object and mesh buffers, a barrier set or cleared, a mesh draw of -//! threadgroups or threads) compiles, links, and validates, and the CPU interpreter's run of it -//! leaves records that `CommandBuffer::decode` reads back exactly as the host contract states them -//! (`HostRecordsV1`): the round trip. A threadgroup length is kept as set, a multiple of 16 or not. -//! Each command a kernel writes (a copy's destination too) has its written flag past the records -//! set, and no other (`written_flag_offset`). A write the descriptor policy does not allow (a -//! command index at the capacity, a binding past its count, a dynamic stride the descriptor does -//! not enable, a pipeline set while inheriting it, a compute command in a render buffer, a copy -//! whose result is Metal's private record layout) sets the header's fault flag and writes nothing, -//! its written flag included, so `decode` fails as an encoding fault. A record buffer outside the -//! resident set is root 0: contained, and counted under isolation. On the profiles without device -//! addresses every encoder operation is `GpuEncodedIndirectCommands`, naming what they lack. +//! A kernel's encoder operation through its argument buffer's command-buffer member (a buffer +//! setter, a pipeline state, a dispatch, a barrier, a reset, a copy of another command; a render +//! command's buffer setter, draw, mesh draw and render state setter) is refused under the +//! resident-table domains on every committed profile and on Profile F, +//! `Unsupported{GpuEncodedIndirectCommands, NotImplemented}` (the identity domains' forms are +//! `tests::engine_identity_icb`'s). A kernel +//! whose argument buffer holds a `depth_stencil_state` compiles with it unread and is refused +//! `NotImplemented(IndirectRenderState)` where it reads it. //! //! `llvm-as` assembles the kernels; without it the tests skip visibly. -use std::collections::BTreeMap; -use std::num::NonZeroU64; use std::sync::atomic::{AtomicU64, Ordering}; -use crate::bind::status::{ExecutionStatus, StatusBits, StatusWord}; -use crate::device::profile::{BufferAccess, DeviceProfile}; -use crate::error::{Error, Feature, Needs, Unsupported}; -use crate::indirect_commands::written_flag_offset; -use crate::indirect_commands::{ - layout, Action, BufferBinding, BufferStage, CommandBuffer, CommandBufferError, - CommandDescriptor, CommandRecord, ComputeDispatch, Inheritance, RenderDraws, StateSource, - BINDING_COUNT, COMMAND_BUFFER_HEADER_BYTES, COMMAND_BYTES, WRITTEN_FLAG_BYTES, -}; -use crate::lower::select::Plan; -use crate::pipeline::interface::PushLoc; -use crate::pipeline::sym::{Axis, PushField, ResourceKind, ResourceSlot, SpecKey, Stage}; -use crate::pipeline::testing::{ - compile, device_f, link_and_validate, llvm_assemble, typed_module, AssembleError, PROFILE_F, -}; -use crate::spirv::interp::{run, Buffer, Config, InterpError, Resources}; -use crate::spirv::ir::TypedModule; +use crate::device::profile::DeviceProfile; +use crate::error::{Error, Feature, Needs}; +use crate::pipeline::testing::{compile, device_f, llvm_assemble, AssembleError, PROFILE_F}; use crate::spirv::testing::committed_profiles; const DATALAYOUT: &str = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32"; @@ -71,19 +45,12 @@ fn assemble(name: &str, body: &str) -> Option> { } } -/// Committed profiles by stem. -type Profiles = Vec<(String, DeviceProfile)>; - -/// One parameter that makes a write invalid, by what it breaks. -type Spoil = (&'static str, fn(&mut Params)); - -/// The committed profiles with device addresses, and those without. -fn profiles() -> (Profiles, Profiles) { +/// The committed profiles and Profile F, by stem. +fn profiles() -> Vec<(String, DeviceProfile)> { let mut all = committed_profiles().expect("profiles"); let f = device_f(crate::device::DevicePolicy::RESIDENT_TABLES).expect(PROFILE_F); all.push((PROFILE_F.into(), f.profile().clone())); - all.into_iter() - .partition(|(_, p)| p.fields().buffer_access == BufferAccess::Addressed) + all } /// The argument buffer `{command_buffer commands; compute_pipeline_state pipeline;}` at Metal @@ -107,731 +74,14 @@ const COMPUTE_META: &str = r#" !21 = !{!"Metal", i32 4, i32 0, i32 0} "#; -/// Each thread `t` reads its parameters `params[t]` (`{u32 index, u32 binding, u32 length, u32 -/// tg_binding, i64 stride, u32 grid_x, u32 pad}`, 32 bytes) and encodes command `index`: the -/// 16 bytes of `data` at `16 t` at kernel buffer `binding` with `stride`, `consts` at `binding + -/// 1`, the pipeline state, `length` at threadgroup binding `tg_binding`, then (in two blocks, -/// with the command handle carried across them) a dispatch of `(grid_x, 2, 3)` threadgroups of -/// `(32, 1, 1)` and a barrier for an even `t`, a dispatch of `(grid_x, 2, 3)` threads of `(16, 2, -/// 1)` for an odd `t`. -fn compute_kernel() -> String { - format!( - r#"%enc = type {{ ptr addrspace(1), ptr addrspace(1) }} - -define void @encode(ptr addrspace(1) %enc, ptr addrspace(1) %data, ptr addrspace(2) %consts, ptr addrspace(1) %params, i32 %t) {{ -entry: - %pc = getelementptr inbounds %enc, ptr addrspace(1) %enc, i64 0, i32 0 - %cmd = load ptr addrspace(1), ptr addrspace(1) %pc, align 8 - %pp = getelementptr inbounds %enc, ptr addrspace(1) %enc, i64 0, i32 1 - %pso = load ptr addrspace(1), ptr addrspace(1) %pp, align 8 - %t64 = zext i32 %t to i64 - %prm = getelementptr inbounds [8 x i32], ptr addrspace(1) %params, i64 %t64 - %index = load i32, ptr addrspace(1) %prm, align 8 - %p1 = getelementptr inbounds i32, ptr addrspace(1) %prm, i64 1 - %binding = load i32, ptr addrspace(1) %p1, align 4 - %p2 = getelementptr inbounds i32, ptr addrspace(1) %prm, i64 2 - %length = load i32, ptr addrspace(1) %p2, align 4 - %p3 = getelementptr inbounds i32, ptr addrspace(1) %prm, i64 3 - %tgb = load i32, ptr addrspace(1) %p3, align 4 - %p4 = getelementptr inbounds i64, ptr addrspace(1) %prm, i64 2 - %stride = load i64, ptr addrspace(1) %p4, align 8 - %p6 = getelementptr inbounds i32, ptr addrspace(1) %prm, i64 6 - %gx = load i32, ptr addrspace(1) %p6, align 4 - %off = mul i64 %t64, 16 - %d = getelementptr inbounds i8, ptr addrspace(1) %data, i64 %off - call void @air.set_kernel_buffer_compute_command.p1i8(ptr addrspace(1) %cmd, i32 %index, ptr addrspace(1) %d, i64 %stride, i32 %binding) - %b1 = add i32 %binding, 1 - call void @air.set_kernel_buffer_compute_command.p2i8(ptr addrspace(1) %cmd, i32 %index, ptr addrspace(2) %consts, i64 -1, i32 %b1) - call void @air.set_pipeline_state_compute_command(ptr addrspace(1) %cmd, i32 %index, ptr addrspace(1) %pso) - call void @air.set_threadgroup_memory_length_compute_command(ptr addrspace(1) %cmd, i32 %index, i32 %length, i32 %tgb) - %g0 = insertelement <3 x i32> , i32 %gx, i64 0 - %odd = and i32 %t, 1 - %isodd = icmp ne i32 %odd, 0 - br i1 %isodd, label %threads, label %groups -groups: - call void @air.concurrent_dispatch_threadgroups_compute_command(ptr addrspace(1) %cmd, i32 %index, <3 x i32> %g0, <3 x i32> ) - call void @air.set_barrier_compute_command(ptr addrspace(1) %cmd, i32 %index) - br label %done -threads: - call void @air.concurrent_dispatch_threads_compute_command(ptr addrspace(1) %cmd, i32 %index, <3 x i32> %g0, <3 x i32> ) - br label %done -done: - ret void -}} - -declare void @air.set_kernel_buffer_compute_command.p1i8(ptr addrspace(1), i32, ptr addrspace(1), i64, i32) -declare void @air.set_kernel_buffer_compute_command.p2i8(ptr addrspace(1), i32, ptr addrspace(2), i64, i32) -declare void @air.set_pipeline_state_compute_command(ptr addrspace(1), i32, ptr addrspace(1)) -declare void @air.set_threadgroup_memory_length_compute_command(ptr addrspace(1), i32, i32, i32) -declare void @air.concurrent_dispatch_threadgroups_compute_command(ptr addrspace(1), i32, <3 x i32>, <3 x i32>) -declare void @air.concurrent_dispatch_threads_compute_command(ptr addrspace(1), i32, <3 x i32>, <3 x i32>) -declare void @air.set_barrier_compute_command(ptr addrspace(1), i32) -{COMPUTE_META}"# - ) -} - -/// A kernel of the same argument buffer encoding render command `t`: the 16 bytes of `data` at -/// `16 t` as vertex buffer 0 (static stride) and fragment buffer 1, and a draw of 3 vertices from -/// `3 t`, 2 instances from 5. -fn render_kernel() -> String { - let meta = COMPUTE_META.replace("compute_pipeline_state", "render_pipeline_state"); - format!( - r#"%enc = type {{ ptr addrspace(1), ptr addrspace(1) }} - -define void @encode(ptr addrspace(1) %enc, ptr addrspace(1) %data, ptr addrspace(2) %consts, ptr addrspace(1) %params, i32 %t) {{ -entry: - %pc = getelementptr inbounds %enc, ptr addrspace(1) %enc, i64 0, i32 0 - %cmd = load ptr addrspace(1), ptr addrspace(1) %pc, align 8 - %t64 = zext i32 %t to i64 - %off = mul i64 %t64, 16 - %d = getelementptr inbounds i8, ptr addrspace(1) %data, i64 %off - call void @air.set_vertex_buffer_render_command.p1i8(ptr addrspace(1) %cmd, i32 %t, ptr addrspace(1) %d, i64 -1, i32 0) - call void @air.set_fragment_buffer_render_command.p1i8(ptr addrspace(1) %cmd, i32 %t, ptr addrspace(1) %d, i32 1) - %start = mul i32 %t, 3 - call void @air.draw_primitives_render_command(ptr addrspace(1) %cmd, i32 %t, i32 3, i32 %start, i32 3, i32 2, i32 5) - ret void -}} - -declare void @air.set_vertex_buffer_render_command.p1i8(ptr addrspace(1), i32, ptr addrspace(1), i64, i32) -declare void @air.set_fragment_buffer_render_command.p1i8(ptr addrspace(1), i32, ptr addrspace(1), i32) -declare void @air.draw_primitives_render_command(ptr addrspace(1), i32, i32, i32, i32, i32, i32) -{meta}"# - ) -} - -/// Each thread `t` sets command `t`'s render pipeline state, the 16 bytes of `data` at `16 t` as -/// object buffer 0 and `consts` as mesh buffer 0, then for an even `t` its barrier and a mesh -/// draw of `(t + 1, 2, 1)` threadgroups of 4 object and 2 mesh threads, for an odd `t` a cleared -/// barrier and a mesh draw of `(12, 4, 1)` threads, 1 object thread and `(4, 2, 1)` mesh threads -/// (the forms of the owned fixture `mesh_commands`). -fn render_mesh_kernel() -> String { - let meta = COMPUTE_META.replace("compute_pipeline_state", "render_pipeline_state"); - format!( - r#"%enc = type {{ ptr addrspace(1), ptr addrspace(1) }} - -define void @encode(ptr addrspace(1) %enc, ptr addrspace(1) %data, ptr addrspace(2) %consts, ptr addrspace(1) %params, i32 %t) {{ -entry: - %pc = getelementptr inbounds %enc, ptr addrspace(1) %enc, i64 0, i32 0 - %cmd = load ptr addrspace(1), ptr addrspace(1) %pc, align 8 - %pp = getelementptr inbounds %enc, ptr addrspace(1) %enc, i64 0, i32 1 - %pso = load ptr addrspace(1), ptr addrspace(1) %pp, align 8 - %t64 = zext i32 %t to i64 - %off = mul i64 %t64, 16 - %d = getelementptr inbounds i8, ptr addrspace(1) %data, i64 %off - call void @air.set_pipeline_state_render_command(ptr addrspace(1) %cmd, i32 %t, ptr addrspace(1) %pso) - call void @air.set_object_buffer_render_command.p1i8(ptr addrspace(1) %cmd, i32 %t, ptr addrspace(1) %d, i32 0) - call void @air.set_mesh_buffer_render_command.p2i8(ptr addrspace(1) %cmd, i32 %t, ptr addrspace(2) %consts, i32 0) - %bit = and i32 %t, 1 - %odd = icmp ne i32 %bit, 0 - br i1 %odd, label %threads, label %groups -groups: - call void @air.set_barrier_render_command(ptr addrspace(1) %cmd, i32 %t) - %x = add i32 %t, 1 - %grid = insertelement <3 x i32> , i32 %x, i64 0 - call void @air.draw_mesh_threadgroups_render_command(ptr addrspace(1) %cmd, i32 %t, <3 x i32> %grid, <3 x i32> , <3 x i32> ) - br label %exit -threads: - call void @air.clear_barrier_render_command(ptr addrspace(1) %cmd, i32 %t) - call void @air.draw_mesh_threads_render_command(ptr addrspace(1) %cmd, i32 %t, <3 x i32> , <3 x i32> , <3 x i32> ) - br label %exit -exit: - ret void -}} - -declare void @air.set_pipeline_state_render_command(ptr addrspace(1), i32, ptr addrspace(1)) -declare void @air.set_object_buffer_render_command.p1i8(ptr addrspace(1), i32, ptr addrspace(1), i32) -declare void @air.set_mesh_buffer_render_command.p2i8(ptr addrspace(1), i32, ptr addrspace(2), i32) -declare void @air.set_barrier_render_command(ptr addrspace(1), i32) -declare void @air.clear_barrier_render_command(ptr addrspace(1), i32) -declare void @air.draw_mesh_threadgroups_render_command(ptr addrspace(1), i32, <3 x i32>, <3 x i32>, <3 x i32>) -declare void @air.draw_mesh_threads_render_command(ptr addrspace(1), i32, <3 x i32>, <3 x i32>, <3 x i32>) -{meta}"# - ) -} - -/// Each thread `t` sets command `t`'s render pipeline state, then for an even `t` an indexed draw -/// of 6 `ushort` indices from `data` at `16 t` (triangles, 2 instances, base vertex `-t`, base -/// instance 7), for an odd `t` one of 4 `uint` indices from `consts` (points, 1 instance); thread -/// 3 then resets its command. -fn render_indexed_kernel() -> String { - let meta = COMPUTE_META.replace("compute_pipeline_state", "render_pipeline_state"); - format!( - r#"%enc = type {{ ptr addrspace(1), ptr addrspace(1) }} - -define void @encode(ptr addrspace(1) %enc, ptr addrspace(1) %data, ptr addrspace(2) %consts, ptr addrspace(1) %params, i32 %t) {{ -entry: - %pc = getelementptr inbounds %enc, ptr addrspace(1) %enc, i64 0, i32 0 - %cmd = load ptr addrspace(1), ptr addrspace(1) %pc, align 8 - %pp = getelementptr inbounds %enc, ptr addrspace(1) %enc, i64 0, i32 1 - %pso = load ptr addrspace(1), ptr addrspace(1) %pp, align 8 - %t64 = zext i32 %t to i64 - %off = mul i64 %t64, 16 - %d = getelementptr inbounds i8, ptr addrspace(1) %data, i64 %off - call void @air.set_pipeline_state_render_command(ptr addrspace(1) %cmd, i32 %t, ptr addrspace(1) %pso) - %bit = and i32 %t, 1 - %odd = icmp ne i32 %bit, 0 - br i1 %odd, label %wide, label %narrow -narrow: - %bv = sub i32 0, %t - call void @air.draw_indexed_primitives_render_command.p1i16(ptr addrspace(1) %cmd, i32 %t, i32 3, i32 6, ptr addrspace(1) %d, i32 2, i32 %bv, i32 7) - br label %done -wide: - call void @air.draw_indexed_primitives_render_command.p2i32(ptr addrspace(1) %cmd, i32 %t, i32 0, i32 4, ptr addrspace(2) %consts, i32 1, i32 0, i32 0) - br label %done -done: - %last = icmp eq i32 %t, 3 - br i1 %last, label %reset, label %exit -reset: - call void @air.reset_render_command(ptr addrspace(1) %cmd, i32 %t) - br label %exit -exit: - ret void -}} - -declare void @air.set_pipeline_state_render_command(ptr addrspace(1), i32, ptr addrspace(1)) -declare void @air.draw_indexed_primitives_render_command.p1i16(ptr addrspace(1), i32, i32, i32, ptr addrspace(1), i32, i32, i32) -declare void @air.draw_indexed_primitives_render_command.p2i32(ptr addrspace(1), i32, i32, i32, ptr addrspace(2), i32, i32, i32) -declare void @air.reset_render_command(ptr addrspace(1), i32) -{meta}"# - ) -} - -/// Each thread `t` encodes command `t`'s patch draw: for an even `t`, 4 control points from patch -/// `t`, 2 patches, no patch index buffer, 3 instances from 1, the factors in `data` at `16 t` with -/// an instance stride of 48 and a scale of 1; for an odd `t`, 3 control points, 1 patch, the -/// patch indices in `data` at `16 t`, 1 instance, the factors in `consts`, a scale of 0.5. -fn render_patches_kernel() -> String { - let meta = COMPUTE_META.replace("compute_pipeline_state", "render_pipeline_state"); - format!( - r#"%enc = type {{ ptr addrspace(1), ptr addrspace(1) }} - -define void @encode(ptr addrspace(1) %enc, ptr addrspace(1) %data, ptr addrspace(2) %consts, ptr addrspace(1) %params, i32 %t) {{ -entry: - %pc = getelementptr inbounds %enc, ptr addrspace(1) %enc, i64 0, i32 0 - %cmd = load ptr addrspace(1), ptr addrspace(1) %pc, align 8 - %t64 = zext i32 %t to i64 - %off = mul i64 %t64, 16 - %d = getelementptr inbounds i8, ptr addrspace(1) %data, i64 %off - %bit = and i32 %t, 1 - %odd = icmp ne i32 %bit, 0 - br i1 %odd, label %indexed, label %plain -plain: - call void @air.draw_patches_render_command.p1i32.p1i8(ptr addrspace(1) %cmd, i32 %t, i32 4, i32 %t, i32 2, ptr addrspace(1) null, i32 3, i32 1, ptr addrspace(1) %d, i32 48, float 1.000000e+00) - br label %exit -indexed: - call void @air.draw_patches_render_command.p1i32.p2i8(ptr addrspace(1) %cmd, i32 %t, i32 3, i32 0, i32 1, ptr addrspace(1) %d, i32 1, i32 0, ptr addrspace(2) %consts, i32 0, float 5.000000e-01) - br label %exit -exit: - ret void -}} - -declare void @air.draw_patches_render_command.p1i32.p1i8(ptr addrspace(1), i32, i32, i32, i32, ptr addrspace(1), i32, i32, ptr addrspace(1), i32, float) -declare void @air.draw_patches_render_command.p1i32.p2i8(ptr addrspace(1), i32, i32, i32, i32, ptr addrspace(1), i32, i32, ptr addrspace(2), i32, float) -{meta}"# - ) -} - -/// Each thread `t` encodes command `t`'s indexed patch draw: for an even `t`, 4 control points -/// from patch `t`, 2 patches, no patch index or control-point index buffer, 3 instances from 1, -/// the factors in `data` at `16 t` with an instance stride of 48 and a scale of 1; for an odd `t`, -/// 3 control points, 1 patch, the patch indices and the factors in `data` at `16 t`, the -/// control-point indices in `consts`, 1 instance, a scale of 0.5. -fn render_indexed_patches_kernel() -> String { - let meta = COMPUTE_META.replace("compute_pipeline_state", "render_pipeline_state"); - format!( - r#"%enc = type {{ ptr addrspace(1), ptr addrspace(1) }} - -define void @encode(ptr addrspace(1) %enc, ptr addrspace(1) %data, ptr addrspace(2) %consts, ptr addrspace(1) %params, i32 %t) {{ -entry: - %pc = getelementptr inbounds %enc, ptr addrspace(1) %enc, i64 0, i32 0 - %cmd = load ptr addrspace(1), ptr addrspace(1) %pc, align 8 - %t64 = zext i32 %t to i64 - %off = mul i64 %t64, 16 - %d = getelementptr inbounds i8, ptr addrspace(1) %data, i64 %off - %bit = and i32 %t, 1 - %odd = icmp ne i32 %bit, 0 - br i1 %odd, label %indexed, label %plain -plain: - call void @air.draw_indexed_patches_render_command.p1i32.p1i8.p1i8(ptr addrspace(1) %cmd, i32 %t, i32 4, i32 %t, i32 2, ptr addrspace(1) null, ptr addrspace(1) null, i32 3, i32 1, ptr addrspace(1) %d, i32 48, float 1.000000e+00) - br label %exit -indexed: - call void @air.draw_indexed_patches_render_command.p1i32.p2i8.p1i8(ptr addrspace(1) %cmd, i32 %t, i32 3, i32 0, i32 1, ptr addrspace(1) %d, ptr addrspace(2) %consts, i32 1, i32 0, ptr addrspace(1) %d, i32 0, float 5.000000e-01) - br label %exit -exit: - ret void -}} - -declare void @air.draw_indexed_patches_render_command.p1i32.p1i8.p1i8(ptr addrspace(1), i32, i32, i32, i32, ptr addrspace(1), ptr addrspace(1), i32, i32, ptr addrspace(1), i32, float) -declare void @air.draw_indexed_patches_render_command.p1i32.p2i8.p1i8(ptr addrspace(1), i32, i32, i32, i32, ptr addrspace(1), ptr addrspace(2), i32, i32, ptr addrspace(1), i32, float) -{meta}"# - ) -} - -// ---- The interpreter's run ---- - -/// Device addresses of the interpreter's address-backed buffers (host), and the guest addresses -/// the run's Metal objects have (a distinct domain, so a mix-up reads the wrong bytes or faults). -const TABLE: u64 = 0x0000_0010_0000_0000; -const SINK: u64 = 0x0000_0011_0000_0000; -const STATUS: u64 = 0x0000_0012_0000_0000; -const DATA_HOST: u64 = 0x0000_0020_0000_0000; -const CONSTS_HOST: u64 = 0x0000_0021_0000_0000; -const RECORDS_HOST: u64 = 0x0000_0022_0000_0000; -const DATA_GUEST: u64 = 0x0000_0001_0000_1000; -const CONSTS_GUEST: u64 = 0x0000_0001_0000_8000; - -/// A buffer slot set plainly to `address`, at the pipeline's stride. -fn plain(address: u64) -> Option { - Some(BufferBinding { - address, - attribute_stride: None, - }) -} -/// The record buffer's resource ID, the command-buffer word, and the guest address of its records. -const RECORDS_ID: u64 = 3; -const RECORDS_GUEST: u64 = crate::indirect_commands::records_address(RECORDS_ID); -/// A copy's second record buffer ([`run_records`]). -const SOURCE_HOST: u64 = 0x0000_0023_0000_0000; -const SOURCE_ID: u64 = 4; -const SOURCE_GUEST: u64 = crate::indirect_commands::records_address(SOURCE_ID); -/// The pipeline state's host-registered token. -const TOKEN: u64 = 0x0123_4567_89ab_cdef; -/// Threads per run, and the record buffer's capacity. -const THREADS: u32 = 4; -const DATA_BYTES: u64 = 16 * THREADS as u64; -const CONSTS_BYTES: u64 = 16; - -fn slot(index: u32) -> ResourceSlot { - ResourceSlot { - stage: Stage::Kernel, - kind: ResourceKind::Buffer, - index, - } -} - -/// The root table: null, the sink with the resident range, the four buffer slots (roots 2 to 5; -/// the wide ones read their entries), and the resident set from root 6 sorted by guest address. -fn root_table(resident: &[(u64, u64, u64)]) -> Vec { - let statics = [ - (0, 0, 0), - (DATA_HOST, DATA_GUEST, DATA_BYTES), - (CONSTS_HOST, CONSTS_GUEST, CONSTS_BYTES), - (0, 0, 0), - ]; - let first = 2 + statics.len(); - let mut t = vec![0u8; 32 * (first + resident.len())]; - let mut put = |root: usize, field: usize, v: u64| { - let at = 32 * root + 8 * field; - t[at..at + 8].copy_from_slice(&v.to_le_bytes()); - }; - put(1, 0, SINK); - put(1, 1, first as u64); - put(1, 2, resident.len() as u64); - for (i, (h, g, s)) in statics.iter().enumerate() { - put(2 + i, 0, *h); - put(2 + i, 1, *g); - put(2 + i, 2, *s); - } - for (i, (h, g, s)) in resident.iter().enumerate() { - put(first + i, 0, *h); - put(first + i, 1, *g); - put(first + i, 2, *s); - } - t -} - -fn push_bytes(plan: &Plan) -> Vec { - let mut push = vec![0u8; plan.push.push_range.map_or(0, |(_, end)| end as usize)]; - for f in &plan.push.fields { - let PushLoc::Push { offset } = f.loc else { - panic!("{:?} spilled to the ArgumentTable", f.field); - }; - let at = offset as usize; - match f.field { - PushField::RootTableAddress => push[at..at + 8].copy_from_slice(&TABLE.to_le_bytes()), - PushField::ExecutionStatusAddress => { - push[at..at + 8].copy_from_slice(&STATUS.to_le_bytes()) - } - // A zero residual (every slot is bound at its start), and a single region. - PushField::SlotBindOffset(_) | PushField::DispatchRegion => {} - other => panic!("unexpected push field {other:?}"), - } - } - push -} - -/// The status buffer, at its device address. -fn status() -> Buffer { - Buffer { - slot: None, - address: Some(STATUS), - bytes: ExecutionStatus::initial().to_vec(), - } -} - -/// One thread's parameters ([`compute_kernel`]). -#[derive(Clone, Copy, Debug)] -struct Params { - index: u32, - binding: u32, - length: u32, - tg_binding: u32, - stride: i64, - grid_x: u32, -} - -impl Params { - fn valid(t: u32) -> Params { - Params { - index: (t + 1) % THREADS, - binding: t % 2, - length: 16 * (t + 1), - tg_binding: t % 3, - stride: -1, - grid_x: 5 + t, - } - } - - fn bytes(self) -> Vec { - let mut b = Vec::with_capacity(32); - for w in [self.index, self.binding, self.length, self.tg_binding] { - b.extend_from_slice(&w.to_le_bytes()); - } - b.extend_from_slice(&self.stride.to_le_bytes()); - b.extend_from_slice(&self.grid_x.to_le_bytes()); - b.extend_from_slice(&0u32.to_le_bytes()); - b - } -} - -/// The little-endian `u32`s of `bytes`. -fn words(bytes: &[u8]) -> Vec { - bytes - .as_chunks::<4>() - .0 - .iter() - .map(|w| u32::from_le_bytes(*w)) - .collect() -} - -/// What one run left: the record buffer (its header and records), its written flags, a copy's -/// source record buffer, the status words, and the sink. -struct Run { - records: Vec, - flags: Vec, - source: Option>, - status: Vec, - sink: Vec, -} - -/// Run `m` (planned as `plan`) over `THREADS` threads with record buffer `records` (initialized) -/// resident at `RECORDS_GUEST` when `resident`, the argument buffer naming it by its ID, and each -/// thread's `params`. -fn run_encoder( - plan: &Plan, - m: &TypedModule, - records: Vec, - params: &[Params], - resident: bool, -) -> Result { - let mut enc = RECORDS_ID.to_le_bytes().to_vec(); - enc.extend_from_slice(&TOKEN.to_le_bytes()); - let params: Vec = params.iter().flat_map(|p| p.bytes()).collect(); - run_records(plan, m, enc, records, None, params, resident) -} - -/// [`run_encoder`] with argument buffer `enc`, the parameters' bytes `params`, and a second -/// record buffer `source` resident at `SOURCE_GUEST`, when there is one. The record buffer holds -/// a written flag a command past its records, each clear (`written_flag_offset`). -fn run_records( - plan: &Plan, - m: &TypedModule, - enc: Vec, - mut records: Vec, - source: Option>, - params: Vec, - resident: bool, -) -> Result { - let length = records.len(); - let commands = (length - COMMAND_BUFFER_HEADER_BYTES) / COMMAND_BYTES; - assert_eq!( - written_flag_offset(commands as u32, 0), - length as u64, - "the flags follow the records" - ); - records.resize(length + commands * WRITTEN_FLAG_BYTES, 0); - let mut set = vec![ - (DATA_HOST, DATA_GUEST, DATA_BYTES), - (CONSTS_HOST, CONSTS_GUEST, CONSTS_BYTES), - ]; - if resident { - set.push((RECORDS_HOST, RECORDS_GUEST, records.len() as u64)); - } - if let Some(source) = &source { - set.push((SOURCE_HOST, SOURCE_GUEST, source.len() as u64)); - } - set.sort_by_key(|e| e.1); - let mut spec = BTreeMap::new(); - spec.insert(SpecKey::LocalSize(Axis::X), u64::from(THREADS)); - spec.insert(SpecKey::LocalSize(Axis::Y), 1); - spec.insert(SpecKey::LocalSize(Axis::Z), 1); - spec.insert(SpecKey::FlatLocalSize, u64::from(THREADS)); - let mut buffers = vec![ - Buffer { - slot: Some(slot(0)), - address: None, - bytes: enc, - }, - Buffer { - slot: Some(slot(1)), - address: Some(DATA_HOST), - bytes: vec![0; DATA_BYTES as usize], - }, - Buffer { - slot: Some(slot(2)), - address: Some(CONSTS_HOST), - bytes: vec![0; CONSTS_BYTES as usize], - }, - Buffer { - slot: Some(slot(3)), - address: None, - bytes: params, - }, - Buffer { - slot: None, - address: Some(TABLE), - bytes: root_table(&set), - }, - Buffer { - slot: None, - address: Some(SINK), - bytes: vec![0; 64], - }, - status(), - Buffer { - slot: None, - address: Some(RECORDS_HOST), - bytes: records, - }, - ]; - let copies = source.is_some(); - if let Some(bytes) = source { - buffers.push(Buffer { - slot: None, - address: Some(SOURCE_HOST), - bytes, - }); - } - let res = Resources { - buffers, - push: push_bytes(plan), - spec, - }; - let out = run(m, &Config::default(), res)?; - let (records, flags) = out.buffers[7].split_at(length); - Ok(Run { - records: records.to_vec(), - flags: words(flags), - source: copies.then(|| out.buffers[8].clone()), - status: out.buffers[6] - .as_chunks::<4>() - .0 - .iter() - .map(|w| u32::from_le_bytes([w[0], w[1], w[2], w[3]])) - .collect(), - sink: out.buffers[5].clone(), - }) -} - -const OWNED: Inheritance = Inheritance { - pipeline: StateSource::Command, - buffers: StateSource::Command, -}; - -fn compute_descriptor(dynamic: bool) -> CommandDescriptor { - CommandDescriptor::Compute { - dispatch: ComputeDispatch::Both, - max_buffer_bind_count: 3, - max_threadgroup_memory_bind_count: 3, - support_dynamic_attribute_stride: dynamic, - } -} - -/// Initialized storage for `THREADS` commands under `descriptor` and `inheritance`. -fn storage(descriptor: &CommandDescriptor, inheritance: Inheritance) -> Vec { - let mut bytes = vec![0xa5; COMMAND_BUFFER_HEADER_BYTES + THREADS as usize * COMMAND_BYTES]; - CommandBuffer::initialize(&mut bytes, THREADS, descriptor, inheritance).expect("initialize"); - bytes -} - -/// The record thread `t` with parameters `p` encodes ([`compute_kernel`]), its pipeline the -/// kernel's (`CommandRecord::kernel_pipeline`). -fn compute_record(t: u32, p: Params) -> CommandRecord { - let mut r = CommandRecord { - kernel_pipeline: true, - ..CommandRecord::default() - }; - let grid = [p.grid_x, 2, 3]; - r.action = if t % 2 == 1 { - Action::DispatchThreads { - grid, - local_size: [16, 2, 1], - } - } else { - r.barrier = true; - Action::DispatchThreadgroups { - grid, - local_size: [32, 1, 1], - } - }; - r.bindings.pipeline = NonZeroU64::new(TOKEN); - let kernel = r.bindings.buffers_mut(BufferStage::Kernel); - kernel[p.binding as usize] = Some(BufferBinding { - address: DATA_GUEST + 16 * u64::from(t), - attribute_stride: (p.stride != -1).then_some(p.stride as u64), - }); - kernel[p.binding as usize + 1] = plain(CONSTS_GUEST); - r.threadgroup_memory_lengths[p.tg_binding as usize] = p.length; - r -} - -/// The records of `bytes` (decoded under `descriptor` and the owned state) in index order. -fn decoded( - bytes: &[u8], - descriptor: &CommandDescriptor, -) -> Result, CommandBufferError> { - Ok(CommandBuffer::decode(bytes, descriptor, OWNED)? - .records(0..THREADS)? - .collect()) -} - -fn compiled(name: &str, text: &str) -> Option> { - let bc = assemble(name, text)?; - let (addressed, _) = profiles(); - assert!(!addressed.is_empty()); - Some( - addressed - .into_iter() - .map(|(stem, p)| { - let a = compile(&bc, "encode", &p).unwrap_or_else(|e| panic!("{stem}: {e}")); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{stem}: L3: {e}")); - let (plan, m) = typed_module(&bc, "encode", &p).expect("module"); - (stem, p, plan, m) - }) - .collect(), - ) -} - -/// On every profile with device addresses, the records a kernel encodes through its argument -/// buffer's command buffer decode exactly as the host contract states them: each thread's command -/// index, its kernel buffers (the device buffer's guest address at its displacement, the constant -/// buffer's, the static or dynamic stride), the pipeline state's token, the threadgroup length at -/// its binding as set (one not a multiple of 16 included), the dispatch (threadgroups with a -/// barrier, or threads), carried across blocks; the header and every untouched word as `initialize` -/// left them; and no write in the sink. Every command starts with a pipeline a reset retained, -/// which the pipeline setter replaces with its own, reported. -#[test] -fn encoded_compute_records_round_trip_through_the_host_contract() { - let Some(runs) = compiled("compute", &compute_kernel()) else { - return; - }; - for (stem, _, plan, m) in &runs { - for dynamic in [false, true] { - let descriptor = compute_descriptor(dynamic); - let params: Vec = (0..THREADS) - .map(|t| Params { - stride: if dynamic && t == 2 { 48 } else { -1 }, - length: if t == 3 { 20 } else { Params::valid(t).length }, - ..Params::valid(t) - }) - .collect(); - let retained = CommandRecord { - retained_pipeline: NonZeroU64::new(5), - ..CommandRecord::default() - }; - let initial = encoded(&descriptor, OWNED, &vec![retained; THREADS as usize]); - let run = run_encoder(plan, m, initial, ¶ms, true) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - let mut want = vec![CommandRecord::default(); THREADS as usize]; - for (t, p) in params.iter().enumerate() { - want[p.index as usize] = compute_record(t as u32, *p); - } - let got = decoded(&run.records, &descriptor) - .unwrap_or_else(|e| panic!("{stem} dynamic={dynamic}: {e}")); - assert_eq!(got, want, "{stem} dynamic={dynamic}"); - // The bytes are exactly the encoded records: nothing else was written. - let mut exact = storage(&descriptor, OWNED); - for (i, r) in want.iter().enumerate() { - let at = COMMAND_BUFFER_HEADER_BYTES + i * COMMAND_BYTES; - r.encode_into(&mut exact[at..at + COMMAND_BYTES]).unwrap(); - } - assert_eq!(run.records, exact, "{stem} dynamic={dynamic}: bytes"); - // Each written command's flag set, and only those. - let mut flags = vec![0; THREADS as usize]; - for p in ¶ms { - flags[p.index as usize] = 1; - } - assert_eq!(run.flags, flags, "{stem} dynamic={dynamic}: written flags"); - assert!(run.sink.iter().all(|b| *b == 0), "{stem}: sink written"); - assert_eq!( - run.status[StatusWord::ResidentMisses.index() as usize], - 0, - "{stem}: misses" - ); - } - } -} - -/// A render command's vertex buffer (static stride), fragment buffer, and draw decode under a -/// render descriptor. -#[test] -fn encoded_render_records_round_trip_through_the_host_contract() { - let Some(runs) = compiled("render", &render_kernel()) else { - return; - }; - let descriptor = CommandDescriptor::Render { - draws: RenderDraws::PRIMITIVES, - max_vertex_buffer_bind_count: 1, - max_fragment_buffer_bind_count: 2, - max_object_buffer_bind_count: 0, - max_mesh_buffer_bind_count: 0, - support_dynamic_attribute_stride: false, - }; - for (stem, _, plan, m) in &runs { - let run = run_encoder(plan, m, storage(&descriptor, OWNED), &[], true) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - let want: Vec = (0..THREADS) - .map(|t| { - let mut r = CommandRecord { - action: Action::DrawPrimitives { - primitive_type: 3, - vertex_start: 3 * t, - vertex_count: 3, - instance_count: 2, - base_instance: 5, - }, - ..CommandRecord::default() - }; - let address = DATA_GUEST + 16 * u64::from(t); - r.bindings.buffers_mut(BufferStage::Vertex)[0] = plain(address); - r.bindings.buffers_mut(BufferStage::Fragment)[1] = plain(address); - r - }) - .collect(); - let got = decoded(&run.records, &descriptor).unwrap_or_else(|e| panic!("{stem}: {e}")); - assert_eq!(got, want, "{stem}"); - } -} - -/// Each thread `t` resets command `t` (`air.reset_render_command`) where `reset`, else reads and -/// writes nothing. -fn render_reset_kernel(reset: bool) -> String { - let meta = COMPUTE_META.replace("compute_pipeline_state", "render_pipeline_state"); - let body = match reset { +/// A kernel whose body loads the argument buffer's command buffer (and, where `pipeline`, its +/// pipeline state as `%pso`), then calls `@air.{op}` on command `t` with `args` after the index; +/// `types` are those operands' types. +fn encoder_kernel(op: &str, args: &str, types: &str, pipeline: bool, meta: &str) -> String { + let pso = match pipeline { true => { - "%pc = getelementptr inbounds %enc, ptr addrspace(1) %enc, i64 0, i32 0 - %cmd = load ptr addrspace(1), ptr addrspace(1) %pc, align 8 - call void @air.reset_render_command(ptr addrspace(1) %cmd, i32 %t)" + " %pp = getelementptr inbounds %enc, ptr addrspace(1) %enc, i64 0, i32 1\n \ + %pso = load ptr addrspace(1), ptr addrspace(1) %pp, align 8\n" } false => "", }; @@ -840,578 +90,110 @@ fn render_reset_kernel(reset: bool) -> String { define void @encode(ptr addrspace(1) %enc, ptr addrspace(1) %data, ptr addrspace(2) %consts, ptr addrspace(1) %params, i32 %t) {{ entry: - {body} + %pc = getelementptr inbounds %enc, ptr addrspace(1) %enc, i64 0, i32 0 + %cmd = load ptr addrspace(1), ptr addrspace(1) %pc, align 8 +{pso} call void @air.{op}(ptr addrspace(1) %cmd, i32 %t{args}) ret void }} -declare void @air.reset_render_command(ptr addrspace(1), i32) +declare void @air.{op}(ptr addrspace(1), i32{types}) {meta}"# ) } -/// A GPU reset clears what a command may have set and nothing else: its command words, the -/// bindings below each stage's count in the header, and the words past the bindings -/// (`default_record`). Every record starts holding a draw, a barrier, a vertex and a fragment -/// binding below the counts (2 and 2), and threadgroup-length words; each byte of a binding past -/// the counts (vertex 2, fragment 2, every object and mesh one) holds a mark, which no writer of -/// the records puts there. After the reset every byte below the counts and of the words reads zero, -/// and every mark stands: the reset wrote 64 + 4 x 16 + 136 bytes of each record, not 2248. The -/// negative control: the same storage under a kernel that does not reset keeps every stale byte, -/// so the zeros are the reset's. +/// On every committed profile and Profile F, each encoder operation of a compute or a render +/// command is `Unsupported{GpuEncodedIndirectCommands, NotImplemented}`: no device lowers one. #[test] -fn a_reset_clears_the_command_words_and_the_counted_bindings_alone() { - let descriptor = CommandDescriptor::Render { - draws: RenderDraws::PRIMITIVES, - max_vertex_buffer_bind_count: 2, - max_fragment_buffer_bind_count: 2, - max_object_buffer_bind_count: 0, - max_mesh_buffer_bind_count: 0, - support_dynamic_attribute_stride: false, - }; - const MARK: u8 = 0xab; - let binding = |stage, slot: usize| { - let at = (layout::buffers(stage) + slot as u64 * layout::BINDING) as usize; - at..at + layout::BINDING as usize - }; - // Each record's ranges a reset clears, and the marked ones it leaves. - let words = 0..layout::buffers(BufferStage::Kernel) as usize; - let mut cleared = vec![words]; - let mut marked = Vec::new(); - for slot in 0..BINDING_COUNT { - let below = slot < 2; - for stage in [BufferStage::Vertex, BufferStage::Fragment] { - match below { - true => cleared.push(binding(stage, slot)), - false => marked.push(binding(stage, slot)), - } - } - marked.push(binding(BufferStage::Mesh, slot)); - marked.push(binding(BufferStage::Object, slot)); - } - cleared.push(layout::THREADGROUP as usize..COMMAND_BYTES); - let mut stale = storage(&descriptor, OWNED); - for t in 0..THREADS as usize { - let record = COMMAND_BUFFER_HEADER_BYTES + t * COMMAND_BYTES; - for range in &cleared { - stale[record + range.start..record + range.end].fill(0x5a); - } - for range in &marked { - stale[record + range.start..record + range.end].fill(MARK); - } - } - for (reset, stem) in [(true, "reset"), (false, "unreset")] { - let Some(runs) = compiled(stem, &render_reset_kernel(reset)) else { - return; - }; - for (profile, _, plan, m) in &runs { - let run = run_encoder(plan, m, stale.clone(), &[], true) - .unwrap_or_else(|e| panic!("{profile}: {e}")); - for t in 0..THREADS as usize { - let record = COMMAND_BUFFER_HEADER_BYTES + t * COMMAND_BYTES; - let bytes = &run.records[record..record + COMMAND_BYTES]; - for range in &cleared { - let want = match reset { - true => 0, - false => 0x5a, - }; - let got = &bytes[range.clone()]; - assert!( - got.iter().all(|&b| b == want), - "{profile} {stem} {t} {range:?}" - ); - } - for range in &marked { - let got = &bytes[range.clone()]; - assert!( - got.iter().all(|&b| b == MARK), - "{profile} {stem} {t} {range:?}" - ); - } - } - } - } -} - -/// `line` without the `i64` operand of its buffer setter: a declaration's `, i64` or a call's -/// `, i64 `. -fn drop_stride(line: &str) -> String { - let Some(at) = line.find(", i64") else { - return line.to_string(); - }; - let rest = &line[at + 2..]; - let end = rest.find(", ").expect("an operand follows the stride"); - format!("{}{}", &line[..at], &rest[end..]) -} - -/// `text` as AIR 2.5 (Metal compiler 31001.723) spells it: its kernel and vertex buffer setters -/// declared and called without the attribute stride, MSL's plain setter, and the module's AIR -/// version 2.5 of language Metal 2.4. -fn stride_less(text: &str) -> String { - let lines = text.lines().map(|line| { - let setter = ["@air.set_kernel_buffer_", "@air.set_vertex_buffer_"] - .iter() - .any(|family| line.contains(family)); - match setter { - true => drop_stride(line), - false => line.to_string(), - } - }); - let mut out = lines.collect::>().join("\n"); - for (from, to) in [ - ( - "!20 = !{i32 2, i32 8, i32 0}", - "!20 = !{i32 2, i32 5, i32 0}", - ), - ( - "!21 = !{!\"Metal\", i32 4, i32 0, i32 0}", - "!21 = !{!\"Metal\", i32 2, i32 4, i32 0}", - ), - ] { - assert!(out.contains(from), "{from}"); - out = out.replace(from, to); - } - assert!(!out.contains(", i64 %stride") && !out.contains("i64, i32)")); - out -} - -/// AIR 2.5's kernel and vertex buffer setters, which take no attribute stride (MSL's plain -/// setter), write exactly the records of today's form called with a stride of all ones, as Metal's -/// compiler spells the plain setter now, on every profile with device addresses: the buffer's -/// address at its slot and the pipeline's own stride, the slot `set_kernel_buffer` (Metal's -/// `setKernelBuffer:offset:atIndex:`) leaves on the host, over a dynamic stride set before too (the -/// kernel-side plain setter writes all ones over it). -#[test] -fn air_2_5_buffer_setters_write_the_plain_setters_records() { - let (Some(today_runs), Some(air25_runs)) = ( - compiled("compute", &compute_kernel()), - compiled("compute-air25", &stride_less(&compute_kernel())), - ) else { - return; - }; - for ((stem, _, sp, sm), (_, _, pp, pm)) in today_runs.iter().zip(&air25_runs) { - for dynamic in [false, true] { - let descriptor = compute_descriptor(dynamic); - let params: Vec = (0..THREADS).map(Params::valid).collect(); - // Each command's slot holds a dynamic stride before, where the descriptor allows one. - let before: Vec = (0..THREADS) - .map(|i| { - let mut r = CommandRecord::default(); - if dynamic { - let at = params.iter().find(|p| p.index == i).expect("a writer"); - r.bindings.buffers_mut(BufferStage::Kernel)[at.binding as usize] = - Some(BufferBinding { - address: DATA_GUEST, - attribute_stride: Some(48), - }); - } - r - }) - .collect(); - let initial = encoded(&descriptor, OWNED, &before); - let today = run_encoder(sp, sm, initial.clone(), ¶ms, true) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - let air25 = run_encoder(pp, pm, initial, ¶ms, true) - .unwrap_or_else(|e| panic!("{stem} AIR 2.5: {e}")); - assert_eq!(air25.records, today.records, "{stem} dynamic={dynamic}"); - let mut want = vec![CommandRecord::default(); THREADS as usize]; - for (t, p) in params.iter().enumerate() { - want[p.index as usize] = compute_record(t as u32, *p); - let kernel = want[p.index as usize] - .bindings - .buffers_mut(BufferStage::Kernel); - let address = DATA_GUEST + 16 * t as u64; - assert_eq!(kernel[p.binding as usize], plain(address), "{stem}"); - } - let got = decoded(&air25.records, &descriptor) - .unwrap_or_else(|e| panic!("{stem} dynamic={dynamic}: {e}")); - assert_eq!(got, want, "{stem} dynamic={dynamic}"); - assert!(air25.sink.iter().all(|b| *b == 0), "{stem}: sink written"); - } - } - let (Some(today_runs), Some(air25_runs)) = ( - compiled("render", &render_kernel()), - compiled("render-air25", &stride_less(&render_kernel())), - ) else { - return; - }; - let descriptor = CommandDescriptor::Render { - draws: RenderDraws::PRIMITIVES, - max_vertex_buffer_bind_count: 1, - max_fragment_buffer_bind_count: 2, - max_object_buffer_bind_count: 0, - max_mesh_buffer_bind_count: 0, - support_dynamic_attribute_stride: false, - }; - for ((stem, _, sp, sm), (_, _, pp, pm)) in today_runs.iter().zip(&air25_runs) { - let today = run_encoder(sp, sm, storage(&descriptor, OWNED), &[], true) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - let air25 = run_encoder(pp, pm, storage(&descriptor, OWNED), &[], true) - .unwrap_or_else(|e| panic!("{stem} AIR 2.5: {e}")); - assert_eq!(air25.records, today.records, "{stem}"); - let got = decoded(&air25.records, &descriptor).unwrap_or_else(|e| panic!("{stem}: {e}")); - for (t, r) in got.iter().enumerate() { - let address = DATA_GUEST + 16 * t as u64; - assert_eq!( - r.bindings.buffers(BufferStage::Vertex)[0], - plain(address), - "{stem}" - ); - } - } -} - -/// A render descriptor of mesh draws (of threadgroups where `threadgroups`, else of threads) -/// alone, with one object and one mesh buffer, `primitive` vertex buffers and twice as many -/// fragment buffers. -fn mesh_descriptor(threadgroups: bool, primitive: u32) -> CommandDescriptor { - CommandDescriptor::Render { - draws: RenderDraws { - primitives: false, - mesh_threadgroups: threadgroups, - mesh_threads: !threadgroups, - ..RenderDraws::PRIMITIVES - }, - max_vertex_buffer_bind_count: primitive, - max_fragment_buffer_bind_count: 2 * primitive, - max_object_buffer_bind_count: 1, - max_mesh_buffer_bind_count: 1, - support_dynamic_attribute_stride: false, - } -} - -/// A kernel's mesh draws of either kind decode under a render descriptor of either mesh kind, whose -/// records hold both (a Metal probe): the grid and the object and mesh threadgroups' threads, the -/// barrier set or cleared, the pipeline state's token, the object buffer's guest address (device -/// memory) and the mesh buffer's (constant memory), which take the words of a compute command's -/// kernel buffers. Under a descriptor of draws of primitives, whose records do not hold them, the -/// header's fault flag fails the decode, as the GPU faults on Metal. -#[test] -fn encoded_mesh_draws_round_trip_through_the_host_contract() { - let Some(runs) = compiled("render_mesh", &render_mesh_kernel()) else { - return; - }; - for (stem, _, plan, m) in &runs { - for threadgroups in [true, false] { - let descriptor = mesh_descriptor(threadgroups, 0); - let run = run_encoder(plan, m, storage(&descriptor, OWNED), &[], true) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - let want: Vec = (0..THREADS) - .map(|t| { - let action = if t % 2 == 0 { - Action::DrawMeshThreadgroups { - threadgroups: [t + 1, 2, 1], - object_threads: [4, 1, 1], - mesh_threads: [2, 1, 1], - } - } else { - Action::DrawMeshThreads { - threads: [12, 4, 1], - object_threads: [1, 1, 1], - mesh_threads: [4, 2, 1], - } - }; - let mut r = CommandRecord { - action, - barrier: t % 2 == 0, - ..CommandRecord::default() - }; - r.bindings.pipeline = NonZeroU64::new(TOKEN); - r.kernel_pipeline = true; - r.bindings.buffers_mut(BufferStage::Object)[0] = - plain(DATA_GUEST + 16 * u64::from(t)); - r.bindings.buffers_mut(BufferStage::Mesh)[0] = plain(CONSTS_GUEST); - r - }) - .collect(); - let got = decoded(&run.records, &descriptor) - .unwrap_or_else(|e| panic!("{stem} threadgroups={threadgroups}: {e}")); - assert_eq!(got, want, "{stem} threadgroups={threadgroups}"); - } - let primitives = CommandDescriptor::Render { - draws: RenderDraws::PRIMITIVES, - max_vertex_buffer_bind_count: 0, - max_fragment_buffer_bind_count: 0, - max_object_buffer_bind_count: 1, - max_mesh_buffer_bind_count: 1, - support_dynamic_attribute_stride: false, - }; - let run = run_encoder(plan, m, storage(&primitives, OWNED), &[], true) - .unwrap_or_else(|e| panic!("{stem} primitives: {e}")); - assert_eq!( - decoded(&run.records, &primitives).err(), - Some(CommandBufferError::EncodingFault(1)), - "{stem} primitives" - ); - } -} - -/// A kernel's draw of primitives on a buffer of mesh draws alone is dropped: it writes nothing and -/// sets no fault, as it draws nothing on Metal without a fault (a Metal probe); its buffer setters -/// write as on any render buffer. -#[test] -fn a_draw_of_primitives_on_a_buffer_of_mesh_draws_is_dropped() { - let Some(runs) = compiled("render_dropped", &render_kernel()) else { - return; - }; - for (stem, _, plan, m) in &runs { - let descriptor = mesh_descriptor(true, 1); - let run = run_encoder(plan, m, storage(&descriptor, OWNED), &[], true) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - let want: Vec = (0..THREADS) - .map(|t| { - let mut r = CommandRecord::default(); - let address = DATA_GUEST + 16 * u64::from(t); - r.bindings.buffers_mut(BufferStage::Vertex)[0] = plain(address); - r.bindings.buffers_mut(BufferStage::Fragment)[1] = plain(address); - r - }) - .collect(); - let got = decoded(&run.records, &descriptor).unwrap_or_else(|e| panic!("{stem}: {e}")); - assert_eq!(got, want, "{stem}"); - } -} - -/// A write the descriptor policy does not allow sets the header's fault flag and writes nothing of -/// its own, so `decode` fails the run as an encoding fault: each invalid parameter alone, a compute -/// descriptor that inherits the pipeline, and a render descriptor (every compute operation is -/// outside its policy). -#[test] -fn a_write_outside_the_descriptor_policy_faults_and_writes_nothing() { - let Some(runs) = compiled("faults", &compute_kernel()) else { - return; - }; - let invalid: [Spoil; 4] = [ - ("index at capacity", |p| p.index = THREADS), - ("binding past its count", |p| p.binding = 2), - ("threadgroup binding past its count", |p| p.tg_binding = 3), - ("dynamic stride not enabled", |p| p.stride = 32), - ]; - for (stem, _, plan, m) in &runs { - let descriptor = compute_descriptor(false); - for (what, spoil) in invalid { - let mut params: Vec = (0..THREADS).map(Params::valid).collect(); - spoil(&mut params[1]); - let run = run_encoder(plan, m, storage(&descriptor, OWNED), ¶ms, true) - .unwrap_or_else(|e| panic!("{stem} {what}: {e}")); - assert_eq!( - decoded(&run.records, &descriptor).err(), - Some(CommandBufferError::EncodingFault(1)), - "{stem} {what}" - ); - // Thread 1's own command keeps the words of every write that faulted. - if what == "index at capacity" { - let mut want = storage(&descriptor, OWNED); - want[4..8].copy_from_slice(&1u32.to_le_bytes()); - for (t, p) in params.iter().enumerate().filter(|(t, _)| *t != 1) { - let at = COMMAND_BUFFER_HEADER_BYTES + p.index as usize * COMMAND_BYTES; - compute_record(t as u32, *p) - .encode_into(&mut want[at..at + COMMAND_BYTES]) - .unwrap(); - } - assert_eq!(run.records, want, "{stem} {what}"); - // Thread 1's writes all faulted: the flags of the others' commands alone are set. - let mut flags = vec![0; THREADS as usize]; - for (_, p) in params.iter().enumerate().filter(|(t, _)| *t != 1) { - flags[p.index as usize] = 1; - } - assert_eq!(run.flags, flags, "{stem} {what}: written flags"); - } - } - let inherit = Inheritance { - pipeline: StateSource::Parent, - buffers: StateSource::Command, - }; - let params: Vec = (0..THREADS).map(Params::valid).collect(); - let run = run_encoder(plan, m, storage(&descriptor, inherit), ¶ms, true) - .unwrap_or_else(|e| panic!("{stem} inherited: {e}")); - assert_eq!( - CommandBuffer::decode(&run.records, &descriptor, inherit).err(), - Some(CommandBufferError::EncodingFault(1)), - "{stem} inherited pipeline" - ); - let render = CommandDescriptor::Render { - draws: RenderDraws::PRIMITIVES, - max_vertex_buffer_bind_count: 3, - max_fragment_buffer_bind_count: 3, - max_object_buffer_bind_count: 0, - max_mesh_buffer_bind_count: 0, - support_dynamic_attribute_stride: false, - }; - let initial = storage(&render, OWNED); - let run = run_encoder(plan, m, initial.clone(), ¶ms, true) - .unwrap_or_else(|e| panic!("{stem} render: {e}")); - let mut want = initial; - want[4..8].copy_from_slice(&1u32.to_le_bytes()); - assert_eq!(run.records, want, "{stem} render descriptor"); - assert_eq!( - run.flags, - vec![0; THREADS as usize], - "{stem} render descriptor: no written flag" - ); - } -} - -/// A record buffer no resident allocation holds is root 0: nothing of it is read or written (the -/// header loads read 0, so every write faults into the sink), and each operation's access is -/// counted as a resident-set miss, which the executor reads as no evidence. -#[test] -fn a_record_buffer_outside_the_resident_set_is_contained_and_counted() { - let Some(runs) = compiled("miss", &compute_kernel()) else { - return; - }; - for (stem, _, plan, m) in &runs { - let descriptor = compute_descriptor(false); - let initial = storage(&descriptor, OWNED); - let params: Vec = (0..THREADS).map(Params::valid).collect(); - let run = run_encoder(plan, m, initial.clone(), ¶ms, false) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - assert_eq!(run.records, initial, "{stem}"); - // One per operation: six for an even thread (with the barrier), five for an odd one. - assert_eq!( - run.status[StatusWord::ResidentMisses.index() as usize], - (0..THREADS).map(|t| 6 - t % 2).sum::(), - "{stem}" - ); - assert!( - StatusBits(run.status[StatusWord::Status.index() as usize]) - .contains(StatusBits::RESIDENT_MISS), - "{stem}" - ); - } -} - -/// Without device addresses every encoder operation is `GpuEncodedIndirectCommands`, at the first -/// one, naming what the profile lacks of Profile A. -#[test] -fn encoding_without_device_addresses_names_what_the_profile_lacks() { - let Some(bc) = assemble("floor", &compute_kernel()) else { - return; - }; - let (_, floor) = profiles(); - assert!(!floor.is_empty()); - for (stem, p) in floor { - let Error::Unsupported(u) = compile(&bc, "encode", &p).expect_err(&stem) else { - panic!("{stem}: not Unsupported"); - }; - let want = Unsupported::needs_any_of( - Feature::GpuEncodedIndirectCommands, - vec![p.addressed_needs()], - ); - assert!( - !matches!(u.needs, Needs::NotImplemented | Needs::NotRepresentable), - "{stem}" - ); - assert_eq!((u.feature, &u.needs), (want.feature, &want.needs), "{stem}"); - assert_eq!( - u.location - .as_ref() - .and_then(|l| l.in_function()) - .map(|(_, b, i)| (b, i)), - Some((Some(0), Some(19))), - "{stem}: the first encoder operation" - ); - } -} - -/// A kernel's render state setter (cull mode, depth bias, depth clip mode, front-facing winding, -/// triangle fill mode, depth/stencil state; the declarations Metal's compiler writes) decodes, and -/// on every profile with device addresses the lowering refuses it -/// `NotImplemented(IndirectRenderState)`: the record holds no render state, and Metal's compiler -/// refuses every one on an M4. The depth/stencil state is the argument buffer's second member, -/// `air.depth_stencil_state`, in place of a pipeline state. -#[test] -fn render_state_setters_refuse_as_indirect_render_state() { +fn every_encoder_operation_is_refused_on_every_profile() { let render = COMPUTE_META.replace("compute_pipeline_state", "render_pipeline_state"); - let depth_stencil = COMPUTE_META.replace("compute_pipeline_state", "depth_stencil_state"); - let state = " %ps = getelementptr inbounds %enc, ptr addrspace(1) %enc, i64 0, i32 1\n \ - %ds = load ptr addrspace(1), ptr addrspace(1) %ps, align 8\n"; - for (name, setter, types, values, prelude, meta) in [ + let grid = "<3 x i32> "; + let groups = format!(", {grid}, <3 x i32> "); + let mesh = format!(", {grid}, {grid}, {grid}"); + let vec3 = ", <3 x i32>, <3 x i32>"; + let vec3s = ", <3 x i32>, <3 x i32>, <3 x i32>"; + let ops: [(&str, &str, &str, bool, &str); 10] = [ + ("set_barrier_compute_command", "", "", false, COMPUTE_META), + ( + "concurrent_dispatch_threadgroups_compute_command", + &groups, + vec3, + false, + COMPUTE_META, + ), + ( + "set_kernel_buffer_compute_command.p1i8", + ", ptr addrspace(1) %data, i64 -1, i32 0", + ", ptr addrspace(1), i64, i32", + false, + COMPUTE_META, + ), + ( + "set_pipeline_state_compute_command", + ", ptr addrspace(1) %pso", + ", ptr addrspace(1)", + true, + COMPUTE_META, + ), + ("reset_compute_command", "", "", false, COMPUTE_META), + ( + "copy_compute_command", + ", ptr addrspace(1) %cmd, i32 0", + ", ptr addrspace(1), i32", + false, + COMPUTE_META, + ), + ( + "set_vertex_buffer_render_command.p1i8", + ", ptr addrspace(1) %data, i64 -1, i32 0", + ", ptr addrspace(1), i64, i32", + false, + &render, + ), + ( + "draw_primitives_render_command", + ", i32 3, i32 0, i32 3, i32 1, i32 0", + ", i32, i32, i32, i32, i32", + false, + &render, + ), + ( + "draw_mesh_threadgroups_render_command", + &mesh, + vec3s, + false, + &render, + ), ( - "cull", "set_cull_mode_render_command", - "i32", - "i32 2", - "", + ", i32 2", + ", i32", + false, &render, ), - ( - "depth_bias", - "set_depth_bias_render_command", - "float, float, float", - "float 1.0, float 2.0, float 0.5", - "", - &render, - ), - ( - "depth_clip", - "set_depth_clip_mode_render_command", - "i32", - "i32 1", - "", - &render, - ), - ( - "winding", - "set_front_facing_winding_render_command", - "i32", - "i32 1", - "", - &render, - ), - ( - "fill", - "set_triangle_fill_mode_render_command", - "i32", - "i32 1", - "", - &render, - ), - ( - "depth_stencil", - "set_depth_stencil_state_render_command", - "ptr addrspace(1)", - "ptr addrspace(1) %ds", - state, - &depth_stencil, - ), - ] { - let text = format!( - r#"%enc = type {{ ptr addrspace(1), ptr addrspace(1) }} - -define void @encode(ptr addrspace(1) %enc, ptr addrspace(1) %data, ptr addrspace(2) %consts, ptr addrspace(1) %params, i32 %t) {{ -entry: - %pc = getelementptr inbounds %enc, ptr addrspace(1) %enc, i64 0, i32 0 - %cmd = load ptr addrspace(1), ptr addrspace(1) %pc, align 8 -{prelude} call void @air.{setter}(ptr addrspace(1) %cmd, i32 %t, {values}) - ret void -}} - -declare void @air.{setter}(ptr addrspace(1), i32, {types}) -{meta}"# - ); - let Some(bc) = assemble(name, &text) else { + ]; + let all = profiles(); + assert!(!all.is_empty()); + for (op, args, types, pipeline, meta) in ops { + let Some(bc) = assemble(op, &encoder_kernel(op, args, types, pipeline, meta)) else { return; }; - let (addressed, _) = profiles(); - assert!(!addressed.is_empty()); - let want = Unsupported::not_implemented(Feature::IndirectRenderState); - for (stem, p) in addressed { - let Error::Unsupported(u) = compile(&bc, "encode", &p).expect_err(&stem) else { - panic!("{name} on {stem}: not Unsupported"); + for (stem, p) in &all { + let Error::Unsupported(u) = compile(&bc, "encode", p).expect_err(stem) else { + panic!("{op} on {stem}: not Unsupported"); }; assert_eq!( - (u.feature, &u.needs), - (want.feature.clone(), &want.needs), - "{name} on {stem}" + (u.feature, u.needs), + (Feature::GpuEncodedIndirectCommands, Needs::NotImplemented), + "{op} on {stem}" ); } } } /// A kernel whose argument buffer holds a `depth_stencil_state` it never reads compiles on every -/// profile with device addresses, as Metal's compiler compiles such a kernel's draw on an M4; one -/// that reads the state for anything but a setter is refused `NotImplemented(IndirectRenderState)`, -/// the state's one use being a render command's. +/// committed profile, as Metal's compiler compiles such a kernel on an M4; one that reads the +/// state for anything but a setter is refused `NotImplemented(IndirectRenderState)`, the state's +/// one use being a render command's. #[test] fn a_depth_stencil_state_member_compiles_unread_and_is_refused_read() { let meta = COMPUTE_META.replace("compute_pipeline_state", "depth_stencil_state"); @@ -1421,17 +203,12 @@ fn a_depth_stencil_state_member_compiles_unread_and_is_refused_read() { define void @encode(ptr addrspace(1) %enc, ptr addrspace(1) %data, ptr addrspace(2) %consts, ptr addrspace(1) %params, i32 %t) {{ entry: - %pc = getelementptr inbounds %enc, ptr addrspace(1) %enc, i64 0, i32 0 - %cmd = load ptr addrspace(1), ptr addrspace(1) %pc, align 8 {body} ret void }} - -declare void @air.set_barrier_render_command(ptr addrspace(1), i32) {meta}"# ) }; - let unread = - kernel(" call void @air.set_barrier_render_command(ptr addrspace(1) %cmd, i32 %t)\n"); + let unread = kernel(""); let read = kernel( " %ps = getelementptr inbounds %enc, ptr addrspace(1) %enc, i64 0, i32 1\n \ %ds = load ptr addrspace(1), ptr addrspace(1) %ps, align 8\n \ @@ -1441,9 +218,9 @@ declare void @air.set_barrier_render_command(ptr addrspace(1), i32) else { return; }; - let (addressed, _) = profiles(); - assert!(!addressed.is_empty()); - for (stem, p) in addressed { + let all = committed_profiles().expect("profiles"); + assert!(!all.is_empty()); + for (stem, p) in all { if let Err(e) = compile(&unread, "encode", &p) { panic!("an unread depth/stencil state on {stem}: {e}"); } @@ -1457,885 +234,3 @@ declare void @air.set_barrier_render_command(ptr addrspace(1), i32) ); } } - -/// A kernel whose encoder argument buffer `{command_buffer commands; compute_pipeline_state -/// pipeline; ulong n;}` (Metal buffer 0, read-write) counts its threads in `n` with a `u64` -/// atomic, and sets a barrier on command `t`. -fn counted_kernel() -> String { - r#"%enc = type { ptr addrspace(1), ptr addrspace(1), i64 } - -define void @encode(ptr addrspace(1) %enc, ptr addrspace(1) %data, i32 %t) { -entry: - %pc = getelementptr inbounds %enc, ptr addrspace(1) %enc, i64 0, i32 0 - %cmd = load ptr addrspace(1), ptr addrspace(1) %pc, align 8 - call void @air.set_barrier_compute_command(ptr addrspace(1) %cmd, i32 %t) - %pn = getelementptr inbounds %enc, ptr addrspace(1) %enc, i64 0, i32 2 - %n = atomicrmw add ptr addrspace(1) %pn, i64 1 monotonic, align 8 - %w = trunc i64 %n to i32 - store i32 %w, ptr addrspace(1) %data, align 4 - ret void -} - -declare void @air.set_barrier_compute_command(ptr addrspace(1), i32) - -!air.kernel = !{!0} -!air.version = !{!20} -!air.language_version = !{!21} -!0 = !{ptr @encode, !1, !2} -!1 = !{} -!2 = !{!3, !7, !10} -!3 = !{i32 0, !"air.indirect_buffer", !"air.buffer_size", i32 24, !"air.location_index", i32 0, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.struct_type_info", !4, !"air.arg_type_size", i32 24, !"air.arg_type_align_size", i32 8, !"air.arg_type_name", !"Encoder", !"air.arg_name", !"enc"} -!4 = !{i32 0, i32 8, i32 0, !"command_buffer", !"commands", !"air.indirect_argument", !5, i32 8, i32 8, i32 0, !"compute_pipeline_state", !"pipeline", !"air.indirect_argument", !6, i32 16, i32 8, i32 0, !"ulong", !"n", !"air.indirect_argument", !11} -!5 = !{i32 0, !"air.command_buffer", !"air.location_index", i32 0, i32 1, !"air.arg_type_name", !"command_buffer", !"air.arg_name", !"commands"} -!6 = !{i32 1, !"air.compute_pipeline_state", !"air.location_index", i32 1, i32 1, !"air.arg_type_name", !"compute_pipeline_state", !"air.arg_name", !"pipeline"} -!11 = !{i32 2, !"air.indirect_constant", !"air.location_index", i32 2, i32 1, !"air.arg_type_name", !"ulong", !"air.arg_name", !"n"} -!7 = !{i32 1, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"data"} -!10 = !{i32 2, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"t"} -!20 = !{i32 2, i32 8, i32 0} -!21 = !{!"Metal", i32 4, i32 0, i32 0} -"# - .to_owned() -} - -/// An object word's load is named by the memory it reaches. Read through the argument buffer's -/// descriptor view, [`compute_kernel`]'s command-buffer and pipeline-state words are -/// `access.encode.word`; once a `u64` atomic on the buffer's counter lowers the buffer by device -/// address, the command-buffer word is `access.encode.word.psb`. A profile with device addresses -/// but no `u64` buffer atomics refuses the counter naming them. -#[test] -fn a_command_word_is_named_by_the_memory_it_reaches() { - let Some(runs) = compiled("view", &compute_kernel()) else { - return; - }; - for (stem, _, plan, _) in &runs { - let census = plan.census(); - let word = |name: &str| census.get(name).map_or(0, |(n, _)| *n); - assert_eq!(word("access.encode.word"), 2, "{stem}"); - assert_eq!(word("access.encode.word.psb"), 0, "{stem}"); - } - let Some(bc) = assemble("counted", &counted_kernel()) else { - return; - }; - let (addressed, _) = profiles(); - let mut compiled = 0; - for (stem, p) in addressed { - if !p.fields().leaf.buffer_int64_atomics { - let Error::Unsupported(u) = compile(&bc, "encode", &p).expect_err(&stem) else { - panic!("{stem}: not Unsupported"); - }; - assert_eq!(u.feature, Feature::Int64Atomics, "{stem}"); - continue; - } - let a = compile(&bc, "encode", &p).unwrap_or_else(|e| panic!("{stem}: {e}")); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{stem}: L3: {e}")); - let (plan, _) = typed_module(&bc, "encode", &p).expect("module"); - let census = plan.census(); - let word = |name: &str| census.get(name).map_or(0, |(n, _)| *n); - assert_eq!(word("access.encode.word.psb"), 1, "{stem}"); - assert_eq!(word("access.encode.word"), 0, "{stem}"); - assert_eq!(word("access.encode.barrier"), 1, "{stem}"); - compiled += 1; - } - assert!( - compiled > 0, - "no committed profile has device addresses and u64 atomics" - ); -} - -/// A kernel's `clear_barrier`, `set_stage_in_region`, `set_imageblock_size` and `reset` on a -/// compute command (the symbols and shapes Apple's compiler emits for `compute_command`'s members) -/// round-trip on every profile with device addresses: each even thread's -/// command, which they follow the dispatch of, decodes with its barrier cleared, its region, its -/// size (a width of 65535 held zero-extended), or as the default record but for the pipeline it -/// executes with, retained and reported cleared, and the bytes are exactly the encoded records. -#[test] -fn compute_command_setters_round_trip_through_the_host_contract() { - let barrier = "call void @air.set_barrier_compute_command(ptr addrspace(1) %cmd, i32 %index)"; - type Expect = fn(&mut CommandRecord); - let cases: [(&str, &str, &str, Expect); 4] = [ - ( - "clear", - "call void @air.clear_barrier_compute_command(ptr addrspace(1) %cmd, i32 %index)", - "declare void @air.clear_barrier_compute_command(ptr addrspace(1), i32)", - |r| r.barrier = false, - ), - ( - "stage-in", - "call void @air.set_stage_in_region_compute_command(ptr addrspace(1) %cmd, i32 %index, \ - <3 x i32> , <3 x i32> )", - "declare void @air.set_stage_in_region_compute_command(ptr addrspace(1), i32, \ - <3 x i32>, <3 x i32>)", - |r| { - r.barrier = false; - r.stage_in_region = [1, 2, 3, 4, 5, 6]; - }, - ), - ( - "imageblock", - "call void @air.set_imageblock_size_compute_command(ptr addrspace(1) %cmd, \ - i32 %index, <2 x i16> )", - "declare void @air.set_imageblock_size_compute_command(ptr addrspace(1), i32, \ - <2 x i16>)", - |r| { - r.barrier = false; - r.imageblock_size = [65535, 8]; - }, - ), - ( - "reset", - "call void @air.reset_compute_command(ptr addrspace(1) %cmd, i32 %index)", - "declare void @air.reset_compute_command(ptr addrspace(1), i32)", - // The pipeline the command executes with stays, reported cleared, and a kernel's - // still: the one its write resolved. - |r| { - *r = CommandRecord { - retained_pipeline: r.bindings.pipeline, - kernel_pipeline: r.kernel_pipeline, - ..CommandRecord::default() - } - }, - ), - ]; - for (name, call, declaration, expect) in cases { - let kernel = compute_kernel(); - assert_eq!(kernel.matches(barrier).count(), 1); - let kernel = kernel.replace(barrier, call).replace( - "declare void @air.set_barrier_compute_command(ptr addrspace(1), i32)", - declaration, - ); - let Some(runs) = compiled(name, &kernel) else { - return; - }; - let descriptor = compute_descriptor(false); - for (stem, _, plan, m) in &runs { - let params: Vec = (0..THREADS).map(Params::valid).collect(); - let run = run_encoder(plan, m, storage(&descriptor, OWNED), ¶ms, true) - .unwrap_or_else(|e| panic!("{name} on {stem}: {e}")); - let mut want = vec![CommandRecord::default(); THREADS as usize]; - for (t, p) in params.iter().enumerate() { - let mut r = compute_record(t as u32, *p); - if t % 2 == 0 { - expect(&mut r); - } - want[p.index as usize] = r; - } - let got = decoded(&run.records, &descriptor) - .unwrap_or_else(|e| panic!("{name} on {stem}: {e}")); - assert_eq!(got, want, "{name} on {stem}"); - let mut exact = storage(&descriptor, OWNED); - for (i, r) in want.iter().enumerate() { - let at = COMMAND_BUFFER_HEADER_BYTES + i * COMMAND_BYTES; - r.encode_into(&mut exact[at..at + COMMAND_BYTES]).unwrap(); - } - assert_eq!(run.records, exact, "{name} on {stem}: bytes"); - assert!(run.sink.iter().all(|b| *b == 0), "{name} on {stem}: sink"); - } - } -} - -/// A kernel whose argument buffer `{command_buffer commands; command_buffer source;}` (Metal -/// buffer 0, as [`compute_kernel`]'s) copies, in thread `t`, command `params[t].from` of `source` -/// onto command `params[t].index` of `commands` (`{u32 index, u32 from, ...}`, 32 bytes a -/// thread), then makes `after` of the copied command. -fn copy_kernel(after: &str) -> String { - let meta = COMPUTE_META - .replace( - r#"i32 8, i32 8, i32 0, !"compute_pipeline_state", !"pipeline""#, - r#"i32 8, i32 8, i32 0, !"command_buffer", !"source""#, - ) - .replace( - r#"!6 = !{i32 1, !"air.compute_pipeline_state", !"air.location_index", i32 1, i32 1, !"air.arg_type_name", !"compute_pipeline_state", !"air.arg_name", !"pipeline"}"#, - r#"!6 = !{i32 1, !"air.command_buffer", !"air.location_index", i32 1, i32 1, !"air.arg_type_name", !"command_buffer", !"air.arg_name", !"source"}"#, - ); - assert!( - !meta.contains("pipeline"), - "the source member replaced the pipeline's" - ); - format!( - r#"%enc = type {{ ptr addrspace(1), ptr addrspace(1) }} - -define void @encode(ptr addrspace(1) %enc, ptr addrspace(1) %data, ptr addrspace(2) %consts, ptr addrspace(1) %params, i32 %t) {{ -entry: - %pc = getelementptr inbounds %enc, ptr addrspace(1) %enc, i64 0, i32 0 - %cmd = load ptr addrspace(1), ptr addrspace(1) %pc, align 8 - %ps = getelementptr inbounds %enc, ptr addrspace(1) %enc, i64 0, i32 1 - %src = load ptr addrspace(1), ptr addrspace(1) %ps, align 8 - %t64 = zext i32 %t to i64 - %prm = getelementptr inbounds [8 x i32], ptr addrspace(1) %params, i64 %t64 - %index = load i32, ptr addrspace(1) %prm, align 8 - %p1 = getelementptr inbounds i32, ptr addrspace(1) %prm, i64 1 - %from = load i32, ptr addrspace(1) %p1, align 4 - call void @air.copy_compute_command(ptr addrspace(1) %cmd, i32 %index, ptr addrspace(1) %src, i32 %from) - {after} - ret void -}} - -declare void @air.copy_compute_command(ptr addrspace(1), i32, ptr addrspace(1), i32) -declare void @air.clear_barrier_compute_command(ptr addrspace(1), i32) -{meta}"# - ) -} - -/// Run a [`copy_kernel`]: thread `t` copies command `copies[t].1` onto command `copies[t].0`, from -/// the record buffer `source` when there is one, else within `records`. -fn run_copies( - plan: &Plan, - m: &TypedModule, - records: Vec, - source: Option>, - copies: [(u32, u32); THREADS as usize], -) -> Result { - let mut enc = RECORDS_ID.to_le_bytes().to_vec(); - let from = if source.is_some() { - SOURCE_ID - } else { - RECORDS_ID - }; - enc.extend_from_slice(&from.to_le_bytes()); - let mut params = Vec::new(); - for (index, from) in copies { - params.extend_from_slice(&index.to_le_bytes()); - params.extend_from_slice(&from.to_le_bytes()); - params.extend_from_slice(&[0; 24]); - } - run_records(plan, m, enc, records, source, params, true) -} - -/// Storage under `descriptor` and `inheritance` whose commands are `records`, as the host's -/// encoder writes them. -fn encoded( - descriptor: &CommandDescriptor, - inheritance: Inheritance, - records: &[CommandRecord], -) -> Vec { - let mut bytes = storage(descriptor, inheritance); - for (i, r) in records.iter().enumerate() { - let at = COMMAND_BUFFER_HEADER_BYTES + i * COMMAND_BYTES; - r.encode_into(&mut bytes[at..at + COMMAND_BYTES]).unwrap(); - } - bytes -} - -/// Four full compute commands: [`compute_record`]'s, command 2 with a dynamic stride, each with -/// a stage-in region and an imageblock size of its own. -fn copied_sources() -> Vec { - (0..THREADS) - .map(|t| { - let p = Params { - stride: if t == 2 { 48 } else { -1 }, - ..Params::valid(t) - }; - // The host encodes them: their pipelines are not a kernel's. - let mut r = compute_record(t, p); - r.kernel_pipeline = false; - r.stage_in_region = [t, 1, 2, 3 + t, 4, 5]; - r.imageblock_size = [8 + t as u16, 4]; - r - }) - .collect() -} - -/// A kernel's `copy_command` between buffers of equal descriptors (on Metal, M3 and M4: the -/// destination executes as its source, and a setter after the copy writes over it) copies the whole -/// record on every profile with device addresses: between two buffers (each command from another -/// index, over full commands), within one (two commands onto empty ones, two onto themselves), and -/// with the barrier cleared after the copy; the source is left as it was and the bytes are exactly -/// the copied records. -#[test] -fn copied_commands_round_trip_between_equal_descriptors() { - let clear = "call void @air.clear_barrier_compute_command(ptr addrspace(1) %cmd, i32 %index)"; - let descriptor = compute_descriptor(true); - let sources = copied_sources(); - let full = encoded(&descriptor, OWNED, &sources); - for (name, after) in [("copy", ""), ("copy then clear", clear)] { - let Some(runs) = compiled(name, ©_kernel(after)) else { - return; - }; - let cleared = |mut r: CommandRecord| { - if !after.is_empty() { - r.barrier = false; - } - r - }; - for (stem, _, plan, m) in &runs { - let census = plan.census(); - assert_eq!(census.get("access.encode.copy").map(|c| c.0), Some(1)); - // Between two buffers: command t from command 3 - t, over full commands. - let run = run_copies( - plan, - m, - full.clone(), - Some(full.clone()), - [(0, 3), (1, 2), (2, 1), (3, 0)], - ) - .unwrap_or_else(|e| panic!("{name} on {stem}: {e}")); - let want: Vec = sources.iter().rev().cloned().map(cleared).collect(); - assert_eq!( - run.records, - encoded(&descriptor, OWNED, &want), - "{name} on {stem}" - ); - assert_eq!(run.source.as_ref(), Some(&full), "{name} on {stem}: source"); - assert_eq!(decoded(&run.records, &descriptor).unwrap(), want); - // Each destination's written flag set. - let flags = vec![1; THREADS as usize]; - assert_eq!(run.flags, flags, "{name} on {stem}: written flags"); - // Within one buffer: commands 0 and 1 onto the empty 2 and 3, and onto themselves. - let initial = encoded(&descriptor, OWNED, &sources[..2]); - let run = run_copies(plan, m, initial, None, [(2, 0), (3, 1), (0, 0), (1, 1)]) - .unwrap_or_else(|e| panic!("{name} on {stem}: {e}")); - let pair = [sources[0].clone(), sources[1].clone()].map(cleared); - let want = [pair.clone(), pair].concat(); - assert_eq!( - run.records, - encoded(&descriptor, OWNED, &want), - "{name} on {stem}" - ); - assert_eq!(run.flags, flags, "{name} on {stem}: written flags"); - assert!(run.sink.iter().all(|b| *b == 0), "{name} on {stem}: sink"); - } - } -} - -/// A copy into a buffer that inherits its pipeline and its buffers from one that inherits neither -/// (of the same descriptor otherwise, the destination binding no kernel buffer) copies every word -/// but the pipeline's and the buffer bindings', which stay the destination's: on Metal (M3 and M4) -/// the destination executes the source's dispatch, barrier and threadgroup length with the -/// encoder's pipeline and buffers. The records decode under the destination's inheritance. The -/// destination holds five commands and the copies land on commands 1 to 4: a copy onto command 0 -/// faults (Metal's runs it with zero grid sizes; the fault test). -#[test] -fn a_copy_into_a_buffer_that_inherits_keeps_its_pipeline_and_buffers() { - let Some(runs) = compiled("into_inheriting", ©_kernel("")) else { - return; - }; - let source_descriptor = compute_descriptor(false); - let descriptor = CommandDescriptor::Compute { - dispatch: ComputeDispatch::Both, - max_buffer_bind_count: 0, - max_threadgroup_memory_bind_count: 3, - support_dynamic_attribute_stride: false, - }; - let inherit = Inheritance { - pipeline: StateSource::Parent, - buffers: StateSource::Parent, - }; - // The host encodes them: their pipelines are not a kernel's. - let sources: Vec = (0..THREADS) - .map(|t| CommandRecord { - kernel_pipeline: false, - ..compute_record(t, Params::valid(t)) - }) - .collect(); - let source = encoded(&source_descriptor, OWNED, &sources); - let capacity = THREADS + 1; - let mut initial = vec![0xa5; COMMAND_BUFFER_HEADER_BYTES + capacity as usize * COMMAND_BYTES]; - CommandBuffer::initialize(&mut initial, capacity, &descriptor, inherit).expect("initialize"); - let mut want: Vec = sources - .iter() - .rev() - .map(|r| CommandRecord { - bindings: Default::default(), - ..r.clone() - }) - .collect(); - want.insert(0, CommandRecord::default()); - let mut bytes = initial.clone(); - for (i, r) in want.iter().enumerate() { - let at = COMMAND_BUFFER_HEADER_BYTES + i * COMMAND_BYTES; - r.encode_into(&mut bytes[at..at + COMMAND_BYTES]).unwrap(); - } - for (stem, _, plan, m) in &runs { - let run = run_copies( - plan, - m, - initial.clone(), - Some(source.clone()), - [(1, 3), (2, 2), (3, 1), (4, 0)], - ) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - assert_eq!(run.records, bytes, "{stem}"); - let got: Vec = CommandBuffer::decode(&run.records, &descriptor, inherit) - .unwrap_or_else(|e| panic!("{stem}: {e}")) - .records(0..capacity) - .unwrap() - .collect(); - assert_eq!(got, want, "{stem}"); - assert_eq!(run.source.as_ref(), Some(&source), "{stem}: source"); - } -} - -/// A copy from a command that reports no pipeline (none set, or one its reset retained) keeps the -/// destination's pipeline as it was, reported or retained, and copies every other word; a copy from -/// one that reports a pipeline replaces the destination's (Metal's copy, measured on the M3 Max and -/// the M4: a copy of a fresh or a reset command leaves the destination's pipeline readable and -/// running). -#[test] -fn a_copy_from_a_command_without_a_pipeline_keeps_the_destinations() { - let Some(runs) = compiled("copy_pipelines", ©_kernel("")) else { - return; - }; - let descriptor = compute_descriptor(false); - let own = NonZeroU64::new(TOKEN); - let other = NonZeroU64::new(0x77); - let sources = copied_sources(); - let named = |mut r: CommandRecord, pipeline| { - r.bindings.pipeline = pipeline; - r - }; - let retaining = |mut r: CommandRecord, pipeline| { - r.bindings.pipeline = None; - r.retained_pipeline = pipeline; - r - }; - // Destination: full commands 0, 1 and 3 (pipeline `own`), command 2 reset (`own` retained). - let destination = [ - named(sources[0].clone(), own), - named(sources[1].clone(), own), - retaining(CommandRecord::default(), own), - named(sources[3].clone(), own), - ]; - // Source: 0 fresh, 1 reset with `other` retained, 2 fresh, 3 with `other` set. - let source = [ - CommandRecord::default(), - retaining(sources[1].clone(), other), - CommandRecord::default(), - named(sources[3].clone(), other), - ]; - let want = [ - named(CommandRecord::default(), own), - named(retaining(sources[1].clone(), None), own), - retaining(CommandRecord::default(), own), - named(sources[3].clone(), other), - ]; - for (stem, _, plan, m) in &runs { - let run = run_copies( - plan, - m, - encoded(&descriptor, OWNED, &destination), - Some(encoded(&descriptor, OWNED, &source)), - [(0, 0), (1, 1), (2, 2), (3, 3)], - ) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - assert_eq!(decoded(&run.records, &descriptor).unwrap(), want, "{stem}"); - assert_eq!(run.records, encoded(&descriptor, OWNED, &want), "{stem}"); - } -} - -/// A copy whose result on Metal depends on its private record layout, or was not measured, sets the -/// destination's sticky fault and copies nothing, so `decode` fails the run as an encoding fault: a -/// copy between descriptors of other dispatch types (on Metal the destination ran a dispatch its -/// descriptor does not allow), of fewer bindings (Metal's overwrote the next command), from a -/// buffer that inherits (Metal's executed a garbage pipeline), of another dynamic stride, into one -/// that inherits the pipeline alone or binds kernel buffers while inheriting them (not measured), -/// onto command 0 of one that inherits both (Metal's ran it with `threads_per_grid` and -/// `threadgroups_per_grid` zero, M3 Max and M4), a source or destination index at its capacity -/// (Metal's corrupted a command), and into a render command buffer. Every thread makes the same -/// copy, from full commands. -#[test] -fn a_copy_whose_result_is_metals_private_layout_faults_and_copies_nothing() { - let Some(runs) = compiled("copy_faults", ©_kernel("")) else { - return; - }; - let compute = |dispatch, buffers, dynamic| CommandDescriptor::Compute { - dispatch, - max_buffer_bind_count: buffers, - max_threadgroup_memory_bind_count: 3, - support_dynamic_attribute_stride: dynamic, - }; - let pipeline = Inheritance { - pipeline: StateSource::Parent, - buffers: StateSource::Command, - }; - let both = Inheritance { - pipeline: StateSource::Parent, - buffers: StateSource::Parent, - }; - let render = CommandDescriptor::Render { - draws: RenderDraws::PRIMITIVES, - max_vertex_buffer_bind_count: 3, - max_fragment_buffer_bind_count: 3, - max_object_buffer_bind_count: 0, - max_mesh_buffer_bind_count: 0, - support_dynamic_attribute_stride: false, - }; - let owned = || compute(ComputeDispatch::Both, 3, false); - let groups = compute(ComputeDispatch::Threadgroups, 3, false); - let threads = compute(ComputeDispatch::Threads, 3, false); - // (what, destination, its inheritance, source, its inheritance, each thread's copy) - type Fault = ( - &'static str, - CommandDescriptor, - Inheritance, - CommandDescriptor, - Inheritance, - (u32, u32), - ); - let faults: [Fault; 10] = [ - ("other dispatch type", threads, OWNED, groups, OWNED, (0, 0)), - ( - "fewer bindings", - compute(ComputeDispatch::Both, 2, false), - OWNED, - owned(), - OWNED, - (0, 0), - ), - ( - "other dynamic stride", - compute(ComputeDispatch::Both, 3, true), - OWNED, - owned(), - OWNED, - (0, 0), - ), - ( - "inheriting the pipeline alone", - owned(), - pipeline, - owned(), - OWNED, - (1, 0), - ), - ( - "from a buffer that inherits", - owned(), - OWNED, - compute(ComputeDispatch::Both, 0, false), - both, - (0, 0), - ), - ( - "into one that inherits and binds kernel buffers", - owned(), - both, - owned(), - OWNED, - (1, 0), - ), - ( - "onto command 0 of one that inherits", - compute(ComputeDispatch::Both, 0, false), - both, - owned(), - OWNED, - (0, 1), - ), - ( - "source index at capacity", - owned(), - OWNED, - owned(), - OWNED, - (0, THREADS), - ), - ( - "destination index at capacity", - owned(), - OWNED, - owned(), - OWNED, - (THREADS, 0), - ), - ( - "into a render command buffer", - render, - OWNED, - owned(), - OWNED, - (0, 0), - ), - ]; - for (stem, _, plan, m) in &runs { - for (what, descriptor, inheritance, from, from_inheritance, copy) in &faults { - let records: Vec = copied_sources() - .into_iter() - .map(|r| match from_inheritance.buffers { - StateSource::Parent => CommandRecord { - bindings: Default::default(), - ..r - }, - StateSource::Command => r, - }) - .collect(); - let source = encoded(from, *from_inheritance, &records); - let initial = storage(descriptor, *inheritance); - let run = run_copies(plan, m, initial.clone(), Some(source.clone()), [*copy; 4]) - .unwrap_or_else(|e| panic!("{what} on {stem}: {e}")); - let mut want = initial; - want[4..8].copy_from_slice(&1u32.to_le_bytes()); - assert_eq!(run.records, want, "{what} on {stem}"); - assert_eq!( - CommandBuffer::decode(&run.records, descriptor, *inheritance).err(), - Some(CommandBufferError::EncodingFault(1)), - "{what} on {stem}" - ); - assert_eq!( - run.source.as_ref(), - Some(&source), - "{what} on {stem}: source" - ); - } - } -} - -/// A kernel's render pipeline setter, indexed draws (`ushort` indices in device memory, `uint` -/// ones in constant memory, a negative base vertex) and render reset decode under a render -/// descriptor of indexed draws, each value where the record format holds it: the index buffer as -/// its guest address, the index type from the overload. Under a descriptor of draws of primitives -/// alone, the indexed draw is outside the policy: the header's fault flag fails the decode. -#[test] -fn encoded_indexed_draws_round_trip_through_the_host_contract() { - let Some(runs) = compiled("render_indexed", &render_indexed_kernel()) else { - return; - }; - let indexed = CommandDescriptor::Render { - draws: RenderDraws { - primitives: false, - indexed: true, - patches: false, - indexed_patches: false, - mesh_threadgroups: false, - mesh_threads: false, - }, - max_vertex_buffer_bind_count: 1, - max_fragment_buffer_bind_count: 1, - max_object_buffer_bind_count: 0, - max_mesh_buffer_bind_count: 0, - support_dynamic_attribute_stride: false, - }; - for (stem, _, plan, m) in &runs { - let run = run_encoder(plan, m, storage(&indexed, OWNED), &[], true) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - let want: Vec = (0..THREADS) - .map(|t| { - if t == 3 { - return CommandRecord::default(); - } - let action = if t % 2 == 0 { - Action::DrawIndexedPrimitives { - primitive_type: 3, - index_count: 6, - index_type: 0, - index_buffer: DATA_GUEST + 16 * u64::from(t), - instance_count: 2, - base_vertex: -(t as i32), - base_instance: 7, - } - } else { - Action::DrawIndexedPrimitives { - primitive_type: 0, - index_count: 4, - index_type: 1, - index_buffer: CONSTS_GUEST, - instance_count: 1, - base_vertex: 0, - base_instance: 0, - } - }; - let mut r = CommandRecord { - action, - kernel_pipeline: true, - ..CommandRecord::default() - }; - r.bindings.pipeline = NonZeroU64::new(TOKEN); - r - }) - .collect(); - let got = decoded(&run.records, &indexed).unwrap_or_else(|e| panic!("{stem}: {e}")); - assert_eq!(got, want, "{stem}"); - let primitives = CommandDescriptor::Render { - draws: RenderDraws::PRIMITIVES, - max_vertex_buffer_bind_count: 1, - max_fragment_buffer_bind_count: 1, - max_object_buffer_bind_count: 0, - max_mesh_buffer_bind_count: 0, - support_dynamic_attribute_stride: false, - }; - let run = run_encoder(plan, m, storage(&primitives, OWNED), &[], true) - .unwrap_or_else(|e| panic!("{stem} primitives: {e}")); - assert_eq!( - decoded(&run.records, &primitives).err(), - Some(CommandBufferError::EncodingFault(1)), - "{stem} primitives" - ); - } -} - -/// A kernel's indexed patch draws decode under a render descriptor of indexed patch draws: a patch -/// draw's arguments and the control-point index buffer's guest address (0 for null), from device -/// and constant memory, where the record keeps it. A descriptor of patch draws alone holds them -/// too; under one of indexed draws alone, whose records do not, the indexed patch draw is outside -/// the policy: the decode fails. -#[test] -fn encoded_indexed_patch_draws_round_trip_through_the_host_contract() { - let Some(runs) = compiled("render_indexed_patches", &render_indexed_patches_kernel()) else { - return; - }; - let draws = |patches, indexed_patches| CommandDescriptor::Render { - draws: RenderDraws { - primitives: false, - indexed: false, - patches, - indexed_patches, - mesh_threadgroups: false, - mesh_threads: false, - }, - max_vertex_buffer_bind_count: 1, - max_fragment_buffer_bind_count: 1, - max_object_buffer_bind_count: 0, - max_mesh_buffer_bind_count: 0, - support_dynamic_attribute_stride: false, - }; - let indexed = draws(false, true); - for (stem, _, plan, m) in &runs { - let run = run_encoder(plan, m, storage(&indexed, OWNED), &[], true) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - let want: Vec = (0..THREADS) - .map(|t| { - let data = DATA_GUEST + 16 * u64::from(t); - let action = if t % 2 == 0 { - Action::DrawIndexedPatches { - control_points: 4, - patch_start: t, - patch_count: 2, - patch_index_buffer: 0, - control_point_index_buffer: 0, - instance_count: 3, - base_instance: 1, - factor_buffer: data, - factor_instance_stride: 48, - factor_scale: 1.0f32.to_bits(), - } - } else { - Action::DrawIndexedPatches { - control_points: 3, - patch_start: 0, - patch_count: 1, - patch_index_buffer: data, - control_point_index_buffer: CONSTS_GUEST, - instance_count: 1, - base_instance: 0, - factor_buffer: data, - factor_instance_stride: 0, - factor_scale: 0.5f32.to_bits(), - } - }; - CommandRecord { - action, - ..CommandRecord::default() - } - }) - .collect(); - let got = decoded(&run.records, &indexed).unwrap_or_else(|e| panic!("{stem}: {e}")); - assert_eq!(got, want, "{stem}"); - let patches = draws(true, false); - let run = run_encoder(plan, m, storage(&patches, OWNED), &[], true) - .unwrap_or_else(|e| panic!("{stem} patches: {e}")); - let got = decoded(&run.records, &patches).unwrap_or_else(|e| panic!("{stem}: {e}")); - assert_eq!(got, want, "{stem} patches"); - let indexed_draws = CommandDescriptor::Render { - draws: RenderDraws { - primitives: false, - indexed: true, - patches: false, - indexed_patches: false, - mesh_threadgroups: false, - mesh_threads: false, - }, - max_vertex_buffer_bind_count: 1, - max_fragment_buffer_bind_count: 1, - max_object_buffer_bind_count: 0, - max_mesh_buffer_bind_count: 0, - support_dynamic_attribute_stride: false, - }; - let run = run_encoder(plan, m, storage(&indexed_draws, OWNED), &[], true) - .unwrap_or_else(|e| panic!("{stem} indexed draws: {e}")); - assert_eq!( - decoded(&run.records, &indexed_draws).err(), - Some(CommandBufferError::EncodingFault(1)), - "{stem} indexed draws" - ); - } -} - -/// A kernel's patch draws decode under a render descriptor of patch draws: the patch index and -/// factor buffers as guest addresses (0 for a null patch index buffer), from device and constant -/// memory, and the factor scale's bits, as the record format holds them. Under a descriptor of -/// draws of primitives alone, the patch draw is outside the policy: the decode fails. -#[test] -fn encoded_patch_draws_round_trip_through_the_host_contract() { - let Some(runs) = compiled("render_patches", &render_patches_kernel()) else { - return; - }; - let patches = CommandDescriptor::Render { - draws: RenderDraws { - primitives: false, - indexed: false, - patches: true, - indexed_patches: false, - mesh_threadgroups: false, - mesh_threads: false, - }, - max_vertex_buffer_bind_count: 1, - max_fragment_buffer_bind_count: 1, - max_object_buffer_bind_count: 0, - max_mesh_buffer_bind_count: 0, - support_dynamic_attribute_stride: false, - }; - for (stem, _, plan, m) in &runs { - let run = run_encoder(plan, m, storage(&patches, OWNED), &[], true) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - let want: Vec = (0..THREADS) - .map(|t| { - let data = DATA_GUEST + 16 * u64::from(t); - let action = if t % 2 == 0 { - Action::DrawPatches { - control_points: 4, - patch_start: t, - patch_count: 2, - patch_index_buffer: 0, - instance_count: 3, - base_instance: 1, - factor_buffer: data, - factor_instance_stride: 48, - factor_scale: 1.0f32.to_bits(), - } - } else { - Action::DrawPatches { - control_points: 3, - patch_start: 0, - patch_count: 1, - patch_index_buffer: data, - instance_count: 1, - base_instance: 0, - factor_buffer: CONSTS_GUEST, - factor_instance_stride: 0, - factor_scale: 0.5f32.to_bits(), - } - }; - CommandRecord { - action, - ..CommandRecord::default() - } - }) - .collect(); - let got = decoded(&run.records, &patches).unwrap_or_else(|e| panic!("{stem}: {e}")); - assert_eq!(got, want, "{stem}"); - let primitives = CommandDescriptor::Render { - draws: RenderDraws::PRIMITIVES, - max_vertex_buffer_bind_count: 1, - max_fragment_buffer_bind_count: 1, - max_object_buffer_bind_count: 0, - max_mesh_buffer_bind_count: 0, - support_dynamic_attribute_stride: false, - }; - let run = run_encoder(plan, m, storage(&primitives, OWNED), &[], true) - .unwrap_or_else(|e| panic!("{stem} primitives: {e}")); - assert_eq!( - decoded(&run.records, &primitives).err(), - Some(CommandBufferError::EncodingFault(1)), - "{stem} primitives" - ); - } -} diff --git a/docs/API.md b/docs/API.md index f572f27bf..54d00b3c4 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1484,7 +1484,11 @@ and the lowest constant level of detail). A sample's level is its sampler's to b ### Indirect command buffers An indirect command buffer's commands are records in ordinary buffer storage -(`bind::indirect_commands`): one format whatever the descriptor, written by the CPU or by a kernel. +(`bind::indirect_commands`): one format whatever the descriptor, written by the CPU. Under the +resident-table domains a function's encoder operations are refused, +`Unsupported{GpuEncodedIndirectCommands, NotImplemented}`; under the identity domains a function +writes the render commands section 1 names, into the records `pipeline::IndirectDrawLayout` +states, and is refused the same way for any other operation. The binder replays records into dispatches and draws: on the host, or on the device through a preprocessing kernel (`replay_preprocess`), and through `VK_EXT_device_generated_commands` where the device has it (`replay_preprocess_generated`). Draws of primitives under the encoder's @@ -1501,14 +1505,12 @@ reads no buffer and no `[[primitive_id]]` may instead merge into one draw (`Draw two merge passes (`draw_merge_module`) write each command's first vertex in the merged draw, and the vertex function, compiled as its merged variant (`VariantKey::merged_draws`), finds its command by that prefix and runs the command's vertex, instance and buffers, in the commands' -order. A kernel that encodes commands writes the records that start at -`bind::indirect_commands::records_address` of the buffer's ID, outside every Metal address, and -finds them only at their start: records may run past later IDs' starts, and a resident set -(`bind::ResidentSet`) keeps each records range whole. Each of the kernel's writes of a command's -record also stores 1 at the command's written flag, a `u32` a command past the records -(`bind::indirect_commands::written_flag_offset`), where the storage holds them; storage that ends -at its records takes none. A consumer whose own writes of the records set the flags too may reset -only the flagged records of a run of commands, clearing each flag with its record. +order. A buffer's records start at `bind::indirect_commands::records_address` of its ID, outside +every Metal address; records may run past later IDs' starts, and a resident set +(`bind::ResidentSet`) keeps each records range whole. Storage may hold a written flag per command, +a `u32` a command past the records (`bind::indirect_commands::written_flag_offset`): a consumer +whose own writes of the records set the flags may reset only the flagged records of a run of +commands, clearing each flag with its record. ## 7. Caching diff --git a/docs/REFUSALS.md b/docs/REFUSALS.md index ad32deb51..299dd5e3f 100644 --- a/docs/REFUSALS.md +++ b/docs/REFUSALS.md @@ -40,7 +40,7 @@ Columns: | Kind | `metal-measured` | `metal-documented` | `metal-takes` | `device` | `ours` | `unknown` | `delegated` | `-` | |---|---|---|---|---|---|---|---|---| -| Translator and front-end refusals | 0 | 0 | 0 | 44 | 55 | 0 | 0 | 36 | +| Translator and front-end refusals | 0 | 0 | 0 | 44 | 54 | 0 | 0 | 37 | | Binder refusals at a device limit | 0 | 0 | 0 | 9 | 0 | 0 | 0 | 0 | | Translation caps | 0 | 0 | 0 | 0 | 14 | 0 | 0 | 0 | | Rate maps the compile layer does not compile | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 5 | @@ -78,7 +78,7 @@ Columns: | `SimdgroupMatrix16x16x16` | A 16x16x16 simdgroup matrix product (`air.simdgroup_matrix_16x16x16_[widening_]multiply_accumulate`), in any stage | every device (not implemented) | `ours` | 1: `crates/metal2vulkan/src/lower/simd/matrix.rs (select)` | `rare`: 16x16x16 simdgroup matrix products (Metal: Apple10 GPUs and later) | | `ArgumentBufferPointers` | Argument buffers holding buffer pointers (dynamic roots) | devices without buffer device addresses (`addressed_needs`) | `device` | 1: `crates/metal2vulkan/src/device/metal.rs (unsupported_features)` | `app`: argument buffers holding buffer pointers | | `ArgumentBufferTextures` | Argument buffers holding textures or samplers (handle domain) | devices without a capability the site computes (`gaps`); devices without a capability the site computes (`missing`); every device (not implemented) | `ours` | 15: `crates/metal2vulkan/src/bind/heap.rs (array)`, `crates/metal2vulkan/src/bind/heap.rs (member_texel_view, 2 sites)` (+8) | `app`: argument buffers holding textures and samplers (bindless) | -| `ArgumentBufferObjects` | Argument-buffer members that are pipeline states, ICBs, function tables, or acceleration structures | every device (not implemented) | `ours` | 6: `crates/metal2vulkan/src/lower/access/encode.rs (select_command, 3 sites)`, `crates/metal2vulkan/src/lower/access/icb.rs (select)` (+2) | `rare`: pipeline states and ICBs in argument buffers | +| `ArgumentBufferObjects` | Argument-buffer members that are pipeline states, ICBs, function tables, or acceleration structures | every device (not implemented) | `ours` | 4: `crates/metal2vulkan/src/lower/access/icb.rs (select)`, `crates/metal2vulkan/src/lower/access/object.rs (select)` (+2) | `rare`: pipeline states and ICBs in argument buffers | | `DereferenceLoadedPointer` | Dereferencing a pointer loaded from memory or made from an integer | devices short of a Vulkan feature the site names; devices without buffer device addresses (`addressed_needs`); every device (no Vulkan mechanism) | `device` | 4: `crates/metal2vulkan/src/lower/access/dynamic.rs (plan_misses)`, `crates/metal2vulkan/src/lower/access/local.rs (access_ptr)` (+2) | `app`: pointers loaded from argument buffers | | `PointerToInteger` | Storing a pointer or converting it to an integer | - | `-` | via a helper: 1: `crates/metal2vulkan/src/lower/access/dynamic.rs (require_addresses)` | `rare`: pointer to integer casts | | `PointerCompare` | Comparing pointers with different roots | - | `-` | via a helper: 1: `crates/metal2vulkan/src/lower/access/copy.rs (addressed)` | `rare`: comparing pointers of different roots | @@ -136,7 +136,7 @@ Columns: | `RayTracing` | | devices without a capability the site computes (`missing`); every device (no Vulkan mechanism); every device (not implemented) | `ours` | 12: `crates/metal2vulkan/src/bind/acceleration.rs (instance_record, 2 sites)`, `crates/metal2vulkan/src/lower/raytracing/mod.rs (instance_count)` (+5) | `rare`: ray tracing (out of scope by ruling) | | `Tensors` | | every device (not implemented) | `ours` | 2: `crates/metal2vulkan-air/src/canon/matmul2d/synth.rs (refuse)`, `crates/metal2vulkan/src/lower/select.rs (route_air)` | `rare`: shader tensors | | `RasterizationRateMap` | | devices without VkFeature::MultiViewport; devices without VkFeature::ShaderDrawParameters; devices without VkFeature::ShaderOutputViewportIndex; every device (not implemented) | `ours` | 2: `crates/metal2vulkan/src/lower/stage_io/plan.rs (region_viewport, 2 sites)` | `rare`: rasterization rate maps | -| `GpuEncodedIndirectCommands` | | devices short of a Vulkan feature the site names; devices without buffer device addresses (`addressed_needs`); every device (no Vulkan mechanism); every device (not implemented) | `ours` | 25: `crates/metal2vulkan/src/bind/replay.rs (preprocess)`, `crates/metal2vulkan/src/bind/replay.rs (replay_preprocess_module)` (+15) | `rare`: indirect command buffers encoded by a kernel | +| `GpuEncodedIndirectCommands` | | devices short of a Vulkan feature the site names; devices without buffer device addresses (`addressed_needs`); every device (no Vulkan mechanism); every device (not implemented) | `ours` | 22: `crates/metal2vulkan/src/bind/replay.rs (preprocess)`, `crates/metal2vulkan/src/bind/replay.rs (replay_preprocess_module)` (+14) | `rare`: indirect command buffers encoded by a kernel | | `VulkanVersion` | The device's Vulkan version is below the 1.2 floor | devices without ApiVersion::V1_2 | `device` | 2: `crates/metal2vulkan/src/ash_interop/query.rs (query)`, `crates/metal2vulkan/src/device/derive.rs (from_queries)` | `none`: a device below Vulkan 1.2 | | `PushWindow` | The device's `maxPushConstantsSize` is below the 256 bytes of the push window every stage is lowered for | devices without VkLimit::MaxPushConstantsSize | `device` | 1: `crates/metal2vulkan/src/device/derive.rs (from_queries)` | `none`: a device whose maxPushConstantsSize is below 256 bytes | | `IdentityDomains` | The identity pointer and handle domains (`PointerDomain::Identity`, `HandleDomain::Identity`) | devices without a capability the site computes (`all`); every device (not implemented) | `ours` | 7: `crates/metal2vulkan/src/device/derive.rs (identity_domains)`, `crates/metal2vulkan/src/lower/sampler/anisotropic.rs (select)` (+5) | `none`: the identity domains, which the runtime alone takes and which lower only kernels over buffer slots, textures in slots or argument buffers, and runtime samplers, so far | @@ -180,7 +180,7 @@ Columns: | `HeapTextureTiling` | A texture of a heap whose memory the device's optimal images do not take (a `Shared` heap on a device whose optimal images take no host-visible... | - | `-` | 0 | `app`: textures in Shared heaps on a device whose optimal images take no host memory | | `UndeclaredTextureUsage` | A shader write to a texture made without `ShaderWrite` (or `ShaderAtomic`), or a read of one made without `ShaderRead`, which plain Metal runs,... | - | `-` | 0 | `app`: a shader write to a texture made without ShaderWrite, which plain Metal runs | | `RenderTargetSize` | A render pass whose render area or layers are past the device's framebuffer limits (`Capability::Limit` names `MaxFramebufferWidth`,... | - | `-` | 0 | `rare`: a render area past a device's framebuffer limits | -| `IndirectRenderState` | A render state a function sets on an indirect render command (`render_command::set_cull_mode`, `set_front_facing_winding`,... | every device (not implemented) | `ours` | 1: `crates/metal2vulkan/src/lower/access/encode.rs (select_command)` | `rare`: render state set by a kernel on an indirect command | +| `IndirectRenderState` | A `depth_stencil_state` a function reads from an argument buffer or takes as a parameter, the state of an indirect render command, which no record... | - | `-` | via a helper: 2: `crates/metal2vulkan/src/lower/access/pointer.rs (unlowered)`, `crates/metal2vulkan/src/lower/select.rs (param_family)` | `rare`: render state set by a kernel on an indirect command | | `GlobalBuiltinInFragment` | A fragment function's read of a Metal 3.1 program-scope built-in variable that Metal does not lower there | every device (not implemented) | `ours` | 1: `crates/metal2vulkan/src/lower/select.rs (route_air)` | `rare`: Metal 3.1 global built-ins in fragment functions | | `PrivateRenderState` | A private fixed-function property of Metal's pipeline descriptor (Apple SPI, OpenGL on Metal's) set to a value whose effect the translation has... | devices without VkFeature::LogicOp; devices without VkFeature::RasterizationOrderColorAttachmentAccess; every device (not implemented) | `ours` | 7: `crates/metal2vulkan/src/bind/heap.rs (array)`, `crates/metal2vulkan/src/bind/plan/resources.rs (write_rounding)` (+5) | `none`: Apple-private pipeline fields of OpenGL on Metal (no public header) | | `ExtendedRangeBlend` | A blend the function computes in the shader, into an extended-range attachment (`BGRA10_XR`, `BGR10_XR`, `RGB10A8_2P_XR10` and their `_sRGB`... | every device (not implemented) | `ours` | 2: `crates/metal2vulkan/src/lower/arith/extended_range/blend.rs (refused)`, `crates/metal2vulkan/src/lower/fragment/fetch.rs (extended_range_output)` | `system`: an extended-range (XR10) attachment blended from an output other than four half or float lanes; a 16-bit float attachment's storage-form blend of a second-source factor or a one-color-channel mask under fast math; the consumer's guests blend RGB10A8_2P_XR10 attachments | @@ -419,7 +419,7 @@ Each refusal's sites, with the function that builds it. - `feature::SimdgroupMatrix16x16x16`: `crates/metal2vulkan/src/lower/simd/matrix.rs (select)` - `feature::ArgumentBufferPointers`: `crates/metal2vulkan/src/device/metal.rs (unsupported_features)` - `feature::ArgumentBufferTextures`: `crates/metal2vulkan/src/bind/heap.rs (array)`; `crates/metal2vulkan/src/bind/heap.rs (member_texel_view, 2 sites)`; `crates/metal2vulkan/src/bind/heap.rs (member_view, 4 sites)`; `crates/metal2vulkan/src/bind/heap.rs (new)`; `crates/metal2vulkan/src/lower/access/handle.rs (select)`; `crates/metal2vulkan/src/lower/sampler/select.rs (select_one)`; `crates/metal2vulkan/src/lower/sampler/select.rs (select_sampling)`; `crates/metal2vulkan/src/lower/texture/atomic.rs (select)`; `crates/metal2vulkan/src/lower/texture/slot.rs (declare_heap, 2 sites)`; `crates/metal2vulkan/src/pipeline/link.rs (heap_set)` -- `feature::ArgumentBufferObjects`: `crates/metal2vulkan/src/lower/access/encode.rs (select_command, 3 sites)`; `crates/metal2vulkan/src/lower/access/icb.rs (select)`; `crates/metal2vulkan/src/memory/provenance.rs (access)`; `crates/metal2vulkan/src/memory/provenance.rs (classify)` +- `feature::ArgumentBufferObjects`: `crates/metal2vulkan/src/lower/access/icb.rs (select)`; `crates/metal2vulkan/src/lower/access/object.rs (select)`; `crates/metal2vulkan/src/memory/provenance.rs (access)`; `crates/metal2vulkan/src/memory/provenance.rs (classify)` - `feature::DereferenceLoadedPointer`: `crates/metal2vulkan/src/lower/access/dynamic.rs (plan_misses)`; `crates/metal2vulkan/src/lower/access/local.rs (access_ptr)`; `crates/metal2vulkan/src/lower/access/local.rs (threadgroup_constant_refusal)`; `crates/metal2vulkan/src/memory/plan.rs (analyze)` - `feature::PointerToInteger`: `crates/metal2vulkan/src/lower/access/dynamic.rs (require_addresses)` - `feature::PointerCompare`: `crates/metal2vulkan/src/lower/access/copy.rs (addressed)` @@ -476,7 +476,7 @@ Each refusal's sites, with the function that builds it. - `feature::RayTracing`: `crates/metal2vulkan/src/bind/acceleration.rs (instance_record, 2 sites)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs (instance_count)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs (intersect, 5 sites)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs (primitive_data_read)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs (select_param)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs (slot_of)`; `crates/metal2vulkan/src/lower/select.rs (route_air)` - `feature::Tensors`: `crates/metal2vulkan-air/src/canon/matmul2d/synth.rs (refuse)`; `crates/metal2vulkan/src/lower/select.rs (route_air)` - `feature::RasterizationRateMap`: `crates/metal2vulkan/src/lower/stage_io/plan.rs (region_viewport, 2 sites)` -- `feature::GpuEncodedIndirectCommands`: `crates/metal2vulkan/src/bind/replay.rs (preprocess)`; `crates/metal2vulkan/src/bind/replay.rs (replay_preprocess_module)`; `crates/metal2vulkan/src/bind/replay/draws.rs (draw_replay_module)`; `crates/metal2vulkan/src/bind/replay/draws.rs (draw_replay_preprocess)`; `crates/metal2vulkan/src/bind/replay/merged.rs (draw_merge_module)`; `crates/metal2vulkan/src/lower/access/encode.rs (needs, 3 sites)`; `crates/metal2vulkan/src/lower/access/encode.rs (select_command)`; `crates/metal2vulkan/src/lower/access/icb.rs (needs, 2 sites)`; `crates/metal2vulkan/src/lower/access/icb.rs (select, 2 sites)`; `crates/metal2vulkan/src/lower/access/mod.rs (plan_replay, 3 sites)`; `crates/metal2vulkan/src/lower/mesh/mod.rs (plan_partial_groups)`; `crates/metal2vulkan/src/lower/select.rs (finish, 2 sites)`; `crates/metal2vulkan/src/lower/simd/divergent.rs (barriers)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (indirect_range)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (merged)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (param)`; `crates/metal2vulkan/src/pipeline/compile.rs (analyze_one, 2 sites)` +- `feature::GpuEncodedIndirectCommands`: `crates/metal2vulkan/src/bind/replay.rs (preprocess)`; `crates/metal2vulkan/src/bind/replay.rs (replay_preprocess_module)`; `crates/metal2vulkan/src/bind/replay/draws.rs (draw_replay_module)`; `crates/metal2vulkan/src/bind/replay/draws.rs (draw_replay_preprocess)`; `crates/metal2vulkan/src/bind/replay/merged.rs (draw_merge_module)`; `crates/metal2vulkan/src/lower/access/icb.rs (needs, 2 sites)`; `crates/metal2vulkan/src/lower/access/icb.rs (select, 2 sites)`; `crates/metal2vulkan/src/lower/access/mod.rs (plan_replay, 3 sites)`; `crates/metal2vulkan/src/lower/access/object.rs (select)`; `crates/metal2vulkan/src/lower/mesh/mod.rs (plan_partial_groups)`; `crates/metal2vulkan/src/lower/select.rs (finish, 2 sites)`; `crates/metal2vulkan/src/lower/simd/divergent.rs (barriers)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (indirect_range)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (merged)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (param)`; `crates/metal2vulkan/src/pipeline/compile.rs (analyze_one, 2 sites)` - `feature::VulkanVersion`: `crates/metal2vulkan/src/ash_interop/query.rs (query)`; `crates/metal2vulkan/src/device/derive.rs (from_queries)` - `feature::PushWindow`: `crates/metal2vulkan/src/device/derive.rs (from_queries)` - `feature::IdentityDomains`: `crates/metal2vulkan/src/device/derive.rs (identity_domains)`; `crates/metal2vulkan/src/lower/sampler/anisotropic.rs (select)`; `crates/metal2vulkan/src/lower/sampler/mod.rs (finish)`; `crates/metal2vulkan/src/lower/select.rs (identity_admits)`; `crates/metal2vulkan/src/lower/sync/barrier.rs (require_seq_cst)`; `crates/metal2vulkan/src/lower/texture/slot.rs (storage_format)`; `crates/metal2vulkan/src/pipeline/link.rs (identity_set)` @@ -506,7 +506,7 @@ Each refusal's sites, with the function that builds it. - `feature::TextureSwizzle`: `crates/metal2vulkan/src/bind/heap.rs (member_texel_view)`; `crates/metal2vulkan/src/bind/plan/resources.rs (plain_texture)`; `crates/metal2vulkan/src/lower/sampler/select.rs (select_one)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select_read_as)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select_write)`; `crates/metal2vulkan/src/lower/texture/slice.rs (select)` - `feature::PrivateMemory`: `crates/metal2vulkan/src/lower/access/local.rs (device_arena)` - `feature::Reflection`: `crates/metal2vulkan/src/reflection/derive.rs (gap_at)`; `crates/metal2vulkan/src/reflection/derive.rs (read_attributes)`; `crates/metal2vulkan/src/reflection/derive.rs (specialized_reads)`; `crates/metal2vulkan/src/reflection/function.rs (attribute)`; `crates/metal2vulkan/src/reflection/function.rs (module_constants)`; `crates/metal2vulkan/src/reflection/function.rs (unmeasured)`; `crates/metal2vulkan/src/reflection/linked.rs (function)`; `crates/metal2vulkan/src/reflection/mod.rs (kernel_stage)` -- `feature::IndirectRenderState`: `crates/metal2vulkan/src/lower/access/encode.rs (select_command)` +- `feature::IndirectRenderState`: `crates/metal2vulkan/src/lower/access/pointer.rs (unlowered)`; `crates/metal2vulkan/src/lower/select.rs (param_family)` - `feature::GlobalBuiltinInFragment`: `crates/metal2vulkan/src/lower/select.rs (route_air)` - `feature::PrivateRenderState`: `crates/metal2vulkan/src/bind/heap.rs (array)`; `crates/metal2vulkan/src/bind/plan/resources.rs (write_rounding)`; `crates/metal2vulkan/src/lower/sampler/select.rs (clamps_reference)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (alpha_test_refused)`; `crates/metal2vulkan/src/lower/texture/mod.rs (mode_rounded_write)`; `crates/metal2vulkan/src/pipeline/private_state.rs (logic_operation)`; `crates/metal2vulkan/src/pipeline/private_state.rs (refused)` - `feature::ExtendedRangeBlend`: `crates/metal2vulkan/src/lower/arith/extended_range/blend.rs (refused)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs (extended_range_output)`