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
73 changes: 72 additions & 1 deletion crates/xcl/src/gpu/recomp/dxc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -569,17 +569,35 @@ pub(super) fn toolchain_identity() -> &'static str {
}

/// FNV-1a 64 of the inputs that determine the DXIL.
#[cfg(test)]
fn cache_key_for_toolchain(src: &str, entry: &str, profile: &str, toolchain: &str) -> u64 {
cache_key_for_toolchain_extra(src, entry, profile, toolchain, &[])
}

fn cache_key_for_toolchain_extra(src: &str, entry: &str, profile: &str, toolchain: &str, extra: &[&str]) -> u64 {
let mut h = 0xcbf2_9ce4_8422_2325u64;
for part in [env!("CARGO_PKG_VERSION"), toolchain, profile, entry, src] {
for b in part.bytes().chain([0u8]) {
h ^= b as u64;
h = h.wrapping_mul(0x100_0000_01b3);
}
}
if !extra.is_empty() {
for part in std::iter::once("xcl-extra").chain(extra.iter().copied()) {
for b in part.bytes().chain([0u8]) {
h ^= b as u64;
h = h.wrapping_mul(0x100_0000_01b3);
}
}
}
h
}

pub(super) fn cache_key_with_extra(src: &str, entry: &str, profile: &str, extra: &[&str]) -> u64 {
cache_key_for_toolchain_extra(src, entry, profile, toolchain_identity(), extra)
}

#[cfg(test)]
fn cache_key(src: &str, entry: &str, profile: &str) -> u64 {
cache_key_for_toolchain(src, entry, profile, toolchain_identity())
}
Expand Down Expand Up @@ -665,6 +683,11 @@ pub fn compile_cached_in(dir: &Path, src: &str, entry: &str, profile: &str) -> R
compile_cached_in_with(dir, src, entry, profile, || compile(src, entry, profile, &[]))
}

/// Like `compile_cached_in`, keyed also by extra DXC flags such as `["-opt-disable", "gvn"]`.
pub fn compile_cached_in_with_extra(dir: &Path, src: &str, entry: &str, profile: &str, extra: &[&str]) -> Result<(Vec<u8>, bool), String> {
compile_cached_in_observed_with_extra(dir, src, entry, profile, extra, cache_counters(), || compile(src, entry, profile, extra))
}

type CacheFlight = (PathBuf, u64);

fn cache_flight(key: CacheFlight) -> Arc<Mutex<()>> {
Expand Down Expand Up @@ -804,7 +827,22 @@ fn compile_cached_in_observed<F>(
where
F: FnOnce() -> Result<Vec<u8>, String>,
{
let key = cache_key(src, entry, profile);
compile_cached_in_observed_with_extra(dir, src, entry, profile, &[], counters, compile_one)
}

fn compile_cached_in_observed_with_extra<F>(
dir: &Path,
src: &str,
entry: &str,
profile: &str,
extra: &[&str],
counters: &CacheCounters,
compile_one: F,
) -> Result<(Vec<u8>, bool), String>
where
F: FnOnce() -> Result<Vec<u8>, String>,
{
let key = cache_key_with_extra(src, entry, profile, extra);
let dir = normalized_cache_dir(dir);
let file = dir.join(format!("{key:016x}.dxil"));
if let Some(b) = cached_file(&file) {
Expand Down Expand Up @@ -921,6 +959,10 @@ pub fn compile_cached(src: &str, entry: &str, profile: &str) -> Result<(Vec<u8>,
compile_cached_in(&cache_dir(), src, entry, profile)
}

pub fn compile_cached_with_extra(src: &str, entry: &str, profile: &str, extra: &[&str]) -> Result<(Vec<u8>, bool), String> {
compile_cached_in_with_extra(&cache_dir(), src, entry, profile, extra)
}

#[cfg(test)]
mod cache_tests {
use super::*;
Expand Down Expand Up @@ -1043,6 +1085,35 @@ mod cache_tests {
assert_ne!(a, cache_key_for_toolchain("source", "main", "cs_6_6", "compiler-a/signer-b"));
}

#[test]
fn cache_key_tracks_extra_dxc_flags() {
let base = cache_key_for_toolchain("source", "main", "cs_6_6", "tc");
assert_eq!(base, cache_key_for_toolchain_extra("source", "main", "cs_6_6", "tc", &[]));
let nogvn = cache_key_for_toolchain_extra("source", "main", "cs_6_6", "tc", &["-opt-disable", "gvn"]);
assert_ne!(base, nogvn);
assert_ne!(nogvn, cache_key_for_toolchain_extra("source", "main", "cs_6_6", "tc", &["-O0"]));
}

#[test]
fn dxil_cache_with_extra_flags_round_trip() {
if location().is_err() {
crate::gpu::recomp::runner::skip_test("no DXC");
return;
}
let dir = std::env::temp_dir().join(format!("xcl-dxil-extra-test-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let src = "RWByteAddressBuffer o : register(u0);\n[numthreads(64, 1, 1)] void main(uint3 t : SV_DispatchThreadID) {\n uint a = o.Load(t.x * 4);\n uint b = (a & 1) ? o.Load(t.x * 4 + 256) : o.Load(t.x * 4 + 256) + 1;\n o.Store(t.x * 4, b);\n}";
let (default_dxil, hit0) = compile_cached_in(&dir, src, "main", "cs_6_6").unwrap();
let (nogvn_dxil, hit1) = compile_cached_in_with_extra(&dir, src, "main", "cs_6_6", &["-opt-disable", "gvn"]).unwrap();
assert!(!hit0 && !hit1);
assert!(valid_dxil_container(&default_dxil) && valid_dxil_container(&nogvn_dxil));
assert_ne!(default_dxil, nogvn_dxil, "-opt-disable gvn must change the compiled DXIL");
assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 2, "extra-flag build must use a distinct cache entry");
let (cached_nogvn, hit2) = compile_cached_in_with_extra(&dir, src, "main", "cs_6_6", &["-opt-disable", "gvn"]).unwrap();
assert!(hit2 && cached_nogvn == nogvn_dxil);
let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn validates_dxil_cache_structure_and_rebuilds_corruption() {
let valid = synthetic_dxil(7);
Expand Down
38 changes: 33 additions & 5 deletions crates/xcl/src/gpu/recomp/pso.rs
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,13 @@ pub struct Compiled {
pub samplers: Vec<StaticSampler>,
}

/// A no-GVN compilation and the disk-cache keys for both compiler variants.
pub struct WithoutGvn {
pub compiled: Compiled,
pub rejected_key: u64,
pub retry_key: u64,
}

/// Translate a console shader for `stage` to signed DXIL (DXC, disk-cached); its static
/// samplers take registers from `sampler_base` (space 1).
/// Fails when the blob is not a console shader or the program is not fully translated.
Expand All @@ -140,6 +147,18 @@ pub fn console_to_dxil_for(blob: &[u8], stage: Stage, sampler_base: u32, split_w
console_to_dxil_in(blob, stage, sampler_base, split_wave64, mem_windows())
}

/// Like `console_to_dxil_for`, disabling DXC's GVN pass for retrying driver-rejected shaders
/// without overwriting the default `ShaderCache` / `translated` entries.
pub fn console_to_dxil_without_gvn(blob: &[u8], stage: Stage, sampler_base: u32, split_wave64: bool) -> Result<WithoutGvn, String> {
console_to_dxil_in_without_gvn(blob, stage, sampler_base, split_wave64, mem_windows())
}

/// Like `console_to_dxil_in`, disabling DXC's GVN pass and using a distinct DXIL disk-cache key.
pub fn console_to_dxil_in_without_gvn(blob: &[u8], stage: Stage, sampler_base: u32, split_wave64: bool, windows: u32) -> Result<WithoutGvn, String> {
compile_console_shader_with_extra(blob, stage, sampler_base, windows, split_wave64, &["-opt-disable", "gvn"])
.map(|(compiled, _, rejected_key, retry_key)| WithoutGvn { compiled, rejected_key, retry_key })
}

/// Global in-memory cache for translated shaders shared by `console_to_dxil_in` and `console_mesh`.
fn shader_cache() -> &'static Mutex<ShaderCache> {
static CACHE: OnceLock<Mutex<ShaderCache>> = OnceLock::new();
Expand Down Expand Up @@ -446,6 +465,10 @@ fn enormous(stage: Stage, hlsl_len: usize) -> bool {
/// The program's DXIL, and whether it is an `enormous` one the direct translator made (its
/// disk cache entry then follows that translator's version: `translated::cached`).
fn compile_console_shader(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, split_wave64: bool) -> Result<(Compiled, bool), String> {
compile_console_shader_with_extra(blob, stage, sampler_base, windows, split_wave64, &[]).map(|(c, direct, _, _)| (c, direct))
}

fn compile_console_shader_with_extra(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, split_wave64: bool, extra: &[&str]) -> Result<(Compiled, bool, u64, u64), String> {
// `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() {
Expand All @@ -455,7 +478,7 @@ fn compile_console_shader(blob: &[u8], stage: Stage, sampler_base: u32, windows:
match direct_compute(blob, sampler_base, windows, split_wave64) {
Ok(c) => {
crate::gpu::dxil::coverage::record_translated("CS");
return Ok((c, false));
return Ok((c, false, 0, 0));
}
Err(e) => direct_fallback("CS", &e),
}
Expand All @@ -470,12 +493,15 @@ fn compile_console_shader(blob: &[u8], stage: Stage, sampler_base: u32, windows:
match direct_graphics(blob, stage, sampler_base, windows) {
Ok(c) => {
crate::gpu::dxil::coverage::record_translated(if stage == Stage::Vertex { "VS" } else { "PS" });
return Ok((c, false));
return Ok((c, false, 0, 0));
}
Err(e) => direct_fallback(if stage == Stage::Vertex { "VS" } else { "PS" }, &e),
}
}
let (mut t, profile) = console_translation(blob, stage, sampler_base, windows, split_wave64)?;
if !extra.is_empty() && extra.contains(&"-opt-disable") && t.hlsl.len() > 8 * 1024 * 1024 {
return Err("already compiled at -O0 without GVN".into());
}
if enormous(stage, t.hlsl.len()) && !crate::gpu::dxil::kernel::enabled() {
if dxc::defer() {
return Err("DXIL not compiled yet".into());
Expand All @@ -488,7 +514,7 @@ fn compile_console_shader(blob: &[u8], stage: Stage, sampler_base: u32, windows:
t.hlsl.len() >> 10,
c.dxil.len() >> 10
);
return Ok((c, true));
return Ok((c, true, 0, 0));
}
Err(e) => direct_fallback("CS", &e),
}
Expand Down Expand Up @@ -522,8 +548,10 @@ 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;
Ok((Compiled { dxil, samplers: t.static_samplers }, false))
let rejected_key = dxc::cache_key_with_extra(&t.hlsl, "main", profile, &[]);
let retry_key = dxc::cache_key_with_extra(&t.hlsl, "main", profile, extra);
let dxil = dxc::compile_cached_with_extra(&t.hlsl, "main", profile, extra)?.0;
Ok((Compiled { dxil, samplers: t.static_samplers }, false, rejected_key, retry_key))
}

/// Every `X_T.Sample(args)` of generated HLSL as `X_T.SampleLevel(args, 0.0f)`.
Expand Down
Loading
Loading