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
30 changes: 26 additions & 4 deletions crates/xcl/src/gpu/dxil/compact.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//! The compact form: each distinct block of a program lowered once, in a loop over a table.

use super::cfg::{Cfg, Term};
use super::lower::{ext_encoding, LResult, Lw, VAR_BUDGET};
use super::lower::{ext_encoding, LResult, Lw, LOOP_BUDGET, VAR_BUDGET, VAR_BUDGET_OWNER, VAR_BUDGET_TOTAL};
use super::lower_mem::VAR_TMP;
use super::module::{Block, Pred, Value};
use std::collections::{BTreeSet, HashMap};
Expand Down Expand Up @@ -78,9 +78,13 @@ pub fn plan(cfg: &Cfg, lw: &Lw) -> Option<Plan> {
let mut ids: HashMap<(Vec<u64>, &'static str), u32> = HashMap::new();
let (mut class, mut rep, mut next) = (Vec::new(), Vec::new(), Vec::new());
let mut falls = true;
// a loop head's guard names its loop region: heads of two regions are two classes
let regions = if lw.region_budgets { crate::gpu::recomp::budget_regions(&crate::gpu::recomp::loop_ranges(&cfg.insts)) } else { Vec::new() };
for (n, &b) in order.iter().enumerate() {
let blk = &cfg.blocks[b];
let mut key = vec![cfg.headers.contains(&b) as u64];
let head = cfg.headers.contains(&b);
let region = if head { crate::gpu::recomp::budget_region(&regions, blk.pc).unwrap_or(0) as u64 } else { 0 };
let mut key = vec![head as u64 + region];
for &i in &blk.insts {
let d = &cfg.insts[i];
key.push(d.words.len() as u64);
Expand Down Expand Up @@ -238,6 +242,8 @@ pub fn emit_with_nest(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block

let (at, to) = (lw.tmp_var(), lw.tmp_var());
let (at, to, budget) = (slot(lw, at), slot(lw, to), slot(lw, VAR_BUDGET));
let regions = if lw.region_budgets { crate::gpu::recomp::budget_regions(&crate::gpu::recomp::loop_ranges(&cfg.insts)) } else { Vec::new() };
let owner = if regions.is_empty() { None } else { Some((slot(lw, VAR_BUDGET_OWNER), slot(lw, VAR_BUDGET_TOTAL))) };
lw.s.m.set_block(head);
let b = lw.s.m.load(at, 4);
let w = lw.c(width);
Expand Down Expand Up @@ -300,8 +306,19 @@ pub fn emit_with_nest(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block
lw.ssa.begin_log();
let blk = &cfg.blocks[p.order[r]];
if cfg.headers.contains(&p.order[r]) {
// a loop head spends the loop budget
let left = lw.s.m.load(budget, 4);
// a loop head spends the loop budget (of its region: the recompiler's `loop_guard`)
let region = owner.zip(crate::gpu::recomp::budget_region(&regions, blk.pc));
let mut left = lw.s.m.load(budget, 4);
if let Some(((own_at, total_at), r)) = region {
let own = lw.s.m.load(own_at, 4);
let other = lw.cmpc(Pred::Ne, own, r);
left = lw.selc(other, LOOP_BUDGET * crate::gpu::recomp::LOOP_BUDGETS_PER_REGION, left);
let rv = lw.c(r);
lw.s.m.store(own_at, rv, 4);
let total = lw.s.m.load(total_at, 4);
let spent = lw.cmpc(Pred::Eq, total, 0);
left = lw.selc(spent, 0, left);
}
let none = lw.cmpc(Pred::Eq, left, 0);
let (out, body) = (lw.block(Some(1)), lw.block(Some(1)));
lw.cond_br(none, out, body);
Expand All @@ -313,6 +330,11 @@ pub fn emit_with_nest(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block
let one = lw.c(1);
let l = lw.sub(left, one);
lw.s.m.store(budget, l, 4);
if let Some(((_, total_at), _)) = region {
let total = lw.s.m.load(total_at, 4);
let t = lw.sub(total, one);
lw.s.m.store(total_at, t, 4);
}
}
for &i in &blk.insts {
lw.inst(&cfg.insts[i])?;
Expand Down
41 changes: 40 additions & 1 deletion crates/xcl/src/gpu/dxil/compact_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,45 @@ fn gpu_compact_form_spends_the_loop_budget_as_the_plain_form() {
assert_eq!(&c.sgpr[..2], &p.sgpr[..2]);
}

/// The direct translator's forms give each loop region its own budget as the HLSL path does
/// (`recomp::tests::gpu_a_loop_after_a_spin_to_the_budget_still_runs`).
#[test]
fn gpu_a_loop_after_a_spin_to_the_budget_still_runs_in_both_forms() {
match (runner::adapter(), runner::wave64_programs_supported(), crate::gpu::recomp::dxc::location()) {
(Ok(_), Ok(true), Ok(_)) => {}
(a, _, d) => return runner::skip_test(if a.is_err() { "no GPU" } else if d.is_err() { "no DXC" } else { "no wave64" }),
}
let o = KernelOptions { wave64: true, split: runner::split_wave64(), mem_windows: 1, sampler_base: 0 };
for (spin, n, nested) in [(0x10000, 3, false), (0xFFF0, 1000, false), (0x10000, 3, true)] {
let i = |nm: &str, e: &str, f: &[(&str, u64)], lit: Option<u32>| encode(nm, e, f, lit).unwrap_or_else(|x| panic!("{nm}: {x}"));
// a spin of `spin` tries (in an outer loop that runs once when `nested`), a loop of `n`,
// then s2 = 7 (as `recomp::tests::spin_then_loop`)
let mut v = Vec::new();
v.extend(i("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 128)], None));
if nested {
v.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 3), ("SSRC0", 3), ("SSRC1", 129)], None));
}
v.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 129)], None));
v.extend(i("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 255)], Some(spin)));
v.extend(i("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFC)], None));
if nested {
v.extend(i("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 3), ("SSRC1", 129)], None));
v.extend(i("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFF9)], None));
}
v.extend(i("S_MOV_B32", "ENC_SOP1", &[("SDST", 1), ("SSRC0", 128)], None));
v.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 1), ("SSRC1", 129)], None));
v.extend(i("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 1), ("SSRC1", 255)], Some(n)));
v.extend(i("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFC)], None));
v.extend(i("S_MOV_B32", "ENC_SOP1", &[("SDST", 2), ("SSRC0", 135)], None));
v.extend(i("S_ENDPGM", "ENC_SOPP", &[], None));
for compact in [true, false] {
let k = translate_full_as(&v, o, compact).unwrap_or_else(|e| panic!("compact {compact}: {e}"));
let r = runner::run_with_statics(&k.dxil, &KernelState::default(), &[], &[], &[], &k.static_samplers).expect("GPU run");
assert_eq!(&r.sgpr[..3], &[spin, n, 7], "spin {spin:#x}, loop {n}, nested {nested}, compact {compact}");
}
}
}

fn early_outs(copies: usize) -> Vec<u8> {
let i = |n: &str, e: &str, f: &[(&str, u64)]| encode(n, e, f, None).unwrap_or_else(|x| panic!("{n}: {x}"));
let mut v = Vec::new();
Expand Down Expand Up @@ -210,7 +249,7 @@ fn a_gpu_with_64_lane_waves_keeps_the_first_table_limit() {
let code = two_segments(8192);
let o = KernelOptions { wave64: true, split: false, mem_windows: 1, sampler_base: 0 };
let cs = crate::gpu::recomp::CsInterface { threads: [64, 1, 1], user_sgprs: 4, tgid: [false; 3], tg_size: false, tid_components: 1 };
let size = |wave32_only| super::kernel::translate_compute_on(&code, o, &cs, wave32_only).unwrap().dxil.len();
let size = |wave32_only| super::kernel::translate_compute_on(&code, o, &cs, wave32_only, true).unwrap().dxil.len();
let (compact, plain) = (size(true), size(false));
assert!(compact * 20 < plain, "{compact} B on a GPU with 32-lane waves only, {plain} B on one with 64-lane waves");
}
Expand Down
66 changes: 51 additions & 15 deletions crates/xcl/src/gpu/dxil/kernel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use std::collections::{BTreeSet, HashMap};

use super::cfg::{Cfg, Term};
use super::container::Stage;
use super::lower::{ComputeInit, Init, Lw, Partner, VAR_BUDGET, VAR_SCC, VAR_VGPR};
use super::lower::{ComputeInit, Init, Lw, Partner, LOOP_BUDGET, VAR_BUDGET, VAR_BUDGET_OWNER, VAR_BUDGET_TOTAL, VAR_SCC, VAR_VGPR};
use super::module::{Block, Pred, Value};
use super::shader::{RawUav, Shader};
use super::ssa::Ssa;
Expand Down Expand Up @@ -91,39 +91,39 @@ pub fn compact_nest_tag() -> Option<String> {
/// `translate_full` in the compact form (`compact = true`) or the plain one.
#[cfg(test)]
pub fn translate_full_as(code: &[u8], o: KernelOptions, compact: bool) -> Result<Kernel, String> {
translate_entry(code, o, Entry::Kernel, Some(compact), None, super::compact::TABLE_WORDS_WAVE32)
translate_entry(code, o, Entry::Kernel, Some(compact), None, super::compact::TABLE_WORDS_WAVE32, true)
}

/// `translate_full` in the compact form with an explicit dispatch nesting policy.
#[cfg(test)]
pub fn translate_full_nested(code: &[u8], o: KernelOptions, nest: super::compact::Nest) -> Result<Kernel, String> {
translate_entry(code, o, Entry::Kernel, Some(true), Some(nest), super::compact::TABLE_WORDS_WAVE32)
translate_entry(code, o, Entry::Kernel, Some(true), Some(nest), super::compact::TABLE_WORDS_WAVE32, true)
}

pub fn translate_full(code: &[u8], o: KernelOptions) -> Result<Kernel, String> {
translate_entry(code, o, Entry::Kernel, compact_mode(), None, super::compact::TABLE_WORDS_WAVE32)
translate_entry(code, o, Entry::Kernel, compact_mode(), None, super::compact::TABLE_WORDS_WAVE32, true)
}

/// A mesh-mode (NGG) program: the first pass that writes one record per group into
/// `res` (the recompiler's `Mode::Mesh`; the pass-through mesh shader draws them).
pub fn translate_mesh(code: &[u8], o: KernelOptions, ms: &MsInterface) -> Result<Kernel, String> {
translate_entry(code, o, Entry::Mesh(ms.clone()), None, None, 0)
translate_entry(code, o, Entry::Mesh(ms.clone()), None, None, 0, true)
}

/// A vertex shader (the recompiler's `Mode::Vertex`; wave-size independent).
pub fn translate_vertex(code: &[u8], o: KernelOptions, vs: &VsInterface) -> Result<Kernel, String> {
translate_entry(code, o, Entry::Vertex(vs.clone()), None, None, 0)
translate_entry(code, o, Entry::Vertex(vs.clone()), None, None, 0, true)
}

/// A pixel shader (the recompiler's `Mode::Pixel`; wave-size independent).
pub fn translate_pixel(code: &[u8], o: KernelOptions, ps: &PsInterface) -> Result<Kernel, String> {
translate_entry(code, o, Entry::Pixel(ps.clone()), None, None, 0)
translate_entry(code, o, Entry::Pixel(ps.clone()), None, None, 0, true)
}

/// A geometry-mode (ES+GS) program: the compute pass that writes one mesh record per
/// group of 21 triangles into `res` (the recompiler's `Mode::Geometry`). Always wave64.
pub fn translate_geometry(code: &[u8], o: KernelOptions, g: &GsInterface) -> Result<Kernel, String> {
translate_entry(code, KernelOptions { wave64: true, ..o }, Entry::Geometry(g.clone()), None, None, 0)
translate_entry(code, KernelOptions { wave64: true, ..o }, Entry::Geometry(g.clone()), None, None, 0, true)
}

/// The entry ABI.
Expand All @@ -139,13 +139,21 @@ pub enum Entry {

/// A compute-mode program (the CS ABI of `cs`).
pub fn translate_compute(code: &[u8], o: KernelOptions, cs: &CsInterface) -> Result<Kernel, String> {
translate_compute_on(code, o, cs, true)
translate_compute_on(code, o, cs, true, true)
}

/// `translate_compute` for a GPU: one that runs only 32-lane waves takes larger compact tables.
pub fn translate_compute_on(code: &[u8], o: KernelOptions, cs: &CsInterface, wave32_only: bool) -> Result<Kernel, String> {
/// `translate_compute` for a GPU: one that runs only 32-lane waves takes larger compact tables,
/// and one whose compute programs keep the single loop budget (`recomp::Options::region_budgets`,
/// `pso::region_budgets`) passes `region_budgets` false.
pub fn translate_compute_on(code: &[u8], o: KernelOptions, cs: &CsInterface, wave32_only: bool, region_budgets: bool) -> Result<Kernel, String> {
let tables = if wave32_only { super::compact::TABLE_WORDS_WAVE32 } else { super::compact::TABLE_WORDS };
translate_entry(code, o, Entry::Compute(cs.clone()), compact_mode(), None, tables)
translate_entry(code, o, Entry::Compute(cs.clone()), compact_mode(), None, tables, region_budgets)
}

/// `translate_compute_on` in the compact form (`compact = true`) or the plain one.
#[cfg(test)]
pub fn translate_compute_as(code: &[u8], o: KernelOptions, cs: &CsInterface, compact: bool, region_budgets: bool) -> Result<Kernel, String> {
translate_entry(code, o, Entry::Compute(cs.clone()), Some(compact), None, super::compact::TABLE_WORDS_WAVE32, region_budgets)
}

fn translate_entry(
Expand All @@ -155,14 +163,15 @@ fn translate_entry(
compact: Option<bool>,
nest: Option<super::compact::Nest>,
tables: usize,
region_budgets: bool,
) -> Result<Kernel, String> {
// SSA construction recurses along the CFG (one level per guarded memory access between
// a register's definition and its use): a thread with a large stack for big programs
let code = code.to_vec();
std::thread::Builder::new()
.name("xcl-dxil-translate".into())
.stack_size(256 << 20)
.spawn(move || translate_on_this_thread(&code, o, entry, compact, nest, tables))
.spawn(move || translate_on_this_thread(&code, o, entry, compact, nest, tables, region_budgets))
.map_err(|e| format!("translator thread: {e}"))?
.join()
.map_err(|e| {
Expand Down Expand Up @@ -193,6 +202,7 @@ fn translate_on_this_thread(
compact: Option<bool>,
nest: Option<super::compact::Nest>,
tables: usize,
region_budgets: bool,
) -> Result<Kernel, String> {
let geo = match &entry {
Entry::Geometry(g) => Some(g.clone()),
Expand All @@ -209,6 +219,8 @@ fn translate_on_this_thread(
let split = o.wave64 && o.split && !gfx;
let leaders: BTreeSet<u64> = cfg.blocks.iter().filter_map(|b| b.insts.first().map(|&i| cfg.insts[i].pc)).collect();
let mut lw = Lw::new(&cfg.insts, &leaders, o, &entry);
// a compute program's region budgets only where the caller wants them (`compact` reads this too)
lw.region_budgets &= kernel || region_budgets;
let uses_lds = lw.lds.is_some();
let res = lw.res;
let io = lw.init.io.expect("the I/O buffer");
Expand Down Expand Up @@ -343,6 +355,13 @@ fn translate_on_this_thread(
None => super::compact::emit(&mut lw, &cfg, p, h0, exit)?,
}
}
// Per-region loop budgets target compute spin-wait passes (PR #2793); keep graphics/mesh
// stages on the single-budget CFG so AMD LLPC does not trip on multi-PHI mesh loop headers.
let regions = if lw.region_budgets {
crate::gpu::recomp::budget_regions(&crate::gpu::recomp::loop_ranges(&cfg.insts))
} else {
Vec::new()
};
for &b in cfg.rpo.iter().filter(|_| plan.is_none()) {
let h = head(&mut lw, b);
lw.s.m.set_block(h);
Expand All @@ -358,15 +377,31 @@ fn translate_on_this_thread(
}
let end = if es_block { switch.unwrap() } else { exit };
if cfg.headers.contains(&b) {
// a lane's loop iterations are capped (the recompiler's LOOP_GUARD)
let left = lw.rd(VAR_BUDGET);
// a lane's loop iterations are capped (the recompiler's LOOP_GUARD / loop_guard)
let region = crate::gpu::recomp::budget_region(&regions, cfg.blocks[b].pc);
let mut left = lw.rd(VAR_BUDGET);
if let Some(r) = region {
let own = lw.rd(VAR_BUDGET_OWNER);
let other = lw.cmpc(Pred::Ne, own, r);
left = lw.selc(other, LOOP_BUDGET * crate::gpu::recomp::LOOP_BUDGETS_PER_REGION, left);
let rv = lw.c(r);
lw.wr(VAR_BUDGET_OWNER, rv);
let total = lw.rd(VAR_BUDGET_TOTAL);
let spent = lw.cmpc(Pred::Eq, total, 0);
left = lw.selc(spent, 0, left);
}
let none = lw.cmpc(Pred::Eq, left, 0);
let cont = lw.block(Some(1));
lw.cond_br(none, end, cont);
lw.s.m.set_block(cont);
let one = lw.c(1);
let l = lw.sub(left, one);
lw.wr(VAR_BUDGET, l);
if region.is_some() {
let total = lw.rd(VAR_BUDGET_TOTAL);
let t = lw.sub(total, one);
lw.wr(VAR_BUDGET_TOTAL, t);
}
}
for &i in &cfg.blocks[b].insts {
lw.reload = reloads.get(b, i);
Expand Down Expand Up @@ -553,6 +588,7 @@ impl Lw {
guard_override: None,
mask_override: None,
local_masks: false,
region_budgets: kernel || cs.is_some(),
exchange_error: None,
pc: 0,
};
Expand Down
12 changes: 11 additions & 1 deletion crates/xcl/src/gpu/dxil/lower.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@ pub const VAR_XDEAD: u32 = VAR_BUDGET + 4;
pub const VAR_IMG_WRITE: u32 = VAR_BUDGET + 8;
/// loop iterations a lane may run (the recompiler's `xcl_budget`)
pub const LOOP_BUDGET: u32 = 1 << 16;
/// the loop region whose budget [`VAR_BUDGET`] holds (the recompiler's `xcl_bown`, `budget_region`)
pub const VAR_BUDGET_OWNER: u32 = VAR_BUDGET + 7;
/// iterations left to all the regions together (the recompiler's `xcl_btotal`)
pub const VAR_BUDGET_TOTAL: u32 = VAR_BUDGET + 24;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Dst {
Expand Down Expand Up @@ -115,10 +119,13 @@ impl Init {
if var == VAR_BUDGET {
return s.m.i32c(LOOP_BUDGET);
}
if var == VAR_BUDGET_TOTAL {
return s.m.i32c(LOOP_BUDGET * crate::gpu::recomp::LOOP_BUDGETS_IN_ALL);
}
if var == super::lower_round::VAR_F32_MODE {
return s.m.i32c(super::lower_round::MODE_INIT);
}
if var == VAR_FP16_RM || var == VAR_WIN || var == VAR_XK || var == VAR_XDEAD || (VAR_IMG_WRITE..VAR_IMG_WRITE + 16).contains(&var) {
if var == VAR_FP16_RM || var == VAR_BUDGET_OWNER || var == VAR_WIN || var == VAR_XK || var == VAR_XDEAD || (VAR_IMG_WRITE..VAR_IMG_WRITE + 16).contains(&var) {
return s.m.i32c(0);
}
if var >= super::lower_mem::VAR_TMP {
Expand Down Expand Up @@ -264,6 +271,9 @@ pub struct Lw {
/// when it is never read whole. Set by a caller that reads back only each lane's own bit
/// (the per-lane form's bridge), so no exchange meets the other half.
pub local_masks: bool,
/// the program's loop regions get their own budgets (`recomp::budget_regions`): kernels,
/// and compute programs unless the adapter's are kept on one (`kernel::translate_compute_on`)
pub region_budgets: bool,
}

impl Lw {
Expand Down
Loading
Loading