diff --git a/README.md b/README.md index bdb207620f..e340bbe1d9 100644 --- a/README.md +++ b/README.md @@ -126,6 +126,7 @@ xcl shaders D:\data\shaders.rpf --precompile --only cs --pipelines # build com xcl shaders D:\data\shaders.rpf --precompile --only cs --pipelines --used-only # only the compute pipelines an earlier run of the title used xcl shaders D:\data\shaders.rpf --export-hlsl out --record-hash HEX # exact compute HLSL for investigation xcl shaders D:\data\shaders.rpf --measure-pso HEX --repeat 3 # cold driver PSO timing (cache disabled) +xcl shaders D:\data\shaders.rpf --precompile --max-source-mb 16 # skip uncached programs over 16 MB of HLSL (default 8, 0: no limit; listed at the end) xcl rpf D:\data\shaders.rpf --extract NAME --out folder ``` diff --git a/crates/xcl/src/gpu/recomp/dxc.rs b/crates/xcl/src/gpu/recomp/dxc.rs index fe5664f584..1e8b1ee0d5 100644 --- a/crates/xcl/src/gpu/recomp/dxc.rs +++ b/crates/xcl/src/gpu/recomp/dxc.rs @@ -814,6 +814,12 @@ where MISSED.with(|m| m.set(true)); return Err("DXIL not compiled yet".into()); } + // inside `source_capped`: a miss over the cap is refused, not compiled (and not cached) + let cap = SOURCE_CAP.with(|c| c.get()); + if !within_source_cap(src.len(), cap) { + REFUSED.with(|r| r.set(Some(r.get().map_or(src.len(), |n| n.max(src.len()))))); + return Err(format!("{} B HLSL over the source cap of {} B: not compiled", src.len(), cap.unwrap_or(0))); + } counters.misses.fetch_add(1, Ordering::Relaxed); let flight = cache_flight((dir.clone(), key)); let _guard = flight.lock().unwrap_or_else(|e| e.into_inner()); @@ -886,6 +892,26 @@ pub fn compile_counts() -> (usize, usize) { thread_local! { static CACHED_ONLY: std::cell::Cell = const { std::cell::Cell::new(false) }; static MISSED: std::cell::Cell = const { std::cell::Cell::new(false) }; + static SOURCE_CAP: std::cell::Cell> = const { std::cell::Cell::new(None) }; + static REFUSED: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// Whether a cache miss of `len` bytes of HLSL is compiled under a cap of `cap` bytes (None: +/// no cap). +pub fn within_source_cap(len: usize, cap: Option) -> bool { + cap.is_none_or(|cap| len <= cap) +} + +/// Run `f` with cache misses whose HLSL is longer than `cap` bytes refused instead of compiled +/// (`xcl shaders --precompile --max-source-mb`: the biggest programs held every compile thread +/// until memory ran out, #1269); programs already in the cache are still returned. Returns +/// `f`'s result and the length of the longest source refused, if any. +pub fn source_capped(cap: Option, f: impl FnOnce() -> R) -> (R, Option) { + let before = SOURCE_CAP.with(|c| c.replace(cap)); + REFUSED.with(|r| r.set(None)); + let r = f(); + SOURCE_CAP.with(|c| c.set(before)); + (r, REFUSED.with(|r| r.take())) } /// Run `f` without compiling: a program missing from the disk cache fails at once instead @@ -1265,4 +1291,136 @@ mod cache_tests { second_rx.recv_timeout(Duration::from_secs(2)).unwrap(); }); } + + #[test] + fn source_cap_boundaries() { + assert!(within_source_cap(0, None)); + assert!(within_source_cap(usize::MAX, None)); + assert!(within_source_cap(10, Some(10))); + assert!(!within_source_cap(11, Some(10))); + assert!(within_source_cap(9, Some(10))); + assert!(within_source_cap(0, Some(0))); + assert!(!within_source_cap(1, Some(0))); + } + + fn capped_request(dir: &Path, src: &str, counters: &CacheCounters, calls: &AtomicUsize) -> Result<(Vec, bool), String> { + compile_cached_in_observed(dir, src, "main", "cs_6_6", counters, || { + calls.fetch_add(1, Ordering::SeqCst); + Ok(synthetic_dxil(9)) + }) + } + + fn capped_dir(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("xcl-dxil-cap-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + dir + } + + #[test] + fn a_miss_over_the_source_cap_is_refused_and_not_cached() { + let dir = capped_dir("refuse"); + let (counters, calls) = (CacheCounters::default(), AtomicUsize::new(0)); + let src = "x".repeat(100); + let (r, refused) = source_capped(Some(99), || capped_request(&dir, &src, &counters, &calls)); + let error = r.unwrap_err(); + assert!(error.contains("over the source cap"), "{error}"); + assert_eq!(refused, Some(100)); + assert_eq!(calls.load(Ordering::SeqCst), 0); + assert_eq!(counters.snapshot(), CacheStats::default()); + let written = std::fs::read_dir(&dir).map(|d| d.count()).unwrap_or(0); + assert_eq!(written, 0, "a refused source must leave no .dxil behind"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn an_oversized_source_already_cached_is_still_returned() { + let dir = capped_dir("hit"); + let (counters, calls) = (CacheCounters::default(), AtomicUsize::new(0)); + let src = "y".repeat(100); + assert!(!capped_request(&dir, &src, &counters, &calls).unwrap().1); + let (r, refused) = source_capped(Some(10), || capped_request(&dir, &src, &counters, &calls)); + assert_eq!(r.unwrap(), (synthetic_dxil(9), true)); + assert_eq!(refused, None); + assert_eq!(calls.load(Ordering::SeqCst), 1); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_miss_at_or_under_the_source_cap_compiles() { + let dir = capped_dir("under"); + let (counters, calls) = (CacheCounters::default(), AtomicUsize::new(0)); + let (r, refused) = source_capped(Some(100), || capped_request(&dir, &"a".repeat(100), &counters, &calls)); + assert_eq!(r.unwrap(), (synthetic_dxil(9), false)); + assert_eq!(refused, None); + let (r, refused) = source_capped(Some(100), || capped_request(&dir, &"b".repeat(40), &counters, &calls)); + assert!(r.is_ok()); + assert_eq!(refused, None); + assert_eq!(calls.load(Ordering::SeqCst), 2); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_zero_cap_refuses_every_non_empty_miss() { + let dir = capped_dir("zero"); + let (counters, calls) = (CacheCounters::default(), AtomicUsize::new(0)); + let (r, refused) = source_capped(Some(0), || capped_request(&dir, "z", &counters, &calls)); + assert!(r.unwrap_err().contains("over the source cap")); + assert_eq!(refused, Some(1)); + assert_eq!(calls.load(Ordering::SeqCst), 0); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn refusals_report_the_longest_source_and_start_afresh_each_call() { + let dir = capped_dir("longest"); + let (counters, calls) = (CacheCounters::default(), AtomicUsize::new(0)); + let ((a, b), refused) = source_capped(Some(5), || { + ( + capped_request(&dir, &"1".repeat(50), &counters, &calls), + capped_request(&dir, &"2".repeat(20), &counters, &calls), + ) + }); + assert!(a.is_err() && b.is_err()); + assert_eq!(refused, Some(50)); + // the shorter one last must not lower it; the next call must not inherit it + let (r, refused) = source_capped(Some(5), || capped_request(&dir, &"3".repeat(30), &counters, &calls)); + assert!(r.is_err()); + assert_eq!(refused, Some(30)); + let (r, refused) = source_capped(Some(5), || capped_request(&dir, "ok", &counters, &calls)); + assert!(r.is_ok()); + assert_eq!(refused, None); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn the_source_cap_ends_with_source_capped_and_nests() { + let dir = capped_dir("scope"); + let (counters, calls) = (CacheCounters::default(), AtomicUsize::new(0)); + let big = "q".repeat(100); + let ((), _) = source_capped(Some(10), || ()); + assert!(capped_request(&dir, &big, &counters, &calls).is_ok(), "the cap outlived source_capped"); + + let ((inner, outer_after), outer_refused) = source_capped(Some(10), || { + let (inner, inner_refused) = source_capped(Some(1000), || capped_request(&dir, &"w".repeat(200), &counters, &calls)); + assert_eq!(inner_refused, None); + (inner, capped_request(&dir, &"e".repeat(60), &counters, &calls)) + }); + assert!(inner.is_ok()); + assert!(outer_after.unwrap_err().contains("over the source cap"), "the outer cap was not restored"); + assert_eq!(outer_refused, Some(60)); + + // `None` inside a cap lifts it for the inner call only + let ((inner, outer_after), _) = source_capped(Some(10), || { + let (inner, refused) = source_capped(None, || capped_request(&dir, &"r".repeat(300), &counters, &calls)); + assert_eq!(refused, None); + (inner, capped_request(&dir, &"t".repeat(70), &counters, &calls)) + }); + assert!(inner.is_ok() && outer_after.is_err()); + + // `None` outside any cap changes nothing + let (r, refused) = source_capped(None, || capped_request(&dir, &"u".repeat(400), &counters, &calls)); + assert!(r.is_ok()); + assert_eq!(refused, None); + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/crates/xcl/src/main.rs b/crates/xcl/src/main.rs index 6291b5dea0..ae4678ab3d 100644 --- a/crates/xcl/src/main.rs +++ b/crates/xcl/src/main.rs @@ -38,6 +38,8 @@ Usage: compute HLSL for investigation; an exact hash bypasses the size threshold. --measure-pso HEX [--repeat N]: times cache-disabled driver compilation of one exact compute record with XCL's real root signature and static samplers. + --precompile [--only vs|ps|ms|cs] [--max-source-mb N]: compiles every program into the + DXIL cache; skips a program not cached yet whose HLSL is over N MB (8; 0: no limit). --direct [--sample N] [--seed S] [--validate] [--compare]: direct DXIL translator coverage over a seeded sample (default 200 programs, 0 = all); also --timeout, --max-bytes, --threads, --json, --hash H, --dump DIR. diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 68ee303327..3e5460005b 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -898,7 +898,15 @@ pub fn run(path: &Path, args: &[String]) -> i32 { let used = args.iter().any(|a| a == "--used-only").then(crate::hle::d3d12x::pso_async::earlier_used_keys); // the runtime's key: heap windows with `XCL_HEAP_WINDOWS=1` (`pso::mem_windows`) let windows = runtime_windows(); - return precompile(&input, opt("--limit").unwrap_or(usize::MAX), windows, opt("--split").map(|v| v != 0), only.as_deref(), pipelines, used.as_ref(), t0); + // a cache miss with more HLSL than this is refused, not compiled (#1269) + let max_source = match max_source_arg(args) { + Ok(m) => m, + Err(e) => { + eprintln!("xcl shaders: {e}"); + return 2; + } + }; + return precompile(&input, opt("--limit").unwrap_or(usize::MAX), windows, opt("--split").map(|v| v != 0), only.as_deref(), pipelines, used.as_ref(), max_source, t0); } if args.iter().any(|a| a == "--direct") { return direct_sweep(&input, args, top, json, t0); @@ -1326,7 +1334,24 @@ fn used_compute(blob: &[u8], used: &std::collections::HashSet) -> bool { used.contains(&crate::hle::d3d12x::real::shaders_key(&[blob.to_vec()])) } -fn precompile(input: &Input, limit: usize, windows: u32, split: Option, only: Option<&str>, pipelines: bool, used: Option<&std::collections::HashSet>, t0: std::time::Instant) -> i32 { +/// `--max-source-mb N` in bytes: 8 MB without the option (where `dxc` switches to -O0), None +/// (no cap) for 0; an error when N is missing or not a whole number of MB (an unparsed cap +/// would silently run the pass without one). +fn max_source_arg(args: &[String]) -> Result, String> { + let Some(i) = args.iter().position(|a| a == "--max-source-mb") else { return Ok(Some(8 << 20)) }; + match args.get(i + 1).map(|v| (v, v.parse::())) { + Some((_, Ok(0))) => Ok(None), + Some((_, Ok(mb))) => Ok(Some(mb.saturating_mul(1 << 20))), + Some((v, Err(_))) => Err(format!("--max-source-mb {v:?}: expected a whole number of MB")), + None => Err("--max-source-mb: expected a whole number of MB".into()), + } +} + +/// `--max-source-mb N` (`max_source`, bytes): a program missing from the DXIL cache whose HLSL +/// is longer is not compiled (`dxc::source_capped`) and is listed at the end; one already in the +/// cache is still used. 8 MB by default, off with `--max-source-mb 0`. +#[allow(clippy::too_many_arguments)] +fn precompile(input: &Input, limit: usize, windows: u32, split: Option, only: Option<&str>, pipelines: bool, used: Option<&std::collections::HashSet>, max_source: Option, t0: std::time::Instant) -> i32 { let pipelines = if pipelines { match Pipelines::new() { Ok(p) => Some(p), @@ -1347,6 +1372,8 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on if let Some(u) = used { println!("--used-only: {} pipelines earlier runs used (used-pipelines.txt); compute programs of other pipelines are passed over", u.len()); } + // (program, HLSL bytes) refused by `--max-source-mb` + let refused: Mutex> = Mutex::new(Vec::new()); // the compiles run on the DXC pool; these threads translate and keep it fed let threads = recomp::dxc::compile_threads() + 2; // no title runs: only a little commit is kept free besides the compiles @@ -1385,14 +1412,18 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on done.fetch_add(1, Ordering::Relaxed); continue; } - match recomp::pso::console_to_dxil_in(&blob, recomp::pso::Stage::Compute, 0, split, windows) { - Ok(c) => { + match recomp::dxc::source_capped(max_source, || recomp::pso::console_to_dxil_in(&blob, recomp::pso::Stage::Compute, 0, split, windows)) { + (Ok(c), _) => { if let Some(p) = pipelines { p.make(&c); } compiled.fetch_add(1, Ordering::Relaxed) } - Err(e) => { + (Err(_), Some(len)) => { + refused.lock().unwrap().push((name.to_string(), len)); + 0 + } + (Err(e), None) => { let mut g = errors.lock().unwrap(); if g.len() < 10 { g.push(format!("{name}: {}", e.lines().find(|l| l.contains("error")).unwrap_or(e.lines().next().unwrap_or("")))); @@ -1429,10 +1460,14 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on continue; } for (profile, src) in &jobs { - match recomp::dxc::compile_cached(src.as_deref().unwrap_or(&t.hlsl), "main", profile) { - Ok((_, true)) => cached.fetch_add(1, Ordering::Relaxed), - Ok(_) => compiled.fetch_add(1, Ordering::Relaxed), - Err(e) => { + match recomp::dxc::source_capped(max_source, || recomp::dxc::compile_cached(src.as_deref().unwrap_or(&t.hlsl), "main", profile)) { + (Ok((_, true)), _) => cached.fetch_add(1, Ordering::Relaxed), + (Ok(_), _) => compiled.fetch_add(1, Ordering::Relaxed), + (Err(_), Some(len)) => { + refused.lock().unwrap().push((format!("{name} {profile}"), len)); + 0 + } + (Err(e), None) => { let mut g = errors.lock().unwrap(); if g.len() < 10 { g.push(format!("{name}: {}", e.lines().find(|l| l.contains("error")).unwrap_or(""))); @@ -1450,12 +1485,14 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on }); } }); + let mut refused = refused.into_inner().unwrap(); println!( - "compiled {}, already cached {}, errors {}, skipped (GS – paired at pipeline creation) {}, time {:.1} s", + "compiled {}, already cached {}, errors {}, skipped (GS – paired at pipeline creation) {}{}, time {:.1} s", compiled.into_inner(), cached.into_inner(), failed.into_inner(), skipped.into_inner(), + max_source.map(|cap| format!(", refused over the {} MB source cap (--max-source-mb) {}", cap >> 20, refused.len())).unwrap_or_default(), t0.elapsed().as_secs_f64() ); if used.is_some() { @@ -1472,6 +1509,10 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on for e in errors.into_inner().unwrap() { println!(" {e}"); } + refused.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0))); + for (program, len) in &refused { + println!(" refused: {program}, HLSL {:.1} MB", *len as f64 / 1048576.0); + } 0 } @@ -1962,6 +2003,54 @@ mod tests { assert_eq!(agg.failed_count, 0, "{:?}", agg.failed); assert_eq!(agg.insts.undecoded, 0); } + + fn args(a: &[&str]) -> Vec { + a.iter().map(|s| s.to_string()).collect() + } + + #[test] + fn max_source_mb_without_the_option_is_8_mb() { + assert_eq!(max_source_arg(&args(&[])), Ok(Some(8 << 20))); + assert_eq!(max_source_arg(&args(&["--precompile", "--only", "cs"])), Ok(Some(8 << 20))); + } + + #[test] + fn max_source_mb_converts_whole_megabytes_to_bytes() { + assert_eq!(max_source_arg(&args(&["--max-source-mb", "8"])), Ok(Some(8 << 20))); + assert_eq!(max_source_arg(&args(&["--precompile", "--max-source-mb", "8", "--only", "cs"])), Ok(Some(8 << 20))); + // 0 turns the cap off + assert_eq!(max_source_arg(&args(&["--max-source-mb", "0"])), Ok(None)); + // a value too big for bytes saturates, no overflow panic + assert_eq!(max_source_arg(&args(&["--max-source-mb", &usize::MAX.to_string()])), Ok(Some(usize::MAX))); + } + + #[test] + fn max_source_mb_refuses_a_value_that_is_not_a_whole_number() { + let e = max_source_arg(&args(&["--max-source-mb", "8MB"])).unwrap_err(); + assert!(e.contains("--max-source-mb") && e.contains("\"8MB\""), "{e}"); + for bad in ["8.5", "-1", "", " 8"] { + let r = max_source_arg(&args(&["--max-source-mb", bad])); + assert!(r.is_err(), "{bad:?} gave {r:?}"); + } + } + + #[test] + fn max_source_mb_needs_a_value() { + assert_eq!( + max_source_arg(&args(&["--precompile", "--max-source-mb"])), + Err("--max-source-mb: expected a whole number of MB".to_string()) + ); + // a following flag is not taken as the value silently + let e = max_source_arg(&args(&["--max-source-mb", "--only", "cs"])).unwrap_err(); + assert!(e.contains("--only"), "{e}"); + } + + #[test] + fn only_the_first_max_source_mb_is_read() { + assert_eq!(max_source_arg(&args(&["--max-source-mb", "2", "--max-source-mb", "9"])), Ok(Some(2 << 20))); + // a bad first one is not rescued by a good later one + assert!(max_source_arg(&args(&["--max-source-mb", "x", "--max-source-mb", "9"])).is_err()); + } } /// `XCL_DUMP_HLSL=` (`--recomp`): every `XCL_DUMP_EVERY`-th complete translation (by a