From dd43765097194ab84e82b811de3990bd70241387 Mon Sep 17 00:00:00 2001 From: Alp Pesen <5701011+AlpPesen@users.noreply.github.com> Date: Fri, 27 Nov 2026 02:02:59 +0300 Subject: [PATCH] Shaders: cache normalized DXIL cache dir and passthrough DXIL in RAM dxc::compile_cached_in_observed previously called std::fs::canonicalize via normalized_cache_dir on every shader lookup, and finish_two_pass_compiled / rect_list_gs re-read and re-validated passthrough DXIL from disk on every two-pass MS/GS or rect-list PSO build. Cache canonicalized existing cache directories in dxc.rs and cache compiled passthrough DXIL (ms_6_6 / gs_6_6) in RAM in pso.rs. Fixes #2885. Assisted-by: Antigravity (Gemini 4 Neon) --- crates/xcl/src/gpu/recomp/dxc.rs | 68 +++++++++++++++++++++++++-- crates/xcl/src/gpu/recomp/pso.rs | 80 +++++++++++++++++++++++++++++--- 2 files changed, 138 insertions(+), 10 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/dxc.rs b/crates/xcl/src/gpu/recomp/dxc.rs index 379bd8518f..079187c73f 100644 --- a/crates/xcl/src/gpu/recomp/dxc.rs +++ b/crates/xcl/src/gpu/recomp/dxc.rs @@ -816,13 +816,32 @@ fn cache_mutex_name(file: &Path) -> String { format!(r"Local\XclDxilCache-{h:016x}") } -fn normalized_cache_dir(dir: &Path) -> PathBuf { - if let Ok(canonical) = std::fs::canonicalize(dir) { +/// Canonicalize `dir` (or its deepest existing ancestor) for cache mutex/flight keys. +/// Keys the in-memory cache by `std::path::absolute(dir)` so relative `XCL_DXIL_CACHE` paths +/// still resolve cleanly if the process working directory changes. Mid-process symlink or +/// junction re-pointing of an already-cached directory is not handled. +fn normalized_cache_dir_in( + cache: &Mutex>, + dir: &Path, + canonicalize: impl Fn(&Path) -> std::io::Result, +) -> PathBuf { + let absolute = std::path::absolute(dir).unwrap_or_else(|_| dir.to_path_buf()); + if absolute.is_absolute() { + if let Some(hit) = cache.lock().unwrap_or_else(|e| e.into_inner()).get(&absolute).cloned() { + return hit; + } + } + if let Ok(canonical) = canonicalize(&absolute) { + if absolute.is_absolute() { + let mut g = cache.lock().unwrap_or_else(|e| e.into_inner()); + if g.len() < 64 { + g.insert(absolute, canonical.clone()); + } + } return canonical; } - let absolute = std::path::absolute(dir).unwrap_or_else(|_| dir.to_path_buf()); for ancestor in absolute.ancestors().skip(1) { - if let Ok(canonical) = std::fs::canonicalize(ancestor) { + if let Ok(canonical) = canonicalize(ancestor) { if let Ok(remainder) = absolute.strip_prefix(ancestor) { return canonical.join(remainder); } @@ -831,6 +850,17 @@ fn normalized_cache_dir(dir: &Path) -> PathBuf { absolute } +pub(crate) fn normalized_cache_dir(dir: &Path) -> PathBuf { + static CACHE: OnceLock>> = OnceLock::new(); + normalized_cache_dir_in(CACHE.get_or_init(|| Mutex::new(HashMap::new())), dir, |p| std::fs::canonicalize(p)) +} + +/// Record a DXIL cache hit served from an upper in-memory layer (e.g. passthrough DXIL cache) +/// so `cache_counters()` / `XCL_ACTIVITY` stats remain accurate. +pub(crate) fn record_cache_hit() { + cache_counters().hits.fetch_add(1, Ordering::Relaxed); +} + fn process_cache_lock(file: &Path) -> Result { use windows_sys::Win32::Foundation::{CloseHandle, WAIT_ABANDONED, WAIT_OBJECT_0}; use windows_sys::Win32::System::Threading::{CreateMutexW, WaitForSingleObject, INFINITE}; @@ -1619,4 +1649,34 @@ mod accessor_library_tests { assert!(!gate.open()); assert!(!gate.close()); } + + #[test] + fn normalized_cache_dir_caches_existing_dir_and_retries_missing() { + let cache = Mutex::new(HashMap::new()); + let dir = PathBuf::from(r"C:\fake\cache"); + let calls = std::sync::atomic::AtomicUsize::new(0); + let first = normalized_cache_dir_in(&cache, &dir, |_| { + calls.fetch_add(1, Ordering::Relaxed); + Ok(PathBuf::from(r"\\?\C:\fake\cache")) + }); + let second = normalized_cache_dir_in(&cache, &dir, |_| panic!("existing dir should hit normalized cache")); + assert_eq!(first, PathBuf::from(r"\\?\C:\fake\cache")); + assert_eq!(first, second); + assert_eq!(calls.load(Ordering::Relaxed), 1); + + let missing = PathBuf::from(r"C:\fake\missing_dir_xyz"); + let miss_calls = std::sync::atomic::AtomicUsize::new(0); + let _ = normalized_cache_dir_in(&cache, &missing, |_| { + miss_calls.fetch_add(1, Ordering::Relaxed); + Err(std::io::Error::new(std::io::ErrorKind::NotFound, "missing")) + }); + let after_first = miss_calls.load(Ordering::Relaxed); + assert!(after_first >= 1); + let _ = normalized_cache_dir_in(&cache, &missing, |_| { + miss_calls.fetch_add(1, Ordering::Relaxed); + Err(std::io::Error::new(std::io::ErrorKind::NotFound, "missing")) + }); + assert!(cache.lock().unwrap().get(&missing).is_none(), "non-existent dir must not be cached"); + assert!(miss_calls.load(Ordering::Relaxed) > after_first, "missing dir must retry canonicalize on second lookup"); + } } diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 5d000775ef..1b5a0422d7 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -1071,9 +1071,45 @@ pub struct TwoPass { pub samplers: Vec, } +type PassthroughKey = (PathBuf, &'static str, String); + +fn compile_passthrough_cached_in( + cache: &Mutex>>, + cache_dir: PathBuf, + hlsl: &str, + profile: &'static str, + on_hit: impl FnOnce(), + compile: impl FnOnce() -> Result, String>, +) -> Result, String> { + let key = (cache_dir, profile, hlsl.to_string()); + if let Some(hit) = cache.lock().unwrap_or_else(|e| e.into_inner()).get(&key).cloned() { + on_hit(); + return Ok(hit); + } + let dxil = compile()?; + let mut g = cache.lock().unwrap_or_else(|e| e.into_inner()); + if g.len() < 256 { + g.insert(key, dxil.clone()); + } + Ok(dxil) +} + +fn compile_passthrough_cached(hlsl: &str, profile: &'static str) -> Result, String> { + static CACHE: std::sync::OnceLock>>> = std::sync::OnceLock::new(); + let dir = dxc::normalized_cache_dir(&dxc::cache_dir()); + compile_passthrough_cached_in( + CACHE.get_or_init(|| Mutex::new(HashMap::new())), + dir, + hlsl, + profile, + dxc::record_cache_hit, + || dxc::compile_cached(hlsl, "main", profile).map(|(b, _)| b), + ) +} + fn finish_two_pass_compiled(cs: Compiled, record: super::MsInterface, ps: Option<&[u8]>) -> Result { let ps_inputs = ps.map(|p| crate::gpu::dxbc::signatures(p).0); - let ms = dxc::compile_cached(&super::emit::mesh_passthrough_for(&record, ps_inputs.as_deref()), "main", "ms_6_6")?.0; + let ms = compile_passthrough_cached(&super::emit::mesh_passthrough_for(&record, ps_inputs.as_deref()), "ms_6_6")?; let mesh_groups_per_record = super::emit::passthrough_split(&record, super::emit::passthrough_elements(&record, ps_inputs.as_deref())); Ok(TwoPass { cs: cs.dxil, ms, record, mesh_groups_per_record, samplers: cs.samplers }) } @@ -1226,10 +1262,7 @@ pub fn console_geometry(vs: &[u8], gs: &[u8], ps: Option<&[u8]>, split_wave64: b match crate::gpu::dxil::kernel::translate_geometry(&code, o, &g) { Ok(k) => { crate::gpu::dxil::coverage::record_translated("GS"); - let ps_inputs = ps.map(|p| crate::gpu::dxbc::signatures(p).0); - let msb = dxc::compile_cached(&super::emit::mesh_passthrough_for(&record, ps_inputs.as_deref()), "main", "ms_6_6")?.0; - let mesh_groups_per_record = super::emit::passthrough_split(&record, super::emit::passthrough_elements(&record, ps_inputs.as_deref())); - return Ok(TwoPass { cs: k.dxil, ms: msb, record, mesh_groups_per_record, samplers: k.static_samplers }); + return finish_two_pass_compiled(Compiled { dispatch_chain: None, dxil: k.dxil, samplers: k.static_samplers }, record, ps); } Err(e) => direct_fallback("GS", &e), } @@ -1246,7 +1279,7 @@ pub fn rect_list_gs(vs: &[u8]) -> Result, String> { if outputs.is_empty() { return Err("the VS has no output signature".into()); } - Ok(dxc::compile_cached(&super::emit::rect_list_gs(&outputs), "main", "gs_6_6")?.0) + compile_passthrough_cached(&super::emit::rect_list_gs(&outputs), "gs_6_6") } /// XCL shader ABI root signature (see the module docs); `graphics` allows an input layout. @@ -2220,6 +2253,41 @@ mod shader_cache_tests { let _ = std::fs::remove_dir_all(&dir); } + + #[test] + fn passthrough_ram_cache_reuses_compiled_dxil_and_does_not_cache_errors() { + let cache = Mutex::new(HashMap::new()); + let dir_a = PathBuf::from(r"C:\cache_a"); + let dir_b = PathBuf::from(r"C:\cache_b"); + let src = "void main() {}"; + let mut hits = 0usize; + // Errors (including cached_only deferred misses) must not be cached. + assert!(compile_passthrough_cached_in(&cache, dir_a.clone(), src, "ms_6_6", || hits += 1, || Err("DXIL not compiled yet".into())).is_err()); + let mut calls = 0usize; + let first = compile_passthrough_cached_in(&cache, dir_a.clone(), src, "ms_6_6", || hits += 1, || { + calls += 1; + Ok(vec![0x44, 0x58, 0x42, 0x43]) + }) + .unwrap(); + let second = compile_passthrough_cached_in(&cache, dir_a.clone(), src, "ms_6_6", || hits += 1, || { + panic!("second call with identical dir+HLSL+profile must hit RAM cache") + }) + .unwrap(); + assert_eq!(calls, 1); + assert_eq!(hits, 1, "RAM hit must invoke DXIL cache hit accounting"); + assert_eq!(first, second); + // Changing cache_dir must miss so cold-cache tests populate the new directory. + let other_dir = compile_passthrough_cached_in(&cache, dir_b, src, "ms_6_6", || hits += 1, || { + calls += 1; + Ok(vec![0x44, 0x58, 0x42, 0x43]) + }) + .unwrap(); + assert_eq!(calls, 2); + assert_eq!(other_dir, first); + // Different profile uses a distinct key. + let gs = compile_passthrough_cached_in(&cache, dir_a, src, "gs_6_6", || hits += 1, || Ok(vec![1, 2, 3, 4])).unwrap(); + assert_eq!(gs, vec![1, 2, 3, 4]); + } } #[cfg(test)]