Skip to content
Merged
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
30 changes: 25 additions & 5 deletions crates/victory-shader/src/emit/lower.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ mod atomics;
mod bvh;
mod halves;
mod mesh;
use barriers::{in_step, split_wave_barriers};
use barriers::{split_wave_barriers, step_and_cap};
pub(crate) use mesh::KeptOutputs;
use mesh::prune_signature;

Expand Down Expand Up @@ -104,6 +104,10 @@ pub(crate) struct Lowered {
/// Barriers added for narrow host waves ([`split_wave_barriers`]).
#[cfg(test)]
pub split_barriers: usize,
/// Group barriers written (`dx.op.barrier`), for structural tests of
/// the exchanges between 32-lane halves.
#[cfg(test)]
pub barriers: usize,
/// The `WaveSize` the program declares.
#[cfg(test)]
pub wave_size: Option<u32>,
Expand Down Expand Up @@ -340,8 +344,13 @@ struct Lower<'a> {
/// [`Lower::relabelled_flat`], once made.
relabelled: Option<V>,
/// In halves: per IR block, whether every lane of the group runs it
/// together ([`in_step`]), where values can pass between the halves.
/// together ([`step_and_cap`]), where values can pass between the halves.
step: Vec<bool>,
/// Per IR block, whether a lane may have left the program early at a
/// capped back edge's iteration limit before reaching it
/// ([`step_and_cap`]): an explicit `s_barrier` there would wait for
/// lanes that are gone.
cap_escaped: Vec<bool>,
/// In halves: the group-shared dwords values pass between the halves
/// through, once made ([`Lower::exchange_halves`]).
half_words: Option<V>,
Expand Down Expand Up @@ -829,6 +838,7 @@ impl<'a> Lower<'a> {
}
}
}
let (step, cap_escaped) = step_and_cap(p, x.st, halves);
Lower {
s,
x,
Expand Down Expand Up @@ -880,7 +890,8 @@ impl<'a> Lower<'a> {
halves,
halves_refused,
relabelled: None,
step: if halves { in_step(p, x.st) } else { Vec::new() },
step: if halves { step } else { Vec::new() },
cap_escaped,
half_words: None,
level: 0,
alike: if halves {
Expand Down Expand Up @@ -1691,6 +1702,8 @@ impl<'a> Lower<'a> {
#[cfg(test)]
split_barriers: self.split_barriers.len(),
#[cfg(test)]
barriers: self.s.m.written_calls("dx.op.barrier"),
#[cfg(test)]
wave_size: self.s.wave_size,
#[cfg(test)]
uses_lane_index: self.s.m.has_function("dx.op.waveGetLaneIndex"),
Expand Down Expand Up @@ -3948,8 +3961,15 @@ impl<'a> Lower<'a> {
Fields::Sop { .. } => self.sop(inst),
Fields::Sopp { .. } if name == "s_barrier" && self.no_barrier.contains(&b) => Ok(()),
Fields::Sopp { .. } if name == "s_barrier" => {
self.group_barrier();
Ok(())
// A lane may have left the program early at a capped back
// edge's iteration limit before this block; a group barrier
// here would wait for lanes that are gone.
if self.cap_escaped.get(b).copied().unwrap_or(false) {
Err("an s_barrier where a lane may have left the program early at a loop's iteration limit")
} else {
self.group_barrier();
Ok(())
}
}
Fields::Sopp { .. } => Ok(()),
Fields::Smem { .. } => self.smem(inst, (b, i)),
Expand Down
240 changes: 228 additions & 12 deletions crates/victory-shader/src/emit/lower/barriers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ pub(crate) fn split_wave_barriers(p: &Program, st: &Structured) -> Option<Set<(u
};
let n = p.blocks.len();
let succ = |b: usize| p.blocks[b].exit.successors();
let step = in_step(p, st);
let step = step_and_cap(p, st, true).0;
let divergent_writes = (0..n).any(|b| {
!step[b]
&& p.blocks[b]
Expand Down Expand Up @@ -130,11 +130,104 @@ pub(crate) fn split_wave_barriers(p: &Program, st: &Structured) -> Option<Set<(u
/// Scalars are assumed alike until shown otherwise (a loop counter needs
/// itself), and the regions and the scalars are narrowed together to a
/// fixed point. With an indirect branch, the blocks each lane runs once.
pub(crate) fn in_step(p: &Program, st: &Structured) -> Vec<bool> {
let Some(regions) = halves::branch_regions(st) else {
return once_per_lane(p);
};
///
/// The other half is per block whether a lane may have left the program
/// early at a capped back edge's iteration limit before reaching it. Lowering
/// caps an unconditional back edge with an early return at the loop
/// iteration limit (`LOOP_LIMIT`): a lane whose count reaches it leaves the
/// program from the latch. The header's counter is shared by *every* back
/// edge to it, so the cap check holds for every lane only when the latch
/// and the header run together and so does each back edge to the header — a
/// conditional one with a uniform condition. Otherwise one wave's count can
/// reach the limit at the latch while another goes on, and that wave leaves
/// there: no block reachable from that loop is run by every lane of the
/// group, the same number of times, so those blocks are not in step either.
/// The escape reaches past the loop too, along the sibling paths of every
/// divergent branch the latch is reachable from: a lane that took the other
/// arm never passes the latch's cap, so a barrier after that branch can
/// still be reached while a lane in the loop arm has left at the cap. The
/// walk back from the latch stops at a block every lane runs together,
/// though: every lane reconverges there before the cap exit, so a divergent
/// branch earlier than that, whose arms already reconverged there, is no
/// escape.
///
/// With `need_step` false the step half is left out unless the program has
/// an `s_barrier` after a capped back edge, the only reader of the escape
/// half.
pub(crate) fn step_and_cap(
p: &Program,
st: &Structured,
need_step: bool,
) -> (Vec<bool>, Vec<bool>) {
let n = p.blocks.len();
// Reverse postorder ranks, as lowering numbers them: a Jump to a block at
// or before the jump is a back edge.
let order = crate::ir::reverse_postorder(&p.blocks);
let mut rpo = vec![usize::MAX; n];
for (r, &b) in order.iter().enumerate() {
rpo[b] = r;
}
let back = |b: usize, t: usize| rpo[b] != usize::MAX && rpo[t] <= rpo[b];
// The unconditional back edges, (latch, header): lowering counts the
// loop's iterations and at the limit leaves the program from the latch
// with an early return.
let capped: Vec<(usize, usize)> = (0..n)
.filter_map(|b| match st.exits[b] {
LaneExit::Jump(t) if back(b, t) => Some((b, t)),
_ => None,
})
.collect();
if !need_step
&& (capped.is_empty()
|| !p
.blocks
.iter()
.any(|b| b.insts.iter().any(|i| i.name() == "s_barrier")))
{
return (Vec::new(), vec![false; n]);
}
let Some(regions) = halves::branch_regions(p, st) else {
return (
if need_step {
once_per_lane(p)
} else {
Vec::new()
},
vec![false; n],
);
};
let mut succ: Vec<Vec<usize>> = vec![Vec::new(); n];
for (b, e) in st.exits.iter().enumerate() {
match *e {
LaneExit::Jump(t) => succ[b].push(t),
LaneExit::Branch {
taken, not_taken, ..
} => {
succ[b].push(taken);
succ[b].push(not_taken);
}
LaneExit::End | LaneExit::Indirect => {}
}
}
// Every back edge to each header: the header's iteration counter is
// shared by all of them.
let mut back_to: Vec<Vec<usize>> = vec![Vec::new(); n];
for b in 0..n {
match st.exits[b] {
LaneExit::Jump(t) if back(b, t) => back_to[t].push(b),
LaneExit::Branch {
taken, not_taken, ..
} => {
if back(b, taken) {
back_to[taken].push(b);
}
if back(b, not_taken) {
back_to[not_taken].push(b);
}
}
_ => {}
}
}
let scalar = |r: Reg| matches!(r, Reg::S(_) | Reg::Scc);
// Not EXEC or VCC: lane masks.
let mask = |r: Reg| matches!(r, Reg::S(k) if [EXEC, EXEC + 1, VCC, VCC + 1].contains(&k));
Expand All @@ -154,6 +247,12 @@ pub(crate) fn in_step(p: &Program, st: &Structured) -> Vec<bool> {
_ => true,
}
};
let together = |when: Bool, alike: &Set<Value>| {
st.bools
.support(when)
.iter()
.all(|a| matches!(a, Atom::Uniform(v) if alike.contains(v)))
};
let mut alike: Set<Value> = p
.inputs
.iter()
Expand All @@ -177,17 +276,134 @@ pub(crate) fn in_step(p: &Program, st: &Structured) -> Vec<bool> {
let LaneExit::Branch { when, .. } = st.exits[*d] else {
continue;
};
let together = st
.bools
.support(when)
.iter()
.all(|a| matches!(a, Atom::Uniform(v) if alike.contains(v)));
if !together {
if !together(when, &alike) {
for (b, &r) in region.iter().enumerate() {
step[b] &= !r;
}
}
}
// A capped back edge's cap check holds for every lane only when the
// latch and the header run together and so does every back edge to
// the header (a conditional one with a uniform condition): one the
// lanes do not run together can put one wave's count over the limit
// at the latch while another goes on, and that wave leaves the
// program there — so no block reachable from the loop is run by
// every lane of the group, the same number of times.
let cap_uniform = |latch: usize, header: usize, step: &[bool], alike: &Set<Value>| {
step[latch]
&& step[header]
&& back_to[header].iter().all(|&b| {
if !step[b] {
return false;
}
match st.exits[b] {
LaneExit::Jump(t) => t == header,
LaneExit::Branch {
when,
taken,
not_taken,
} => {
(taken == header || not_taken == header)
&& together(when, alike)
}
_ => false,
}
})
};
let mut escaped = vec![false; n];
// Reverse adjacency, to walk back from each latch to the branches
// that can reach it.
let mut preds: Vec<Vec<usize>> = vec![Vec::new(); n];
for (b, ss) in succ.iter().enumerate() {
for &s in ss {
preds[s].push(b);
}
}
// Mark every block forward-reachable from `from`.
let mark = |from: usize, escaped: &mut Vec<bool>| {
let mut seen = vec![false; n];
let mut stack = vec![from];
seen[from] = true;
while let Some(b) = stack.pop() {
escaped[b] = true;
for &s in &succ[b] {
if !seen[s] {
seen[s] = true;
stack.push(s);
}
}
}
};
loop {
let mut changed = false;
for &(latch, header) in &capped {
if cap_uniform(latch, header, &step, &alike) {
continue;
}
// Whether the latch is in step, before the walk from the
// header below clears it.
let latch_in_step = step[latch];
let mut seen = vec![false; n];
let mut stack = vec![header];
seen[header] = true;
while let Some(b) = stack.pop() {
escaped[b] = true;
if std::mem::replace(&mut step[b], false) {
changed = true;
}
for &s in &succ[b] {
if !seen[s] {
seen[s] = true;
stack.push(s);
}
}
}
// The sibling paths of every divergent branch the latch is
// reachable from: a lane that took another arm of such a
// branch never passes the latch's cap, so it can still reach
// a barrier after the branch while a lane in the loop arm
// has left the program at the cap. (The branch's own block
// every lane runs, and a uniform branch sends every lane the
// same way, so neither is marked here.)
let arms = |d: usize, escaped: &mut Vec<bool>| {
if let LaneExit::Branch { when, .. } = st.exits[d]
&& !together(when, &alike)
{
for &s in &succ[d] {
mark(s, escaped);
}
}
};
let mut seen = vec![false; n];
let mut stack = vec![latch];
if latch_in_step {
// The latch is in step, but a back edge to the header
// the lanes do not run together shares its counter all
// the same: walk back from those sources too.
stack.extend(back_to[header].iter().copied().filter(|&b| !step[b]));
}
while let Some(b) = stack.pop() {
if std::mem::replace(&mut seen[b], true) {
continue;
}
arms(b, &mut escaped);
for &p in &preds[b] {
arms(p, &mut escaped);
// Walk back only through blocks the lanes do not run
// together: at a block every lane runs together they
// all reconverge before the cap exit, so an earlier
// divergent branch whose arms already reconverged
// there cannot strand a lane past the cap.
if !step[p] {
stack.push(p);
}
}
}
}
if !changed {
break;
}
}
let mut next: Set<Value> = p
.inputs
.iter()
Expand All @@ -213,7 +429,7 @@ pub(crate) fn in_step(p: &Program, st: &Structured) -> Vec<bool> {
}
}
if next.len() == alike.len() {
return step;
return (step, escaped);
}
alike = next;
}
Expand Down
Loading