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
35 changes: 35 additions & 0 deletions crates/xcl/src/gpu/recomp/emit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ pub(super) struct Em {
cur_pc: u64,
/// MIMG instruction address → its sampler's S# when the code builds it from constants
pub static_ss: BTreeMap<u64, [u32; 4]>,
/// loops emitted so far with a pass count of their own (`loop_guard`)
loop_ids: u32,
/// the static samplers sampled with: (S#, comparison), in register order
pub static_used: Vec<([u32; 4], bool)>,
/// highest VGPR the program references (v_movrel* ranges)
Expand Down Expand Up @@ -587,6 +589,7 @@ impl Em {
upper: None,
cur_pc: 0,
static_ss: BTreeMap::new(),
loop_ids: 0,
static_used: Vec::new(),
max_vgpr: 0,
has_f16_round_op: false,
Expand Down Expand Up @@ -4648,6 +4651,19 @@ impl Em {
h.push_str(" xcl_xn = XCL_X_THREADS > ((xcl_tid & ~31u) ^ 32u) ? min(32u, XCL_X_THREADS - ((xcl_tid & ~31u) ^ 32u)) : 0u;\n");
}

/// What goes before a loop and at its top (`LOOP_GUARD`). In a compute program every entry
/// of a loop also has its own count of passes, `xcl_cap`: 65 536, or the share of
/// `DISPATCH_LOOP_PASSES` the dispatch gives a lane (`IO_LOOP_BUDGET`). A loop that runs
/// away alone ends there; loops inside one another keep the lane's whole budget.
pub fn loop_guard(&mut self) -> (String, String) {
if !matches!(self.opt.mode, Mode::Compute(_)) {
return (String::new(), super::LOOP_GUARD.to_string());
}
self.loop_ids += 1;
let n = format!("xcl_n{}", self.loop_ids);
(format!("uint {n}{LOOP_CAP_INIT}"), format!("if ({n} == 0u) break; {n}--; {}", super::LOOP_GUARD))
}

pub fn finish(&self, body: &str) -> String {
let mut h = String::new();
h.push_str("// generated by XCL (RDNA2 -> HLSL), do not edit\n");
Expand Down Expand Up @@ -4678,6 +4694,11 @@ impl Em {
let _ = writeln!(h, "{ty} xcl_ss{k} : register(s{k}, space1);");
}
h.push_str(PRELUDE);
if body.contains(LOOP_CAP_INIT) {
h.push_str("// loop passes one entry of a loop may run (`Em::loop_guard`)
static uint xcl_cap = 1u << 16;
");
}
if matches!(self.opt.mode, Mode::Pixel(_)) {
h.push_str(PRELUDE_PIXEL);
}
Expand Down Expand Up @@ -4844,6 +4865,17 @@ impl Em {
h.push_str(" lane_id = WaveGetLaneIndex();\n");
}
load_sgprs(&mut h);
// a program with a loop: the dispatch's share of loop passes for a group
// (`IO_LOOP_BUDGET`, 0 = not known) among its threads
if body.contains(LOOP_CAP_INIT) {
let _ = writeln!(
h,
" {{ uint xcl_gb = io.Load({}u); if (xcl_gb != 0u) xcl_cap = clamp(xcl_gb / {}u, {}u, 1u << 16); }}",
super::IO_LOOP_BUDGET * 4,
x * y * z,
super::DISPATCH_LOOP_PASSES_MIN
);
}
// system SGPRs after the user data: enabled group ids, then TG_SIZE
let mut next = cs.user_sgprs as u64;
for (k, c) in ["x", "y", "z"].iter().enumerate() {
Expand Down Expand Up @@ -6067,6 +6099,9 @@ uint2 ballot_px_local(bool b) {
}
"#;

/// How `Em::loop_guard` starts a loop's own pass count (and how `finish` knows of them).
const LOOP_CAP_INIT: &str = " = xcl_cap;";

const PRELUDE: &str = r#"
static uint lane_id;
// loop iterations a lane may run (`LOOP_GUARD`): far above what a working program needs
Expand Down
38 changes: 35 additions & 3 deletions crates/xcl/src/gpu/recomp/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,10 @@ pub const GS_PRIMS_PER_GROUP: u32 = 21;
pub const IO_GS_PRIMS: usize = 110;
pub const IO_GS_VERTICES: usize = 111;
pub const IO_UMA_BASE_HI: usize = 112;
/// io slot of a compute dispatch's loop budget (`dispatch_loop_budget`): the passes the lanes
/// of one of its thread groups may run together in one entry of a loop, 0 = not known (an
/// indirect dispatch, a test: 65 536 a lane, as the lane's whole budget).
pub const IO_LOOP_BUDGET: usize = 113;

impl GsInterface {
/// bytes of one ES vertex in LDS (ESGS item: 16 per ES output register)
Expand Down Expand Up @@ -639,12 +643,32 @@ impl Conts {
}

/// At the top of every emitted loop: a lane's loop iterations are capped (`xcl_budget`, in
/// the prelude: 65 536) – console code that loops on what XCL passed it wrong (an address, a
/// the prelude: 65 536; in a compute program each entry of a loop besides, by the dispatch's
/// size: `Em::loop_guard`, `dispatch_loop_budget`) – console code that loops on what XCL passed it wrong (an address, a
/// count) must not keep the PC GPU busy for minutes (a process with such work in flight cannot
/// even be terminated). Once the budget is spent every loop
/// leaves at its next iteration and the program runs to its end.
const LOOP_GUARD: &str = "if (xcl_budget == 0u) break; xcl_budget--;";

/// The passes all the lanes of one compute dispatch may run together in one entry of a loop
/// before the loop is ended (`Em::loop_guard`). 65 536 passes a lane keep a small dispatch
/// busy for a moment and a large one for far longer than Windows waits for the GPU (2 s, then
/// the device is removed): a retail program of 4 x 4 x 4 threads given a loop count that never
/// comes, dispatched as 16 x 16 x 16 groups on an RTX 3060 Ti, measured 0.47 ms a pass – 31 s
/// for 65 536 of them, 0.5 s for the 1024 a lane that this many passes in all leave it.
pub const DISPATCH_LOOP_PASSES: u64 = 1 << 28;
/// The passes of one entry of a loop a lane has however large its dispatch is: a working
/// program's loop is not cut short because many threads run it.
pub const DISPATCH_LOOP_PASSES_MIN: u32 = 1024;

/// What a compute dispatch of `groups` thread groups puts into `IO_LOOP_BUDGET`: its share of
/// `DISPATCH_LOOP_PASSES` for one group. The program divides it by its threads per group
/// (between `DISPATCH_LOOP_PASSES_MIN` and 65 536 a lane); never 0, which means "not known".
pub fn dispatch_loop_budget(groups: [u32; 3]) -> u32 {
let n: u64 = groups.iter().map(|&g| g.max(1) as u64).product();
(DISPATCH_LOOP_PASSES / n).clamp(1, u32::MAX as u64) as u32
}

/// Structured code longer than this many bytes per byte of program falls back to the `pc` form.
/// Each guard of the structured form lists every pending skip flag, so it grows with the
/// square of the flags: one retail program made 455 B per byte (148 MB, 14 MB as `pc` blocks),
Expand Down Expand Up @@ -1022,7 +1046,11 @@ fn emit_structured(
}
let raised: BTreeSet<u64> = match it {
Item::Loop { a, b, latch, entry } => {
body.push_str(&format!("{ipad}[loop] for (;;) {{\n{ipad} {LOOP_GUARD}\n"));
let (before, guard) = em.loop_guard();
if !before.is_empty() {
body.push_str(&format!("{ipad}{before}\n"));
}
body.push_str(&format!("{ipad}[loop] for (;;) {{\n{ipad} {guard}\n"));
let (lcont, lin) = if entry.is_none() { (cont.enter(Some(a)), &inner) } else { (cont.enter(None), &none) };
let mut r = emit_structured(c, em, body, entry.unwrap_or(a), latch, None, nest + 1, &lcont, lin, d + 1, blocks, flags);
for &t in &r {
Expand Down Expand Up @@ -1143,7 +1171,11 @@ fn emit_range(c: &Ctx, em: &mut emit::Em, body: &mut String, lo: u64, hi: u64, d
let start = c.leaders[i];
let inner = c.loops.iter().filter(|&&(a, b)| a == start && b <= hi && (a, b) != (lo, hi)).max_by_key(|x| x.1).copied();
if let Some((a, b)) = inner {
body.push_str(&format!("{pad}[loop] while (pc >= {a}u && pc < {b}u) {{\n{pad} {LOOP_GUARD}\n"));
let (before, guard) = em.loop_guard();
if !before.is_empty() {
body.push_str(&format!("{pad}{before}\n"));
}
body.push_str(&format!("{pad}[loop] while (pc >= {a}u && pc < {b}u) {{\n{pad} {guard}\n"));
emit_range(c, em, body, a, b, depth + 1, blocks, flags);
body.push_str(&format!("{pad}}}\n"));
i = c.leaders.partition_point(|&l| l < b);
Expand Down
118 changes: 118 additions & 0 deletions crates/xcl/src/gpu/recomp/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7188,6 +7188,124 @@ fn gpu_compute_tg_size_counts_a_partial_last_wave() {
}
}

/// A loop that only ends when its counter wraps to 0, then global_store_dword [v0 * 4], the
/// counter: the passes a lane ran before the loop was ended.
fn endless_loop_program() -> Vec<u8> {
prog(&[
("S_MOV_B32", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 128)], None),
("S_ADD_U32", "ENC_SOP2", &[("SDST", 10), ("SSRC0", 10), ("SSRC1", 129)], None),
("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 10), ("SSRC1", 128)], None),
("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFD)], None),
("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 10)], None),
("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 130), ("VSRC1", 0)], None),
("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 128)], None),
("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 6), ("DATA", 4), ("SADDR", 0x7D)], None),
])
}

/// The same loop inside one of three passes: global_store_dword [v0 * 4], the sum of the
/// inner loop's passes over its three entries.
fn endless_loop_entered_three_times() -> Vec<u8> {
prog(&[
("S_MOV_B32", "ENC_SOP1", &[("SDST", 11), ("SSRC0", 128)], None),
("S_MOV_B32", "ENC_SOP1", &[("SDST", 12), ("SSRC0", 128)], None),
// the outer loop: three passes
("S_MOV_B32", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 128)], None),
("S_ADD_U32", "ENC_SOP2", &[("SDST", 10), ("SSRC0", 10), ("SSRC1", 129)], None),
("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 10), ("SSRC1", 128)], None),
("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFD)], None),
("S_ADD_U32", "ENC_SOP2", &[("SDST", 12), ("SSRC0", 12), ("SSRC1", 10)], None),
("S_ADD_U32", "ENC_SOP2", &[("SDST", 11), ("SSRC0", 11), ("SSRC1", 129)], None),
("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 11), ("SSRC1", 131)], None),
("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFF8)], None),
("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 12)], None),
("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 130), ("VSRC1", 0)], None),
("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 128)], None),
("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 6), ("DATA", 4), ("SADDR", 0x7D)], None),
])
}

/// `IO_LOOP_BUDGET`: one thread group's share of `DISPATCH_LOOP_PASSES` – all of it for a
/// dispatch of one group, less the more groups there are, and never 0 ("not known").
#[test]
fn dispatch_loop_budget_shrinks_with_the_groups() {
use super::{dispatch_loop_budget as budget, DISPATCH_LOOP_PASSES};
assert_eq!(budget([1, 1, 1]) as u64, DISPATCH_LOOP_PASSES);
assert_eq!(budget([16, 16, 16]) as u64, DISPATCH_LOOP_PASSES / 4096);
// 64 threads a group: 1024 passes a lane
assert_eq!(budget([16, 16, 16]) / 64, 1024);
// a count of 0 dispatches nothing: as 1
assert_eq!(budget([0, 8, 0]), budget([1, 8, 1]));
assert_eq!(budget([65_535, 65_535, 65_535]), 1);
}

/// Only the loops of a compute program count their own passes against the dispatch's share:
/// the HLSL of every other program (and with it the DXIL cache's key) is as it was.
#[test]
fn only_compute_programs_with_a_loop_read_the_dispatch_loop_budget() {
let cs = super::CsInterface { threads: [8, 4, 2], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1 };
let compute = Options { mode: Mode::Compute(cs), wave64: false, ..Default::default() };
let looping = translate(&endless_loop_program(), &compute).unwrap();
assert!(looping.complete(), "{:?}", looping.unsupported_why);
let read = format!("uint xcl_gb = io.Load({}u); if (xcl_gb != 0u) xcl_cap = clamp(xcl_gb / 64u, 1024u, 1u << 16);", super::IO_LOOP_BUDGET * 4);
assert_eq!(looping.hlsl.matches(&read).count(), 1, "{}", looping.hlsl);
assert_eq!(looping.hlsl.matches("static uint xcl_cap = 1u << 16;").count(), 1, "{}", looping.hlsl);
assert!(looping.hlsl.contains("uint xcl_n1 = xcl_cap;"), "{}", looping.hlsl);
assert!(looping.hlsl.contains("if (xcl_n1 == 0u) break; xcl_n1--; if (xcl_budget == 0u) break; xcl_budget--;"), "{}", looping.hlsl);
// each loop has a count of its own
let nested = translate(&endless_loop_entered_three_times(), &compute).unwrap();
assert!(nested.hlsl.contains("uint xcl_n1 = xcl_cap;") && nested.hlsl.contains("uint xcl_n2 = xcl_cap;"), "{}", nested.hlsl);
// the same program as a kernel, and a compute program without a loop
let kernel = translate(&endless_loop_program(), &Options { wave64: false, ..Default::default() }).unwrap();
assert!(kernel.hlsl.contains("xcl_budget--") && !kernel.hlsl.contains("xcl_cap") && !kernel.hlsl.contains("xcl_gb"), "{}", kernel.hlsl);
let straight = prog(&[
("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 2)], None),
("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 130), ("VSRC1", 0)], None),
("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 128)], None),
("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 6), ("DATA", 4), ("SADDR", 0x7D)], None),
]);
let straight = translate(&straight, &compute).unwrap();
assert!(!straight.hlsl.contains("xcl_cap") && !straight.hlsl.contains("xcl_gb") && !straight.hlsl.contains("xcl_budget--"), "{}", straight.hlsl);
}

/// A compute program's loop that never meets its exit runs the passes its dispatch gives one
/// entry of a loop: `IO_LOOP_BUDGET` among the group's threads, between 1024 and 65 536 a
/// lane, the same in every thread (both halves of a split wave64). A dispatch that does not
/// say (0) leaves it the lane's 65 536. Entered three times the loop runs them three times:
/// loops inside one another are not cut to one loop's share. The HLSL path: the direct
/// translator has its own fixed budget.
#[test]
fn gpu_compute_loop_passes_follow_the_dispatch() {
if !gpu_ready() {
return;
}
let threads = 64u32;
let run = |p: &[u8], wave64: bool, slot: u32| -> u32 {
let cs = super::CsInterface { threads: [threads, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1 };
let opt = on_gpu(Options { mode: Mode::Compute(cs), wave64, ..Default::default() });
let t = translate(p, &opt).unwrap();
assert!(t.complete(), "{:?}", t.unsupported_why);
let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", t.hlsl));
let mut io = [0u32; 128];
io[super::IO_LOOP_BUDGET] = slot;
let mem = runner::dispatch(&dxil, [1, 1, 1], &io, &vec![0xFFFF_FFFFu32; threads as usize]).unwrap();
for (k, &got) in mem.iter().take(threads as usize).enumerate() {
assert_eq!(got, mem[0], "wave{}, slot {slot}: thread {k}", if wave64 { 64 } else { 32 });
}
mem[0]
};
for wave64 in [false, true] {
// (the slot, passes): not known; 5000 a lane; shares below and above the bounds
for (slot, passes) in [(0u32, 65_536u32), (threads * 5000, 5000), (1, 1024), (u32::MAX, 65_536)] {
assert_eq!(run(&endless_loop_program(), wave64, slot), passes, "wave64 {wave64}, slot {slot}");
}
// three entries of 1024 passes; without a share the first entry spends the lane's
// budget (but for the outer loop's own pass) and ends the program
assert_eq!(run(&endless_loop_entered_three_times(), wave64, 1), 3 * 1024, "wave64 {wave64}");
assert_eq!(run(&endless_loop_entered_three_times(), wave64, 0), 65_535, "wave64 {wave64}");
}
}

/// v_fract_f32 at the edges, as RDNA computes it (x - floor(x) kept below 1.0): ±inf gives
/// NaN and a NaN stays NaN – a `min()` clamp returned 0.99999994 there on NVIDIA (HLSL min
/// returns its non-NaN operand); a tiny negative value rounds to the largest float below 1.
Expand Down
14 changes: 9 additions & 5 deletions crates/xcl/src/hle/d3d12x/bind.rs
Original file line number Diff line number Diff line change
Expand Up @@ -297,7 +297,7 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us
return;
}
let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return };
match bind_abi(this, list, pso, gfx) {
match bind_abi(this, list, pso, gfx, None) {
Ok(()) => {
count(if gfx { DRAWS } else { DISPATCHES });
fresh_indirect_arguments(this, || pc(this, sig, max, args, args_off, count_buf, count_off))
Expand Down Expand Up @@ -525,7 +525,7 @@ unsafe fn graphics_bound(this: *mut c_void) -> Option<ID3D12GraphicsCommandList>
if super::present::trace_frame() {
trace_ui_draw(this, pso);
}
match bind_abi(this, &list, pso, true) {
match bind_abi(this, &list, pso, true, None) {
Ok(()) => {
count(DRAWS);
Some(list)
Expand Down Expand Up @@ -934,15 +934,16 @@ unsafe fn translated_dispatch(this: *mut c_void, list: &ID3D12GraphicsCommandLis
if super::present::trace_frame() {
trace_fullscreen(this, pso, [x, y, z]);
}
bind_abi(this, list, pso, false)?;
bind_abi(this, list, pso, false, Some([x, y, z]))?;
list.Dispatch(x, y, z);
Ok(())
}

/// XCL's ABI for a translated pipeline: its root signature, the user SGPRs (`io`, the kept
/// arguments the console's way – compute or graphics) and the argument table in unified
/// memory, u1 res, u2… the memory windows; then the pipeline.
unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usize, gfx: bool) -> Result<(), String> {
/// memory, u1 res, u2… the memory windows; then the pipeline. `groups`: the thread groups of a
/// dispatch whose counts are known here (`IO_LOOP_BUDGET`).
unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usize, gfx: bool, groups: Option<[u32; 3]>) -> Result<(), String> {
super::list_x::ensure_view_heap(this);
let u = crate::gpu::uma::get().ok_or("no unified memory")?;
let windows = super::real::uma_window_vas();
Expand All @@ -967,6 +968,9 @@ unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usi
};
io.resize(crate::gpu::recomp::KERNEL_SGPRS, 0);
io[crate::gpu::recomp::IO_UMA_BASE_HI] = (u.base() >> 32) as u32;
if let Some(groups) = groups {
io[crate::gpu::recomp::IO_LOOP_BUDGET] = crate::gpu::recomp::dispatch_loop_budget(groups);
}
let io_at = copy(&io.iter().flat_map(|w| w.to_le_bytes()).collect::<Vec<u8>>())?;
let res_at = copy(&[0u8; 256])?;
let va = |p: usize| super::real::uma_va_of(p).unwrap_or(first);
Expand Down
1 change: 1 addition & 0 deletions crates/xcl/src/hle/d3d12x/console_list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -832,6 +832,7 @@ pub unsafe fn close(obj: *mut c_void) -> Result<Translation, String> {
};
io.resize(crate::gpu::recomp::KERNEL_SGPRS, 0);
io[crate::gpu::recomp::IO_UMA_BASE_HI] = (u.base() >> 32) as u32;
io[crate::gpu::recomp::IO_LOOP_BUDGET] = crate::gpu::recomp::dispatch_loop_budget([x, y, z]);
let io_at = uma_copy(st, bytemuck_u32(&io)).ok_or("UMA: io")?;
let res_at = uma_copy(st, &[0u8; 256]).ok_or("UMA: res")?;
// the pipeline's own root signature when it has static samplers
Expand Down
Loading