Skip to content
Open
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
140 changes: 133 additions & 7 deletions crates/xcl/src/gpu/recomp/pso.rs
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,9 @@ mod translated {
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(super) enum Backend {
Hlsl,
/// the HLSL path, huge compute programs (direct DXIL of at least this many bytes,
/// `huge_direct_min`) through the direct translator
HlslHugeDirect(usize),
/// direct DXIL for compute + the mesh pass (`=1`)
DirectCompute,
/// direct DXIL for VS / PS too (`=all`)
Expand All @@ -203,7 +206,7 @@ mod translated {
match (crate::gpu::dxil::kernel::enabled(), crate::gpu::dxil::kernel::enabled_graphics()) {
(_, true) => Backend::DirectAll,
(true, false) => Backend::DirectCompute,
_ => Backend::Hlsl,
_ => super::huge_direct_min().map_or(Backend::Hlsl, Backend::HlslHugeDirect),
}
}
}
Expand All @@ -214,9 +217,14 @@ mod translated {
let base = identity_for(source, toolchain);
let tag = match backend {
Backend::Hlsl => return base,
Backend::HlslHugeDirect(min) => return identity_tagged(base, &format!("huge-direct-{min}"), direct_version),
Backend::DirectCompute => "compute",
Backend::DirectAll => "all",
};
identity_tagged(base, tag, direct_version)
}

fn identity_tagged(base: u64, tag: &str, direct_version: u32) -> u64 {
let mut h = base;
for part in ["xcl-direct-dxil", tag, &direct_version.to_string()] {
for byte in part.bytes().chain([0]) {
Expand All @@ -227,18 +235,30 @@ mod translated {
h | 1
}

/// The backend whose identity tags `stage`'s entries: the huge-program route only ever
/// changes compute entries, so vertex / pixel entries keep the plain HLSL identity and
/// are not re-keyed by a bump of the direct translator's version.
pub(super) fn backend_for(backend: Backend, stage: Stage) -> Backend {
match backend {
Backend::HlslHugeDirect(_) if stage != Stage::Compute => Backend::Hlsl,
b => b,
}
}

/// Translation semantics and the DXC DLLs, independent of link metadata and build profile.
/// Zero means the disk cache is disabled.
fn identity() -> u64 {
static I: OnceLock<u64> = OnceLock::new();
*I.get_or_init(|| {
fn identity(stage: Stage) -> u64 {
static COMPUTE: OnceLock<u64> = OnceLock::new();
static OTHER: OnceLock<u64> = OnceLock::new();
let cell = if stage == Stage::Compute { &COMPUTE } else { &OTHER };
*cell.get_or_init(|| {
if std::env::var("XCL_TRANSLATED_CACHE").is_ok_and(|v| v == "0") {
return 0;
}
let id = identity_with(
env!("XCL_TRANSLATOR_SOURCE_ID"),
super::dxc::toolchain_identity(),
Backend::current(),
backend_for(Backend::current(), stage),
crate::gpu::dxil::kernel::TRANSLATOR_VERSION,
);
// `XCL_PER_LANE=1` (direct compute only): its entries under their own identity
Expand Down Expand Up @@ -341,7 +361,7 @@ mod translated {
split: bool,
translate: impl FnOnce() -> Result<Compiled, String>,
) -> Result<Compiled, String> {
cached_in(dir, identity(), blob, stage, sampler_base, windows, split, translate)
cached_in(dir, identity(stage), blob, stage, sampler_base, windows, split, translate)
}
}

Expand All @@ -351,6 +371,7 @@ fn compile_console_shader(blob: &[u8], stage: Stage, sampler_base: u32, windows:
// `XCL_DIRECT_DXIL=1`: compute shaders through the direct DXIL translator, the HLSL path
// for what it cannot translate yet
if stage == Stage::Compute && crate::gpu::dxil::kernel::enabled() {
defer_direct_compute()?;
match direct_compute(blob, sampler_base, windows, split_wave64) {
Ok(c) => {
crate::gpu::dxil::coverage::record_translated("CS");
Expand All @@ -359,6 +380,21 @@ fn compile_console_shader(blob: &[u8], stage: Stage, sampler_base: u32, windows:
Err(e) => direct_fallback("CS", &e),
}
}
// a huge compute program through the direct translator also without `XCL_DIRECT_DXIL`:
// the driver compiles its container 3 - 6x faster than DXC's (`huge_direct_min`)
if stage == Stage::Compute && !crate::gpu::dxil::kernel::enabled() {
if let Some(min) = huge_direct_min() {
defer_direct_compute()?;
match direct_compute(blob, sampler_base, windows, split_wave64) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] This path bypasses the cached-only/defer contract. real::attempt() wraps console_to_dxil_in in dxc::cached_only; when this direct translation returns a container at or above the threshold, the probe sees a successful compile without ever calling dxc::defer(). It therefore performs cold direct translation synchronously instead of returning the stand-in, defeating the async probe fix in #1788 (the guard there covers XCL_DIRECT_DXIL=1, while this branch runs with that flag off). Please check dxc::defer() before direct_compute and return the same DXIL not compiled yet miss; extend direct_compute_pso_cached_only to cover the default XCL_DIRECT_HUGE path.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, good catch. Fixed in 4bc5e40: both direct compute routes (the default huge-program route and XCL_DIRECT_DXIL=1) now call defer_direct_compute() before direct_compute. Inside dxc::cached_only that marks the miss via dxc::defer() and returns DXIL not compiled yet, so the probe hands out the stand-in and the build happens in the background instead of translating on the title's thread.

Since #1788's direct_compute_pso_cached_only isn't on main yet, I added a focused unit test here: pso::direct_probe_tests::direct_compute_routes_defer_inside_cached_only_probes. It calls compile_console_shader for a compute stage inside cached_only and asserts the miss is recorded and nothing is translated (the input isn't a console container, so any translation attempt would fail with a different error). It also checks that the same call outside a probe does reach the translator. It passes with the default route, with XCL_DIRECT_DXIL=1, and skips with XCL_DIRECT_HUGE=0. gpu::recomp: 200 passed, 0 failed. Once #1788 lands, its test can take a default-route case too.

AI use: Claude Code (Claude Opus 5.5) wrote this comment for @bmjask.

Ok(c) if c.dxil.len() >= min => {
crate::xlog_info!("[SHADER] huge compute program {:016x}: direct DXIL ({} B)", crate::gpu::shader::fnv64(blob), c.dxil.len());
return Ok(c);
}
Ok(_) => {}
Err(e) => crate::xlog_info!("[SHADER] huge-program direct DXIL unavailable: {}", e.lines().next().unwrap_or("")),
}
}
}
// `XCL_DIRECT_DXIL=all`: vertex / pixel shaders too (not with the PS debug hooks below)
let ps_debug = stage == Stage::Pixel
&& (debug_color(blob).is_some() || ["XCL_DEBUG_LOD0", "XCL_DEBUG_PS_SUB", "XCL_DEBUG_PS_EXPR"].iter().any(|v| std::env::var_os(v).is_some()));
Expand Down Expand Up @@ -593,6 +629,39 @@ pub fn console_hlsl(blob: &[u8], stage: Stage, windows: u32, split_wave64: bool)
console_translation(blob, stage, 0, windows, split_wave64).map(|(t, p)| (t.hlsl, p))
}

/// Direct DXIL size from which a compute program takes the direct translator by default
/// (no `XCL_DIRECT_DXIL`). Its containers are smaller than DXC's for the same program and
/// lack the HLSL path's per-access window `switch`es and helper inlining, so the driver
/// compiles them much faster (RTX 4090, cold: 11.7 s -> 1.8 s, 17.0 s -> 5.9 s,
/// 19.3 s -> 5.7 s for 107 - 264 KB containers). `XCL_DIRECT_HUGE=0` keeps every program on
/// the HLSL path, `XCL_DIRECT_HUGE=<KiB>` moves the threshold.
pub const HUGE_DIRECT_MIN_DEFAULT: usize = 64 << 10;

/// Inside a cached-only probe (`dxc::cached_only`, the non-blocking PSO path): a compute
/// program bound for the direct translator is not translated there – the translation caches
/// were already checked – but reported as not compiled yet (`dxc::defer` marks the miss), so
/// the probe hands out the stand-in and the build happens in the background. Without this a
/// cold direct translation of a huge program would run synchronously on the title's thread.
fn defer_direct_compute() -> Result<(), String> {
if dxc::defer() {
return Err("DXIL not compiled yet".into());
}
Ok(())
}

pub fn huge_direct_min() -> Option<usize> {
static V: OnceLock<Option<usize>> = OnceLock::new();
*V.get_or_init(|| huge_direct_min_from(std::env::var("XCL_DIRECT_HUGE").ok().as_deref()))
}

fn huge_direct_min_from(v: Option<&str>) -> Option<usize> {
match v.map(str::trim) {
None | Some("") | Some("1") => Some(HUGE_DIRECT_MIN_DEFAULT),
Some("0") => None,
Some(kib) => Some(kib.parse::<usize>().map_or(HUGE_DIRECT_MIN_DEFAULT, |k| k.max(1) << 10)),
}
}

/// A direct DXIL translation that fell back to the HLSL path: one structured log line
/// (`stage=… reason=…`, the reason with operands stripped) and the live summary counter
/// (`XCL_DIRECT_DXIL_STATS=1`, `gpu::dxil::coverage`).
Expand All @@ -603,7 +672,7 @@ fn direct_fallback(stage: &str, err: &str) {

/// A console compute shader through the direct DXIL translator (`gpu::dxil::kernel`).
/// FSPX (driver) containers are left to the HLSL path.
fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split_wave64: bool) -> Result<Compiled, String> {
pub(crate) fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split_wave64: bool) -> Result<Compiled, String> {
let sh = xbox::parse(blob).ok_or("not a console shader container")?;
let f = sh.fssm.iter().find(|f| f.stages.first().is_some_and(|s| s.hw == 6)).ok_or("no hardware CS variant")?;
let Some(Mode::Compute(cs)) = interface(blob, &sh, f) else { return Err("not a compute interface".into()) };
Expand Down Expand Up @@ -999,6 +1068,9 @@ mod shader_cache_tests {
hlsl,
identity_with("s", "t", Backend::DirectCompute, 1),
identity_with("s", "t", Backend::DirectAll, 1),
identity_with("s", "t", Backend::HlslHugeDirect(64 << 10), 1),
identity_with("s", "t", Backend::HlslHugeDirect(64 << 10), 2),
identity_with("s", "t", Backend::HlslHugeDirect(128 << 10), 1),
identity_with("s", "t", Backend::DirectCompute, 2),
identity_with("s2", "t", Backend::DirectCompute, 1),
identity_with("s", "t2", Backend::DirectCompute, 1),
Expand All @@ -1007,6 +1079,28 @@ mod shader_cache_tests {
assert_eq!(ids.iter().collect::<std::collections::HashSet<_>>().len(), ids.len());
}

#[test]
fn huge_direct_threshold_from_env() {
assert_eq!(huge_direct_min_from(None), Some(HUGE_DIRECT_MIN_DEFAULT));
assert_eq!(huge_direct_min_from(Some("1")), Some(HUGE_DIRECT_MIN_DEFAULT));
assert_eq!(huge_direct_min_from(Some("0")), None);
assert_eq!(huge_direct_min_from(Some(" 200 ")), Some(200 << 10));
assert_eq!(huge_direct_min_from(Some("junk")), Some(HUGE_DIRECT_MIN_DEFAULT));
}

#[test]
fn huge_route_tags_compute_entries_only() {
use translated::{backend_for, identity_with, Backend};
let huge = Backend::HlslHugeDirect(64 << 10);
assert_eq!(backend_for(huge, Stage::Compute), huge);
for stage in [Stage::Vertex, Stage::Pixel] {
assert_eq!(backend_for(huge, stage), Backend::Hlsl);
// a direct translator version bump leaves these entries' identity alone
assert_eq!(identity_with("s", "t", backend_for(huge, stage), 1), identity_with("s", "t", backend_for(huge, stage), 2));
}
assert_eq!(backend_for(Backend::DirectAll, Stage::Pixel), Backend::DirectAll);
}

/// Hit / miss through a temp cache dir: a direct entry is reused by the same identity and
/// is a miss for the HLSL identity (and the other way round) for the same request.
#[test]
Expand Down Expand Up @@ -1262,6 +1356,38 @@ mod shader_cache_tests {
}
}

#[cfg(test)]
mod direct_probe_tests {
use super::*;

/// The probe contract for both direct compute routes (`XCL_DIRECT_DXIL=1` and the default
/// huge-program route): inside `cached_only` nothing is translated – the blob below is not
/// even a console container, so any translation attempt would fail differently – and the
/// attempt counts as a miss; outside it the same call does translate (and fails to parse).
#[test]
fn direct_compute_routes_defer_inside_cached_only_probes() {
if !crate::gpu::dxil::kernel::enabled() && huge_direct_min().is_none() {
return crate::gpu::recomp::runner::skip_test("no direct compute route (XCL_DIRECT_HUGE=0)");
}
let blob = b"not a console shader";
let (r, missed) = dxc::cached_only(|| compile_console_shader(blob, Stage::Compute, 0, 1, false));
assert!(missed, "a cached-only probe must mark the direct route as not compiled yet");
assert_eq!(r.err().as_deref(), Some("DXIL not compiled yet"));
// outside a probe the direct route runs (this blob then fails in translation, not deferral)
let e = compile_console_shader(blob, Stage::Compute, 0, 1, false).err().unwrap_or_default();
assert_ne!(e, "DXIL not compiled yet");
assert!(!dxc::in_cached_only());
}

/// `defer_direct_compute` only defers inside a probe.
#[test]
fn defer_direct_compute_is_a_no_op_outside_probes() {
assert!(defer_direct_compute().is_ok());
let (r, missed) = dxc::cached_only(defer_direct_compute);
assert!(missed && r.is_err());
}
}

#[cfg(test)]
mod compile_time_bench {
use super::*;
Expand Down
21 changes: 17 additions & 4 deletions crates/xcl/src/shaders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1059,11 +1059,23 @@ fn measure_pso_result(input: &Input, hash: u64, repeat: usize, windows: u32, spl
unsafe { dev9.ShaderCacheControl(cache_kinds, D3D12_SHADER_CACHE_CONTROL_FLAG_DISABLE) }
.map_err(|e| Unavailable(format!("cannot disable the driver cache (Windows Developer Mode is required): {e}")))?;
let split = split.unwrap_or_else(|| recomp::pso::split_wave64_forced() || recomp::pso::wave32_only_for_device(&pipeline.dev));
let (translation, profile) = recomp::pso::console_translation(&blob, recomp::pso::Stage::Compute, 0, windows, split).map_err(|e| Failed(format!("{name}: {e}")))?;
let dxc_start = std::time::Instant::now();
let dxil = recomp::dxc::compile(&translation.hlsl, "main", profile, &[]).map_err(|e| Failed(format!("DXC: {e}")))?;
// `XCL_DIRECT_DXIL=1`: the direct translator's container instead (no HLSL fallback, so the
// number is never silently the other path's)
let (dxil, samplers) = if crate::gpu::dxil::kernel::enabled() {
let c = recomp::pso::direct_compute(&blob, 0, windows, split).map_err(|e| Failed(format!("{name}: direct: {e}")))?;
(c.dxil, c.samplers)
} else {
let (translation, profile) = recomp::pso::console_translation(&blob, recomp::pso::Stage::Compute, 0, windows, split).map_err(|e| Failed(format!("{name}: {e}")))?;
let dxil = recomp::dxc::compile(&translation.hlsl, "main", profile, &[]).map_err(|e| Failed(format!("DXC: {e}")))?;
(dxil, translation.static_samplers)
};
let dxc_ms = dxc_start.elapsed().as_millis();
let rs = recomp::pso::abi_root_signature_with(&pipeline.dev, true, &translation.static_samplers).map_err(|e| Failed(format!("root signature: {e}")))?;
// `XCL_MEASURE_DUMP=<dir>`: the measured container as <hash>.<path>.dxil there
if let Ok(dir) = std::env::var("XCL_MEASURE_DUMP") {
let _ = std::fs::write(Path::new(&dir).join(format!("{hash:016x}.{}.dxil", if crate::gpu::dxil::kernel::enabled() { "direct" } else { "hlsl" })), &dxil);
}
let rs = recomp::pso::abi_root_signature_with(&pipeline.dev, true, &samplers).map_err(|e| Failed(format!("root signature: {e}")))?;
let mut desc = D3D12_COMPUTE_PIPELINE_STATE_DESC {
pRootSignature: std::mem::ManuallyDrop::new(Some(rs)),
CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr().cast(), BytecodeLength: dxil.len() },
Expand Down Expand Up @@ -1093,7 +1105,8 @@ fn measure_pso_result(input: &Input, hash: u64, repeat: usize, windows: u32, spl
times.sort_by(f64::total_cmp);
let median = if times.len() & 1 == 0 { (times[times.len() / 2 - 1] + times[times.len() / 2]) / 2.0 } else { times[times.len() / 2] };
println!(
"PSO {hash:016x}: {} bytes DXIL, {dxc_ms} ms DXC, {repeat} cache-off run(s), median {:.3} s, min {:.3} s, max {:.3} s, {name}",
"PSO {hash:016x} [{}]: {} bytes DXIL, {dxc_ms} ms translate, {repeat} cache-off run(s), median {:.3} s, min {:.3} s, max {:.3} s, {name}",
if crate::gpu::dxil::kernel::enabled() { "direct" } else { "hlsl" },
dxil.len(),
median,
times[0],
Expand Down
Loading