From 7a066a4b8022db808b942e7e4994af2069c3b7d7 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Fri, 4 Dec 2026 17:21:11 -0800 Subject: [PATCH] Canon and lowering: a load made where the program did not run it is checked in the address form The constant-reference hoist makes a kernel's load of a constant T& at a fixed offset in its entry block, so every thread of every dispatch reads it where the program read it only behind a branch. Metal requires the reference's binding only where the program reads it, so an app may leave it unbound, or bound shorter than the object, while that branch is not taken. In the bound form the pipeline's robust buffer access contains the read (a null descriptor or a short range reads zero), but where the slot is reached by its device address an access at a constant offset was never checked: a short binding was read past its end by every thread, and an unbound one past the nil buffer's 64 KiB under a larger object, a GPU fault where a mapping ends. The mark: InstKind::Load gains `speculative`, false for every decoded load. const_hoist sets it on each load it moves; speculate sets it on each load of an arm it flattens (a constant reference's, at offset 0, run in every lane of the branch's block: the same window, narrower); aggregates carries it to a split load's members. Lowering reads it: a speculative load's slots are noted as reached at a variable offset (SlotBounds and, for a device-address read, the zero range), and emit::prepare checks it against the slot's buffer whatever its offset, reading zero outside, as an access at a run-time offset is. The bound form is unchanged: a bound slot drops its bounds and its view is not checked in the shader. Covered: a device without the bound form's queries, a slot bound below its argument's alignment on one with them, and every render stage. const_hoist also leaves a reference whose pointer another root may share (the parameter or an address step from it as a phi, select or insert operand, a stored value or the result): such a pointer may meet one loaded from memory, and lowering then reaches the reference by a device address no check bounds. Docs: const_hoist's and speculate's module docs, canon's list, ARCHITECTURE.md, API.md sections 1 and 5, the runtime README's bounds paragraphs and push layout, PushField::SlotBounds. The public signature table is re-blessed for InstKind::Load (no consumer use of InstKind: zero hits in the consumer's development and its day-old steelbrain/* tips). SEMANTICS_VERSION 2388. Tests: engine_hoist_contain (red at the base in jobs m3-max-87402 and m3-max-87403: no SlotBounds for the hoisted load's slot on any identity profile or for a word-bound slot on a bound-form profile, and the interpreter traps OutOfBounds at EXTRA+98304 and NIL+98304 with the flag off); constant_hoist's loads are speculative where moved and a shared reference keeps its loads; speculate's arm load is speculative where speculated and not where kept. --- .../metal2vulkan-air/src/bitcode/function.rs | 1 + .../metal2vulkan-air/src/canon/aggregates.rs | 11 +- .../metal2vulkan-air/src/canon/const_hoist.rs | 120 ++++++++++++++++-- crates/metal2vulkan-air/src/canon/devirt.rs | 3 + .../src/canon/devirt_tests.rs | 5 + .../src/canon/dynamic_tests.rs | 1 + .../metal2vulkan-air/src/canon/link_tests.rs | 3 + crates/metal2vulkan-air/src/canon/mod.rs | 3 +- crates/metal2vulkan-air/src/canon/opencl.rs | 1 + crates/metal2vulkan-air/src/canon/out.rs | 1 + crates/metal2vulkan-air/src/canon/pieces.rs | 1 + crates/metal2vulkan-air/src/canon/rate_map.rs | 1 + .../metal2vulkan-air/src/canon/recursion.rs | 1 + .../metal2vulkan-air/src/canon/sccp_tests.rs | 1 + .../metal2vulkan-air/src/canon/speculate.rs | 21 ++- .../src/canon/speculate_tests.rs | 72 ++++++++++- crates/metal2vulkan-air/src/canon/tests.rs | 2 + .../src/canon/tests/aggregates.rs | 1 + .../src/canon/tests/constant_hoist.rs | 70 ++++++++++ .../src/canon/tests/unobserved.rs | 1 + crates/metal2vulkan-air/src/ir/inst.rs | 6 + crates/metal2vulkan-air/src/ir/print.rs | 4 + crates/metal2vulkan-air/src/ir/print_tests.rs | 1 + .../metal2vulkan-air/src/ir/verify_tests.rs | 2 + crates/metal2vulkan-runtime/README.md | 17 ++- .../src/air_writer/text.rs | 3 + .../src/oracle_fuel/emit.rs | 1 + crates/metal2vulkan/src/lower/access/copy.rs | 1 + .../metal2vulkan/src/lower/access/dynamic.rs | 15 ++- crates/metal2vulkan/src/lower/access/emit.rs | 26 ++-- .../metal2vulkan/src/lower/access/handle.rs | 6 +- crates/metal2vulkan/src/lower/access/mod.rs | 54 +++++--- .../metal2vulkan/src/lower/access/pointer.rs | 6 +- crates/metal2vulkan/src/lower/access/quad.rs | 2 +- .../src/lower/simd/uniform/tests.rs | 1 + crates/metal2vulkan/src/memory/plan/tests.rs | 5 + .../src/memory/plan/tests/gaps.rs | 3 + crates/metal2vulkan/src/pipeline/sym.rs | 6 +- crates/metal2vulkan/tests/api_signatures.tsv | 2 +- docs/API.md | 22 ++-- docs/ARCHITECTURE.md | 2 +- 41 files changed, 430 insertions(+), 75 deletions(-) diff --git a/crates/metal2vulkan-air/src/bitcode/function.rs b/crates/metal2vulkan-air/src/bitcode/function.rs index df21aa9be..e2390e3d1 100644 --- a/crates/metal2vulkan-air/src/bitcode/function.rs +++ b/crates/metal2vulkan-air/src/bitcode/function.rs @@ -1180,6 +1180,7 @@ impl FnDecoder { volatile, atomic, range: None, + speculative: false, }; self.push(s, cx, code, (ty, tid), kind, m) } diff --git a/crates/metal2vulkan-air/src/canon/aggregates.rs b/crates/metal2vulkan-air/src/canon/aggregates.rs index d8c8a8e8a..9cc7073e7 100644 --- a/crates/metal2vulkan-air/src/canon/aggregates.rs +++ b/crates/metal2vulkan-air/src/canon/aggregates.rs @@ -59,6 +59,8 @@ struct Split { ptr_ty: TypeId, align: Option, members: (usize, usize), + /// A speculative load's (`InstKind::Load`'s `speculative`): each member's load is too. + speculative: bool, } impl Split { @@ -184,14 +186,15 @@ fn split_of( members: &mut Vec, m: &mut Meter, ) -> Result, Error> { - let (ptr, val, ty, align) = match &inst.kind { + let (ptr, val, ty, align, speculative) = match &inst.kind { InstKind::Load { ptr, align, volatile: false, atomic: None, + speculative, .. - } => (*ptr, None, inst.ty, *align), + } => (*ptr, None, inst.ty, *align, *speculative), InstKind::Store { val, ptr, @@ -199,7 +202,7 @@ fn split_of( volatile: false, atomic: None, } => match ty_of(*val) { - Some(ty) => (*ptr, Some(*val), ty, *align), + Some(ty) => (*ptr, Some(*val), ty, *align, false), None => return Ok(None), }, _ => return Ok(None), @@ -223,6 +226,7 @@ fn split_of( ptr_ty, align, members, + speculative, })) } @@ -331,6 +335,7 @@ fn emit( volatile: false, atomic: None, range: None, + speculative: s.speculative, }, }, m, diff --git a/crates/metal2vulkan-air/src/canon/const_hoist.rs b/crates/metal2vulkan-air/src/canon/const_hoist.rs index 50a0312ea..637644c11 100644 --- a/crates/metal2vulkan-air/src/canon/const_hoist.rs +++ b/crates/metal2vulkan-air/src/canon/const_hoist.rs @@ -12,12 +12,14 @@ //! parameter the ABI binds as a buffer of the constant address space with a stated //! `air.buffer_size` (a `constant T&`; no function constant gates it), or that parameter plus //! `getelementptr`s at constant, non-negative indices and bitcasts, which move with the load. The -//! bytes read lie inside the referenced object, `[0, air.buffer_size)`. The address is then one -//! address for every thread of the dispatch, and each form of the access contains it at the -//! entry as it did where it stood: the same slot, a bound storage view under its robust buffer -//! access, or a device address read at a constant offset inside the object, which no check -//! clamps in either place. A pointer parameter (`constant T*`, no size), an offset outside the +//! bytes read lie inside the referenced object, `[0, air.buffer_size)`, one address for every +//! thread of the dispatch. A pointer parameter (`constant T*`, no size), an offset outside the //! object, and an offset the run computes stay. +//! - **A pointer no other root shares.** Neither the parameter nor an address step from it (a +//! `getelementptr`, a bitcast or address-space cast, a `freeze`) is an operand of a phi, a +//! `select`, or a vector or aggregate insert, the value of a store, or the function's result. +//! Such a pointer may meet one loaded from memory, and lowering then reaches the reference +//! through a device address it checks nowhere; its loads stay. //! - **No write before it.** No instruction on any path from the function's start to the load may //! write device memory or order another thread's writes before it: a store or memory intrinsic //! whose destination is not thread or threadgroup memory, an atomic or atomic load of any space, @@ -25,10 +27,17 @@ //! operations, built-in reads and texture reads and queries. A device buffer may cover the //! constant buffer's bytes, so such a write could change what the load reads. //! -//! Anything else stays where it is. The moved load reads the bytes it read where it stood: a -//! thread that skipped its block reads them too and uses nothing of them. +//! Anything else stays where it is. The moved load reads the bytes it read where it stood, and a +//! thread that skipped its block reads them too and uses nothing of them. That thread runs a load +//! the program did not run, so the moved load is marked speculative +//! ([`InstKind::Load`]'s `speculative`): Metal requires the reference's binding only where the +//! program reads it, and an app may leave it unbound, or bound shorter than the object, where the +//! branch is not taken. Lowering contains a speculative load whatever its offset: a bound storage +//! view's robust buffer access reads zero outside its range, and a slot reached by its device +//! address checks the load against its bounds and reads zero outside, as it checks an access at +//! an offset the run computes. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use crate::abi::{ParamBinding, ParamRole}; use crate::budget::Meter; @@ -44,7 +53,8 @@ use super::rewrite::{apply, filled, invariant, scoped, BodyEdit}; const STEPS: usize = 64; /// Make in the entry block each load of `func`'s body that reads a constant reference the -/// entry's `bindings` bind, where nothing before it may write device memory (the module docs). +/// entry's `bindings` bind, where nothing before it may write device memory, each marked +/// speculative (the module docs). pub(super) fn expand( body: Body, parts: &ModuleParts, @@ -74,11 +84,37 @@ pub(super) fn expand( tys, objects: &objects, }; + let shared = cx.shared(m, held)?; + let own: BTreeMap = (objects.iter()) + .filter(|(p, _)| !shared.contains(p)) + .map(|(&p, &size)| (p, size)) + .collect(); + let bytes = own.len() * std::mem::size_of::<(u32, u64)>() * 2; + m.charge(bytes)?; + *held = held.saturating_add(bytes); + let cx = Cx { + objects: &own, + ..cx + }; let moved = cx.moves(m, held)?; if moved.is_empty() { return Ok(None); } let mut edit = BodyEdit::keep_all(&body, m, held)?; + // Each moved load runs where the program did not run it. + for &id in moved.keys() { + let Some(inst) = body.insts.get(id) else { + continue; + }; + let mut kind = inst.kind.clone(); + if let InstKind::Load { speculative, .. } = &mut kind { + *speculative = true; + let bytes = std::mem::size_of::<(InstId, InstKind)>() * 2; + m.charge(bytes)?; + *held = held.saturating_add(bytes); + edit.rewrite.insert(id, kind); + } + } edit.moved = moved; apply(&body, &edit, &|c| c, m).map(Some) }); @@ -123,6 +159,72 @@ struct Cx<'a> { } impl Cx<'_> { + /// The constant references whose pointer another root may share: the parameter, or an address + /// step from it (a `getelementptr`, a bitcast or address-space cast, a `freeze`), is an + /// operand of a phi, a `select`, or a vector or aggregate insert, the value of a store, or the + /// function's result (the module docs). Its table is charged to `held`. + fn shared(&self, m: &mut Meter, held: &mut usize) -> Result, Error> { + let n = self.body.insts.len(); + // The reference each instruction's pointer steps from. + let mut from: Vec> = filled(m, held, n, None)?; + let of = |from: &[Option], v: Value| match v { + Value::Arg(a) => u32::try_from(a.index()) + .ok() + .filter(|p| self.objects.contains_key(p)), + Value::Inst(i) => from.get(i.index()).copied().flatten(), + Value::Const(_) => None, + }; + // To a fixed point: a step may lie before its base in the layout. Each pass that changes + // anything adds a step, so at most `n` passes run. + for _ in 0..=n { + let mut changed = false; + for (id, inst) in self.body.insts.iter() { + m.tick(1)?; + let base = match &inst.kind { + InstKind::Gep { base, .. } => *base, + InstKind::Cast { + op: CastOp::Bitcast | CastOp::AddrSpaceCast, + v, + } + | InstKind::Freeze(v) => *v, + _ => continue, + }; + let Some(p) = of(&from, base) else { + continue; + }; + if let Some(slot) = from.get_mut(id.index()).filter(|s| s.is_none()) { + *slot = Some(p); + changed = true; + } + } + if !changed { + break; + } + } + let mut shared = BTreeSet::new(); + for (_, inst) in self.body.insts.iter() { + m.tick(1)?; + let mut share = |v: Value| { + if let Some(p) = of(&from, v) { + shared.insert(p); + } + }; + match &inst.kind { + InstKind::Store { val, .. } => share(*val), + InstKind::Select { t, f, .. } => { + share(*t); + share(*f); + } + InstKind::Phi { .. } + | InstKind::InsertElement { .. } + | InstKind::InsertValue { .. } + | InstKind::Ret(_) => inst.kind.for_each_value(share), + _ => {} + } + } + Ok(shared) + } + /// The loads to make in the entry block, each with the address steps it moves with, mapped to /// the entry block. Its tables are charged to `held`. fn moves(&self, m: &mut Meter, held: &mut usize) -> Result, Error> { diff --git a/crates/metal2vulkan-air/src/canon/devirt.rs b/crates/metal2vulkan-air/src/canon/devirt.rs index 1458bad26..88350b95d 100644 --- a/crates/metal2vulkan-air/src/canon/devirt.rs +++ b/crates/metal2vulkan-air/src/canon/devirt.rs @@ -2246,6 +2246,7 @@ fn emit( volatile: false, atomic: None, range: None, + speculative: false, }; for &decl in a.escapes.markers.get(&i).into_iter().flatten() { let marker = Call { @@ -2322,6 +2323,7 @@ fn emit( volatile: false, atomic: None, range: None, + speculative: false, }; e.push(e.words.i64t, kind, m)?; } @@ -2343,6 +2345,7 @@ fn emit( volatile: false, atomic: None, range: None, + speculative: false, }; let wide = e.push(e.words.i64t, kind, m)?; let cast = InstKind::Cast { diff --git a/crates/metal2vulkan-air/src/canon/devirt_tests.rs b/crates/metal2vulkan-air/src/canon/devirt_tests.rs index 6fd6f0e6c..afe19bc54 100644 --- a/crates/metal2vulkan-air/src/canon/devirt_tests.rs +++ b/crates/metal2vulkan-air/src/canon/devirt_tests.rs @@ -620,6 +620,7 @@ fn phi_kernel(dead: bool) -> (Module, AirAbi) { volatile: false, atomic: None, range: None, + speculative: false, }, ); k.br(join); @@ -1081,6 +1082,7 @@ fn a_function_pointer_kept_in_a_thread_s_memory_is_its_word() { volatile: false, atomic: None, range: None, + speculative: false, }, ); call_through(k, fp, arg(1)) @@ -1207,6 +1209,7 @@ fn a_loaded_pointer_no_function_can_answer_is_a_dynamic_call() { volatile: false, atomic: None, range: None, + speculative: false, }, ); call_through(k, fp, arg(1)) @@ -1240,6 +1243,7 @@ fn constant_chosen_kernel() -> (Module, AirAbi, GlobalId) { volatile: false, atomic: None, range: None, + speculative: false, }, ); let is = k.push( @@ -1500,6 +1504,7 @@ fn argument_buffer_kernel(how: TableUse) -> (Module, AirAbi) { volatile: false, atomic: None, range: None, + speculative: false, }, ) }; diff --git a/crates/metal2vulkan-air/src/canon/dynamic_tests.rs b/crates/metal2vulkan-air/src/canon/dynamic_tests.rs index a6be70c59..e428472ff 100644 --- a/crates/metal2vulkan-air/src/canon/dynamic_tests.rs +++ b/crates/metal2vulkan-air/src/canon/dynamic_tests.rs @@ -152,6 +152,7 @@ fn compute(f: &mut FunctionBuilder<'_>, names: &mut Names, x: Value, d: &Def<'_> volatile: false, atomic: None, range: None, + speculative: false, }, ); v = f.bin(BinOp::Add, v, word); diff --git a/crates/metal2vulkan-air/src/canon/link_tests.rs b/crates/metal2vulkan-air/src/canon/link_tests.rs index de5959a4e..d309e4034 100644 --- a/crates/metal2vulkan-air/src/canon/link_tests.rs +++ b/crates/metal2vulkan-air/src/canon/link_tests.rs @@ -216,6 +216,7 @@ fn callee(name: &str, calls: &[&str]) -> LinkedModule { volatile: false, atomic: None, range: None, + speculative: false, }, ); let mut v = f.bin(BinOp::Add, x3, word); @@ -549,6 +550,7 @@ fn constant_callee() -> LinkedCode { volatile: false, atomic: None, range: None, + speculative: false, }, ) }; @@ -1310,6 +1312,7 @@ fn a_difference_no_adapter_passes_is_not_implemented() { volatile: false, atomic: None, range: None, + speculative: false, }, )) }, diff --git a/crates/metal2vulkan-air/src/canon/mod.rs b/crates/metal2vulkan-air/src/canon/mod.rs index 1fa246423..10259558a 100644 --- a/crates/metal2vulkan-air/src/canon/mod.rs +++ b/crates/metal2vulkan-air/src/canon/mod.rs @@ -88,7 +88,8 @@ //! and vector members' accesses, joined by `insertvalue` or split by `extractvalue` //! (`aggregates`). **Constant references**: in a kernel, each plain load of a scalar or vector //! from a `constant T&` parameter's object, at an offset fixed at translation time, is made in -//! the entry block where nothing on any path before it may write device memory +//! the entry block where nothing on any path before it may write device memory and no other +//! root shares the parameter's pointer, marked speculative, as a speculated arm's load is //! (`const_hoist`). **Program-scope buffer bindings**: each load of the pointer a bound buffer's //! global holds becomes a read of the entry's parameter of that buffer, its own or one appended //! (`global_binding`). **Global built-in diff --git a/crates/metal2vulkan-air/src/canon/opencl.rs b/crates/metal2vulkan-air/src/canon/opencl.rs index 877a65d5e..09254618f 100644 --- a/crates/metal2vulkan-air/src/canon/opencl.rs +++ b/crates/metal2vulkan-air/src/canon/opencl.rs @@ -334,6 +334,7 @@ impl Sink<'_> { volatile: false, atomic: None, range: None, + speculative: false, }, m, )?; diff --git a/crates/metal2vulkan-air/src/canon/out.rs b/crates/metal2vulkan-air/src/canon/out.rs index 5047b1315..0669e77e7 100644 --- a/crates/metal2vulkan-air/src/canon/out.rs +++ b/crates/metal2vulkan-air/src/canon/out.rs @@ -258,6 +258,7 @@ impl<'p> Out<'p> { volatile: false, atomic: None, range: None, + speculative: false, }; self.push(ty, kind, m) } diff --git a/crates/metal2vulkan-air/src/canon/pieces.rs b/crates/metal2vulkan-air/src/canon/pieces.rs index 9e4e9775b..e5890cc09 100644 --- a/crates/metal2vulkan-air/src/canon/pieces.rs +++ b/crates/metal2vulkan-air/src/canon/pieces.rs @@ -195,6 +195,7 @@ fn emit( volatile: false, atomic: None, range: None, + speculative: false, }, }, m, diff --git a/crates/metal2vulkan-air/src/canon/rate_map.rs b/crates/metal2vulkan-air/src/canon/rate_map.rs index 5c913bcec..da8e0608d 100644 --- a/crates/metal2vulkan-air/src/canon/rate_map.rs +++ b/crates/metal2vulkan-air/src/canon/rate_map.rs @@ -292,6 +292,7 @@ impl Sink<'_> { volatile: false, atomic: None, range: None, + speculative: false, }; self.push(ty, load, m) } diff --git a/crates/metal2vulkan-air/src/canon/recursion.rs b/crates/metal2vulkan-air/src/canon/recursion.rs index f7ede9d11..ba41d29bf 100644 --- a/crates/metal2vulkan-air/src/canon/recursion.rs +++ b/crates/metal2vulkan-air/src/canon/recursion.rs @@ -3153,6 +3153,7 @@ fn load(ptr: Value) -> InstKind { volatile: false, atomic: None, range: None, + speculative: false, } } diff --git a/crates/metal2vulkan-air/src/canon/sccp_tests.rs b/crates/metal2vulkan-air/src/canon/sccp_tests.rs index c88c9fa13..573df65db 100644 --- a/crates/metal2vulkan-air/src/canon/sccp_tests.rs +++ b/crates/metal2vulkan-air/src/canon/sccp_tests.rs @@ -298,6 +298,7 @@ fn load(ty: TypeId, ptr: Value) -> Inst { volatile: false, atomic: None, range: None, + speculative: false, }, } } diff --git a/crates/metal2vulkan-air/src/canon/speculate.rs b/crates/metal2vulkan-air/src/canon/speculate.rs index 04f7aeb86..81fa8ca22 100644 --- a/crates/metal2vulkan-air/src/canon/speculate.rs +++ b/crates/metal2vulkan-air/src/canon/speculate.rs @@ -39,7 +39,11 @@ //! [`expand`] speculates each outermost branch Metal speculates whose arms hold a group operation //! that answers differently there (the operations above): the branch becomes a jump into its arm //! (a diamond's arms run one after the other), each value the arms join with becomes a `select` -//! on the condition, and a sunk store stores the chosen value where the arms join. A branch whose +//! on the condition, and a sunk store stores the chosen value where the arms join. Each load of +//! the arms, a `constant` reference's, then runs in lanes the program did not run it in, and is +//! marked speculative ([`InstKind::Load`]'s `speculative`): lowering contains it where the +//! reference is unbound or bound shorter than the load, as the constant-reference hoist's loads +//! (`const_hoist`). A branch whose //! arms hold no such operation is left as it is, as is one whose arms hold an instruction no //! measurement covers (a vector or aggregate operation, an address computation, a math function //! other than `sqrt`, a call outside the families above, a load other than a `constant` @@ -681,6 +685,21 @@ fn flatten( let Some(head_term) = term(fold.head) else { return; }; + // Each load of the arms runs in every lane of the branch's block. + for a in &fold.arms { + for &b in &a.blocks { + for (id, i) in body.block_insts(b) { + if !matches!(i.kind, InstKind::Load { .. }) { + continue; + } + let mut kind = i.kind.clone(); + if let InstKind::Load { speculative, .. } = &mut kind { + *speculative = true; + } + edit.rewrite.insert(id, kind); + } + } + } match &fold.arms[..] { [a] => { edit.rewrite.insert( diff --git a/crates/metal2vulkan-air/src/canon/speculate_tests.rs b/crates/metal2vulkan-air/src/canon/speculate_tests.rs index b7c10e019..0aec29508 100644 --- a/crates/metal2vulkan-air/src/canon/speculate_tests.rs +++ b/crates/metal2vulkan-air/src/canon/speculate_tests.rs @@ -22,8 +22,8 @@ struct Types { i32t: TypeId, } -/// A body of `fn(i32 t, ptr addrspace(1) out)` that `build` writes, with its type table and -/// parameter types. +/// A body of `fn(i32 t, ptr addrspace(1) out, ptr addrspace(2) k)` that `build` writes, `k` a +/// `constant` reference of 4 bytes, with its type table and parameter types. struct Built { body: Body, types: TypeTable, @@ -32,9 +32,18 @@ struct Built { } impl Built { + /// The parameters' attributes: `k` dereferenceable for its 4 bytes. + fn params(&self) -> Vec { + let mut params = vec![Param::default(); self.param_tys.len()]; + if let Some(k) = params.get_mut(2) { + k.attrs.dereferenceable = Some(4); + } + params + } + fn decisions(&self) -> Vec { let mut m = meter(); - let params = vec![Param::default(); self.param_tys.len()]; + let params = self.params(); decisions( &self.body, (&self.types, &self.consts), @@ -54,7 +63,7 @@ impl Built { /// measurement decides. fn expanded_noting(self) -> (Body, bool) { let mut m = meter(); - let params = vec![Param::default(); self.param_tys.len()]; + let params = self.params(); expand( self.body, (&self.types, &self.consts), @@ -73,7 +82,8 @@ fn built(build: impl FnOnce(&mut FunctionBuilder<'_>, &Types)) -> Built { i32t: m.int(32), }; let dev = m.ptr(AddrSpace::Device); - let fty = m.fn_ty(types.void, &[types.i32t, dev]); + let cst = m.ptr(AddrSpace::Constant); + let fty = m.fn_ty(types.void, &[types.i32t, dev, cst]); let mut f = m.define("f", fty); build(&mut f, &types); let id = f.finish(); @@ -341,6 +351,57 @@ fn a_quad_reduction_keeps_its_arm() { assert_eq!(phis_and_selects(&body), (1, 0)); } +/// The load of `k`, a `constant` reference, then `+ t`. +fn read_k(f: &mut FunctionBuilder<'_>, t: &Types) -> Value { + let x = f.push( + t.i32t, + InstKind::Load { + ptr: f.arg(2), + align: None, + volatile: false, + atomic: None, + range: None, + speculative: false, + }, + ); + f.bin(BinOp::Add, x, f.arg(0)) +} + +/// Whether each load of `body` is speculative, in layout order. +fn speculative_loads(body: &Body) -> Vec { + body.insts + .iter() + .filter_map(|(_, i)| match i.kind { + InstKind::Load { speculative, .. } => Some(speculative), + _ => None, + }) + .collect() +} + +/// A `constant` reference's load in a speculated arm runs in every lane of the branch's block, +/// where the program ran it in the arm's lanes alone: it is marked speculative, so lowering +/// contains it where the reference is bound shorter than the load or not at all. An arm that keeps +/// its lanes keeps its load as it is. +#[test] +fn a_constant_reference_load_of_a_speculated_arm_is_speculative() { + let b = triangle(|f, t| { + let x = read_k(f, t); + first(f, t, x) + }); + assert_eq!(b.decisions(), [Decision::Speculated]); + let body = b.expanded(); + assert_eq!(conditional_branches(&body), 0); + assert_eq!(speculative_loads(&body), [true]); + let b = triangle(|f, t| { + let x = read_k(f, t); + let y = first(f, t, x); + let s = quad_sum(f, t, x); + f.bin(BinOp::Add, y, s) + }); + assert_eq!(b.decisions(), [Decision::Kept]); + assert_eq!(speculative_loads(&b.expanded()), [false]); +} + /// A device read keeps its arm. #[test] fn a_device_read_keeps_its_arm() { @@ -354,6 +415,7 @@ fn a_device_read_keeps_its_arm() { volatile: false, atomic: None, range: None, + speculative: false, }, ); first(f, t, x) diff --git a/crates/metal2vulkan-air/src/canon/tests.rs b/crates/metal2vulkan-air/src/canon/tests.rs index 40ec1cb63..c0683b47d 100644 --- a/crates/metal2vulkan-air/src/canon/tests.rs +++ b/crates/metal2vulkan-air/src/canon/tests.rs @@ -166,6 +166,7 @@ fn load(f: &mut FunctionBuilder<'_>, ty: TypeId, ptr: Value) -> Value { volatile: false, atomic: None, range: None, + speculative: false, }, ) } @@ -2052,6 +2053,7 @@ fn a_deeply_nested_written_global_is_rebuilt_on_a_small_stack() { volatile: true, atomic: None, range: None, + speculative: false, }, ); store(&mut f, v, arg(0)); diff --git a/crates/metal2vulkan-air/src/canon/tests/aggregates.rs b/crates/metal2vulkan-air/src/canon/tests/aggregates.rs index 89269533f..310f2b400 100644 --- a/crates/metal2vulkan-air/src/canon/tests/aggregates.rs +++ b/crates/metal2vulkan-air/src/canon/tests/aggregates.rs @@ -92,6 +92,7 @@ fn moved(how: Move) -> Entry { volatile, atomic: None, range: None, + speculative: false, }, ) }; diff --git a/crates/metal2vulkan-air/src/canon/tests/constant_hoist.rs b/crates/metal2vulkan-air/src/canon/tests/constant_hoist.rs index 719073c6b..8acf4408c 100644 --- a/crates/metal2vulkan-air/src/canon/tests/constant_hoist.rs +++ b/crates/metal2vulkan-air/src/canon/tests/constant_hoist.rs @@ -21,6 +21,9 @@ enum Shape { Pointer, /// `p.bias` read at byte 8, past `p`'s 8 bytes. PastObject, + /// `scale`'s pointer also chosen by a `select` against a pointer loaded from `out`, and read + /// through it: another root shares it. + Shared, } /// `kernel k(device float* out [[buffer(0)]], constant uint& n [[buffer(1)]], constant float& @@ -140,6 +143,30 @@ fn kernel_of(shape: Shape) -> Entry { ), }; let bias = load(&mut f, f32t, bias_ptr); + let shared = match shape { + Shape::Shared => { + let loaded = load(&mut f, cst, arg(0)); + let first = f.push( + i1, + InstKind::ICmp { + pred: IntPredicate::Eq, + a: arg(4), + b: zero, + }, + ); + let either = f.push( + cst, + InstKind::Select { + c: first, + t: arg(2), + f: loaded, + fmf: FastMath::NONE, + }, + ); + Some(load(&mut f, f32t, either)) + } + _ => None, + }; let g = f.push( f32t, InstKind::Cast { @@ -149,6 +176,10 @@ fn kernel_of(shape: Shape) -> Entry { ); let x = f.bin(BinOp::FMul, g, scale); let y = f.bin(BinOp::FAdd, x, bias); + let y = match shared { + Some(v) => f.bin(BinOp::FAdd, y, v), + None => y, + }; store(&mut f, y, o); f.br(exit); f.switch_to(exit); @@ -205,12 +236,33 @@ fn placed(e: &Entry) -> (usize, usize, bool) { (entry, elsewhere, stored) } +/// The speculative loads of the specialized kernel, each in its entry block: the loads the hoist +/// made there, where the program ran them behind the branch. +fn speculative(e: &Entry) -> usize { + let body = e.module.func(e.func).unwrap().body.as_ref().unwrap(); + let mut n = 0; + for (b, _) in body.blocks.iter() { + for (_, i) in body.block_insts(b) { + if let InstKind::Load { + speculative: true, .. + } = i.kind + { + assert_eq!(b.index(), 0, "a speculative load outside the entry block"); + n += 1; + } + } + } + n +} + /// Behind the bounds branch alone, the loads of `scale` and of `p.bias` (with its address) are made /// in the entry block beside `n`'s; the store stays behind the branch. #[test] fn a_constant_reference_read_behind_the_bounds_branch_is_read_in_the_entry_block() { let e = kernel_of(Shape::Bounds); assert_eq!(placed(&e), (3, 0, false), "{}", body_text(&e)); + // `scale`'s and `p.bias`'s, which the program read behind the branch; `n`'s it read there. + assert_eq!(speculative(&e), 2, "{}", body_text(&e)); } /// A store to device memory before the loads keeps them behind the branch: `out` may cover the @@ -219,6 +271,7 @@ fn a_constant_reference_read_behind_the_bounds_branch_is_read_in_the_entry_block fn a_store_before_the_load_keeps_it_where_it_is() { let e = kernel_of(Shape::StoreBefore); assert_eq!(placed(&e), (1, 2, false), "{}", body_text(&e)); + assert_eq!(speculative(&e), 0, "{}", body_text(&e)); } /// An atomic before the loads keeps them behind the branch. @@ -226,6 +279,7 @@ fn a_store_before_the_load_keeps_it_where_it_is() { fn an_atomic_before_the_load_keeps_it_where_it_is() { let e = kernel_of(Shape::AtomicBefore); assert_eq!(placed(&e), (1, 2, false), "{}", body_text(&e)); + assert_eq!(speculative(&e), 0, "{}", body_text(&e)); } /// A load in a callee that writes `out` first keeps it, and the load after the call, behind the @@ -234,6 +288,7 @@ fn an_atomic_before_the_load_keeps_it_where_it_is() { fn a_load_in_a_callee_that_writes_keeps_it_where_it_is() { let e = kernel_of(Shape::CalleeWrites); assert_eq!(placed(&e), (1, 2, false), "{}", body_text(&e)); + assert_eq!(speculative(&e), 0, "{}", body_text(&e)); } /// A load whose address the branch's block computes stays; `scale`'s, at the parameter itself, is @@ -242,6 +297,7 @@ fn a_load_in_a_callee_that_writes_keeps_it_where_it_is() { fn a_pointer_computed_behind_the_branch_keeps_its_load_where_it_is() { let e = kernel_of(Shape::PointerBehind); assert_eq!(placed(&e), (2, 1, false), "{}", body_text(&e)); + assert_eq!(speculative(&e), 1, "{}", body_text(&e)); } /// A load through a `constant float*`, which states no object size, stays; `p.bias`'s is made in @@ -250,6 +306,7 @@ fn a_pointer_computed_behind_the_branch_keeps_its_load_where_it_is() { fn a_constant_pointer_without_an_object_size_keeps_its_load_where_it_is() { let e = kernel_of(Shape::Pointer); assert_eq!(placed(&e), (2, 1, false), "{}", body_text(&e)); + assert_eq!(speculative(&e), 1, "{}", body_text(&e)); } /// A load past the referenced object's bytes stays; `scale`'s is made in the entry block. @@ -257,4 +314,17 @@ fn a_constant_pointer_without_an_object_size_keeps_its_load_where_it_is() { fn a_load_past_the_object_keeps_it_where_it_is() { let e = kernel_of(Shape::PastObject); assert_eq!(placed(&e), (2, 1, false), "{}", body_text(&e)); + assert_eq!(speculative(&e), 1, "{}", body_text(&e)); +} + +/// A reference whose pointer a `select` shares with a pointer loaded from memory keeps its loads +/// where they are: lowering may reach it through a device address no check bounds. `p.bias`'s is +/// made in the entry block. +#[test] +fn a_reference_another_root_shares_keeps_its_loads_where_they_are() { + let e = kernel_of(Shape::Shared); + // `n`'s and `p.bias`'s in the entry block; `scale`'s, the loaded pointer's and the selected + // load behind the branch. + assert_eq!(placed(&e), (2, 3, false), "{}", body_text(&e)); + assert_eq!(speculative(&e), 1, "{}", body_text(&e)); } diff --git a/crates/metal2vulkan-air/src/canon/tests/unobserved.rs b/crates/metal2vulkan-air/src/canon/tests/unobserved.rs index 1c375e08e..842ac8315 100644 --- a/crates/metal2vulkan-air/src/canon/tests/unobserved.rs +++ b/crates/metal2vulkan-air/src/canon/tests/unobserved.rs @@ -157,6 +157,7 @@ fn a_side_effect_nothing_uses_stays() { volatile: true, atomic: None, range: None, + speculative: false, }, ); air_call(f, "air.wg.barrier", void, &[i32t, i32t], &[two, one]); diff --git a/crates/metal2vulkan-air/src/ir/inst.rs b/crates/metal2vulkan-air/src/ir/inst.rs index b2bd83ecf..258888277 100644 --- a/crates/metal2vulkan-air/src/ir/inst.rs +++ b/crates/metal2vulkan-air/src/ir/inst.rs @@ -163,6 +163,12 @@ pub enum InstKind { atomic: Option, /// A `!range` attachment on the loaded value. range: Option, + /// The load runs where the program does not run it: canonicalization made it out of the + /// branch's arm it stood in (a constant reference's load made in a kernel's entry block, + /// or a load of a branch's arm that Metal's backend speculates). A thread may then read + /// bytes the program never read, which its binding need not hold, so lowering contains + /// the access whatever its offset. A decoded load is never speculative. + speculative: bool, }, /// `store` of `val` to `ptr`. Store { diff --git a/crates/metal2vulkan-air/src/ir/print.rs b/crates/metal2vulkan-air/src/ir/print.rs index a7765666a..7fb932580 100644 --- a/crates/metal2vulkan-air/src/ir/print.rs +++ b/crates/metal2vulkan-air/src/ir/print.rs @@ -319,6 +319,7 @@ impl Printer<'_> { volatile, atomic, range, + speculative, } => { self.out.push_str("load"); self.atomic_prefix(*atomic, *volatile); @@ -330,6 +331,9 @@ impl Printer<'_> { if let Some(r) = range { w!(self, ", !range {:?}", r.ranges); } + if *speculative { + self.out.push_str(", speculative"); + } } InstKind::Store { val, diff --git a/crates/metal2vulkan-air/src/ir/print_tests.rs b/crates/metal2vulkan-air/src/ir/print_tests.rs index 8ea0cfe11..4e9873148 100644 --- a/crates/metal2vulkan-air/src/ir/print_tests.rs +++ b/crates/metal2vulkan-air/src/ir/print_tests.rs @@ -232,6 +232,7 @@ fn every_opcode_prints() { volatile: true, atomic, range, + speculative: false, }; let x = k.push(i32t, load); k.push_void(InstKind::Store { diff --git a/crates/metal2vulkan-air/src/ir/verify_tests.rs b/crates/metal2vulkan-air/src/ir/verify_tests.rs index 7628b8b18..b916c2b44 100644 --- a/crates/metal2vulkan-air/src/ir/verify_tests.rs +++ b/crates/metal2vulkan-air/src/ir/verify_tests.rs @@ -56,6 +56,7 @@ fn load(f: &mut FunctionBuilder<'_>, ty: TypeId, ptr: Value) -> Value { volatile: false, atomic: None, range: None, + speculative: false, }, ) } @@ -505,6 +506,7 @@ fn instruction_typing_is_enforced() { scope: SyncScope::System, }), range: None, + speculative: false, }, ); }, diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index ae6d799e9..9ffa777bd 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -3350,8 +3350,9 @@ while the driver's exit handler waited on a lock, with every runtime thread alre that names no live buffer undefined; here it reads or writes whatever the device holds at that address, or faults, and a fault ends as the device ends it, up to a device loss that every guest process shares (above). What is bounded is a buffer argument's access at a byte offset that is - not a translation-time constant: outside its buffer a load reads zero and a store does nothing - (below). An access at a constant offset is not checked. + not a translation-time constant, and a load the translator makes where the program did not run + it: outside its buffer a load reads zero and a store does nothing (below). Any other access at a + constant offset is not checked. - No guest word indexes a set 1 array past its length. A slot's texture or sampler, and a constexpr sampler, are read at the runtime's own placement (texture indices 1 to 65,535, sampler indices 1 to 3,999; a placement outside them is refused). An argument buffer's texture is read at @@ -3369,7 +3370,8 @@ while the driver's exit handler waited on a lock, with every runtime thread alre device keeps from its first such dispatch or draw, its address the argument's pushed value, as Metal's nil buffer reads zeros. Its pushed buffer is 0 bytes long, so every checked access of it (below) is outside. Reads past the 64 KiB and writes through a nil argument at a constant - offset aren't covered. + offset aren't covered, but for a load the translator makes where the program did not run it + (below), which is checked. - A buffer argument's access at a byte offset that is not a translation-time constant is checked against its buffer, from the buffer's start to its end, as Metal's domain is the buffer: a dispatch or draw pushes, beside the argument's address, the bind offset and the buffer's length @@ -3377,7 +3379,11 @@ while the driver's exit handler waited on a lock, with every runtime thread alre writes the buffer's bytes there. Outside the buffer, a load reads zero, from 16 bytes of zeros the device keeps in a ring chunk of their own, taken at the first dispatch or draw that checks a load, which nothing is bound to and nothing writes; a store or an atomic does nothing, and an - atomic answers 0. This holds on every device. An access at a constant offset is not checked, + atomic answers 0. This holds on every device. So is a load the translator makes where the + program did not run it, at any offset: a kernel's load of a `constant T&` argument's object + made in its entry block, ahead of the branch it stood behind, and a load of a branch's arm that + Metal's backend speculates, each of which a thread may run where the guest bound the argument + short or not at all. Any other access at a constant offset is not checked, before the bind offset or past it: a draw or dispatch that binds a buffer shorter than the function's constant-offset accesses to it meets the device's own out-of-bounds behaviour, and where nothing maps there that is a fault, which loses the device on NVIDIA's driver and on RADV @@ -6391,7 +6397,8 @@ pass's end orders its writes before every later command. first command (4 bytes each), then any other leading word (4 bytes each); 4. its buffer slots' words, in slot order (8 bytes each); 5. its other fields, including, for each slot it reads at an offset that is not a - translation-time constant, that slot's bounds and the zero range's address (8 bytes each); + translation-time constant or by a load made where the program did not run it, that slot's + bounds and the zero range's address (8 bytes each); 6. 24 bytes of gap and a 4-byte tail word, or its last bounds field as the tail. From the first field that does not fit, its fields sit in its parameter block. So a vertex function with no other leading address pushes 25 slot words ((248 - 16 - 28) / 8, rounded down) diff --git a/crates/metal2vulkan-validation/src/air_writer/text.rs b/crates/metal2vulkan-validation/src/air_writer/text.rs index d23f3ab9a..3afbce68c 100644 --- a/crates/metal2vulkan-validation/src/air_writer/text.rs +++ b/crates/metal2vulkan-validation/src/air_writer/text.rs @@ -678,12 +678,15 @@ impl Printer<'_, '_> { w!(out, ", addrspace({space})"); } } + // A speculative load is the same load in AIR: the mark only asks lowering to contain + // it. InstKind::Load { ptr, align: a, volatile, atomic, range, + speculative: _, } => { let ty = res_ty(self)?; let ptr = self.typed(*ptr, ops, 0, names)?; diff --git a/crates/metal2vulkan-validation/src/oracle_fuel/emit.rs b/crates/metal2vulkan-validation/src/oracle_fuel/emit.rs index efaa88a9d..7eaa822b1 100644 --- a/crates/metal2vulkan-validation/src/oracle_fuel/emit.rs +++ b/crates/metal2vulkan-validation/src/oracle_fuel/emit.rs @@ -948,6 +948,7 @@ impl Rewrite<'_> { volatile: false, atomic: None, range: None, + speculative: false, } } diff --git a/crates/metal2vulkan/src/lower/access/copy.rs b/crates/metal2vulkan/src/lower/access/copy.rs index 48a4dd8ea..a631335a6 100644 --- a/crates/metal2vulkan/src/lower/access/copy.rs +++ b/crates/metal2vulkan/src/lower/access/copy.rs @@ -424,6 +424,7 @@ pub fn endpoint( coherence: None, volatile: false, blob, + speculative: false, })) } diff --git a/crates/metal2vulkan/src/lower/access/dynamic.rs b/crates/metal2vulkan/src/lower/access/dynamic.rs index 18cdbddbf..b9896d1b2 100644 --- a/crates/metal2vulkan/src/lower/access/dynamic.rs +++ b/crates/metal2vulkan/src/lower/access/dynamic.rs @@ -448,16 +448,17 @@ fn pointer_leaf( } /// A static-root load (or, `write`, store) of `leaf` through `ptr` (the access family's -/// `Access`). +/// `Access`), a speculative load where `speculative`: checked as at an offset that is not a +/// translation-time constant. fn static_access( cx: &mut SelectCx<'_>, ptr: Value, leaf: Leaf, - write: bool, + (write, speculative): (bool, bool), m: &mut Meter, ) -> Result { let (targets, null) = static_roots(cx, ptr, m)?; - let fixed = super::fixed_offset(cx, ptr); + let fixed = super::fixed_offset(cx, ptr) && !speculative; for t in &targets { let plan = cx .memory @@ -477,6 +478,7 @@ fn static_access( coherence: None, volatile: false, blob: false, + speculative, }) } @@ -572,12 +574,13 @@ pub fn select( align, volatile: false, atomic: None, + speculative, .. } if result_wide => { let leaf = pointer_leaf(cx, inst.ty, *align)?; let source = match cx.memory.repr(*ptr) { Some(Repr::BufPtr { wide: false, .. }) => { - Source::Static(static_access(cx, *ptr, leaf, false, m)?) + Source::Static(static_access(cx, *ptr, leaf, (false, *speculative), m)?) } Some(Repr::BufPtr { wide: true, .. }) => Source::Wide(WideAccess { ptr: plan_deref(cx, *ptr)?, @@ -605,7 +608,7 @@ pub fn select( let leaf = pointer_leaf(cx, ty, *align)?; let to = match cx.memory.repr(*ptr) { Some(Repr::BufPtr { wide: false, .. }) => { - Source::Static(static_access(cx, *ptr, leaf, true, m)?) + Source::Static(static_access(cx, *ptr, leaf, (true, false), m)?) } _ => store_destination(cx, *ptr, leaf)?, }; @@ -1274,7 +1277,7 @@ pub(super) fn plan_word( let leaf = pointer_leaf(cx, ty, align)?; Ok(match cx.memory.repr(ptr) { Some(Repr::BufPtr { wide: false, .. }) => { - Source::Static(static_access(cx, ptr, leaf, false, m)?) + Source::Static(static_access(cx, ptr, leaf, (false, false), m)?) } Some(Repr::BufPtr { wide: true, .. }) => Source::Wide(WideAccess { ptr: plan_deref(cx, ptr)?, diff --git a/crates/metal2vulkan/src/lower/access/emit.rs b/crates/metal2vulkan/src/lower/access/emit.rs index 65c803758..d0a94274b 100644 --- a/crates/metal2vulkan/src/lower/access/emit.rs +++ b/crates/metal2vulkan/src/lower/access/emit.rs @@ -319,11 +319,13 @@ pub(super) struct Prepared { } /// Prepare `t` for an access of `n` bytes at Metal offset `m`, a load or a copy's read where -/// `read`. +/// `read`, a speculative load where `speculative`. /// /// Under the identity domains a slot an access may reach at an offset that is not a -/// translation-time constant (`AccessPlan::variable`) is checked where `m` is not a constant, -/// against its buffer (`psb::in_buffer`): `m`, read as signed, plus the bytes before the bind +/// translation-time constant (`AccessPlan::variable`) is checked where `m` is not a constant, or +/// for a speculative load (`Access::speculative`, a load the program did not run there, which a +/// binding shorter than the object or none at all may not hold) at any `m`, against its buffer +/// (`psb::in_buffer`): `m`, read as signed, plus the bytes before the bind /// offset, under the slot's limit for `n` bytes (`psb::limit`), both from the slot's `SlotBounds` /// and made once per function (`EmitCx::slot_limit`), the normative check (`contain::in_bounds`) /// in `u32`. So an offset before the bind offset is inside where the @@ -342,8 +344,9 @@ pub(super) fn prepare( t: &Target, m: SValue, (n, read): (u32, bool), + speculative: bool, ) -> BResult { - prepare_access(cx, fb, t, m, (n, read), false) + prepare_access(cx, fb, t, m, (n, read), (false, speculative)) } /// [`prepare`] for an atomic of `n` bytes: a storage view's atomic is checked against its bound @@ -357,7 +360,7 @@ pub(super) fn prepare_atomic( m: SValue, n: u32, ) -> BResult { - prepare_access(cx, fb, t, m, (n, false), true) + prepare_access(cx, fb, t, m, (n, false), (true, false)) } /// [`prepare`], a robust storage view checked where `atomic`. @@ -367,7 +370,7 @@ fn prepare_access( t: &Target, m: SValue, (n, read): (u32, bool), - atomic: bool, + (atomic, speculative): (bool, bool), ) -> BResult { let Some(choice) = cx.plan.slots.get(t.slot).copied().flatten() else { return Err(cx.fail("an access names an unplanned slot")); @@ -393,7 +396,7 @@ fn prepare_access( let read_only = cx.plan.families.access.unwritten.contains(&t.slot); let mut mem = a.mem.with(ops).with_units(units).read_only(read_only); let checked = cx.plan.families.access.variable.contains(&choice.slot) - && leaf::known(fb, m)?.is_none(); + && (speculative || leaf::known(fb, m)?.is_none()); if checked { let limit = cx.slot_limit(fb, choice.slot, n)?; let inb = psb::in_buffer(fb, m, limit)?; @@ -546,7 +549,14 @@ pub(super) fn access_at( }; let mut prepared = Vec::with_capacity(a.targets.len()); for t in &a.targets { - let mut p = prepare(cx, fb, t, m, (a.leaf.bytes, stored.is_none()))?; + let mut p = prepare( + cx, + fb, + t, + m, + (a.leaf.bytes, stored.is_none()), + a.speculative, + )?; p.mem = p.mem.with(ops); prepared.push((t.root, t.slot, p)); } diff --git a/crates/metal2vulkan/src/lower/access/handle.rs b/crates/metal2vulkan/src/lower/access/handle.rs index b08ebd8da..5f2ffa73a 100644 --- a/crates/metal2vulkan/src/lower/access/handle.rs +++ b/crates/metal2vulkan/src/lower/access/handle.rs @@ -1140,7 +1140,11 @@ fn lookup( return Err(refuse(AccessCause::ConstantAddress)); } IdLoad::Static(super::access_with_leaf( - cx, ptr, None, leaf, targets, null, false, + cx, + (ptr, None), + leaf, + targets, + (null, false, false), )?) } }; diff --git a/crates/metal2vulkan/src/lower/access/mod.rs b/crates/metal2vulkan/src/lower/access/mod.rs index 1f3bbdb7c..de14dd4c1 100644 --- a/crates/metal2vulkan/src/lower/access/mod.rs +++ b/crates/metal2vulkan/src/lower/access/mod.rs @@ -298,6 +298,11 @@ pub struct Access { /// The pointer may point into the constant blob (a load only): the blob, read under /// [`BLOB_ROOT`] in the switch-at-use, checked in the shader. pub blob: bool, + /// A speculative load (`InstKind::Load`'s `speculative`), which runs where the program did + /// not run it: under the identity domains with containment on, a slot it reaches by its + /// device address is checked against its buffer whatever the load's offset + /// ([`note_variable`], `emit::prepare`). + pub speculative: bool, } impl Access { @@ -699,9 +704,10 @@ pub struct AccessPlan { /// the profile): a sub-word store there is one narrow store instead of two word atomics. pub psb_units: Units, /// Under the identity domains with containment on ([`identity_contained`]), the buffer slots - /// an access may reach at a byte offset that is not a translation-time constant - /// ([`note_variable`]): each reads its `PushField::SlotBounds`, and each of those accesses - /// whose emitted offset is not a constant is checked against its buffer (`emit::prepare`). + /// an access may reach at a byte offset that is not a translation-time constant, or a + /// speculative load reaches ([`Access::speculative`], [`note_variable`]): each reads its + /// `PushField::SlotBounds`, and each of those accesses whose emitted offset is not a constant, + /// and each speculative load, is checked against its buffer (`emit::prepare`). pub variable: BTreeSet, /// Under the identity domains with containment on ([`identity_contained`]), the buffer slots /// a load, a copy's read or a pulled fetch may reach, at any offset ([`note_variable`]): a @@ -1022,7 +1028,8 @@ pub(crate) fn identity_contained(cx: &SelectCx<'_>) -> bool { /// ([`identity_contained`]), a slot an access may reach at another offset is checked /// ([`AccessPlan::variable`]) and reads its `PushField::SlotBounds`, and a read is noted at any /// offset ([`AccessPlan::read`]): which reads take `PushField::ZeroAddress` is known once the -/// slots' forms are ([`place_zero_address`]). An access at a constant offset of a slot no other +/// slots' forms are ([`place_zero_address`]). A speculative load ([`Access::speculative`]) is +/// noted as at another offset, whatever its own. An access at a constant offset of a slot no other /// access reaches at another stays unchecked. pub(crate) fn note_variable(cx: &mut SelectCx<'_>, slot: SlotRef, fixed: bool, read: bool) { if !identity_contained(cx) { @@ -1827,19 +1834,20 @@ fn gep_offset_indexed( Ok((konst, terms)) } +/// The leaf access of a value of type `ty` at `ptr`, a store of `value` where it has one, aligned +/// as `align` states; a speculative load where `speculative` ([`access_with_leaf`]). fn select_access( cx: &mut SelectCx<'_>, - ptr: Value, - value: Option, - ty: crate::air::ir::TypeId, - align: Option, + (ptr, value): (Value, Option), + (ty, align): (crate::air::ir::TypeId, Option), + speculative: bool, m: &mut Meter, ) -> Result { let (targets, null, blob) = blob_roots(cx, ptr, value.is_some(), m)?; let align = align.map_or(1, |a| a.bytes()); let proven = cx.memory.proven_align(cx.entry, ptr); let leaf = leaf::leaf_of(cx.entry, cx.profile, &cx.memory.layouts, ty, align, proven)?; - access_with_leaf(cx, ptr, value, leaf, targets, null, blob) + access_with_leaf(cx, (ptr, value), leaf, targets, (null, blob, speculative)) } /// The candidate targets of static-root pointer `ptr` ([`buffer_roots`]), accessed as a write @@ -1931,17 +1939,16 @@ fn note_units( } /// The leaf access `leaf` through static-root pointer `ptr` with candidate `targets` (from -/// [`buffer_roots`]), placed by [`place_targets`]. +/// [`buffer_roots`]), placed by [`place_targets`]: a speculative load's as at an offset that is +/// not a translation-time constant, so each slot it reaches is checked for it. fn access_with_leaf( cx: &mut SelectCx<'_>, - ptr: Value, - value: Option, + (ptr, value): (Value, Option), leaf: Leaf, targets: Vec, - null: bool, - blob: bool, + (null, blob, speculative): (bool, bool, bool), ) -> Result { - let fixed = fixed_offset(cx, ptr); + let fixed = fixed_offset(cx, ptr) && !speculative; place_targets( cx, &targets, @@ -1978,6 +1985,7 @@ fn access_with_leaf( coherence: None, volatile: false, blob, + speculative, }) } @@ -2021,7 +2029,7 @@ fn select_coherent( .layouts .abi_align(ty) .and_then(crate::air::ir::Align::from_bytes); - let mut a = select_access(cx, ptr, value, ty, align, m)?; + let mut a = select_access(cx, (ptr, value), (ty, align), false, m)?; a.coherence = Some(crate::lower::sync::memory_model::coherent_access(cx)); a.volatile = c.volatile; Ok(match c.kind { @@ -2111,9 +2119,14 @@ pub fn select( align, volatile: false, atomic: None, + speculative, .. } if !is_ptr_ty(cx, inst.ty) => Ok(AccessStrategy::Load(select_access( - cx, *ptr, None, inst.ty, *align, m, + cx, + (*ptr, None), + (inst.ty, *align), + *speculative, + m, )?)), InstKind::Store { val, @@ -2130,10 +2143,9 @@ pub fn select( } Ok(AccessStrategy::Store(select_access( cx, - *ptr, - Some(*val), - ty, - *align, + (*ptr, Some(*val)), + (ty, *align), + false, m, )?)) } diff --git a/crates/metal2vulkan/src/lower/access/pointer.rs b/crates/metal2vulkan/src/lower/access/pointer.rs index ed3869099..29d5e9fee 100644 --- a/crates/metal2vulkan/src/lower/access/pointer.rs +++ b/crates/metal2vulkan/src/lower/access/pointer.rs @@ -464,7 +464,11 @@ fn store_pointer( return Err(refuse(AccessCause::ConstantAddress)); } Source::Static(super::access_with_leaf( - cx, ptr, None, leaf, targets, null, false, + cx, + (ptr, None), + leaf, + targets, + (null, false, false), )?) } _ => dynamic::store_destination(cx, ptr, leaf)?, diff --git a/crates/metal2vulkan/src/lower/access/quad.rs b/crates/metal2vulkan/src/lower/access/quad.rs index ba57d893b..74acdff5b 100644 --- a/crates/metal2vulkan/src/lower/access/quad.rs +++ b/crates/metal2vulkan/src/lower/access/quad.rs @@ -759,7 +759,7 @@ pub(super) fn emit<'c>(cx: &mut EmitCx<'c>, fb: &mut FunctionBuilder<'_>, q: &Qu } let p = cx.operand(fb, first.ptr)?; let m = fat_part(fb, p, 1)?; - let mut at = prepare(cx, fb, t, m, (16, false))?; + let mut at = prepare(cx, fb, t, m, (16, false), false)?; at.mem = at .mem .with(WordOps::of(crate::lower::sync::memory_model::coherence( diff --git a/crates/metal2vulkan/src/lower/simd/uniform/tests.rs b/crates/metal2vulkan/src/lower/simd/uniform/tests.rs index 35b28ef24..1f410a03b 100644 --- a/crates/metal2vulkan/src/lower/simd/uniform/tests.rs +++ b/crates/metal2vulkan/src/lower/simd/uniform/tests.rs @@ -187,6 +187,7 @@ fn load(fb: &mut FunctionBuilder<'_>, ty: TypeId, ptr: Value) -> Value { volatile: false, atomic: None, range: None, + speculative: false, }, ) } diff --git a/crates/metal2vulkan/src/memory/plan/tests.rs b/crates/metal2vulkan/src/memory/plan/tests.rs index 288f40690..14d807f9e 100644 --- a/crates/metal2vulkan/src/memory/plan/tests.rs +++ b/crates/metal2vulkan/src/memory/plan/tests.rs @@ -171,6 +171,7 @@ fn load(fb: &mut FunctionBuilder<'_>, ty: TypeId, ptr: Value) -> Value { volatile: false, atomic: None, range: None, + speculative: false, }, ) } @@ -1382,6 +1383,7 @@ fn an_argument_buffer_texture_member_seeds_a_dynamic_handle() { volatile: false, atomic: None, range: None, + speculative: false, }, ); let _ = fb.push(ptr, InstKind::Freeze(t)); @@ -1728,6 +1730,7 @@ fn a_texture_array_parameter_is_a_pointer_to_its_handles() { volatile: false, atomic: None, range: None, + speculative: false, }, ); let _ = fb.push(tex, InstKind::Freeze(t)); @@ -1793,6 +1796,7 @@ fn a_handle_array_load_laid_out_before_its_gep_is_not_dynamic() { volatile: false, atomic: None, range: None, + speculative: false, }, ); let _ = fb.push(tex, InstKind::Freeze(t)); @@ -2023,6 +2027,7 @@ fn heap_chain_kernel(n: usize) -> (Entry, Value) { volatile: false, atomic: None, range: None, + speculative: false, }, ) }; diff --git a/crates/metal2vulkan/src/memory/plan/tests/gaps.rs b/crates/metal2vulkan/src/memory/plan/tests/gaps.rs index 8e0ed7008..fa9c16a23 100644 --- a/crates/metal2vulkan/src/memory/plan/tests/gaps.rs +++ b/crates/metal2vulkan/src/memory/plan/tests/gaps.rs @@ -30,6 +30,7 @@ fn element(fb: &mut FunctionBuilder<'_>, t: Value, k: Value) -> Value { volatile: false, atomic: None, range: None, + speculative: false, }, ) } @@ -299,6 +300,7 @@ fn an_argument_buffer_table_element_seeds_its_members() { volatile: false, atomic: None, range: None, + speculative: false, }, ); t = fb.push( @@ -309,6 +311,7 @@ fn an_argument_buffer_table_element_seeds_its_members() { volatile: false, atomic: None, range: None, + speculative: false, }, ); let _ = fb.push(dptr, InstKind::Freeze(t)); diff --git a/crates/metal2vulkan/src/pipeline/sym.rs b/crates/metal2vulkan/src/pipeline/sym.rs index 28e48a58c..35159984e 100644 --- a/crates/metal2vulkan/src/pipeline/sym.rs +++ b/crates/metal2vulkan/src/pipeline/sym.rs @@ -686,8 +686,10 @@ pub enum PushField { /// Under the identity domains, a buffer slot's buffer (`uvec2`): the bytes of the buffer before /// the slot's bind offset (the bind offset), then the buffer's length; for a `set*Bytes` copy 0 /// and its length, for nil 0 and 0. A load, store or atomic of the slot at a byte offset `m` - /// from the bind offset, read as signed, that is not a translation-time constant is checked - /// against the buffer, `(len >= n) && (m + before <= len - n)` in `u32`, as `m + before < + /// from the bind offset, read as signed, that is not a translation-time constant, and a load + /// the translator makes where the program did not run it (a kernel's constant-reference load + /// made in its entry block, a load of a branch's arm Metal's backend speculates) at any `m`, is + /// checked against the buffer, `(len >= n) && (m + before <= len - n)` in `u32`, as `m + before < /// len - min(len, n - 1)` with the limit made once per slot and size: outside, a load reads /// zero at `ZeroAddress` and a store or atomic runs nothing (`docs/API.md`, section 5). A /// buffer is at most 2 GiB, so the length is never `u32::MAX`: a floor stage whose tail it is diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 2698c7c1a..34e08da25 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -8385,7 +8385,7 @@ variant metal2vulkan-air::ir::InstKind::Gep Gep { src_ty: TypeId, base: Value, i variant metal2vulkan-air::ir::InstKind::ICmp ICmp { pred: IntPredicate, a: Value, b: Value } variant metal2vulkan-air::ir::InstKind::InsertElement InsertElement { vec: Value, elt: Value, idx: Value } variant metal2vulkan-air::ir::InstKind::InsertValue InsertValue { agg: Value, val: Value, indices: Box<[u32]> } -variant metal2vulkan-air::ir::InstKind::Load Load { ptr: Value, align: Option, volatile: bool, atomic: Option, range: Option } +variant metal2vulkan-air::ir::InstKind::Load Load { ptr: Value, align: Option, volatile: bool, atomic: Option, range: Option, speculative: bool } variant metal2vulkan-air::ir::InstKind::Phi Phi { incoming: Box<[(Value, BlockId)]>, fmf: FastMath } variant metal2vulkan-air::ir::InstKind::Ret Ret(Option) variant metal2vulkan-air::ir::InstKind::Select Select { c: Value, t: Value, f: Value, fmf: FastMath } diff --git a/docs/API.md b/docs/API.md index 365f15430..29462130c 100644 --- a/docs/API.md +++ b/docs/API.md @@ -125,9 +125,12 @@ the runtime's, the command line's, the compile worker's and every validation too translation-time constant is checked against the slot's buffer (`PushField::SlotBounds`), from the buffer's start to its end, as Metal's domain is the buffer: an offset before the bind offset reads and writes the buffer's bytes there. Outside the buffer, a load reads zero and a - store or atomic does nothing (section 5). An access at a constant offset is not checked. A - pointer loaded from memory or made from an integer, null included, is used as given: no binding - bounds its accesses. A slot + store or atomic does nothing (section 5). An access at a constant offset is not checked, but for + a load the translator makes where the program did not run it, which is checked at any offset: a + kernel's load of a `constant T&` parameter's object made in its entry block ahead of the branch + it stood behind, and a load of a branch's arm that Metal's backend speculates. A pointer loaded + from memory or made from an integer, null included, is used as given: no binding bounds its + accesses. A slot whose argument states an alignment of at least 4 (`air.arg_type_align_size`) is reached from that address as it is: each access is at the pushed word plus its 32-bit byte offset plus 2^31, modulo 2^32, zero-extended, which is the address plus the offset read as signed, exact as the @@ -1297,12 +1300,13 @@ for dependency in &pipeline.dependencies { alone is a new push word. - Under the identity domains, a buffer slot that an access may reach at a byte offset that is not a translation-time constant (an index the memory plan does not prove one value, a looping `memcpy` - or `memset`, a pulled fetch) also reads `PushField::SlotBounds`: a `uvec2`, the bound buffer's - bytes before the bind offset (the bind offset), then the buffer's length; 0 and the length of its - `setBytes` copy; 0 and 0 where nothing is bound. Each such access whose offset the module does not - hold as a constant is checked against the buffer: for an `n`-byte access at its 32-bit byte offset - `m` from the bind offset, read as signed, the normative check `(len >= n) && (m + before <= len - - n)` in `u32`. The domain is the bound buffer, as Metal's is and as a storage view of a whole + or `memset`, a pulled fetch), or that a load reaches where the program did not run it (section + 1, "The forms"), also reads `PushField::SlotBounds`: a `uvec2`, the bound buffer's bytes before + the bind offset (the bind offset), then the buffer's length; 0 and the length of its `setBytes` + copy; 0 and 0 where nothing is bound. Each such access whose offset the module does not hold as + a constant, and each such load, is checked against the buffer: for an `n`-byte access at its + 32-bit byte offset `m` from the bind offset, read as signed, the normative check `(len >= n) && + (m + before <= len - n)` in `u32`. The domain is the bound buffer, as Metal's is and as a storage view of a whole window's is (from the buffer's start): an offset before the bind offset is inside where the buffer holds it, and one before the buffer's start wraps to at least 2^31, outside. The module computes it as `m + before < limit`, the slot's limit for `n`-byte accesses `len - min(len, n - 1)` (0 for diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index e73812345..6addb6556 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -72,7 +72,7 @@ rest is `crates/metal2vulkan/src/`. | Module | Role | |---|---| -| `air` (`metal2vulkan-air`) | The container (metallib, bitcode wrapper, raw module), the bitstream and bitcode readers, the typed IR, the `air.*` and `llvm.*` intrinsic families, the metadata ABI (`AirAbi`), and canonicalization (`canon`: inlining (each `byval` argument's copy made at its call first), function constants, SCCP (a value one of a few constants, from a PHI of literal constants or a `select` between two, folded member by member so a branch every member decides alike is decided; reading the integer fields of a constant global whose value is known, folding the integer bit operations `llvm.ctpop`, `llvm.bitreverse` and `llvm.bswap` and the scalar `llvm.umin`, `llvm.umax`, `llvm.smin` and `llvm.smax` on constants, settling the float operations a constant operand decides whatever the others hold (a NaN operand, the first in order: as it is beside a value the run computes, quieted where every operand is a constant; a product by a zero under `nnan` and `nsz`, `+0`), and reading the immediates of an intrinsic call that its function's parameters gave it once inlining makes them its call site's constants), the unrolling of loops whose constant trip count decides a branch where that leaves the entry no larger, the allocation of a private array of nested arrays as far as its indices reach where constants and counted loops bound every one of them (`canon::reach`), a pointer loaded from a constant table at an index only the run knows (a table of constexpr samplers) read as the `select` chain over the table's elements (`canon::const_tables`), each of MSL 4.1's generic pointers made a pointer of the one address space every pointer it may hold comes from, its space queries answered (`canon::generic`), devirtualization, linking, the load of a stack allocation's field that one dominating store wrote read as the stored value (an aggregate holding a pointer excepted), and an allocation no read is left of removed with its stores, so a lambda's closure of captured addresses leaves the captured objects' own (`canon::forward`), pruning, pointee erasure, the speculation of the short branch arms Metal's backend runs in every lane, the split of a whole array's or struct's load or store in buffer or threadgroup memory into its members' accesses, a kernel's plain loads of a `constant T&` parameter's object at an offset fixed at translation time made in its entry block where nothing on any path before them may write device memory (`canon::const_hoist`), and a kernel of a pipeline of OpenCL mode linked as Metal links it: the three hidden buffers appended, its buffer indices 3 on, OpenCL C's work-item reads made reads of their built-ins or of the first buffer, each image format query a read of the third, each `air.wg.barrier`'s flags read as OpenCL C's `cl_mem_fence_flags`, and each operation of a 1D image the 2D texture's that Apple's OpenCL binds for it, `canon::opencl` and `canon::opencl_1d`; and OpenCL C's vector data loads and stores made their element accesses, `canon::vector_data`). Canonicalization also writes the formats the binder and runtime read: the visible-function table's words and the rasterization-rate map's parameter data | +| `air` (`metal2vulkan-air`) | The container (metallib, bitcode wrapper, raw module), the bitstream and bitcode readers, the typed IR, the `air.*` and `llvm.*` intrinsic families, the metadata ABI (`AirAbi`), and canonicalization (`canon`: inlining (each `byval` argument's copy made at its call first), function constants, SCCP (a value one of a few constants, from a PHI of literal constants or a `select` between two, folded member by member so a branch every member decides alike is decided; reading the integer fields of a constant global whose value is known, folding the integer bit operations `llvm.ctpop`, `llvm.bitreverse` and `llvm.bswap` and the scalar `llvm.umin`, `llvm.umax`, `llvm.smin` and `llvm.smax` on constants, settling the float operations a constant operand decides whatever the others hold (a NaN operand, the first in order: as it is beside a value the run computes, quieted where every operand is a constant; a product by a zero under `nnan` and `nsz`, `+0`), and reading the immediates of an intrinsic call that its function's parameters gave it once inlining makes them its call site's constants), the unrolling of loops whose constant trip count decides a branch where that leaves the entry no larger, the allocation of a private array of nested arrays as far as its indices reach where constants and counted loops bound every one of them (`canon::reach`), a pointer loaded from a constant table at an index only the run knows (a table of constexpr samplers) read as the `select` chain over the table's elements (`canon::const_tables`), each of MSL 4.1's generic pointers made a pointer of the one address space every pointer it may hold comes from, its space queries answered (`canon::generic`), devirtualization, linking, the load of a stack allocation's field that one dominating store wrote read as the stored value (an aggregate holding a pointer excepted), and an allocation no read is left of removed with its stores, so a lambda's closure of captured addresses leaves the captured objects' own (`canon::forward`), pruning, pointee erasure, the speculation of the short branch arms Metal's backend runs in every lane, the split of a whole array's or struct's load or store in buffer or threadgroup memory into its members' accesses, a kernel's plain loads of a `constant T&` parameter's object at an offset fixed at translation time made in its entry block where nothing on any path before them may write device memory and no other root shares the parameter's pointer, each marked speculative, as the speculated arms' loads are, so lowering contains it against a short or absent binding at any offset (`canon::const_hoist`), and a kernel of a pipeline of OpenCL mode linked as Metal links it: the three hidden buffers appended, its buffer indices 3 on, OpenCL C's work-item reads made reads of their built-ins or of the first buffer, each image format query a read of the third, each `air.wg.barrier`'s flags read as OpenCL C's `cl_mem_fence_flags`, and each operation of a 1D image the 2D texture's that Apple's OpenCL binds for it, `canon::opencl` and `canon::opencl_1d`; and OpenCL C's vector data loads and stores made their element accesses, `canon::vector_data`). Canonicalization also writes the formats the binder and runtime read: the visible-function table's words and the rasterization-rate map's parameter data | | `graph` | The shared RPO, dominator tree, loop forest and SCC | | `budget` | `Budget`, `CancelToken`, and the per-attempt `Meter`: deadline, cancellation, work units, the byte ledger and every structural cap | | `memory/` | Pointer provenance, the `MemoryPlan`, leaf access emitters, arenas, root and handle lookups, word composition, atomics; `memory::views`, a descriptor slot's views: a storage block or a uniform block |