From d252dcfc91608c362e265fa4a383dde4b48a3b30 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 08:01:10 +0300 Subject: [PATCH] Recompiler: stream gpu::effects without Vec/HashSet and avoid copying compute blobs Replace Vec + HashSet in gpu::effects::of with a single-pass streaming decoder over sorted instruction PCs, delegating to an explicit far-jump path only when S_SETPC_B64 appears. Add early-exit on memory writes and zero-copy slice borrowing for FSPX and FSSM compute shaders in big_and_image_only. Part of #2508 Part of #1833 Assisted-by: Google Antigravity (Gemini 4 Neon) Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/gpu/effects.rs | 232 ++++++++++++++++++++++++++++------ 1 file changed, 196 insertions(+), 36 deletions(-) diff --git a/crates/xcl/src/gpu/effects.rs b/crates/xcl/src/gpu/effects.rs index 4fe79eb859..8703febfb8 100644 --- a/crates/xcl/src/gpu/effects.rs +++ b/crates/xcl/src/gpu/effects.rs @@ -21,16 +21,70 @@ pub struct Effects { pub instructions: usize, } -/// The writes of the RDNA2 program `code` (one program, as `xbox::Fssm::programs` cuts it). -/// None when the program cannot be decoded through a terminator, falls through past decoded -/// code, contains an unresolved indirect transfer, or branches outside the decoded instructions. -pub fn of(code: &[u8]) -> Option { - let mut insts = Vec::new(); +fn update_writes(e: &mut Effects, d: &rdna2::Decoded) { + let n = d.inst.name; + let writes = n.contains("_STORE") || n.contains("_ATOMIC"); + match d.enc.name { + "ENC_MIMG" => e.images |= writes, + "ENC_MUBUF" | "ENC_MTBUF" | "ENC_FLAT" | "ENC_FLAT_GLBL" | "ENC_FLAT_SCRATCH" | "ENC_SMEM" => e.memory |= writes, + // LDS is the group's own and gone after it; the global data share is not + "ENC_DS" => { + let gds = rdna2::field_value(d.enc, &d.words, "GDS").is_some_and(|v| v != 0); + e.memory |= gds || n == "DS_APPEND" || n == "DS_CONSUME" || n == "DS_ORDERED_COUNT" || n.starts_with("DS_GWS_"); + } + _ => {} + } +} + +fn analyze(code: &[u8], stop_on_memory: bool) -> Option { + let cap = if stop_on_memory { (code.len() / 6).min(256) } else { code.len() / 6 }; + let mut pcs = Vec::with_capacity(cap); + let mut targets = Vec::new(); let mut off = 0; // the whole program: code can follow an early terminator (a branch to it, or past it); what // does not decode (or S_CODE_END padding) after one is taken for trailing data, unless a // decoded branch still targets past it or the tail falls through into it let mut ended = false; + let mut last_ok_end = false; + let mut e = Effects::default(); + while off + 4 <= code.len() { + let Ok(d) = rdna2::decode(&code[off..], off as u64) else { + if ended { + break; + } + return None; + }; + if ended && d.inst.name == "S_CODE_END" { + break; + } + if d.inst.name == "S_SETPC_B64" { + return analyze_with_far_jumps(code, stop_on_memory); + } + if d.inst.flags & (rdna2::F_BRANCH | rdna2::F_INDIRECT) != 0 { + targets.push(rdna2::branch_target(&d)?); + } + off += d.len; + let term = d.inst.flags & rdna2::F_TERMINATOR != 0; + ended |= term; + last_ok_end = term || d.inst.name == "S_BRANCH"; + e.instructions += 1; + update_writes(&mut e, &d); + if stop_on_memory && e.memory { + return None; + } + pcs.push(d.pc); + } + if !ended || !last_ok_end || !targets.iter().all(|t| pcs.binary_search(t).is_ok()) { + return None; + } + Some(e) +} + +fn analyze_with_far_jumps(code: &[u8], stop_on_memory: bool) -> Option { + let mut insts = Vec::with_capacity(code.len() / 6); + let mut off = 0; + let mut ended = false; + let mut e = Effects::default(); while off + 4 <= code.len() { let Ok(d) = rdna2::decode(&code[off..], off as u64) else { if ended { @@ -43,6 +97,11 @@ pub fn of(code: &[u8]) -> Option { } off += d.len; ended |= d.inst.flags & rdna2::F_TERMINATOR != 0; + e.instructions += 1; + update_writes(&mut e, &d); + if stop_on_memory && e.memory { + return None; + } insts.push(d); } if !ended { @@ -53,42 +112,25 @@ pub fn of(code: &[u8]) -> Option { if last.inst.flags & rdna2::F_TERMINATOR == 0 && last.inst.name != "S_BRANCH" && last.far_target.is_none() { return None; } - let pcs: std::collections::HashSet = insts.iter().map(|d| d.pc).collect(); - let mut e = Effects::default(); for d in &insts { - if d.inst.flags & (rdna2::F_BRANCH | rdna2::F_INDIRECT) != 0 && rdna2::branch_target(d).is_none_or(|t| !pcs.contains(&t)) { + if d.inst.flags & (rdna2::F_BRANCH | rdna2::F_INDIRECT) != 0 + && rdna2::branch_target(d).is_none_or(|t| insts.binary_search_by_key(&t, |x| x.pc).is_err()) + { return None; } - e.instructions += 1; - let n = d.inst.name; - let writes = n.contains("_STORE") || n.contains("_ATOMIC"); - match d.enc.name { - "ENC_MIMG" => e.images |= writes, - "ENC_MUBUF" | "ENC_MTBUF" | "ENC_FLAT" | "ENC_FLAT_GLBL" | "ENC_FLAT_SCRATCH" | "ENC_SMEM" => e.memory |= writes, - // LDS is the group's own and gone after it; the global data share is not - "ENC_DS" => { - let gds = rdna2::field_value(d.enc, &d.words, "GDS").is_some_and(|v| v != 0); - e.memory |= gds || n == "DS_APPEND" || n == "DS_CONSUME" || n == "DS_ORDERED_COUNT" || n.starts_with("DS_GWS_"); - } - _ => {} - } } Some(e) } -/// The compute program of a console shader container (the hardware CS variant of an FSSM, or -/// an FSPX driver container), as the translators take it. -fn compute_code(blob: &[u8]) -> Option> { - if let Some(f) = recomp::pso::fspx(blob) { - return Some(f.code.to_vec()); - } - let sh = xbox::parse(blob)?; - let f = sh.fssm.iter().find(|f| f.stages.first().is_some_and(|s| s.hw == 6))?; - if f.error.is_some() { - return None; - } - let p = f.programs.first()?; - Some(f.data.get(p.offset..p.offset.checked_add(p.len)?)?.to_vec()) +/// The writes of the RDNA2 program `code` (one program, as `xbox::Fssm::programs` cuts it). +/// None when the program cannot be decoded through a terminator, falls through past decoded +/// code, contains an unresolved indirect transfer, or branches outside the decoded instructions. +pub fn of(code: &[u8]) -> Option { + analyze(code, false) +} + +fn is_big_image_only_code(code: &[u8]) -> bool { + code.len() >= BIG_CODE && analyze(code, true).is_some() } /// Console code a compute program needs to be `big`: 16 KiB, about 4 000 instructions. The @@ -100,8 +142,17 @@ pub const BIG_CODE: usize = 16 << 10; /// title can do without for the frames its pipeline takes to build. False for anything that /// cannot be read. pub fn big_and_image_only(blob: &[u8]) -> bool { - let Some(code) = compute_code(blob) else { return false }; - code.len() >= BIG_CODE && of(&code).is_some_and(|e| !e.memory) + if let Some(f) = recomp::pso::fspx(blob) { + return is_big_image_only_code(f.code); + } + let Some(sh) = xbox::parse(blob) else { return false }; + let Some(f) = sh.fssm.iter().find(|f| f.stages.first().is_some_and(|s| s.hw == 6)) else { return false }; + if f.error.is_some() { + return false; + } + let Some(p) = f.programs.first() else { return false }; + let Some(end) = p.offset.checked_add(p.len) else { return false }; + f.data.get(p.offset..end).is_some_and(is_big_image_only_code) } #[cfg(test)] @@ -255,4 +306,113 @@ mod tests { assert!(sh.fssm[0].error.is_some() && !sh.fssm[0].programs.is_empty()); assert!(!big_and_image_only(&errored)); } + + fn of_reference(code: &[u8]) -> Option { + let (mut insts, mut off, mut ended) = (Vec::new(), 0, false); + while off + 4 <= code.len() { + let Ok(d) = rdna2::decode(&code[off..], off as u64) else { if ended { break; } return None; }; + if ended && d.inst.name == "S_CODE_END" { break; } + off += d.len; ended |= d.inst.flags & rdna2::F_TERMINATOR != 0; insts.push(d); + } + if !ended { return None; } + rdna2::resolve_far_jumps(&mut insts); + let last = insts.last()?; + if last.inst.flags & rdna2::F_TERMINATOR == 0 && last.inst.name != "S_BRANCH" && last.far_target.is_none() { return None; } + let pcs: std::collections::HashSet = insts.iter().map(|d| d.pc).collect(); + let mut e = Effects::default(); + for d in &insts { + if d.inst.flags & (rdna2::F_BRANCH | rdna2::F_INDIRECT) != 0 && rdna2::branch_target(d).is_none_or(|t| !pcs.contains(&t)) { return None; } + e.instructions += 1; update_writes(&mut e, d); + } + Some(e) + } + + fn fspx_blob(code: &[u8]) -> Vec { + let mut head = [0u8; 0x20]; + for o in [0x0C, 0x0E, 0x10] { head[o..o + 2].copy_from_slice(&1u16.to_le_bytes()); } + let mut accc = [b"FSPX".as_slice(), &[0; 4], &2u32.to_le_bytes(), &[0; 4]].concat(); + for w in [0u32, 0x30, 0x20, 0, 6, 0x50, (0x24 + code.len()) as u32, 0] { accc.extend_from_slice(&w.to_le_bytes()); } + accc.extend_from_slice(&head); accc.extend_from_slice(&[0u8; 0x24]); accc.extend_from_slice(code); + let mut out = [b"DXBC".as_slice(), &[0; 16]].concat(); + for w in [1u32, (44 + accc.len()) as u32, 1, 36] { out.extend_from_slice(&w.to_le_bytes()); } + out.extend_from_slice(b"ACCC"); out.extend_from_slice(&(accc.len() as u32).to_le_bytes()); out.extend_from_slice(&accc); + out + } + + #[test] + fn streaming_matches_reference_of_across_edge_cases() { + let store: (&str, &str, &[(&str, u64)]) = ("BUFFER_STORE_DWORD", "ENC_MUBUF", &[("VDATA", 1), ("SRSRC", 2)]); + let setpc: (&str, &str, &[(&str, u64)]) = ("S_SETPC_B64", "ENC_SOP1", &[("SSRC0", 0)]); + let swappc: (&str, &str, &[(&str, u64)]) = ("S_SWAPPC_B64", "ENC_SOP1", &[("SDST", 2), ("SSRC0", 0)]); + let call_ok: (&str, &str, &[(&str, u64)]) = ("S_CALL_B64", "ENC_SOPK", &[("SDST", 0), ("SIMM16", 0)]); + let code_end: (&str, &str, &[(&str, u64)]) = ("S_CODE_END", "ENC_SOPP", &[]); + let oob_br: (&str, &str, &[(&str, u64)]) = ("S_BRANCH", "ENC_SOPP", &[("SIMM16", 9)]); + let getpc: (&str, &str, &[(&str, u64)]) = ("S_GETPC_B64", "ENC_SOP1", &[("SDST", 0)]); + let add16: (&str, &str, &[(&str, u64)]) = ("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 128 + 16)]); + let addc0: (&str, &str, &[(&str, u64)]) = ("S_ADDC_U32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 1), ("SSRC1", 128)]); + let mut cases = vec![ + Vec::new(), + [asm(&[store]), vec![0xff; 8]].concat(), + asm(&[store, oob_br, END]), + asm(&[store, END, code_end]), + asm(&[IMAGE_STORE, END, store, END]), + asm(&[getpc, add16, addc0, setpc, END, IMAGE_STORE, END]), + asm(&[IMAGE_STORE, END, getpc, ("S_SUB_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 128 + 16)]), ("S_SUBB_U32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 1), ("SSRC1", 128)]), setpc]), + asm(&[getpc, ("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 128 + 64)]), addc0, setpc, END]), + asm(&[getpc, add16, addc0, setpc, END, store, END]), + asm(&[store, getpc, add16, addc0, setpc, END, IMAGE_STORE, END]), + asm(&[IMAGE_STORE, swappc, END]), + asm(&[IMAGE_STORE, call_ok, END]), + ]; + assert_eq!(of(&cases[6]), Some(Effects { memory: false, images: true, instructions: 6 })); + let pool = [asm(&[MOV]), asm(&[IMAGE_STORE]), asm(&[store]), asm(&[END]), asm(&[code_end]), asm(&[("S_BRANCH", "ENC_SOPP", &[("SIMM16", 0)])]), asm(&[oob_br]), asm(&[setpc])]; + let mut rng = 0x9E37_79B9_7F4A_7C15u64; + for _ in 0..64 { + let mut s = Vec::new(); + for _ in 0..16 { rng ^= rng << 13; rng ^= rng >> 7; rng ^= rng << 17; s.extend_from_slice(&pool[(rng as usize) % pool.len()]); } + cases.push(s); + } + for c in &cases { + let want = of_reference(c); + assert_eq!(of(c), want); + assert_eq!(analyze(c, true).is_some(), want.is_some_and(|e| !e.memory)); + } + + let (mov, small) = (asm(&[MOV]), asm(&[IMAGE_STORE, END])); + assert!(!big_and_image_only(&xbox::tests::sample(5, &[xbox::tests::fssm(&small, &[(6, 0)])]))); + assert!(!big_and_image_only(&fspx_blob(&small))); + let mut big_img = Vec::with_capacity(BIG_CODE + 16); + while big_img.len() < BIG_CODE { big_img.extend_from_slice(&mov); } + big_img.extend(asm(&[IMAGE_STORE, END])); + let mut big_mem = asm(&[store]); + while big_mem.len() < BIG_CODE { big_mem.extend_from_slice(&mov); } + big_mem.extend(asm(&[END])); + assert!(big_and_image_only(&fspx_blob(&big_img)) && !big_and_image_only(&fspx_blob(&big_mem)) && !big_and_image_only(&fspx_blob(&big_img)[..40])); + assert!(big_and_image_only(&xbox::tests::sample(5, &[xbox::tests::fssm(&big_img, &[(6, 0)])])) && !big_and_image_only(&xbox::tests::sample(5, &[xbox::tests::fssm(&big_mem, &[(6, 0)])]))); + + if !cfg!(debug_assertions) { + fn bench(iters: u32, mut f: impl FnMut() -> bool) -> (f64, u32) { + let (t0, mut acc) = (std::time::Instant::now(), 0u32); + for _ in 0..iters { acc += u32::from(std::hint::black_box(f())); } + (t0.elapsed().as_micros() as f64 / iters as f64, acc) + } + let (mut img_100k, mut mem_100k) = (Vec::with_capacity(100_016), asm(&[store])); + while img_100k.len() < 100_000 { img_100k.extend_from_slice(&mov); } + img_100k.extend(asm(&[IMAGE_STORE, END])); + while mem_100k.len() < 100_000 { mem_100k.extend_from_slice(&mov); } + mem_100k.extend(asm(&[END])); + let (blob_img, blob_mem) = (xbox::tests::sample(5, &[xbox::tests::fssm(&img_100k, &[(6, 0)])]), xbox::tests::sample(5, &[xbox::tests::fssm(&mem_100k, &[(6, 0)])])); + let ref_big = |blob: &[u8]| { + let sh = xbox::parse(blob)?; + let f = sh.fssm.iter().find(|f| f.stages.first().is_some_and(|s| s.hw == 6))?; + let p = f.programs.first()?; + let c = f.data.get(p.offset..p.offset.checked_add(p.len)?)?.to_vec(); + Some(c.len() >= BIG_CODE && of_reference(&c).is_some_and(|e| !e.memory)) + }; + let ((ib, a1), (ia, a2)) = (bench(50, || ref_big(&blob_img).unwrap_or(false)), bench(50, || big_and_image_only(&blob_img))); + let ((mb, b1), (ma, b2)) = (bench(50, || ref_big(&blob_mem).unwrap_or(false)), bench(50, || big_and_image_only(&blob_mem))); + assert_eq!((a1, a2, b1, b2), (50, 50, 0, 0)); + println!("EFFECTS_BENCH_US img_100k: before={ib:.1} after={ia:.1} | mem_100k: before={mb:.1} after={ma:.1}"); + } + } }