From 0f8f57b6a04283ae35450a74e9ec2415c6bc6351 Mon Sep 17 00:00:00 2001 From: bobcatchris <83428450+bobcatchris@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:38:40 -0600 Subject: [PATCH] leonida-shader: hoist uniform createHandleFromHeap out of branches and loops (D3D12-SHADER-OPT-HOIST-HEAP-HANDLES) Addresses the d3d12/docs/findings.md item ("descriptors made again in every branch of a program (createHandleFromHeap of an index that is a root constant plus an offset, behind a branch on a load)"). Adds Module::hoist_handles() under REUSE: marks uniform (nonuniform = false) dx.op.createHandleFromHeap calls, their wrapping annotateHandle calls, and their pure, non-trapping index/clamp operands (cbufferLoadLegacy, integer non-div/rem arithmetic, casts, extracts, dx.op.binary.i32 clamp), and hoists each in RPO order to the deepest dominating block defining its operands. REUSE then collapses duplicate handles across sibling branches and loops into a single descriptor handle. Nonuniform handles and handles whose index depends on branch-local memory loads remain in their original blocks. AI-assisted: Antigravity (Gemini 4 Neon) --- .../leonida-shader/src/emit/bitcode/opt.rs | 180 +++++++++++++++++- 1 file changed, 179 insertions(+), 1 deletion(-) diff --git a/d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs b/d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs index d0e205663c..dd9dd711e1 100644 --- a/d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs +++ b/d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs @@ -247,7 +247,11 @@ impl Module { // the next (a loop's registers that only go round), and a // branch that goes one way leaves blocks with one way in. for _ in 0..4 { - let mut changed = self.merge(passes); + let mut changed = false; + if passes & REUSE != 0 { + changed |= self.hoist_handles(); + } + changed |= self.merge(passes); if passes & FOLD != 0 { changed |= self.prune(); } @@ -769,6 +773,121 @@ impl Module { }) } + /// Hoists uniform `dx.op.createHandleFromHeap` calls (and their `annotateHandle` + /// plus pure, non-trapping index/clamp operands such as `cbufferLoadLegacy` + add) + /// to the earliest dominating block where all operands are defined, so `REUSE` + /// collapses identical descriptors created in sibling branches or loops to one. + fn hoist_handles(&mut self) -> bool { + if self.blocks.len() <= 1 { + return false; + } + let tree = self.dominator_tree(); + let mut depth = vec![0usize; self.blocks.len()]; + let mut dfs = vec![0usize]; + while let Some(b) = dfs.pop() { + for &c in &tree.children[b] { + depth[c] = depth[b] + 1; + dfs.push(c); + } + } + let mut def_block: Vec> = vec![None; self.insts.len()]; + for &b in &tree.order { + for &i in self.blocks[b].phis.iter().chain(&self.blocks[b].body) { + def_block[i as usize] = Some(b); + } + } + let is_false = |v: V| matches!(v, V::Const(c) if matches!(self.consts[c as usize].1, Const::Int(0))); + let mut eligible = vec![false; self.insts.len()]; + let mut work = Vec::new(); + for &b in &tree.order { + for &i in &self.blocks[b].body { + if let Op::Call(f, args) = &self.insts[i as usize].op + && self.funcs[*f as usize].name == "dx.op.createHandleFromHeap" + && args.len() >= 4 + && is_false(args[3]) + { + eligible[i as usize] = true; + work.push(i); + } + } + } + if work.is_empty() { + return false; + } + // Mark `annotateHandle` wrapping an eligible uniform heap handle. + for &b in &tree.order { + for &i in &self.blocks[b].body { + if let Op::Call(f, args) = &self.insts[i as usize].op + && self.funcs[*f as usize].name == "dx.op.annotateHandle" + && let Some(&V::Inst(h)) = args.get(1) + && eligible[h as usize] + { + eligible[i as usize] = true; + } + } + } + // Walk backward from eligible handles to include pure, non-trapping index/clamp operands. + while let Some(i) = work.pop() { + for_each_operand(&self.insts[i as usize].op, |v| { + let V::Inst(op) = v else { return }; + if eligible[op as usize] || def_block[op as usize].is_none() { + return; + } + let hoistable = match &self.insts[op as usize].op { + Op::Bin(bin, _, _) => !matches!(bin, Bin::UDiv | Bin::SDiv | Bin::URem), + Op::Cast(..) | Op::Extract(..) => true, + Op::Call(f, _) => { + let name = &self.funcs[*f as usize].name; + name.starts_with("dx.op.cbufferLoadLegacy") + || name == "dx.op.binary.i32" + || name == "dx.op.createHandleFromBinding" + || name.starts_with("dx.op.createHandleForLib") + } + _ => false, + }; + if hoistable { + eligible[op as usize] = true; + work.push(op); + } + }); + } + // Move eligible instructions in RPO order to the deepest dominating operand block. + let mut moved = false; + for &b in &tree.order { + if b == 0 { + continue; + } + let body = std::mem::take(&mut self.blocks[b].body); + let mut kept = Vec::with_capacity(body.len()); + for i in body { + if !eligible[i as usize] { + kept.push(i); + continue; + } + let mut target = 0usize; + let mut ok = true; + for_each_operand(&self.insts[i as usize].op, |v| { + if let V::Inst(op) = v { + match def_block[op as usize] { + Some(ob) if depth[ob] > depth[target] => target = ob, + Some(_) => {} + None => ok = false, + } + } + }); + if ok && target != b && depth[target] < depth[b] { + self.blocks[target].body.push(i); + def_block[i as usize] = Some(target); + moved = true; + } else { + kept.push(i); + } + } + self.blocks[b].body = kept; + } + moved + } + /// [`FOLD`], [`REUSE`], [`FACTS`] and [`LOADS`]: one walk over the /// dominator tree. Returns whether anything changed. fn merge(&mut self, passes: u32) -> bool { @@ -2621,6 +2740,65 @@ mod tests { g.k.m } + #[test] + fn uniform_heap_handles_hoist_out_of_branches_and_deduplicate() { + let Diamond { + k: Kit { mut m, b: entry, writes, .. }, + then, + other, + join, + .. + } = diamond(); + let i32t = m.int(32); + let i1t = m.int(1); + let cfty = m.func_ty(i32t, vec![i32t, i32t]); + let cb = m.function("dx.op.cbufferLoadLegacy.i32", cfty, Some(Attr::ReadOnly), false); + let hfty = m.func_ty(i32t, vec![i32t, i32t, i1t, i1t]); + let heap = m.function("dx.op.createHandleFromHeap", hfty, Some(Attr::ReadNone), false); + let afty = m.func_ty(i32t, vec![i32t, i32t, i32t]); + let ann = m.function("dx.op.annotateHandle", afty, Some(Attr::ReadNone), false); + let (op_heap, op_ann, op_cb) = (m.i32(218), m.i32(216), m.i32(59)); + let (slot, off, props) = (m.i32(0), m.i32(4), m.i32(1)); + let (no, yes) = (m.bool(false), m.bool(true)); + + // Both branches independently compute `cb(0) + 4` -> uniform `createHandleFromHeap` -> `annotateHandle`. + let r1 = m.call(then, cb, vec![op_cb, slot]); + let idx1 = m.bin(then, Bin::Add, r1, off); + let h1 = m.call(then, heap, vec![op_heap, idx1, no, no]); + let a1 = m.call(then, ann, vec![op_ann, h1, props]); + m.call(then, writes, vec![a1, off]); + + let r2 = m.call(other, cb, vec![op_cb, slot]); + let idx2 = m.bin(other, Bin::Add, r2, off); + let h2 = m.call(other, heap, vec![op_heap, idx2, no, no]); + let a2 = m.call(other, ann, vec![op_ann, h2, props]); + m.call(other, writes, vec![a2, off]); + + // A nonuniform handle in `then` must NOT be hoisted to `entry`. + let h_nu = m.call(then, heap, vec![op_heap, idx1, no, yes]); + m.call(then, writes, vec![h_nu, off]); + let _ = join; + + m.optimise(REUSE | DEAD); + let then_stores = super::tests::stores(&m, then); + let other_stores = super::tests::stores(&m, other); + assert_eq!( + then_stores[0][0], other_stores[0][0], + "uniform heap handles in sibling branches should hoist to entry and collapse to one" + ); + let V::Inst(a_id) = then_stores[0][0] else { panic!() }; + assert!( + m.blocks[entry].body.contains(&a_id), + "hoisted annotateHandle should live in entry" + ); + let V::Inst(nu_id) = then_stores[1][0] else { panic!() }; + assert!( + m.blocks[then].body.contains(&nu_id), + "nonuniform createHandleFromHeap must remain in its branch" + ); + m.write(); + } + #[test] fn every_pass_leaves_what_random_programs_store() { let mut removed = 0;