From 3cde150b3c7a869e95b8eefcb5a2379859ad77d0 Mon Sep 17 00:00:00 2001 From: Jesse Date: Thu, 26 Nov 2026 13:59:55 +0200 Subject: [PATCH 1/2] Recompiler: each loop region of a program gets its own iteration budget A translated program caps its loops with one per-lane counter, 65,536 iterations shared by the whole program. A program whose own spin-wait gives up after 0x10000 tries uses all of it, and every loop after that spin then leaves at its first guard. A retail FSR pass (CS a8de35e47f36d28c) polls flags written by an earlier pass with a cap of exactly 0x10000 tries, inside an outer loop. When the spin ran out, its main loop never ran. A spilled SGPR then held a weight from an earlier load where the constant buffer's 0 should have been, and the flags it publishes read that weight with bit 0 set instead of 1. The pass waiting on those flags (5f29d7e51b2c6230) spun to its own cap every frame: about 260 ms of GPU time a frame on an RTX 5070 Ti. Measured with a local probe: the flags, cb[0xa8] = 0, and the weight dword the flags carry. The outermost ranges of loop_ranges are the program's loop regions. Control only moves forward between them: a jump back would make them one range. In a program with two or more regions, each region starts with two budgets. Two, so that a 0x10000 spin inside an outer loop fits, because the outer loop's head spends from the same count. All regions together have at most four budgets (xcl_btotal / VAR_BUDGET_TOTAL), so a program that really runs away stops within four budgets. Before, it stopped within one. This is done in all three emitters: the HLSL structured and pc forms (loop_guard), the direct DXIL plain form (kernel.rs) and the compact form. In the compact form, a loop head's class now includes its region. Programs with fewer than two regions keep their exact HLSL text and cached translations. Of the title's 2,682 compute programs, 1,916 have two or more regions, so those are translated and compiled again once. Assisted-by: Claude Code (Claude Opus 5.5) Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/dxil/compact.rs | 30 +++++++++-- crates/xcl/src/gpu/dxil/compact_tests.rs | 39 ++++++++++++++ crates/xcl/src/gpu/dxil/kernel.rs | 23 ++++++-- crates/xcl/src/gpu/dxil/lower.rs | 9 +++- crates/xcl/src/gpu/recomp/mod.rs | 56 +++++++++++++++++-- crates/xcl/src/gpu/recomp/tests.rs | 69 ++++++++++++++++++++++++ 6 files changed, 213 insertions(+), 13 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/compact.rs b/crates/xcl/src/gpu/dxil/compact.rs index b84298be5e..3eb93334cd 100644 --- a/crates/xcl/src/gpu/dxil/compact.rs +++ b/crates/xcl/src/gpu/dxil/compact.rs @@ -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}; @@ -78,9 +78,13 @@ pub fn plan(cfg: &Cfg, lw: &Lw) -> Option { let mut ids: HashMap<(Vec, &'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 = crate::gpu::recomp::budget_regions(&crate::gpu::recomp::loop_ranges(&cfg.insts)); 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(®ions, 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); @@ -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 = crate::gpu::recomp::budget_regions(&crate::gpu::recomp::loop_ranges(&cfg.insts)); + 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); @@ -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(®ions, 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); @@ -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])?; diff --git a/crates/xcl/src/gpu/dxil/compact_tests.rs b/crates/xcl/src/gpu/dxil/compact_tests.rs index e0bb2e8935..21de76da32 100644 --- a/crates/xcl/src/gpu/dxil/compact_tests.rs +++ b/crates/xcl/src/gpu/dxil/compact_tests.rs @@ -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| 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 { 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(); diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 82cf4c0905..6a01b5879f 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -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; @@ -343,6 +343,7 @@ fn translate_on_this_thread( None => super::compact::emit(&mut lw, &cfg, p, h0, exit)?, } } + let regions = crate::gpu::recomp::budget_regions(&crate::gpu::recomp::loop_ranges(&cfg.insts)); for &b in cfg.rpo.iter().filter(|_| plan.is_none()) { let h = head(&mut lw, b); lw.s.m.set_block(h); @@ -358,8 +359,19 @@ 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(®ions, 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); @@ -367,6 +379,11 @@ fn translate_on_this_thread( 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); diff --git a/crates/xcl/src/gpu/dxil/lower.rs b/crates/xcl/src/gpu/dxil/lower.rs index 5034d31903..d64f169fa9 100644 --- a/crates/xcl/src/gpu/dxil/lower.rs +++ b/crates/xcl/src/gpu/dxil/lower.rs @@ -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 { @@ -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 { diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 528493d6e5..48f46e7688 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -565,6 +565,8 @@ struct Ctx<'a> { starts: &'a BTreeSet, leaders: &'a [u64], loops: &'a [(u64, u64)], + /// [`budget_regions`] + regions: &'a [(u64, u64)], /// every branch: (address of the branch, target) edges: &'a [(u64, u64)], /// split wave64 geometry mode: the ES's s_setpc ends the ES phase and `gs_start` is the GS @@ -647,6 +649,46 @@ impl Conts { /// leaves at its next iteration and the program runs to its end. const LOOP_GUARD: &str = "if (xcl_budget == 0u) break; xcl_budget--;"; +/// A program with two or more loop regions gives each this many budgets of iterations +/// ([`loop_guard`]): a title's own spin capped at one budget (0x10000 tries) must fit, also +/// when it sits in an outer loop whose head spends from the same count. +pub(crate) const LOOP_BUDGETS_PER_REGION: u32 = 2; +/// ... and all of its regions together at most this many. +pub(crate) const LOOP_BUDGETS_IN_ALL: u32 = 4; + +/// The outermost of [`loop_ranges`]: the program's loop regions, in order. Control only moves +/// forward from one to the next (a jump back into an earlier one would make them one range). +/// Empty for a program with fewer than two, whose guards stay [`LOOP_GUARD`]. +pub(crate) 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 + } +} + +/// The region ([`budget_regions`]) of the loop headed at `head`, numbered from 1. +pub(crate) fn budget_region(regions: &[(u64, u64)], head: u64) -> Option { + regions.iter().position(|&(a, b)| a <= head && head < b).map(|k| k as u32 + 1) +} + +/// The guard of the loop headed at `head`. In a program with loop regions, each region starts +/// with [`LOOP_BUDGETS_PER_REGION`] budgets, and `xcl_btotal` keeps all of them to +/// [`LOOP_BUDGETS_IN_ALL`]: a title's own spin that gives up after 0x10000 tries, the budget, +/// otherwise left every loop after it without an iteration (a retail FSR pass then published a +/// flag made from a register its main loop never set, and the pass waiting on that flag spun +/// 260 ms a frame). +fn loop_guard(regions: &[(u64, u64)], head: u64) -> String { + match budget_region(regions, head) { + Some(r) => format!( + "if (xcl_bown != {r}u) {{ xcl_bown = {r}u; xcl_budget = {}u; }} if (xcl_budget == 0u || xcl_btotal == 0u) break; xcl_budget--; xcl_btotal--;", + LOOP_BUDGETS_PER_REGION << 16 + ), + None => LOOP_GUARD.to_string(), + } +} + /// 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), @@ -656,7 +698,7 @@ const STRUCTURED_BYTES_PER_CODE_BYTE: usize = 128; /// The loops the translator emits: ranges spanned by backward jumps (far jumps included), /// partly overlapping ones merged until they nest, sorted. `x64_masks` uses them for the /// exits through `LOOP_GUARD`. -pub(super) fn loop_ranges(insts: &[Decoded]) -> Vec<(u64, u64)> { +pub(crate) fn loop_ranges(insts: &[Decoded]) -> Vec<(u64, u64)> { let mut loops: Vec<(u64, u64)> = Vec::new(); for d in insts { if let Some(t) = rdna2::branch_target(d) { @@ -1098,7 +1140,7 @@ fn emit_structured( } let raised: BTreeSet = match it { Item::Loop { a, b, latch, entry } => { - body.push_str(&format!("{ipad}[loop] for (;;) {{\n{ipad} {LOOP_GUARD}\n")); + body.push_str(&format!("{ipad}[loop] for (;;) {{\n{ipad} {}\n", loop_guard(c.regions, a))); 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 { @@ -1219,7 +1261,7 @@ 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")); + body.push_str(&format!("{pad}[loop] while (pc >= {a}u && pc < {b}u) {{\n{pad} {}\n", loop_guard(c.regions, a))); 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); @@ -1597,13 +1639,14 @@ pub fn translate(code: &[u8], opt: &Options) -> Result { // (optimising one big dispatcher loop took minutes on large retail programs). let leaders: Vec = leaders.into_iter().filter(|l| starts.contains(l)).collect(); let loops = loop_ranges(&insts); + let regions = budget_regions(&loops); let edges: Vec<(u64, u64)> = insts.iter().filter_map(|d| rdna2::branch_target(d).map(|t| (d.pc, t))).collect(); let phase_split = gs_jump.is_some_and(|t| t.is_some()) && opt.split_wave64 && opt.wave64; - let ctx = Ctx { insts: &insts, starts: &starts, leaders: &leaders, loops: &loops, edges: &edges, phase_split, memo: Default::default() }; + let ctx = Ctx { insts: &insts, starts: &starts, leaders: &leaders, loops: &loops, regions: ®ions, edges: &edges, phase_split, memo: Default::default() }; let mut flags = BTreeSet::new(); let mut code = String::new(); let nested = nested_loop_ranges(&insts); - let sctx = Ctx { insts: &insts, starts: &starts, leaders: &leaders, loops: &nested, edges: &edges, phase_split, memo: Default::default() }; + let sctx = Ctx { insts: &insts, starts: &starts, leaders: &leaders, loops: &nested, regions: ®ions, edges: &edges, phase_split, memo: Default::default() }; if gs_jump.is_none() && opt.structured && std::env::var_os("XCL_RECOMP_NO_STRUCTURED").is_none() && structurable(&sctx, 0, u64::MAX).is_some() { // structured control flow: plain if / loops, no block dispatch on `pc` (much // smaller for DXC and the driver on big programs) @@ -1619,6 +1662,9 @@ pub fn translate(code: &[u8], opt: &Options) -> Result { } emit_range(&ctx, &mut em, &mut code, 0, u64::MAX, 1, &mut blocks, &mut flags); } + if !regions.is_empty() { + body.push_str(&format!(" uint xcl_bown = 0u;\n uint xcl_btotal = {}u;\n", LOOP_BUDGETS_IN_ALL << 16)); + } for &t in &flags { body.push_str(&format!(" bool {} = false;\n", skip_flag(t))); } diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 0b018edc36..af4cceb8c9 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -1426,6 +1426,75 @@ fn gpu_scalar_loop_and_scc() { assert_eq!((r.sgpr[41], r.sgpr[42], r.sgpr[43]), (48, 33, u32::MAX), "flbit_i64 high-then-low scan"); } +/// A spin of `spin` tries (a retail FSR pass polls a flag up to 0x10000 times, the loop budget), +/// inside an outer loop that runs once when `nested` (as in that pass), then a loop of `n` +/// iterations, then `s2 = 7`. +fn spin_then_loop(spin: u32, n: u32, nested: bool) -> Vec { + let i = |nm: &str, e: &str, f: &[(&str, u64)], lit: Option| encode(nm, e, f, lit).unwrap_or_else(|x| panic!("{nm}: {x}")); + let mut v = i("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 128)], None); // s0 = 0 + if nested { + v.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 3), ("SSRC0", 3), ("SSRC1", 129)], None)); // outer: s3 += 1 + } + v.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 129)], None)); // spin: s0 += 1 + 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)); // → spin + if nested { + v.extend(i("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 3), ("SSRC1", 129)], None)); // until s3 == 1 + v.extend(i("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFF9)], None)); // → outer + } + v.extend(i("S_MOV_B32", "ENC_SOP1", &[("SDST", 1), ("SSRC0", 128)], None)); // s1 = 0 + v.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 1), ("SSRC1", 129)], None)); // loop: s1 += 1 + 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)); // → loop + v.extend(i("S_MOV_B32", "ENC_SOP1", &[("SDST", 2), ("SSRC0", 135)], None)); // s2 = 7 + v.extend(i("S_ENDPGM", "ENC_SOPP", &[], None)); + v +} + +/// A program's own spin that gives up at the loop budget, or just before it, must not leave the +/// loops after it short of iterations: the FSR pass then published a flag built from a register +/// its main loop never set, and the pass waiting on it spun for 260 ms a frame. Both HLSL forms. +#[test] +fn gpu_a_loop_after_a_spin_to_the_budget_still_runs() { + if !gpu_ready() { + return; + } + for (spin, n, nested) in [(0x10000, 3, false), (0xFFF0, 1000, false), (0x10000, 3, true)] { + let code = spin_then_loop(spin, n, nested); + for structured in [true, false] { + let opt = Options { structured, ..runner::options(Mode::Kernel) }; + let t = translate(&code, &opt).unwrap(); + let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(); + let r = runner::run(&dxil, &KernelState::default(), &[]).unwrap(); + let what = format!("spin {spin:#x}, loop {n}, nested {nested}, structured {structured}"); + assert_eq!(r.sgpr[0], spin, "{what}: the spin ran to its own end"); + assert_eq!((r.sgpr[1], r.sgpr[2]), (n, 7), "{what}: the loop after it ran all its iterations"); + } + } +} + +/// Loops that never end still stop: four budgets in all, then every loop leaves. (The direct +/// translator ends the program where a budget runs out, so this is the HLSL path's.) +#[test] +fn gpu_endless_loops_in_many_regions_stop_after_four_budgets() { + if !gpu_ready() { + return; + } + // six regions, each `s0 += 1` until s0 == 0 (2^32 tries); s1 counts the regions reached + let mut list: Vec<(&str, &str, &[(&str, u64)], Option)> = Vec::new(); + for _ in 0..6 { + list.push(("S_ADD_U32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 1), ("SSRC1", 129)], None)); + list.push(("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 129)], None)); + list.push(("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 128)], None)); + list.push(("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFD)], None)); + } + let t = translate(&prog(&list), &runner::options(Mode::Kernel)).unwrap(); + let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(); + let r = runner::run(&dxil, &KernelState::default(), &[]).unwrap(); + assert_eq!(r.sgpr[1], 6, "every region was reached"); + assert_eq!(r.sgpr[0], super::LOOP_BUDGETS_IN_ALL << 16, "four budgets of iterations in all"); +} + #[test] fn gpu_divergence_through_exec() { if !gpu_ready() { From 22c5f68cda9ecfa0d651357c79302eba83c8d21e Mon Sep 17 00:00:00 2001 From: Jesse Date: Thu, 26 Nov 2026 22:30:12 +0200 Subject: [PATCH 2/2] Recompiler: region loop budgets for compute and kernel programs only Taken from @Saksukella's #2865. The spin-wait the region budgets are for is in a compute program. Graphics and mesh stages keep the single budget: - On AMD (RX 9070 XT), the extra loop-carried values in multi-region mesh loop headers crashed the driver's compiler in CreatePipelineState (#2865). - On NVIDIA (RTX 5070 Ti, retail title), a 900 s run with region budgets in every stage hung (0x887a0006) 580 s into the world; the same run with this scope ran to the end. One run each. A pixel shader loop that runs away got up to four budgets instead of one. Pixel, vertex, geometry and mesh programs emit exactly the HLSL of main again, so their cached translations stay valid. Assisted-by: Claude Code (Claude Opus 5.5) Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/dxil/kernel.rs | 8 +++++++- crates/xcl/src/gpu/recomp/mod.rs | 8 +++++++- crates/xcl/src/gpu/recomp/tests.rs | 32 ++++++++++++++++++++++++++++++ 3 files changed, 46 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 6a01b5879f..8233554359 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -343,7 +343,13 @@ fn translate_on_this_thread( None => super::compact::emit(&mut lw, &cfg, p, h0, exit)?, } } - let regions = crate::gpu::recomp::budget_regions(&crate::gpu::recomp::loop_ranges(&cfg.insts)); + // 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 compute || kernel { + 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); diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 48f46e7688..b8e0e13f6c 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -1639,7 +1639,13 @@ pub fn translate(code: &[u8], opt: &Options) -> Result { // (optimising one big dispatcher loop took minutes on large retail programs). let leaders: Vec = leaders.into_iter().filter(|l| starts.contains(l)).collect(); let loops = loop_ranges(&insts); - let regions = budget_regions(&loops); + // Per-region loop budgets target compute spin-wait passes (PR #2793); keep graphics/mesh + // stages on the single-budget CFG. + let regions = if matches!(opt.mode, Mode::Compute(_) | Mode::Kernel) { + budget_regions(&loops) + } else { + Vec::new() + }; let edges: Vec<(u64, u64)> = insts.iter().filter_map(|d| rdna2::branch_target(d).map(|t| (d.pc, t))).collect(); let phase_split = gs_jump.is_some_and(|t| t.is_some()) && opt.split_wave64 && opt.wave64; let ctx = Ctx { insts: &insts, starts: &starts, leaders: &leaders, loops: &loops, regions: ®ions, edges: &edges, phase_split, memo: Default::default() }; diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index af4cceb8c9..5ef0547349 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -1495,6 +1495,38 @@ fn gpu_endless_loops_in_many_regions_stop_after_four_budgets() { assert_eq!(r.sgpr[0], super::LOOP_BUDGETS_IN_ALL << 16, "four budgets of iterations in all"); } +/// Per-region loop budgets (`xcl_bown` / `xcl_btotal`) are compute-only: Compute and Kernel +/// modes emit them for multi-region loops, while Pixel and Mesh stages keep the single-budget +/// CFG (avoiding multi-PHI mesh loop headers that crash AMD LLPC). +#[test] +fn per_region_loop_budgets_are_compute_only() { + let mut list: Vec<(&str, &str, &[(&str, u64)], Option)> = Vec::new(); + for _ in 0..2 { + list.push(("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 129)], None)); + list.push(("S_CMP_LT_U32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 130)], None)); + list.push(("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFD)], None)); + } + let code = prog(&list); + + let cs = super::CsInterface { threads: [64, 1, 1], ..Default::default() }; + let ps = super::PsInterface::default(); + let ms = super::MsInterface { threads: 64, max_vertices: 64, max_primitives: 64, ..Default::default() }; + + for mode in [Mode::Kernel, Mode::Compute(cs.clone())] { + let t = translate(&code, &Options { mode, ..Default::default() }).unwrap(); + assert!(t.hlsl.contains("xcl_bown") && t.hlsl.contains("xcl_btotal"), "compute/kernel should emit per-region budgets"); + } + for mode in [Mode::Pixel(ps), Mode::Mesh(ms.clone())] { + let t = translate(&code, &Options { mode, ..Default::default() }).unwrap(); + assert!(!t.hlsl.contains("xcl_bown") && !t.hlsl.contains("xcl_btotal"), "pixel/mesh must not emit per-region budgets"); + } + + // Direct DXIL compute & mesh both translate cleanly for a multi-region loop program. + let o = crate::gpu::dxil::kernel::KernelOptions { wave64: true, split: false, mem_windows: 1, sampler_base: 0 }; + assert!(!crate::gpu::dxil::kernel::translate_compute(&code, o, &cs).unwrap().dxil.is_empty()); + assert!(!crate::gpu::dxil::kernel::translate_mesh(&code, o, &ms).unwrap().dxil.is_empty()); +} + #[test] fn gpu_divergence_through_exec() { if !gpu_ready() {