Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
229 changes: 194 additions & 35 deletions crates/xcl/src/gpu/recomp/pso.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,22 @@
//! 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::*;

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?
Expand Down Expand Up @@ -139,15 +140,19 @@ 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<ShaderCache> {
static CACHE: OnceLock<Mutex<ShaderCache>> = 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<Compiled, String> {
let compile_one = || compile_console_shader(blob, stage, sampler_base, windows, split_wave64);
if !cache_allowed(stage, |name| std::env::var_os(name).is_some()) {
return compile_one();
}
static CACHE: OnceLock<Mutex<ShaderCache>> = OnceLock::new();
let cache = CACHE.get_or_init(|| Mutex::new(ShaderCache::new(64 << 20)));
let key = ShaderKey {
hash: crate::gpu::shader::fnv64(blob),
stage,
Expand All @@ -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
Expand Down Expand Up @@ -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");
Expand All @@ -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" });
Expand Down Expand Up @@ -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,
Expand All @@ -477,6 +492,7 @@ struct ShaderEntry {
key: ShaderKey,
blob: Vec<u8>,
shader: Arc<Compiled>,
gen: u64,
}

impl ShaderEntry {
Expand All @@ -489,54 +505,121 @@ impl ShaderEntry {
}

struct ShaderCache {
entries: VecDeque<ShaderEntry>,
entries: HashMap<u64, ShaderEntry>,
by_key: HashMap<ShaderKey, Vec<u64>>,
lru: VecDeque<(u64, u64)>,
next_id: u64,
next_gen: u64,
bytes: usize,
limit: usize,
}

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<Arc<Compiled>> {
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<Compiled>) {
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()
+ shader.samplers.capacity() * std::mem::size_of::<StaticSampler>();
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<Mutex<()>> {
static FLIGHTS: OnceLock<Mutex<HashMap<ShaderKey, Weak<Mutex<()>>>>> = 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<ShaderCache>,
key: ShaderKey,
Expand All @@ -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) {
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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),
}
}
Expand Down Expand Up @@ -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);
Expand All @@ -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"] {
Expand Down
Loading
Loading