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)
This commit is contained in:
Anees Iqbal committed 2026-11-07 09:53:17 -08:00
1 parent fa599c471a
commit 89d8e46d26
37 files changed
+758 -76

No files matched your search

@@ -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 {
@@ -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)?,
@@ -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;
@@ -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,
}
+15 -6
View File
@@ -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<Option<ConstId>, 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
@@ -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,
}
}
+17 -6
View File
@@ -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.
+1 -1
View File
@@ -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)),
+20 -8
View File
@@ -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<LlvmIntrinsic, Error> {
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());
+82 -3
View File
@@ -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<LlvmIntOp> {
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<Option<InstKind>, 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::<Call>().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);
@@ -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)),
},
@@ -27,6 +27,7 @@ mod global_builtins;
mod private_memory;
mod table_copies;
mod texture_writes;
mod unbound_immediates;
mod unobserved;
mod unrolling;
@@ -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<Result<crate::bitcode::Decoded, Error>> {
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<Entry, Error>, 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<Sync> {
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)
);
}
@@ -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);
+38 -9
View File
@@ -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::<u8>().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<Elem, Fail> {
}
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<Signature> {
let flag = Operand::Imm(ImmKind::Bool);
let mem = |dst: AddrSpace, src: Option<AddrSpace>, 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, .. } => {
+42 -2
View File
@@ -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<Template> {
match self {
DeclClass::Air(op) => Some(Template::Air(op)),
DeclClass::Llvm(op) => Some(Template::Llvm(op)),
DeclClass::Drop(_) | DeclClass::Unknown | DeclClass::Mismatch => None,
}
}
}
/// An intrinsic in the closed set before a call's immediates are read in: the template its
/// declaration classifies as. A call whose immediate operand is not an integer constant in the
/// function that makes it keeps its template (`Callee::Unbound`) until canonicalization reads
/// the immediates where inlining gives them each call site's arguments ([`Template::bind`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Template {
/// An `air.*` intrinsic's template.
Air(AirIntrinsic),
/// An `llvm.*` intrinsic's template.
Llvm(LlvmIntrinsic),
}
impl Template {
/// Bind one call with `args` to an intrinsic of this template, as [`bind`] binds a call to
/// its declaration's class.
pub fn bind(self, args: &[Value], consts: &ConstTable) -> Result<Bound, IntrinsicError> {
let class = match self {
Template::Air(op) => DeclClass::Air(op),
Template::Llvm(op) => DeclClass::Llvm(op),
};
bind(class, args, consts)
}
}
/// A call's decoded callee, from its declaration's class and its arguments.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Bound {
@@ -373,7 +373,7 @@ fn atomics_read_their_immediates() {
let args = [ptr, val, c.i32(order), c.i32(scope), yes];
assert_eq!(bind(template, &args, &c.table), Ok(Bound::Unknown));
}
// A non-constant immediate is malformed.
// A non-constant immediate does not bind (decode keeps the call unbound).
let args = [ptr, val, val, device, yes];
assert_eq!(
bind(template, &args, &c.table),
@@ -694,6 +694,56 @@ fn llvm_bitreverse_decodes_at_every_integer_width() {
}
}
/// An integer operation on a scalar of a width no `NumTy` names (Metal's compiler leaves
/// `llvm.bitreverse.i2` in OpenCL C's fences) decodes as its narrow form, checked against its
/// declaration: every operand the result's width, the suffix spelling it.
#[test]
fn llvm_integer_operations_on_narrow_widths_decode() {
let m = &mut meter();
let mut t = TypeTable::new();
let mut decl = |t: &mut TypeTable, ret: u8, params: &[u8]| {
let ret = t.intern(Type::Int(ret), m).unwrap();
let params: Vec<_> = params
.iter()
.map(|&w| t.intern(Type::Int(w), m).unwrap())
.collect();
let f = Type::Function {
ret,
params: params.into(),
vararg: false,
};
t.intern(f, m).unwrap()
};
for (name, op, bits, arity) in [
("llvm.bitreverse.i2", LlvmIntOp::BitReverse, 2, 1),
("llvm.ctpop.i3", LlvmIntOp::Ctpop, 3, 1),
("llvm.bswap.i48", LlvmIntOp::Bswap, 48, 1),
("llvm.umax.i24", LlvmIntOp::UMax, 24, 2),
] {
let ty = decl(&mut t, bits, &vec![bits; arity]);
assert_eq!(
classify(name.as_bytes(), sym(), ty, &t),
Some(DeclClass::Llvm(LlvmIntrinsic::NarrowInt { op, bits })),
"{name}"
);
}
// A declaration that disagrees: an operand of another width, the suffix, the arity, a
// `bswap` of a width that is no multiple of 16 bits.
for (name, ret, params) in [
("llvm.bitreverse.i2", 2, &[3][..]),
("llvm.bitreverse.i3", 2, &[2][..]),
("llvm.bitreverse.i2", 2, &[2, 2][..]),
("llvm.bswap.i24", 24, &[24][..]),
] {
let ty = decl(&mut t, ret, params);
assert_eq!(
classify(name.as_bytes(), sym(), ty, &t),
Some(DeclClass::Mismatch),
"{name}"
);
}
}
#[test]
fn llvm_bases_decode_against_their_declarations() {
let f32s = Operand::Num(NumTy::scalar(Elem::F32));
+21 -5
View File
@@ -8,7 +8,7 @@
use super::attrs::CallAttrs;
use super::id::{ArgIdx, BlockId, ConstId, FuncId, InstId, TypeId};
use crate::intrinsics::{AirIntrinsic, LlvmIntrinsic};
use crate::intrinsics::{AirIntrinsic, LlvmIntrinsic, Template};
/// An SSA operand. Globals and functions are operands through [`super::Const::GlobalAddr`] /
/// [`super::Const::FuncAddr`] constants, so every value has exactly one spelling.
@@ -662,14 +662,16 @@ impl Callee {
Callee::Indirect { callee, fn_ty } => no_heap(callee).saturating_add(no_heap(fn_ty)),
Callee::Air { decl, op } => no_heap(decl).saturating_add(no_heap(op)),
Callee::Llvm { decl, op } => no_heap(decl).saturating_add(no_heap(op)),
Callee::Unbound { decl, template } => no_heap(decl).saturating_add(no_heap(template)),
}
}
}
/// What a call calls. Every call to a declaration named `air.*` or `llvm.*` is decoded once
/// into [`Callee::Air`] / [`Callee::Llvm`], or kept as [`Callee::UnknownIntrinsic`] until after
/// function-constant specialization; afterwards no code inspects intrinsic names. The declaration
/// is kept on every form so the verifier checks arguments against its type.
/// into [`Callee::Air`] / [`Callee::Llvm`], kept as [`Callee::Unbound`] until its immediates are
/// constants, or kept as [`Callee::UnknownIntrinsic`] until after function-constant
/// specialization; afterwards no code inspects intrinsic names. The declaration is kept on every
/// form so the verifier checks arguments against its type.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum Callee {
/// A defined or declared (non-intrinsic) function.
@@ -697,6 +699,19 @@ pub enum Callee {
},
/// An `air.*`/`llvm.*` declaration outside the closed set.
UnknownIntrinsic(FuncId),
/// An intrinsic in the closed set whose immediate operands are not all integer constants in
/// the function that makes the call: an operand computed from the function's parameters, as
/// Metal's compiler leaves OpenCL C's `barrier(flags)` out of line, passing its flags to
/// `air.wg.barrier`. Specialization's constant propagation reads the immediates where
/// inlining gives the parameters each call site's arguments, making the call
/// [`Callee::Air`] or [`Callee::Llvm`]; one whose immediates are still not constant there is
/// refused (`IntrinsicError::ImmediateNotConstant`).
Unbound {
/// The intrinsic's declaration.
decl: FuncId,
/// The declaration's template, its immediates not read in.
template: Template,
},
}
impl Callee {
@@ -706,7 +721,8 @@ impl Callee {
Callee::Direct(f)
| Callee::Air { decl: f, .. }
| Callee::Llvm { decl: f, .. }
| Callee::UnknownIntrinsic(f) => Some(*f),
| Callee::UnknownIntrinsic(f)
| Callee::Unbound { decl: f, .. } => Some(*f),
Callee::Indirect { .. } => None,
}
}
+3
View File
@@ -434,6 +434,9 @@ impl Printer<'_> {
Callee::Air { decl, op } => w!(self, "@f{} [air {op:?}]", decl.raw()),
Callee::Llvm { decl, op } => w!(self, "@f{} [llvm {op:?}]", decl.raw()),
Callee::UnknownIntrinsic(f) => w!(self, "@f{} [unknown]", f.raw()),
Callee::Unbound { decl, template } => {
w!(self, "@f{} [unbound {template:?}]", decl.raw())
}
}
self.out.push('(');
for (i, &a) in call.args.iter().enumerate() {
+1
View File
@@ -910,6 +910,7 @@ impl<'a> Verifier<'a> {
Callee::Direct(f) => self.callee_ty(cx, *f, false)?,
Callee::Air { decl, .. }
| Callee::Llvm { decl, .. }
| Callee::Unbound { decl, .. }
| Callee::UnknownIntrinsic(decl) => self.callee_ty(cx, *decl, true)?,
};
let Some((ret, params, vararg)) = fn_sig(types, fn_ty) else {
@@ -331,6 +331,7 @@ intrinsics Signature use(sig::Signature)
intrinsics SimdMatrix use(matrix::SimdMatrix)
intrinsics SimdgroupSize use(simd::SimdgroupSize)
intrinsics Sync use(sync::Sync)
intrinsics Template enum(E)
intrinsics Tensor use(objects::Tensor)
intrinsics TexOp use(texture::TexOp)
intrinsics TexRole use(texture::TexRole)
@@ -255,6 +255,8 @@ mod no_copy_lies;
mod noted_apart;
mod numbered_samplers;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod opencl_kernels;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod optional_extensions;
mod options;
mod own;
@@ -0,0 +1,152 @@
//! Kernels in the shapes Metal's compiler writes for OpenCL C (`newLibraryWithSource` with
//! `sourceLanguage` 1, as the GL renderer's compute path builds an OpenCL program), each run and
//! compared with what Metal computes.
//!
//! - **A barrier out of line**: OpenCL C's `barrier(flags)` stays an internal function passing its
//! flags on to `air.wg.barrier`, and `mem_fence(flags)` computes `air.atomic.fence`'s flags from
//! them through `llvm.bitreverse.i2`. Both made and run on an M3 Max (macOS 27.0.1) and an Intel
//! UHD 630 (26.7.1): `x[i] = 1`, the barrier, `x[i] += x[i ^ 1]` stores 2 in every word.
//!
//! A device test: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`,
//! `m2v_cpu_icd`), on the kind of device the cfg selects. The modules are LLVM text written here
//! (`llvm-as`).
use super::blit_holds::{device, Scratch, WAIT};
use crate::{Buffer, ComputePipelineState, Device, PipelineOptions, ResourceOptions, Size};
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\
declare i32 @air.get_global_id.i32(i32) #9\n\
attributes #9 = { nounwind readnone willreturn }\n\
!air.version = !{!90}\n\
!air.language_version = !{!91}\n\
!90 = !{i32 2, i32 8, i32 0}\n\
!91 = !{!\"Metal\", i32 3, i32 2, i32 0}\n";
/// The node of kernel argument 0, `x`, a read-write `int` buffer at index 0.
const X: &str = "!{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\"}";
/// The words a dispatch runs over.
const WORDS: u64 = 64;
/// The state of kernel `name` of the module `text` (after [`HEAD`]).
fn state(device: &Device, text: &str, name: &str) -> ComputePipelineState {
let air = metal2vulkan_devtools::llvm_assemble_text(&format!("{HEAD}{text}")).unwrap();
let library = metal2vulkan::library::Library::from_air(&air).unwrap();
let function = device
.new_library_with_compile_library(library)
.new_function_with_name(name)
.unwrap();
device
.new_compute_pipeline_state_with_function(&function, &PipelineOptions::default())
.unwrap()
}
/// The words of `buffer`, which no command uses now.
fn words(buffer: &Buffer) -> Vec<u32> {
let contents = buffer.contents().unwrap();
// SAFETY: the buffer's bytes, which no command uses now.
let bytes = unsafe { std::slice::from_raw_parts(contents.as_ptr(), buffer.length() as usize) };
bytes
.chunks_exact(4)
.map(|w| u32::from_le_bytes(w.try_into().unwrap()))
.collect()
}
/// `state` run over [`WORDS`] threads in threadgroups of `group`, `x` holding `init` and `bind`
/// binding the rest; `x`'s words after.
fn run(
device: &Device,
state: &ComputePipelineState,
init: &[u32],
group: u64,
bind: impl FnOnce(&mut crate::ComputeCommandEncoder),
) -> Vec<u32> {
let bytes: Vec<u8> = init.iter().flat_map(|w| w.to_le_bytes()).collect();
let x = device
.new_buffer_with_bytes(&bytes, ResourceOptions::shared())
.unwrap();
let queue = device.new_command_queue().unwrap();
let command_buffer = queue.command_buffer().unwrap();
let mut encoder = command_buffer.compute_command_encoder().unwrap();
encoder.set_compute_pipeline_state(state).unwrap();
encoder.set_buffer(Some(&x), 0, 0).unwrap();
bind(&mut encoder);
encoder
.dispatch_threads(Size::new(WORDS, 1, 1), Size::new(group, 1, 1))
.unwrap();
encoder.end_encoding().unwrap();
command_buffer.commit().unwrap();
command_buffer.wait_until_completed_for(WAIT).unwrap();
assert_eq!(command_buffer.error(), None);
words(&x)
}
/// `x[i] = 1`, `@wait(3)`, `x[i] += x[i ^ 1]`, the barrier's flags (`mem_device |
/// mem_threadgroup`, which order the device words the threads exchange) `@wait`'s parameter.
const BARRIER: &str = "define void @fence(ptr addrspace(1) nocapture %x) #3 {\n\
%id = tail call i32 @air.get_global_id.i32(i32 0)\n\
%i = zext i32 %id to i64\n\
%p = getelementptr inbounds i32, ptr addrspace(1) %x, i64 %i\n\
store i32 1, ptr addrspace(1) %p, align 4\n\
tail call fastcc void @wait(i32 3)\n\
%j = xor i64 %i, 1\n\
%q = getelementptr inbounds i32, ptr addrspace(1) %x, i64 %j\n\
%a = load i32, ptr addrspace(1) %q, align 4\n\
%b = load i32, ptr addrspace(1) %p, align 4\n\
%s = add i32 %a, %b\n\
store i32 %s, ptr addrspace(1) %p, align 4\n\
ret void\n}\n\
define internal fastcc void @wait(i32 %flags) #2 {\n\
tail call void @air.wg.barrier(i32 %flags, i32 1) #1\n\
ret void\n}\n\
declare void @air.wg.barrier(i32, i32) #1\n\
attributes #1 = { convergent nounwind willreturn }\n\
attributes #2 = { convergent noinline nounwind }\n\
attributes #3 = { convergent nounwind }\n\
!air.kernel = !{!0}\n\
!0 = !{ptr @fence, !1, !2}\n\
!1 = !{}\n\
!2 = !{!3}\n";
/// `x[i] = 1`, `@fence(2)` (its flags `bitreverse.i2` of the parameter's low bits, as OpenCL C's
/// `mem_fence(CLK_GLOBAL_MEM_FENCE)` becomes `mem_device`), `x[i] = 2`.
const FENCE: &str = "define void @store2(ptr addrspace(1) nocapture %x) #3 {\n\
%id = tail call i32 @air.get_global_id.i32(i32 0)\n\
%i = zext i32 %id to i64\n\
%p = getelementptr inbounds i32, ptr addrspace(1) %x, i64 %i\n\
store i32 1, ptr addrspace(1) %p, align 4\n\
tail call fastcc void @fence(i32 2)\n\
store i32 2, ptr addrspace(1) %p, align 4\n\
ret void\n}\n\
define internal fastcc void @fence(i32 %flags) #2 {\n\
%t = trunc i32 %flags to i2\n\
%r = tail call i2 @llvm.bitreverse.i2(i2 %t)\n\
%m = zext i2 %r to i32\n\
tail call void @air.atomic.fence(i32 %m, i32 3, i32 1) #1\n\
ret void\n}\n\
declare void @air.atomic.fence(i32, i32, i32) #1\n\
declare i2 @llvm.bitreverse.i2(i2) #9\n\
attributes #1 = { nounwind willreturn }\n\
attributes #2 = { noinline nounwind }\n\
attributes #3 = { nounwind }\n\
!air.kernel = !{!0}\n\
!0 = !{ptr @store2, !1, !2}\n\
!1 = !{}\n\
!2 = !{!3}\n";
#[test]
fn a_barrier_and_a_fence_out_of_line_compute_what_metal_computes() {
let scratch = Scratch::new("opencl-barrier");
let device = device(&scratch.0);
let start = vec![0u32; WORDS as usize];
for (text, name) in [(BARRIER, "fence"), (FENCE, "store2")] {
let text = format!("{text}!3 = {X}\n");
let state = state(&device, &text, name);
assert_eq!(
run(&device, &state, &start, 32, |_| ()),
vec![2; WORDS as usize],
"{name}"
);
}
}
@@ -348,6 +348,9 @@ impl Render<'_> {
Callee::Air { decl, op } => format!("air @{} {op:?}", self.fname(*decl)),
Callee::Llvm { decl, .. } => format!("llvm @{}", self.fname(*decl)),
Callee::UnknownIntrinsic(f) => format!("unknown @{}", self.fname(*f)),
Callee::Unbound { decl, template } => {
format!("unbound @{} {template:?}", self.fname(*decl))
}
};
format!(
"call {callee} {:?} {:?} {} {:?}",
@@ -18,7 +18,8 @@
//! exactly.
//!
//! The same lane is the intrinsic census: every decoded row reports how many of its calls decoded
//! to `Callee::Air` / `Callee::Llvm` and which callee names stayed `Callee::UnknownIntrinsic`, so
//! to `Callee::Air` / `Callee::Llvm` (or to their templates, `Callee::Unbound`, whose immediates
//! specialization binds) and which callee names stayed `Callee::UnknownIntrinsic`, so
//! decode completeness is measured over the corpus rather than asserted. Each unknown name is
//! reported as `listed` when it belongs to a family the decoder lists as not decoded
//! (`metal2vulkan_air::intrinsics::UNDECODED`), else `unlisted`: a closed census has no unlisted
@@ -37,7 +38,7 @@ use metal2vulkan::error::Error;
use metal2vulkan::Budget;
use metal2vulkan_air::bitcode::{decode, Decoded};
use metal2vulkan_air::budget::Meter;
use metal2vulkan_air::intrinsics::dropped_family;
use metal2vulkan_air::intrinsics::{dropped_family, Template};
use metal2vulkan_air::ir::{Callee, CastOp, Const, ConstExpr, FuncId, InstKind, Value};
use serde::{Deserialize, Serialize};
use wait_timeout::ChildExt;
@@ -180,7 +181,9 @@ pub fn ir_fingerprint(d: &Decoded) -> Fingerprint {
};
let callee = match &call.callee {
Callee::Direct(f) | Callee::UnknownIntrinsic(f) => fn_name(*f),
Callee::Air { decl, .. } | Callee::Llvm { decl, .. } => fn_name(*decl),
Callee::Air { decl, .. }
| Callee::Llvm { decl, .. }
| Callee::Unbound { decl, .. } => fn_name(*decl),
// A call whose type differs from its callee's still names the function, also
// through typed-pointer bitcasts, which opaque-pointer `llvm-dis` folds away.
Callee::Indirect {
@@ -477,8 +480,16 @@ pub fn intrinsic_census(d: &Decoded) -> IntrinsicCensus {
continue;
};
match &call.callee {
Callee::Air { .. } => out.air += 1,
Callee::Llvm { .. } => out.llvm += 1,
Callee::Air { .. }
| Callee::Unbound {
template: Template::Air(_),
..
} => out.air += 1,
Callee::Llvm { .. }
| Callee::Unbound {
template: Template::Llvm(_),
..
} => out.llvm += 1,
Callee::UnknownIntrinsic(decl) => {
*out.unknown.entry(name(*decl)).or_default() += 1;
}
@@ -676,7 +676,7 @@ impl CallGraph {
local.resize(edges.len(), false);
}
}
Callee::Air { .. } | Callee::Llvm { .. } => {}
Callee::Air { .. } | Callee::Llvm { .. } | Callee::Unbound { .. } => {}
}
}
graph.edges[node] = edges;
@@ -125,7 +125,7 @@ fn call_kind(
Some(targets) => CallKind::Local(targets.iter().copied().collect()),
None => CallKind::Barrier,
},
Callee::UnknownIntrinsic(_) => CallKind::Barrier,
Callee::UnknownIntrinsic(_) | Callee::Unbound { .. } => CallKind::Barrier,
}
}
+3 -1
View File
@@ -1760,7 +1760,9 @@ fn llvm_math(op: &LlvmIntrinsic) -> Result<Fun, Error> {
LlvmIntrinsic::Abs { .. } => Fun::Int(IntFn::Abs),
LlvmIntrinsic::Cttz { .. } => Fun::Int(IntFn::Ctz),
LlvmIntrinsic::Ctlz { .. } => Fun::Int(IntFn::Clz),
LlvmIntrinsic::Memset { .. }
// An operation on a narrow integer that constant propagation did not fold.
LlvmIntrinsic::NarrowInt { .. }
| LlvmIntrinsic::Memset { .. }
| LlvmIntrinsic::Memcpy { .. }
| LlvmIntrinsic::Memmove { .. }
| LlvmIntrinsic::Agx(_) => return Err(not_lowered()),
@@ -217,9 +217,10 @@ fn contribution(cx: &SelectCx<'_>, id: InstId, inst: &Inst) -> Reach {
_ => 0,
},
// Refused by `select` before this runs; counted as everything to stay conservative.
Callee::Direct(_) | Callee::Indirect { .. } | Callee::UnknownIntrinsic(_) => {
Reach::TANGLED | Reach::SIDE_EFFECT | Reach::NON_QUAD
}
Callee::Direct(_)
| Callee::Indirect { .. }
| Callee::UnknownIntrinsic(_)
| Callee::Unbound { .. } => Reach::TANGLED | Reach::SIDE_EFFECT | Reach::NON_QUAD,
},
_ => 0,
};
+7
View File
@@ -908,6 +908,9 @@ fn route_llvm(op: &LlvmIntrinsic) -> Route {
L::Float { .. } | L::Int { .. } | L::Abs { .. } | L::Cttz { .. } | L::Ctlz { .. } => {
Route::Family(LowerFamily::Arith)
}
// A narrow integer's operation canonicalization did not fold over constants: no SPIR-V
// type has its width.
L::NarrowInt { .. } => Route::Refuse(not_lowered(LowerFamily::Arith)),
}
}
@@ -979,6 +982,10 @@ fn route(cx: &SelectCx<'_>, id: InstId, inst: &Inst) -> Route {
Callee::UnknownIntrinsic(_) => {
Route::Refuse(Unsupported::not_implemented(Feature::UnknownIntrinsic).into())
}
// Canon's post-check refuses every call whose immediates are not constants.
Callee::Unbound { .. } => {
Route::Refuse(invariant("an unbound intrinsic survived canon"))
}
},
}
}
@@ -233,6 +233,7 @@ fn per_invocation_arithmetic(callee: &Callee) -> bool {
op,
LlvmIntrinsic::Float { .. }
| LlvmIntrinsic::Int { .. }
| LlvmIntrinsic::NarrowInt { .. }
| LlvmIntrinsic::Abs { .. }
| LlvmIntrinsic::Cttz { .. }
| LlvmIntrinsic::Ctlz { .. }
@@ -137,7 +137,10 @@ fn observes(callee: &Callee) -> bool {
Callee::Air { op, .. } => op,
Callee::Llvm { .. } => return false,
// Canonicalization inlines every defined callee; what remains is not the kernel's own.
Callee::Direct(_) | Callee::Indirect { .. } | Callee::UnknownIntrinsic(_) => return true,
Callee::Direct(_)
| Callee::Indirect { .. }
| Callee::UnknownIntrinsic(_)
| Callee::Unbound { .. } => return true,
};
let scoped =
|scope: ThreadScope| matches!(scope, ThreadScope::Threadgroup | ThreadScope::Simdgroup);
+5 -1
View File
@@ -655,6 +655,7 @@ impl<'a> Engine<'a> {
Callee::Llvm { op, .. } => match op {
LlvmIntrinsic::Float { .. }
| LlvmIntrinsic::Int { .. }
| LlvmIntrinsic::NarrowInt { .. }
| LlvmIntrinsic::Abs { .. }
| LlvmIntrinsic::Cttz { .. }
| LlvmIntrinsic::Ctlz { .. } => false,
@@ -669,7 +670,10 @@ impl<'a> Engine<'a> {
}
LlvmIntrinsic::Agx(_) => true,
},
Callee::Direct(_) | Callee::Indirect { .. } | Callee::UnknownIntrinsic(_) => true,
Callee::Direct(_)
| Callee::Indirect { .. }
| Callee::UnknownIntrinsic(_)
| Callee::Unbound { .. } => true,
}
}
+21 -9
View File
@@ -746,6 +746,7 @@ fn structural(d: &Decoded) -> Vec<String> {
Callee::Indirect { fn_ty, .. } => format!("indirect {}", ty(fn_ty)),
Callee::Air { op, .. } => format!("{op:?}"),
Callee::Llvm { op, .. } => format!("{op:?}"),
Callee::Unbound { template, .. } => format!("unbound {template:?}"),
},
InstKind::Gep { src_ty, .. } => ty(*src_ty),
InstKind::Alloca { ty: t, .. } => ty(*t),
@@ -1097,18 +1098,27 @@ fn a_declaration_mismatch_names_the_declaration_and_its_function() {
#[test]
fn intrinsic_call_errors_are_typed() {
use crate::air::error::{DiagName, InputErrorKind, IntrinsicError};
/// What decode makes of the call.
#[derive(Debug)]
enum Want {
Refused(IntrinsicError),
Unbound,
Unknown,
}
let cases = [
(
"declare float @air.fmax.f32(float)\n\
define float @k(float %x) {\n %r = call float @air.fmax.f32(float %x)\n ret float %r\n}\n",
Some(IntrinsicError::DeclaredSignatureMismatch {
Want::Refused(IntrinsicError::DeclaredSignatureMismatch {
name: DiagName::new("air.fmax.f32"),
}),
),
// An immediate the function computes keeps the call unbound: specialization binds it
// where its call sites' constants reach it, or refuses it (`canon`'s tests).
(
"declare i32 @air.clz.i32(i32, i1)\n\
define i32 @k(i32 %x, i1 %f) {\n %r = call i32 @air.clz.i32(i32 %x, i1 %f)\n ret i32 %r\n}\n",
Some(IntrinsicError::ImmediateNotConstant),
Want::Unbound,
),
// A declared but never called mismatch is not an error; an unmodeled scope keeps the
// call unknown.
@@ -1116,7 +1126,7 @@ fn intrinsic_call_errors_are_typed() {
"declare float @air.fmax.f32(float)\n\
declare i32 @air.atomic.local.load.i32(ptr addrspace(3), i32, i32, i1)\n\
define i32 @k(ptr addrspace(3) %p) {\n %r = call i32 @air.atomic.local.load.i32(ptr addrspace(3) %p, i32 0, i32 9, i1 true)\n ret i32 %r\n}\n",
None,
Want::Unknown,
),
];
for (text, want) in cases {
@@ -1125,14 +1135,16 @@ fn intrinsic_call_errors_are_typed() {
return;
};
match (got, want) {
(Err(Error::InvalidInput(e)), Some(want)) => {
(Err(Error::InvalidInput(e)), Want::Refused(want)) => {
assert_eq!(e.kind, InputErrorKind::Intrinsic(want), "{text}")
}
(Ok(d), None) => {
assert!(matches!(
calls(&d, "k")[0].callee,
Callee::UnknownIntrinsic(_)
));
(Ok(d), Want::Unbound) => {
let callee = &calls(&d, "k")[0].callee;
assert!(matches!(callee, Callee::Unbound { .. }), "{callee:?}");
}
(Ok(d), Want::Unknown) => {
let callee = &calls(&d, "k")[0].callee;
assert!(matches!(callee, Callee::UnknownIntrinsic(_)), "{callee:?}");
}
(got, want) => panic!("{text}: {got:?}, want {want:?}"),
}
@@ -1191,6 +1191,7 @@ enum metal2vulkan-air::intrinsics::SamplerOp #[derive(Clone, Copy, Debug, Partia
enum metal2vulkan-air::intrinsics::Sign #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum Sign
enum metal2vulkan-air::intrinsics::SimdMatrix #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum SimdMatrix
enum metal2vulkan-air::intrinsics::Sync #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum Sync
enum metal2vulkan-air::intrinsics::Template #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum Template
enum metal2vulkan-air::intrinsics::Tensor #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum Tensor
enum metal2vulkan-air::intrinsics::TexOp #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum TexOp
enum metal2vulkan-air::intrinsics::TexRole #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum TexRole
@@ -7450,6 +7451,7 @@ method metal2vulkan-air::intrinsics::AtomicSpace::space pub const fn space(self)
method metal2vulkan-air::intrinsics::BoolReduce::signature pub fn signature(&self) -> Signature
method metal2vulkan-air::intrinsics::Coherent::signature pub fn signature(&self) -> Signature
method metal2vulkan-air::intrinsics::Convert::signature pub fn signature(&self) -> Signature
method metal2vulkan-air::intrinsics::DeclClass::template pub fn template(self) -> Option<Template>
method metal2vulkan-air::intrinsics::Derivative::signature pub fn signature(&self) -> Signature
method metal2vulkan-air::intrinsics::Elem::bits pub const fn bits(self) -> u32
method metal2vulkan-air::intrinsics::Elem::is_float pub const fn is_float(self) -> bool
@@ -7511,6 +7513,7 @@ method metal2vulkan-air::intrinsics::SimdMatrix::signature pub fn signature(&sel
method metal2vulkan-air::intrinsics::SimdgroupSize::signature pub fn signature(&self) -> Signature
method metal2vulkan-air::intrinsics::Sync::barrier_order pub fn barrier_order(&self) -> Option<MemoryOrder>
method metal2vulkan-air::intrinsics::Sync::signature pub fn signature(&self) -> Signature
method metal2vulkan-air::intrinsics::Template::bind pub fn bind(self, args: &[Value], consts: &ConstTable) -> Result<Bound, IntrinsicError>
method metal2vulkan-air::intrinsics::Tensor::signature pub fn signature(&self) -> Signature
method metal2vulkan-air::intrinsics::Texture::layout pub fn layout(&self) -> Layout<TexRole>
method metal2vulkan-air::intrinsics::Texture::signature pub fn signature(&self) -> Signature
@@ -10892,6 +10895,7 @@ variant metal2vulkan-air::intrinsics::LlvmIntrinsic::Int Int { op: LlvmIntOp, ty
variant metal2vulkan-air::intrinsics::LlvmIntrinsic::Memcpy Memcpy { dst: AddrSpace, src: AddrSpace, len: Elem, volatile: bool }
variant metal2vulkan-air::intrinsics::LlvmIntrinsic::Memmove Memmove { dst: AddrSpace, src: AddrSpace, len: Elem, volatile: bool }
variant metal2vulkan-air::intrinsics::LlvmIntrinsic::Memset Memset { dst: AddrSpace, len: Elem, volatile: bool }
variant metal2vulkan-air::intrinsics::LlvmIntrinsic::NarrowInt NarrowInt { op: LlvmIntOp, bits: u8 }
variant metal2vulkan-air::intrinsics::LodMode::Bias Bias
variant metal2vulkan-air::intrinsics::LodMode::Level Level
variant metal2vulkan-air::intrinsics::MatElem::BF16 BF16
@@ -11055,6 +11059,8 @@ variant metal2vulkan-air::intrinsics::SimdMatrix::Store8x8 Store8x8 { elem: MatE
variant metal2vulkan-air::intrinsics::SimdMatrix::Store8x8Legacy Store8x8Legacy { elem: MatElem, space: AddrSpace }
variant metal2vulkan-air::intrinsics::Sync::Barrier Barrier { name: BarrierName, flags: MemFlags, order: Option<MemoryOrder>, scope: ThreadScope, memory: ThreadScope }
variant metal2vulkan-air::intrinsics::Sync::Fence Fence { flags: MemFlags, order: MemoryOrder, scope: ThreadScope }
variant metal2vulkan-air::intrinsics::Template::Air Air(AirIntrinsic)
variant metal2vulkan-air::intrinsics::Template::Llvm Llvm(LlvmIntrinsic)
variant metal2vulkan-air::intrinsics::Tensor::DescriptorSize DescriptorSize
variant metal2vulkan-air::intrinsics::Tensor::Extent Extent
variant metal2vulkan-air::intrinsics::Tensor::InitStrided InitStrided { data: AddrSpace }
@@ -11148,6 +11154,7 @@ variant metal2vulkan-air::ir::Callee::Air Air { decl: FuncId, op: AirIntrinsic }
variant metal2vulkan-air::ir::Callee::Direct Direct(FuncId)
variant metal2vulkan-air::ir::Callee::Indirect Indirect { callee: Value, fn_ty: TypeId }
variant metal2vulkan-air::ir::Callee::Llvm Llvm { decl: FuncId, op: LlvmIntrinsic }
variant metal2vulkan-air::ir::Callee::Unbound Unbound { decl: FuncId, template: Template }
variant metal2vulkan-air::ir::Callee::UnknownIntrinsic UnknownIntrinsic(FuncId)
variant metal2vulkan-air::ir::CastOp::AddrSpaceCast AddrSpaceCast
variant metal2vulkan-air::ir::CastOp::Bitcast Bitcast
Can't render this file because it is too large.
+11
View File
@@ -596,6 +596,17 @@ layout stride of `None` is `MTLBufferLayoutStrideDynamic`: the stride comes from
does.
- **Dynamic libraries.** `DynamicLibrary::new(library, &budget)` checks a dynamic metallib as
Metal's `newDynamicLibrary:` does; pipelines link its exported functions.
- **OpenCL C kernels.** Metal compiles OpenCL C (`newLibraryWithSource` with the compile options'
`sourceLanguage` 1, which the GL renderer's compute path uses), naming each kernel
`__entry_<name>`, and its AIR has shapes MSL's does not:
- A helper left out of line that passes its parameter on as an intrinsic's immediate operand:
OpenCL C's `barrier(flags)` passes its flags to `air.wg.barrier`, and `mem_fence(flags)`
computes `air.atomic.fence`'s flags from them with `llvm.bitreverse.i2`. Each inlined copy
reads its own call site's constants, folded through the integer arithmetic between them. An
immediate that is still not a constant after that is
`InvalidInput(Intrinsic(ImmediateNotConstant))` at the call. An integer operation on a width
no SPIR-V type has (`i2`) is folded over constants; one that is not folded is refused
(`Lowering(Arith)`).
## 4. A render pipeline
+1 -1
View File
@@ -67,7 +67,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, function constants, SCCP (reading the integer fields of a constant global whose value is known), the unrolling of loops whose constant trip count decides a branch where that leaves the entry no larger, devirtualization, linking, pruning, pointee erasure, the speculation of the short branch arms Metal's backend runs in every lane, and the split of a whole array's or struct's load or store in buffer or threadgroup memory into its members' accesses). 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, function constants, SCCP (reading the integer fields of a constant global whose value is known, folding integer `llvm.*` operations on constants, 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, devirtualization, linking, pruning, pointee erasure, the speculation of the short branch arms Metal's backend runs in every lane, and the split of a whole array's or struct's load or store in buffer or threadgroup memory into its members' accesses). 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 |