Translator: a float function constant gates an argument

Apple's OpenGL front end gates a vertex function's point_size output on a
function constant of type float (MTL_global_pointsize). The static
initializer stores air.normalize_function_constant_predicate.f32 of it into
a float predicate global, which the ABI check and the specializer refused:
every pipeline of such a vertex function was refused, first as
Abi(BadValue) at air.function_constant, then as StaticInitializer.

- air.normalize_function_constant_predicate parses .f16 and .f32 and folds
  to 1.0 where its operand is a known non-zero and to 0.0 where it is zero
  or undefined, as the integer forms do.
- A predicate global may be of floating-point type; its argument is present
  where the global holds a non-zero float (an unsupplied constant's is 0).

Tests: the float predicate's ABI check, the intrinsic's signature, and a
specialization that keeps and drops the gated parameter by the constant's
value (non-zero, zero, unsupplied).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HL11F898zP6tAUb9Phkfsv
This commit is contained in:
ExtremenisandClaude Opus 5.5 committed 2026-11-27 01:40:25 +01:00
1 parent fc9c99916d
commit 267d3163a6
8 files changed
+142 -9

No files matched your search

+1 -1
View File
@@ -376,7 +376,7 @@ fn predicate(m: &Module, p: Option<&Predicate>, site: &Site) -> Result<(), Error
&& !g.externally_initialized
&& g.section.is_none()
&& g.init.is_some()
&& matches!(m.types().get(g.value_ty), Some(Type::Int(_)))
&& matches!(m.types().get(g.value_ty), Some(Type::Int(_) | Type::Half | Type::Float | Type::Double))
});
if ok {
Ok(())
+13 -5
View File
@@ -1039,7 +1039,7 @@ fn kernel_with_predicate(
}
#[test]
fn predicates_name_a_static_initializer_integer_global() {
fn predicates_name_a_static_initializer_integer_or_float_global() {
// As the frontend writes them: `internal addrspace(2) global i8 0`, and a few `i16`/`i32`
// predicates.
for bits in [8, 16, 32] {
@@ -1050,6 +1050,14 @@ fn predicates_name_a_static_initializer_integer_global() {
});
assert!(abi.is_ok(), "i{bits}: {abi:?}");
}
// A function constant that is a `float` (Apple's OpenGL front end's point size) gates an
// argument through a floating-point predicate global.
let abi = kernel_with_predicate(|b| {
let t = b.float();
let zero = b.constant(t, Const::Float(0));
b.simple_global("pred", t, AddrSpace::Constant, Some(zero))
});
assert!(abi.is_ok(), "float: {abi:?}");
let refused = |abi: Result<AirAbi, Error>| {
let site = Site {
entry: Some(DiagName::new("k")),
@@ -1064,11 +1072,11 @@ fn predicates_name_a_static_initializer_integer_global() {
refused(kernel_with_predicate(|b| {
fc_global(b, "fc0", Some(Section::FcInitializer))
}));
// Not an integer.
// Not a number.
refused(kernel_with_predicate(|b| {
let t = b.float();
let zero = b.constant(t, Const::Undef);
b.simple_global("pred", t, AddrSpace::Constant, Some(zero))
let t = b.ptr(AddrSpace::Device);
let null = b.constant(t, Const::Null);
b.simple_global("pred", t, AddrSpace::Constant, Some(null))
}));
// A declaration: the static initializer has nothing to store into.
refused(kernel_with_predicate(|b| {
+27
View File
@@ -327,6 +327,33 @@ impl Folder<'_> {
self.mk_int(ty, v, m)
}
/// `air.normalize_function_constant_predicate.<f16|f32>(x)`: 1.0 when `x` is a known non-zero
/// float, 0.0 when it is zero or undefined (`None`: a value computed from an unsupplied
/// function constant). `None` where `x` is no float or `ty` is neither `half` nor `float`.
pub fn normalize_predicate_float(
&mut self,
ty: TypeId,
x: Option<ConstId>,
m: &mut Meter,
) -> Result<Option<ConstId>, Error> {
let one = match self.types.get(ty) {
Some(Type::Float) => 0x3f80_0000u64,
Some(Type::Half) => 0x3c00,
_ => return Ok(None),
};
let nonzero = match x {
None => false,
Some(c) => match self.value(c) {
Some(Const::Undef | Const::Poison) => false,
_ => match self.float(c) {
Some(v) => v != 0.0,
None => return Ok(None),
},
},
};
self.mk(ty, Const::Float(if nonzero { one } else { 0 }), m).map(Some)
}
/// `icmp pred a, b` over scalar integers (and null pointers), typed `ty` (`i1`).
pub fn icmp(
&mut self,
@@ -111,6 +111,22 @@ impl Values<'_> {
}
}
/// Whether global `g`'s initializer is a floating-point constant.
fn holds_float(&self, g: GlobalId) -> bool {
let init = self.globals.get(g).and_then(|g| g.init);
matches!(init.and_then(|c| self.consts.get(c)).map(|c| &c.value), Some(Const::Float(_)))
}
/// Whether the floating-point constant global `g` holds is non-zero; an unsupplied one's is
/// not.
fn float_nonzero(&self, g: GlobalId) -> bool {
if self.fcs.get(&g).is_some_and(|f| !f.supplied) {
return false;
}
let init = self.globals.get(g).and_then(|g| g.init);
matches!(init.and_then(|c| self.consts.get(c)).map(|c| &c.value), Some(Const::Float(b)) if *b != 0)
}
fn resolve(&self, v: &mut AbiInt) -> Result<(), Error> {
if let AbiInt::Global(g) = *v {
let x = u32::try_from(self.int(g)?).map_err(|_| not_evaluable())?;
@@ -127,6 +143,9 @@ impl Values<'_> {
/// Whether the argument or output a predicate gates is present.
fn present(&self, p: &Option<Predicate>) -> Result<bool, Error> {
match p {
// A function constant that is not a `bool`, of floating-point type, is normalized to
// 1.0 where it is supplied and non-zero and to 0.0 otherwise.
Some(p) if self.holds_float(p.global) => Ok(self.float_nonzero(p.global)),
Some(p) => Ok(self.int(p.global)? != 0),
None => Ok(true),
}
@@ -539,7 +539,10 @@ impl<'a> Eval<'a> {
Some(SVal::Opaque) => return Ok(Step::Next(Some(SVal::Opaque))),
_ => return Err(not_evaluable(at)),
};
let c = self.folder.normalize_predicate(ty, x, m)?;
let c = match self.folder.normalize_predicate_float(ty, x, m)? {
Some(c) => Some(c),
None => self.folder.normalize_predicate(ty, x, m)?,
};
SVal::C(c.ok_or_else(|| not_evaluable(at.clone()))?)
}
Callee::Llvm {
@@ -1378,6 +1378,79 @@ fn copied_flag() -> (Module, AirAbi) {
(module, abi)
}
fn normalize_f32(f: &mut FunctionBuilder<'_>, ty: TypeId, v: Value) -> Value {
let decl_ty = f.module().fn_ty(ty, &[ty]);
let decl = f
.module()
.declare("air.normalize_function_constant_predicate.f32", decl_ty);
call(
f,
ty,
Callee::Air {
decl,
op: AirIntrinsic::FunctionConstant(FunctionConstant::NormalizePredicate(
crate::intrinsics::Elem::F32,
)),
},
&[v],
)
}
fn float_constant(v: f32) -> ConstValue {
ConstValue {
ty: DataType::Float,
bytes: Box::new(v.to_le_bytes()),
}
}
/// Apple's OpenGL front end's shape for a function constant that is a `float` (a point size):
/// the static initializer stores the constant's normalized predicate, a `float`, into `pred`,
/// which gates parameter 1.
fn float_predicate() -> (Module, AirAbi) {
let mut m = ModuleBuilder::new();
let void = m.void();
let ft = m.float();
let dev = m.ptr(AddrSpace::Device);
let size = fc_global(&mut m, "size", ft);
let zero = m.constant(ft, Const::Float(0));
let pred = m.simple_global("pred", ft, AddrSpace::Constant, Some(zero));
let (size_addr, pred_addr) = (m.global_addr(size), m.global_addr(pred));
static_init(&mut m, "init", |f| {
let v = load(f, ft, size_addr);
let p = normalize_f32(f, ft, v);
store(f, p, pred_addr);
});
let fty = m.fn_ty(void, &[dev, dev]);
let mut f = m.define("k", fty);
f.ret(None);
let k = f.finish();
let module = m.finish().unwrap();
let gated = ParamBinding {
predicate: Some(Predicate {
global: pred,
name: DiagName::new("pred"),
}),
..buffer(1, 1)
};
let abi = abi(
vec![kernel(k, vec![buffer(0, 0), gated])],
vec![fc_decl(0, size, ft)],
);
(module, abi)
}
#[test]
fn a_float_function_constant_gates_a_parameter_where_it_is_supplied_and_non_zero() {
let kept = |constants: &[(u32, ConstValue)]| -> Vec<u32> {
let (module, abi) = float_predicate();
let e = specialize(module, &abi, &request(constants), &mut meter()).unwrap();
e.ep.params.iter().map(|p| p.param).collect()
};
assert_eq!(kept(&[(0, float_constant(1.5))]), [0, 1], "non-zero is on");
assert_eq!(kept(&[(0, float_constant(0.0))]), [0], "zero is off");
assert_eq!(kept(&[]), [0], "unsupplied is off");
}
#[test]
fn a_static_initializer_bakes_its_stores_into_constant_globals() {
let (module, abi) = copied_flag();
@@ -851,6 +851,7 @@ const OBSERVED: &[(&str, &str)] = &[
// Function constants, fragment, imageblocks.
("air.is_function_constant_defined", "i1 (p2)"),
("air.normalize_function_constant_predicate.i8", "i8 (i8)"),
("air.normalize_function_constant_predicate.f32", "f32 (f32)"),
("air.discard_fragment", "void ()"),
(
"air.map_physical_to_screen_coordinates.v2f32.p2i8.i32",
@@ -92,7 +92,9 @@ impl BoolReduce {
pub enum FunctionConstant {
/// `air.is_function_constant_defined`: `i1 (ptr addrspace(2))`, the constant's global.
IsDefined,
/// `air.normalize_function_constant_predicate.<iN>`: `iN (iN)`.
/// `air.normalize_function_constant_predicate.<iN>`: `iN (iN)`; of a float constant, `.f16` or
/// `.f32`: the same over a float, 1.0 where it is a known non-zero and 0.0 where it is zero or
/// undefined.
NormalizePredicate(Elem),
/// The texture operation `t` (a read, sample, gather, query, or atomic) of a texture argument
/// the pipeline's function constants removed, or through a sampler argument they removed,
@@ -127,7 +129,7 @@ impl FunctionConstant {
return Some(FunctionConstant::IsDefined);
}
let ty = NumTy::parse(rest.strip_prefix("normalize_function_constant_predicate.")?)?;
(matches!(ty.elem, Elem::I8 | Elem::I16 | Elem::I32) && !ty.is_vector())
(matches!(ty.elem, Elem::I8 | Elem::I16 | Elem::I32 | Elem::F16 | Elem::F32) && !ty.is_vector())
.then_some(FunctionConstant::NormalizePredicate(ty.elem))
}