From 5ae62c52c218f2ee7ba36e18a83769b5d5ae13a9 Mon Sep 17 00:00:00 2001 From: BetterJdue <359682234+BetterJdue@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:05:56 +0100 Subject: [PATCH 1/3] Tests: generate RDNA2 programs for compile-time measurements (#1269) The synthetic compile-time benchmark of #1269 needs console programs that anyone can build, CI included, without game data. This adds the generator it will measure: deterministic RDNA2 programs, assembled with rdna2::encode, from a seed and knobs for the number of operations, divergent ifs (v_cmp, s_and_saveexec, s_cbranch_execz) and how deep they nest, uniform loops (SGPR counter, backward s_cbranch_scc1) and how deep they nest, wave32 or wave64, the VGPR and SGPR pools, and the share of LDS and memory accesses. Knobs that would give more operations than asked for (fewer than two per loop level) are refused. Nothing is timed yet; that comes next, with DXC. The tests count what each knob does in the disassembly of the program, not in the generator: the operations, how deep the ifs and loops nest, that every s_cbranch_execz lands on its EXEC restore and every loop branch on the instruction after its counter is set, the EXEC instructions of each wave size, the LDS and memory shares, the highest VGPR. Every knob combination the tests use translates completely, structured and as the guarded block chain, with as many instructions as the disassembly. Negative control: ten mutations of the generator (seed ignored, loops not nested, loop and execz branch offsets off by one, wave32 using the 64-bit EXEC instructions, if depth ignored, VGPR pool one too large, LDS share ignored, operations miscounted, the operation-count check removed) each make at least one test fail. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/tests/compile_bench/gen.rs | 189 +++++++++++++++++++++++++ crates/xcl/tests/compile_bench/main.rs | 172 ++++++++++++++++++++++ 2 files changed, 361 insertions(+) create mode 100644 crates/xcl/tests/compile_bench/gen.rs create mode 100644 crates/xcl/tests/compile_bench/main.rs diff --git a/crates/xcl/tests/compile_bench/gen.rs b/crates/xcl/tests/compile_bench/gen.rs new file mode 100644 index 000000000..5ce046e42 --- /dev/null +++ b/crates/xcl/tests/compile_bench/gen.rs @@ -0,0 +1,189 @@ +//! Generated RDNA2 programs for compile-time measurements: no game data, the same program for +//! the same knobs and seed. The code is meant to be translated and compiled, not run: register +//! values and addresses are not set up to compute anything. +//! +//! Register use: v0 is the lane id (read only), v1 the lane's byte offset for memory, v2.. the +//! `vgprs` pool. s[2:3] is the memory base, s4.. the `sgprs` pool, s[64 + 2d] the EXEC saved by +//! an `if` at depth d, s[80 + d] the counter of a loop at depth d. + +use xcl::gpu::rdna2::encode; +use xcl::gpu::recomp::Options; + +#[derive(Debug, Clone, PartialEq)] +pub struct Knobs { + pub seed: u64, + /// operations (ALU and memory instructions); the control flow comes on top + pub ops: usize, + /// how deep divergent `if`s (v_cmp → s_and_saveexec → s_cbranch_execz) nest; 0: none + pub if_depth: u32, + /// percent of operation slots that open an `if` while `if_depth` allows one + pub divergent_pct: u32, + /// uniform loops (counter in an SGPR, backward s_cbranch_scc1), each `loop_depth` deep + pub loops: u32, + pub loop_depth: u32, + /// trips of every loop, 1..=64 (an inline constant) + pub loop_trips: u32, + /// wave64 (64-bit EXEC) or wave32 program + pub wave64: bool, + /// VGPRs the operations use, 2..=254; SGPRs, 1..=16 + pub vgprs: u32, + pub sgprs: u32, + /// percent of operations that are LDS reads / writes, and global or scalar memory accesses + pub lds_pct: u32, + pub mem_pct: u32, +} + +impl Default for Knobs { + fn default() -> Self { + Knobs { seed: 1, ops: 200, if_depth: 2, divergent_pct: 10, loops: 0, loop_depth: 1, loop_trips: 4, wave64: true, vgprs: 16, sgprs: 8, lds_pct: 5, mem_pct: 10 } + } +} + +impl Knobs { + /// The recompiler options the program is meant for (kernel mode, its wave size). + pub fn options(&self) -> Options { + Options { wave64: self.wave64, ..Options::default() } + } +} + +const VCC: u64 = 106; +const EXEC: u64 = 126; +const LIT: u64 = 255; +const V: u64 = 256; + +fn inst(name: &str, enc: &str, fields: &[(&str, u64)], lit: Option) -> Vec { + encode(name, enc, fields, lit).unwrap_or_else(|e| panic!("{name}: {e}")) +} + +/// splitmix64: small, and the same sequence on every platform +struct Rng(u64); + +impl Rng { + fn next(&mut self) -> u64 { + self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = self.0; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + } + + fn below(&mut self, n: u64) -> u64 { + self.next() % n + } +} + +struct Gen<'a> { + k: &'a Knobs, + rng: Rng, +} + +impl Gen<'_> { + fn vgpr(&mut self) -> u64 { + 2 + self.rng.below(self.k.vgprs as u64) + } + + fn sgpr(&mut self) -> u64 { + 4 + self.rng.below(self.k.sgprs as u64) + } + + fn op(&mut self) -> Vec { + let r = self.rng.below(100) as u32; + if r < self.k.mem_pct { + return match self.rng.below(3) { + 0 => inst("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", self.vgpr()), ("ADDR", 1), ("SADDR", 2), ("OFFSET", 4 * self.rng.below(256))], None), + 1 => inst("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 1), ("DATA", self.vgpr()), ("SADDR", 2), ("OFFSET", 4 * self.rng.below(256))], None), + _ => inst("S_LOAD_DWORD", "ENC_SMEM", &[("SDATA", self.sgpr()), ("SBASE", 1), ("OFFSET", 4 * self.rng.below(256))], None), + }; + } + if r < self.k.mem_pct + self.k.lds_pct { + return if self.rng.below(2) == 0 { + inst("DS_WRITE_B32", "ENC_DS", &[("ADDR", 1), ("DATA0", self.vgpr())], None) + } else { + inst("DS_READ_B32", "ENC_DS", &[("VDST", self.vgpr()), ("ADDR", 1)], None) + }; + } + // the rest: about one scalar operation for three vector ones, as in console programs + if self.rng.below(4) == 0 { + let name = ["S_ADD_U32", "S_XOR_B32", "S_MUL_I32"][self.rng.below(3) as usize]; + return inst(name, "ENC_SOP2", &[("SDST", self.sgpr()), ("SSRC0", self.sgpr()), ("SSRC1", self.sgpr())], None); + } + let (d, a, b, c) = (self.vgpr(), self.vgpr(), self.vgpr(), self.vgpr()); + match self.rng.below(6) { + 0 => inst("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", d), ("SRC0", V + a), ("VSRC1", b)], None), + 1 => inst("V_XOR_B32", "ENC_VOP2", &[("VDST", d), ("SRC0", self.sgpr()), ("VSRC1", b)], None), + 2 => inst("V_MUL_F32", "ENC_VOP2", &[("VDST", d), ("SRC0", LIT), ("VSRC1", b)], Some(0x3F80_0000 + (self.rng.below(1 << 16) as u32))), + 3 => inst("V_FMAC_F32", "ENC_VOP2", &[("VDST", d), ("SRC0", V + a), ("VSRC1", b)], None), + 4 => inst("V_MUL_LO_U32", "ENC_VOP3", &[("VDST", d), ("SRC0", V + a), ("SRC1", V + b)], None), + _ => inst("V_FMA_F32", "ENC_VOP3", &[("VDST", d), ("SRC0", V + a), ("SRC1", V + b), ("SRC2", V + c)], None), + } + } + + /// `n` operations, some of them inside divergent `if`s from depth `depth` on. + fn seq(&mut self, mut n: usize, depth: u32) -> Vec { + let mut v = Vec::new(); + while n > 0 { + if depth < self.k.if_depth && (self.rng.below(100) as u32) < self.k.divergent_pct { + let inner = n.min(4 + self.rng.below(12) as usize); + v.extend(self.divergent_if(inner, depth)); + n -= inner; + } else { + v.extend(self.op()); + n -= 1; + } + } + v + } + + fn divergent_if(&mut self, n: usize, depth: u32) -> Vec { + let save = 64 + 2 * depth as u64; + let (and_saveexec, or) = if self.k.wave64 { ("S_AND_SAVEEXEC_B64", "S_OR_B64") } else { ("S_AND_SAVEEXEC_B32", "S_OR_B32") }; + let body = self.seq(n, depth + 1); + let mut v = inst("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", LIT), ("VSRC1", self.vgpr())], Some(self.rng.next() as u32)); + v.extend(inst(and_saveexec, "ENC_SOP1", &[("SDST", save), ("SSRC0", VCC)], None)); + v.extend(inst("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", (body.len() / 4) as u64)], None)); + v.extend(body); + v.extend(inst(or, "ENC_SOP2", &[("SDST", EXEC), ("SSRC0", EXEC), ("SSRC1", save)], None)); + v + } + + /// A loop `levels` deep: each level runs `per_level` operations, then the next level. + fn nested_loop(&mut self, levels: u32, per_level: usize, depth: u32) -> Vec { + let counter = 80 + depth as u64; + let mut v = inst("S_MOV_B32", "ENC_SOP1", &[("SDST", counter), ("SSRC0", 128 + self.k.loop_trips as u64)], None); + let head = v.len(); + v.extend(self.seq(per_level, 0)); + if levels > 1 { + v.extend(self.nested_loop(levels - 1, per_level, depth + 1)); + } + v.extend(inst("S_SUB_U32", "ENC_SOP2", &[("SDST", counter), ("SSRC0", counter), ("SSRC1", 129)], None)); + v.extend(inst("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", counter), ("SSRC1", 128)], None)); + // the offset counts dwords from the instruction after the branch + let back = -(((v.len() - head) / 4 + 1) as i64); + v.extend(inst("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", back as i16 as u16 as u64)], None)); + v + } +} + +/// The program for `k`, ending in s_endpgm. Half of the operations go into the loops when +/// there are any, spread evenly over their levels; the rest runs before, between and after them. +pub fn program(k: &Knobs) -> Vec { + assert!((2..=254).contains(&k.vgprs) && (1..=16).contains(&k.sgprs), "{k:?}"); + assert!((1..=64).contains(&k.loop_trips) && k.loop_depth >= 1 && k.if_depth <= 8 && k.loop_depth <= 8, "{k:?}"); + assert!(k.lds_pct + k.mem_pct <= 100 && k.divergent_pct <= 100, "{k:?}"); + let mut g = Gen { k, rng: Rng(k.seed) }; + let mut v = inst("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 130), ("VSRC1", 0)], None); // v1 = lane * 4 + let (loops, levels) = (k.loops as usize, k.loop_depth as usize); + // every loop level runs at least one operation, so the program would get more than `ops` + assert!(k.ops / 2 >= loops * levels, "too few operations: ops {} for {loops} loops × {levels} levels needs ops ≥ {}", k.ops, 2 * loops * levels); + let per_level = (k.ops / 2).checked_div(loops * levels).unwrap_or(0); + let outside = k.ops.saturating_sub(per_level * levels * loops); + for i in 0..=loops { + // the operations outside the loops, split into loops + 1 runs + v.extend(g.seq(outside * (i + 1) / (loops + 1) - outside * i / (loops + 1), 0)); + if i < loops { + v.extend(g.nested_loop(k.loop_depth, per_level, 0)); + } + } + v.extend(inst("S_ENDPGM", "ENC_SOPP", &[], None)); + v +} diff --git a/crates/xcl/tests/compile_bench/main.rs b/crates/xcl/tests/compile_bench/main.rs new file mode 100644 index 000000000..3e21c5107 --- /dev/null +++ b/crates/xcl/tests/compile_bench/main.rs @@ -0,0 +1,172 @@ +//! Compile-time benchmark on generated RDNA2 programs (issue #1269): no game data, so it can +//! run anywhere, CI included. This part checks the generator: what each knob does is counted +//! in the disassembly of the program, and every program the knobs allow translates completely. + +mod gen; + +use gen::{program, Knobs}; +use xcl::gpu::rdna2::{disassemble, Line}; +use xcl::gpu::recomp::{translate, Options}; + +fn mnemonic(l: &Line) -> &str { + l.text.split_whitespace().next().unwrap_or("") +} + +fn lines(code: &[u8]) -> Vec { + let ls = disassemble(code, 0, true); + assert!(ls.iter().all(|l| l.ok), "undecoded: {:?}", ls.iter().find(|l| !l.ok).map(|l| &l.text)); + assert_eq!(ls.iter().map(|l| l.bytes.len()).sum::(), code.len(), "the disassembly ends before the code"); + ls +} + +/// Target of a SOPP branch: SIMM16 dwords from the next instruction. +fn target(l: &Line) -> u64 { + let simm = u16::from_le_bytes([l.bytes[0], l.bytes[1]]) as i16 as i64; + (l.pc as i64 + 4 + 4 * simm) as u64 +} + +/// Instructions that the control flow and the prologue add (the rest are the operations). +const CONTROL: &[&str] = &[ + "v_lshlrev_b32", "v_cmp_gt_u32", "s_and_saveexec_b64", "s_and_saveexec_b32", "s_cbranch_execz", "s_or_b64", "s_or_b32", + "s_mov_b32", "s_sub_u32", "s_cmp_lg_u32", "s_cbranch_scc1", "s_endpgm", +]; + +#[derive(Debug, Default)] +struct Shape { + ops: usize, + ifs: usize, + if_depth: u32, + loops: usize, + loop_depth: u32, + lds: usize, + mem: usize, + max_vgpr: u32, +} + +fn shape(code: &[u8]) -> Shape { + let ls = lines(code); + let at = |pc: u64| ls.iter().position(|l| l.pc == pc).unwrap_or_else(|| panic!("no instruction at {pc:#x}")); + let mut s = Shape::default(); + let mut depth = 0u32; + let mut loops = Vec::new(); + for (i, l) in ls.iter().enumerate() { + let m = mnemonic(l); + match m { + "s_and_saveexec_b64" | "s_and_saveexec_b32" => { + s.ifs += 1; + depth += 1; + s.if_depth = s.if_depth.max(depth); + } + "s_or_b64" | "s_or_b32" => depth -= 1, + // an if's skip lands on its EXEC restore + "s_cbranch_execz" => assert!(mnemonic(&ls[at(target(l))]).starts_with("s_or_b"), "execz at {:#x}", l.pc), + // a loop's branch goes back to the instruction after its counter is set + "s_cbranch_scc1" => { + let head = at(target(l)); + assert!(head < i && mnemonic(&ls[head - 1]) == "s_mov_b32", "scc1 at {:#x}", l.pc); + loops.push((ls[head].pc, l.pc)); + } + _ => {} + } + if !CONTROL.contains(&m) { + s.ops += 1; + s.lds += m.starts_with("ds_") as usize; + s.mem += (m.starts_with("global_") || m.starts_with("s_load")) as usize; + } + for tok in l.text.split(|c: char| !c.is_ascii_alphanumeric()) { + if let Some(n) = tok.strip_prefix('v').and_then(|n| n.parse::().ok()) { + s.max_vgpr = s.max_vgpr.max(n); + } + } + } + assert_eq!(depth, 0, "every if restores EXEC"); + s.loops = loops.len(); + s.loop_depth = loops.iter().map(|&(h, b)| loops.iter().filter(|&&(h2, b2)| h2 <= h && b <= b2).count() as u32).max().unwrap_or(0); + s +} + +#[test] +fn same_knobs_and_seed_give_the_same_program() { + let k = Knobs { ops: 500, loops: 2, loop_depth: 2, ..Knobs::default() }; + assert_eq!(program(&k), program(&k)); + assert_ne!(program(&k), program(&Knobs { seed: 2, ..k })); +} + +#[test] +fn operations_and_control_flow_follow_the_knobs() { + for (ops, if_depth, loops, loop_depth) in [(200, 0, 0, 1), (400, 1, 1, 1), (600, 3, 2, 2), (2000, 8, 3, 4), (120, 2, 5, 3), (12, 0, 2, 3)] { + let k = Knobs { ops, if_depth, loops, loop_depth, divergent_pct: 30, ..Knobs::default() }; + let s = shape(&program(&k)); + assert_eq!(s.ops, ops, "{k:?}"); + assert!(s.if_depth <= if_depth && (if_depth == 0) == (s.ifs == 0), "{k:?}: {s:?}"); + assert_eq!((s.loops, s.loop_depth), ((loops * loop_depth) as usize, if loops > 0 { loop_depth } else { 0 }), "{k:?}"); + } + // always divergent: the ifs nest as deep as allowed + for if_depth in [1, 4, 8] { + let s = shape(&program(&Knobs { ops: 1000, if_depth, divergent_pct: 100, ..Knobs::default() })); + assert_eq!(s.if_depth, if_depth); + } + let none = shape(&program(&Knobs { ops: 1000, divergent_pct: 0, ..Knobs::default() })); + assert_eq!(none.ifs, 0); +} + +#[test] +#[should_panic(expected = "too few operations")] +fn knobs_with_fewer_operations_than_loop_levels_are_refused() { + // 2 × 3 levels need 12 operations: the program would get more than the 10 asked for + program(&Knobs { ops: 10, loops: 2, loop_depth: 3, ..Knobs::default() }); +} + +#[test] +fn wave_size_picks_the_exec_instructions() { + for wave64 in [true, false] { + let code = program(&Knobs { ops: 500, if_depth: 3, divergent_pct: 50, wave64, ..Knobs::default() }); + let ms: Vec = lines(&code).iter().map(|l| mnemonic(l).to_string()).collect(); + let (want, other) = if wave64 { ("_b64", "_b32") } else { ("_b32", "_b64") }; + assert!(ms.iter().any(|m| *m == format!("s_and_saveexec{want}"))); + assert!(!ms.iter().any(|m| *m == format!("s_and_saveexec{other}") || *m == format!("s_or{other}")), "wave64 {wave64}"); + } +} + +#[test] +fn lds_and_memory_shares_follow_the_knobs() { + let at = |lds_pct, mem_pct| shape(&program(&Knobs { ops: 2000, lds_pct, mem_pct, ..Knobs::default() })); + let s = at(0, 0); + assert_eq!((s.lds, s.mem), (0, 0)); + let s = at(100, 0); + assert_eq!((s.lds, s.mem), (2000, 0)); + let s = at(0, 100); + assert_eq!((s.lds, s.mem), (0, 2000)); + // 10 % and 30 % of 2000 operations, give or take what the seed draws + let s = at(10, 30); + assert!((150..250).contains(&s.lds) && (500..700).contains(&s.mem), "{s:?}"); +} + +#[test] +fn vgprs_stay_in_the_pool() { + for vgprs in [2, 16, 200] { + let s = shape(&program(&Knobs { ops: 3000, vgprs, ..Knobs::default() })); + // v0 and v1 are the lane id and offset; the pool is v2..v(vgprs + 1) + assert_eq!(s.max_vgpr, vgprs + 1, "vgprs {vgprs}"); + } +} + +#[test] +fn every_program_translates_completely() { + let mut n = 0; + for wave64 in [true, false] { + for (if_depth, loops, loop_depth) in [(0, 0, 1), (2, 1, 1), (4, 2, 3), (8, 4, 2)] { + for (lds_pct, mem_pct) in [(0, 0), (5, 10), (20, 40)] { + let k = Knobs { seed: n, ops: 300, if_depth, divergent_pct: 25, loops, loop_depth, wave64, lds_pct, mem_pct, ..Knobs::default() }; + let code = program(&k); + let insts = lines(&code).len(); + for structured in [true, false] { + let t = translate(&code, &Options { structured, ..k.options() }).unwrap_or_else(|e| panic!("{k:?}: {e}")); + assert!(t.complete(), "{k:?}: {:?}", t.unsupported_why); + assert_eq!(t.instructions, insts, "{k:?}"); + } + n += 1; + } + } + } +} From 0f257d19e5b3950ebf00b61090ab78d25fc45ea4 Mon Sep 17 00:00:00 2001 From: anes66 <37009523+anes66@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:26:37 +0100 Subject: [PATCH 2/3] Tests: reject overflowing benchmark loop branches Large synthetic loop bodies can exceed the signed SOPP displacement. The narrowing cast silently wraps the back edge and produces a different program. Check the displacement before encoding it; cover rejection and a large representable loop. --- crates/xcl/tests/compile_bench/gen.rs | 3 ++- crates/xcl/tests/compile_bench/main.rs | 12 ++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/crates/xcl/tests/compile_bench/gen.rs b/crates/xcl/tests/compile_bench/gen.rs index 5ce046e42..326403320 100644 --- a/crates/xcl/tests/compile_bench/gen.rs +++ b/crates/xcl/tests/compile_bench/gen.rs @@ -159,7 +159,8 @@ impl Gen<'_> { v.extend(inst("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", counter), ("SSRC1", 128)], None)); // the offset counts dwords from the instruction after the branch let back = -(((v.len() - head) / 4 + 1) as i64); - v.extend(inst("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", back as i16 as u16 as u64)], None)); + let back = i16::try_from(back).expect("loop body exceeds SOPP branch range"); + v.extend(inst("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", back as u16 as u64)], None)); v } } diff --git a/crates/xcl/tests/compile_bench/main.rs b/crates/xcl/tests/compile_bench/main.rs index 3e21c5107..7cb4b59dc 100644 --- a/crates/xcl/tests/compile_bench/main.rs +++ b/crates/xcl/tests/compile_bench/main.rs @@ -128,6 +128,18 @@ fn wave_size_picks_the_exec_instructions() { } } +#[test] +#[should_panic(expected = "loop body exceeds SOPP branch range")] +fn oversized_loop_branches_are_refused() { + program(&Knobs { ops: 100_000, loops: 1, if_depth: 0, lds_pct: 0, mem_pct: 0, ..Knobs::default() }); +} + +#[test] +fn large_representable_loop_still_targets_its_body() { + let s = shape(&program(&Knobs { ops: 10_000, loops: 1, if_depth: 0, lds_pct: 0, mem_pct: 0, ..Knobs::default() })); + assert_eq!((s.ops, s.loops, s.loop_depth), (10_000, 1, 1)); +} + #[test] fn lds_and_memory_shares_follow_the_knobs() { let at = |lds_pct, mem_pct| shape(&program(&Knobs { ops: 2000, lds_pct, mem_pct, ..Knobs::default() })); From cc131b2f121cba9c15c2fc036270eef33dcf6304 Mon Sep 17 00:00:00 2001 From: BetterJdue <359682234+BetterJdue@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:24:56 +0100 Subject: [PATCH 3/3] Tests: time DXC on generated RDNA2 programs and write JSON / CSV (#1269) The compile-time benchmark of #1269 measures what DXC does with the recompiler's HLSL without game data. Each generated program is translated and compiled with DXC one at a time; its instructions, blocks, code, HLSL and DXIL bytes, translation time and DXC times go into compile_bench.json (with the commit, whether the tree was dirty, the DXC toolchain, the build profile and the CPU) and compile_bench.csv. Every test run compiles a small set of six programs, so CI goes through the same code; XCL_COMPILE_BENCH=full runs five shapes at four sizes up to 20 000 operations, each in the native form and in the split wave64 / 4-window form, plus controls whose effect is known (the guarded block chain, 1 against 4 memory windows). XCL_COMPILE_BENCH_OUT, _REPS and _DXC_ARGS set the output folder, the compiles per program and extra DXC arguments; without the latter dxc.rs picks the optimisation level from the source size, as it does for a title. Without DXC the test calls skip_test("no DXC"). A program that does not translate completely, that DXC refuses, or whose HLSL or DXIL differs between repeats fails the test; the times are recorded, not judged. The generator gets buffer (V#) and image (T#, S#) access knobs and a compute mode (64 threads, 4 user SGPRs). At zero they draw nothing, so the programs of the first version stay byte for byte the same, which a test checks against hashes computed with the generator of 5ae62c5. Negative control: six mutations (buffer or image share ignored, compute ignored, the draws changed, the CSV time separator, the knobs not flattened into the row) each make at least one test fail. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/tests/compile_bench/gen.rs | 43 ++++- crates/xcl/tests/compile_bench/main.rs | 116 +++++++++++++- crates/xcl/tests/compile_bench/measure.rs | 187 ++++++++++++++++++++++ 3 files changed, 334 insertions(+), 12 deletions(-) create mode 100644 crates/xcl/tests/compile_bench/measure.rs diff --git a/crates/xcl/tests/compile_bench/gen.rs b/crates/xcl/tests/compile_bench/gen.rs index 326403320..5a2dbdeb5 100644 --- a/crates/xcl/tests/compile_bench/gen.rs +++ b/crates/xcl/tests/compile_bench/gen.rs @@ -3,13 +3,14 @@ //! values and addresses are not set up to compute anything. //! //! Register use: v0 is the lane id (read only), v1 the lane's byte offset for memory, v2.. the -//! `vgprs` pool. s[2:3] is the memory base, s4.. the `sgprs` pool, s[64 + 2d] the EXEC saved by -//! an `if` at depth d, s[80 + d] the counter of a loop at depth d. +//! `vgprs` pool. s[2:3] is the memory base, s4.. the `sgprs` pool, s[32:35] the buffer's V#, +//! s[40:47] the image's T#, s[48:51] its S#, s[64 + 2d] the EXEC saved by an `if` at depth d, +//! s[80 + d] the counter of a loop at depth d. use xcl::gpu::rdna2::encode; -use xcl::gpu::recomp::Options; +use xcl::gpu::recomp::{CsInterface, Mode, Options}; -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, serde::Serialize)] pub struct Knobs { pub seed: u64, /// operations (ALU and memory instructions); the control flow comes on top @@ -31,18 +32,31 @@ pub struct Knobs { /// percent of operations that are LDS reads / writes, and global or scalar memory accesses pub lds_pct: u32, pub mem_pct: u32, + /// percent of operations that are buffer loads / stores (V#), and image loads / samples (T#) + pub buffer_pct: u32, + pub image_pct: u32, + /// translate as a compute shader (64 threads, 4 user SGPRs) instead of a kernel + pub compute: bool, } impl Default for Knobs { fn default() -> Self { - Knobs { seed: 1, ops: 200, if_depth: 2, divergent_pct: 10, loops: 0, loop_depth: 1, loop_trips: 4, wave64: true, vgprs: 16, sgprs: 8, lds_pct: 5, mem_pct: 10 } + Knobs { + seed: 1, ops: 200, if_depth: 2, divergent_pct: 10, loops: 0, loop_depth: 1, loop_trips: 4, wave64: true, vgprs: 16, sgprs: 8, + lds_pct: 5, mem_pct: 10, buffer_pct: 0, image_pct: 0, compute: false, + } } } impl Knobs { - /// The recompiler options the program is meant for (kernel mode, its wave size). + /// The recompiler options the program is meant for: kernel or compute mode, its wave size. pub fn options(&self) -> Options { - Options { wave64: self.wave64, ..Options::default() } + let mode = if self.compute { + Mode::Compute(CsInterface { threads: [64, 1, 1], user_sgprs: 4, tid_components: 1, ..CsInterface::default() }) + } else { + Mode::Kernel + }; + Options { mode, wave64: self.wave64, ..Options::default() } } } @@ -102,6 +116,19 @@ impl Gen<'_> { inst("DS_READ_B32", "ENC_DS", &[("VDST", self.vgpr()), ("ADDR", 1)], None) }; } + let resources = self.k.mem_pct + self.k.lds_pct + self.k.buffer_pct; + if r < resources { + let name = if self.rng.below(2) == 0 { "BUFFER_LOAD_DWORD" } else { "BUFFER_STORE_DWORD" }; + return inst(name, "ENC_MUBUF", &[("VDATA", self.vgpr()), ("VADDR", 1), ("SRSRC", 8), ("SOFFSET", 128), ("OFFSET", 4 * self.rng.below(256)), ("OFFEN", 1)], None); + } + if r < resources + self.k.image_pct { + // 2D at (v0, v1), one channel + return if self.rng.below(2) == 0 { + inst("IMAGE_LOAD", "ENC_MIMG", &[("VDATA", self.vgpr()), ("VADDR", 0), ("SRSRC", 10), ("DMASK", 1), ("DIM", 1), ("UNORM", 1)], None) + } else { + inst("IMAGE_SAMPLE_LZ", "ENC_MIMG", &[("VDATA", self.vgpr()), ("VADDR", 0), ("SRSRC", 10), ("SSAMP", 12), ("DMASK", 1), ("DIM", 1)], None) + }; + } // the rest: about one scalar operation for three vector ones, as in console programs if self.rng.below(4) == 0 { let name = ["S_ADD_U32", "S_XOR_B32", "S_MUL_I32"][self.rng.below(3) as usize]; @@ -170,7 +197,7 @@ impl Gen<'_> { pub fn program(k: &Knobs) -> Vec { assert!((2..=254).contains(&k.vgprs) && (1..=16).contains(&k.sgprs), "{k:?}"); assert!((1..=64).contains(&k.loop_trips) && k.loop_depth >= 1 && k.if_depth <= 8 && k.loop_depth <= 8, "{k:?}"); - assert!(k.lds_pct + k.mem_pct <= 100 && k.divergent_pct <= 100, "{k:?}"); + assert!(k.lds_pct + k.mem_pct + k.buffer_pct + k.image_pct <= 100 && k.divergent_pct <= 100, "{k:?}"); let mut g = Gen { k, rng: Rng(k.seed) }; let mut v = inst("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 130), ("VSRC1", 0)], None); // v1 = lane * 4 let (loops, levels) = (k.loops as usize, k.loop_depth as usize); diff --git a/crates/xcl/tests/compile_bench/main.rs b/crates/xcl/tests/compile_bench/main.rs index 7cb4b59dc..2d9b18734 100644 --- a/crates/xcl/tests/compile_bench/main.rs +++ b/crates/xcl/tests/compile_bench/main.rs @@ -1,12 +1,15 @@ //! Compile-time benchmark on generated RDNA2 programs (issue #1269): no game data, so it can -//! run anywhere, CI included. This part checks the generator: what each knob does is counted +//! run anywhere, CI included. The generator is checked first: what each knob does is counted //! in the disassembly of the program, and every program the knobs allow translates completely. +//! Then the programs are compiled with DXC and measured (`measure.rs`: what to set for the full +//! set and for the JSON / CSV output). mod gen; +mod measure; use gen::{program, Knobs}; use xcl::gpu::rdna2::{disassemble, Line}; -use xcl::gpu::recomp::{translate, Options}; +use xcl::gpu::recomp::{dxc, runner, translate, Options}; fn mnemonic(l: &Line) -> &str { l.text.split_whitespace().next().unwrap_or("") @@ -40,6 +43,8 @@ struct Shape { loop_depth: u32, lds: usize, mem: usize, + buffer: usize, + image: usize, max_vgpr: u32, } @@ -72,6 +77,8 @@ fn shape(code: &[u8]) -> Shape { s.ops += 1; s.lds += m.starts_with("ds_") as usize; s.mem += (m.starts_with("global_") || m.starts_with("s_load")) as usize; + s.buffer += m.starts_with("buffer_") as usize; + s.image += m.starts_with("image_") as usize; } for tok in l.text.split(|c: char| !c.is_ascii_alphanumeric()) { if let Some(n) = tok.strip_prefix('v').and_then(|n| n.parse::().ok()) { @@ -152,6 +159,34 @@ fn lds_and_memory_shares_follow_the_knobs() { // 10 % and 30 % of 2000 operations, give or take what the seed draws let s = at(10, 30); assert!((150..250).contains(&s.lds) && (500..700).contains(&s.mem), "{s:?}"); + assert_eq!((s.buffer, s.image), (0, 0)); + let res = |buffer_pct, image_pct| shape(&program(&Knobs { ops: 2000, lds_pct: 0, mem_pct: 0, buffer_pct, image_pct, ..Knobs::default() })); + let s = res(100, 0); + assert_eq!((s.buffer, s.image, s.lds, s.mem), (2000, 0, 0, 0)); + let s = res(0, 100); + assert_eq!((s.buffer, s.image, s.lds, s.mem), (0, 2000, 0, 0)); + let s = res(10, 5); + assert!((150..250).contains(&s.buffer) && (50..150).contains(&s.image), "{s:?}"); +} + +#[test] +fn compute_knob_translates_as_a_compute_shader() { + use xcl::gpu::recomp::Mode; + let k = Knobs { compute: true, ..Knobs::default() }; + assert!(matches!(&k.options().mode, Mode::Compute(cs) if cs.threads == [64, 1, 1] && cs.user_sgprs == 4), "{:?}", k.options().mode); + assert_eq!(Knobs::default().options().mode, Mode::Kernel); + // the same code translates differently in the two modes + let code = program(&k); + assert_ne!(translate(&code, &k.options()).unwrap().hlsl, translate(&code, &Knobs::default().options()).unwrap().hlsl); +} + +#[test] +fn buffer_and_image_knobs_at_zero_keep_the_programs_of_the_first_version() { + // FNV-1a of the programs the generator gave before it had buffer and image accesses, so the + // benchmark's programs stay comparable across commits + let fnv = |b: &[u8]| b.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, &x| (h ^ x as u64).wrapping_mul(0x100_0000_01b3)); + let ks = [Knobs::default(), Knobs { ops: 2000, if_depth: 6, divergent_pct: 40, loops: 3, loop_depth: 2, wave64: false, seed: 7, ..Knobs::default() }]; + assert_eq!(ks.map(|k| fnv(&program(&k))), [GOLDEN_DEFAULT, GOLDEN_MIXED]); } #[test] @@ -168,8 +203,8 @@ fn every_program_translates_completely() { let mut n = 0; for wave64 in [true, false] { for (if_depth, loops, loop_depth) in [(0, 0, 1), (2, 1, 1), (4, 2, 3), (8, 4, 2)] { - for (lds_pct, mem_pct) in [(0, 0), (5, 10), (20, 40)] { - let k = Knobs { seed: n, ops: 300, if_depth, divergent_pct: 25, loops, loop_depth, wave64, lds_pct, mem_pct, ..Knobs::default() }; + for (lds_pct, mem_pct, buffer_pct, image_pct, compute) in [(0, 0, 0, 0, false), (5, 10, 0, 0, false), (20, 40, 0, 0, false), (5, 10, 10, 5, false), (5, 10, 10, 5, true), (0, 0, 0, 0, true)] { + let k = Knobs { seed: n, ops: 300, if_depth, divergent_pct: 25, loops, loop_depth, wave64, lds_pct, mem_pct, buffer_pct, image_pct, compute, ..Knobs::default() }; let code = program(&k); let insts = lines(&code).len(); for structured in [true, false] { @@ -182,3 +217,76 @@ fn every_program_translates_completely() { } } } + +/// `buffer_and_image_knobs_at_zero_keep_the_programs_of_the_first_version`: computed with the +/// generator of 5ae62c5 (1 536 and 32 688 bytes) +const GOLDEN_DEFAULT: u64 = 0x2365_3488_bf15_5939; +const GOLDEN_MIXED: u64 = 0xa184_a8b7_f231_29f2; + +#[test] +fn dxc_compiles_the_generated_programs() { + if let Err(e) = dxc::location() { + println!("DXC unavailable – skipping ({e})"); + runner::skip_test("no DXC"); + return; + } + let set = std::env::var("XCL_COMPILE_BENCH").unwrap_or_default(); + let (cases, default_reps) = match set.as_str() { + "" => (measure::small(), 1), + "full" => (measure::full(), 3), + x => panic!("XCL_COMPILE_BENCH={x}: only `full` (or unset for the small set)"), + }; + let reps = std::env::var("XCL_COMPILE_BENCH_REPS").map(|r| r.parse().expect("XCL_COMPILE_BENCH_REPS")).unwrap_or(default_reps); + let args_var = std::env::var("XCL_COMPILE_BENCH_DXC_ARGS").unwrap_or_default(); + let args: Vec<&str> = args_var.split_whitespace().collect(); + let mut rows: Vec = cases.iter().map(|c| measure::measure(c, reps, &args)).collect(); + rows.sort_by(|a, b| a.name.cmp(&b.name)); + assert_eq!(rows.len(), cases.len()); + for r in &rows { + println!( + "{:<32} {:>6} insts {:>9} B HLSL {:>8} B DXIL DXC {:>9.1} ms (min {:.1})", + r.name, r.instructions, r.hlsl_bytes, r.dxil_bytes, r.dxc_ms_median, r.dxc_ms_min + ); + } + if let Ok(dir) = std::env::var("XCL_COMPILE_BENCH_OUT") { + let set = if set.is_empty() { "small" } else { "full" }; + measure::write(std::path::Path::new(&dir), &measure::environment(set, reps), &rows); + println!("written: {dir}\\compile_bench.json, compile_bench.csv"); + } +} + +#[test] +fn results_are_written_as_json_and_csv() { + let row = measure::Row { + name: "x".into(), + knobs: Knobs::default(), + split_wave64: true, + mem_windows: 4, + structured: true, + instructions: 10, + blocks: 2, + code_bytes: 40, + hlsl_bytes: 1000, + translate_ms: 0.5, + dxc_args: "-O1".into(), + dxc_ms: vec![2.0, 1.0, 3.0], + dxc_ms_median: 2.0, + dxc_ms_min: 1.0, + dxil_bytes: 300, + }; + let dir = std::env::temp_dir().join(format!("xcl_compile_bench_{}", std::process::id())); + measure::write(&dir, &serde_json::json!({ "set": "small" }), &[row.clone(), measure::Row { name: "y".into(), ..row }]); + let json: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(dir.join("compile_bench.json")).unwrap()).unwrap(); + assert_eq!(json["environment"]["set"], "small"); + assert_eq!(json["programs"][1]["name"], "y"); + assert_eq!((json["programs"][0]["ops"].as_u64(), json["programs"][0]["dxil_bytes"].as_u64()), (Some(200), Some(300)), "knobs are flattened into the row"); + let csv = std::fs::read_to_string(dir.join("compile_bench.csv")).unwrap(); + let lines: Vec<&str> = csv.lines().collect(); + assert_eq!(lines.len(), 3, "{csv}"); + let header: Vec<&str> = lines[0].split(',').collect(); + let first: Vec<&str> = lines[1].split(',').collect(); + assert_eq!(header.len(), first.len(), "{csv}"); + let col = |n: &str| first[header.iter().position(|h| *h == n).unwrap_or_else(|| panic!("no column {n}: {csv}"))]; + assert_eq!((col("name"), col("dxc_ms"), col("dxil_bytes"), col("wave64")), ("x", "2.0;1.0;3.0", "300", "true")); + std::fs::remove_dir_all(&dir).unwrap(); +} diff --git a/crates/xcl/tests/compile_bench/measure.rs b/crates/xcl/tests/compile_bench/measure.rs new file mode 100644 index 000000000..301503d5d --- /dev/null +++ b/crates/xcl/tests/compile_bench/measure.rs @@ -0,0 +1,187 @@ +//! The measurement: each generated program is translated to HLSL and compiled with DXC, one +//! compile at a time, and its sizes and times are written as JSON and CSV. +//! +//! - `XCL_COMPILE_BENCH=full`: the full set (sizes up to 20 000 operations); unset: a small set +//! that runs in seconds, so CI and every test run go through the same code +//! - `XCL_COMPILE_BENCH_OUT=`: write `compile_bench.json` and `compile_bench.csv` there +//! - `XCL_COMPILE_BENCH_REPS=`: compiles per program (default 1, full set 3) +//! - `XCL_COMPILE_BENCH_DXC_ARGS="-O1 …"`: extra DXC arguments; unset, `dxc.rs` picks the +//! optimisation level from the source size, as it does for a title +//! +//! Times are wall-clock and only comparable on one machine; run the full set with nothing else +//! running (`--test-threads=1`). + +use std::time::Instant; + +use serde::Serialize; +use xcl::gpu::recomp::{dxc, translate, Options}; + +use crate::gen::{program, Knobs}; + +#[derive(Debug, Clone, Serialize)] +pub struct Row { + pub name: String, + #[serde(flatten)] + pub knobs: Knobs, + pub split_wave64: bool, + pub mem_windows: u32, + pub structured: bool, + pub instructions: usize, + pub blocks: usize, + pub code_bytes: usize, + pub hlsl_bytes: usize, + pub translate_ms: f64, + pub dxc_args: String, + pub dxc_ms: Vec, + pub dxc_ms_median: f64, + pub dxc_ms_min: f64, + pub dxil_bytes: usize, +} + +/// A program of the set: its name, knobs and the recompiler options it is translated with. +pub struct Case { + pub name: String, + pub knobs: Knobs, + pub options: Options, +} + +fn case(name: &str, knobs: Knobs, split: bool, windows: u32, structured: bool) -> Case { + let options = Options { split_wave64: split, mem_windows: windows, structured, ..knobs.options() }; + Case { name: name.to_string(), knobs, options } +} + +/// The small set: one program per kind of control flow, wave size and form, a few hundred +/// operations each. +pub fn small() -> Vec { + let k = |ops| Knobs { ops, ..Knobs::default() }; + vec![ + case("w64", k(300), false, 1, true), + case("w32", Knobs { wave64: false, ..k(300) }, false, 1, true), + case("w64-split-4win", k(300), true, 4, true), + case("loops", Knobs { loops: 2, loop_depth: 2, ..k(300) }, false, 1, true), + case("divergent", Knobs { if_depth: 4, divergent_pct: 40, ..k(300) }, false, 1, true), + case("cs-resources", Knobs { compute: true, buffer_pct: 10, image_pct: 5, ..k(300) }, false, 1, true), + ] +} + +/// The full set: five shapes at four sizes, each in the form a 64-lane GPU gets and the one a +/// 32-lane GPU gets (split wave64, 4 memory windows), plus controls whose effect on the HLSL is +/// known (the guarded block chain, 1 against 4 memory windows). +pub fn full() -> Vec { + let mut v = Vec::new(); + for ops in [500, 2000, 8000, 20000] { + let shapes = [ + ("base", Knobs { ops, ..Knobs::default() }), + ("divergent", Knobs { ops, if_depth: 6, divergent_pct: 40, ..Knobs::default() }), + ("loops", Knobs { ops, loops: 4, loop_depth: 3, ..Knobs::default() }), + ("resources", Knobs { ops, compute: true, mem_pct: 10, buffer_pct: 10, image_pct: 5, ..Knobs::default() }), + ("w32", Knobs { ops, wave64: false, ..Knobs::default() }), + ]; + for (shape, knobs) in shapes { + v.push(case(&format!("{shape}-{ops}"), knobs.clone(), false, 1, true)); + if knobs.wave64 { + v.push(case(&format!("{shape}-{ops}-split-4win"), knobs, true, 4, true)); + } + } + let base = Knobs { ops, ..Knobs::default() }; + v.push(case(&format!("control-guarded-chain-{ops}"), base.clone(), false, 1, false)); + v.push(case(&format!("control-4win-{ops}"), base, false, 4, true)); + } + v +} + +fn median(v: &[f64]) -> f64 { + let mut s = v.to_vec(); + s.sort_by(f64::total_cmp); + if s.len() % 2 == 1 { s[s.len() / 2] } else { (s[s.len() / 2 - 1] + s[s.len() / 2]) / 2.0 } +} + +fn ms(t: Instant) -> f64 { + (t.elapsed().as_secs_f64() * 1e6).round() / 1e3 +} + +/// Translate and compile one program `reps` times. Panics when it does not translate completely, +/// DXC refuses it, or a repeat gives different HLSL or DXIL. +pub fn measure(c: &Case, reps: usize, dxc_args: &[&str]) -> Row { + let code = program(&c.knobs); + let t0 = Instant::now(); + let t = translate(&code, &c.options).unwrap_or_else(|e| panic!("{}: {e}", c.name)); + let translate_ms = ms(t0); + assert!(t.complete(), "{}: {:?}", c.name, t.unsupported_why); + assert_eq!(translate(&code, &c.options).unwrap().hlsl, t.hlsl, "{}: the HLSL differs between two translations", c.name); + let (mut times, mut dxil_bytes) = (Vec::new(), None); + for _ in 0..reps { + let t0 = Instant::now(); + let dxil = dxc::compile(&t.hlsl, "main", "cs_6_6", dxc_args).unwrap_or_else(|e| panic!("{}: {}", c.name, e.lines().next().unwrap_or(""))); + times.push(ms(t0)); + assert!(!dxil.is_empty(), "{}: empty DXIL", c.name); + assert_eq!(*dxil_bytes.get_or_insert(dxil.len()), dxil.len(), "{}: the DXIL size differs between compiles", c.name); + } + Row { + name: c.name.clone(), + knobs: c.knobs.clone(), + split_wave64: c.options.split_wave64, + mem_windows: c.options.mem_windows, + structured: c.options.structured, + instructions: t.instructions, + blocks: t.blocks, + code_bytes: code.len(), + hlsl_bytes: t.hlsl.len(), + translate_ms, + dxc_args: dxc_args.join(" "), + dxc_ms_median: median(×), + dxc_ms_min: times.iter().copied().fold(f64::INFINITY, f64::min), + dxc_ms: times, + dxil_bytes: dxil_bytes.unwrap_or(0), + } +} + +fn git(args: &[&str]) -> String { + std::process::Command::new("git") + .args(args) + .current_dir(env!("CARGO_MANIFEST_DIR")) + .output() + .ok() + .filter(|o| o.status.success()) + .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string()) + .unwrap_or_default() +} + +/// What the numbers depend on: the code's commit, the DXC, the build and the machine. +pub fn environment(set: &str, reps: usize) -> serde_json::Value { + let var = |n: &str| std::env::var(n).unwrap_or_default(); + serde_json::json!({ + "set": set, + "reps": reps, + "commit": git(&["rev-parse", "HEAD"]), + "dirty": !git(&["status", "--porcelain"]).is_empty(), + "dxc": dxc::toolchain(), + "profile": if cfg!(debug_assertions) { "debug" } else { "release" }, + "cpu": var("PROCESSOR_IDENTIFIER"), + "logical_cpus": std::thread::available_parallelism().map(|n| n.get()).unwrap_or(0), + }) +} + +/// `compile_bench.json` ({environment, programs}) and `compile_bench.csv` (one row per program, +/// columns in name order; the compile times joined with `;`). +pub fn write(dir: &std::path::Path, env: &serde_json::Value, rows: &[Row]) { + std::fs::create_dir_all(dir).unwrap(); + let programs: Vec = rows.iter().map(|r| serde_json::to_value(r).unwrap()).collect(); + let json = serde_json::json!({ "environment": env, "programs": programs }); + std::fs::write(dir.join("compile_bench.json"), serde_json::to_string_pretty(&json).unwrap() + "\n").unwrap(); + let cell = |v: &serde_json::Value| match v { + serde_json::Value::Array(a) => a.iter().map(|x| x.to_string()).collect::>().join(";"), + serde_json::Value::String(s) => s.clone(), + x => x.to_string(), + }; + let mut csv = String::new(); + if let Some(serde_json::Value::Object(first)) = programs.first() { + csv += &first.keys().cloned().collect::>().join(","); + csv += "\n"; + for p in &programs { + csv += &p.as_object().unwrap().values().map(cell).collect::>().join(","); + csv += "\n"; + } + } + std::fs::write(dir.join("compile_bench.csv"), csv).unwrap(); +}