Skip to content
Open
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
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,9 +117,27 @@ xcl shaders D:\data\shaders.rpf --top 50 # pack statistics; --recomp / --compi
xcl shaders D:\data\shaders.rpf --precompile --only cs --pipelines # build compute pipelines and save driver blobs for the next run
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 --measure-pso HEX --backend direct --repeat 3 --json
xcl rpf D:\data\shaders.rpf --extract NAME --out folder
```

`--measure-pso --json` reports the exact shader hash and name, backend, selected DXGI
adapter, translation/DXC time, DXIL size, and every cache-disabled driver PSO time. Record
the driver version, OS build, full command line, and GPU power settings beside the JSON;
compare interleaved HLSL/direct runs of the same hash and do not treat an in-game FPS
screenshot as a shader-compiler benchmark.

On NVIDIA, successful `ShaderCacheControl` calls can still leave repeat measurements
cached. With the JSON/backend measurement support above, use
`scripts/measure-nvidia-pso.ps1 -Pack D:\data\shaders.rpf -Hash HEX -Backend direct`.
It copies the exe beside the original, registers a unique temporary NVIDIA profile
with the shader disk cache off, and removes both afterwards, including on measurement
failure. Other profiles and shared cache files are untouched. Run HLSL/direct
interleaved and check the individual timings; this is compilation time, not GPU
execution time. If the script is forcibly terminated, its printed `XCL cold PSO ...`
profile may need removal from NVIDIA settings. Requires Windows NVIDIA NVAPI and
permission to save an application profile; existing application matches cause an error.

- **Without a command line** (xcl.exe opened from Explorer) XCL shows a small menu: *Choose a
game…* (pick its exe or `MicrosoftGame.config`) or *Run again* (the last one). On an error the
window stays open until Enter.
Expand Down
1 change: 1 addition & 0 deletions THIRD_PARTY.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ carry a note in their header about its origin and the date of changes (GPL-2.0
| [LLVM](https://github.com/llvm/llvm-project) | Apache-2.0 WITH LLVM-exception | `tests/data/llvm-amdgpu/*` (test data, not part of the program); GFX10 buffer format values (`UfmtSymbolicGFX10`) in `gpu/recomp/emit.rs` | test vectors; hardware facts |
| [WinDurango](https://github.com/WinDurango/WinDurango) | LGPL-3.0 | no code; d3d12_x.dll export numbers (facts) in `crates/xcl/data/stubdb.toml` | reference only |
| [libHttpClient](https://github.com/microsoft/libHttpClient) | MIT | no code; XTaskQueue/XAsync contract | specification |
| [NVIDIA NVAPI](https://github.com/NVIDIA/nvapi) | MIT | no SDK code; function signatures, IDs and structure layout facts in `scripts/measure-nvidia-pso.ps1` | independently written bindings; system driver DLL loaded at runtime, not distributed |
| Windows XGameRuntime (`System32\xgameruntime.dll`) | system | class GUIDs and slot order of the GDK thunk protocol in `hle/xgameruntime/api.rs` (facts, determined by analysis); APIs XCL does not implement are forwarded to it at runtime | interoperability; not distributed |
| docs.xbox.com | documentation | signatures, enums, structs written independently | reference |
| Rust crates (`Cargo.lock`) | MIT / BSD-2 / Zlib / Unlicense (or with an MIT alternative) | build dependencies | statically linked |
Expand Down
2 changes: 1 addition & 1 deletion crates/xcl/src/gpu/recomp/pso.rs
Original file line number Diff line number Diff line change
Expand Up @@ -597,7 +597,7 @@ fn direct_fallback(stage: &str, err: &str) {

/// A console compute shader through the direct DXIL translator (`gpu::dxil::kernel`).
/// FSPX (driver) containers are left to the HLSL path.
fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split_wave64: bool) -> Result<Compiled, String> {
pub(crate) fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split_wave64: bool) -> Result<Compiled, String> {
let sh = xbox::parse(blob).ok_or("not a console shader container")?;
let f = sh.fssm.iter().find(|f| f.stages.first().is_some_and(|s| s.hw == 6)).ok_or("no hardware CS variant")?;
let Some(Mode::Compute(cs)) = interface(blob, &sh, f) else { return Err("not a compute interface".into()) };
Expand Down
5 changes: 3 additions & 2 deletions crates/xcl/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,9 @@ Usage:
--compile N: additionally compiles N complete translations with DXC.
--export-hlsl DIR [--count N] [--min-kb N] [--record-hash HEX]: writes deterministic
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.
--measure-pso HEX [--repeat N] [--backend hlsl|direct] [--json]:
times cache-disabled driver compilation of one exact compute record.
The default backend is hlsl. Direct translation failures are reported.
--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.
Expand Down
92 changes: 72 additions & 20 deletions crates/xcl/src/shaders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -759,6 +759,19 @@ pub fn run(path: &Path, args: &[String]) -> i32 {
);
}
if let Some(hash) = measure {
let direct = match required("--backend") {
Ok(None) => false,
Ok(Some(v)) if v == "hlsl" => false,
Ok(Some(v)) if v == "direct" => true,
Ok(Some(_)) => {
eprintln!("xcl shaders: --backend must be hlsl or direct");
return 2;
}
Err(e) => {
eprintln!("{e}");
return 2;
}
};
let hash = match parse_record_hash(hash) {
Ok(h) => h,
Err(e) => {
Expand All @@ -772,6 +785,8 @@ pub fn run(path: &Path, args: &[String]) -> i32 {
opt("--repeat").unwrap_or(1).max(1),
runtime_windows(),
opt("--split").map(|v| v != 0),
direct,
json,
);
}
if args.iter().any(|a| a == "--precompile") {
Expand Down Expand Up @@ -910,12 +925,11 @@ enum MeasureError {
Failed(String),
}

/// Compile one exact console compute shader through DXC, then time only the driver's
/// Translate one exact console compute shader, then time only the driver's
/// `CreateComputePipelineState`. The implicit D3D and driver caches must both be disabled;
/// refusing to do that is an error rather than a misleading warm-cache measurement.
/// This is the HLSL path the runtime uses by default (not `XCL_DIRECT_DXIL`).
fn measure_pso(input: &Input, hash: u64, repeat: usize, windows: u32, split: Option<bool>) -> i32 {
match measure_pso_result(input, hash, repeat, windows, split) {
fn measure_pso(input: &Input, hash: u64, repeat: usize, windows: u32, split: Option<bool>, direct: bool, json: bool) -> i32 {
match measure_pso_result(input, hash, repeat, windows, split, direct, json) {
Ok(()) => 0,
Err(MeasureError::Unavailable(e) | MeasureError::Failed(e)) => {
eprintln!("xcl shaders --measure-pso: {e}");
Expand All @@ -924,7 +938,7 @@ fn measure_pso(input: &Input, hash: u64, repeat: usize, windows: u32, split: Opt
}
}

fn measure_pso_result(input: &Input, hash: u64, repeat: usize, windows: u32, split: Option<bool>) -> Result<(), MeasureError> {
fn measure_pso_result(input: &Input, hash: u64, repeat: usize, windows: u32, split: Option<bool>, direct: bool, json: bool) -> Result<(), MeasureError> {
use windows::core::Interface;
use windows::Win32::Graphics::Direct3D12::*;
use MeasureError::{Failed, Unavailable};
Expand All @@ -933,7 +947,9 @@ fn measure_pso_result(input: &Input, hash: u64, repeat: usize, windows: u32, spl
if !is_compute_container(&blob) {
return Err(Failed(format!("{name} is not a console compute shader")));
}
recomp::dxc::location().map_err(|e| Unavailable(format!("DXC: {e}")))?;
if !direct {
recomp::dxc::location().map_err(|e| Unavailable(format!("DXC: {e}")))?;
}
let pipeline = Pipelines::new().map_err(|e| Unavailable(format!("no GPU device: {e}")))?;
// before translating and compiling (tens of seconds for a big program): a machine that
// cannot turn the caches off fails at once
Expand All @@ -942,11 +958,20 @@ fn measure_pso_result(input: &Input, hash: u64, repeat: usize, windows: u32, spl
unsafe { dev9.ShaderCacheControl(cache_kinds, D3D12_SHADER_CACHE_CONTROL_FLAG_DISABLE) }
.map_err(|e| Unavailable(format!("cannot disable the driver cache (Windows Developer Mode is required): {e}")))?;
let split = split.unwrap_or_else(|| recomp::pso::split_wave64_forced() || recomp::pso::wave32_only_for_device(&pipeline.dev));
let (translation, profile) = recomp::pso::console_translation(&blob, recomp::pso::Stage::Compute, 0, windows, split).map_err(|e| Failed(format!("{name}: {e}")))?;
let dxc_start = std::time::Instant::now();
let dxil = recomp::dxc::compile(&translation.hlsl, "main", profile, &[]).map_err(|e| Failed(format!("DXC: {e}")))?;
let dxc_ms = dxc_start.elapsed().as_millis();
let rs = recomp::pso::abi_root_signature_with(&pipeline.dev, true, &translation.static_samplers).map_err(|e| Failed(format!("root signature: {e}")))?;
let start = std::time::Instant::now();
let (dxil, samplers, translation_ms, hlsl_bytes, dxc_ms) = if direct {
let compiled = recomp::pso::direct_compute(&blob, 0, windows, split)
.map_err(|e| Failed(format!("{name}: direct DXIL: {e}")))?;
(compiled.dxil, compiled.samplers, start.elapsed().as_secs_f64() * 1000.0, None, None)
} else {
let (translation, profile) = recomp::pso::console_translation(&blob, recomp::pso::Stage::Compute, 0, windows, split)
.map_err(|e| Failed(format!("{name}: {e}")))?;
let translation_ms = start.elapsed().as_secs_f64() * 1000.0;
let dxc_start = std::time::Instant::now();
let dxil = recomp::dxc::compile(&translation.hlsl, "main", profile, &[]).map_err(|e| Failed(format!("DXC: {e}")))?;
(dxil, translation.static_samplers, translation_ms, Some(translation.hlsl.len()), Some(dxc_start.elapsed().as_secs_f64() * 1000.0))
};
let rs = recomp::pso::abi_root_signature_with(&pipeline.dev, true, &samplers).map_err(|e| Failed(format!("root signature: {e}")))?;
let mut desc = D3D12_COMPUTE_PIPELINE_STATE_DESC {
pRootSignature: std::mem::ManuallyDrop::new(Some(rs)),
CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr().cast(), BytecodeLength: dxil.len() },
Expand All @@ -965,22 +990,43 @@ fn measure_pso_result(input: &Input, hash: u64, repeat: usize, windows: u32, spl
break;
}
}
println!("PSO run {run}/{repeat}: {:.3} s", elapsed.as_secs_f64());
if !json {
println!("PSO run {run}/{repeat}: {:.3} s", elapsed.as_secs_f64());
}
times.push(elapsed.as_secs_f64());
}
// the root signature's reference, on every path
drop(unsafe { std::mem::ManuallyDrop::take(&mut desc.pRootSignature) });
if let Some(e) = failure {
return Err(e);
}
times.sort_by(f64::total_cmp);
let median = if times.len() & 1 == 0 { (times[times.len() / 2 - 1] + times[times.len() / 2]) / 2.0 } else { times[times.len() / 2] };
let mut sorted = times.clone();
sorted.sort_by(f64::total_cmp);
let backend = if direct { "direct" } else { "hlsl" };
let mid = sorted.len() / 2;
let median = if sorted.len() & 1 == 0 { (sorted[mid - 1] + sorted[mid]) / 2.0 } else { sorted[mid] };
if json {
println!("{}", serde_json::json!({
// Keep enough context in every result to reject the kind of unqualified FPS or
// compile-time claim that cannot be reproduced on another adapter. Driver version,
// OS build, and command line remain properties of the benchmark host/run manifest.
"record_hash": format!("{hash:016x}"), "record_name": name,
"backend": backend, "adapter": pipeline.adapter,
"windows": windows & !recomp::HEAP_WINDOWS, "heap_windows": windows & recomp::HEAP_WINDOWS != 0,
"split_wave64": split, "static_samplers": samplers,
"translation_ms": translation_ms, "hlsl_bytes": hlsl_bytes, "dxc_ms": dxc_ms,
"dxil_bytes": dxil.len(), "driver_seconds": times, "driver_median_seconds": median
}));
return Ok(());
}
let dxc = dxc_ms.map_or_else(String::new, |ms| format!(", {ms:.3} ms DXC"));
println!(
"PSO {hash:016x}: {} bytes DXIL, {dxc_ms} ms DXC, {repeat} cache-off run(s), median {:.3} s, min {:.3} s, max {:.3} s, {name}",
"PSO {hash:016x} ({backend}, {}): {} bytes DXIL, {translation_ms:.3} ms translation{dxc}, {repeat} cache-off run(s), median {:.3} s, min {:.3} s, max {:.3} s, {name}",
pipeline.adapter,
dxil.len(),
median,
times[0],
times[times.len() - 1]
sorted[0],
sorted[sorted.len() - 1]
);
Ok(())
}
Expand All @@ -1001,6 +1047,9 @@ fn measure_pso_result(input: &Input, hash: u64, repeat: usize, windows: u32, spl
/// cache the runtime reads at startup. Nothing runs on the GPU.
struct Pipelines {
dev: windows::Win32::Graphics::Direct3D12::ID3D12Device,
/// DXGI adapter name recorded with cold-compile measurements. A timing without the
/// adapter (and the run manifest's driver version) is not a comparable benchmark.
adapter: String,
signatures: Mutex<std::collections::HashMap<Vec<u32>, windows::Win32::Graphics::Direct3D12::ID3D12RootSignature>>,
made: AtomicUsize,
refused: AtomicUsize,
Expand All @@ -1021,10 +1070,11 @@ impl Pipelines {
unsafe {
let factory: IDXGIFactory6 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).map_err(|e| e.to_string())?;
let sel = crate::gpu::adapter::Selector::from_env_or("auto");
let (adapter, _) = crate::gpu::adapter::candidates(&factory, &sel).into_iter().next().ok_or_else(|| crate::gpu::adapter::no_match(&factory, &sel))?;
let (adapter, desc) = crate::gpu::adapter::candidates(&factory, &sel).into_iter().next().ok_or_else(|| crate::gpu::adapter::no_match(&factory, &sel))?;
let adapter_name = crate::gpu::adapter::name(&desc);
let dev = crate::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_12_0).map_err(|e| e.to_string())?;
let most = std::env::var("XCL_PIPELINE_THREADS").ok().and_then(|v| v.parse().ok()).unwrap_or(4usize).max(1);
Ok(Pipelines { dev, signatures: Mutex::new(Default::default()), made: AtomicUsize::new(0), refused: AtomicUsize::new(0), reused: AtomicUsize::new(0), running: (Mutex::new(0), std::sync::Condvar::new()), most })
Ok(Pipelines { dev, adapter: adapter_name, signatures: Mutex::new(Default::default()), made: AtomicUsize::new(0), refused: AtomicUsize::new(0), reused: AtomicUsize::new(0), running: (Mutex::new(0), std::sync::Condvar::new()), most })
}
}

Expand Down Expand Up @@ -1598,6 +1648,8 @@ mod tests {
assert_eq!(run(&dir, &args(&["--export-hlsl", "--record-hash", "DEADBEEF"])), 2);
assert!(!std::path::Path::new("--record-hash").exists(), "the next flag is not taken as the value");
assert_eq!(run(&dir, &args(&["--measure-pso"])), 2);
assert_eq!(run(&dir, &args(&["--measure-pso", "deadbeef", "--backend", "--json"])), 2);
assert_eq!(run(&dir, &args(&["--measure-pso", "deadbeef", "--backend", "auto"])), 2);
assert_eq!(run(&dir, &args(&["--export-hlsl", "out", "--record-hash"])), 2);
let _ = std::fs::remove_dir_all(&dir);
}
Expand All @@ -1618,7 +1670,7 @@ mod tests {
let blob = compute_sample();
std::fs::write(&path.0, &blob).unwrap();
let hash = shader::fnv64(&blob);
match measure_pso_result(&Input::Files(vec![path.0.clone()]), hash, 1, 4, None) {
match measure_pso_result(&Input::Files(vec![path.0.clone()]), hash, 1, 4, None, false, false) {
Ok(()) => {}
// no DXC, a WARP-only or cacheless device, cache control without Developer Mode
Err(MeasureError::Unavailable(e)) => recomp::runner::skip_test(&e),
Expand Down
Loading
Loading