From 3842fe8d7e0f0c186361f976447729b32ef4955b Mon Sep 17 00:00:00 2001 From: KarolKurzyna <187065594+KarolKurzyna@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:32:17 +0100 Subject: [PATCH 1/3] D3D12.X: retry driver-rejected compute PSOs without DXC GVN (#756) NVIDIA D3D12 drivers can fail CreateComputePipelineState with E_OUTOFMEMORY (0x8007000E) when DXC's GVN pass merges descriptor heap handles into `phi %dx.types.Handle`, as diagnosed by @psuedo-tty in Keep the fast GVN-optimized DXIL build on the primary path and retry once with `-opt-disable gvn` only when the driver rejects the PSO: - Key DXC's disk cache on extra compiler flags (`cache_key_for_toolchain_extra`) so fallback DXIL is cached on disk without overwriting default entries. - Add `console_to_dxil_without_gvn` / `console_to_dxil_in_without_gvn` bypassing `ShaderCache` and the `translated` memory cache, and skip recompiling >8 MB HLSL already compiled at `-O0`. - Retry once on driver failure in `translated_compute_pso` (reusing the driver blob cache path) and in `xcl shaders --pipelines` (`Pipelines::make`). Fixes #756. Part of #1269. Assisted-by: Google Antigravity (Gemini 4 Neon) --- crates/xcl/src/gpu/recomp/dxc.rs | 67 ++++++++++++++++++++- crates/xcl/src/gpu/recomp/pso.rs | 20 ++++++- crates/xcl/src/hle/d3d12x/real.rs | 96 ++++++++++++++++++++++++++++++- crates/xcl/src/shaders.rs | 34 +++++++++-- 4 files changed, 208 insertions(+), 9 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/dxc.rs b/crates/xcl/src/gpu/recomp/dxc.rs index ec63906c58..6801c56a02 100644 --- a/crates/xcl/src/gpu/recomp/dxc.rs +++ b/crates/xcl/src/gpu/recomp/dxc.rs @@ -569,7 +569,12 @@ 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]) { @@ -577,9 +582,18 @@ fn cache_key_for_toolchain(src: &str, entry: &str, profile: &str, toolchain: &st 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 } +#[cfg(test)] fn cache_key(src: &str, entry: &str, profile: &str) -> u64 { cache_key_for_toolchain(src, entry, profile, toolchain_identity()) } @@ -665,6 +679,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, 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> { @@ -804,7 +823,22 @@ fn compile_cached_in_observed( where F: FnOnce() -> Result, 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( + dir: &Path, + src: &str, + entry: &str, + profile: &str, + extra: &[&str], + counters: &CacheCounters, + compile_one: F, +) -> Result<(Vec, bool), String> +where + F: FnOnce() -> Result, String>, +{ + let key = cache_key_for_toolchain_extra(src, entry, profile, toolchain_identity(), extra); let dir = normalized_cache_dir(dir); let file = dir.join(format!("{key:016x}.dxil")); if let Some(b) = cached_file(&file) { @@ -921,6 +955,10 @@ pub fn compile_cached(src: &str, entry: &str, profile: &str) -> Result<(Vec, compile_cached_in(&cache_dir(), src, entry, profile) } +pub fn compile_cached_with_extra(src: &str, entry: &str, profile: &str, extra: &[&str]) -> Result<(Vec, bool), String> { + compile_cached_in_with_extra(&cache_dir(), src, entry, profile, extra) +} + #[cfg(test)] mod cache_tests { use super::*; @@ -1043,6 +1081,33 @@ 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() { + 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 b : register(u0); [numthreads(1, 1, 1)] void main() { b.Store(0, 1u); }"; + 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_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); diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index c9a50b72b4..6406022724 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -140,6 +140,17 @@ 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 { + 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 { + compile_console_shader_with_extra(blob, stage, sampler_base, windows, split_wave64, &["-opt-disable", "gvn"]).map(|(compiled, _)| compiled) +} + /// Global in-memory cache for translated shaders shared by `console_to_dxil_in` and `console_mesh`. fn shader_cache() -> &'static Mutex { static CACHE: OnceLock> = OnceLock::new(); @@ -446,6 +457,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, &[]) +} + +fn compile_console_shader_with_extra(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, split_wave64: bool, extra: &[&str]) -> Result<(Compiled, bool), 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() { @@ -476,6 +491,9 @@ fn compile_console_shader(blob: &[u8], stage: Stage, sampler_base: u32, windows: } } 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()); @@ -522,7 +540,7 @@ 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; + let dxil = dxc::compile_cached_with_extra(&t.hlsl, "main", profile, extra)?.0; Ok((Compiled { dxil, samplers: t.static_samplers }, false)) } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 6cf818107b..31f52ff930 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -4277,7 +4277,7 @@ unsafe fn translated_compute_pso(this: *mut c_void, f: PsoFn, desc: *const c_voi } unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option> { - use crate::gpu::recomp::pso::{console_to_dxil_for, is_console, Stage}; + use crate::gpu::recomp::pso::{console_to_dxil_for, console_to_dxil_without_gvn, is_console, Stage}; if !crate::gpu::shader::readable(desc as usize, std::mem::size_of::()) { return None; } @@ -4297,7 +4297,7 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const return Some(Err(())); } }; - let dxil = compiled.dxil; + let mut dxil = compiled.dxil; // a big program: the driver's compile takes it seconds to a minute (a retail game's 1 MB // ray-tracing resolve programs ~30 s each, ~600 of them): built in the background like one // whose DXIL is missing – the title's loading does not wait for it, its first bind does @@ -4350,7 +4350,7 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const hr = retried; in_driver += took; } - let reused = hr >= 0 && cached.is_some() && copy.CachedPSO.CachedBlobSizeInBytes != 0; + let mut reused = hr >= 0 && cached.is_some() && copy.CachedPSO.CachedBlobSizeInBytes != 0; if hr >= 0 && !reused { keep_compute_blob(key, *ppv, dxil.len()); if let (Some(p), Some(b)) = (disk.as_deref(), compute_blob(key)) { @@ -4359,6 +4359,75 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const } else if reused && from_disk { driver_cache::note(true, None); } + if hr < 0 && !HEAP_WINDOW_OOM.with(|o| o.get()) { + let mut retry_reused = false; + let mut retry_in_driver = std::time::Duration::ZERO; + let mut retry_dxil = None; + let (retry_hr, retried) = retry_compute_pso_without_gvn( + hr, + &dxil, + || console_to_dxil_without_gvn(cs, Stage::Compute, 0, wave32_only(this)).map(|c| c.dxil), + |new_dxil| { + retry_dxil = Some(new_dxil.to_vec()); + copy.CS = bytecode(new_dxil); + copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); + let retry_key = compute_blob_key(new_dxil, rs as usize, copy.Flags.0); + let mut retry_cached = compute_blob(retry_key); + let retry_disk = driver_cache::path(new_dxil, copy.Flags.0); + let retry_from_disk = retry_cached.is_none(); + if retry_from_disk { + retry_cached = retry_disk.as_deref().and_then(driver_cache::load).map(std::sync::Arc::new); + } + if let Some(b) = &retry_cached { + copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE { pCachedBlob: b.as_ptr() as *const c_void, CachedBlobSizeInBytes: b.len() }; + } + let (mut retry_hr, mut took) = driver_compile_identified( + "compute no-gvn", + new_dxil.len(), + gate_compute_driver_compile(retry_cached.is_some()), + Some((record, retry_cached.is_some())), + || finish_pso(this, f, © as *const _ as *const c_void, riid, ppv), + ); + if retry_hr < 0 && retry_cached.is_some() { + forget_compute_blob(retry_key); + if retry_from_disk { + driver_cache::note(false, retry_disk.as_deref()); + } + copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); + let (uncached_hr, uncached_took) = driver_compile_identified( + "compute no-gvn retry", + new_dxil.len(), + gate_compute_driver_compile(false), + Some((record, false)), + || finish_pso(this, f, © as *const _ as *const c_void, riid, ppv), + ); + retry_hr = uncached_hr; + took += uncached_took; + } + let reused = retry_hr >= 0 && retry_cached.is_some() && copy.CachedPSO.CachedBlobSizeInBytes != 0; + if retry_hr >= 0 && !reused { + keep_compute_blob(retry_key, *ppv, new_dxil.len()); + if let (Some(p), Some(b)) = (retry_disk.as_deref(), compute_blob(retry_key)) { + driver_cache::keep(p, &b, took); + } + } else if reused && retry_from_disk { + driver_cache::note(true, None); + } + retry_reused = reused; + retry_in_driver = took; + retry_hr + }, + ); + hr = retry_hr; + if let Some(retry_dxil) = retry_dxil { + dxil = retry_dxil; + } + if retried { + reused = retry_reused; + in_driver = retry_in_driver; + crate::xlog_info!("D3D12.X: compute PSO driver refusal succeeded after recompiling without DXC GVN"); + } + } if hr < 0 { // A huge program's verdict in the log itself: `note_translation_error` goes to the // report, or to the notes of a cached-only attempt – a retail title's 13.8 MB program @@ -4392,6 +4461,27 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const Some(Ok(hr)) } +/// Retry a driver-rejected compute PSO once using DXIL recompiled without DXC's GVN pass +/// (avoiding handle phis that some drivers refuse with `E_OUTOFMEMORY`, #756). +fn retry_compute_pso_without_gvn( + first_hr: HRESULT, + orig_dxil: &[u8], + recompile: impl FnOnce() -> Result, String>, + mut create: impl FnMut(&[u8]) -> HRESULT, +) -> (HRESULT, bool) { + if first_hr >= 0 { + return (first_hr, false); + } + let Ok(retry_dxil) = recompile() else { + return (first_hr, false); + }; + if retry_dxil == orig_dxil { + return (first_hr, false); + } + let hr2 = create(&retry_dxil); + (hr2, hr2 >= 0) +} + /// The blobs of `COMPUTE_BLOBS`, kept on disk between runs. /// /// `COMPUTE_BLOBS` saves the second build of a program in one run; the first build of every diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 68ee303327..f7566d5287 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1226,6 +1226,28 @@ impl Pipelines { } fn make_with_cache_path(&self, c: &recomp::pso::Compiled, path_override: Option) { + let _ = self.make_with_cache_path_result(c, path_override); + } + + fn make_with_cache_path_and_retry(&self, name: &str, c: &recomp::pso::Compiled, retry_without_gvn: impl FnOnce() -> Option) { + if self.make_with_cache_path_result(c, None) != Some(false) { + return; + } + let Some(nogvn) = retry_without_gvn() else { return }; + if nogvn.dxil == c.dxil { + return; + } + // Count the retry as the pipeline's final result, not as an extra refused pipeline. + self.refused.fetch_sub(1, Ordering::Relaxed); + let retried = self.make_with_cache_path_result(&nogvn, None); + if retried.is_none() { + self.refused.fetch_add(1, Ordering::Relaxed); + } else if retried == Some(true) { + eprintln!(" {name}: driver refused compute pipeline; built without GVN ({} B DXIL)", nogvn.dxil.len()); + } + } + + fn make_with_cache_path_result(&self, c: &recomp::pso::Compiled, path_override: Option) -> Option { use windows::Win32::Graphics::Direct3D12::*; let key: Vec = c.samplers.iter().flat_map(|(w, cmp)| w.iter().copied().chain([*cmp as u32])).collect(); let rs = { @@ -1239,7 +1261,7 @@ impl Pipelines { } Err(_) => { self.refused.fetch_add(1, Ordering::Relaxed); - return; + return None; } }, } @@ -1260,7 +1282,7 @@ impl Pipelines { self.capped.fetch_add(1, Ordering::Relaxed); self.capped_bytes.fetch_add(c.dxil.len(), Ordering::Relaxed); drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); - return; + return None; } { let mut n = self.running.0.lock().unwrap(); @@ -1288,7 +1310,7 @@ impl Pipelines { self.capped.fetch_add(1, Ordering::Relaxed); self.capped_bytes.fetch_add(c.dxil.len(), Ordering::Relaxed); drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); - return; + return None; } let r = if let Some(pso) = from_cache { self.reused.fetch_add(1, Ordering::Relaxed); @@ -1310,6 +1332,7 @@ impl Pipelines { *self.running.0.lock().unwrap() -= 1; self.running.1.notify_one(); drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); + let ok = r.is_ok(); let done = match r { Ok(_) => self.made.fetch_add(1, Ordering::Relaxed) + 1, Err(_) => self.refused.fetch_add(1, Ordering::Relaxed) + 1, @@ -1317,6 +1340,7 @@ impl Pipelines { if done % 25 == 0 { eprintln!(" pipelines: {} made, {} refused", self.made.load(Ordering::Relaxed), self.refused.load(Ordering::Relaxed)); } + Some(ok) } } @@ -1388,7 +1412,9 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on match recomp::pso::console_to_dxil_in(&blob, recomp::pso::Stage::Compute, 0, split, windows) { Ok(c) => { if let Some(p) = pipelines { - p.make(&c); + p.make_with_cache_path_and_retry(&name, &c, || { + recomp::pso::console_to_dxil_in_without_gvn(&blob, recomp::pso::Stage::Compute, 0, split, windows).ok() + }); } compiled.fetch_add(1, Ordering::Relaxed) } From 335f3f26754591544d04c8ab671576e4cee651cb Mon Sep 17 00:00:00 2001 From: KarolKurzyna <187065594+KarolKurzyna@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:58:58 +0100 Subject: [PATCH 2/3] D3D12.X: log cache keys and driver reason on compute PSO GVN retry Addresses review feedback from @pickles976 on #1398: - Return both DXIL disk-cache keys (default GVN build -> `-opt-disable gvn` build) via `WithoutGvn` and log them whenever a compute PSO is retried or refused. - Capture the first non-empty line of any D3D12 debug-layer error emitted on the calling thread (or fall back to Windows' formatted HRESULT) and include it in `translated_compute_pso` and `Pipelines::make` retry/failure logs. Assisted-by: Google Antigravity (Gemini 4 Neon) --- crates/xcl/src/gpu/recomp/dxc.rs | 6 ++- crates/xcl/src/gpu/recomp/pso.rs | 28 +++++++++---- crates/xcl/src/hle/d3d12x/real.rs | 68 ++++++++++++++++++++++++++++--- crates/xcl/src/shaders.rs | 32 +++++++++------ 4 files changed, 105 insertions(+), 29 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/dxc.rs b/crates/xcl/src/gpu/recomp/dxc.rs index 6801c56a02..ae26a747f3 100644 --- a/crates/xcl/src/gpu/recomp/dxc.rs +++ b/crates/xcl/src/gpu/recomp/dxc.rs @@ -593,6 +593,10 @@ fn cache_key_for_toolchain_extra(src: &str, entry: &str, profile: &str, toolchai 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()) @@ -838,7 +842,7 @@ fn compile_cached_in_observed_with_extra( where F: FnOnce() -> Result, String>, { - let key = cache_key_for_toolchain_extra(src, entry, profile, toolchain_identity(), extra); + 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) { diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 6406022724..477ea140f4 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -125,6 +125,13 @@ pub struct Compiled { pub samplers: Vec, } +/// 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. @@ -142,13 +149,14 @@ pub fn console_to_dxil_for(blob: &[u8], stage: Stage, sampler_base: u32, split_w /// 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 { +pub fn console_to_dxil_without_gvn(blob: &[u8], stage: Stage, sampler_base: u32, split_wave64: bool) -> Result { 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 { - compile_console_shader_with_extra(blob, stage, sampler_base, windows, split_wave64, &["-opt-disable", "gvn"]).map(|(compiled, _)| compiled) +pub fn console_to_dxil_in_without_gvn(blob: &[u8], stage: Stage, sampler_base: u32, split_wave64: bool, windows: u32) -> Result { + 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`. @@ -457,10 +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, &[]) + 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), String> { +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() { @@ -470,7 +478,7 @@ fn compile_console_shader_with_extra(blob: &[u8], stage: Stage, sampler_base: u3 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), } @@ -485,7 +493,7 @@ fn compile_console_shader_with_extra(blob: &[u8], stage: Stage, sampler_base: u3 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), } @@ -506,7 +514,7 @@ fn compile_console_shader_with_extra(blob: &[u8], stage: Stage, sampler_base: u3 t.hlsl.len() >> 10, c.dxil.len() >> 10 ); - return Ok((c, true)); + return Ok((c, true, 0, 0)); } Err(e) => direct_fallback("CS", &e), } @@ -540,8 +548,10 @@ fn compile_console_shader_with_extra(blob: &[u8], stage: Stage, sampler_base: u3 }) { t.hlsl = t.hlsl.replacen(" if (!xcl_live) discard;\n return xo;\n}", &format!(" xo.t0 = {expr};\n return xo;\n}}"), 1); } + 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)) + 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)`. diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 31f52ff930..d5d517a909 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -555,6 +555,11 @@ pub fn init() -> Result { } } +thread_local! { + /// First line of the latest error-severity D3D12 debug layer message on this thread. + static LAST_D3D12_ERROR: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; +} + /// A debug layer message: errors and warnings into the log – the first 8 of each message id /// (3 000 in all). One cap for all of them (200) was used up in seconds by two per-frame state /// errors of a retail game, long before the message that came with its device removal. @@ -564,6 +569,12 @@ unsafe extern "system" fn debug_message(_category: D3D12_MESSAGE_CATEGORY, sever if severity.0 > D3D12_MESSAGE_SEVERITY_WARNING.0 { return; } + if severity.0 <= D3D12_MESSAGE_SEVERITY_ERROR.0 && !text.is_null() { + let msg = String::from_utf8_lossy(text.as_bytes()); + if let Some(line) = first_error_line(&msg) { + LAST_D3D12_ERROR.with(|e| *e.borrow_mut() = Some(line.to_string())); + } + } { let mut g = PER_ID.lock().unwrap(); let n = g.get_or_insert_with(HashMap::new).entry(id.0).or_insert(0); @@ -4326,6 +4337,7 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const } // in the background, a few at a time and within the commit headroom the program asks for let record = crate::gpu::shader::fnv64(cs); + LAST_D3D12_ERROR.with(|e| *e.borrow_mut() = None); let (mut hr, mut in_driver) = driver_compile_identified( "compute", dxil.len(), @@ -4359,15 +4371,28 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const } else if reused && from_disk { driver_cache::note(true, None); } + let mut retried_no_gvn: Option<(u64, u64, String)> = None; + let mut failure_note: Option = None; if hr < 0 && !HEAP_WINDOW_OOM.with(|o| o.get()) { + let first_hr = hr; + let first_msg = LAST_D3D12_ERROR.with(|e| e.borrow_mut().take()); + let first_reason = format_driver_rejection(first_hr, first_msg.as_deref()); let mut retry_reused = false; let mut retry_in_driver = std::time::Duration::ZERO; let mut retry_dxil = None; + let mut retry_keys = None; + let mut retry_attempted = false; let (retry_hr, retried) = retry_compute_pso_without_gvn( - hr, + first_hr, &dxil, - || console_to_dxil_without_gvn(cs, Stage::Compute, 0, wave32_only(this)).map(|c| c.dxil), + || { + let without = console_to_dxil_without_gvn(cs, Stage::Compute, 0, wave32_only(this))?; + retry_keys = Some((without.rejected_key, without.retry_key)); + Ok(without.compiled.dxil) + }, |new_dxil| { + LAST_D3D12_ERROR.with(|e| *e.borrow_mut() = None); + retry_attempted = true; retry_dxil = Some(new_dxil.to_vec()); copy.CS = bytecode(new_dxil); copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); @@ -4425,7 +4450,19 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const if retried { reused = retry_reused; in_driver = retry_in_driver; - crate::xlog_info!("D3D12.X: compute PSO driver refusal succeeded after recompiling without DXC GVN"); + retried_no_gvn = retry_keys.map(|(g, ng)| (g, ng, first_reason.clone())); + } else { + failure_note = Some(if retry_attempted { + let retry_msg = LAST_D3D12_ERROR.with(|e| e.borrow_mut().take()); + let retry_reason = format_driver_rejection(hr, retry_msg.as_deref()); + if let Some((g, ng)) = retry_keys { + format!("{first_reason}; retry without GVN {g:016x} -> {ng:016x} refused: {retry_reason}") + } else { + retry_reason + } + } else { + first_reason + }); } } if hr < 0 { @@ -4443,7 +4480,10 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const in_driver.as_millis() ); } - note_translation_error(format!("the driver rejected the compute PSO with the translated CS ({hr:#x})")); + note_translation_error(format!( + "the driver rejected the compute PSO with the translated CS ({})", + failure_note.unwrap_or_else(|| format!("{hr:#x}")) + )); return Some(Err(())); } TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); @@ -4452,15 +4492,31 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const PSO_USER_SGPRS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, n); } note_translated_compute(hr, ppv); + let retry_note = retried_no_gvn + .map(|(g, ng, reason)| format!(", retried without GVN (dxil cache {g:016x} -> {ng:016x}; driver refused: {reason})")) + .unwrap_or_default(); crate::xlog_info!( - "D3D12.X: compute PSO with the translated console CS ({} B DXIL, {} ms{})", + "D3D12.X: compute PSO with the translated console CS ({} B DXIL, {} ms{}{})", dxil.len(), in_driver.as_millis(), - if reused { ", the driver's blob of an earlier build" } else { "" } + if reused { ", the driver's blob of an earlier build" } else { "" }, + retry_note ); Some(Ok(hr)) } +pub(crate) fn first_error_line(text: &str) -> Option<&str> { + text.lines().map(str::trim).find(|l| !l.is_empty()) +} + +fn format_driver_rejection(hr: HRESULT, retained_message: Option<&str>) -> String { + if let Some(line) = retained_message.and_then(first_error_line) { + return format!("{hr:#x}: {line}"); + } + let msg = windows::core::Error::from_hresult(windows::core::HRESULT(hr)).to_string(); + first_error_line(&msg).map(str::to_string).unwrap_or_else(|| format!("{hr:#x}")) +} + /// Retry a driver-rejected compute PSO once using DXIL recompiled without DXC's GVN pass /// (avoiding handle phis that some drivers refuse with `E_OUTOFMEMORY`, #756). fn retry_compute_pso_without_gvn( diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index f7566d5287..01ba828ccc 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1229,25 +1229,31 @@ impl Pipelines { let _ = self.make_with_cache_path_result(c, path_override); } - fn make_with_cache_path_and_retry(&self, name: &str, c: &recomp::pso::Compiled, retry_without_gvn: impl FnOnce() -> Option) { - if self.make_with_cache_path_result(c, None) != Some(false) { - return; - } + fn make_with_cache_path_and_retry(&self, name: &str, c: &recomp::pso::Compiled, retry_without_gvn: impl FnOnce() -> Option) { + let Some(Err(first_error)) = self.make_with_cache_path_result(c, None) else { return }; let Some(nogvn) = retry_without_gvn() else { return }; - if nogvn.dxil == c.dxil { + if nogvn.compiled.dxil == c.dxil { return; } + let reason = crate::hle::d3d12x::real::first_error_line(&first_error).unwrap_or(&first_error).to_string(); // Count the retry as the pipeline's final result, not as an extra refused pipeline. self.refused.fetch_sub(1, Ordering::Relaxed); - let retried = self.make_with_cache_path_result(&nogvn, None); - if retried.is_none() { - self.refused.fetch_add(1, Ordering::Relaxed); - } else if retried == Some(true) { - eprintln!(" {name}: driver refused compute pipeline; built without GVN ({} B DXIL)", nogvn.dxil.len()); + let retried = self.make_with_cache_path_result(&nogvn.compiled, None); + match retried { + None => { + self.refused.fetch_add(1, Ordering::Relaxed); + } + Some(Ok(())) => eprintln!( + " {name}: driver refused compute pipeline ({reason}); built without GVN (dxil cache {:016x} -> {:016x}, {} B DXIL)", + nogvn.rejected_key, + nogvn.retry_key, + nogvn.compiled.dxil.len() + ), + Some(Err(_)) => {} } } - fn make_with_cache_path_result(&self, c: &recomp::pso::Compiled, path_override: Option) -> Option { + fn make_with_cache_path_result(&self, c: &recomp::pso::Compiled, path_override: Option) -> Option> { use windows::Win32::Graphics::Direct3D12::*; let key: Vec = c.samplers.iter().flat_map(|(w, cmp)| w.iter().copied().chain([*cmp as u32])).collect(); let rs = { @@ -1332,7 +1338,7 @@ impl Pipelines { *self.running.0.lock().unwrap() -= 1; self.running.1.notify_one(); drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); - let ok = r.is_ok(); + let error = r.as_ref().err().map(ToString::to_string); let done = match r { Ok(_) => self.made.fetch_add(1, Ordering::Relaxed) + 1, Err(_) => self.refused.fetch_add(1, Ordering::Relaxed) + 1, @@ -1340,7 +1346,7 @@ impl Pipelines { if done % 25 == 0 { eprintln!(" pipelines: {} made, {} refused", self.made.load(Ordering::Relaxed), self.refused.load(Ordering::Relaxed)); } - Some(ok) + Some(error.map_or(Ok(()), Err)) } } From 36e23fddc9396f550c5a3e352b6857c1814c4586 Mon Sep 17 00:00:00 2001 From: KarolKurzyna <187065594+KarolKurzyna@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:24:18 +0100 Subject: [PATCH 3/3] D3D12.X: bound GVN retry to fast driver refusals and test DXIL diff Addresses two review points from @erickbobd on #1398: - Guard `-opt-disable gvn` retries on `first_elapsed <= 5 s` (`NO_GVN_RETRY_MAX_REFUSAL`) in both `translated_compute_pso` and `Pipelines::make`, resetting `started` around uncached fallback driver compiles so slow multi-minute driver OOMs on huge programs do not pay for a second, larger no-GVN compile. - Strengthen `dxil_cache_with_extra_flags_round_trip` with a GVN-sensitive HLSL compute shader and `assert_ne!(default_dxil, nogvn_dxil)`, plus `runner::skip_test("no DXC")` when DXC is absent. Assisted-by: Google Antigravity (Gemini 4 Neon) --- crates/xcl/src/gpu/recomp/dxc.rs | 4 +- crates/xcl/src/hle/d3d12x/real.rs | 124 +++++++++++++++++++++++++++++- crates/xcl/src/shaders.rs | 27 +++---- 3 files changed, 139 insertions(+), 16 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/dxc.rs b/crates/xcl/src/gpu/recomp/dxc.rs index ae26a747f3..0f260ef869 100644 --- a/crates/xcl/src/gpu/recomp/dxc.rs +++ b/crates/xcl/src/gpu/recomp/dxc.rs @@ -1097,15 +1097,17 @@ mod cache_tests { #[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 b : register(u0); [numthreads(1, 1, 1)] void main() { b.Store(0, 1u); }"; + 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); diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index d5d517a909..485a50ed45 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -4345,6 +4345,7 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const Some((record, cached.is_some())), || finish_pso(this, f, © as *const _ as *const c_void, riid, ppv), ); + let mut refusal_elapsed = in_driver; if hr < 0 && cached.is_some() { // a blob the driver does not take (another root signature at the same address…): compiled forget_compute_blob(key); @@ -4361,6 +4362,7 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const ); hr = retried; in_driver += took; + refusal_elapsed = took; } let mut reused = hr >= 0 && cached.is_some() && copy.CachedPSO.CachedBlobSizeInBytes != 0; if hr >= 0 && !reused { @@ -4384,6 +4386,7 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const let mut retry_attempted = false; let (retry_hr, retried) = retry_compute_pso_without_gvn( first_hr, + refusal_elapsed, &dxil, || { let without = console_to_dxil_without_gvn(cs, Stage::Compute, 0, wave32_only(this))?; @@ -4517,15 +4520,20 @@ fn format_driver_rejection(hr: HRESULT, retained_message: Option<&str>) -> Strin first_error_line(&msg).map(str::to_string).unwrap_or_else(|| format!("{hr:#x}")) } -/// Retry a driver-rejected compute PSO once using DXIL recompiled without DXC's GVN pass +/// Upper bound on how long an initial driver refusal may take to qualify for a `-opt-disable gvn` +/// retry: fast handle-phi refusals can benefit, while multi-minute OOMs should not pay for another compile. +pub(crate) const NO_GVN_RETRY_MAX_REFUSAL: std::time::Duration = std::time::Duration::from_secs(5); + +/// Retry a fast driver-rejected compute PSO once using DXIL recompiled without DXC's GVN pass /// (avoiding handle phis that some drivers refuse with `E_OUTOFMEMORY`, #756). fn retry_compute_pso_without_gvn( first_hr: HRESULT, + first_elapsed: std::time::Duration, orig_dxil: &[u8], recompile: impl FnOnce() -> Result, String>, mut create: impl FnMut(&[u8]) -> HRESULT, ) -> (HRESULT, bool) { - if first_hr >= 0 { + if first_hr >= 0 || first_elapsed > NO_GVN_RETRY_MAX_REFUSAL { return (first_hr, false); } let Ok(retry_dxil) = recompile() else { @@ -4538,6 +4546,118 @@ fn retry_compute_pso_without_gvn( (hr2, hr2 >= 0) } +#[cfg(test)] +mod compute_pso_retry_tests { + use super::*; + + const REFUSED_OOM: HRESULT = 0x8007_000Eu32 as i32; + const REFUSED_ARG: HRESULT = 0x8007_0057u32 as i32; + + #[test] + fn compute_pso_success_skips_no_gvn_retry() { + let mut calls = 0; + let (hr, retried) = retry_compute_pso_without_gvn(0, std::time::Duration::ZERO, b"orig", || panic!("successful PSO must not recompile"), |_| { + calls += 1; + 0 + }); + assert_eq!((hr, retried, calls), (0, false, 0)); + } + + #[test] + fn compute_pso_refusal_retries_without_gvn() { + let mut seen = Vec::new(); + let (hr, retried) = retry_compute_pso_without_gvn( + REFUSED_OOM, + std::time::Duration::from_millis(100), + b"orig-dxil", + || Ok(b"no-gvn-dxil".to_vec()), + |dxil| { + seen.push(dxil.to_vec()); + 0 + }, + ); + assert_eq!((hr, retried), (0, true)); + assert_eq!(seen, vec![b"no-gvn-dxil".to_vec()]); + } + + #[test] + fn compute_pso_refusal_skips_unchanged_dxil() { + let mut calls = 0; + let (hr, retried) = retry_compute_pso_without_gvn( + REFUSED_OOM, + std::time::Duration::from_millis(100), + b"same-dxil", + || Ok(b"same-dxil".to_vec()), + |_| { + calls += 1; + 0 + }, + ); + assert_eq!((hr, retried, calls), (REFUSED_OOM, false, 0)); + } + + #[test] + fn compute_pso_refusal_propagates_retry_failure() { + let (hr1, retried1) = retry_compute_pso_without_gvn( + REFUSED_OOM, + std::time::Duration::from_millis(100), + b"orig-dxil", + || Err("already -O0".into()), + |_| 0, + ); + assert_eq!((hr1, retried1), (REFUSED_OOM, false)); + let (hr2, retried2) = retry_compute_pso_without_gvn( + REFUSED_OOM, + std::time::Duration::from_millis(100), + b"orig-dxil", + || Ok(b"no-gvn-dxil".to_vec()), + |_| REFUSED_ARG, + ); + assert_eq!((hr2, retried2), (REFUSED_ARG, false)); + } + + #[test] + fn compute_pso_slow_refusal_skips_no_gvn_retry() { + let mut calls = 0; + let (hr, retried) = retry_compute_pso_without_gvn( + REFUSED_OOM, + std::time::Duration::from_secs(6), + b"orig-dxil", + || panic!("slow refusal must not trigger another compile"), + |_| { + calls += 1; + 0 + }, + ); + assert_eq!((hr, retried, calls), (REFUSED_OOM, false, 0)); + let (hr_edge, retried_edge) = retry_compute_pso_without_gvn( + REFUSED_OOM, + NO_GVN_RETRY_MAX_REFUSAL, + b"orig-dxil", + || Ok(b"no-gvn-dxil".to_vec()), + |_| 0, + ); + assert_eq!((hr_edge, retried_edge), (0, true)); + } + + #[test] + fn first_error_line_picks_first_nonempty_trimmed_line() { + assert_eq!(first_error_line("\n \n useful detail \r\nsecond line\n"), Some("useful detail")); + assert_eq!(first_error_line(" \r\n\t "), None); + } + + #[test] + fn format_driver_rejection_uses_debug_message_or_hresult() { + assert_eq!( + format_driver_rejection(REFUSED_OOM, Some("\n D3D12 ERROR: rejected phi handle \nsecond line")), + "0x8007000e: D3D12 ERROR: rejected phi handle" + ); + let fallback = format_driver_rejection(REFUSED_OOM, None); + assert!(!fallback.is_empty() && !fallback.contains('\n')); + assert!(fallback.to_ascii_lowercase().contains("8007000e")); + } +} + /// The blobs of `COMPUTE_BLOBS`, kept on disk between runs. /// /// `COMPUTE_BLOBS` saves the second build of a program in one run; the first build of every diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 01ba828ccc..5bab01dc39 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1220,17 +1220,16 @@ impl Pipelines { } } - /// The compute pipeline of `c` (made and released). - fn make(&self, c: &recomp::pso::Compiled) { - self.make_with_cache_path(c, None); - } - + #[cfg(test)] fn make_with_cache_path(&self, c: &recomp::pso::Compiled, path_override: Option) { let _ = self.make_with_cache_path_result(c, path_override); } fn make_with_cache_path_and_retry(&self, name: &str, c: &recomp::pso::Compiled, retry_without_gvn: impl FnOnce() -> Option) { - let Some(Err(first_error)) = self.make_with_cache_path_result(c, None) else { return }; + let Some((Err(first_error), first_elapsed)) = self.make_with_cache_path_result(c, None) else { return }; + if first_elapsed > crate::hle::d3d12x::real::NO_GVN_RETRY_MAX_REFUSAL { + return; + } let Some(nogvn) = retry_without_gvn() else { return }; if nogvn.compiled.dxil == c.dxil { return; @@ -1243,17 +1242,17 @@ impl Pipelines { None => { self.refused.fetch_add(1, Ordering::Relaxed); } - Some(Ok(())) => eprintln!( + Some((Ok(()), _)) => eprintln!( " {name}: driver refused compute pipeline ({reason}); built without GVN (dxil cache {:016x} -> {:016x}, {} B DXIL)", nogvn.rejected_key, nogvn.retry_key, nogvn.compiled.dxil.len() ), - Some(Err(_)) => {} + Some((Err(_), _)) => {} } } - fn make_with_cache_path_result(&self, c: &recomp::pso::Compiled, path_override: Option) -> Option> { + fn make_with_cache_path_result(&self, c: &recomp::pso::Compiled, path_override: Option) -> Option<(Result<(), String>, std::time::Duration)> { use windows::Win32::Graphics::Direct3D12::*; let key: Vec = c.samplers.iter().flat_map(|(w, cmp)| w.iter().copied().chain([*cmp as u32])).collect(); let rs = { @@ -1318,12 +1317,14 @@ impl Pipelines { drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); return None; } - let r = if let Some(pso) = from_cache { + let (r, elapsed) = if let Some(pso) = from_cache { self.reused.fetch_add(1, Ordering::Relaxed); - Ok(pso) + (Ok(pso), std::time::Duration::ZERO) } else { desc.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); + let t0 = std::time::Instant::now(); let pso = unsafe { self.dev.CreateComputePipelineState::(&desc) }; + let elapsed = t0.elapsed(); if let (Some(path), Ok(pso)) = (path.as_deref(), &pso) { if let Ok(blob) = unsafe { pso.GetCachedBlob() } { let bytes = unsafe { blob.GetBufferPointer() }.cast::(); @@ -1333,7 +1334,7 @@ impl Pipelines { } } } - pso + (pso, elapsed) }; *self.running.0.lock().unwrap() -= 1; self.running.1.notify_one(); @@ -1346,7 +1347,7 @@ impl Pipelines { if done % 25 == 0 { eprintln!(" pipelines: {} made, {} refused", self.made.load(Ordering::Relaxed), self.refused.load(Ordering::Relaxed)); } - Some(error.map_or(Ok(()), Err)) + Some((error.map_or(Ok(()), Err), elapsed)) } }