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
26 changes: 22 additions & 4 deletions crates/xcl/src/gpu/recomp/emit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4703,7 +4703,8 @@ impl Em {
}
}
if windows > 1 {
h = windowed(&h, windows);
let coherent = if matches!(self.opt.mode, Mode::Compute(_)) { "globallycoherent " } else { "" };
h = windowed(&h, windows, self.opt.heap_windows.then_some(coherent));
}
h
}
Expand Down Expand Up @@ -5092,7 +5093,9 @@ const LOADX4_ONE_WINDOW: &str = "uint4 xcl_loadx4(uint4 a) { return uint4(mem.Lo
/// Several memory windows: every `mem.Method(` of the program (and of the preludes) becomes
/// an accessor `xcl_mMethod(` that switches on `xcl_w` between `mem` and `mem1`.., whose
/// definitions replace the placeholder.
fn windowed(h: &str, windows: u32) -> String {
/// `heap`: Some(storage class) – the accessors take window k from the descriptor heap
/// (`Options::heap_windows`) instead of switching over the root UAVs.
fn windowed(h: &str, windows: u32, heap: Option<&str>) -> String {
let mut out = String::with_capacity(h.len() + 8192);
let mut rest = h;
while let Some(i) = rest.find("mem.") {
Expand All @@ -5110,14 +5113,16 @@ fn windowed(h: &str, windows: u32) -> String {
}
}
out.push_str(rest);
out.replacen(MEM_ACCESSORS_HERE, &mem_accessors(windows), 1)
out.replacen(MEM_ACCESSORS_HERE, &mem_accessors(windows, heap), 1)
}

/// The accessor functions: one per `mem` method (and overload) the translator emits.
/// Only explicit windows `0..windows` touch GPU buffers; any out-of-range `xcl_w` hits
/// `default` (reads return 0, stores/atomics are dropped and zero their `out` parameter) so
/// out-of-UMA pointers can never wrap onto live memory windows.
fn mem_accessors(windows: u32) -> String {
/// `heap`: Some(storage class) – window k is taken from the descriptor heap
/// (`Options::heap_windows`) and the same rule is one comparison before the access.
fn mem_accessors(windows: u32, heap: Option<&str>) -> String {
let mut sigs: Vec<(&str, String, &str, &str, &str)> = vec![
("uint", "Load".into(), "uint a", "a", "return 0u;"),
("uint2", "Load2".into(), "uint a", "a", "return uint2(0u, 0u);"),
Expand All @@ -5142,6 +5147,19 @@ fn mem_accessors(windows: u32) -> String {
}
}
let mut s = String::new();
if let Some(coherent) = heap {
// one access: window k is descriptor MEM_HEAP_BASE + k; an `xcl_w` outside the windows
// does what the switch's `default` does
let _ = writeln!(s, "#define XCL_MW {coherent}RWByteAddressBuffer m = ResourceDescriptorHeap[NonUniformResourceIndex({}u + xcl_w)]", super::MEM_HEAP_BASE);
let _ = writeln!(s, "uint4 xcl_loadx4(uint4 a) {{ [branch] if (xcl_w >= {windows}u) {{ return uint4(0u, 0u, 0u, 0u); }} XCL_MW; return uint4(m.Load(a.x), m.Load(a.y), m.Load(a.z), m.Load(a.w)); }}");
for (ret, name, params, args, def) in sigs {
let r = if ret == "void" { "" } else { "return " };
// (the switch's `break` leaves the accessor)
let outside = def.replace("break;", "return;");
let _ = writeln!(s, "{ret} xcl_m{name}({params}) {{ [branch] if (xcl_w >= {windows}u) {{ {outside} }} XCL_MW; {r}m.{name}({args}); }}");
}
return s;
}
let _ = write!(s, "uint4 xcl_loadx4(uint4 a) {{ [branch] switch (xcl_w) {{ ");
let _ = write!(s, "case 0u: return uint4(mem.Load(a.x), mem.Load(a.y), mem.Load(a.z), mem.Load(a.w)); ");
for k in 1..windows {
Expand Down
164 changes: 164 additions & 0 deletions crates/xcl/src/gpu/recomp/heap_window_tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
//! Memory windows from the descriptor heap (`Options::heap_windows`): the raw view a window gets
//! (`runner::raw_window_uav`) on a real 4 GiB reserved buffer.

use std::mem::{transmute_copy, ManuallyDrop};

use windows::core::Interface;
use windows::Win32::Graphics::Direct3D::*;
use windows::Win32::Graphics::Direct3D12::*;
use windows::Win32::Graphics::Dxgi::Common::*;
use windows::Win32::Graphics::Dxgi::*;

const GIB: u64 = 1 << 30;
const TILE: u64 = 0x1_0000;

fn buf(dev: &ID3D12Device, size: u64, heap: D3D12_HEAP_TYPE, state: D3D12_RESOURCE_STATES, uav: bool) -> ID3D12Resource {
let desc = D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
Width: size,
Height: 1,
DepthOrArraySize: 1,
MipLevels: 1,
SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
Flags: if uav { D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS } else { D3D12_RESOURCE_FLAG_NONE },
..Default::default()
};
let mut r: Option<ID3D12Resource> = None;
unsafe { dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: heap, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut r).unwrap() };
r.unwrap()
}

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

fn device() -> Option<(ID3D12Device, String)> {
unsafe {
let factory: IDXGIFactory6 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).ok()?;
let sel = crate::gpu::adapter::Selector::from_env_or("auto");
if sel == crate::gpu::adapter::Selector::Warp {
return None;
}
let (a, desc) = crate::gpu::adapter::candidates(&factory, &sel).into_iter().next()?;
let dev = crate::gpu::agility::create_device(&a, D3D_FEATURE_LEVEL_12_0).ok()?;
Some((dev, crate::gpu::adapter::name(&desc)))
}
}

/// The heap-window form (`Options::heap_windows`) on a real sparse window: a 4 GiB reserved
/// buffer seen through `runner::raw_window_uav` reaches its last tile, which the sparse windows
/// hand out (a reservation across two windows covers it), up to its last 32 bytes (the view
/// ends there: an older D3D12 runtime removes the device for a raw view that ends above).
#[test]
fn gpu_raw_window_view_reaches_its_top() {
let Some((dev, name)) = device() else {
super::runner::skip_test("no GPU");
return;
};
if super::dxc::location().is_err() {
super::runner::skip_test("no DXC");
return;
}
let top = (4 * GIB) - TILE; // the window's last tile
let src = r#"
#define RS "RootFlags(CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED), UAV(u0)"
RWByteAddressBuffer outb : register(u0);
[RootSignature(RS)]
[numthreads(64, 1, 1)]
void main(uint l : SV_GroupThreadID) {
RWByteAddressBuffer w = ResourceDescriptorHeap[NonUniformResourceIndex(0u)];
w.Store(0xFFFF0000u + 4u * l, 0x5A000000u | l);
w.Store(4u * l, 0xA5000000u | l);
if (l < 56u) w.Store(0xFFFFFF00u + 4u * l, 0x3C000000u | l);
DeviceMemoryBarrier();
outb.Store(8u * l, w.Load(0xFFFF0000u + 4u * l));
outb.Store(8u * l + 4u, w.Load(4u * l));
outb.Store(512u + 4u * l, l < 56u ? w.Load(0xFFFFFF00u + 4u * l) : 0u);
}
"#;
unsafe {
let dxil = super::dxc::compile(src, "main", "cs_6_6", &[]).unwrap();
let rs: ID3D12RootSignature = dev.CreateRootSignature(0, &dxil).unwrap();
let pso: ID3D12PipelineState = dev
.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
pRootSignature: transmute_copy(&rs),
CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr() as _, BytecodeLength: dxil.len() },
..Default::default()
})
.unwrap();
let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap();
let desc = D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
Width: 4 * GIB,
Height: 1,
DepthOrArraySize: 1,
MipLevels: 1,
SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
..Default::default()
};
let mut win: Option<ID3D12Resource> = None;
if let Err(e) = dev.CreateReservedResource(&desc, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, None, &mut win) {
// a software adapter (the CI's) makes no 4 GiB reserved buffer
println!("{name}: no 4 GiB reserved buffer ({e})");
super::runner::skip_test("no GPU");
return;
}
let win = win.unwrap();
let mut heap: Option<ID3D12Heap> = None;
dev.CreateHeap(&D3D12_HEAP_DESC { SizeInBytes: 2 * TILE, Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, Alignment: 0, Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS }, &mut heap).unwrap();
let heap = heap.unwrap();
let coords = [0u64, top].map(|o| D3D12_TILED_RESOURCE_COORDINATE { X: (o / TILE) as u32, ..Default::default() });
let regions = [D3D12_TILE_REGION_SIZE { NumTiles: 1, ..Default::default() }; 2];
let flags = [D3D12_TILE_RANGE_FLAG_NONE; 2];
queue.UpdateTileMappings(&win, 2, Some(coords.as_ptr()), Some(regions.as_ptr()), &heap, 2, Some(flags.as_ptr()), Some([0u32, 1].as_ptr()), Some([1u32; 2].as_ptr()), D3D12_TILE_MAPPING_FLAG_NONE);
let dh: ID3D12DescriptorHeap = dev
.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, NumDescriptors: 1, Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, NodeMask: 0 })
.unwrap();
dev.CreateUnorderedAccessView(&win, None::<&ID3D12Resource>, Some(&super::runner::raw_window_uav(4 * GIB)), dh.GetCPUDescriptorHandleForHeapStart());
let out = buf(&dev, 768, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, true);
let rb = buf(&dev, 768 + 256, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, false);
let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap();
let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, &pso).unwrap();
list.SetDescriptorHeaps(&[Some(dh.clone())]);
list.SetComputeRootSignature(&rs);
list.SetComputeRootUnorderedAccessView(0, out.GetGPUVirtualAddress());
list.Dispatch(1, 1, 1);
list.ResourceBarrier(&[
transition(&win, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE),
transition(&out, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE),
]);
list.CopyBufferRegion(&rb, 0, &out, 0, 768);
list.CopyBufferRegion(&rb, 768, &win, top, 256);
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, None, 20_000).map_err(|e| format!("{e}")).unwrap();
let mut q = std::ptr::null_mut();
rb.Map(0, None, Some(&mut q)).unwrap();
let w = std::slice::from_raw_parts(q as *const u32, 256).to_vec();
rb.Unmap(0, None);
for l in 0..64usize {
assert_eq!(w[2 * l], 0x5A00_0000 | l as u32, "{name}: lane {l}, the window's top tile through the heap view");
assert_eq!(w[2 * l + 1], 0xA500_0000 | l as u32, "{name}: lane {l}, the window's first tile");
assert_eq!(w[192 + l], 0x5A00_0000 | l as u32, "{name}: lane {l}, the top tile in memory");
if l < 56 {
assert_eq!(w[128 + l], 0x3C00_0000 | l as u32, "{name}: lane {l}, the window's last dwords");
}
}
}
}
24 changes: 23 additions & 1 deletion crates/xcl/src/gpu/recomp/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,16 @@ pub use emit::mesh_passthrough;
pub mod runner;
#[cfg(test)]
mod tests;
#[cfg(test)]
mod heap_window_tests;

/// First descriptor of the memory windows in the shader-visible heap (`Options::heap_windows`):
/// window k is raw UAV `MEM_HEAP_BASE + k`.
pub const MEM_HEAP_BASE: u32 = 0;

/// Flag in a memory-windows count (`pso::mem_windows`, the translation caches' keys):
/// `Options::heap_windows`. `translate` takes it out of `mem_windows`.
pub const HEAP_WINDOWS: u32 = 0x100;
pub mod upper_lanes;

use std::collections::{BTreeMap, BTreeSet};
Expand Down Expand Up @@ -492,14 +502,19 @@ pub struct Options {
/// then exactly the single-window form); 2..4 add `mem1`.. (u3..) and pick the window of
/// every access from the high address bits
pub mem_windows: u32,
/// with `mem_windows` > 1: reach window k through descriptor `MEM_HEAP_BASE + k` of the
/// shader-visible heap (a raw UAV of the window, `ResourceDescriptorHeap`) – one access per
/// site instead of a `switch` over the root UAVs `mem`, `mem1`.., which inlines every
/// access once per window (HANDOFF: twice the DXC + driver time with 4 windows)
pub heap_windows: bool,
/// structured control flow when the program allows it (false, or `XCL_RECOMP_NO_STRUCTURED`:
/// always the guarded block chain)
pub structured: 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, structured: true }
Options { 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 Expand Up @@ -1357,6 +1372,13 @@ fn constant_samplers(insts: &[Decoded], leaders: &BTreeSet<u64>) -> BTreeMap<u64
}

pub fn translate(code: &[u8], opt: &Options) -> Result<Translation, String> {
let normalized;
let opt = if opt.mem_windows & HEAP_WINDOWS != 0 {
normalized = Options { mem_windows: opt.mem_windows & !HEAP_WINDOWS, heap_windows: true, ..opt.clone() };
&normalized
} else {
opt
};
let mut insts: Vec<Decoded> = Vec::new();
let mut off = 0usize;
while off + 4 <= code.len() {
Expand Down
40 changes: 38 additions & 2 deletions crates/xcl/src/gpu/recomp/pso.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,45 @@ pub fn fspx(blob: &[u8]) -> Option<Fspx<'_>> {
Some(Fspx { threads, rsrc1: u32_at(head, 0x14)?, rsrc2: u32_at(head, 0x18)?, code: &code[..4 * (end + 1)] })
}

/// Memory windows of the title's unified memory (1 without it).
/// Memory windows of the title's unified memory (1 without it), with `HEAP_WINDOWS` when
/// shaders take them from the descriptor heap (`heap_windows`).
pub fn mem_windows() -> u32 {
crate::gpu::uma::get().map_or(1, |u| u.shader_windows() as u32)
let n = crate::gpu::uma::get().map_or(1, |u| u.shader_windows() as u32);
if n > 1 && heap_windows() && !SWITCH_FORM.with(|s| s.get()) {
n | super::HEAP_WINDOWS
} else {
n
}
}

thread_local! {
/// this thread translates in the switch form (`in_switch_form`)
static SWITCH_FORM: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

/// Run `f` with this thread's translations in the switch form over root UAVs (`mem_windows`
/// without `HEAP_WINDOWS`, so other cache keys): for a pipeline the driver would not build with
/// heap windows. The root signature and the binds are the same for both forms.
pub fn in_switch_form<R>(f: impl FnOnce() -> R) -> R {
struct Restore(bool);
impl Drop for Restore {
fn drop(&mut self) {
SWITCH_FORM.with(|s| s.set(self.0));
}
}
let _restore = Restore(SWITCH_FORM.with(|s| s.replace(true)));
f()
}

/// Whether translated shaders reach the memory windows through the shared descriptor heap
/// (`Options::heap_windows`; descriptors `MEM_HEAP_BASE`.. made by `console_heap::set_window_views`)
/// instead of a `switch` over root UAVs. Opt-in: on with `XCL_HEAP_WINDOWS=1`, unless the views
/// could not be made (no shared heap: then the switch, as before). Off by default: two NVIDIA
/// setups failed with it (the driver's compiler ending the process; a device removal when the
/// views are made on an 8 GB card) that other machines do not show.
pub fn heap_windows() -> bool {
static ENV: OnceLock<bool> = OnceLock::new();
*ENV.get_or_init(|| std::env::var("XCL_HEAP_WINDOWS").is_ok_and(|v| v.trim() == "1")) && !crate::hle::d3d12x::console_heap::window_views_failed()
}

/// A static sampler of a translated program: (S#, comparison) – see `Translation`.
Expand Down
Loading
Loading