From 4afd8a55bd63e82cee8ac1d33a1941d78d50e456 Mon Sep 17 00:00:00 2001 From: Foniass <107039406+Foniass@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:02:09 +0100 Subject: [PATCH 1/2] Recompiler: compact literal indices are read from one table word on AMD The compact form (#3261) gives each block of a parameterized class its literal through two tables: a bit-packed index per block (xcl_lit_idx) and the pool of distinct literals (xcl_lit_pool). An index could straddle two words of xcl_lit_idx and was read with a two-word funnel extraction. AMD's driver (an RX 7800 XT, 32.0.32029, and a Ryzen 7800X3D's RDNA2 iGPU, 32.0.21030) gets the pool index wrong from that extraction: gpu_compact_form_with_micro_blocks_and_literal_table_runs_ as_the_plain_form read 0 for every literal (s1 = 0 instead of 10045), in native and split wave64. The same DXIL runs correctly on NVIDIA, and the index is right when used as a value; only its use as the next table's index goes wrong (with a clamp, it read the last pool entry). The index width is now a power of two, so an index never straddles two words and the lookup reads one word. The table grows at most 2x (an 8-bit index stays 8 bits; 9 bits take 16). Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/dxil/compact.rs | 13 ++++------ crates/xcl/src/gpu/dxil/compact_tests.rs | 32 ++++++++++++++++++------ 2 files changed, 29 insertions(+), 16 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/compact.rs b/crates/xcl/src/gpu/dxil/compact.rs index 65c1a51b00..8c0febd196 100644 --- a/crates/xcl/src/gpu/dxil/compact.rs +++ b/crates/xcl/src/gpu/dxil/compact.rs @@ -801,7 +801,10 @@ pub fn emit_with_nest(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block }); blk_idx.push(idx); } - let lit_w = bits(pool.len()).min(32); + // a power of two, so no index straddles two words: AMD's driver (RDNA2 / RDNA3) reads + // a wrong pool index from the two-word extraction (`gpu_compact_form_with_micro_blocks_ + // and_literal_table_runs_as_the_plain_form` read 0 for every literal) + let lit_w = bits(pool.len()).next_power_of_two().min(32); let mut idx_packed = vec![0u32; (n * lit_w as usize).div_ceil(32) + 1]; for (b, &id) in blk_idx.iter().enumerate() { let v = id as u64; @@ -861,13 +864,7 @@ pub fn emit_with_nest(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block let li = lw.lshrc(lbit, 5); let lsh = lw.andc(lbit, 31); let llo = word(lw, idx_tbl, li); - let li1 = lw.addc(li, 1); - let lhi = word(lw, idx_tbl, li1); - let llo = lw.lshr(llo, lsh); - let lhi = lw.shlc(lhi, 1); - let lup = lw.sub(k31, lsh); - let lhi = lw.shl(lhi, lup); - let le = lw.or(llo, lhi); + let le = lw.lshr(llo, lsh); lw.andc(le, (1u32 << lit_w) - 1) }; word(lw, pool_tbl, id) diff --git a/crates/xcl/src/gpu/dxil/compact_tests.rs b/crates/xcl/src/gpu/dxil/compact_tests.rs index cf56c97c85..a0c88f3975 100644 --- a/crates/xcl/src/gpu/dxil/compact_tests.rs +++ b/crates/xcl/src/gpu/dxil/compact_tests.rs @@ -151,6 +151,19 @@ fn loads_and_literals(copies: usize) -> Vec { v } +/// Each block's literal index sits in one word of `xcl_lit_idx` (a power-of-two width), so the +/// lookup reads one word: AMD's driver got the index wrong from a two-word extraction. +#[test] +fn a_literal_index_is_read_from_one_word() { + for copies in [200, 300] { + let o = KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 }; + let k = translate_full_as(&loads_and_literals(copies), o, true).expect("compact form"); + let dis = super::validate::disassemble(&k.dxil).expect("disassemble"); + let reads = dis.lines().filter(|l| l.contains("getelementptr") && l.contains("@xcl_lit_idx,")).count(); + assert_eq!(reads, 1, "{copies} copies: {reads} reads of the literal index table"); + } +} + #[test] fn repeated_loads_split_into_micro_blocks_and_literals_into_a_table() { let code = loads_and_literals(200); @@ -174,15 +187,18 @@ fn gpu_compact_form_with_micro_blocks_and_literal_table_runs_as_the_plain_form() let mut st = KernelState::default(); // s[2:3] = 0: the loads read mem[0]; the early out is taken in the 10th copy st.sgpr[4] = 50; - let code = loads_and_literals(200); let o = KernelOptions { wave64: true, split: runner::split_wave64(), mem_windows: 1, sampler_base: 0 }; - let run = |compact: bool| { - let k = translate_full_as(&code, o, compact).unwrap_or_else(|e| panic!("compact {compact}: {e}")); - runner::run_with_statics(&k.dxil, &st, &[5, 0, 0, 0], &[], &[], &k.static_samplers).expect("GPU run") - }; - let (c, p) = (run(true), run(false)); - assert_eq!((c.sgpr[0], c.sgpr[1], c.sgpr[5], c.sgpr[8]), (50, (1000..1010).sum::(), 1, 5)); - assert_eq!((c.sgpr, c.vgpr, c.scc), (p.sgpr, p.vgpr, p.scc)); + // 200 copies: 8-bit literal indices; 300: 9 bits, which the table stores in 16 + for copies in [200, 300] { + let code = loads_and_literals(copies); + let run = |compact: bool| { + let k = translate_full_as(&code, o, compact).unwrap_or_else(|e| panic!("compact {compact}: {e}")); + runner::run_with_statics(&k.dxil, &st, &[5, 0, 0, 0], &[], &[], &k.static_samplers).expect("GPU run") + }; + let (c, p) = (run(true), run(false)); + assert_eq!((c.sgpr[0], c.sgpr[1], c.sgpr[5], c.sgpr[8]), (50, (1000..1010).sum::(), 1, 5), "{copies} copies"); + assert_eq!((c.sgpr, c.vgpr, c.scc), (p.sgpr, p.vgpr, p.scc), "{copies} copies"); + } } #[test] From 70ed9c603b013e6726461378c6c1123e00db61f8 Mon Sep 17 00:00:00 2001 From: Foniass <107039406+Foniass@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:17:06 +0100 Subject: [PATCH 2/2] Recompiler: compact block-PC table reads one word, and words() counts it Follow-ups to the compact form's review on #3263 (KOLESNiii): - Plan::words(), which the table limit is checked against, now counts the block-PC table and the literal index and pool tables, so a program can no longer take the form with more table words than MAX_TABLE_WORDS. A plan with a PC table and no block literal no longer emits empty literal tables. - The block-PC table gets the literal index table's fix: entries of a power-of-two width, read from one word (entry_bits). The two-word read is what AMD's driver got wrong for the literal index; the PC values themselves read right on AMD in the new test, so this one is for consistency, not a seen failure. - The comments said repeated memory ops split out at >= 4 occurrences; the code does it at >= 2. - Tests for code that had none: a GPU run of blocks that share a class through the PC table, dead far-jump veneers left out (all of them in a compute program, all but the last in the kernel form) and a GPU run of that kernel form against the plain one, and words() against the table sizes in the DXIL. On the retail title nothing changes: none of its 768 compute programs that reach the compact plan has a literal or PC table. One of them has a 16121-word plan (19840 blocks), over main's former 12288-word limit and under the 32768 one. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/dxil/compact.rs | 82 +++++++++------ crates/xcl/src/gpu/dxil/compact_tests.rs | 122 +++++++++++++++++++++++ 2 files changed, 173 insertions(+), 31 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/compact.rs b/crates/xcl/src/gpu/dxil/compact.rs index 8c0febd196..ca41682e63 100644 --- a/crates/xcl/src/gpu/dxil/compact.rs +++ b/crates/xcl/src/gpu/dxil/compact.rs @@ -237,7 +237,7 @@ impl Plan { (bits(self.rep.len()), pb) } - /// 32-bit words of the tables. + /// 32-bit words of the tables, the block-PC and literal ones included. pub fn words(&self) -> usize { let (cb, pb) = self.widths(); let extra = match self.next_enc { @@ -245,8 +245,48 @@ impl Plan { NextEnc::Inline => 0, NextEnc::TargetPool => self.targets.len(), }; - (self.mblocks.len() * (cb + pb) as usize).div_ceil(32) + 1 + extra + let packed = |w: u32| (self.mblocks.len() * w as usize).div_ceil(32) + 1; + let pc = if self.use_pc { packed(self.pc_width()) } else { 0 }; + let lit = if self.use_lit { + let (pool, _) = self.lit_pool(); + packed(entry_bits(pool.len())) + pool.len() + } else { + 0 + }; + packed(cb + pb) + extra + pc + lit + } + + /// Bits of a block's PC entry in `xcl_pc` (PCs in dwords). + fn pc_width(&self) -> u32 { + let max_pc_dw = self.mblocks.iter().map(|blk| (blk.pc >> 2) as usize).max().unwrap_or(0); + entry_bits(max_pc_dw + 1) } + + /// The distinct parameterized literals (0 first, for blocks without one) and each block's + /// index into them. + fn lit_pool(&self) -> (Vec, Vec) { + let mut pool: Vec = vec![0]; + let mut idx_map: HashMap = HashMap::from([(0, 0)]); + let blk_idx = self + .blk_lit + .iter() + .map(|&opt| { + let val = opt.unwrap_or(0); + *idx_map.entry(val).or_insert_with(|| { + pool.push(val); + pool.len() as u32 - 1 + }) + }) + .collect(); + (pool, blk_idx) + } +} + +/// Bits of an entry of a per-block table that takes `n` values: a power of two, so no entry +/// straddles two words and a lookup reads one word. AMD's driver (RDNA2 / RDNA3) got the +/// literal pool index wrong from a two-word extraction (every literal read 0). +fn entry_bits(n: usize) -> u32 { + bits(n).next_power_of_two().min(32) } /// A consumed atomic result prevents cutting a dispatch into independent pipelines. @@ -318,7 +358,7 @@ fn single_param_lit(cfg: &Cfg, blk: &MicroBlock) -> Option { } /// Sorts the reachable blocks into classes the lowering would emit the same for. -/// On large shaders, repeated heavy memory instructions (appearing `>= 4` times) are split +/// On large shaders, repeated heavy memory instructions (appearing `>= 2` times) are split /// into standalone micro-blocks so each unique buffer/SMEM/image lowering is emitted once /// instead of once per surrounding ALU context. pub fn plan(cfg: &Cfg, lw: &Lw) -> Option { @@ -340,7 +380,7 @@ pub fn plan(cfg: &Cfg, lw: &Lw) -> Option { } } - // Pass 1: split blocks around repeated heavy memory ops (`>= 4` occurrences). + // Pass 1: split blocks around repeated heavy memory ops (`>= 2` occurrences). let mut segs_per_orig: Vec<(usize, Vec>)> = Vec::with_capacity(orig_order.len()); let mut orig_to_mb = vec![END; cfg.blocks.len()]; let mut mb_cursor = 0u32; @@ -595,7 +635,8 @@ pub fn plan(cfg: &Cfg, lw: &Lw) -> Option { let only_lit = if has_getpc { build(true, false) } else { cand.clone() }; let saved_pc = only_lit.1.len().saturating_sub(cand.1.len()); if has_getpc && saved_pc >= 64 && saved_pc * 60 > mblocks.len() * 2 { - (true, true, cand) + // (no literal tables when no block has a literal to take from them) + (cand.3.iter().any(Option::is_some), true, cand) } else if base.1.len().saturating_sub(only_lit.1.len()) >= 64 && base.1.len().saturating_sub(only_lit.1.len()) * 60 > mblocks.len() * 2 { @@ -776,8 +817,7 @@ pub fn emit_with_nest(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block let steps = (p.next_enc == NextEnc::Steps).then(|| table(lw, "xcl_steps", &steps)); let target_pool = (p.next_enc == NextEnc::TargetPool).then(|| table(lw, "xcl_targets", &p.targets)); let pc_table = p.use_pc.then(|| { - let max_pc_dw = p.mblocks.iter().map(|blk| (blk.pc >> 2) as usize).max().unwrap_or(0); - let pc_w = bits(max_pc_dw + 1).min(32); + let pc_w = p.pc_width(); let mut pc_packed = vec![0u32; (n * pc_w as usize).div_ceil(32) + 1]; for (b, blk) in p.mblocks.iter().enumerate() { let v = (blk.pc >> 2) as u64; @@ -788,23 +828,9 @@ pub fn emit_with_nest(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block (table(lw, "xcl_pc", &pc_packed), pc_w) }); let lit_table = p.use_lit.then(|| { - // Deduplicate unique 32-bit literals into a pool and bit-pack pool indices per block. - let mut pool: Vec = vec![0]; - let mut idx_map: HashMap = HashMap::from([(0, 0)]); - let mut blk_idx: Vec = Vec::with_capacity(n); - for &opt in &p.blk_lit { - let val = opt.unwrap_or(0); - let idx = *idx_map.entry(val).or_insert_with(|| { - let id = pool.len() as u32; - pool.push(val); - id - }); - blk_idx.push(idx); - } - // a power of two, so no index straddles two words: AMD's driver (RDNA2 / RDNA3) reads - // a wrong pool index from the two-word extraction (`gpu_compact_form_with_micro_blocks_ - // and_literal_table_runs_as_the_plain_form` read 0 for every literal) - let lit_w = bits(pool.len()).next_power_of_two().min(32); + // the distinct literals in a pool, and each block's pool index bit-packed + let (pool, blk_idx) = p.lit_pool(); + let lit_w = entry_bits(pool.len()); let mut idx_packed = vec![0u32; (n * lit_w as usize).div_ceil(32) + 1]; for (b, &id) in blk_idx.iter().enumerate() { let v = id as u64; @@ -844,13 +870,7 @@ pub fn emit_with_nest(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block let pi = lw.lshrc(pbit, 5); let psh = lw.andc(pbit, 31); let plo = word(lw, pc_tbl, pi); - let pi1 = lw.addc(pi, 1); - let phi = word(lw, pc_tbl, pi1); - let plo = lw.lshr(plo, psh); - let phi = lw.shlc(phi, 1); - let pup = lw.sub(k31, psh); - let phi = lw.shl(phi, pup); - let pe = lw.or(plo, phi); + let pe = lw.lshr(plo, psh); lw.andc(pe, (1u32 << pc_w) - 1) }; lw.shlc(pm, 2) diff --git a/crates/xcl/src/gpu/dxil/compact_tests.rs b/crates/xcl/src/gpu/dxil/compact_tests.rs index a0c88f3975..3e542fa207 100644 --- a/crates/xcl/src/gpu/dxil/compact_tests.rs +++ b/crates/xcl/src/gpu/dxil/compact_tests.rs @@ -151,6 +151,128 @@ fn loads_and_literals(copies: usize) -> Vec { v } +/// `copies` blocks that each read their own PC (`s_getpc_b64 s[10:11]`) and add it to s1; s0 +/// counts them, and the early out after the copy where s0 == s4 goes to `s_mov s5, 1`. +fn pcs(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(); + for k in 0..copies { + v.extend(i("S_GETPC_B64", "ENC_SOP1", &[("SDST", 10)])); + v.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 1), ("SSRC1", 10)])); + v.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 129)])); + v.extend(i("S_CMP_EQ_U32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 4)])); + // to the s_mov after the last copy: 5 dwords per copy + v.extend(i("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", ((copies - 1 - k) * 5) as u64)])); + } + v.extend(i("S_MOV_B32", "ENC_SOP1", &[("SDST", 5), ("SSRC0", 129)])); + v.extend(i("S_ENDPGM", "ENC_SOPP", &[])); + v +} + +/// Blocks that differ only in where their `s_getpc_b64` is share a class and read the block's PC +/// from `xcl_pc`; the result is the plain form's. +#[test] +fn gpu_compact_form_with_a_block_pc_table_runs_as_the_plain_form() { + 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 code = pcs(200); + let cfg = super::cfg::Cfg::build(&code).unwrap(); + let leaders = cfg.blocks.iter().filter_map(|b| b.insts.first().map(|&i| cfg.insts[i].pc)).collect(); + let o = KernelOptions { wave64: true, split: runner::split_wave64(), mem_windows: 1, sampler_base: 0 }; + let lw = super::lower::Lw::new(&cfg.insts, &leaders, o, &super::kernel::Entry::Kernel); + let p = super::compact::plan(&cfg, &lw).unwrap(); + assert!(p.use_pc && p.rep.len() < 8, "block PC table {}, {} classes", p.use_pc, p.rep.len()); + let mut st = KernelState::default(); + st.sgpr[4] = 10; + let run = |compact: bool| { + let k = translate_full_as(&code, o, compact).unwrap_or_else(|e| panic!("compact {compact}: {e}")); + runner::run_with_statics(&k.dxil, &st, &[], &[], &[], &k.static_samplers).expect("GPU run") + }; + let (c, p) = (run(true), run(false)); + // copy k starts at 20 k; its s_getpc_b64 gives the address after it, 20 k + 4 + assert_eq!((c.sgpr[0], c.sgpr[1], c.sgpr[5]), (10, (0..10).map(|k| 20 * k + 4).sum::(), 1)); + assert_eq!((c.sgpr, c.vgpr, c.scc), (p.sgpr, p.vgpr, p.scc)); +} + +/// `copies` blocks that each add 1 to s0 and go to the next one through a far-jump veneer +/// (`s_getpc_b64 s[10:11]`, `s_add_u32` / `s_addc_u32`, `s_setpc_b64`). +fn far_jumps(copies: usize) -> Vec { + let i = |n: &str, e: &str, f: &[(&str, u64)], lit: Option| encode(n, e, f, lit).unwrap_or_else(|x| panic!("{n}: {x}")); + let mut v = Vec::new(); + for _ in 0..copies { + v.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 129)], None)); + v.extend(i("S_GETPC_B64", "ENC_SOP1", &[("SDST", 10)], None)); + // the next copy is 16 bytes after the address s_getpc_b64 gives (24 bytes a copy) + v.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 10), ("SSRC0", 10), ("SSRC1", 255)], Some(16))); + v.extend(i("S_ADDC_U32", "ENC_SOP2", &[("SDST", 11), ("SSRC0", 11), ("SSRC1", 128)], None)); + v.extend(i("S_SETPC_B64", "ENC_SOP1", &[("SSRC0", 10)], None)); + } + v.extend(i("S_ENDPGM", "ENC_SOPP", &[], None)); + v +} + +/// A far-jump veneer whose address registers and SCC nobody reads after the jump is left out of +/// the compact form: in a compute program (nothing is live at its end) all of them, in the +/// kernel form of the tests (every register is read at the end) all but the last. +#[test] +fn dead_far_jump_veneers_are_left_out() { + let code = far_jumps(70); + let cfg = super::cfg::Cfg::build(&code).unwrap(); + let leaders = cfg.blocks.iter().filter_map(|b| b.insts.first().map(|&i| cfg.insts[i].pc)).collect(); + let o = KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 }; + let cs = crate::gpu::recomp::CsInterface { threads: [64, 1, 1], user_sgprs: 4, tgid: [false; 3], tg_size: false, tid_components: 1 }; + let getpcs = |entry: &super::kernel::Entry| { + let lw = super::lower::Lw::new(&cfg.insts, &leaders, o, entry); + let p = super::compact::plan(&cfg, &lw).unwrap(); + p.mblocks.iter().flat_map(|b| &b.insts).filter(|&&i| cfg.insts[i].inst.name == "S_GETPC_B64").count() + }; + assert_eq!(getpcs(&super::kernel::Entry::Compute(cs)), 0); + assert_eq!(getpcs(&super::kernel::Entry::Kernel), 1); +} + +/// With the veneers left out, the kernel form still ends as the plain one (the last veneer's +/// address in s[10:11] included). +#[test] +fn gpu_compact_form_without_dead_veneers_runs_as_the_plain_form() { + 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 code = far_jumps(70); + let o = KernelOptions { wave64: true, split: runner::split_wave64(), mem_windows: 1, sampler_base: 0 }; + let st = KernelState::default(); + let run = |compact: bool| { + let k = translate_full_as(&code, o, compact).unwrap_or_else(|e| panic!("compact {compact}: {e}")); + runner::run_with_statics(&k.dxil, &st, &[], &[], &[], &k.static_samplers).expect("GPU run") + }; + let (c, p) = (run(true), run(false)); + assert_eq!((c.sgpr[0], c.sgpr[10]), (70, 69 * 24 + 8 + 16)); + assert_eq!((c.sgpr, c.vgpr, c.scc), (p.sgpr, p.vgpr, p.scc)); +} + +/// The plan's word count is what the tables take, the block-PC and literal ones included. +#[test] +fn the_word_count_includes_the_pc_and_literal_tables() { + for (code, what) in [(loads_and_literals(300), "literals"), (pcs(200), "pcs")] { + let o = KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 }; + let cfg = super::cfg::Cfg::build(&code).unwrap(); + let leaders = cfg.blocks.iter().filter_map(|b| b.insts.first().map(|&i| cfg.insts[i].pc)).collect(); + let lw = super::lower::Lw::new(&cfg.insts, &leaders, o, &super::kernel::Entry::Kernel); + let p = super::compact::plan(&cfg, &lw).unwrap(); + assert!(p.use_lit || p.use_pc, "{what}: no parameterized table"); + let k = translate_full_as(&code, o, true).expect("compact form"); + let dis = super::validate::disassemble(&k.dxil).expect("disassemble"); + let words: usize = dis + .lines() + .filter(|l| l.starts_with("@xcl_") && l.contains("internal constant [")) + .map(|l| l.split("internal constant [").nth(1).unwrap().split(" x i32]").next().unwrap().parse::().unwrap()) + .sum(); + assert_eq!(p.words(), words, "{what}"); + } +} + /// Each block's literal index sits in one word of `xcl_lit_idx` (a power-of-two width), so the /// lookup reads one word: AMD's driver got the index wrong from a two-word extraction. #[test]