Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
533 changes: 533 additions & 0 deletions crates/xcl/src/gpu/recomp/lift.rs

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions crates/xcl/src/gpu/recomp/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ pub mod cfg;
pub mod dxc;
pub mod dxil;
pub mod lane_masks;
pub mod lift;
pub mod lower;
pub mod lower_dxil;
pub(crate) mod emit;
Expand Down
73 changes: 54 additions & 19 deletions crates/xcl/src/gpu/recomp/pso.rs
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,9 @@ pub struct Compiled {
pub dxil: Vec<u8>,
pub samplers: Vec<StaticSampler>,
pub dispatch_remap: Option<(u32, u32)>,
/// a lifted compute program's literals (`lift`): its dispatches write them to `io` from
/// `lift::IO_LIFTED` on. Empty for any other program.
pub lifted: Vec<u32>,
}

/// Translate a console shader for `stage` to signed DXIL (DXC, disk-cached); its static
Expand Down Expand Up @@ -264,6 +267,11 @@ fn console_to_dxil_in_with(blob: &[u8], stage: Stage, sampler_base: u32, split_w
rt32_mask,
cache_dir: dxc::cache_dir(),
};
// a member of a literal family (`lift`) is translated again rather than read from the disk
// cache, which keeps no lifted values (an entry stored without lifting would stay unlifted)
if stage == Stage::Compute && super::lift::lookup(key.hash, windows, split_wave64).is_some() {
return cached_shader(shader_cache(), key, blob, || compile_one().map(|(c, _)| c)).map(|shader| shader.as_ref().clone());
}
// with `XCL_DIRECT_DXIL` the disk entries live under their own identity (backend tag,
// direct translator version, routing mode): never mixed with the HLSL path's entries
let from_disk = || translated::cached_for(&dxc::cache_dir(), blob, stage, sampler_base, windows, split_wave64, rt32_mask, compile_one);
Expand Down Expand Up @@ -452,7 +460,7 @@ mod translated {
let start = b.len() - len;
b.copy_within(start.., 0);
b.truncate(len);
return Some(Compiled { dxil: b, samplers, dispatch_chain: None, dispatch_remap });
return Some(Compiled { lifted: Vec::new(), dxil: b, samplers, dispatch_chain: None, dispatch_remap });
} else {
let dwords_per_group = u32_(&mut rest)?;
let count = u32_(&mut rest)?;
Expand All @@ -469,7 +477,7 @@ mod translated {
if !rest.is_empty() { return None; }
Some(std::sync::Arc::new(crate::gpu::dxil::kernel::DispatchChain { dwords_per_group, pieces }))
};
Some(Compiled { dxil: whole.to_vec(), samplers, dispatch_chain, dispatch_remap })
Some(Compiled { lifted: Vec::new(), dxil: whole.to_vec(), samplers, dispatch_chain, dispatch_remap })
}

pub(super) fn store_in(path: &Path, ident: u64, blob: &[u8], c: &Compiled) {
Expand Down Expand Up @@ -872,11 +880,22 @@ fn compile_console_shader(blob: &[u8], stage: Stage, sampler_base: u32, windows:
}) {
t.hlsl = t.hlsl.replacen(" if (!xcl_live) discard;\n return xo;\n}", &format!(" xo.t0 = {expr};\n return xo;\n}}"), 1);
}
let dxil = dxc::compile_cached(&t.hlsl, "main", profile)?.0;
// a member of a literal family: the family's one text, with this member's literals in `io`
// (if DXC refuses it, the program as it is)
let lifted = (stage == Stage::Compute && cs_subs.is_none()).then(|| super::lift::apply(blob, windows, split_wave64, &t.hlsl)).flatten();
let (dxil, lifted) = match lifted.map(|(text, values)| (dxc::compile_cached(&text, "main", profile), values)) {
Some((Ok((dxil, ..)), values)) => (dxil, values),
other => {
if let Some((Err(e), _)) = other {
crate::xlog_warn!("[SHADER] {:016x}: lifted literals do not compile, translated as it is: {}", crate::gpu::shader::fnv64(blob), e.lines().next().unwrap_or(""));
}
(dxc::compile_cached(&t.hlsl, "main", profile)?.0, Vec::new())
}
};
if stage == Stage::Compute {
note_compute_path(blob, if cs_subs.is_some() { "HLSL, with XCL_DEBUG_CS_SUB" } else { "HLSL" });
note_compute_path(blob, if cs_subs.is_some() { "HLSL, with XCL_DEBUG_CS_SUB" } else if lifted.is_empty() { "HLSL" } else { "HLSL, literals lifted" });
}
Ok((Compiled { dispatch_chain: None, dxil, samplers: t.static_samplers, dispatch_remap: t.dispatch_remap }, false))
Ok((Compiled { lifted, dispatch_chain: None, dxil, samplers: t.static_samplers, dispatch_remap: t.dispatch_remap }, false))
}

/// `XCL_DEBUG_PS_SUB` / `XCL_DEBUG_CS_SUB` = `hash:from=>to||from=>to…` (a dump hash, hex): the
Expand Down Expand Up @@ -1299,7 +1318,7 @@ pub(crate) fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split
Ok(k) => {
crate::gpu::dxil::coverage::record_translated("CS per-lane");
dump_direct(blob, &k.dxil);
return Ok(Compiled { dispatch_chain: None, dxil: k.dxil, samplers: k.static_samplers, dispatch_remap: None });
return Ok(Compiled { lifted: Vec::new(), dispatch_chain: None, dxil: k.dxil, samplers: k.static_samplers, dispatch_remap: None });
}
Err(e) => {
let reason = crate::gpu::dxil::coverage::record_fallback("CS per-lane", &e);
Expand All @@ -1309,7 +1328,7 @@ pub(crate) fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split
}
let k = crate::gpu::dxil::kernel::translate_compute_rodata(code, o, &cs, &rodata)?;
dump_direct(blob, &k.dxil);
Ok(Compiled { dispatch_chain: k.dispatch_chain, dxil: k.dxil, samplers: k.static_samplers, dispatch_remap: None })
Ok(Compiled { lifted: Vec::new(), dispatch_chain: k.dispatch_chain, dxil: k.dxil, samplers: k.static_samplers, dispatch_remap: None })
}

/// `XCL_DXIL_DUMP=<hash>[,<hash>…]` (`[SHADER]` hashes, or `all`): writes the direct path's
Expand Down Expand Up @@ -1346,7 +1365,19 @@ fn direct_graphics(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, s
};
let k = crate::gpu::dxil::kernel::translate_entry_rodata_rt32(code, o, entry, &f.rodata(p), if stage == Stage::Pixel { rt32_mask } else { 0 })?;
dump_direct(blob, &k.dxil);
Ok(Compiled { dispatch_chain: None, dxil: k.dxil, samplers: k.static_samplers, dispatch_remap: None })
Ok(Compiled { lifted: Vec::new(), dispatch_chain: None, dxil: k.dxil, samplers: k.static_samplers, dispatch_remap: None })
}

/// `f` of a compute program's code (its FSPX code or its compute variant's first program).
/// None: not a compute program.
pub(crate) fn with_compute_code<R>(blob: &[u8], f: impl FnOnce(&[u8]) -> R) -> Option<R> {
if let Some(x) = fspx(blob) {
return Some(f(x.code));
}
let sh = xbox::parse(blob)?;
let v = sh.fssm.iter().find(|v| v.stages.first().is_some_and(|s| s.hw == 6))?;
let p = v.programs.first()?;
Some(f(v.data.get(p.offset..p.offset + p.len)?))
}

pub(crate) fn console_translation(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, split_wave64: bool, no_remap: bool) -> Result<(super::Translation, &'static str), String> {
Expand Down Expand Up @@ -1425,7 +1456,7 @@ fn finish_two_pass(t: super::Translation, record: super::MsInterface, ps: Option
return Err(format!("incomplete translation, missing: {missing:?}"));
}
let cs = dxc::compile_cached(&t.hlsl, "main", "cs_6_6")?.0;
finish_two_pass_compiled(Compiled { dispatch_chain: None, dxil: cs, samplers: t.static_samplers, dispatch_remap: None }, record, ps)
finish_two_pass_compiled(Compiled { lifted: Vec::new(), dispatch_chain: None, dxil: cs, samplers: t.static_samplers, dispatch_remap: None }, record, ps)
}

fn compile_console_mesh(
Expand All @@ -1452,7 +1483,7 @@ fn compile_console_mesh(
Ok(k) => {
crate::gpu::dxil::coverage::record_translated("MS");
dump_direct(blob, &k.dxil);
return Ok(Compiled { dispatch_chain: None, dxil: k.dxil, samplers: k.static_samplers, dispatch_remap: None });
return Ok(Compiled { lifted: Vec::new(), dispatch_chain: None, dxil: k.dxil, samplers: k.static_samplers, dispatch_remap: None });
}
Err(e) => direct_fallback("MS", &e),
}
Expand All @@ -1463,7 +1494,7 @@ fn compile_console_mesh(
return Err(format!("incomplete translation, missing: {missing:?}"));
}
let dxil = dxc::compile_cached(&t.hlsl, "main", "cs_6_6")?.0;
Ok(Compiled { dispatch_chain: None, dxil, samplers: t.static_samplers, dispatch_remap: None })
Ok(Compiled { lifted: Vec::new(), dispatch_chain: None, dxil, samplers: t.static_samplers, dispatch_remap: None })
}

fn console_mesh_with(
Expand Down Expand Up @@ -2030,7 +2061,7 @@ mod shader_cache_tests {
fn translations_on_disk_need_the_same_bytes_and_identity() {
let dir = std::env::temp_dir().join(format!("xcl-translated-{}", std::process::id()));
let path = dir.join("t.bin");
let c = Compiled { dispatch_chain: None, dxil: synthetic_dxil(5), samplers: vec![([7, 8, 9, 10], true), ([1, 2, 3, 4], false)], dispatch_remap: Some((2, 1)) };
let c = Compiled { lifted: Vec::new(), dispatch_chain: None, dxil: synthetic_dxil(5), samplers: vec![([7, 8, 9, 10], true), ([1, 2, 3, 4], false)], dispatch_remap: Some((2, 1)) };
translated::store_in(&path, 42, b"console", &c);
let back = translated::load_in(&path, 42, b"console").expect("stored");
assert_eq!((back.dxil, back.samplers, back.dispatch_remap), (c.dxil.clone(), c.samplers.clone(), c.dispatch_remap));
Expand Down Expand Up @@ -2276,7 +2307,7 @@ mod shader_cache_tests {

// Store a valid entry first, then corrupt only the DXIL payload while keeping the
// XCLTRAN2 header and payload length intact (e.g. zeroed blocks after a hard reset).
let valid = Compiled { dispatch_chain: None, dxil: synthetic_dxil(1), samplers: vec![([1, 2, 3, 4], false)], dispatch_remap: None };
let valid = Compiled { lifted: Vec::new(), dispatch_chain: None, dxil: synthetic_dxil(1), samplers: vec![([1, 2, 3, 4], false)], dispatch_remap: None };
translated::store_in(&path, ident, blob, &valid);
let mut raw = std::fs::read(&path).unwrap();
let dxil_start = raw.len() - valid.dxil.len();
Expand All @@ -2295,7 +2326,7 @@ mod shader_cache_tests {
let mut calls = 0usize;
let rebuilt = translated::cached_in(&dir, ident, blob, Stage::Compute, 0, 1, false, || {
calls += 1;
Ok(Compiled { dispatch_chain: None, dxil: synthetic_dxil(9), samplers: vec![([5, 6, 7, 8], true)], dispatch_remap: None })
Ok(Compiled { lifted: Vec::new(), dispatch_chain: None, dxil: synthetic_dxil(9), samplers: vec![([5, 6, 7, 8], true)], dispatch_remap: None })
})
.unwrap();
assert_eq!(calls, 1);
Expand All @@ -2319,20 +2350,20 @@ mod shader_cache_tests {
let path = translated::file(&dir, ident, blob, Stage::Compute, 0, 1, false);

let err = translated::cached_in(&dir, ident, blob, Stage::Compute, 0, 1, false, || {
Ok(Compiled { dispatch_chain: None, dxil: b"not DXIL".to_vec(), samplers: Vec::new(), dispatch_remap: None })
Ok(Compiled { lifted: Vec::new(), dispatch_chain: None, dxil: b"not DXIL".to_vec(), samplers: Vec::new(), dispatch_remap: None })
})
.err()
.expect("invalid fresh DXIL must be rejected");
assert!(err.contains("invalid DXIL container"), "{err}");
assert!(!path.exists(), "invalid fresh DXIL must not be written to disk");

translated::store_in(&path, ident, blob, &Compiled { dispatch_chain: None, dxil: b"not DXIL".to_vec(), samplers: Vec::new(), dispatch_remap: None });
translated::store_in(&path, ident, blob, &Compiled { lifted: Vec::new(), dispatch_chain: None, dxil: b"not DXIL".to_vec(), samplers: Vec::new(), dispatch_remap: None });
assert!(!path.exists(), "store_in must not write an invalid DXIL container");

// A real container emitted by the direct DXIL backend must be accepted and cached.
let real_direct = crate::gpu::dxil::shader::Shader::new(crate::gpu::dxil::container::Stage::Compute, (6, 6)).finish([1, 1, 1], None);
let stored = translated::cached_in(&dir, ident, blob, Stage::Compute, 0, 1, false, || {
Ok(Compiled { dispatch_chain: None, dxil: real_direct.clone(), samplers: Vec::new(), dispatch_remap: None })
Ok(Compiled { lifted: Vec::new(), dispatch_chain: None, dxil: real_direct.clone(), samplers: Vec::new(), dispatch_remap: None })
})
.unwrap();
assert_eq!(stored.dxil, real_direct);
Expand All @@ -2346,6 +2377,7 @@ mod shader_cache_tests {

fn compiled(marker: u8) -> Compiled {
Compiled {
lifted: Vec::new(),
dispatch_chain: None,
dxil: synthetic_dxil(marker),
samplers: vec![([marker as u32; 4], false)],
Expand Down Expand Up @@ -2488,6 +2520,7 @@ mod shader_cache_tests {
cached_shader(&cache, key(1), b"a", || {
let dxil = dxc::compile_cached_in(&dir, "probe", "main", "cs_6_6")?.0;
Ok(Compiled {
lifted: Vec::new(),
dispatch_chain: None,
dxil,
samplers: Vec::new(),
Expand Down Expand Up @@ -2523,6 +2556,7 @@ mod shader_cache_tests {
key(4),
b"d",
Arc::new(Compiled {
lifted: Vec::new(),
dispatch_chain: None,
dxil: vec![0; limit + 1],
samplers: Vec::new(),
Expand Down Expand Up @@ -2728,6 +2762,7 @@ mod shader_cache_tests {
let dxil =
dxc::compile_cached_in(&dir, "pending probe", "main", "cs_6_6")?.0;
Ok(Compiled {
lifted: Vec::new(),
dispatch_chain: None,
dxil,
samplers: Vec::new(),
Expand Down Expand Up @@ -2820,7 +2855,7 @@ mod shader_cache_tests {
let (res, missed) = dxc::cached_only(|| {
translated::cached_in(&dir, ident_v1, deferred_blob, Stage::Compute, 0, 1, false, || {
let dxil = dxc::compile_cached_in(&dir, "deferred probe", "main", "cs_6_6")?.0;
Ok(Compiled { dxil, samplers: Vec::new(), dispatch_chain: None, dispatch_remap: None })
Ok(Compiled { lifted: Vec::new(), dxil, samplers: Vec::new(), dispatch_chain: None, dispatch_remap: None })
})
});
assert!(res.is_err() && missed);
Expand Down Expand Up @@ -2968,7 +3003,7 @@ mod direct_probe_tests {
let cache = Mutex::new(ShaderCache::new(1 << 20));
let k0 = ShaderKey { hash: 99, stage: Stage::Pixel, sampler_base: 0, windows: 1, split_wave64: false, rt32_mask: 0, cache_dir: "cache".into() };
let k1 = ShaderKey { rt32_mask: 1 << 1, ..k0.clone() };
let mk = |m: u8| Compiled { dispatch_chain: None, dxil: vec![m; 68], samplers: Vec::new(), dispatch_remap: None };
let mk = |m: u8| Compiled { lifted: Vec::new(), dispatch_chain: None, dxil: vec![m; 68], samplers: Vec::new(), dispatch_remap: None };
let a = cached_shader(&cache, k0, blob, || Ok(mk(1))).unwrap();
let b = cached_shader(&cache, k1, blob, || Ok(mk(2))).unwrap();
assert!(!Arc::ptr_eq(&a, &b));
Expand Down
3 changes: 2 additions & 1 deletion crates/xcl/src/gpu/recomp/runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1825,7 +1825,8 @@ fn dispatch_with(
chain: Option<(&[ID3D12PipelineState], u32, u64)>,
) -> Result<(Vec<u32>, Vec<f64>), String> {
let mut io = sgprs.to_vec();
io.resize(KERNEL_SGPRS, 0);
// (more than the SGPRs: a lifted program's literals after them, `lift::IO_LIFTED`)
io.resize(io.len().max(KERNEL_SGPRS), 0);
let mem_len = mem.len().max(64);
unsafe {
let (io_bytes, mem_bytes) = ((io.len() * 4) as u64, (mem_len * 4) as u64);
Expand Down
48 changes: 48 additions & 0 deletions crates/xcl/src/gpu/recomp/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12422,3 +12422,51 @@ fn geometry_padding_before_gs_start_keeps_its_entry() {
assert!(t.hlsl.contains(&format!("if (pc == {s}u)")), "split {split}: {}", t.hlsl);
}
}

/// Two programs that differ only in their literals (`lift`): lifted, they are one HLSL text and
/// one DXIL container, and each gives on the GPU what it gives as it is, with its own literals
/// in `io` after the SGPRs.
#[test]
fn gpu_lifted_literal_family_shares_dxil_and_keeps_results() {
if !gpu_ready() {
return;
}
use super::{dxc, lift, CsInterface};
let cs = CsInterface { threads: [64, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1 };
let program = |a: u32, b: u32| prog(&[
("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 130), ("VSRC1", 0)], None), // lane · 4
("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 0), ("VSRC1", 2)], None), // + output base
("V_MOV_B32", "ENC_VOP1", &[("VDST", 3), ("SRC0", 128)], None),
("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 255)], Some(a)),
("V_XOR_B32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 255), ("VSRC1", 4)], Some(b)),
("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 4), ("SRC0", V), ("VSRC1", 4)], None), // + lane
("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 2), ("DATA", 4), ("SADDR", 0x7D)], None),
]);
let opt = on_gpu(Options { mode: Mode::Compute(cs), wave64: true, ..Default::default() });
let members = [(0x3F01_8182u32, 0x0000_1234u32), (0x3B80_8081, 0x00AB_0000)];
let hlsl: Vec<String> = members.iter().map(|&(a, b)| {
let t = translate(&program(a, b), &opt).unwrap();
assert!(t.complete(), "{:?}", t.unsupported_why);
t.hlsl
}).collect();
assert_eq!(lift::masked_hash(&hlsl[0]), lift::masked_hash(&hlsl[1]), "one family");
let positions = lift::varying(&[&hlsl[0], &hlsl[1]]).unwrap_or_else(|| panic!("nothing liftable in:\n{}", hlsl[0]));
let lifted: Vec<(String, Vec<u32>)> = hlsl.iter().map(|h| lift::rewrite(h, &positions).unwrap()).collect();
assert_eq!(lifted[0].0, lifted[1].0, "one text");
let shared = dxc::compile(&lifted[0].0, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", lifted[0].0));
assert_eq!(shared, dxc::compile(&lifted[1].0, "main", "cs_6_6", &[]).unwrap(), "one DXIL container");
let base = 0x100usize;
for (k, &(a, b)) in members.iter().enumerate() {
let plain = dxc::compile(&hlsl[k], "main", "cs_6_6", &[]).unwrap();
let mut io = vec![0u32; lift::IO_LIFTED];
io[0] = base as u32;
let as_is = runner::dispatch(&plain, [1, 1, 1], &io, &vec![0u32; base / 4 + 64]).unwrap();
io.extend_from_slice(&lifted[k].1);
let out = runner::dispatch(&shared, [1, 1, 1], &io, &vec![0u32; base / 4 + 64]).unwrap();
for lane in 0..64 {
let at = base / 4 + lane;
assert_eq!(as_is[at], (a ^ b).wrapping_add(lane as u32), "member {k}, lane {lane}: as it is");
assert_eq!(out[at], as_is[at], "member {k}, lane {lane}: lifted");
}
}
}
Loading
Loading