From ce91bce594260f78ba9c66546db57b6d1e48a54e Mon Sep 17 00:00:00 2001 From: djrolfes Date: Tue, 1 Dec 2026 08:34:45 +0100 Subject: [PATCH] shader/opt: extend Module::bounded() to zero-identity Add/Sub and budgeted acyclic Phi --- .../leonida-shader/src/emit/bitcode/opt.rs | 196 ++++++++++++++++-- 1 file changed, 184 insertions(+), 12 deletions(-) diff --git a/d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs b/d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs index 17ba664162..d670235a89 100644 --- a/d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs +++ b/d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs @@ -455,51 +455,91 @@ impl Module { /// For a float that is a number and not an infinity whatever the program /// reads: a power of two its magnitude does not pass. pub(crate) fn bounded(&self, v: V, depth: u32) -> Option { + let mut budget = 64; + self.bounded_inner(v, depth, &mut budget) + } + + fn bounded_inner(&self, v: V, depth: u32, budget: &mut u32) -> Option { if let Some(k) = self.float_k(v) { return k.is_finite().then(|| k.abs().max(1e-30).log2().ceil()); } let V::Inst(i) = v else { return None }; let depth = depth.checked_sub(1)?; - let of = |v: V| self.bounded(v, depth); + *budget = budget.checked_sub(1)?; // (A power that overflows, or might with rounding, is no bound.) let held = |b: f32| (b < 126.0).then_some(b); match &self.insts[i as usize].op { Op::Cast(Cast::UiToFp | Cast::SiToFp, _) => Some(32.0), Op::Cast(Cast::Bitcast, x) => match *x { V::Inst(j) => match self.insts[j as usize].op { - Op::Cast(Cast::Bitcast, y) if self.type_of(y) == self.type_of(v) => of(y), + Op::Cast(Cast::Bitcast, y) if self.type_of(y) == self.type_of(v) => { + self.bounded_inner(y, depth, budget) + } _ => None, }, _ => None, }, - Op::Bin(Bin::Mul, a, b) => held(of(*a)? + of(*b)?), - Op::Bin(Bin::Add | Bin::Sub, a, b) => held(of(*a)?.max(of(*b)?) + 1.0), - Op::Select(_, a, b) => Some(of(*a)?.max(of(*b)?)), + Op::Bin(Bin::Mul, a, b) => { + held(self.bounded_inner(*a, depth, budget)? + self.bounded_inner(*b, depth, budget)?) + } + Op::Bin(Bin::Add | Bin::Sub, a, b) => { + if self.float_k(*a) == Some(0.0) { + self.bounded_inner(*b, depth, budget) + } else if self.float_k(*b) == Some(0.0) { + self.bounded_inner(*a, depth, budget) + } else { + held( + self.bounded_inner(*a, depth, budget)? + .max(self.bounded_inner(*b, depth, budget)?) + + 1.0, + ) + } + } + Op::Select(_, a, b) => { + Some(self.bounded_inner(*a, depth, budget)?.max(self.bounded_inner(*b, depth, budget)?)) + } + Op::Phi(inc) if !inc.is_empty() && inc.len() <= 64 => { + let mut hi = f32::NEG_INFINITY; + for (idx, &(val, _)) in inc.iter().enumerate() { + if inc[..idx].iter().any(|&(prev, _)| prev == val) { + continue; + } + hi = hi.max(self.bounded_inner(val, depth, budget)?); + } + Some(hi) + } Op::Call(_, args) => { let (_, code) = self.int_k(*args.first()?)?; match (code, &args[1..]) { // Saturated, a fraction, a cosine or sine (of a number). (7, [_]) => Some(0.0), - (6, [x]) => of(*x), - (22 | 12 | 13, [x]) => of(*x).map(|_| 0.0), - (26..=29, [x]) => held(of(*x)? + 1.0), + (6, [x]) => self.bounded_inner(*x, depth, budget), + (22 | 12 | 13, [x]) => self.bounded_inner(*x, depth, budget).map(|_| 0.0), + (26..=29, [x]) => held(self.bounded_inner(*x, depth, budget)? + 1.0), // Of two numbers; or one of them the other way round: the // minimum (36) of a constant and a maximum of another. - (35 | 36, [a, b]) => match (of(*a), of(*b)) { + (35 | 36, [a, b]) => match ( + self.bounded_inner(*a, depth, budget), + self.bounded_inner(*b, depth, budget), + ) { (Some(x), Some(y)) => Some(x.max(y)), _ => { let other = if code == 35 { 36 } else { 35 }; let (inner, k) = if self.float_k(*b).is_some() { (*a, *b) } else { (*b, *a) }; - let k = self.float_k(k).and_then(|_| of(k))?; + let k = self.float_k(k).and_then(|_| self.bounded_inner(k, depth, budget))?; let V::Inst(j) = inner else { return None }; let Op::Call(_, inner) = &self.insts[j as usize].op else { return None }; let (_, code) = self.int_k(*inner.first()?)?; let low = inner[1..].iter().find(|x| self.float_k(**x).is_some())?; (code == other).then_some(())?; - Some(k.max(of(*low)?)) + Some(k.max(self.bounded_inner(*low, depth, budget)?)) } }, - (46, [a, b, c]) => held((of(*a)? + of(*b)?).max(of(*c)?) + 1.0), + (46, [a, b, c]) => held( + (self.bounded_inner(*a, depth, budget)? + self.bounded_inner(*b, depth, budget)?) + .max(self.bounded_inner(*c, depth, budget)?) + + 1.0, + ), _ => None, } } @@ -2884,4 +2924,136 @@ mod tests { // The programs are of the wasteful kind: the passes find work. assert!(removed > 4000, "{removed} instructions removed"); } + + #[test] + fn bounded_tracks_zero_identity_and_acyclic_phi() { + let mut m = Module::default(); + let i32t = m.int(32); + let f32t = m.float(); + let void = m.void(); + let unary_ty = m.func_ty(f32t, vec![i32t, f32t]); + m.ptr(unary_ty); + let unary_fn = m.function("dx.op.unary.f32", unary_ty, Some(Attr::ReadNone), false); + let load_ty = m.func_ty(f32t, vec![i32t]); + m.ptr(load_ty); + let load_fn = m.function("dx.op.loadInput.f32", load_ty, Some(Attr::ReadOnly), false); + let main_ty = m.func_ty(void, vec![]); + m.ptr(main_ty); + m.function("main", main_ty, None, true); + + let b0 = m.new_block(); + let b1 = m.new_block(); + let b2 = m.new_block(); + let join = m.new_block(); + let loop_bb = m.new_block(); + + let zero_i = m.i32(0); + let x = m.call(b0, load_fn, vec![zero_i]); + let sat_op = m.i32(7); + let sat = m.call(b0, unary_fn, vec![sat_op, x]); + assert_eq!(m.bounded(x, 12), None); + assert_eq!(m.bounded(sat, 12), Some(0.0)); + + // Zero-identity Add/Sub preserves the exact bound without adding +1.0 + // (including IEEE negation `-0.0 - x` and values near the 2^125 overflow cutoff). + let pos_zero = m.f32(0.0f32.to_bits()); + let neg_zero = m.f32((-0.0f32).to_bits()); + let neg_sat = m.bin(b0, Bin::Sub, neg_zero, sat); + let add_l = m.bin(b0, Bin::Add, pos_zero, sat); + let add_r = m.bin(b0, Bin::Add, sat, pos_zero); + let sub_r = m.bin(b0, Bin::Sub, sat, pos_zero); + assert_eq!(m.bounded(neg_sat, 12), Some(0.0)); + assert_eq!(m.bounded(add_l, 12), Some(0.0)); + assert_eq!(m.bounded(add_r, 12), Some(0.0)); + assert_eq!(m.bounded(sub_r, 12), Some(0.0)); + + let big = m.f32(2.0f32.powi(125).to_bits()); + let neg_big = m.bin(b0, Bin::Sub, neg_zero, big); + assert_eq!(m.bounded(neg_big, 12), Some(125.0)); + + let neg_unbounded = m.bin(b0, Bin::Sub, neg_zero, x); + let add_unbounded = m.bin(b0, Bin::Add, pos_zero, x); + assert_eq!(m.bounded(neg_unbounded, 12), None); + assert_eq!(m.bounded(add_unbounded, 12), None); + + // Acyclic Phi takes the maximum bound across all incoming edges. + let four = m.f32(4.0f32.to_bits()); + let one = m.f32(1.0f32.to_bits()); + let phi_ok = m.phi(join, f32t); + m.set_phi(phi_ok, vec![(neg_sat, b1), (four, b2)]); + assert_eq!(m.bounded(phi_ok, 12), Some(2.0)); + + // Empty Phi and Phi with any unbounded edge must return None. + let phi_empty = m.phi(join, f32t); + m.set_phi(phi_empty, vec![]); + assert_eq!(m.bounded(phi_empty, 12), None); + + let phi_bad = m.phi(join, f32t); + m.set_phi(phi_bad, vec![(sat, b1), (x, b2)]); + assert_eq!(m.bounded(phi_bad, 12), None); + + // Cyclic loop Phis (incrementing or self-referential) must hit the depth limit. + let loop_phi = m.phi(loop_bb, f32t); + let inc = m.bin(loop_bb, Bin::Add, loop_phi, one); + m.set_phi(loop_phi, vec![(one, b0), (inc, loop_bb)]); + assert_eq!(m.bounded(loop_phi, 12), None); + + let self_phi = m.phi(loop_bb, f32t); + m.set_phi(self_phi, vec![(one, b0), (self_phi, loop_bb)]); + assert_eq!(m.bounded(self_phi, 12), None); + } + + #[test] + fn bounded_budget_caps_wide_phi_dag() { + let mut m = Module::default(); + let i32t = m.int(32); + let f32t = m.float(); + let void = m.void(); + let unary_ty = m.func_ty(f32t, vec![i32t, f32t]); + m.ptr(unary_ty); + let unary_fn = m.function("dx.op.unary.f32", unary_ty, Some(Attr::ReadNone), false); + let load_ty = m.func_ty(f32t, vec![i32t]); + m.ptr(load_ty); + let load_fn = m.function("dx.op.loadInput.f32", load_ty, Some(Attr::ReadOnly), false); + let main_ty = m.func_ty(void, vec![]); + m.ptr(main_ty); + m.function("main", main_ty, None, true); + + let b0 = m.new_block(); + let zero_i = m.i32(0); + let x = m.call(b0, load_fn, vec![zero_i]); + let sat_op = m.i32(7); + let mut cur = m.call(b0, unary_fn, vec![sat_op, x]); + let neg_zero = m.f32((-0.0f32).to_bits()); + + // Small 2-way acyclic Phi diamond stays within the 64-visit budget and proves Some(0.0). + let mut small = cur; + for _ in 0..2 { + let l = m.new_block(); + let r = m.new_block(); + let j = m.new_block(); + let a = m.bin(l, Bin::Sub, neg_zero, small); + let b = m.bin(r, Bin::Add, neg_zero, small); + let p = m.phi(j, f32t); + m.set_phi(p, vec![(a, l), (b, r)]); + small = p; + } + assert_eq!(m.bounded(small, 12), Some(0.0)); + + // 5-level 4-way diamond DAG with distinct ops per edge (>4^5 = 1,024 paths; + // 10 levels would be >10^6 without a visit budget): capped cleanly to None. + for _ in 0..10 { + let mut incoming = Vec::with_capacity(4); + let j = m.new_block(); + for _ in 0..4 { + let arm = m.new_block(); + let v = m.bin(arm, Bin::Sub, neg_zero, cur); + incoming.push((v, arm)); + } + let p = m.phi(j, f32t); + m.set_phi(p, incoming); + cur = p; + } + assert_eq!(m.bounded(cur, 12), None); + } }