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
225 changes: 216 additions & 9 deletions crates/xcl/src/gpu/recomp/lower.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ use std::collections::HashSet;
use super::lane_masks::{self, Edge, Summary};
use super::ssa::{Sink, Ssa, Var};
use super::{KERNEL_SCC_SLOT, KERNEL_SGPRS, KERNEL_VGPRS};
use crate::gpu::dxil::lower::LOOP_BUDGET;
use crate::gpu::rdna2::{self, Decoded, Variant};

mod wave;
Expand Down Expand Up @@ -1243,6 +1244,29 @@ pub fn survey_compute<I: Ir>(insts: &[Decoded], cs: &super::CsInterface, wave64:
}
}

const LOOP_BUDGETS_PER_REGION: u32 = 2;
const LOOP_BUDGETS_IN_ALL: u32 = 4;
const LOOP_COST_BYTES: u64 = 128;
const LOOP_COST_MOST: u32 = 256;

fn budget_regions(loops: &[(u64, u64)]) -> Vec<(u64, u64)> {
let outer: Vec<(u64, u64)> = loops
.iter()
.copied()
.filter(|&(a, b)| !loops.iter().any(|&(c, d)| (c, d) != (a, b) && c <= a && b <= d))
.collect();
if outer.len() < 2 { Vec::new() } else { outer }
}

fn budget_region(regions: &[(u64, u64)], head: u64) -> Option<u32> {
regions.iter().position(|&(a, b)| a <= head && head < b).map(|k| k as u32 + 1)
}

fn loop_cost(loops: &[(u64, u64)], head: u64) -> u32 {
let innermost = loops.iter().filter(|&&(a, b)| a <= head && head < b).map(|&(a, b)| b - a).min();
innermost.map_or(1, |len| (len / LOOP_COST_BYTES).clamp(1, LOOP_COST_MOST as u64) as u32)
}

fn lower_with<I: Ir>(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I, survey: bool) -> R<(I, Vec<u8>, Vec<String>)> {
// the lanes past a dispatch's thread limit leave at the start (`IO_THREAD_LIMIT`): a group
// barrier would wait for them (#1426's form keeps them, out of EXEC, in such a program)
Expand All @@ -1268,27 +1292,53 @@ fn lower_with<I: Ir>(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I, s
if n == 0 {
return Err("empty program".into());
}
let loops = super::loop_ranges(insts);
let regions = if kernel { budget_regions(&loops) } else { Vec::new() };
// IR blocks: 0 prologue, 1..=n the program's, n + 1 exit, n + 2 lane 0's scalar stores,
// n + 3 every lane's vector stores, n + 4 the way to the exit of lanes outside EXEC at launch,
// then for every coalesced guarded run (only the lanes with their EXEC bit enter): the run's
// block and the one the rest of its block continues in. `tail[b]`: the IR block the
// program's block b ends in.
let (exit, sstore, vstore, skip) = (n + 1, n + 2, n + 3, n + 4);
let mut rpo_pos = vec![usize::MAX; n];
for (pos, &b) in sum.order.iter().enumerate() {
rpo_pos[b] = pos;
}
let mut loop_header = vec![false; n];
for &b in &sum.order {
for &(s, _) in &sum.blocks[b].succ {
if rpo_pos[s] <= rpo_pos[b] {
loop_header[s] = true;
}
}
}
let guarded: HashSet<u64> = sum.guarded.iter().copied().collect();
let mut budget_cont: Vec<Option<usize>> = vec![None; n];
let mut splits: Vec<Vec<(std::ops::Range<usize>, usize, usize)>> = vec![Vec::new(); n]; // (run, body, cont)
let mut count = n + 5;
let mut count = n + 1;
for (b, block) in sum.blocks.iter().enumerate() {
if loop_header[b] {
budget_cont[b] = Some(count);
count += 1;
}
for run in coalesced_runs(insts, &block.insts, &guarded) {
splits[b].push((run, count, count + 1));
count += 2;
}
}
let tail: Vec<usize> = (0..n).map(|b| splits[b].last().map_or(blk(b), |s| s.2)).collect();
let (exit, sstore, vstore, skip) = (count, count + 1, count + 2, count + 3);
count += 4;
let body_start = |b: usize| budget_cont[b].unwrap_or(blk(b));
let tail: Vec<usize> = (0..n).map(|b| splits[b].last().map_or(body_start(b), |s| s.2)).collect();
let mut partial = vec![false; count];
let mut def_owner: Vec<usize> = (0..count).collect();
let mut use_owner: Vec<usize> = (0..count).collect();
for (b, p) in partial_blocks(&sum).into_iter().enumerate() {
partial[blk(b)] = p;
if let Some(bc) = budget_cont[b] {
partial[bc] = p;
def_owner[bc] = blk(b);
use_owner[bc] = blk(b);
}
for &(_, s, c) in &splits[b] {
partial[s] = true;
partial[c] = p;
Expand All @@ -1309,7 +1359,10 @@ fn lower_with<I: Ir>(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I, s
preds[blk(s)].push(tail[b]);
}
}
let mut prev = blk(b);
if let Some(bc) = budget_cont[b] {
preds[bc] = vec![blk(b)];
}
let mut prev = body_start(b);
for &(_, s, c) in &splits[b] {
preds[s] = vec![prev];
preds[c] = vec![prev, s];
Expand All @@ -1326,7 +1379,12 @@ fn lower_with<I: Ir>(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I, s
} else if matches!(stage, Stage::Compute(_)) {
preds[skip] = vec![0];
}
preds[exit] = kernel.then_some(skip).into_iter().chain(ends.iter().map(|&b| tail[b])).collect();
preds[exit] = kernel
.then_some(skip)
.into_iter()
.chain(ends.iter().map(|&b| tail[b]))
.chain(sum.order.iter().copied().filter(|&b| loop_header[b]).map(blk))
.collect();
for i in 0..count {
let id = ir.new_block();
debug_assert_eq!(id, i);
Expand Down Expand Up @@ -1378,6 +1436,14 @@ fn lower_with<I: Ir>(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I, s
// prologue: the SGPRs from `io` (kernel: the whole register file; compute: the user data)
l.ir.at(0);
l.ssa.seal(&mut l.ir, 0);
let budget = l.ir.int(LOOP_BUDGET);
l.ssa.write(0, Var::Budget, budget);
if !regions.is_empty() {
let owner = l.ir.int(0);
let total = l.ir.int(LOOP_BUDGET * LOOP_BUDGETS_IN_ALL);
l.ssa.write(0, Var::BudgetOwner, owner);
l.ssa.write(0, Var::BudgetTotal, total);
}
let lane = l.lane();
for &r in &sregs {
let a = l.ir.int(r as u32);
Expand Down Expand Up @@ -1547,6 +1613,43 @@ fn lower_with<I: Ir>(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I, s
let last = block.insts.end - 1;
let body_end = block_body_end(insts, &block.insts);
let mut cur = ib;
if let Some(bc) = budget_cont[b] {
// Charge long loops for their code size, matching the other lowering backends;
// kernel programs also keep per-region budgets while compute/graphics stay on one
// program-wide budget to avoid the AMD compiler crash (#2874).
let pc = insts[block.insts.start].pc;
let cost = l.ir.int(loop_cost(&loops, pc));
let mut left = l.read(cur, Var::Budget);
let mut total = None;
let region = budget_region(&regions, pc);
if let Some(r) = region {
let owner = l.read(cur, Var::BudgetOwner);
let r_value = l.ir.int(r);
let changed = l.ir.icmp(Cmp::Ne, owner, r_value);
let fresh = l.ir.int(LOOP_BUDGET * LOOP_BUDGETS_PER_REGION);
left = l.ir.select(changed, fresh, left);
total = Some(l.read(cur, Var::BudgetTotal));
}
let mut exhausted = l.ir.icmp(Cmp::Ult, left, cost);
if let Some(t) = total {
let depleted = l.ir.icmp(Cmp::Ult, t, cost);
exhausted = l.ir.bin(Bin::Or, exhausted, depleted);
}
l.ir.br_if(exhausted, exit, bc);
done[cur] = true;
l.ir.at(bc);
l.ssa.seal(&mut l.ir, bc);
sealed[bc] = true;
let next = l.ir.bin(Bin::Sub, left, cost);
l.ssa.write(bc, Var::Budget, next);
if let (Some(r), Some(t)) = (region, total) {
let owner = l.ir.int(r);
l.ssa.write(bc, Var::BudgetOwner, owner);
let remaining = l.ir.bin(Bin::Sub, t, cost);
l.ssa.write(bc, Var::BudgetTotal, remaining);
}
cur = bc;
}
let mut split = splits[b].iter().peekable();
let mut i = block.insts.start;
while i < body_end {
Expand Down Expand Up @@ -1638,6 +1741,16 @@ fn lower_with<I: Ir>(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I, s
return l.finish(stale);
};
// kernel exit: every lane is here; masks the runner reads as numbers are the wave's ballots
let exit_stale = |l: &mut Lower<I>, var: Var, exit_v: I::V| -> bool {
if ends.is_empty() {
l.stale(exit, exit_v)
} else {
ends.iter().any(|&b| {
let v = l.read(tail[b], var);
l.stale(tail[b], v)
})
}
};
let mut sval: Vec<(u8, I::V)> = Vec::new();
let mut i = 0;
while i < sregs.len() {
Expand All @@ -1646,7 +1759,7 @@ fn lower_with<I: Ir>(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I, s
let s = l.read(exit, Var::S(r));
if l.ssa.resolve_value(s) != l.num_marker && !l.reaches(s, l.num_marker) {
l.num_uses.push(s);
if l.stale(exit, s) {
if exit_stale(&mut l, Var::S(r), s) {
stale.push(r);
}
sval.push((r, s));
Expand All @@ -1660,7 +1773,7 @@ fn lower_with<I: Ir>(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I, s
}
// read directly: a stale bit here is reported, not refused (only the ABI's store sees it)
let m = l.read(exit, Var::M(r));
if r != EXEC && l.stale(exit, m) {
if r != EXEC && exit_stale(&mut l, Var::M(r), m) {
stale.push(r);
if l.wave64 {
stale.push(r + 1); // the upper half comes from the same mask
Expand All @@ -1677,7 +1790,7 @@ fn lower_with<I: Ir>(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I, s
}
}
let scc = l.read(exit, Var::Scc);
if l.stale(exit, scc) {
if exit_stale(&mut l, Var::Scc, scc) {
stale.push(KERNEL_SCC_SLOT as u8);
}
let vval: Vec<(u16, I::V)> = vregs.iter().map(|&v| (v, l.read(exit, Var::V(v)))).collect();
Expand Down Expand Up @@ -1840,7 +1953,7 @@ impl<I: Ir> Lower<'_, I> {
let s = self.ir.icmp(Cmp::Ne, v, z);
self.write_scc(b, s);
}
Var::S(_) | Var::M(_) => {}
Var::S(_) | Var::M(_) | Var::Budget | Var::BudgetOwner | Var::BudgetTotal => {}
}
}
if name.starts_with("V_") && !sw.is_empty() {
Expand Down Expand Up @@ -4701,4 +4814,98 @@ pub(crate) mod tests {
}
check_mem(true);
}

#[test]
fn infinite_loop_exits_at_loop_budget() {
let lines: &[I] = &[
("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 128)]),
("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 129)]),
("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 129), ("VSRC1", 1)]),
("S_BRANCH", "ENC_SOPP", &[("SIMM16", 0xFFFD)]),
];
let (mut s, mut v) = state(32);
s[0] = 0;
s[126] = 1; // lane 0 active so the CPU interpreter finishes well within its step limit
v[0][1] = 0;
let (s, v) = run(lines, false, &s, &v);
assert_eq!(s[0], LOOP_BUDGET);
assert_eq!(v[0][1], LOOP_BUDGET);
}

#[test]
fn long_loop_spends_its_code_size_per_header_visit() {
let mut lines: Vec<I> = vec![
("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 128)]),
("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 255), ("LITERAL", 1)]),
];
for _ in 0..30 {
lines.push(("S_ADD_U32", "ENC_SOP2", &[("SDST", 4), ("SSRC0", 4), ("SSRC1", 255), ("LITERAL", 1)]));
}
lines.push(("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 128)]));
lines.push(("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFC0)]));
lines.push(ENDPGM);
let (mut s, mut v) = state(32);
s[126] = 1;
v[0][1] = 0;
let (s, _) = run(&lines, false, &s, &v);
assert_eq!(s[0], LOOP_BUDGET / 2, "a 256-byte loop spends two units per visit");
}

const SPIN_THEN_LOOP: &[I] = &[
("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 128)]),
("S_MOV_B32", "ENC_SOP1", &[("SDST", 1), ("SSRC0", 128)]),
("S_MOV_B32", "ENC_SOP1", &[("SDST", 3), ("SSRC0", 255), ("LITERAL", LOOP_BUDGET as u64)]),
("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 129)]),
("S_CMP_LT_U32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 3)]),
("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFD)]),
("S_ADD_U32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 1), ("SSRC1", 129)]),
("S_CMP_LT_U32", "ENC_SOPC", &[("SSRC0", 1), ("SSRC1", 131)]),
("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFD)]),
ENDPGM,
];

#[test]
fn kernel_loop_after_a_full_spin_keeps_its_own_budget() {
let (mut s, v) = state(32);
s[126] = 1;
let (s, _) = run(SPIN_THEN_LOOP, false, &s, &v);
assert_eq!(s[0], LOOP_BUDGET);
assert_eq!(s[1], 3, "the second loop must run after the first spends one budget");
}

#[test]
fn nested_loops_share_loop_budget_across_headers() {
// Outer infinite loop (header at inst 2, counted in s0) wrapping an inner loop that
// runs K = 3 times per outer iteration (header at inst 4, counted in s1 per outer
// trip and accumulated in s2 / v1 across all outer trips). Both headers decrement
// the same shared Var::Budget initialized at entry, so total header trips (s0 + s2)
// equal LOOP_BUDGET rather than LOOP_BUDGET * 3 or hanging on reinitialization.
let lines: &[I] = &[
("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 128)]),
("S_MOV_B32", "ENC_SOP1", &[("SDST", 2), ("SSRC0", 128)]),
("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 129)]),
("S_MOV_B32", "ENC_SOP1", &[("SDST", 1), ("SSRC0", 128)]),
("S_ADD_U32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 1), ("SSRC1", 129)]),
("S_ADD_U32", "ENC_SOP2", &[("SDST", 2), ("SSRC0", 2), ("SSRC1", 129)]),
("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 129), ("VSRC1", 1)]),
("S_CMP_LT_U32", "ENC_SOPC", &[("SSRC0", 1), ("SSRC1", 131)]),
("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFB)]),
("S_BRANCH", "ENC_SOPP", &[("SIMM16", 0xFFF8)]),
];
let (mut s, mut v) = state(32);
s[0] = 0;
s[1] = 0;
s[2] = 0;
s[126] = 1; // lane 0 active so the CPU interpreter finishes well within its step limit
v[0][1] = 0;
let (s, v) = run(lines, false, &s, &v);
let full_outer = LOOP_BUDGET / 4;
let rem = LOOP_BUDGET % 4;
let expected_outer = full_outer + u32::from(rem > 0);
let expected_inner = full_outer * 3 + rem.saturating_sub(1);
assert_eq!(s[0], expected_outer);
assert_eq!(s[2], expected_inner);
assert_eq!(s[0] + s[2], LOOP_BUDGET);
assert_eq!(v[0][1], expected_inner);
}
}
3 changes: 2 additions & 1 deletion crates/xcl/src/gpu/recomp/lower_dxil.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ impl DxilIr {
fn ty(&mut self, var: Var) -> crate::gpu::dxil::module::Ty {
match var {
Var::M(_) | Var::Scc => self.lw.s.m.i1(),
Var::S(_) | Var::V(_) => self.lw.s.m.i32(),
Var::S(_) | Var::V(_) | Var::Budget | Var::BudgetOwner | Var::BudgetTotal => self.lw.s.m.i32(),
}
}

Expand Down Expand Up @@ -267,6 +267,7 @@ impl Ir for DxilIr {
Var::V(n) => VAR_VGPR + n as u32,
Var::Scc => VAR_SCC,
Var::M(_) => unreachable!("a lane-bit view is not a register"),
Var::Budget | Var::BudgetOwner | Var::BudgetTotal => unreachable!("loop budget is not a register"),
};
for &(v, x) in inputs {
self.lw.wr(var(v), x);
Expand Down
4 changes: 4 additions & 0 deletions crates/xcl/src/gpu/recomp/ssa.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ pub enum Var {
M(u8),
V(u16),
Scc,
/// remaining loop-header iterations for this lane (`i32`)
Budget,
BudgetOwner,
BudgetTotal,
}

/// What the construction needs from the module builder.
Expand Down
Loading