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
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,14 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder
- With `XCL_DRED=1`, a D3D12 device removal logs GPU breadcrumbs in `xcl.log`.
XCL examines up to 4,096 command lists and reports up to 64 unfinished lists, starting with
those on which the GPU completed at least one operation.
- `XCL_HOST_DXR=1` enables an experimental shadow-build capture of XboxBvhBuilder
build, rehydrate and copy calls on DXR 1.1 devices. It snapshots triangle inputs from
mapped UMA windows and rewrites readable CPU instance arrays to native BLAS addresses.
Compressed rehydration, command-buffer replay, procedural geometry and GPU-generated
instance arrays are not supported. Rehydration invalidates earlier shadow mappings.
Native buffers are retained until exit with a 256 MiB allocation budget
per device. Translated shaders still use the console BVH, so this diagnostic mode
adds GPU work and does not accelerate rendering yet. It is disabled by default.
- `XCL_DSTORAGE_PARALLEL_DECOMPRESS=1` enables parallel CPU decompression for file-backed zlib
requests with virtual destinations. Defaults: four workers and a shared 32 MiB staging budget
(`XCL_DSTORAGE_WORKERS`, `XCL_DSTORAGE_MEMORY_BUDGET_MIB`). Requests retire in queue order.
Expand Down
1 change: 1 addition & 0 deletions crates/xcl/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ const TRANSLATOR_SOURCES: &[&str] = &[
"src/gpu/recomp/emit.rs",
"src/gpu/recomp/mesh_wave.rs",
"src/gpu/recomp/mod.rs",
"src/gpu/recomp/rayquery.rs",
"src/gpu/recomp/upper_lanes.rs",
"src/gpu/recomp/x64_masks.rs",
"src/gpu/shader.rs",
Expand Down
4 changes: 3 additions & 1 deletion crates/xcl/src/gpu/recomp/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ pub(crate) fn valid_window_count(windows: usize, heap: bool) -> bool {
|| (heap && windows.is_power_of_two() && windows <= crate::gpu::uma::MAX_HEAP_WINDOWS)
}
pub mod upper_lanes;
pub(crate) mod rayquery;

use std::collections::{BTreeMap, BTreeSet};

Expand Down Expand Up @@ -526,11 +527,12 @@ pub struct Options {
/// structured control flow when the program allows it (false, or `XCL_RECOMP_NO_STRUCTURED`:
/// always the guarded block chain)
pub structured: bool,
pub host_rayquery: bool,
}

impl Default for Options {
fn default() -> Self {
Options { mode: Mode::Kernel, wave64: true, hw_wave: 0, split_wave64: false, static_sampler_base: 0, mem_windows: 1, heap_windows: false, structured: true }
Options { host_rayquery: false, mode: Mode::Kernel, wave64: true, hw_wave: 0, split_wave64: false, static_sampler_base: 0, mem_windows: 1, heap_windows: false, structured: true }
}
}

Expand Down
25 changes: 20 additions & 5 deletions crates/xcl/src/gpu/recomp/pso.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,15 +128,15 @@ pub struct Compiled {
/// Translate a console shader for `stage` to signed DXIL (DXC, disk-cached); its static
/// samplers take registers from `sampler_base` (space 1).
/// Fails when the blob is not a console shader or the program is not fully translated.
pub fn console_to_dxil(blob: &[u8], stage: Stage, sampler_base: u32) -> Result<Compiled, String> {
pub fn console_to_dxil(blob: &[u8], stage: Stage, sampler_base: u32) -> Result<Arc<Compiled>, String> {
console_to_dxil_for(blob, stage, sampler_base, false)
}

/// `console_to_dxil` for a GPU that runs only 32-lane waves when `split_wave64`
/// (`wave32_only_for_device`): a wave64 compute program gets the split form
/// (`Options::split_wave64`) instead of `[WaveSize(64)]`, which such a driver rejects.
/// Finished shaders are also kept in memory (`ShaderCache`): pipelines share their shaders.
pub fn console_to_dxil_for(blob: &[u8], stage: Stage, sampler_base: u32, split_wave64: bool) -> Result<Compiled, String> {
pub fn console_to_dxil_for(blob: &[u8], stage: Stage, sampler_base: u32, split_wave64: bool) -> Result<Arc<Compiled>, String> {
console_to_dxil_in(blob, stage, sampler_base, split_wave64, mem_windows())
}

Expand All @@ -148,10 +148,10 @@ fn shader_cache() -> &'static Mutex<ShaderCache> {

/// `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> {
pub fn console_to_dxil_in(blob: &[u8], stage: Stage, sampler_base: u32, split_wave64: bool, windows: u32) -> Result<Arc<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();
return compile_one().map(Arc::new);
}
let key = ShaderKey {
hash: crate::gpu::shader::fnv64(blob),
Expand All @@ -164,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(shader_cache(), key, blob, from_disk).map(|shader| shader.as_ref().clone())
cached_shader(shader_cache(), key, blob, from_disk)
}

/// Translations on disk: a console program's (DXIL, static samplers) by its bytes, so a run
Expand Down Expand Up @@ -1566,6 +1566,21 @@ mod shader_cache_tests {
mod compile_time_bench {
use super::*;

#[test]
fn repeated_console_shader_requests_share_dxil() {
use crate::gpu::xbox::tests::{fssm, sample, CODE};
let mut f = fssm(&CODE, &[(6, 0)]);
for offset in [0x13C, 0x140, 0x144] {
f[offset..offset + 4].copy_from_slice(&1u32.to_le_bytes());
}
let blob = sample(5, &[f]);
let first = console_to_dxil(&blob, Stage::Compute, 0).unwrap();
let second = console_to_dxil(&blob, Stage::Compute, 0).unwrap();
assert_eq!(first.dxil, second.dxil);
assert_eq!(first.samplers, second.samplers);
assert_eq!(first.dxil.as_ptr(), second.dxil.as_ptr(), "a cache hit shares its compiled storage");
}

#[test]
#[ignore]
fn repeated_pso_shader_compile() {
Expand Down
150 changes: 150 additions & 0 deletions crates/xcl/src/gpu/recomp/rayquery.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
//! Opt-in replacement of verified whole traversal regions with inline RayQuery.

use super::{Mode, Options};
use crate::gpu::{rdna2, shader};

pub const MAGIC: u32 = 0x58445231;
pub const HOST_AS_ROOT: u32 = 6;
pub const SHADOW_RECORD: u64 = 0x9d51ce32ab9a9ab5;

#[derive(Clone, Copy, Debug)]
pub(super) struct Region {
pub start: u64,
pub end: u64,
}

pub(super) fn identify(code: &[u8], opt: &Options, insts: &[rdna2::Decoded]) -> Option<Region> {
if !opt.host_rayquery || !opt.structured {
return None;
}
let hash = shader::fnv64(code);
let region = if matches!(opt.mode, Mode::Compute(_)) && hash == 0x65cd3172658edef2 && code.len() == 9724 {
Region { start: 0x13d4, end: 0x1c6c }
} else {
#[cfg(test)]
if matches!(opt.mode, Mode::Kernel) && hash == 0x4f7800379203c280 && code.len() == 2204 {
return Some(Region { start: 0, end: 2200 });
}
return None;
};
// No entry into the middle of the replaced region, and a single continuation.
if insts.iter().any(|d| rdna2::branch_target(d).is_some_and(|target| {
let inside = d.pc >= region.start && d.pc < region.end;
(!inside && target > region.start && target < region.end)
|| (inside && (target < region.start || target > region.end))
})) {
return None;
}
Some(region)
}


#[cfg(test)]
pub(crate) mod test_support;

#[cfg(test)]
mod tests {
use super::super::{dxc, runner, translate};
use crate::gpu::{bvh, shader, xbox};

#[test]
fn gpu_retail_shadow_region_matches_console_scene() {
let Some(path) = std::env::var_os("XCL_SAMPLE_RAYQUERY") else {
runner::skip_test("no XCL_SAMPLE_RAYQUERY");
return;
};
if runner::adapter().is_err() || dxc::location().is_err() {
runner::skip_test("no GPU or DXC");
return;
}
let blob = std::fs::read(path).unwrap();
assert_eq!(shader::fnv64(&blob), 0x9d51ce32ab9a9ab5);
let sh = xbox::parse(&blob).unwrap();
let f = sh.fssm.iter().find(|f| f.stages.iter().any(|s| s.hw == 6)).unwrap();
let p = f.programs.first().unwrap();
let full = &f.data[p.offset..p.offset + p.len];
println!("retail program hash {:016x}, {} bytes", shader::fnv64(full), full.len());
let mut insts = Vec::new();
let mut at = 0;
while at < full.len() {
let d = crate::gpu::rdna2::decode(&full[at..], at as u64).unwrap();
at += d.len; insts.push(d);
}
let cfg = super::super::cfg::Cfg::new(&insts).unwrap();
for scalar in [false, true] {
use std::collections::BTreeSet;
let uses = |d: &crate::gpu::rdna2::Decoded| if scalar { crate::gpu::rdna2::sgpr_uses(d) } else { crate::gpu::rdna2::vgpr_uses(d) };
let mut live = vec![BTreeSet::<u64>::new(); cfg.start.len()];
loop {
let mut changed = false;
for b in (0..cfg.start.len()).rev() {
let mut next: BTreeSet<u64> = cfg.succ[b].iter().flat_map(|&s| live[s].iter().copied()).collect();
for i in cfg.range(b).rev() {
let (r,w) = uses(&insts[i]);
for reg in w { next.remove(&reg); }
next.extend(r);
}
changed |= live[b] != next; live[b] = next;
}
if !changed { break; }
}
let end = insts.iter().position(|d| d.pc == 0x1c6c).unwrap();
let written: BTreeSet<u64> = insts.iter().filter(|d| d.pc >= 0x13d4 && d.pc < 0x1c6c).flat_map(|d| uses(d).1).collect();
let out: Vec<_> = written.intersection(&live[cfg.block_of[end]]).copied().collect();
println!("retail region live {} outputs: {out:?}", if scalar { "scalar" } else { "vector" });
assert_eq!(out, if scalar { vec![] } else { vec![28, 31] });
}
let mode = super::super::interface(&blob, &sh, f).unwrap();
let mut native = runner::options(mode);
native.host_rayquery = true;
native.mem_windows = 4;
let full_translation = translate(full, &native).unwrap();
assert!(full_translation.complete(), "{:?}", full_translation.unsupported);
assert_eq!(full_translation.hlsl.matches("TraceRayInline").count(), 0);
assert!(super::identify(full, &native, &insts).is_some());
let dxil = dxc::compile(&full_translation.hlsl, "main", "cs_6_6", &[]).unwrap();
println!("Full retail shader baseline compiled: {} B DXIL", dxil.len());
let mut altered = full.to_vec();
altered[0] ^= 1;
assert!(super::identify(&altered, &native, &insts).is_none());
native.host_rayquery = false;
assert!(super::identify(full, &native, &insts).is_none());
let mut code = full[0x13d4..0x1c6c].to_vec();
code.extend_from_slice(&0xbf810000u32.to_le_bytes());
let opt = runner::options(super::super::Mode::Kernel);
let t = translate(&code, &opt).unwrap();
assert!(t.complete(), "{:?}", t.unsupported);
let dxil = dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap();
let triangle = [[0., 0., 0.], [1., 0., 0.], [0., 1., 0.]];
let bottom = bvh::build(&[triangle], 0);
let top = bvh::build_top(&[bvh::Instance {
transform: [[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.]],
id: 0, mask: 0xff, contribution: 0, flags: 0,
blas_address: 0x4000, blas_root: bottom.root, blas_bounds: bottom.bounds(),
}]);
let mut memory = vec![0u8; 0x8000];
memory[0x1000..0x1000 + top.data.len()].copy_from_slice(&top.data);
memory[0x4000..0x4000 + bottom.data.len()].copy_from_slice(&bottom.data);
let memory: Vec<u32> = memory.chunks_exact(4).map(|w| u32::from_le_bytes(w.try_into().unwrap())).collect();
let mut state = runner::KernelState::default();
state.sgpr[4] = 0x1000;
for (lane, v) in state.vgpr.iter_mut().enumerate() {
let origin = if lane % 2 == 0 { [0.25f32, 0.25, 1.] } else { [2., 2., 1.] };
for (r, value) in [(6, origin[0]), (66, origin[1]), (62, origin[2]),
(47, origin[0]), (48, origin[1]), (49, origin[2]),
(11, 0.), (12, 0.), (52, -1.), (50, 0.), (51, 0.), (5, -1.), (8, 10.)] {
v[r] = value.to_bits();
}
for r in [35, 36, 37] { v[r] = u32::MAX; }
}
let result = runner::run(&dxil, &state, &memory).unwrap();
for lane in 0..4 {
println!("lane {lane}: limit {}, distance {}, flag {}", f32::from_bits(result.vgpr[lane][8]),
f32::from_bits(result.vgpr[lane][28]), f32::from_bits(result.vgpr[lane][31]));
}
for lane in (0..64).step_by(2) {
assert_eq!(f32::from_bits(result.vgpr[lane][8]), 1.);
assert_eq!(f32::from_bits(result.vgpr[lane][28]), 1.);
}
}
}
91 changes: 91 additions & 0 deletions crates/xcl/src/gpu/recomp/rayquery/test_support.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
//! Native scene fixtures for the upcoming sample-gated traversal comparison.
#![allow(dead_code, unused_imports)]

use std::mem::{transmute_copy, ManuallyDrop};
use windows::core::Interface;
use windows::Win32::Graphics::Direct3D12::*;
use windows::Win32::Graphics::Dxgi::Common::*;
use crate::gpu::bvh;
use super::super::{dxc, runner, translate, KERNEL_RES_DWORDS, KERNEL_SCC_SLOT, KERNEL_SGPRS};

unsafe fn buffer(dev: &ID3D12Device5, bytes: usize, heap: D3D12_HEAP_TYPE, state: D3D12_RESOURCE_STATES) -> ID3D12Resource {
let desc = D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: bytes.div_ceil(256) as u64 * 256,
Height: 1, DepthOrArraySize: 1, MipLevels: 1,
SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
Flags: if heap == D3D12_HEAP_TYPE_DEFAULT { D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS } else { D3D12_RESOURCE_FLAG_NONE },
..Default::default()
};
let mut resource = None;
dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: heap, ..Default::default() }, D3D12_HEAP_FLAG_NONE,
&desc, state, None, &mut resource).unwrap();
resource.unwrap()
}

unsafe fn upload(dev: &ID3D12Device5, words: &[u32]) -> ID3D12Resource {
let resource = buffer(dev, words.len() * 4, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ);
let mut mapped = std::ptr::null_mut();
resource.Map(0, None, Some(&mut mapped)).unwrap();
std::ptr::copy_nonoverlapping(words.as_ptr(), mapped.cast(), words.len());
resource.Unmap(0, None);
resource
}

unsafe fn transition(resource: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) -> D3D12_RESOURCE_BARRIER {
D3D12_RESOURCE_BARRIER {
Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION,
Anonymous: D3D12_RESOURCE_BARRIER_0 { Transition: ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER {
pResource: transmute_copy(resource), Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
StateBefore: before, StateAfter: after,
}) },
..Default::default()
}
}

pub(crate) unsafe fn scene(dev: &ID3D12Device5, queue: &ID3D12CommandQueue, triangles: &[bvh::Triangle]) -> (ID3D12Resource, Vec<ID3D12Resource>) {
let words: Vec<u32> = triangles.iter().flatten().flatten().map(|v| v.to_bits()).collect();
let vertices = upload(dev, &words);
let geometry = D3D12_RAYTRACING_GEOMETRY_DESC {
Type: D3D12_RAYTRACING_GEOMETRY_TYPE_TRIANGLES, Flags: D3D12_RAYTRACING_GEOMETRY_FLAG_OPAQUE,
Anonymous: D3D12_RAYTRACING_GEOMETRY_DESC_0 { Triangles: D3D12_RAYTRACING_GEOMETRY_TRIANGLES_DESC {
VertexFormat: DXGI_FORMAT_R32G32B32_FLOAT, VertexCount: triangles.len() as u32 * 3,
VertexBuffer: D3D12_GPU_VIRTUAL_ADDRESS_AND_STRIDE { StartAddress: vertices.GetGPUVirtualAddress(), StrideInBytes: 12 },
..Default::default()
} },
};
let inputs = D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS {
Type: D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL, NumDescs: 1, DescsLayout: D3D12_ELEMENTS_LAYOUT_ARRAY,
Anonymous: D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS_0 { pGeometryDescs: &geometry }, ..Default::default()
};
let allocator: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap();
let list: ID3D12GraphicsCommandList4 = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None).unwrap();
let mut retained = Vec::new();
let mut build = |inputs: D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS| {
let mut size = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO::default();
dev.GetRaytracingAccelerationStructurePrebuildInfo(&inputs, &mut size);
let result = buffer(dev, size.ResultDataMaxSizeInBytes as usize, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE);
let scratch = buffer(dev, size.ScratchDataSizeInBytes as usize, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
list.BuildRaytracingAccelerationStructure(&D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC {
DestAccelerationStructureData: result.GetGPUVirtualAddress(), ScratchAccelerationStructureData: scratch.GetGPUVirtualAddress(), Inputs: inputs, ..Default::default()
}, None);
list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_UAV,
Anonymous: D3D12_RESOURCE_BARRIER_0 { UAV: ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: transmute_copy(&result) }) }, ..Default::default() }]);
retained.push(scratch); retained.push(result.clone()); result
};
let bottom = build(inputs);
let mut instance = [0u32; 16];
for i in [0, 5, 10] { instance[i] = 1f32.to_bits(); }
instance[12] = 0xff000000;
instance[14] = bottom.GetGPUVirtualAddress() as u32;
instance[15] = (bottom.GetGPUVirtualAddress() >> 32) as u32;
let instances = upload(dev, &instance);
let top = build(D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS {
Type: D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL, NumDescs: 1, DescsLayout: D3D12_ELEMENTS_LAYOUT_ARRAY,
Anonymous: D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS_0 { InstanceDescs: instances.GetGPUVirtualAddress() }, ..Default::default()
});
list.Close().unwrap(); queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]);
let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); queue.Signal(&fence, 1).unwrap();
crate::gpu::fence::wait(&fence, 1, &dev.cast().unwrap(), None, 30000).unwrap();
// A TLAS references its BLAS even after the build has completed.
(top, retained)
}
6 changes: 6 additions & 0 deletions crates/xcl/src/gpu/uma.rs
Original file line number Diff line number Diff line change
Expand Up @@ -465,6 +465,8 @@ impl Uma {
len += l;
}
g.0.insert(start, len);
drop(g);
crate::hle::d3d12x::host_bvh::forget_range(p, size);
Some(size)
}

Expand Down Expand Up @@ -689,6 +691,8 @@ impl Uma {
let mut g = self.pool.lock().unwrap();
if p >= g.0 && p < g.1 {
g.2.push(p);
drop(g);
crate::hle::d3d12x::host_bvh::forget_range(p, ARENA_BLOCK);
return true;
}
}
Expand All @@ -708,6 +712,8 @@ impl Uma {
len += l;
}
g.free.insert(start, len);
drop(g);
crate::hle::d3d12x::host_bvh::forget_range(p, orig);
true
}

Expand Down
Loading
Loading