diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 8a8b95b065..7cad8edcec 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -5,9 +5,9 @@ //! directly indexed descriptor heaps (images / samplers). Mapping the title's root arguments //! onto that ABI at draw time is the next step (needs the console runtime's user-data layout). -use std::collections::VecDeque; +use std::collections::{HashMap, VecDeque}; use std::path::PathBuf; -use std::sync::{Arc, Mutex, OnceLock}; +use std::sync::{Arc, Mutex, OnceLock, Weak}; use windows::Win32::Graphics::Direct3D::ID3DBlob; use windows::Win32::Graphics::Direct3D12::*; @@ -15,11 +15,12 @@ use windows::Win32::Graphics::Direct3D12::*; use super::{dxc, interface, translate, Mode, Options}; use crate::gpu::xbox; -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum Stage { Vertex, Pixel, Compute, + Mesh, } /// A console (xbox-native) shader container? @@ -139,6 +140,12 @@ 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()) } +/// 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(); + CACHE.get_or_init(|| Mutex::new(ShaderCache::new(64 << 20))) +} + /// `console_to_dxil_for` with the title's memory windows given (`xcl shaders --precompile` /// fills the caches without a title: the same keys as at its run). pub fn console_to_dxil_in(blob: &[u8], stage: Stage, sampler_base: u32, split_wave64: bool, windows: u32) -> Result { @@ -146,8 +153,6 @@ pub fn console_to_dxil_in(blob: &[u8], stage: Stage, sampler_base: u32, split_wa if !cache_allowed(stage, |name| std::env::var_os(name).is_some()) { return compile_one(); } - static CACHE: OnceLock> = OnceLock::new(); - let cache = CACHE.get_or_init(|| Mutex::new(ShaderCache::new(64 << 20))); let key = ShaderKey { hash: crate::gpu::shader::fnv64(blob), stage, @@ -159,7 +164,7 @@ pub fn console_to_dxil_in(blob: &[u8], stage: Stage, sampler_base: u32, split_wa // 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(&dxc::cache_dir(), blob, stage, sampler_base, windows, split_wave64, compile_one); - cached_shader(cache, key, blob, from_disk).map(|shader| shader.as_ref().clone()) + cached_shader(shader_cache(), key, blob, from_disk).map(|shader| shader.as_ref().clone()) } /// Translations on disk: a console program's (DXIL, static samplers) by its bytes, so a run @@ -351,6 +356,9 @@ 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() { + if dxc::defer() { + return Err("DXIL not compiled yet".into()); + } match direct_compute(blob, sampler_base, windows, split_wave64) { Ok(c) => { crate::gpu::dxil::coverage::record_translated("CS"); @@ -362,7 +370,10 @@ fn compile_console_shader(blob: &[u8], stage: Stage, sampler_base: u32, windows: // `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())); - if stage != Stage::Compute && !ps_debug && crate::gpu::dxil::kernel::enabled_graphics() { + if matches!(stage, Stage::Vertex | Stage::Pixel) && !ps_debug && crate::gpu::dxil::kernel::enabled_graphics() { + if dxc::defer() { + return Err("DXIL not compiled yet".into()); + } match direct_graphics(blob, stage, sampler_base, windows) { Ok(c) => { crate::gpu::dxil::coverage::record_translated(if stage == Stage::Vertex { "VS" } else { "PS" }); @@ -463,7 +474,11 @@ pub fn console_to_hlsl(blob: &[u8], stage: Stage) -> Result<(String, &'static st console_translation(blob, stage, 0, mem_windows(), false).map(|(t, p)| (t.hlsl, p)) } -#[derive(Clone, PartialEq, Eq)] +/// Upper entry cap for `ShaderCache` (the 64 MiB byte limit is the primary bound; a retail game +/// has ~2 800 unique shaders across ~58 000 PSOs, so a 128-entry cap thrashed RAM to disk). +const SHADER_CACHE_MAX_ENTRIES: usize = 4096; + +#[derive(Clone, PartialEq, Eq, Hash)] struct ShaderKey { hash: u64, stage: Stage, @@ -477,6 +492,7 @@ struct ShaderEntry { key: ShaderKey, blob: Vec, shader: Arc, + gen: u64, } impl ShaderEntry { @@ -489,7 +505,11 @@ impl ShaderEntry { } struct ShaderCache { - entries: VecDeque, + entries: HashMap, + by_key: HashMap>, + lru: VecDeque<(u64, u64)>, + next_id: u64, + next_gen: u64, bytes: usize, limit: usize, } @@ -497,24 +517,65 @@ struct ShaderCache { impl ShaderCache { fn new(limit: usize) -> Self { Self { - entries: VecDeque::new(), + entries: HashMap::new(), + by_key: HashMap::new(), + lru: VecDeque::new(), + next_id: 0, + next_gen: 0, bytes: 0, limit, } } + fn compact_lru(&mut self) { + if self.lru.len() > self.entries.len().max(64) * 4 { + self.lru.retain(|&(id, gen)| self.entries.get(&id).is_some_and(|e| e.gen == gen)); + } + } + + fn evict_one(&mut self) -> bool { + while let Some((id, gen)) = self.lru.pop_front() { + if self.entries.get(&id).is_some_and(|e| e.gen == gen) { + if let Some(old) = self.entries.remove(&id) { + self.bytes -= old.bytes(); + if let Some(ids) = self.by_key.get_mut(&old.key) { + ids.retain(|&x| x != id); + if ids.is_empty() { + self.by_key.remove(&old.key); + } + } + return true; + } + } + } + false + } + fn get(&mut self, key: &ShaderKey, blob: &[u8]) -> Option> { - let at = self - .entries + let id = self + .by_key + .get(key)? .iter() - .rposition(|e| &e.key == key && e.blob == blob)?; - let entry = self.entries.remove(at)?; - let shader = entry.shader.clone(); - self.entries.push_back(entry); + .copied() + .find(|id| self.entries.get(id).is_some_and(|e| e.blob == blob))?; + self.next_gen += 1; + let gen = self.next_gen; + let shader = { + let entry = self.entries.get_mut(&id)?; + entry.gen = gen; + entry.shader.clone() + }; + self.lru.push_back((id, gen)); + self.compact_lru(); Some(shader) } fn insert(&mut self, key: ShaderKey, blob: &[u8], shader: Arc) { + if let Some(ids) = self.by_key.get(&key) { + if ids.iter().any(|id| self.entries.get(id).is_some_and(|e| e.blob == blob)) { + return; + } + } let bytes = blob.len() + key.cache_dir.capacity() + shader.dxil.capacity() @@ -522,21 +583,43 @@ impl ShaderCache { if bytes > self.limit { return; } - while self.bytes + bytes > self.limit || self.entries.len() >= 128 { - let Some(old) = self.entries.pop_front() else { + while self.bytes + bytes > self.limit || self.entries.len() >= SHADER_CACHE_MAX_ENTRIES { + if !self.evict_one() { break; - }; - self.bytes -= old.bytes(); + } } - self.entries.push_back(ShaderEntry { - key, - blob: blob.to_vec(), - shader, - }); + self.next_id += 1; + self.next_gen += 1; + let (id, gen) = (self.next_id, self.next_gen); + self.by_key.entry(key.clone()).or_default().push(id); + self.entries.insert( + id, + ShaderEntry { + key, + blob: blob.to_vec(), + shader, + gen, + }, + ); + self.lru.push_back((id, gen)); self.bytes += bytes; } } +/// Per-`ShaderKey` in-flight mutex so concurrent PSO workers requesting the same shader coalesce +/// into a single translation/compilation instead of translating the same program N times in parallel. +fn shader_flight(key: ShaderKey) -> Arc> { + static FLIGHTS: OnceLock>>>> = OnceLock::new(); + let mut flights = FLIGHTS.get_or_init(|| Mutex::new(HashMap::new())).lock().unwrap(); + flights.retain(|_, v| v.strong_count() != 0); + if let Some(flight) = flights.get(&key).and_then(Weak::upgrade) { + return flight; + } + let flight = Arc::new(Mutex::new(())); + flights.insert(key, Arc::downgrade(&flight)); + flight +} + fn cached_shader( cache: &Mutex, key: ShaderKey, @@ -547,7 +630,23 @@ fn cached_shader( dxc::note_memory_hit(); return Ok(shader); } - // Keep compilation outside the cache lock, including cached-only probes. + // Cached-only probes (non-blocking PSO creation) must never block on an in-flight worker. + if dxc::in_cached_only() { + let shader = Arc::new(compile_one()?); + let mut cache = cache.lock().unwrap(); + if let Some(existing) = cache.get(&key, blob) { + return Ok(existing); + } + cache.insert(key, blob, shader.clone()); + return Ok(shader); + } + let flight = shader_flight(key.clone()); + let _guard = flight.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(shader) = cache.lock().unwrap().get(&key, blob) { + dxc::note_memory_hit(); + return Ok(shader); + } + // Keep compilation outside the cache lock. let shader = Arc::new(compile_one()?); let mut cache = cache.lock().unwrap(); if let Some(existing) = cache.get(&key, blob) { @@ -684,6 +783,7 @@ pub(crate) fn console_translation(blob: &[u8], stage: Stage, sampler_base: u32, Stage::Vertex => 4, Stage::Pixel => 5, Stage::Compute => 6, + Stage::Mesh => return Err("mesh shaders go through console_mesh".into()), }; let f = sh .fssm @@ -746,17 +846,44 @@ pub fn console_mesh(blob: &[u8], ps: Option<&[u8]>, split_wave64: bool) -> Resul let p = f.programs.first().ok_or("FSSM without a program")?; let code = &f.data[p.offset..p.offset + p.len]; let wave64 = super::detect_wave64(code); - // `XCL_DIRECT_DXIL=1`: the compute pass through the direct DXIL translator (HLSL fallback) + // `XCL_DIRECT_DXIL=1`: the compute pass through the direct DXIL translator, cached in RAM + // (`ShaderCache` + in-flight coalescing) and on disk (`translated/v2`) across all `(MS, PS)` + // pipelines that share this mesh shader (HLSL fallback on unsupported ops). if crate::gpu::dxil::kernel::enabled() { - let o = crate::gpu::dxil::kernel::KernelOptions { wave64, split: wave64 && split_wave64, mem_windows: mem_windows(), sampler_base: 0 }; - match crate::gpu::dxil::kernel::translate_mesh(code, o, ms) { - Ok(k) => { - crate::gpu::dxil::coverage::record_translated("MS"); + let windows = mem_windows(); + let split = wave64 && split_wave64; + let translate_ms = || { + if dxc::defer() { + return Err("DXIL not compiled yet".into()); + } + let o = crate::gpu::dxil::kernel::KernelOptions { wave64, split, mem_windows: windows, sampler_base: 0 }; + let k = crate::gpu::dxil::kernel::translate_mesh(code, o, ms)?; + crate::gpu::dxil::coverage::record_translated("MS"); + dump_direct(blob, &k.dxil); + Ok(Compiled { dxil: k.dxil, samplers: k.static_samplers }) + }; + let compiled = if cache_allowed(Stage::Mesh, |name| std::env::var_os(name).is_some()) { + let key = ShaderKey { + hash: crate::gpu::shader::fnv64(blob), + stage: Stage::Mesh, + sampler_base: 0, + windows, + split_wave64: split, + cache_dir: dxc::cache_dir(), + }; + let from_disk = || translated::cached(&dxc::cache_dir(), blob, Stage::Mesh, 0, windows, split, translate_ms); + cached_shader(shader_cache(), key, blob, from_disk).map(|s| s.as_ref().clone()) + } else { + translate_ms() + }; + match compiled { + Ok(c) => { 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 Ok(TwoPass { cs: c.dxil, ms: msb, record, mesh_groups_per_record, samplers: c.samplers }); } + Err(e) if dxc::in_cached_only() => return Err(e), Err(e) => direct_fallback("MS", &e), } } @@ -1148,6 +1275,7 @@ mod shader_cache_tests { key: key(1), blob: b"a".to_vec(), shader: t.clone(), + gen: 0, } .bytes(); let mut cache = ShaderCache::new(limit); @@ -1169,14 +1297,45 @@ mod shader_cache_tests { assert!(cache.get(&key(4), b"d").is_none()); assert_eq!(cache.bytes, limit); assert_eq!(cache.entries.len(), 2); - let mut cache = ShaderCache::new(1 << 20); - for i in 0..129 { + let mut cache = ShaderCache::new(64 << 20); + for i in 0..=(SHADER_CACHE_MAX_ENTRIES as u64) { cache.insert(key(i), b"a", t.clone()); } - assert_eq!(cache.entries.len(), 128); + assert_eq!(cache.entries.len(), SHADER_CACHE_MAX_ENTRIES); assert!(cache.get(&key(0), b"a").is_none()); } + #[test] + fn shader_cache_coalesces_concurrent_same_key_compiles() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let cache = Mutex::new(ShaderCache::new(1 << 20)); + let compiles = AtomicUsize::new(0); + let barrier = std::sync::Barrier::new(4); + let k = key(0xC0A1_E5CE); + std::thread::scope(|scope| { + let mut threads = Vec::new(); + for _ in 0..4 { + let cache = &cache; + let compiles = &compiles; + let barrier = &barrier; + let k = k.clone(); + threads.push(scope.spawn(move || { + barrier.wait(); + cached_shader(cache, k, b"shared-ms", || { + compiles.fetch_add(1, Ordering::AcqRel); + std::thread::sleep(std::time::Duration::from_millis(40)); + Ok(compiled(0x42)) + }) + })); + } + let results: Vec<_> = threads.into_iter().map(|t| t.join().unwrap().unwrap()).collect(); + assert_eq!(compiles.load(Ordering::Acquire), 1, "concurrent same-key translates must coalesce to 1"); + for r in &results[1..] { + assert!(Arc::ptr_eq(&results[0], r)); + } + }); + } + #[test] fn shader_cache_bypasses_debug_overrides() { for name in ["XCL_RECOMP_NO_STRUCTURED", "XCL_RECOMP_WHY", "XCL_X64_ALL_MASKS", "XCL_WAVE64_SPIN"] { diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index fed31e6224..49c0cd711c 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -3929,9 +3929,22 @@ pub(crate) mod driver_cache { format!("{:016x}-{:x}-{:x}.pso", crate::gpu::shader::fnv64(dxil), dxil.len(), flags) } - pub fn path(dxil: &[u8], flags: i32) -> Option { + /// The file of a translated graphics pipeline keyed by its full state + shader digest. + pub fn graphics_name(hash: u64, bytes: usize) -> String { + format!("gfx-{hash:016x}-{bytes:x}.pso") + } + + fn enabled() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - ON.get_or_init(|| std::env::var("XCL_PSO_DISK_CACHE").map_or(true, |v| v.trim() != "0")).then(|| crate::gpu::recomp::dxc::cache_dir().join("driver").join(name(dxil, flags))) + *ON.get_or_init(|| std::env::var("XCL_PSO_DISK_CACHE").map_or(true, |v| v.trim() != "0")) + } + + pub fn path(dxil: &[u8], flags: i32) -> Option { + enabled().then(|| crate::gpu::recomp::dxc::cache_dir().join("driver").join(name(dxil, flags))) + } + + pub fn graphics_path(hash: u64, bytes: usize) -> Option { + enabled().then(|| crate::gpu::recomp::dxc::cache_dir().join("driver").join(graphics_name(hash, bytes))) } pub fn load(p: &Path) -> Option> { @@ -4131,19 +4144,36 @@ mod compute_blob_tests { } } -/// The driver's blob of the PSO just built (adopted: its PC `GetCachedBlob` through `orig_fn`). -unsafe fn keep_compute_blob(key: (u64, usize, i32), pso: *mut c_void, dxil_len: usize) { - if dxil_len < COMPUTE_BLOB_MIN_DXIL || pso.is_null() || !is_adopted(pso) || compute_blob(key).is_some() { - return; - } - type GetBlob = unsafe extern "system" fn(*mut c_void, *mut *mut c_void) -> HRESULT; - let get: GetBlob = std::mem::transmute(orig_fn(pso, slot_of(pso, "GetCachedBlob"))); - let mut raw = std::ptr::null_mut(); - if get(pso, &mut raw) < 0 || raw.is_null() { - return; +/// Read `GetCachedBlob` from either an adopted or raw PC `ID3D12PipelineState`. +unsafe fn read_pso_cached_blob(pso: *mut c_void) -> Option> { + if pso.is_null() { + return None; } + let raw = if is_adopted(pso) { + type GetBlob = unsafe extern "system" fn(*mut c_void, *mut *mut c_void) -> HRESULT; + let get: GetBlob = std::mem::transmute(orig_fn(pso, slot_of(pso, "GetCachedBlob"))); + let mut out = std::ptr::null_mut(); + if get(pso, &mut out) < 0 || out.is_null() { + return None; + } + out + } else { + let p = ID3D12PipelineState::from_raw_borrowed(&pso)?; + let blob = p.GetCachedBlob().ok()?; + return Some(std::slice::from_raw_parts(blob.GetBufferPointer() as *const u8, blob.GetBufferSize()).to_vec()); + }; let blob = ID3DBlob::from_raw(raw); let bytes = std::slice::from_raw_parts(blob.GetBufferPointer() as *const u8, blob.GetBufferSize()).to_vec(); + (!bytes.is_empty()).then_some(bytes) +} + +/// The driver's blob of the PSO just built (works on both adopted title PSOs and raw PC compute +/// passes owned by `TwoPassPso`). +unsafe fn keep_compute_blob(key: (u64, usize, i32), pso: *mut c_void, dxil_len: usize) { + if dxil_len < COMPUTE_BLOB_MIN_DXIL || pso.is_null() || compute_blob(key).is_some() { + return; + } + let Some(bytes) = read_pso_cached_blob(pso) else { return }; let mut g = COMPUTE_BLOBS.lock().unwrap(); let (m, total) = g.get_or_insert_with(|| (HashMap::new(), 0)); if bytes.is_empty() || *total + bytes.len() > COMPUTE_BLOBS_MAX { @@ -4153,6 +4183,226 @@ unsafe fn keep_compute_blob(key: (u64, usize, i32), pso: *mut c_void, dxil_len: m.insert(key, std::sync::Arc::new(bytes)); } +/// The driver's compiled form of translated graphics pipelines (`GetCachedBlob`), +/// keyed by `(full_state_and_shader_hash, total_dxil_bytes)`, up to `GRAPHICS_BLOBS_MAX`. +static GRAPHICS_BLOBS: Mutex>>, usize)>> = Mutex::new(None); +const GRAPHICS_BLOBS_MAX: usize = 256 << 20; + +fn graphics_blob(key: (u64, usize)) -> Option>> { + GRAPHICS_BLOBS.lock().unwrap().as_ref().and_then(|(m, _)| m.get(&key).cloned()) +} + +fn forget_graphics_blob(key: (u64, usize)) { + if let Some((m, total)) = GRAPHICS_BLOBS.lock().unwrap().as_mut() { + if let Some(b) = m.remove(&key) { + *total -= b.len(); + } + } +} + +unsafe fn keep_graphics_blob(key: (u64, usize), pso: *mut c_void, dxil_len: usize) { + if dxil_len < COMPUTE_BLOB_MIN_DXIL || pso.is_null() || graphics_blob(key).is_some() { + return; + } + let Some(bytes) = read_pso_cached_blob(pso) else { return }; + let mut g = GRAPHICS_BLOBS.lock().unwrap(); + let (m, total) = g.get_or_insert_with(|| (HashMap::new(), 0)); + if bytes.is_empty() || *total + bytes.len() > GRAPHICS_BLOBS_MAX { + return; + } + *total += bytes.len(); + m.insert(key, std::sync::Arc::new(bytes)); +} + +/// Deterministic FNV-1a digest of every field in a translated PC graphics PSO (shaders, static +/// samplers, blend/rasterizer/depth-stencil state, input layout, render target / depth formats, +/// sample desc, topology, flags) for in-memory and on-disk driver blob caching. +unsafe fn graphics_blob_key( + copy: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, + vs_dxil: &[u8], + ps_dxil: Option<&[u8]>, + rect_gs: Option<&[u8]>, + samplers: &[crate::gpu::recomp::pso::StaticSampler], +) -> (u64, usize) { + let mut h = 0xcbf2_9ce4_8422_2325u64; + let feed = |h: &mut u64, bytes: &[u8]| { + for &b in bytes { + *h ^= b as u64; + *h = h.wrapping_mul(0x0000_0100_0000_01b3); + } + }; + let feed_u64 = |h: &mut u64, v: u64| feed(h, &v.to_le_bytes()); + let feed_u32 = |h: &mut u64, v: u32| feed(h, &v.to_le_bytes()); + let feed_u8 = |h: &mut u64, v: u8| feed(h, &[v]); + + feed_u64(&mut h, crate::gpu::shader::fnv64(vs_dxil)); + feed_u64(&mut h, vs_dxil.len() as u64); + if let Some(ps) = ps_dxil { + feed_u64(&mut h, crate::gpu::shader::fnv64(ps)); + feed_u64(&mut h, ps.len() as u64); + } else { + feed_u64(&mut h, 0); + } + if let Some(gs) = rect_gs { + feed_u64(&mut h, crate::gpu::shader::fnv64(gs)); + feed_u64(&mut h, gs.len() as u64); + } else { + feed_u64(&mut h, 0); + } + feed_u64(&mut h, samplers.len() as u64); + for (w, cmp) in samplers { + for &x in w { + feed_u32(&mut h, x); + } + feed_u8(&mut h, *cmp as u8); + } + // Hash BlendState, RasterizerState, and DepthStencilState field-by-field so struct + // padding bytes (e.g. D3D12_RENDER_TARGET_BLEND_DESC tail padding and the 2 bytes after + // DepthStencilState.StencilWriteMask) never cause nondeterministic cache keys. + let bs = ©.BlendState; + feed_u32(&mut h, bs.AlphaToCoverageEnable.0 as u32); + feed_u32(&mut h, bs.IndependentBlendEnable.0 as u32); + for rt in &bs.RenderTarget { + feed_u32(&mut h, rt.BlendEnable.0 as u32); + feed_u32(&mut h, rt.LogicOpEnable.0 as u32); + feed_u32(&mut h, rt.SrcBlend.0 as u32); + feed_u32(&mut h, rt.DestBlend.0 as u32); + feed_u32(&mut h, rt.BlendOp.0 as u32); + feed_u32(&mut h, rt.SrcBlendAlpha.0 as u32); + feed_u32(&mut h, rt.DestBlendAlpha.0 as u32); + feed_u32(&mut h, rt.BlendOpAlpha.0 as u32); + feed_u32(&mut h, rt.LogicOp.0 as u32); + feed_u8(&mut h, rt.RenderTargetWriteMask); + } + feed_u32(&mut h, copy.SampleMask); + let rs = ©.RasterizerState; + feed_u32(&mut h, rs.FillMode.0 as u32); + feed_u32(&mut h, rs.CullMode.0 as u32); + feed_u32(&mut h, rs.FrontCounterClockwise.0 as u32); + feed_u32(&mut h, rs.DepthBias as u32); + feed_u32(&mut h, rs.DepthBiasClamp.to_bits()); + feed_u32(&mut h, rs.SlopeScaledDepthBias.to_bits()); + feed_u32(&mut h, rs.DepthClipEnable.0 as u32); + feed_u32(&mut h, rs.MultisampleEnable.0 as u32); + feed_u32(&mut h, rs.AntialiasedLineEnable.0 as u32); + feed_u32(&mut h, rs.ForcedSampleCount); + feed_u32(&mut h, rs.ConservativeRaster.0 as u32); + let ds = ©.DepthStencilState; + feed_u32(&mut h, ds.DepthEnable.0 as u32); + feed_u32(&mut h, ds.DepthWriteMask.0 as u32); + feed_u32(&mut h, ds.DepthFunc.0 as u32); + feed_u32(&mut h, ds.StencilEnable.0 as u32); + feed_u8(&mut h, ds.StencilReadMask); + feed_u8(&mut h, ds.StencilWriteMask); + for op in [&ds.FrontFace, &ds.BackFace] { + feed_u32(&mut h, op.StencilFailOp.0 as u32); + feed_u32(&mut h, op.StencilDepthFailOp.0 as u32); + feed_u32(&mut h, op.StencilPassOp.0 as u32); + feed_u32(&mut h, op.StencilFunc.0 as u32); + } + feed_u32(&mut h, copy.InputLayout.NumElements); + if copy.InputLayout.NumElements > 0 && !copy.InputLayout.pInputElementDescs.is_null() { + let elems = std::slice::from_raw_parts(copy.InputLayout.pInputElementDescs, copy.InputLayout.NumElements as usize); + for e in elems { + if !e.SemanticName.0.is_null() { + feed(&mut h, std::ffi::CStr::from_ptr(e.SemanticName.0 as *const std::ffi::c_char).to_bytes_with_nul()); + } else { + feed(&mut h, &[0]); + } + feed_u32(&mut h, e.SemanticIndex); + feed_u32(&mut h, e.Format.0 as u32); + feed_u32(&mut h, e.InputSlot); + feed_u32(&mut h, e.AlignedByteOffset); + feed_u32(&mut h, e.InputSlotClass.0 as u32); + feed_u32(&mut h, e.InstanceDataStepRate); + } + } + feed_u32(&mut h, copy.IBStripCutValue.0 as u32); + feed_u32(&mut h, copy.PrimitiveTopologyType.0 as u32); + feed_u32(&mut h, copy.NumRenderTargets); + for f in ©.RTVFormats { + feed_u32(&mut h, f.0 as u32); + } + feed_u32(&mut h, copy.DSVFormat.0 as u32); + feed_u32(&mut h, copy.SampleDesc.Count); + feed_u32(&mut h, copy.SampleDesc.Quality); + feed_u32(&mut h, copy.NodeMask); + feed_u32(&mut h, copy.Flags.0 as u32); + let total_bytes = vs_dxil.len() + ps_dxil.map_or(0, <[u8]>::len) + rect_gs.map_or(0, <[u8]>::len); + (h, total_bytes) +} + +#[cfg(test)] +mod graphics_blob_tests { + use super::*; + + #[test] + fn graphics_blob_key_tracks_shaders_samplers_and_state() { + unsafe { + let mut d = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + d.NumRenderTargets = 1; + d.RTVFormats[0] = windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R8G8B8A8_UNORM; + d.SampleDesc.Count = 1; + let vs = b"vs-dxil-1"; + let ps = b"ps-dxil-1"; + let k0 = graphics_blob_key(&d, vs, Some(ps), None, &[]); + assert_eq!(k0, graphics_blob_key(&d, vs, Some(ps), None, &[])); + assert_ne!(k0, graphics_blob_key(&d, b"vs-dxil-2", Some(ps), None, &[])); + assert_ne!(k0, graphics_blob_key(&d, vs, None, None, &[])); + assert_ne!(k0, graphics_blob_key(&d, vs, Some(ps), Some(b"gs"), &[])); + assert_ne!(k0, graphics_blob_key(&d, vs, Some(ps), None, &[([1, 2, 3, 4], false)])); + let mut d2 = d; + d2.RTVFormats[0] = windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R16G16B16A16_FLOAT; + assert_ne!(k0, graphics_blob_key(&d2, vs, Some(ps), None, &[])); + } + } + + #[test] + fn graphics_blob_key_ignores_struct_padding_bytes() { + unsafe { + let mut a: D3D12_GRAPHICS_PIPELINE_STATE_DESC = std::mem::zeroed(); + let mut b: D3D12_GRAPHICS_PIPELINE_STATE_DESC = std::mem::zeroed(); + // Fill every byte of DepthStencilState and BlendState with distinct poison patterns, + // then populate every semantic field identically so only padding bytes differ. + std::ptr::write_bytes(&mut a.DepthStencilState as *mut _ as *mut u8, 0xAA, std::mem::size_of::()); + std::ptr::write_bytes(&mut b.DepthStencilState as *mut _ as *mut u8, 0x55, std::mem::size_of::()); + std::ptr::write_bytes(&mut a.BlendState as *mut _ as *mut u8, 0xAA, std::mem::size_of::()); + std::ptr::write_bytes(&mut b.BlendState as *mut _ as *mut u8, 0x55, std::mem::size_of::()); + + for d in [&mut a, &mut b] { + d.DepthStencilState.DepthEnable = true.into(); + d.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL; + d.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_LESS; + d.DepthStencilState.StencilEnable = false.into(); + d.DepthStencilState.StencilReadMask = 0xFF; + d.DepthStencilState.StencilWriteMask = 0xFF; + d.DepthStencilState.FrontFace = D3D12_DEPTH_STENCILOP_DESC::default(); + d.DepthStencilState.BackFace = D3D12_DEPTH_STENCILOP_DESC::default(); + d.BlendState.AlphaToCoverageEnable = false.into(); + d.BlendState.IndependentBlendEnable = false.into(); + for rt in &mut d.BlendState.RenderTarget { + rt.BlendEnable = false.into(); + rt.LogicOpEnable = false.into(); + rt.SrcBlend = D3D12_BLEND_ONE; + rt.DestBlend = D3D12_BLEND_ZERO; + rt.BlendOp = D3D12_BLEND_OP_ADD; + rt.SrcBlendAlpha = D3D12_BLEND_ONE; + rt.DestBlendAlpha = D3D12_BLEND_ZERO; + rt.BlendOpAlpha = D3D12_BLEND_OP_ADD; + rt.LogicOp = D3D12_LOGIC_OP_NOOP; + rt.RenderTargetWriteMask = 0xF; + } + } + let ka = graphics_blob_key(&a, b"vs", Some(b"ps"), None, &[]); + let kb = graphics_blob_key(&b, b"vs", Some(b"ps"), None, &[]); + assert_eq!(ka, kb, "padding bytes must not affect graphics_blob_key"); + + b.DepthStencilState.StencilWriteMask = 0x7F; + assert_ne!(ka, graphics_blob_key(&b, b"vs", Some(b"ps"), None, &[])); + } + } +} + unsafe fn translated_graphics_pso(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option { with_switch_fallback(|| translated_graphics_pso_once(this, f, desc, riid, ppv)) } @@ -4171,14 +4421,14 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const note_translation_error("PSO with HS/DS – not supported yet".into()); return None; } + // made when first used (`pso_async::lazy`): not even translated now (covers both VS+PS and GS) + if super::pso_async::lazy() && crate::gpu::recomp::dxc::defer() { + return None; + } if let Some(gs) = shader_bytes(&d.GS).filter(|g| is_console(g)) { let _ = f; return Some(translated_gs_pso(this, d, vs, gs, riid, ppv)); } - // made when first used (`pso_async::lazy`): not even translated now - if super::pso_async::lazy() && crate::gpu::recomp::dxc::defer() { - return None; - } // a GPU that can run 32-lane waves may run a wave64 VS / PS in waves of 32 (the driver // picks; RDNA2 does for pixel shaders): the lanes 32..63 it reads come from `upper_lanes` // (split_wave64) @@ -4231,7 +4481,48 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const copy.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; } let bytes = vs_dxil.len() + ps_dxil.as_ref().map_or(0, Vec::len) + rect_gs.as_ref().map_or(0, Vec::len); - let hr = driver_compile("graphics", bytes, true, || retry_without_rect_gs(&mut copy, rect_gs.is_some(), |c| finish_pso(this, f, c as *const _ as *const c_void, riid, ppv))); + let gkey = graphics_blob_key(©, &vs_dxil, ps_dxil.as_deref(), rect_gs.as_deref(), &samplers); + let mut cached = graphics_blob(gkey); + let disk = driver_cache::graphics_path(gkey.0, gkey.1); + let from_disk = cached.is_none(); + if from_disk { + cached = disk.as_deref().and_then(driver_cache::load).map(std::sync::Arc::new); + } + if let Some(b) = &cached { + copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE { pCachedBlob: b.as_ptr() as *const c_void, CachedBlobSizeInBytes: b.len() }; + } + let (mut hr, mut in_driver) = driver_compile_identified( + "graphics", + bytes, + gate_compute_driver_compile(cached.is_some()), + Some((ps_hash, cached.is_some())), + || retry_without_rect_gs(&mut copy, rect_gs.is_some(), |c| finish_pso(this, f, c as *const _ as *const c_void, riid, ppv)), + ); + if hr < 0 && cached.is_some() { + forget_graphics_blob(gkey); + if from_disk { + driver_cache::note(false, disk.as_deref()); + } + copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); + let (retried, took) = driver_compile_identified( + "graphics retry", + bytes, + true, + Some((ps_hash, false)), + || retry_without_rect_gs(&mut copy, rect_gs.is_some(), |c| finish_pso(this, f, c as *const _ as *const c_void, riid, ppv)), + ); + hr = retried; + in_driver += took; + } + let reused = hr >= 0 && cached.is_some() && copy.CachedPSO.CachedBlobSizeInBytes != 0; + if hr >= 0 && !reused { + keep_graphics_blob(gkey, *ppv, bytes); + if let (Some(p), Some(b)) = (disk.as_deref(), graphics_blob(gkey)) { + driver_cache::keep(p, &b, in_driver); + } + } else if reused && from_disk { + driver_cache::note(true, None); + } if hr < 0 { note_translation_error(format!( "the driver rejected the PSO with the translated shaders ({hr:#x}; topology type {}, {} render targets, DSV format {}, HS {}, GS {})", @@ -4779,11 +5070,45 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: let mut cdesc = D3D12_COMPUTE_PIPELINE_STATE_DESC::default(); cdesc.pRootSignature = std::mem::transmute::<*mut c_void, std::mem::ManuallyDrop>>(rs); cdesc.CS = bytecode(&tp.cs); + // Reuse the compiled driver blob of the compute pass across all `(MS/GS, PS)` pipelines that + // share `tp.cs` (in memory and on disk), matching `translated_compute_pso_once`. + let ckey = compute_blob_key(&tp.cs, rs as usize, 0); + let mut ccached = compute_blob(ckey); + let cdisk = driver_cache::path(&tp.cs, 0); + let cfrom_disk = ccached.is_none(); + if cfrom_disk { + ccached = cdisk.as_deref().and_then(driver_cache::load).map(std::sync::Arc::new); + } + if let Some(b) = &ccached { + cdesc.CachedPSO = D3D12_CACHED_PIPELINE_STATE { pCachedBlob: b.as_ptr() as *const c_void, CachedBlobSizeInBytes: b.len() }; + } let iid = pc_iid(Kind::PipelineState); let mut compute: *mut c_void = std::ptr::null_mut(); - let hc = driver_compile("compute pass", tp.cs.len(), false, || { + let (mut hc, mut cin_driver) = driver_compile_identified("compute pass", tp.cs.len(), false, None, || { driver_pso(fc, this, &cdesc as *const _ as *const c_void, &iid, &mut compute) }); + if hc < 0 && ccached.is_some() { + forget_compute_blob(ckey); + if cfrom_disk { + driver_cache::note(false, cdisk.as_deref()); + } + cdesc.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); + compute = std::ptr::null_mut(); + let (retried, took) = driver_compile_identified("compute pass retry", tp.cs.len(), false, None, || { + driver_pso(fc, this, &cdesc as *const _ as *const c_void, &iid, &mut compute) + }); + hc = retried; + cin_driver += took; + } + let creused = hc >= 0 && ccached.is_some() && cdesc.CachedPSO.CachedBlobSizeInBytes != 0; + if hc >= 0 && !creused && !compute.is_null() { + keep_compute_blob(ckey, compute, tp.cs.len()); + if let (Some(p), Some(b)) = (cdisk.as_deref(), compute_blob(ckey)) { + driver_cache::keep(p, &b, cin_driver); + } + } else if creused && cfrom_disk { + driver_cache::note(true, None); + } drop(_slot); if hc < 0 || compute.is_null() { note_translation_error(format!("the driver rejected the compute pass of the console {kind} ({hc:#x})")); @@ -4842,6 +5167,10 @@ unsafe fn translated_mesh_stream_once(this: *mut c_void, desc: *const c_void, ri )); return Some(E_INVALIDARG); } + // made when first bound (`pso_async::lazy`): not even translated now + if super::pso_async::lazy() && crate::gpu::recomp::dxc::defer() { + return None; + } let ps = subs.iter().find(|s| s.0 == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS.0 as u32).and_then(|s| payload_shader(s.1)); let (tp, (ps, ps_samplers)) = match (console_mesh(ms, ps, wave32_only(this)), two_pass_ps(ps, graphics_wave32(this))) { (Ok(tp), Ok(ps)) => (tp, ps),