From ca66c4aeb0def58bddf299c43557e3c5cb79c0fb Mon Sep 17 00:00:00 2001 From: Foniass <107039406+Foniass@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:02:50 +0100 Subject: [PATCH] Recompiler: structured form for programs that needed the pc chain `structurable` works on the layout: every backward jump is a loop to it. Code the console compiler placed after the blocks it jumps back into, entered from before them, and loops with several heads or exits made 3 325 of the retail pack's 26 698 programs fall back to the `pc` dispatcher, about two thirds of their DXC time (every value of the dispatcher loop is loop-carried; jump threading and the loop passes work on it). `structure.rs` builds structured code for any reducible program from its dominator tree (N. Ramsey, "Beyond Relooper"): a loop head becomes `for (;;)`, a merge is reached by leaving a `do { } while (false)`, other blocks go inline, a loop's dominated exits go after it, and a jump out of several constructs passes through `xcl_br`. It is used only where `structurable` fails, after a dry run (a program it rejects is emitted as before), so every other program's HLSL is unchanged. Left on the pc chain: 21 irreducible programs and ES + GS pairs. Checks: every structured program can be walked against its control flow graph with the same random branch decisions (`XCL_RECOMP_CHECK=1`, the retail survey and the new tests do); GPU tests compare the general form with the pc chain; `XCL_RECOMP_GENERAL=1` forces the general form for every program (the GPU suite passes with it). Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/recomp/mod.rs | 23 +- crates/xcl/src/gpu/recomp/structure.rs | 779 +++++++++++++++++++++++++ crates/xcl/src/gpu/recomp/tests.rs | 234 ++++++++ 3 files changed, 1034 insertions(+), 2 deletions(-) create mode 100644 crates/xcl/src/gpu/recomp/structure.rs diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index bd2c568ba..46eb66d11 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -8,7 +8,9 @@ //! if / else, loops with the back edge at their end (also entered in the middle: rotated), //! and any other forward jump – loop breaks, jumps past a join, s_endpgm before the end – //! as a skip flag (`xcl_skip_`: set at the jump, the code up to the target runs -//! under `if (!flag)`, loops `break`); retail pack: 90% of the programs need no `pc`, +//! under `if (!flag)`, loops `break`); retail pack: 88% of the programs; the general form +//! (`structure`: dominator tree, loops, blocks left by `break`) takes all but 21 of the rest +//! (irreducible ones, and ES + GS pairs, keep the `pc` chain), //! * SGPRs, VCC, EXEC, M0 and SCC are ordinary variables that every lane computes alike //! (uniform); lane masks produced by vector instructions come from `WaveActiveBallot`, //! * VGPRs are per-lane variables; vector writes are masked by the lane's EXEC bit, @@ -59,6 +61,7 @@ pub mod x64_masks; pub mod pso; pub use emit::mesh_passthrough; pub mod runner; +mod structure; #[cfg(test)] mod tests; pub mod upper_lanes; @@ -1379,10 +1382,26 @@ pub fn translate(code: &[u8], opt: &Options) -> Result { let ctx = Ctx { insts: &insts, starts: &starts, leaders: &leaders, loops: &loops, edges: &edges, memo: Default::default() }; let mut flags = BTreeSet::new(); let mut code = String::new(); - if gs_jump.is_none() && opt.structured && std::env::var_os("XCL_RECOMP_NO_STRUCTURED").is_none() && structurable(&ctx, 0, u64::MAX).is_some() { + let structured = gs_jump.is_none() && opt.structured && std::env::var_os("XCL_RECOMP_NO_STRUCTURED").is_none(); + // `XCL_RECOMP_GENERAL=1` (tests: `structure::GENERAL_ONLY`): the general form for + // every program with branches + let general_only = std::env::var_os("XCL_RECOMP_GENERAL").is_some() || structure::general_only(); + let general = |em: &mut emit::Em, code: &mut String, blocks: &mut usize| match structure::structure(&ctx, em, blocks) { + Ok(s) => { + *code = s; + true + } + Err(e) => { + why(0, &e); + false + } + }; + if structured && !general_only && structurable(&ctx, 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) emit_structured(&ctx, &mut em, &mut code, 0, u64::MAX, None, 0, None, &BTreeSet::new(), 1, &mut blocks, &mut flags); + } else if structured && general(&mut em, &mut code, &mut blocks) { + // what `structurable` rejects in the general structured form (`structure`) } else { if gs_jump.is_some() && opt.split_wave64 && opt.wave64 { code.push_str(" uint pc = xcl_entry_pc;\n"); diff --git a/crates/xcl/src/gpu/recomp/structure.rs b/crates/xcl/src/gpu/recomp/structure.rs new file mode 100644 index 000000000..df7345464 --- /dev/null +++ b/crates/xcl/src/gpu/recomp/structure.rs @@ -0,0 +1,779 @@ +//! Structured control flow for any reducible program. `structurable` works on the layout: +//! every backward jump is a loop to it, every forward one a skip. Code the console compiler +//! placed after the blocks it jumps back into, entered from before them (acyclic, though its +//! jumps go backwards), and loops with several heads or exits it cannot place made programs +//! fall back to the `pc` dispatcher (`emit_range`). Those +//! programs were 12% of the retail pack's but about two thirds of its DXC time: every value +//! of a dispatcher loop is loop-carried, and DXC's jump threading and loop passes work on it. +//! +//! Method (N. Ramsey, "Beyond Relooper", ICFP 2022): over the dominator tree, a loop head +//! becomes `for (;;)`, a block with several forward predecessors (a merge) is reached by +//! leaving a `do { … } while (false)` that ends right before its code, any other block is +//! emitted inline at its only predecessor's branch. A loop's exits that it dominates are +//! placed after the loop. A jump that leaves several of these constructs at once sets +//! `xcl_br` to its target and each construct passes it outwards. +//! `XCL_RECOMP_GENERAL=1` uses this form for every program with branches (tests). + +use std::collections::BTreeSet; +use std::fmt::Write as _; + +use super::{block_end, emit, insts_in, term, Ctx, Term, LOOP_GUARD}; + +/// Successor of a block: another block, or the end of the program. +type Target = Option; + +#[derive(Clone, Copy, Debug)] +enum Succ { + Exit, + Jump(usize), + /// (taken, not taken) + Cond(Target, Target), +} + +/// Basic blocks of the program (the leaders of `Ctx`) and their successors. +struct Cfg { + succ: Vec, +} + +fn cfg(c: &Ctx) -> Result { + let n = c.leaders.len(); + let index = |t: u64| c.leaders.binary_search(&t).map_err(|_| format!("branch to {t:#x}: not a block")); + let mut succ = Vec::with_capacity(n); + for i in 0..n { + let (start, end) = (c.leaders[i], block_end(c, i)); + let fall: Target = if i + 1 < n && c.leaders[i + 1] == end { Some(i + 1) } else { None }; + let s = match term(c, start, end) { + Term::Next => match fall { + Some(f) => Succ::Jump(f), + None => Succ::Exit, + }, + Term::Jump(t) => Succ::Jump(index(t)?), + Term::Cond(t) => { + let t = index(t)?; + if Some(t) == fall { + Succ::Jump(t) + } else { + Succ::Cond(Some(t), fall) + } + } + Term::End => Succ::Exit, + Term::Other => return Err(format!("block {start:#x}: a terminator without a static target")), + }; + succ.push(s); + } + Ok(Cfg { succ }) +} + +impl Succ { + fn targets(self) -> Vec { + match self { + Succ::Exit => vec![], + Succ::Jump(t) => vec![t], + Succ::Cond(t, f) => t.into_iter().chain(f).collect(), + } + } +} + +/// Dominator tree, loops and merges of the reachable blocks. +struct Shape { + /// reverse postorder number (usize::MAX: unreachable) + rpo: Vec, + order: Vec, + /// dominator tree children in reverse postorder + children: Vec>, + /// loop head → its body (blocks), heads only + body: Vec>>, + /// forward edges into the block + forward_in: Vec, + /// the loop head after whose loop the block is placed (it is outside the loops of its + /// immediate dominator that it leaves; the outermost of them) + placed_after: Vec>, +} + +fn shape(g: &Cfg) -> Result { + let n = g.succ.len(); + // reverse postorder (iterative DFS from block 0) + let mut post = Vec::with_capacity(n); + let mut seen = vec![false; n]; + let mut stack: Vec<(usize, usize)> = vec![(0, 0)]; + seen[0] = true; + while let Some(&mut (b, ref mut k)) = stack.last_mut() { + let ts = g.succ[b].targets(); + if *k < ts.len() { + let t = ts[*k]; + *k += 1; + if !seen[t] { + seen[t] = true; + stack.push((t, 0)); + } + } else { + post.push(b); + stack.pop(); + } + } + let order: Vec = post.into_iter().rev().collect(); + let mut rpo = vec![usize::MAX; n]; + for (k, &b) in order.iter().enumerate() { + rpo[b] = k; + } + let mut preds: Vec> = vec![Vec::new(); n]; + for &b in &order { + for t in g.succ[b].targets() { + preds[t].push(b); + } + } + // dominators (Cooper, Harvey, Kennedy) + let mut idom = vec![usize::MAX; n]; + idom[0] = 0; + let intersect = |idom: &[usize], mut a: usize, mut b: usize| { + while a != b { + while rpo[a] > rpo[b] { + a = idom[a]; + } + while rpo[b] > rpo[a] { + b = idom[b]; + } + } + a + }; + let mut changed = true; + while changed { + changed = false; + for &b in order.iter().skip(1) { + let mut new = usize::MAX; + for &p in &preds[b] { + if idom[p] == usize::MAX { + continue; + } + new = if new == usize::MAX { p } else { intersect(&idom, p, new) }; + } + if new != idom[b] { + idom[b] = new; + changed = true; + } + } + } + let dominates = |a: usize, mut b: usize| loop { + if a == b { + return true; + } + if b == 0 { + return false; + } + b = idom[b]; + }; + // back edges (to a dominating head) and loop bodies; any other retreating edge: irreducible + let mut body: Vec>> = vec![None; n]; + let mut forward_in = vec![0usize; n]; + for &u in &order { + for v in g.succ[u].targets() { + if rpo[v] > rpo[u] { + forward_in[v] += 1; + continue; + } + if !dominates(v, u) { + return Err(format!("irreducible: block {u} → {v}")); + } + let set = body[v].get_or_insert_with(|| { + let mut s = vec![false; n]; + s[v] = true; + s + }); + let mut work = vec![u]; + while let Some(x) = work.pop() { + if !set[x] { + set[x] = true; + work.extend(preds[x].iter().copied()); + } + } + } + } + let size = |h: usize| body[h].as_ref().map_or(0, |s| s.iter().filter(|&&x| x).count()); + let mut heads: Vec = (0..n).filter(|&h| body[h].is_some()).collect(); + heads.sort_by_key(|&h| size(h)); + // innermost loop containing each block (a head: its own), the loop around each loop + let mut inner: Vec> = vec![None; n]; + for &h in &heads { + let s = body[h].as_ref().unwrap(); + for b in 0..n { + if s[b] && inner[b].is_none() { + inner[b] = Some(h); + } + } + } + let mut outer: Vec> = vec![None; n]; + for &h in &heads { + // the smallest other loop containing h + outer[h] = heads.iter().copied().find(|&o| o != h && body[o].as_ref().unwrap()[h] && size(o) > size(h)); + } + let mut children: Vec> = vec![Vec::new(); n]; + for &b in order.iter().skip(1) { + children[idom[b]].push(b); + } + // a block outside loops its immediate dominator is in: after the outermost of them + let mut placed_after = vec![None; n]; + for &w in order.iter().skip(1) { + let mut l = inner[idom[w]]; + let mut last = None; + while let Some(h) = l { + if body[h].as_ref().unwrap()[w] { + break; + } + last = Some(h); + l = outer[h]; + } + placed_after[w] = last; + } + Ok(Shape { rpo, order, children, body, forward_in, placed_after }) +} + +/// A label: the head of a loop (a jump to it continues the loop) or the block that follows +/// a `do { } while (false)` (a jump to it leaves the block). +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)] +pub(super) enum Label { + Loop(usize), + Follow(usize), + /// the end of the program (the mode's epilogue follows) + Exit, +} + +#[derive(Debug)] +pub(super) enum Ast { + /// a block's instructions (indented for `depth`) + Code { block: usize, text: String, depth: usize }, + /// the branch at the end of `block`: `then` runs when it is taken (`negated`: when not) + If { block: usize, cond: String, negated: bool, then: Vec, other: Vec }, + Loop(usize, Vec), + Block(Label, Vec), + Br(Label), +} + +/// Deepest nesting of the emitted constructs (DXC and this translator recurse along it). +const MAX_DEPTH: usize = 160; + +struct Builder<'a, 'b> { + c: &'a Ctx<'a>, + g: &'a Cfg, + s: &'a Shape, + /// None: a dry run (no code; the structure only) + em: Option<&'b mut emit::Em>, + labels: Vec