From 9f43b6efd65e07e378191e85efbac4ccb20b3bd8 Mon Sep 17 00:00:00 2001 From: Prime <215761102+Prime1997@users.noreply.github.com> Date: Fri, 27 Nov 2026 19:32:21 -0800 Subject: [PATCH 1/2] Shaders: retain shared bytecode for derived pipelines Own shader bytes for each retained graphics base and share equal live bytecode through a bounded weak index. Native derivation survives original-buffer reuse and parent release. The 1024-pipeline fixture retains 81920 payload bytes instead of 83886080 with separate copies; this is payload accounting, not process RAM. Full-suite and retail merge checks remain pending. Assisted-by: Codex (GPT-6) --- README.md | 3 + crates/xcl/src/hle/d3d12x/device_x.rs | 298 +++++++++++++++++++++++--- crates/xcl/src/hle/d3d12x/real.rs | 13 ++ 3 files changed, 287 insertions(+), 27 deletions(-) diff --git a/README.md b/README.md index 83a6798152..7f205c810c 100644 --- a/README.md +++ b/README.md @@ -358,6 +358,9 @@ Fill the reusable DXIL cache ahead of a run with the read-only package wrapper. after the bounded in-memory blob cache fills. This is off by default on AMD; `XCL_PSO_DISK_CACHE=1` forces it on, and `XCL_PSO_DISK_CACHE=0` disables it elsewhere. Compute blobs with different ordered static-sampler root signatures use separate entries. +- Derived graphics pipelines and the depth-bias fallback keep their base pipeline's shader + bytes, sharing identical live stage copies, so the title can reuse the original shader memory + after creating the base. The sharing index retains no byte buffers after their last pipeline. - Direct compute dispatches can split large programs into pipelines built in parallel. `XCL_DIRECT_SPLIT_INSTRUCTIONS` sets the target instructions per piece (default 12500, zero disables splitting). Loops stay in one piece. A strongly connected component over the diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index 260207086e..83f3c9c0b7 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -325,11 +325,11 @@ fn clear_dynamic_depth_bias(d: &mut [u8; GFX_DESC]) { struct GfxDesc([u8; GFX_DESC]); /// A title graphics pipeline's description, kept for CreateDerivedPipelineStateX and the -/// patched-PSO fallback of RSSetDepthBiasX. The input layout is copied; the shaders stay the -/// title's and are checked by hash when a pipeline is derived from it. +/// patched-PSO fallback of RSSetDepthBiasX. The input layout and shader bytecode are retained: +/// the title can reuse their original memory after pipeline creation returns. struct Base { desc: GfxDesc, - shaders: [u64; 5], + _shaders: [Option>>; 5], /// Whether this PSO was created with `D3D12_PIPELINE_STATE_FLAG_DYNAMIC_DEPTH_BIAS`. dynamic_depth_bias: bool, /// Original static `RasterizerState.{DepthBias, DepthBiasClamp, SlopeScaledDepthBias}`. @@ -338,7 +338,7 @@ struct Base { _names: Vec, } -// the desc points into `_elems` / `_names` and the title's shaders; nothing is mutated +// the desc points into `_elems` / `_names` / `_shaders`; nothing is mutated unsafe impl Send for Base {} unsafe impl Sync for Base {} @@ -355,19 +355,51 @@ fn rd64(d: &[u8], o: usize) -> u64 { u64::from_le_bytes(d[o..o + 8].try_into().unwrap()) } -/// hash of each stage's bytecode (0: none); None when one is not readable -unsafe fn stage_hashes(d: &[u8; GFX_DESC]) -> Option<[u64; 5]> { - let mut h = [0; 5]; +type BaseShaderIndex = Mutex>>>>; + +/// A weak index shares live Base shader copies, without keeping their byte buffers alive. +/// Unlike Arc<[u8]>, the Vec payload is released at the last strong reference, even while +/// this index keeps a weak reference. The index itself is bounded too. +fn share_base_shader(index: &BaseShaderIndex, hash: u64, bytes: &[u8], limit: usize) -> Arc> { + let key = (hash, bytes.len()); + let cached = index.lock().unwrap().as_ref().and_then(|m| m.get(&key)).and_then(std::sync::Weak::upgrade); + if let Some(cached) = cached.filter(|v| v.as_slice() == bytes) { + return cached; + } + // Copy outside the lock; another creation may have published the same bytes meanwhile. + let owned = Arc::new(bytes.to_vec()); + let mut g = index.lock().unwrap(); + let m = g.get_or_insert_with(HashMap::new); + if let Some(cached) = m.get(&key).and_then(std::sync::Weak::upgrade).filter(|v| v.as_slice() == bytes) { + return cached; + } + if m.len() >= limit { + m.retain(|_, v| v.strong_count() != 0); + } + if m.len() < limit || m.contains_key(&key) { + m.insert(key, Arc::downgrade(&owned)); + } + owned +} + +/// Own each stage's bytes and point the descriptor at them; None when one is not readable. +unsafe fn own_base_shaders(d: &mut [u8; GFX_DESC]) -> Option<[Option>>; 5]> { + static INDEX: BaseShaderIndex = Mutex::new(None); + const INDEX_LIMIT: usize = 65_536; + let mut shaders = std::array::from_fn(|_| None); for (k, &o) in STAGES.iter().enumerate() { let (p, n) = (rd64(d, o) as usize, rd64(d, o + 8) as usize); - if p != 0 && n != 0 { + if n != 0 { if !crate::gpu::shader::readable(p, n) { return None; } - h[k] = crate::gpu::shader::fnv64(std::slice::from_raw_parts(p as *const u8, n)); + let bytes = std::slice::from_raw_parts(p as *const u8, n); + shaders[k] = Some(share_base_shader(&INDEX, crate::gpu::shader::fnv64(bytes), bytes, INDEX_LIMIT)); } + let at = shaders[k].as_ref().map_or(0, |v| v.as_ptr() as u64); + d[o..o + 8].copy_from_slice(&at.to_le_bytes()); } - Some(h) + Some(shaders) } /// Remember a title graphics pipeline's description (not with stream output). @@ -379,7 +411,7 @@ unsafe fn note_base(pso: *mut c_void, desc: *const c_void, dynamic_depth_bias: b if rd32(&d.0, SO_ENTRIES) != 0 { return; } - let Some(shaders) = stage_hashes(&d.0) else { return }; + let Some(shaders) = own_base_shaders(&mut d.0) else { return }; let static_bias = DepthBias::from_desc(&d.0); let (p, n) = (rd64(&d.0, INPUT_LAYOUT) as usize, rd32(&d.0, INPUT_LAYOUT + 8) as usize); let (mut elems, mut names) = (Vec::new(), Vec::new()); @@ -400,7 +432,7 @@ unsafe fn note_base(pso: *mut c_void, desc: *const c_void, dynamic_depth_bias: b let at = if elems.is_empty() { 0 } else { elems.as_ptr() as u64 }; d.0[INPUT_LAYOUT..INPUT_LAYOUT + 8].copy_from_slice(&at.to_le_bytes()); d.0[CACHED_PSO..CACHED_PSO + 16].fill(0); - let base = Arc::new(Base { desc: d, shaders, dynamic_depth_bias, static_bias, _elems: elems, _names: names }); + let base = Arc::new(Base { desc: d, _shaders: shaders, dynamic_depth_bias, static_bias, _elems: elems, _names: names }); BASES.lock().unwrap().get_or_insert_with(HashMap::new).insert(pso as usize, base); } @@ -421,7 +453,7 @@ pub(super) fn depth_bias_cache_len() -> usize { pub(super) fn register_test_base(pso: usize, dynamic_depth_bias: bool, static_bias: DepthBias) { let base = Arc::new(Base { desc: GfxDesc([0u8; GFX_DESC]), - shaders: [0; 5], + _shaders: std::array::from_fn(|_| None), dynamic_depth_bias, static_bias, _elems: Vec::new(), @@ -460,8 +492,8 @@ pub(super) fn forget_base(pso: usize) { } /// Derive (or reuse from cache) a graphics PSO from `base` with patched rasterizer depth-bias -/// fields for `RSSetDepthBiasX`. Returns `None` if `base` is unknown, its shaders are gone, -/// the cache cap is reached, or creation fails. +/// fields for `RSSetDepthBiasX`. Returns `None` if `base` is unknown, the cache cap is reached, +/// or creation fails. pub(super) unsafe fn depth_bias_pso(dev: *mut c_void, base: usize, bias: DepthBias) -> Option { static N: AtomicU64 = AtomicU64::new(0); if dev.is_null() || base == 0 { @@ -471,12 +503,6 @@ pub(super) unsafe fn depth_bias_pso(dev: *mut c_void, base: usize, bias: DepthBi return Some(cached); } let b = BASES.lock().unwrap().as_ref().and_then(|m| m.get(&base).cloned())?; - if stage_hashes(&b.desc.0) != Some(b.shaders) { - if once(&N, 4) { - crate::xlog_warn!("D3D12.X: RSSetDepthBiasX – shaders of base pipeline {base:#x} are gone"); - } - return None; - } let mut d = b.desc; clear_dynamic_depth_bias(&mut d.0); bias.patch_desc(&mut d.0); @@ -551,12 +577,6 @@ pub(super) unsafe extern "system" fn create_derived_pso_x(this: *mut c_void, bas } return E_FAIL; }; - if stage_hashes(&b.desc.0) != Some(b.shaders) { - if once(&N, 4) { - crate::xlog_warn!("D3D12.X: CreateDerivedPipelineStateX – the shaders of base pipeline {base:?} are gone"); - } - return E_FAIL; - } let n = count as usize; if n > 64 || (n > 0 && (patches.is_null() || !crate::gpu::shader::readable(patches as usize, n * PATCH))) { return E_INVALIDARG; @@ -1616,6 +1636,230 @@ mod tests { assert_eq!(pc_initial_state_for_desc(0x6, 0x2, 0x8), 0x10); } + // These keys name bookkeeping entries only, never COM objects. Each test owns its key and + // removes the entry even on an assertion failure; no D3D device or process-wide setting. + struct TestBaseKey(Box); + impl TestBaseKey { + fn new() -> Self { Self(Box::new(0)) } + fn ptr(&self) -> *mut c_void { (&*self.0 as *const u8) as *mut c_void } + fn get(&self) -> Arc { BASES.lock().unwrap().as_ref().unwrap()[&(self.ptr() as usize)].clone() } + } + impl Drop for TestBaseKey { + fn drop(&mut self) { forget_base(self.ptr() as usize); } + } + + #[test] + fn base_shader_bytes_survive_title_memory_reuse() { + let key = TestBaseKey::new(); + let mut title: [Vec; 5] = std::array::from_fn(|k| vec![k as u8 + 1; k + 4]); + let original = title.clone(); + let mut desc = GfxDesc([0; GFX_DESC]); + for (bytes, &o) in title.iter().zip(&STAGES) { + desc.0[o..o + 8].copy_from_slice(&(bytes.as_ptr() as u64).to_le_bytes()); + desc.0[o + 8..o + 16].copy_from_slice(&(bytes.len() as u64).to_le_bytes()); + } + unsafe { note_base(key.ptr(), desc.0.as_ptr().cast(), false); } + let base = key.get(); + // Keep the original allocation readable: the old implementation fails an assertion, + // not a dangling-pointer read, when the title reuses it for another shader. + for bytes in &mut title { bytes.fill(0xEE); } + for (expected, &o) in original.iter().zip(&STAGES) { + let (p, n) = (rd64(&base.desc.0, o), rd64(&base.desc.0, o + 8)); + assert_eq!(unsafe { std::slice::from_raw_parts(p as *const u8, n as usize) }, expected); + assert_ne!(p, rd64(&desc.0, o), "the retained descriptor must own this stage"); + } + // Both derived creation paths clone this Arc while using its descriptor. A concurrent + // forget must not invalidate any of its shader pointers. + forget_base(key.ptr() as usize); + drop(title); + for (expected, &o) in original.iter().zip(&STAGES) { + assert_eq!(unsafe { std::slice::from_raw_parts(rd64(&base.desc.0, o) as *const u8, expected.len()) }, expected); + } + } + + #[test] + fn derived_base_owns_shader_bytes_after_parent_is_forgotten() { + let parent = TestBaseKey::new(); + let child = TestBaseKey::new(); + let mut title = vec![0x11u8, 0x22, 0x33, 0x44]; + let mut desc = GfxDesc([0; GFX_DESC]); + desc.0[STAGES[0]..STAGES[0] + 8].copy_from_slice(&(title.as_ptr() as u64).to_le_bytes()); + desc.0[STAGES[0] + 8..STAGES[0] + 16].copy_from_slice(&(title.len() as u64).to_le_bytes()); + unsafe { note_base(parent.ptr(), desc.0.as_ptr().cast(), false); } + let base = parent.get(); + let mut derived = base.desc; + let mut patch = [0; PATCH]; + patch[0..4].copy_from_slice(&3u32.to_le_bytes()); + patch[4..8].copy_from_slice(&0x1234u32.to_le_bytes()); + assert_eq!(apply_patch(&mut derived.0, &patch), Ok(true)); + // This is the same note_base step made after create_derived_pso_x succeeds. + unsafe { note_base(child.ptr(), derived.0.as_ptr().cast(), false); } + let retained = child.get(); + title.fill(0xEE); + let p = rd64(&retained.desc.0, STAGES[0]); + assert_eq!(unsafe { std::slice::from_raw_parts(p as *const u8, 4) }, &[0x11, 0x22, 0x33, 0x44]); + assert_eq!(p, rd64(&base.desc.0, STAGES[0]), "the child shares owned bytes, not title memory"); + forget_base(parent.ptr() as usize); + drop(base); + drop(title); + assert_eq!(unsafe { std::slice::from_raw_parts(p as *const u8, 4) }, &[0x11, 0x22, 0x33, 0x44]); + assert_eq!(rd32(&retained.desc.0, 0x1C0), 0x1234); + assert_eq!(rd64(&retained.desc.0, STAGES[1] + 8), 0, "absent stages stay absent"); + } + + #[test] + fn base_shader_copy_rejects_unreadable_nonempty_stages() { + let key = TestBaseKey::new(); + let valid = [1u8, 2, 3, 4]; + let mut desc = GfxDesc([0; GFX_DESC]); + desc.0[STAGES[0]..STAGES[0] + 8].copy_from_slice(&(valid.as_ptr() as u64).to_le_bytes()); + desc.0[STAGES[0] + 8..STAGES[0] + 16].copy_from_slice(&4u64.to_le_bytes()); + desc.0[STAGES[1]..STAGES[1] + 8].copy_from_slice(&1u64.to_le_bytes()); + desc.0[STAGES[1] + 8..STAGES[1] + 16].copy_from_slice(&1u64.to_le_bytes()); + unsafe { note_base(key.ptr(), desc.0.as_ptr().cast(), false); } + assert!(base_depth_bias_info(key.ptr() as usize).is_none(), "a partially copied base is not published"); + // A zero length is an absent stage; its input pointer is never read. + desc.0[STAGES[1] + 8..STAGES[1] + 16].fill(0); + unsafe { note_base(key.ptr(), desc.0.as_ptr().cast(), false); } + assert!(base_depth_bias_info(key.ptr() as usize).is_some()); + } + + #[test] + fn base_shader_sharing_checks_collisions_and_bounds_weak_entries() { + let index: BaseShaderIndex = Mutex::new(None); + let a = share_base_shader(&index, 7, &[1, 2, 3], 2); + let same = share_base_shader(&index, 7, &[1, 2, 3], 2); + assert!(Arc::ptr_eq(&a, &same)); + let collision = share_base_shader(&index, 7, &[1, 2, 4], 2); + assert!(!Arc::ptr_eq(&a, &collision)); + assert_eq!(a.as_slice(), &[1, 2, 3]); + assert_eq!(collision.as_slice(), &[1, 2, 4]); + let b = share_base_shader(&index, 7, &[5], 2); + let uncached = share_base_shader(&index, 9, &[6], 2); + assert_eq!(uncached.as_slice(), &[6], "full index still returns owned bytes"); + assert_eq!(index.lock().unwrap().as_ref().unwrap().len(), 2); + let weak = Arc::downgrade(&collision); + drop(collision); + assert!(weak.upgrade().is_none(), "the index does not keep the Vec or its payload live"); + let c = share_base_shader(&index, 9, &[6], 2); + let keys = index.lock().unwrap(); + let keys = keys.as_ref().unwrap(); + assert_eq!(keys.len(), 2); + assert!(!keys.contains_key(&(7, 3)), "dead entry pruned at capacity"); + assert!(keys.contains_key(&(7, 1)) && keys.contains_key(&(9, 1)), "length is part of identity"); + drop((a, same, b, c, uncached)); + } + + #[test] + fn concurrent_bases_publish_one_shader_copy() { + let index = Arc::new(Mutex::new(None)); + let gate = Arc::new(std::sync::Barrier::new(8)); + let threads: Vec<_> = (0..8).map(|_| { + let (index, gate) = (index.clone(), gate.clone()); + std::thread::spawn(move || { + gate.wait(); + share_base_shader(&index, 1, &[7u8; 4096], 2) + }) + }).collect(); + let copies: Vec<_> = threads.into_iter().map(|t| t.join().unwrap()).collect(); + assert!(copies.iter().all(|v| Arc::ptr_eq(&copies[0], v))); + assert_eq!(index.lock().unwrap().as_ref().unwrap().len(), 1); + } + + #[test] + fn many_bases_share_shader_payload() { + const PSOS: usize = 1024; + let (vs, ps) = (vec![0x56u8; 64 << 10], vec![0x50u8; 16 << 10]); + let mut desc = GfxDesc([0; GFX_DESC]); + for (&o, bytes) in STAGES.iter().zip([&vs, &ps]) { + desc.0[o..o + 8].copy_from_slice(&(bytes.as_ptr() as u64).to_le_bytes()); + desc.0[o + 8..o + 16].copy_from_slice(&(bytes.len() as u64).to_le_bytes()); + } + let keys: Vec<_> = (0..PSOS).map(|_| TestBaseKey::new()).collect(); + let mut payload = HashMap::new(); + for key in &keys { + unsafe { note_base(key.ptr(), desc.0.as_ptr().cast(), false); } + let base = key.get(); + for &o in &STAGES { + let (p, n) = (rd64(&base.desc.0, o) as usize, rd64(&base.desc.0, o + 8) as usize); + if n != 0 { payload.insert(p, n); } + } + } + let retained: usize = payload.values().sum(); + let unshared = PSOS * (vs.len() + ps.len()); + eprintln!("S6 payload: bases={PSOS} retained_stages={} unique_allocations={} unique_payload_bytes={retained} per_base_copy_bytes={unshared} base_struct_bytes={}; excludes Arc/index overhead and process commit", PSOS * 2, payload.len(), PSOS * std::mem::size_of::()); + assert_eq!(payload.len(), 2, "all bases share the same two live stage buffers"); + assert_eq!(retained, vs.len() + ps.len()); + } + + /// Native driver creation only: no command list, draw, dispatch or submitted queue work. + #[test] + fn gpu_derived_pipeline_survives_original_shader_reuse() { + use crate::gpu::recomp::{dxc, runner::skip_test}; + if dxc::location().is_err() { return skip_test("no DXC"); } + let mut vs = dxc::compile("float4 main(uint i : SV_VertexID) : SV_Position { return float4(0, 0, 0, 1); }", "main", "vs_6_6", &[]).expect("synthetic VS"); + let mut ps = dxc::compile("float4 main() : SV_Target { return float4(1, 0, 0, 1); }", "main", "ps_6_6", &[]).expect("synthetic PS"); + assert!(!crate::gpu::recomp::pso::is_console(&vs) && !crate::gpu::recomp::pso::is_console(&ps), "native DXIL stays on the synchronous driver path"); + let adapter = match real::init() { + Ok(name) => name, + Err(e) => { eprintln!("S6 device unavailable: {e}"); return skip_test("no GPU or WARP"); } + }; + eprintln!("S6 native adapter={adapter}; validation=PSO creation; dispatches=0"); + unsafe { + let raw = real::device_raw(); + let dev = ID3D12Device::from_raw_borrowed(&raw).unwrap(); + let mut sm = D3D12_FEATURE_DATA_SHADER_MODEL { HighestShaderModel: D3D_SHADER_MODEL_6_6 }; + if dev.CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL, &mut sm as *mut _ as _, std::mem::size_of_val(&sm) as u32).is_err() || sm.HighestShaderModel.0 < D3D_SHADER_MODEL_6_6.0 { + return skip_test("no SM 6.6"); + } + let mut ser = None; + D3D12SerializeRootSignature(&D3D12_ROOT_SIGNATURE_DESC::default(), D3D_ROOT_SIGNATURE_VERSION_1, &mut ser, None).unwrap(); + let ser = ser.unwrap(); + let rs: ID3D12RootSignature = dev.CreateRootSignature(0, std::slice::from_raw_parts(ser.GetBufferPointer() as *const u8, ser.GetBufferSize())).unwrap(); + let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + desc.pRootSignature = std::mem::transmute_copy(&rs); // borrowed; rs stays live below + desc.VS = D3D12_SHADER_BYTECODE { pShaderBytecode: vs.as_ptr().cast(), BytecodeLength: vs.len() }; + desc.PS = D3D12_SHADER_BYTECODE { pShaderBytecode: ps.as_ptr().cast(), BytecodeLength: ps.len() }; + desc.SampleMask = u32::MAX; + desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + desc.RasterizerState.DepthClipEnable = true.into(); + desc.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8; + desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + desc.NumRenderTargets = 1; + desc.RTVFormats[0] = windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R8G8B8A8_UNORM; + desc.SampleDesc.Count = 1; + let before = real::graphics_fallback_attempts_for_test(); + let mut pso = std::ptr::null_mut(); + assert!(create_graphics_pso_pc(raw, (&desc as *const D3D12_GRAPHICS_PIPELINE_STATE_DESC).cast(), &IID_PIPELINE_STATE, &mut pso) >= 0); + assert!(!pso.is_null()); + let base = ID3D12PipelineState::from_raw(pso); + assert!(!super::super::pso_async::is_pending(base.as_raw() as usize), "native base is not an async stand-in"); + assert_eq!(real::graphics_fallback_attempts_for_test(), before, "base uses the supplied shaders"); + vs.fill(0xCC); + ps.fill(0xDD); // pre-fix failure observes live reused memory, never freed memory + let mut patch = [0u8; PATCH]; + patch[0..4].copy_from_slice(&3u32.to_le_bytes()); + patch[4..8].copy_from_slice(&1u32.to_le_bytes()); + pso = std::ptr::null_mut(); + let hr = create_derived_pso_x(raw, base.as_raw(), 1, patch.as_ptr(), &IID_PIPELINE_STATE, &mut pso); + assert!(hr >= 0 && !pso.is_null(), "derived after title reuse: {hr:#x}"); + let child = ID3D12PipelineState::from_raw(pso); + assert!(!super::super::pso_async::is_pending(child.as_raw() as usize), "native child is not an async stand-in"); + assert_eq!(real::graphics_fallback_attempts_for_test(), before, "child uses the retained shaders"); + drop((base, vs, ps)); + pso = std::ptr::null_mut(); + let hr = create_derived_pso_x(raw, child.as_raw(), 0, std::ptr::null(), &IID_PIPELINE_STATE, &mut pso); + assert!(hr >= 0 && !pso.is_null(), "derived after parent release: {hr:#x}"); + let grandchild = ID3D12PipelineState::from_raw(pso); + assert!(!super::super::pso_async::is_pending(grandchild.as_raw() as usize), "native grandchild is not an async stand-in"); + assert_eq!(real::graphics_fallback_attempts_for_test(), before, "grandchild uses the retained shaders"); + drop(grandchild); + drop(child); + assert!(dev.GetDeviceRemovedReason().is_ok()); + } + } + #[test] fn derived_pipeline_patches_land_on_the_desc_parts() { use std::mem::{offset_of, size_of}; diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 1c1c731864..5e227a75e3 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -8617,6 +8617,17 @@ unsafe fn note_pipeline_for_dump(this: *mut c_void, desc: *const c_void, ppv: *m super::capture::note_graphics(*ppv as usize, d, &stages, graphics_wave32(this)); } +#[cfg(test)] +thread_local! { + // Observe synchronous native-DXIL fixture calls without counting other tests' pipelines. + static GRAPHICS_FALLBACK_ATTEMPTS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +#[cfg(test)] +pub(super) fn graphics_fallback_attempts_for_test() -> u64 { + GRAPHICS_FALLBACK_ATTEMPTS.with(|n| n.get()) +} + /// `dev_create_graphics_pso`; `stream`: the desc is a pipeline stream's (`stream_pipeline`). unsafe fn graphics_pso(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void, stream: bool, cacheable: bool) -> HRESULT { super::null::capture_graphics_desc(desc as *const u8); @@ -8638,6 +8649,8 @@ unsafe fn graphics_pso(this: *mut c_void, desc: *const c_void, riid: *const GUID if hr >= 0 || !crate::gpu::shader::readable(desc as usize, std::mem::size_of::()) { return hr; } + #[cfg(test)] + GRAPHICS_FALLBACK_ATTEMPTS.with(|n| n.set(n.get() + 1)); let d = dummy(); let mut copy: D3D12_GRAPHICS_PIPELINE_STATE_DESC = std::ptr::read(desc as *const D3D12_GRAPHICS_PIPELINE_STATE_DESC); copy.VS = bytecode(&d.vs); From 1dad60ed99b343428faff147592de955ae273dfa Mon Sep 17 00:00:00 2001 From: Prime <215761102+Prime1997@users.noreply.github.com> Date: Sat, 28 Nov 2026 00:36:17 -0800 Subject: [PATCH 2/2] Shaders: share pending pipeline shader payloads Adapt the shader interning proposal in PR #827 using the bounded weak Vec ownership index from #3091. Pending compute, graphics and stream recipes share live immutable copies while preserving title-memory lifetime and cache keys. Source patch passed 11 focused CPU tests before integration; full GPU/gameplay validation is waived for this user test build. Concept credit: Cattn / PR #827. Implementation and focused checks: Codex (GPT-6). --- README.md | 2 + crates/xcl/src/hle/d3d12x/device_x.rs | 13 ++- crates/xcl/src/hle/d3d12x/pso_async.rs | 2 +- crates/xcl/src/hle/d3d12x/real.rs | 92 +++++++++++++++++-- .../src/hle/d3d12x/real/compute_build_key.rs | 22 ++--- 5 files changed, 105 insertions(+), 26 deletions(-) diff --git a/README.md b/README.md index 7f205c810c..9851f9a5bf 100644 --- a/README.md +++ b/README.md @@ -361,6 +361,8 @@ Fill the reusable DXIL cache ahead of a run with the read-only package wrapper. - Derived graphics pipelines and the depth-bias fallback keep their base pipeline's shader bytes, sharing identical live stage copies, so the title can reuse the original shader memory after creating the base. The sharing index retains no byte buffers after their last pipeline. +- Pending asynchronous compute, graphics and stream pipelines share these same immutable shader + copies, reducing duplicate CPU storage while large pipeline backlogs wait to be built. - Direct compute dispatches can split large programs into pipelines built in parallel. `XCL_DIRECT_SPLIT_INSTRUCTIONS` sets the target instructions per piece (default 12500, zero disables splitting). Loops stay in one piece. A strongly connected component over the diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index 83f3c9c0b7..aa4a155ef1 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -357,7 +357,7 @@ fn rd64(d: &[u8], o: usize) -> u64 { type BaseShaderIndex = Mutex>>>>; -/// A weak index shares live Base shader copies, without keeping their byte buffers alive. +/// A weak index shares live shader copies, without keeping their byte buffers alive. /// Unlike Arc<[u8]>, the Vec payload is released at the last strong reference, even while /// this index keeps a weak reference. The index itself is bounded too. fn share_base_shader(index: &BaseShaderIndex, hash: u64, bytes: &[u8], limit: usize) -> Arc> { @@ -382,10 +382,15 @@ fn share_base_shader(index: &BaseShaderIndex, hash: u64, bytes: &[u8], limit: us owned } -/// Own each stage's bytes and point the descriptor at them; None when one is not readable. -unsafe fn own_base_shaders(d: &mut [u8; GFX_DESC]) -> Option<[Option>>; 5]> { +/// Share immutable shader storage between retained bases and asynchronous pipeline recipes. +pub(super) fn shared_shader_bytes(bytes: &[u8]) -> Arc> { static INDEX: BaseShaderIndex = Mutex::new(None); const INDEX_LIMIT: usize = 65_536; + share_base_shader(&INDEX, crate::gpu::shader::fnv64(bytes), bytes, INDEX_LIMIT) +} + +/// Own each stage's bytes and point the descriptor at them; None when one is not readable. +unsafe fn own_base_shaders(d: &mut [u8; GFX_DESC]) -> Option<[Option>>; 5]> { let mut shaders = std::array::from_fn(|_| None); for (k, &o) in STAGES.iter().enumerate() { let (p, n) = (rd64(d, o) as usize, rd64(d, o + 8) as usize); @@ -394,7 +399,7 @@ unsafe fn own_base_shaders(d: &mut [u8; GFX_DESC]) -> Option<[Option return None; } let bytes = std::slice::from_raw_parts(p as *const u8, n); - shaders[k] = Some(share_base_shader(&INDEX, crate::gpu::shader::fnv64(bytes), bytes, INDEX_LIMIT)); + shaders[k] = Some(shared_shader_bytes(bytes)); } let at = shaders[k].as_ref().map_or(0, |v| v.as_ptr() as u64); d[o..o + 8].copy_from_slice(&at.to_le_bytes()); diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index df9fabd0da..ab17ef3969 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -9336,7 +9336,7 @@ mod used_tests { super::super::real::compute_build_key::ComputeBuildKey::capture( 1, &windows::Win32::Graphics::Direct3D12::D3D12_COMPUTE_PIPELINE_STATE_DESC::default(), - [tag].into(), + std::sync::Arc::new(vec![tag]), false, ) } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 5e227a75e3..75a8f46ac2 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -8115,9 +8115,9 @@ pub(in crate::hle::d3d12x) mod compute_build_key; /// The title's borrowed root signature is cleared; translated paths install XCL's ABI signature. #[allow(dead_code)] // the vectors only keep the copies alive enum OwnedDesc { - Compute(Box, Vec>), - Graphics(Box, Vec>, Vec, Vec), - Stream(Box<[usize; 2]>, Vec, Vec>), + Compute(Box, Vec>>), + Graphics(Box, Vec>>, Vec, Vec), + Stream(Box<[usize; 2]>, Vec, Vec>>), } unsafe impl Send for OwnedDesc {} @@ -8181,7 +8181,7 @@ impl OwnedDesc { OwnedDesc::Graphics(_, b, ..) => b, OwnedDesc::Stream(_, _, b) => b, }; - let key = shaders_key(blobs); + let key = shader_set_key(blobs.iter().map(|b| b.as_slice())); // each shader by itself too: what a title's shader preparation translates before the // next run (`pso_async::earlier_used_shaders`) let parts: Vec = blobs.iter().map(|b| shader_key(b)).collect(); @@ -8216,10 +8216,10 @@ impl OwnedDesc { } } -/// Copy a shader blob into `blobs` and point `b` at the copy. -unsafe fn own_shader(b: &mut D3D12_SHADER_BYTECODE, blobs: &mut Vec>) { +/// Retain a shared shader copy in `blobs` and point `b` at its owned bytes. +unsafe fn own_shader(b: &mut D3D12_SHADER_BYTECODE, blobs: &mut Vec>>) { if let Some(bytes) = shader_bytes(b) { - blobs.push(bytes.into()); + blobs.push(super::device_x::shared_shader_bytes(bytes)); let v = blobs.last().unwrap(); *b = bytecode(v); } else { @@ -8279,7 +8279,7 @@ unsafe fn own_stream(desc: *const c_void) -> Option { return None; } let mut buf = std::slice::from_raw_parts(base as *const u8, size).to_vec(); - let mut blobs: Vec> = Vec::new(); + let mut blobs: Vec>> = Vec::new(); let mut off = 0usize; while off + 8 <= size { let ty = u32::from_le_bytes(buf[off..off + 4].try_into().ok()?); @@ -8298,7 +8298,7 @@ unsafe fn own_stream(desc: *const c_void) -> Option { if p == 0 || n == 0 { buf[at..at + 16].fill(0); } else if crate::gpu::shader::readable(p, n) { - blobs.push(std::slice::from_raw_parts(p as *const u8, n).into()); + blobs.push(super::device_x::shared_shader_bytes(std::slice::from_raw_parts(p as *const u8, n))); buf[at..at + 8].copy_from_slice(&(blobs.last().unwrap().as_ptr() as u64).to_le_bytes()); } else { return None; @@ -8343,6 +8343,78 @@ mod owned_desc_tests { } } +#[cfg(test)] +mod owned_shader_tests { + use super::*; + use std::sync::Arc; + + fn blobs(owned: &OwnedDesc) -> &[Arc>] { + match owned { + OwnedDesc::Compute(_, b) | OwnedDesc::Graphics(_, b, ..) | OwnedDesc::Stream(_, _, b) => b, + } + } + + #[test] + fn async_recipes_share_shader_bytes_and_keep_them_until_the_last_owner() { + unsafe { + let expected = b"NV-async-owned-desc-lifetime-20261128"; + let mut source = expected.to_vec(); + let compute = D3D12_COMPUTE_PIPELINE_STATE_DESC { CS: bytecode(&source), ..Default::default() }; + let graphics = D3D12_GRAPHICS_PIPELINE_STATE_DESC { VS: bytecode(&source), ..Default::default() }; + let mut stream = [0u8; 24]; + stream[0..4].copy_from_slice(&6u32.to_le_bytes()); + stream[8..16].copy_from_slice(&(source.as_ptr() as u64).to_le_bytes()); + stream[16..24].copy_from_slice(&(source.len() as u64).to_le_bytes()); + let stream_desc = [stream.len(), stream.as_ptr() as usize]; + let mut recipes = vec![ + own_compute((&compute as *const D3D12_COMPUTE_PIPELINE_STATE_DESC).cast()).unwrap(), + own_graphics((&graphics as *const D3D12_GRAPHICS_PIPELINE_STATE_DESC).cast()).unwrap(), + own_stream(stream_desc.as_ptr().cast()).unwrap(), + ]; + let shared = Arc::downgrade(&blobs(&recipes[0])[0]); + for recipe in &recipes { + let bytes = &blobs(recipe)[0]; + assert!(Arc::ptr_eq(&blobs(&recipes[0])[0], bytes), "all async descriptor forms share one shader payload"); + assert_ne!(bytes.as_ptr(), source.as_ptr(), "title memory is copied, not borrowed"); + let pointed = match recipe { + OwnedDesc::Compute(d, _) => d.CS.pShaderBytecode as usize, + OwnedDesc::Graphics(d, ..) => d.VS.pShaderBytecode as usize, + OwnedDesc::Stream(_, s, _) => u64::from_le_bytes(s[8..16].try_into().unwrap()) as usize, + }; + assert_eq!(pointed, bytes.as_ptr() as usize); + assert_eq!(shader_set_key(blobs(recipe).iter().map(|b| b.as_slice())), shaders_key(&[source.clone()])); + } + source.fill(0); + drop(source); + let survivor = recipes.pop().unwrap(); + drop(recipes); + assert_eq!(blobs(&survivor)[0].as_slice(), expected); + assert!(shared.upgrade().is_some(), "the last recipe still owns the payload"); + drop(survivor); + assert!(shared.upgrade().is_none(), "the weak index does not keep the Vec or its payload alive"); + } + } + + #[test] + fn a_thousand_pending_graphics_recipes_keep_two_unique_shader_payloads() { + const RECIPES: usize = 1024; + let (vs, ps) = (vec![0x36u8; 64 << 10], vec![0x37u8; 16 << 10]); + let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { VS: bytecode(&vs), PS: bytecode(&ps), ..Default::default() }; + let recipes: Vec<_> = (0..RECIPES) + .map(|_| unsafe { own_graphics((&desc as *const D3D12_GRAPHICS_PIPELINE_STATE_DESC).cast()).unwrap() }) + .collect(); + let mut payloads = HashMap::new(); + for recipe in &recipes { + for bytes in blobs(recipe) { payloads.insert(bytes.as_ptr() as usize, bytes.len()); } + } + let retained: usize = payloads.values().sum(); + eprintln!("ASYNC_SHADER_PAYLOAD recipes={RECIPES} unique_allocations={} unique_payload_bytes={retained} per_recipe_copy_bytes={}; excludes descriptors, Arc/index overhead and process commit", payloads.len(), RECIPES * (vs.len() + ps.len())); + assert_eq!(payloads.len(), 2); + assert_eq!(retained, vs.len() + ps.len()); + assert_eq!(retained, 81_920); + } +} + /// Raw pointers a one-shot worker needs (the existing process-lifetime device invariant). #[derive(Clone, Copy)] struct Dev(usize, PsoFn); @@ -13655,7 +13727,7 @@ mod mesh_stream_tests { let owned = own_stream(d_valid.as_ptr() as *const c_void).expect("valid stream"); let OwnedDesc::Stream(_, buf, blobs) = owned else { panic!("expected Stream") }; assert_eq!(blobs.len(), 1); - assert_eq!(&*blobs[0], shader.as_slice()); + assert_eq!(blobs[0].as_slice(), shader.as_slice()); let rebased = u64::from_le_bytes(buf[8..16].try_into().unwrap()) as usize; assert_eq!(rebased, blobs[0].as_ptr() as usize); assert_ne!(rebased, shader.as_ptr() as usize); diff --git a/crates/xcl/src/hle/d3d12x/real/compute_build_key.rs b/crates/xcl/src/hle/d3d12x/real/compute_build_key.rs index c35b505bfe..0690a4670c 100644 --- a/crates/xcl/src/hle/d3d12x/real/compute_build_key.rs +++ b/crates/xcl/src/hle/d3d12x/real/compute_build_key.rs @@ -22,7 +22,7 @@ pub(in crate::hle::d3d12x) struct ComputeBuildKey { device: usize, node_mask: u32, flags: i32, - shader: Arc<[u8]>, + shader: Arc>, shader_digest: u64, shader_len: usize, windows: u32, @@ -69,7 +69,7 @@ impl ComputeBuildKey { pub(in crate::hle::d3d12x) fn capture( device: usize, desc: &D3D12_COMPUTE_PIPELINE_STATE_DESC, - shader: Arc<[u8]>, + shader: Arc>, split_wave64: bool, ) -> Self { Self::from_descriptor( @@ -85,7 +85,7 @@ impl ComputeBuildKey { fn from_descriptor( device: usize, desc: &D3D12_COMPUTE_PIPELINE_STATE_DESC, - shader: Arc<[u8]>, + shader: Arc>, windows: u32, split_wave64: bool, policy: ComputePolicyKey, @@ -97,7 +97,7 @@ impl ComputeBuildKey { device: usize, node_mask: u32, flags: i32, - shader: Arc<[u8]>, + shader: Arc>, windows: u32, split_wave64: bool, policy: ComputePolicyKey, @@ -113,7 +113,7 @@ impl ComputeBuildKey { device: usize, node_mask: u32, flags: i32, - shader: Arc<[u8]>, + shader: Arc>, shader_digest: u64, windows: u32, split_wave64: bool, @@ -163,7 +163,7 @@ mod tests { } fn key() -> ComputeBuildKey { - ComputeBuildKey::from_parts(1, 2, 3, [4, 5].into(), 6, false, policy()) + ComputeBuildKey::from_parts(1, 2, 3, Arc::new(vec![4, 5]), 6, false, policy()) } #[test] @@ -202,7 +202,7 @@ mod tests { mutate_policy(|p| p.per_lane = true); mutate_policy(|p| p.disabled_dxil_optimizations = 1); - let other = ComputeBuildKey::from_parts(1, 2, 3, [4, 6].into(), 6, false, policy()); + let other = ComputeBuildKey::from_parts(1, 2, 3, Arc::new(vec![4, 6]), 6, false, policy()); assert_ne!(base, other, "shader"); assert_ne!(hash(&base), hash(&other), "shader"); } @@ -216,7 +216,7 @@ mod tests { fn shader_identity_compares_all_bytes_after_a_digest_collision() { let base = key(); let other = ComputeBuildKey::from_parts_with_digest( - 1, 2, 3, [5, 4].into(), base.shader_digest, 6, false, policy(), + 1, 2, 3, Arc::new(vec![5, 4]), base.shader_digest, 6, false, policy(), ); assert_eq!(hash(&base), hash(&other)); assert_ne!(base, other); @@ -238,14 +238,14 @@ mod tests { std::ptr::write_bytes((&mut b as *mut _ as *mut u8).add(padding), 0xa5, padding_end - padding); } assert_eq!( - ComputeBuildKey::from_descriptor(1, &a, [2, 3].into(), 4, false, policy()), - ComputeBuildKey::from_descriptor(1, &b, [2, 3].into(), 4, false, policy()), + ComputeBuildKey::from_descriptor(1, &a, Arc::new(vec![2, 3]), 4, false, policy()), + ComputeBuildKey::from_descriptor(1, &b, Arc::new(vec![2, 3]), 4, false, policy()), ); } #[test] fn build_key_shares_the_owned_shader_allocation() { - let shader: Arc<[u8]> = [7, 8, 9].into(); + let shader = Arc::new(vec![7u8, 8, 9]); let pointer = shader.as_ptr(); let key = ComputeBuildKey::from_parts(1, 0, 0, shader.clone(), 1, false, policy()); assert_eq!(key.shader.as_ptr(), pointer);