Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
180 changes: 179 additions & 1 deletion d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,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();
}
Expand Down Expand Up @@ -770,6 +774,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<Option<usize>> = 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 {
Expand Down Expand Up @@ -2712,6 +2831,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 cross_block_reads_reuse_dominating_load_without_writes() {
let Diamond {
Expand Down