From b8b4135b7261c9b50cff1abf92a3b03cc2e8e6d2 Mon Sep 17 00:00:00 2001 From: throny <11830644+throny@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:38:37 +0100 Subject: [PATCH] Recompiler: the FSSM header's wave32 flag decides a program's wave size detect_wave64 tells the wave size from the code: 32-bit EXEC writes and no 64-bit ones mean wave32, anything else wave64. A wave32 program that never writes EXEC has nothing in its code to tell, so it was translated as wave64: its cross-lane reads (v_readfirstlane, v_readlane, permutes) then span 64 threads instead of 32. The FSSM header has the answer: bit 5 of the flags word at +0xD4. Measured on a retail shader pack (26 698 programs): the bit is set for all 2 608 programs the code shows to be wave32 and clear for all 24 036 the code takes for wave64, except 54 compute programs with the bit set and no EXEC write in their code. 27 of those 54 have cross-lane instructions (v_readfirstlane, v_readlane, permutes, LDS). As wave32 all 54 translate completely and compile with DXC. fssm_wave64 takes wave32 from the header and leaves everything else to detect_wave64, so only those programs change. An unused field (0xDEADBEEF) and other FSSM versions say nothing. A compute program through the PSO hook (gpu_compute_e2e) shows the effect: 64 threads store v_readfirstlane of their thread id; with the flag threads 32..63 read thread 32, without it they read thread 0. Co-Authored-By: Claude Fable 5.2 --- crates/xcl/src/gpu/recomp/mod.rs | 8 ++++ crates/xcl/src/gpu/recomp/pso.rs | 8 ++-- crates/xcl/src/gpu/xbox.rs | 27 +++++++++++ crates/xcl/src/shaders.rs | 4 +- crates/xcl/tests/gpu_compute_e2e.rs | 71 +++++++++++++++++++++++++++++ 5 files changed, 112 insertions(+), 6 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 414a95e07..c55477348 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -1297,6 +1297,14 @@ pub fn translate_mesh(code: &[u8], ms: MsInterface, wave64: bool, split_wave64: translate(code, &Options { mode: Mode::Mesh(ms), wave64, split_wave64, mem_windows, ..Default::default() }) } +/// Wave size of an FSSM's program: wave32 when its header says so (`Fssm::wave32`), else by +/// the code. A wave32 program that never writes EXEC has nothing in its code to tell, and +/// `detect_wave64` takes it for wave64: its cross-lane reads (`v_readfirstlane`, `v_readlane`, +/// permutes) then span 64 threads instead of 32. +pub fn fssm_wave64(f: &super::xbox::Fssm, code: &[u8]) -> bool { + !f.wave32() && detect_wave64(code) +} + /// Wave size the program was compiled for: 64-bit EXEC/VCC writes mean wave64. pub fn detect_wave64(code: &[u8]) -> bool { let mut off = 0; diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 9b5a305b0..eb52f7ae6 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -713,7 +713,7 @@ fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split_wave64: bo let Some(Mode::Compute(cs)) = interface(blob, &sh, f) else { return Err("not a compute interface".into()) }; let p = f.programs.first().ok_or("FSSM without a program")?; let code = &f.data[p.offset..p.offset + p.len]; - let wave64 = super::detect_wave64(code); + let wave64 = super::fssm_wave64(f, code); let o = crate::gpu::dxil::kernel::KernelOptions { wave64, split: wave64 && split_wave64, mem_windows: windows, sampler_base }; // `XCL_PER_LANE=1`: the per-lane form first, #1426's per-instruction form where it refuses if super::lower_dxil::enabled() { @@ -759,7 +759,7 @@ fn direct_graphics(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32) - let mode = interface(blob, &sh, f).ok_or("unknown shader interface")?; let p = f.programs.first().ok_or("FSSM without a program")?; let code = &f.data[p.offset..p.offset + p.len]; - let o = crate::gpu::dxil::kernel::KernelOptions { wave64: super::detect_wave64(code), split: false, mem_windows: windows, sampler_base }; + let o = crate::gpu::dxil::kernel::KernelOptions { wave64: super::fssm_wave64(f, code), split: false, mem_windows: windows, sampler_base }; let k = match (&mode, stage) { (Mode::Vertex(vs), Stage::Vertex) => crate::gpu::dxil::kernel::translate_vertex(code, o, vs)?, (Mode::Pixel(ps), Stage::Pixel) => crate::gpu::dxil::kernel::translate_pixel(code, o, ps)?, @@ -804,7 +804,7 @@ pub(crate) fn console_translation(blob: &[u8], stage: Stage, sampler_base: u32, }; let p = f.programs.first().ok_or("FSSM without a program")?; let code = &f.data[p.offset..p.offset + p.len]; - let t = translate(code, &Options { mode, wave64: super::detect_wave64(code), split_wave64, static_sampler_base: sampler_base, mem_windows: windows, ..Default::default() })?; + let t = translate(code, &Options { mode, wave64: super::fssm_wave64(f, code), split_wave64, static_sampler_base: sampler_base, mem_windows: windows, ..Default::default() })?; if !t.complete() { let missing: Vec<&String> = t.unsupported.keys().collect(); return Err(format!("incomplete translation, missing: {missing:?}")); @@ -897,7 +897,7 @@ fn console_mesh_with( let record = ms.clone(); let p = f.programs.first().ok_or("FSSM without a program")?; let code = &f.data[p.offset..p.offset + p.len]; - let wave64 = super::detect_wave64(code); + let wave64 = super::fssm_wave64(f, code); let split = wave64 && split_wave64; let compile_one = || compile(code, ms, wave64); // Cache the mesh compute pass in RAM (`ShaderCache` + in-flight coalescing) and on disk diff --git a/crates/xcl/src/gpu/xbox.rs b/crates/xcl/src/gpu/xbox.rs index 3986882b4..c34c07d75 100644 --- a/crates/xcl/src/gpu/xbox.rs +++ b/crates/xcl/src/gpu/xbox.rs @@ -18,6 +18,7 @@ //! +0x18 zlib stream → FSSM //! FSSM +0 "FSSM" +4 u32 version (0x101) +8 u32 size of everything after the 16-B header //! +0xC0 u64 code offset, +0xC8 u64 code size (offsets relative to +0x10) +//! +0xD4 u32 flags: bit 5 = the code is for 32-lane waves (wave32) //! +0x100 hardware-stage descriptor u64 0x000000C0_0002_AAHH //! (HH = PAL hardware stage, AA = API stage; one more every 0x88 B, //! e.g. GS + its VS copy shader); unused fields are 0xDEADBEEF. @@ -143,6 +144,13 @@ impl Fssm { } } + /// The header says the code is for 32-lane waves: bit 5 of the flags word at +0xD4 + /// (measured on a retail pack: set for every program with 32-bit EXEC writes, clear for + /// every one with 64-bit ones). An unused field (0xDEADBEEF) says nothing. + pub fn wave32(&self) -> bool { + self.version == 0x101 && rd32(&self.data, 0xD4).is_some_and(|w| w != 0xDEAD_BEEF && w & 0x20 != 0) + } + pub fn stage_label(&self) -> String { if self.stages.is_empty() { return "?".into(); @@ -799,6 +807,25 @@ pub(crate) mod tests { assert!(f.programs.iter().any(|p| p.offset == 0x308), "{:?}", f.programs); } + /// A wave32 program without an EXEC write (nothing in its code tells the wave size) is + /// wave32 by its header; a clear flag or an unused field leaves it to the code. + #[test] + fn wave_size_comes_from_the_header_flag() { + let wave64 = |flags: u32| { + let mut f = fssm(&CODE, &[(6, 5)]); + f[0xD4..0xD8].copy_from_slice(&flags.to_le_bytes()); + let sh = parse(&sample(5, &[f])).unwrap(); + let f = &sh.fssm[0]; + let p = &f.programs[0]; + (f.wave32(), crate::gpu::recomp::fssm_wave64(f, &f.data[p.offset..p.offset + p.len])) + }; + assert!(crate::gpu::recomp::detect_wave64(&CODE), "the code alone reads as wave64"); + assert_eq!(wave64(0x20), (true, false)); + assert_eq!(wave64(0x1F | 0x40), (false, true)); + assert_eq!(wave64(0), (false, true)); + assert_eq!(wave64(0xDEAD_BEEF), (false, true)); + } + #[test] fn pc_shaders_are_not_xbox() { assert!(parse(&container(&[(b"DXIL", b"\x66\0\0\0\x04\0\0\0DXIL\0\0\0\0")])).is_none()); diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 68ee30332..0193934c4 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1423,7 +1423,7 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on // as `pso` translates: with the title's memory windows (`console_translation`, // `translate_mesh`) let split = if matches!(mode, recomp::Mode::Vertex(_) | recomp::Mode::Pixel(_)) { graphics_split } else { split }; - let opt = recomp::Options { mode: mode.clone(), wave64: recomp::detect_wave64(code), split_wave64: split, mem_windows: windows, ..Default::default() }; + let opt = recomp::Options { mode: mode.clone(), wave64: recomp::fssm_wave64(f, code), split_wave64: split, mem_windows: windows, ..Default::default() }; let Ok(t) = recomp::translate(code, &opt) else { continue }; if !t.complete() { continue; @@ -2059,7 +2059,7 @@ fn direct_sweep(input: &Input, args: &[String], top: usize, json: bool, t0: std: skipped.fetch_add(1, Ordering::Relaxed); continue; } - let wave64 = recomp::detect_wave64(code); + let wave64 = recomp::fssm_wave64(f, code); let o = crate::gpu::dxil::kernel::KernelOptions { wave64, split: wave64 && split, mem_windows: windows, sampler_base: 0 }; if trace { eprintln!("direct: {name} FSSM#{fi} ({} B, {})", code.len(), coverage::stage_name(&mode)); diff --git a/crates/xcl/tests/gpu_compute_e2e.rs b/crates/xcl/tests/gpu_compute_e2e.rs index 0d37e0b84..e76ef65fb 100644 --- a/crates/xcl/tests/gpu_compute_e2e.rs +++ b/crates/xcl/tests/gpu_compute_e2e.rs @@ -26,12 +26,18 @@ fn le(v: &mut Vec, x: u32) { /// holds XBCH (zlib) → FSSM with `code` and a CS stage descriptor: COMPUTE_PGM_RSRC2 /// `rsrc2` at +0x38, numthreads at +0x3C. fn console_cs(code: &[u8], rsrc2: u32, threads: [u32; 3]) -> Vec { + console_cs_flags(code, rsrc2, threads, 0) +} + +/// `console_cs` with the FSSM header's flags word (+0xD4; bit 5 = wave32). +fn console_cs_flags(code: &[u8], rsrc2: u32, threads: [u32; 3], flags: u32) -> Vec { let code_at = 0x308usize; let mut fssm = vec![0u8; code_at]; fssm[0..4].copy_from_slice(b"FSSM"); fssm[4..8].copy_from_slice(&0x101u32.to_le_bytes()); fssm[0xC0..0xC8].copy_from_slice(&((code_at - 0x10) as u64).to_le_bytes()); fssm[0xC8..0xD0].copy_from_slice(&(code.len() as u64).to_le_bytes()); + fssm[0xD4..0xD8].copy_from_slice(&flags.to_le_bytes()); fssm[0x100..0x108].copy_from_slice(&0x0000_00C0_0002_0106u64.to_le_bytes()); // CS, API stage 1 for (k, x) in [rsrc2, threads[0], threads[1], threads[2]].into_iter().enumerate() { fssm[0x138 + 4 * k..0x13C + 4 * k].copy_from_slice(&x.to_le_bytes()); @@ -352,3 +358,68 @@ fn async_compute_pso_registers_real_pso_and_not_standin() { drop(pso); assert!(!real::is_translated_compute(real_raw), "forgetting released async compute PSO must clean up TRANSLATED_COMPUTE"); } + +/// A compute program without an EXEC write has nothing in its code that tells its wave size: +/// the FSSM header's wave32 flag does. 64 threads each store `v_readfirstlane` of the thread +/// id: in 32-lane waves threads 32..63 read thread 32, in a 64-lane wave all read thread 0. +#[test] +fn console_compute_without_an_exec_write_has_the_wave_size_of_its_header() { + let _serial = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + if xcl::gpu::recomp::dxc::location().is_err() { + runner::skip_test("no DXC"); + return; + } + if xcl::hle::d3d12x::backend() != xcl::hle::d3d12x::Backend::Real { + runner::skip_test("no GPU"); + return; + } + if runner::wave64_programs_supported() != Ok(true) { + runner::skip_test("no wave64"); + return; + } + let raw = real::device_raw(); + let dev = unsafe { ID3D12Device::from_raw_borrowed(&raw) }.unwrap().clone(); + let list: &[(&str, &str, &[(&str, u64)], Option)] = &[ + ("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", V)], None), // s4 = first thread of the wave + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 11), ("SRC0", 4)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 12), ("SRC0", V)], None), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 9), ("SRC0", 131), ("VSRC1", 0)], None), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 9), ("SRC0", 0), ("VSRC1", 9)], None), // + output base + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 10), ("SRC0", 128)], None), + ("GLOBAL_STORE_DWORDX2", "ENC_FLAT_GLBL", &[("ADDR", 9), ("DATA", 11), ("SADDR", 0x7D)], None), + ("S_ENDPGM", "ENC_SOPP", &[], None), + ]; + let code: Vec = list.iter().flat_map(|(n, e, f, l)| encode(n, e, f, *l).unwrap_or_else(|x| panic!("{n}: {x}"))).collect(); + assert!(xcl::gpu::recomp::detect_wave64(&code), "the code alone reads as wave64"); + for (flags, upper) in [(0u32, 0u32), (0x20, 32)] { + // user SGPRs 2, thread ids in v0 + let blob = console_cs_flags(&code, 2 << 1 | 1 << 11, [64, 1, 1], flags); + let game_rs: ID3D12RootSignature = unsafe { + let mut ser = None; + D3D12SerializeRootSignature(&D3D12_ROOT_SIGNATURE_DESC::default(), D3D_ROOT_SIGNATURE_VERSION_1, &mut ser, None).unwrap(); + let ser = ser.unwrap(); + dev.CreateRootSignature(0, std::slice::from_raw_parts(ser.GetBufferPointer() as *const u8, ser.GetBufferSize())).unwrap() + }; + let mut desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::ManuallyDrop::new(Some(game_rs)), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: blob.as_ptr() as _, BytecodeLength: blob.len() }, + ..Default::default() + }; + let pso: Result = unsafe { dev.CreateComputePipelineState(&desc) }; + unsafe { std::mem::ManuallyDrop::drop(&mut desc.pRootSignature) }; + let pso = pso.expect("CreateComputePipelineState through the backend hook"); + let real_raw = pso_async::resolve_wait(pso.as_raw() as usize) as *mut std::ffi::c_void; + assert!(real::is_translated_compute(real_raw as usize), "flags {flags:#x}: not built from the translated shader: {:?}", real::stats().translation_errors); + let pso = unsafe { ID3D12PipelineState::from_raw_borrowed(&real_raw) }.unwrap().clone(); + let rs_raw = real::pso_root_signature(pso.as_raw() as usize).expect("root signature of the translated PSO") as *mut std::ffi::c_void; + let rs = unsafe { ID3D12RootSignature::from_raw_borrowed(&rs_raw) }.unwrap().clone(); + let base = 0x100usize; + let mut io = vec![0u32; 128]; + io[0] = base as u32; + let out = runner::dispatch_on(&dev, &pso, &rs, [1, 1, 1], &io, &vec![0xFFFF_FFFFu32; (base + 64 * 8) / 4]).expect("dispatch"); + for t in 0..64usize { + let at = base / 4 + t * 2; + assert_eq!((out[at], out[at + 1]), (if t < 32 { 0 } else { upper }, t as u32), "flags {flags:#x}, thread {t}"); + } + } +}