From 89d8e46d263fcd59c489cb048c0403fc14e02476 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Sat, 7 Nov 2026 09:17:55 -0800 Subject: [PATCH] Bind an intrinsic's immediates from the call sites of the function passing them on Metal's compiler leaves OpenCL C's barrier(flags) and mem_fence(flags) out of line: an internal function passes its parameter on as air.wg.barrier's flags, and mem_fence computes air.atomic.fence's flags from it through llvm.bitreverse.i2. Every call site passes a constant. Decode refused the call (Intrinsic(ImmediateNotConstant)), and so every OpenCL kernel that synchronizes was refused. Decode now keeps such a call as Callee::Unbound, with the family its declaration names (intrinsics::Template). Once inlining has made the parameter the call site's constant, SCCP's edit binds it in the same rebuild, with no pass of its own. SCCP also folds the integer llvm.* operations (min/max, ctpop, bitreverse, bswap) over constants. LlvmIntrinsic::NarrowInt decodes those operations on widths no SPIR-V type has (i2), so the fence's flags fold. An immediate still not constant after canonicalization is refused at the call, in post_check, with the inlined entry's function location. A NarrowInt that survives is refused as Lowering(Arith). Tests: - canon::tests::unbound_immediates: each call site binds its own flags; binding meters no more work than the constant twin (264 vs 265 units) and prints the same module; the i2 fence binds after folding; flags read from a buffer are refused at the call. - intrinsics::tests: the narrow-width decode. - runtime tests::opencl_kernels: a barrier and a fence out of line compute what the M3 and the Intel UHD 630 compute. Verified on the same changes at base c956a4236c: metal2vulkan-air 516/516 (m3-max-4223), the runtime test on lavapipe (m3-max-4223), and the consumer's glcheck b, b0, f and f0 passing with the 5080 and 780M profiles (m3-max-4227). (cherry picked from commit f49960f427b2f1371468b97a215788dea8018d45) --- .../metal2vulkan-air/src/bitcode/function.rs | 16 +- .../metal2vulkan-air/src/bitcode/markers.rs | 1 + .../src/canon/command_writes.rs | 4 +- .../src/canon/discard_sink.rs | 5 +- crates/metal2vulkan-air/src/canon/fold.rs | 21 +- .../metal2vulkan-air/src/canon/interface.rs | 6 +- crates/metal2vulkan-air/src/canon/mod.rs | 23 ++- crates/metal2vulkan-air/src/canon/reads.rs | 2 +- crates/metal2vulkan-air/src/canon/renumber.rs | 28 ++- crates/metal2vulkan-air/src/canon/sccp.rs | 85 +++++++- .../metal2vulkan-air/src/canon/static_init.rs | 8 +- crates/metal2vulkan-air/src/canon/tests.rs | 1 + .../src/canon/tests/unbound_immediates.rs | 194 ++++++++++++++++++ .../src/intrinsics/families_tests.rs | 4 +- .../metal2vulkan-air/src/intrinsics/llvm.rs | 47 ++++- crates/metal2vulkan-air/src/intrinsics/mod.rs | 44 +++- .../metal2vulkan-air/src/intrinsics/tests.rs | 52 ++++- crates/metal2vulkan-air/src/ir/inst.rs | 26 ++- crates/metal2vulkan-air/src/ir/print.rs | 3 + crates/metal2vulkan-air/src/ir/verify.rs | 1 + crates/metal2vulkan-air/tests/api_surface.txt | 1 + crates/metal2vulkan-runtime/src/tests/mod.rs | 2 + .../src/tests/opencl_kernels.rs | 152 ++++++++++++++ .../src/air_writer/tests.rs | 3 + .../src/bitcode_audit.rs | 21 +- .../src/check/loop_free.rs | 2 +- .../src/oracle_fuel/plan.rs | 2 +- crates/metal2vulkan/src/lower/arith/mod.rs | 4 +- .../src/lower/fragment/discard.rs | 7 +- crates/metal2vulkan/src/lower/select.rs | 7 + crates/metal2vulkan/src/lower/simd/uniform.rs | 1 + .../src/pipeline/compile/partition.rs | 5 +- crates/metal2vulkan/src/reflection/live.rs | 6 +- crates/metal2vulkan/src/tests/air_input.rs | 30 ++- crates/metal2vulkan/tests/api_signatures.tsv | 7 + docs/API.md | 11 + docs/ARCHITECTURE.md | 2 +- 37 files changed, 758 insertions(+), 76 deletions(-) create mode 100644 crates/metal2vulkan-air/src/canon/tests/unbound_immediates.rs create mode 100644 crates/metal2vulkan-runtime/src/tests/opencl_kernels.rs diff --git a/crates/metal2vulkan-air/src/bitcode/function.rs b/crates/metal2vulkan-air/src/bitcode/function.rs index a26ceab2c..fb7bf35a0 100644 --- a/crates/metal2vulkan-air/src/bitcode/function.rs +++ b/crates/metal2vulkan-air/src/bitcode/function.rs @@ -1461,9 +1461,19 @@ impl FnDecoder { let at = Location::function(self.symbol_name(cx, self.func), None, None); return Err(InputError::new(kind, at).into()); } - Err(e) => { - return Err(InputError::new(InputErrorKind::Intrinsic(e), s.location()).into()) - } + // An immediate this function computes, such as one of its parameters (OpenCL + // C's `barrier(flags)` out of line): specialization binds the call where inlining + // and constant propagation make it each call site's constant. + Err(e) => match (e, class.template()) { + (IntrinsicError::ImmediateNotConstant, Some(template)) => { + Callee::Unbound { decl: f, template } + } + (e, _) => { + return Err( + InputError::new(InputErrorKind::Intrinsic(e), s.location()).into() + ) + } + }, }, }; let call = Call { diff --git a/crates/metal2vulkan-air/src/bitcode/markers.rs b/crates/metal2vulkan-air/src/bitcode/markers.rs index ff3e9386d..482160a5f 100644 --- a/crates/metal2vulkan-air/src/bitcode/markers.rs +++ b/crates/metal2vulkan-air/src/bitcode/markers.rs @@ -376,6 +376,7 @@ impl Plan { match &mut call.callee { Callee::Direct(f) | Callee::UnknownIntrinsic(f) + | Callee::Unbound { decl: f, .. } | Callee::Air { decl: f, .. } | Callee::Llvm { decl: f, .. } => *f = self.func(*f)?, Callee::Indirect { fn_ty, .. } => *fn_ty = self.ty(*fn_ty)?, diff --git a/crates/metal2vulkan-air/src/canon/command_writes.rs b/crates/metal2vulkan-air/src/canon/command_writes.rs index eaf3409c6..694820980 100644 --- a/crates/metal2vulkan-air/src/canon/command_writes.rs +++ b/crates/metal2vulkan-air/src/canon/command_writes.rs @@ -182,7 +182,9 @@ pub(super) fn command_writes(module: &Module, ep: &EntryPoint) -> CommandWrites .. } => writes = writes.union(CommandWrites::of(op, call, parts)), Callee::Air { .. } | Callee::Llvm { .. } => {} - Callee::Indirect { .. } | Callee::UnknownIntrinsic(_) => return CommandWrites::ANY, + Callee::Indirect { .. } | Callee::UnknownIntrinsic(_) | Callee::Unbound { .. } => { + return CommandWrites::ANY + } Callee::Direct(f) => { if declared(f) && !ep.is_control_point_function(f) { return CommandWrites::ANY; diff --git a/crates/metal2vulkan-air/src/canon/discard_sink.rs b/crates/metal2vulkan-air/src/canon/discard_sink.rs index f4494dd6e..ae1238db8 100644 --- a/crates/metal2vulkan-air/src/canon/discard_sink.rs +++ b/crates/metal2vulkan-air/src/canon/discard_sink.rs @@ -166,7 +166,10 @@ fn has_side_effect(kind: &InstKind) -> bool { | crate::intrinsics::LlvmIntrinsic::Memcpy { .. } | crate::intrinsics::LlvmIntrinsic::Memmove { .. } ), - Callee::Direct(_) | Callee::Indirect { .. } | Callee::UnknownIntrinsic(_) => true, + Callee::Direct(_) + | Callee::Indirect { .. } + | Callee::UnknownIntrinsic(_) + | Callee::Unbound { .. } => true, }, _ => false, } diff --git a/crates/metal2vulkan-air/src/canon/fold.rs b/crates/metal2vulkan-air/src/canon/fold.rs index bd14b7f73..7fac17a40 100644 --- a/crates/metal2vulkan-air/src/canon/fold.rs +++ b/crates/metal2vulkan-air/src/canon/fold.rs @@ -701,17 +701,26 @@ impl Folder<'_> { .map(Some) } - /// `llvm.ctpop` over a scalar integer. - pub fn ctpop( + /// `llvm.{ctpop,bitreverse,bswap}` over a scalar integer (`bswap` of a width that is a + /// multiple of 16 bits, as LLVM defines it). + pub fn int_unary( &mut self, + op: LlvmIntOp, ty: TypeId, x: ConstId, m: &mut Meter, ) -> Result, Error> { - match self.int(x) { - Some(v) => self.mk_int(ty, u64::from(v.count_ones()), m), - None => Ok(None), - } + let (Some(w), Some(v)) = (self.int_bits(ty), self.int(x)) else { + return Ok(None); + }; + let shift = 64 - u32::from(w.min(64)); + let r = match op { + LlvmIntOp::Ctpop => u64::from(v.count_ones()), + LlvmIntOp::BitReverse if w <= 64 => v.reverse_bits() >> shift, + LlvmIntOp::Bswap if w <= 64 && w % 16 == 0 => v.swap_bytes() >> shift, + _ => return Ok(None), + }; + self.mk_int(ty, r, m) } /// An integer-to-float conversion (`sitofp`/`uitofp`, `air.convert.f.*.{s,u}.*`) of a scalar diff --git a/crates/metal2vulkan-air/src/canon/interface.rs b/crates/metal2vulkan-air/src/canon/interface.rs index 3b8d67060..b5ce89e33 100644 --- a/crates/metal2vulkan-air/src/canon/interface.rs +++ b/crates/metal2vulkan-air/src/canon/interface.rs @@ -1080,11 +1080,15 @@ fn value_only(kind: &InstKind) -> bool { op, LlvmIntrinsic::Float { .. } | LlvmIntrinsic::Int { .. } + | LlvmIntrinsic::NarrowInt { .. } | LlvmIntrinsic::Abs { .. } | LlvmIntrinsic::Cttz { .. } | LlvmIntrinsic::Ctlz { .. } ), - Callee::Direct(_) | Callee::Indirect { .. } | Callee::UnknownIntrinsic(_) => false, + Callee::Direct(_) + | Callee::Indirect { .. } + | Callee::UnknownIntrinsic(_) + | Callee::Unbound { .. } => false, } } diff --git a/crates/metal2vulkan-air/src/canon/mod.rs b/crates/metal2vulkan-air/src/canon/mod.rs index 1a8bd1d21..ba6d60c4e 100644 --- a/crates/metal2vulkan-air/src/canon/mod.rs +++ b/crates/metal2vulkan-air/src/canon/mod.rs @@ -29,14 +29,17 @@ //! call through a table a switch over the functions it may call; the direct calls this makes are //! inlined in turn, round after round, until none is made. //! 7. **SCCP** over the inlined entry, including `air.is_function_constant_defined`, loads of -//! bound constants, and loads of the integer fields of a constant-space global whose value is -//! its initializer (`const_loads`); unreachable blocks are deleted. A value use of an unsupplied +//! bound constants, loads of the integer fields of a constant-space global whose value is +//! its initializer (`const_loads`), and the integer `llvm.*` operations on constants; +//! unreachable blocks are deleted. A call whose immediates were not constants where it was +//! decoded (`Callee::Unbound`: an internal function's parameter passed on to the intrinsic) is +//! bound where they now are, each inlined copy with its own call site's constants. A value use of an unsupplied //! constant that survives is `Error::NeedsInput(FunctionConstant)`. **Unrolling**: a loop whose //! trip count SCCP made constant, and whose counter decides a branch of its body, is unrolled //! within fixed ceilings, and SCCP runs again over the copies; the result is kept where it is //! no larger than the loops it replaces (`unroll`). -//! 8. **Post-check**: no unknown intrinsic, indirect call, or call to an undefined non-intrinsic -//! function survives, and no reachable branch tests `undef`. A table call's refused candidate, +//! 8. **Post-check**: no unknown or unbound intrinsic, indirect call, or call to an undefined +//! non-intrinsic function survives, and no reachable branch tests `undef`. A table call's refused candidate, //! a table call no linked function answers, and a function pointer used as a value are refused //! here, as stubs are. Indirect calls, calls to functions of a dynamic library, and ray //! intersection are refused as their typed features, not implemented yet, naming the callee; a @@ -389,7 +392,9 @@ fn calls(module: &Module, ep: &EntryPoint, wanted: impl Fn(&AirIntrinsic) -> boo .any(|inst| match &inst.kind { InstKind::Call(call) => match call.callee { Callee::Air { op, .. } => wanted(&op), - Callee::Indirect { .. } | Callee::UnknownIntrinsic(_) => true, + Callee::Indirect { .. } | Callee::UnknownIntrinsic(_) | Callee::Unbound { .. } => { + true + } Callee::Llvm { .. } => false, Callee::Direct(f) => declared(f) && !ep.is_control_point_function(f), }, @@ -1245,7 +1250,8 @@ pub fn select<'a>(module: &Module, abi: &'a AirAbi, entry: &str) -> Result<&'a E } /// Each refusal carries the call's location in the inlined body (the entry's function, block, and -/// instruction) and names its callee's symbol where it has one. Indirect calls devirtualization +/// instruction) and names its callee's symbol where it has one. A call whose immediates are still +/// not constants (`Callee::Unbound`) is `InvalidInput(Intrinsic(ImmediateNotConstant))`. Indirect calls devirtualization /// left (a function pointer loaded from memory or computed, a table that is no entry parameter), /// calls to functions this module does not define (linking), and unknown intrinsics of a typed /// family (`intrinsics::UNDECODED_FEATURES`) are refused as their features, not implemented yet; @@ -1323,6 +1329,11 @@ fn post_check( }; let refusal = match call.callee { Callee::Air { .. } | Callee::Llvm { .. } => continue, + // An immediate that inlining and constant propagation did not make a constant. + Callee::Unbound { .. } => { + let kind = InputErrorKind::Intrinsic(IntrinsicError::ImmediateNotConstant); + return Err(InputError::new(kind, at).into()); + } // The decoder keeps a call through a function's own constant address indirect when // the call's function type is not the function's (`bitcode::function`): its callee // is still that one function, so it is classified by the function, not as dynamic. diff --git a/crates/metal2vulkan-air/src/canon/reads.rs b/crates/metal2vulkan-air/src/canon/reads.rs index 065b4e413..7f6d3b6f7 100644 --- a/crates/metal2vulkan-air/src/canon/reads.rs +++ b/crates/metal2vulkan-air/src/canon/reads.rs @@ -874,7 +874,7 @@ impl<'a> Flow<'a> { .. } | Callee::Llvm { - op: LlvmIntrinsic::Int { .. }, + op: LlvmIntrinsic::Int { .. } | LlvmIntrinsic::NarrowInt { .. }, .. } => self.union(f, &call.args, m)?, _ => return Ok(Some(Unfollowed)), diff --git a/crates/metal2vulkan-air/src/canon/renumber.rs b/crates/metal2vulkan-air/src/canon/renumber.rs index 0305011c8..7532df8a1 100644 --- a/crates/metal2vulkan-air/src/canon/renumber.rs +++ b/crates/metal2vulkan-air/src/canon/renumber.rs @@ -19,7 +19,7 @@ use std::collections::HashMap; use crate::budget::Meter; use crate::error::Error; -use crate::intrinsics::{AgxOp, LlvmIntrinsic}; +use crate::intrinsics::{AgxOp, LlvmIntrinsic, Template}; use crate::ir::{Arena, Block, Body, Call, CallAttrs, Callee, Const, ConstExpr, ConstId}; use crate::ir::{ConstTable, Constant, FnAttrs, FuncId, Function, Global, GlobalId, Idx}; use crate::ir::{Inst, InstKind, ParamAttrs, Section, Sym, Symbols, Type, TypeId}; @@ -591,6 +591,17 @@ impl<'a> Renumber<'a> { Ok(out) } + /// `op` with its symbol renumbered: an unmodeled AGX operation is the one that keeps its + /// name, for diagnostics. + fn llvm_op(&mut self, op: LlvmIntrinsic, m: &mut Meter) -> Result { + Ok(match op { + LlvmIntrinsic::Agx(AgxOp::Unmodeled(s)) => { + LlvmIntrinsic::Agx(AgxOp::Unmodeled(self.sym(s, m)?)) + } + other => other, + }) + } + fn call(&mut self, call: &mut Call, m: &mut Meter) -> Result<(), Error> { call.callee = match call.callee { Callee::Direct(f) => Callee::Direct(self.func_id(f)?), @@ -604,15 +615,16 @@ impl<'a> Renumber<'a> { }, Callee::Llvm { decl, op } => Callee::Llvm { decl: self.func_id(decl)?, - // The one operation that keeps its name, for diagnostics. - op: match op { - LlvmIntrinsic::Agx(AgxOp::Unmodeled(s)) => { - LlvmIntrinsic::Agx(AgxOp::Unmodeled(self.sym(s, m)?)) - } - other => other, - }, + op: self.llvm_op(op, m)?, }, Callee::UnknownIntrinsic(f) => Callee::UnknownIntrinsic(self.func_id(f)?), + Callee::Unbound { decl, template } => Callee::Unbound { + decl: self.func_id(decl)?, + template: match template { + Template::Llvm(op) => Template::Llvm(self.llvm_op(op, m)?), + air => air, + }, + }, }; if let Some(a) = &call.attrs { let mut params = Vec::with_capacity(a.params.len()); diff --git a/crates/metal2vulkan-air/src/canon/sccp.rs b/crates/metal2vulkan-air/src/canon/sccp.rs index 6e21d4a95..eb3ad5c2e 100644 --- a/crates/metal2vulkan-air/src/canon/sccp.rs +++ b/crates/metal2vulkan-air/src/canon/sccp.rs @@ -36,9 +36,10 @@ use std::collections::{BTreeSet, HashMap, HashSet}; use crate::budget::{vec_bytes, Meter}; -use crate::error::{AbiError, CanonError, DiagName, Error, InputError, InputErrorKind, Location}; -use crate::intrinsics::{AirIntrinsic, FunctionConstant}; -use crate::ir::{Arena, BlockId, Body, Callee, Const, ConstId, ConstTable, Constant, Global}; +use crate::error::{AbiError, CanonError, DiagName, Error, InputError, InputErrorKind}; +use crate::error::{IntrinsicError, Location}; +use crate::intrinsics::{AirIntrinsic, Bound, FunctionConstant, LlvmIntOp, LlvmIntrinsic}; +use crate::ir::{Arena, BlockId, Body, Call, Callee, Const, ConstId, ConstTable, Constant, Global}; use crate::ir::{ArgIdx, BinOp, GlobalId, Idx, InstId, InstKind, Type, Value}; use super::const_loads; @@ -299,6 +300,20 @@ fn is_normalize(kind: &InstKind) -> bool { ) } +/// The integer `llvm.*` operation `kind` calls, which SCCP folds over constant operands. +fn int_op(kind: &InstKind) -> Option { + match kind { + InstKind::Call(call) => match call.callee { + Callee::Llvm { + op: LlvmIntrinsic::Int { op, .. } | LlvmIntrinsic::NarrowInt { op, .. }, + .. + } => Some(op), + _ => None, + }, + _ => None, + } +} + /// What the lattice value of a branch condition decides. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Decision { @@ -1011,6 +1026,19 @@ impl<'b> Solver<'b> { }, None => Lat::Bottom, }, + // An integer operation on constants is their constant; on an undefined value, what + // the run computes, as any call's. + InstKind::Call(call) if int_op(&inst.kind).is_some() => { + let op = int_op(&inst.kind).ok_or_else(|| invariant("an integer operation"))?; + match self.pure(&call.args, cx, m, |f, c, m| match c { + [x] => f.int_unary(op, ty, *x, m), + [x, y] => f.int_minmax(op, ty, *x, *y, m), + _ => Ok(None), + })? { + Lat::Fc(_) => Lat::Bottom, + lat => lat, + } + } kind @ InstKind::Call(_) => match is_defined_arg(kind, cx.folder.consts, cx.fcs) { Some(Some(g)) => { let supplied = cx.fcs.get(&g).is_some_and(|f| f.supplied); @@ -1146,6 +1174,51 @@ impl<'b> Solver<'b> { found.into_iter().try_for_each(|k| read(reads, k, m)) } + /// The call `call` (at block and instruction `at`) bound, when it is `Callee::Unbound` and + /// its immediates are constants now: its constant operands are written in, and the + /// intrinsic binds as decode binds it. `None` for any other call, and for one whose + /// immediates are still not all constants (the post-check refuses it). + fn bound( + &self, + call: &Call, + cx: &Context<'_>, + (b, i): (BlockId, InstId), + m: &mut Meter, + held: &mut usize, + ) -> Result, Error> { + let Callee::Unbound { decl, template } = call.callee else { + return Ok(None); + }; + // The rewritten call is the edit's until the body is rebuilt. + let bytes = std::mem::size_of::().saturating_add(call.heap_bytes()); + m.charge(bytes)?; + *held = held.saturating_add(bytes); + let mut args = call.args.clone(); + for a in args.iter_mut() { + if let Lat::Const(c) = self.lat(*a) { + *a = Value::Const(c); + } + } + let callee = match template.bind(&args, cx.folder.consts) { + Ok(Bound::Air(op)) => Callee::Air { decl, op }, + Ok(Bound::Llvm(op)) => Callee::Llvm { decl, op }, + Ok(Bound::Unknown) => Callee::UnknownIntrinsic(decl), + Err(IntrinsicError::ImmediateNotConstant) => return Ok(None), + Err(e) => { + let at = Location::function(cx.name.clone(), Some(b.raw()), Some(i.raw())); + return Err(InputError::new(InputErrorKind::Intrinsic(e), at).into()); + } + }; + Ok(Some(InstKind::Call(Box::new(Call { + callee, + args, + fmf: call.fmf, + tail: call.tail, + attrs: call.attrs.clone(), + range: call.range.clone(), + })))) + } + fn edit( &self, cx: &mut Context<'_>, @@ -1171,6 +1244,7 @@ impl<'b> Solver<'b> { let lat = self.val.get(i.index()).copied().unwrap_or(Lat::Bottom); let deletable = is_pure(&inst.kind) || is_normalize(&inst.kind) + || int_op(&inst.kind).is_some() || is_defined_arg(&inst.kind, cx.folder.consts, cx.fcs).is_some(); match (&inst.kind, lat) { // A field's address constant serves the loads it folds; the instruction stays, @@ -1244,6 +1318,11 @@ impl<'b> Solver<'b> { ); } } + (InstKind::Call(call), _) => { + if let Some(bound) = self.bound(call, cx, (b, i), m, held)? { + edit.rewrite.insert(i, bound); + } + } _ => {} } let replaced = edit.replace.get(i.index()).is_some_and(Option::is_some); diff --git a/crates/metal2vulkan-air/src/canon/static_init.rs b/crates/metal2vulkan-air/src/canon/static_init.rs index c39188da4..65eb4f8f9 100644 --- a/crates/metal2vulkan-air/src/canon/static_init.rs +++ b/crates/metal2vulkan-air/src/canon/static_init.rs @@ -53,7 +53,7 @@ use std::collections::{BTreeMap, HashMap}; use crate::budget::Meter; use crate::error::{CanonError, DiagName, InputError, InputErrorKind, Location}; use crate::error::{Error, Feature, Unsupported}; -use crate::intrinsics::{AirIntrinsic, FunctionConstant, LlvmIntOp, LlvmIntrinsic, NumKind}; +use crate::intrinsics::{AirIntrinsic, FunctionConstant, LlvmIntrinsic, NumKind}; use crate::ir::layout::Endian; use crate::ir::{AddrSpace, Arena, BlockId, Body, Callee, CastOp, Const, ConstExpr, ConstId}; use crate::ir::{Constant, FuncId, Function, Global, GlobalId, Idx, InstId, InstKind}; @@ -520,16 +520,16 @@ impl<'a> Eval<'a> { SVal::C(c.ok_or_else(|| not_evaluable(at.clone()))?) } Callee::Llvm { - op: LlvmIntrinsic::Int { op, .. }, + op: LlvmIntrinsic::Int { op, .. } | LlvmIntrinsic::NarrowInt { op, .. }, .. } => match &call.args[..] { [a, b] => { let (a, b) = (val(*a)?, val(*b)?); self.pure2(a, b, &at, m, |f, x, y, m| f.int_minmax(op, ty, x, y, m))? } - [x] if op == LlvmIntOp::Ctpop => { + [x] => { let x = val(*x)?; - self.pure2(x, x, &at, m, |f, x, _, m| f.ctpop(ty, x, m))? + self.pure2(x, x, &at, m, |f, x, _, m| f.int_unary(op, ty, x, m))? } _ => return Err(not_evaluable(at)), }, diff --git a/crates/metal2vulkan-air/src/canon/tests.rs b/crates/metal2vulkan-air/src/canon/tests.rs index faf5be8dc..4206df7b8 100644 --- a/crates/metal2vulkan-air/src/canon/tests.rs +++ b/crates/metal2vulkan-air/src/canon/tests.rs @@ -27,6 +27,7 @@ mod global_builtins; mod private_memory; mod table_copies; mod texture_writes; +mod unbound_immediates; mod unobserved; mod unrolling; diff --git a/crates/metal2vulkan-air/src/canon/tests/unbound_immediates.rs b/crates/metal2vulkan-air/src/canon/tests/unbound_immediates.rs new file mode 100644 index 000000000..c77bc49ff --- /dev/null +++ b/crates/metal2vulkan-air/src/canon/tests/unbound_immediates.rs @@ -0,0 +1,194 @@ +//! An intrinsic's immediate that is a parameter of the function calling it (Metal's compiler leaves +//! OpenCL C's `barrier(flags)` and `mem_fence(flags)` out of line, passing the flags on): decode +//! keeps the call unbound, and specialization binds each inlined copy with its call site's +//! constants, folding the integer arithmetic between, or refuses it where they are not constants. +//! The modules are LLVM text written here, assembled with `llvm-as`; a run without it skips. + +use super::*; +use crate::intrinsics::{BarrierName, MemFlags, MemoryOrder, Sync, ThreadScope}; + +const HEAD: &str = "target datalayout = \"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\"\n\ +target triple = \"air64_v28-apple-macosx26.0.0\"\n"; + +/// The ABI of a kernel `@k(ptr addrspace(1) %x)`, `x` a read-write `int` buffer at index 0. +const KERNEL_ABI: &str = "!air.kernel = !{!0}\n\ +!air.version = !{!5}\n\ +!air.language_version = !{!6}\n\ +!0 = !{ptr @k, !1, !2}\n\ +!1 = !{}\n\ +!2 = !{!3}\n\ +!3 = !{i32 0, !\"air.buffer\", !\"air.location_index\", i32 0, 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\", !\"int\", !\"air.arg_name\", !\"x\"}\n\ +!5 = !{i32 2, i32 8, i32 0}\n\ +!6 = !{!\"Metal\", i32 3, i32 2, i32 0}\n"; + +/// `body` (functions and declarations) with the kernel ABI, decoded; `None` without `llvm-as`. +fn decoded(test: &str, body: &str) -> Option> { + let text = format!("{HEAD}{body}{KERNEL_ABI}"); + let bitcode = match metal2vulkan_devtools::llvm_assemble_text(&text) { + Ok(b) => b, + Err(e) => { + eprintln!("SKIP {test}: {e:?}"); + return None; + } + }; + Some(crate::bitcode::decode(&bitcode, &mut meter())) +} + +/// The kernel `@k` of `body` specialized, and the work units specialization metered. +fn specialized(test: &str, body: &str) -> Option<(Result, u64)> { + let d = decoded(test, body)?.expect("decoded"); + let req = SpecRequest { + entry: "k".into(), + ..SpecRequest::default() + }; + let mut m = meter(); + let entry = specialize(d.module, &d.abi, &req, &mut m); + Some((entry, m.work())) +} + +/// The barriers and fences of the specialized entry, in order. +fn syncs(entry: &Entry) -> Vec { + let body = entry + .module + .func(entry.func) + .and_then(|f| f.body.as_ref()) + .expect("the entry's body"); + body.insts + .values() + .filter_map(|i| match &i.kind { + InstKind::Call(call) => match call.callee { + Callee::Air { + op: AirIntrinsic::Sync(s), + .. + } => Some(s), + _ => None, + }, + _ => None, + }) + .collect() +} + +fn flags(raw: u64) -> MemFlags { + MemFlags::from_raw(raw).expect("flags") +} + +/// `@wait(flags)`, the barrier its caller's flags name, called from the kernel with `calls`. +fn barrier_module(barrier_flags: &str, calls: &str) -> String { + format!( + "define void @k(ptr addrspace(1) %x) #0 {{\n\ + \x20 store i32 1, ptr addrspace(1) %x, align 4\n\ + {calls}\ + \x20 ret void\n}}\n\ + define internal fastcc void @wait(i32 %flags) #1 {{\n\ + \x20 tail call void @air.wg.barrier(i32 {barrier_flags}, i32 1) #2\n\ + \x20 ret void\n}}\n\ + declare void @air.wg.barrier(i32, i32) #2\n\ + attributes #0 = {{ convergent nounwind }}\n\ + attributes #1 = {{ convergent noinline nounwind }}\n\ + attributes #2 = {{ convergent nounwind willreturn }}\n" + ) +} + +#[test] +fn a_barrier_whose_flags_are_its_callers_binds_each_call_site_with_its_own() { + let calls = " tail call fastcc void @wait(i32 2)\n tail call fastcc void @wait(i32 1)\n"; + let Some((entry, _)) = specialized( + "a_barrier_whose_flags_are_its_callers_binds_each_call_site_with_its_own", + &barrier_module("%flags", calls), + ) else { + return; + }; + let entry = entry.expect("specialized"); + let scope = ThreadScope::from_raw(1).expect("scope"); + let barrier = |raw| Sync::Barrier { + name: BarrierName::Threadgroup, + flags: flags(raw), + order: None, + scope, + memory: scope, + }; + assert_eq!(syncs(&entry), [barrier(2), barrier(1)]); +} + +/// Binding is no pass of its own: the kernel whose callee passes its parameter on as the +/// barrier's flags specializes to the module of the kernel whose callee writes the same constant, +/// metering no more work than it. +#[test] +fn binding_a_callers_flags_does_no_work_of_its_own() { + let test = "binding_a_callers_flags_does_no_work_of_its_own"; + let calls = " tail call fastcc void @wait(i32 2)\n"; + let (Some((passed, passed_work)), Some((written, written_work))) = ( + specialized(test, &barrier_module("%flags", calls)), + specialized(test, &barrier_module("2", calls)), + ) else { + return; + }; + let (passed, written) = (passed.expect("passed on"), written.expect("written")); + assert_eq!(print(&passed.module), print(&written.module)); + assert!( + passed_work <= written_work, + "{passed_work} units passing the flags on, {written_work} writing them" + ); +} + +#[test] +fn a_fence_whose_flags_its_callers_flags_compute_binds_after_folding() { + // OpenCL C's `mem_fence(flags)` as Metal's compiler leaves it: CLK_GLOBAL_MEM_FENCE (2) + // becomes `mem_device` (1) by reversing the two flag bits, an `i2` operation. + let body = "define void @k(ptr addrspace(1) %x) #0 {\n\ + \x20 store i32 1, ptr addrspace(1) %x, align 4\n\ + \x20 tail call fastcc void @fence(i32 2)\n\ + \x20 store i32 2, ptr addrspace(1) %x, align 4\n\ + \x20 ret void\n}\n\ + define internal fastcc void @fence(i32 %flags) #1 {\n\ + \x20 %t = trunc i32 %flags to i2\n\ + \x20 %r = tail call i2 @llvm.bitreverse.i2(i2 %t)\n\ + \x20 %m = zext i2 %r to i32\n\ + \x20 tail call void @air.atomic.fence(i32 %m, i32 3, i32 1) #2\n\ + \x20 ret void\n}\n\ + declare void @air.atomic.fence(i32, i32, i32) #2\n\ + declare i2 @llvm.bitreverse.i2(i2) #3\n\ + attributes #0 = { nounwind }\n\ + attributes #1 = { noinline nounwind }\n\ + attributes #2 = { nounwind willreturn }\n\ + attributes #3 = { nounwind readnone speculatable willreturn }\n"; + let Some((entry, _)) = specialized( + "a_fence_whose_flags_its_callers_flags_compute_binds_after_folding", + body, + ) else { + return; + }; + let entry = entry.expect("specialized"); + let fence = Sync::Fence { + flags: flags(1), + order: MemoryOrder::from_raw(3).expect("order"), + scope: ThreadScope::from_raw(1).expect("scope"), + }; + assert_eq!(syncs(&entry), [fence]); +} + +#[test] +fn a_barrier_whose_flags_the_run_computes_is_refused_at_the_call() { + // The flags are read from the buffer: no call site makes them a constant. + let calls = + " %f = load i32, ptr addrspace(1) %x, align 4\n tail call fastcc void @wait(i32 %f)\n"; + let Some((entry, _)) = specialized( + "a_barrier_whose_flags_the_run_computes_is_refused_at_the_call", + &barrier_module("%flags", calls), + ) else { + return; + }; + let Err(Error::InvalidInput(e)) = entry else { + panic!("{entry:?}"); + }; + assert_eq!( + e.kind, + InputErrorKind::Intrinsic(crate::error::IntrinsicError::ImmediateNotConstant) + ); + // At the call in the inlined entry, not at a bitstream position. + let (f, block, inst) = e.at.in_function().expect("a function location"); + assert_eq!( + (f.to_string(), block.is_some(), inst.is_some()), + ("k".to_owned(), true, true) + ); +} diff --git a/crates/metal2vulkan-air/src/intrinsics/families_tests.rs b/crates/metal2vulkan-air/src/intrinsics/families_tests.rs index ceaf5ecb9..3383c722c 100644 --- a/crates/metal2vulkan-air/src/intrinsics/families_tests.rs +++ b/crates/metal2vulkan-air/src/intrinsics/families_tests.rs @@ -2291,7 +2291,7 @@ fn texture_immediates_bind() { .. } )); - // An access outside the qualifiers stays unknown; a non-constant flag is malformed. + // An access outside the qualifiers stays unknown; a non-constant flag does not bind. let args = [v(0), v(1), v(2), no, v(4), no, v(6), v(7), c.i32(4)]; assert_eq!(bind(sample, &args, &c.table), Ok(Bound::Unknown)); let args = [v(0), v(1), v(2), v(3), v(4), no, v(6), v(7), zero]; @@ -2719,7 +2719,7 @@ fn air_2_9_atomics_read_their_flags() { // The same call in both forms: only the flags differ. assert_eq!(b.flags, Some(flags), "{name}"); assert_eq!(Atomic { flags: None, ..b }, a, "{name}"); - // A flag bit outside Metal's five stays unknown; a non-constant one is malformed. + // A flag bit outside Metal's five stays unknown; a non-constant one does not bind. let mut args = new_args.clone(); let at = args.len() - 2; args[at] = c.i32(32); diff --git a/crates/metal2vulkan-air/src/intrinsics/llvm.rs b/crates/metal2vulkan-air/src/intrinsics/llvm.rs index da33fef09..e9848bed0 100644 --- a/crates/metal2vulkan-air/src/intrinsics/llvm.rs +++ b/crates/metal2vulkan-air/src/intrinsics/llvm.rs @@ -228,6 +228,16 @@ pub enum LlvmIntrinsic { /// The overload type: the result and every operand. ty: NumTy, }, + /// A kept integer operation on a scalar integer of a width no [`NumTy`] names (2 to 63 bits + /// but 8, 16 and 32), as Metal's compiler leaves OpenCL C's fences computing their flags with + /// `llvm.bitreverse.i2`. Canonicalization folds it over constants; lowering refuses one that + /// remains. + NarrowInt { + /// The operation. + op: LlvmIntOp, + /// The width in bits of the result and of every operand. + bits: u8, + }, /// `llvm.abs`, with its `is_int_min_poison` immediate. Abs { /// The integer overload type. @@ -497,14 +507,30 @@ pub(super) fn parse( spells(0, ty)?; LlvmIntrinsic::Float { op, ty } } - Base::Int(op) => { - let ty = num(*ret)?; - let bswap_ok = op != LlvmIntOp::Bswap || ty.elem.bits() % 16 == 0; - check(ty.elem.is_int() && bswap_ok && params.len() == op.arity())?; - count(1)?; - spells(0, ty)?; - LlvmIntrinsic::Int { op, ty } - } + Base::Int(op) => match types.get(*ret) { + // A scalar integer of a width no `NumTy` names, the result and every operand. + Some(&Type::Int(bits)) if NumTy::of(types, *ret).is_none() => { + let bswap_ok = op != LlvmIntOp::Bswap || bits % 16 == 0; + check( + (2..64).contains(&bits) + && bswap_ok + && params.len() == op.arity() + && params.iter().all(|p| p == ret), + )?; + count(1)?; + let width = token(0).and_then(|t| t.strip_prefix('i')); + check(width.and_then(|w| w.parse::().ok()) == Some(bits))?; + LlvmIntrinsic::NarrowInt { op, bits } + } + _ => { + let ty = num(*ret)?; + let bswap_ok = op != LlvmIntOp::Bswap || ty.elem.bits() % 16 == 0; + check(ty.elem.is_int() && bswap_ok && params.len() == op.arity())?; + count(1)?; + spells(0, ty)?; + LlvmIntrinsic::Int { op, ty } + } + }, Base::Abs | Base::Cttz | Base::Ctlz => { let ty = num(*ret)?; check(ty.elem.is_int())?; @@ -614,7 +640,9 @@ fn len_elem(types: &TypeTable, id: TypeId) -> Result { } impl LlvmIntrinsic { - /// The typed signature; `None` for an AGX operation without a modeled contract. + /// The typed signature; `None` for an AGX operation without a modeled contract, and for an + /// operation on a narrow integer, whose declaration's type the name's parse checks (it has + /// no immediates and no handles). pub fn signature(&self) -> Option { let flag = Operand::Imm(ImmKind::Bool); let mem = |dst: AddrSpace, src: Option, len: Elem| { @@ -635,6 +663,7 @@ impl LlvmIntrinsic { Some(match *self { LlvmIntrinsic::Float { op, ty } => same(ty, op.arity()), LlvmIntrinsic::Int { op, ty } => same(ty, op.arity()), + LlvmIntrinsic::NarrowInt { .. } => return None, LlvmIntrinsic::Abs { ty, .. } | LlvmIntrinsic::Cttz { ty, .. } | LlvmIntrinsic::Ctlz { ty, .. } => { diff --git a/crates/metal2vulkan-air/src/intrinsics/mod.rs b/crates/metal2vulkan-air/src/intrinsics/mod.rs index 2aa5e6cd0..075130913 100644 --- a/crates/metal2vulkan-air/src/intrinsics/mod.rs +++ b/crates/metal2vulkan-air/src/intrinsics/mod.rs @@ -14,8 +14,12 @@ //! `Callee::UnknownIntrinsic` and the post-canonical check refuses them only if they survive //! function-constant specialization. The same holds for a known name whose immediate names an //! enumerator the model does not define. A known name whose declaration disagrees with its -//! signature is [`IntrinsicError::SignatureMismatch`], and a non-constant immediate is -//! [`IntrinsicError::ImmediateNotConstant`] (both malformed input). The `llvm.*` markers +//! signature is [`IntrinsicError::SignatureMismatch`] (malformed input). A call whose immediate is +//! not an integer constant in the function that makes it keeps its [`Template`] +//! (`Callee::Unbound`): an internal function's parameter passed on to the intrinsic, as Metal's +//! compiler leaves OpenCL C's `barrier(flags)`, is each call site's constant once inlining gives +//! the parameter its argument, and the inliner binds the call there. An immediate still not a +//! constant after inlining is [`IntrinsicError::ImmediateNotConstant`]. The `llvm.*` markers //! [`Dropped`] lists are dropped at decode. //! //! A [`Signature`]'s `Operand::Handle` parameters and [`Signature::ret_handle`] give the typed handle positions that @@ -446,6 +450,42 @@ pub fn classify(name: &[u8], sym: Sym, fn_ty: TypeId, types: &TypeTable) -> Opti Some(class) } +impl DeclClass { + /// The template of an intrinsic in the closed set: `None` for a dropped marker, an unknown + /// name or a mismatched declaration. + pub fn template(self) -> Option