Skip to content
Open
Show file tree
Hide file tree
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
84 changes: 73 additions & 11 deletions d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,6 @@
//! Which passes run is `emit::shader_opt()` (`LEONIDA_SHADER_OPT`), part of
//! the translation and so of the shader cache's key.

use std::collections::HashMap;

use crate::fxhash::FxHashMap;

use super::{
Expand Down Expand Up @@ -1393,8 +1391,9 @@ impl Module {
}
Some(cur) == terms[0].existing
};
let mut plans: Vec<(usize, u32, Vec<Cond>)> = Vec::new();
let mut by_block: Vec<(usize, Vec<(u32, Vec<Cond>)>)> = Vec::new();
for &b in &tree.order {
let mut block_plans: Vec<(u32, Vec<Cond>)> = Vec::new();
for &i in &self.blocks[b].body {
let inst = &self.insts[i as usize];
let candidate = inst.ty == i1
Expand All @@ -1411,24 +1410,23 @@ impl Module {
if let Some(terms) = terms_of(self, i)
&& !canonical(self, i, &terms)
{
plans.push((b, i, terms));
block_plans.push((i, terms));
}
}
if !block_plans.is_empty() {
by_block.push((b, block_plans));
}
}
if plans.is_empty() {
if by_block.is_empty() {
return false;
}
let mut repl: Vec<Option<V>> = vec![None; n];
let mut by_block: HashMap<usize, Vec<(u32, Vec<Cond>)>> = HashMap::new();
for (b, i, terms) in plans {
by_block.entry(b).or_default().push((i, terms));
}
for (b, plans) in by_block {
let old = std::mem::take(&mut self.blocks[b].body);
let mut body = Vec::with_capacity(old.len() + 2 * plans.len());
let mut plans: HashMap<u32, Vec<Cond>> = plans.into_iter().collect();
let mut plans = plans.into_iter().peekable();
for i in old {
let Some(terms) = plans.remove(&i) else {
let Some((_, terms)) = plans.next_if(|&(id, _)| id == i) else {
body.push(i);
continue;
};
Expand Down Expand Up @@ -3064,4 +3062,68 @@ mod tests {
// The programs are of the wasteful kind: the passes find work.
assert!(removed > 4000, "{removed} instructions removed");
}

#[test]
fn chains_emits_deterministic_instruction_ids_across_blocks() {
let build = || {
let Kit {
mut m,
b: entry,
reads,
writes,
..
} = kit();
let (zero, one, two) = (m.i32(0), m.i32(1), m.i32(2));
let no = m.bool(false);
let cond = |m: &mut Module, k: V| {
let v = m.call(entry, reads, vec![k, k]);
m.cmp(entry, pred::NE, v, zero)
};
let (c0, c1, c2) = (cond(&mut m, zero), cond(&mut m, one), cond(&mut m, two));
let blocks: Vec<usize> = (0..6).map(|_| m.new_block()).collect();
m.terminate(entry, Term::Br(blocks[0]));
for (idx, &bk) in blocks.iter().enumerate() {
// Reverse-ordered 3-term conjunction forces `chains()` to emit canonical `and`s in every block.
let inner = m.bin(bk, Bin::And, c2, c1);
let all = m.select(bk, inner, c0, no);
let val = m.select(bk, all, one, zero);
m.call(bk, writes, vec![val, two]);
let next = blocks.get(idx + 1).copied().map_or(Term::Ret, Term::Br);
m.terminate(bk, next);
}
(m, blocks)
};

let run_once = || {
let (mut m, blocks) = build();
let before = m.insts.len() as u32;
assert!(m.chains(), "expected chains() to rewrite non-canonical blocks");
let new_ids: Vec<Vec<u32>> = blocks
.iter()
.map(|&bk| {
m.blocks[bk]
.body
.iter()
.copied()
.filter(|&id| id >= before)
.collect()
})
.collect();
for win in new_ids.windows(2) {
let max_prev = win[0].iter().copied().max().expect("emitted ids in block");
let min_next = win[1].iter().copied().min().expect("emitted ids in next block");
assert!(
max_prev < min_next,
"new instruction IDs must advance monotonically in tree order: {new_ids:?}"
);
}
let bodies: Vec<Vec<u32>> = blocks.iter().map(|&bk| m.blocks[bk].body.clone()).collect();
(bodies, m.write())
};

let first = run_once();
for run_idx in 1..16 {
assert_eq!(run_once(), first, "run {run_idx} diverged from run 0");
}
}
}
7 changes: 3 additions & 4 deletions d3d12/crates/leonida-shader/src/emit/lower.rs
Original file line number Diff line number Diff line change
Expand Up @@ -588,7 +588,7 @@ struct Lower<'a> {
code_table: Option<(V, u32, u32)>,
/// Loop headers' iteration counters (see [`LOOP_LIMIT`]): the phi by
/// IR block, and its incoming (value, DXIL block) pairs.
counters: HashMap<usize, (V, Vec<(V, usize)>)>,
counters: BTreeMap<usize, (V, Vec<(V, usize)>)>,
/// The block a loop stopped by [`LOOP_LIMIT`] leaves the program from.
abort: Option<usize>,
/// Mesh loops whose latches jump back unconditionally and that stop at the limit through
Expand Down Expand Up @@ -2935,7 +2935,7 @@ impl<'a> Lower<'a> {
sections: HashMap::new(),
section_out: HashSet::new(),
code_table: None,
counters: HashMap::new(),
counters: BTreeMap::new(),
abort: None,
exit_caps: HashMap::new(),
pack,
Expand Down Expand Up @@ -15371,8 +15371,7 @@ impl<'a> Lower<'a> {
let p = self.x.p;
let idom = crate::ir::idoms(&p.blocks, order, &self.rpo);
let reach = |l: &Self, q: usize| l.block[q].is_some();
let mut headers: Vec<usize> = self.counters.keys().copied().collect();
headers.sort_unstable();
let headers: Vec<usize> = self.counters.keys().copied().collect();
for h in headers {
let back: Vec<usize> = p.blocks[h]
.preds
Expand Down
Loading