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
6 changes: 6 additions & 0 deletions crates/xcl/src/gpu/adapter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,12 @@ pub fn candidates(factory: &IDXGIFactory6, sel: &Selector) -> Vec<(IDXGIAdapter1
hw.into_iter().enumerate().filter(|(i, _)| keep[*i]).map(|(_, a)| a).collect()
}

/// PCI vendor id of the adapter a title would run on here (the first `sel` allows), if any.
pub fn vendor(sel: &Selector) -> Option<u32> {
let factory: IDXGIFactory6 = unsafe { CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)) }.ok()?;
candidates(&factory, sel).first().map(|(_, d)| d.VendorId)
}

/// "`sel` matches no adapter (have: 0 = …, 1 = …)" – for logs and test skips.
pub fn no_match(factory: &IDXGIFactory6, sel: &Selector) -> String {
let have: Vec<String> = hardware(factory).iter().enumerate().map(|(i, (_, d))| format!("{i} = {}", name(d))).collect();
Expand Down
24 changes: 23 additions & 1 deletion crates/xcl/src/gpu/dxil/kernel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,27 @@ pub fn translate_geometry(code: &[u8], o: KernelOptions, g: &GsInterface) -> Res
translate_entry(code, KernelOptions { wave64: true, ..o }, Entry::Geometry(g.clone()), None, None, 0)
}

/// Whether `entry` reads its heap windows without a branch (`Lw::heap_flat`): with heap windows and
/// `HEAP_FLAT`, for compute programs (kernel and CS entries) only, the form that was timed. Mesh, GS,
/// vertex and pixel programs keep the guarded form.
fn reads_heap_flat(entry: &Entry, heap: bool, mem_windows: u32) -> bool {
heap && matches!(entry, Entry::Kernel | Entry::Compute(_)) && mem_windows & crate::gpu::recomp::HEAP_FLAT != 0
}

#[cfg(test)]
#[test]
fn only_compute_programs_read_heap_windows_flat() {
use crate::gpu::recomp::{GsInterface, MsInterface, HEAP_FLAT, HEAP_WINDOWS};
let flat = 4 | HEAP_WINDOWS | HEAP_FLAT;
assert!(reads_heap_flat(&Entry::Kernel, true, flat));
assert!(reads_heap_flat(&Entry::Compute(CsInterface::default()), true, flat));
assert!(!reads_heap_flat(&Entry::Mesh(MsInterface::default()), true, flat));
assert!(!reads_heap_flat(&Entry::Geometry(GsInterface::default()), true, flat));
// the guarded heap form, and the switch over root UAVs
assert!(!reads_heap_flat(&Entry::Compute(CsInterface::default()), true, 4 | HEAP_WINDOWS));
assert!(!reads_heap_flat(&Entry::Compute(CsInterface::default()), false, flat));
}

/// The entry ABI.
#[derive(Clone)]
pub enum Entry {
Expand Down Expand Up @@ -178,7 +199,7 @@ fn translate_entry(
fn mem_windows(s: &mut Shader, mem_windows: u32, coherent: bool) -> (Vec<RawUav>, Option<bool>) {
let heap = mem_windows & crate::gpu::recomp::HEAP_WINDOWS != 0;
let max = if heap { crate::gpu::uma::MAX_HEAP_WINDOWS as u32 } else { crate::gpu::uma::MAX_WINDOWS as u32 };
let n = (mem_windows & !crate::gpu::recomp::HEAP_WINDOWS).clamp(1, max);
let n = (mem_windows & !(crate::gpu::recomp::HEAP_WINDOWS | crate::gpu::recomp::HEAP_FLAT)).clamp(1, max);
if heap && n > 1 {
let z = s.m.i32c(0);
return (vec![RawUav { handle: z, binding: None }; n as usize], Some(coherent));
Expand Down Expand Up @@ -517,6 +538,7 @@ impl Lw {
half: z,
mems,
heap_mem,
heap_flat: reads_heap_flat(entry, heap_mem.is_some(), o.mem_windows),
res,
fmt_table: None,
fmt_desc_cache: HashMap::new(),
Expand Down
2 changes: 2 additions & 0 deletions crates/xcl/src/gpu/dxil/lower.rs
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,8 @@ pub struct Lw {
/// the windows come from the descriptor heap (`lower_window`; `mems` only counts them):
/// Some(globallycoherent)
pub heap_mem: Option<bool>,
/// heap windows read without a branch (`recomp::HEAP_FLAT`; compute programs only, `kernel::reads_heap_flat`)
pub heap_flat: bool,
pub res: Option<RawUav>,
/// the buffer format table (`FMT_INFO`), created on first use
pub fmt_table: Option<Value>,
Expand Down
23 changes: 23 additions & 0 deletions crates/xcl/src/gpu/dxil/lower_mem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -401,12 +401,35 @@ impl Lw {
out
}

/// `with_mem_many_tys` of `n` dwords for a read (`f` only loads). With `heap_flat`, no branch:
/// `f` reads window `w`, or window 0 when `w` is outside the windows or the lane is not in
/// `guard`, and those lanes then take 0 (a raw buffer read out of the view's range gives 0,
/// so the read of window 0 is harmless). One path per access, as #1695 makes the HLSL heap
/// form: no handle phi, no block per read.
pub(crate) fn with_mem_i32s(
&mut self,
guard: Option<Value>,
n: usize,
f: &mut dyn FnMut(&mut Lw, RawUav) -> Vec<Value>,
) -> Vec<Value> {
if let (Some(coherent), true) = (self.heap_mem, self.heap_flat) {
let z = self.c(0);
if guard.is_some_and(|g| self.s.m.const_u64(g) == Some(0)) {
return vec![z; n];
}
let w = self.rd(super::lower::VAR_WIN);
let inside = self.cmpc(Pred::ULt, w, self.mems.len() as u32);
let ok = match guard {
Some(g) if self.s.m.const_u64(g) != Some(1) => self.and(g, inside),
_ => inside,
};
let w = self.sel(ok, w, z);
let i = self.addc(w, crate::gpu::recomp::MEM_HEAP_BASE);
let m = self.s.heap_raw_buffer_uav(i, coherent);
let vals = f(self, m);
debug_assert_eq!(vals.len(), n);
return vals.into_iter().map(|v| self.sel(ok, v, z)).collect();
}
let i32 = self.s.m.i32();
let tys = vec![i32; n];
self.with_mem_many_tys(guard, &tys, f)
Expand Down
7 changes: 6 additions & 1 deletion crates/xcl/src/gpu/recomp/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,11 @@ pub const MEM_HEAP_BASE: u32 = 4;
/// `Options::heap_windows`. `translate` takes it out of `mem_windows`.
pub const HEAP_WINDOWS: u32 = 0x100;

/// Flag in a memory-windows count next to `HEAP_WINDOWS` (`pso::mem_windows`, the caches' keys):
/// the direct DXIL translator reads the heap windows of compute stages without a branch
/// (`Lw::with_mem_i32s`). The HLSL path ignores it.
pub const HEAP_FLAT: u32 = 0x200;

pub(crate) fn valid_window_count(windows: usize, heap: bool) -> bool {
windows <= crate::gpu::uma::MAX_WINDOWS
|| (heap && windows.is_power_of_two() && windows <= crate::gpu::uma::MAX_HEAP_WINDOWS)
Expand Down Expand Up @@ -1501,7 +1506,7 @@ pub fn translate(code: &[u8], opt: &Options) -> Result<Translation, String> {
let program = code;
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 = Options { mem_windows: opt.mem_windows & !(HEAP_WINDOWS | HEAP_FLAT), heap_windows: true, ..opt.clone() };
&normalized
} else {
opt
Expand Down
125 changes: 114 additions & 11 deletions crates/xcl/src/gpu/recomp/pso.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,16 +78,48 @@ pub fn fspx(blob: &[u8]) -> Option<Fspx<'_>> {
}

/// Memory windows of the title's unified memory (1 without it), with `HEAP_WINDOWS` when
/// shaders take them from the descriptor heap (`heap_windows`).
/// shaders of every stage take them from the descriptor heap (`XCL_HEAP_WINDOWS=1`).
pub fn mem_windows() -> 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
graphics_windows(crate::gpu::uma::get().map_or(1, |u| u.shader_windows() as u32))
}

/// `n` windows as a VS, PS, mesh or GS program of this run takes them (`mem_windows`; the keys
/// `xcl shaders --precompile` makes for them).
pub fn graphics_windows(n: u32) -> u32 {
with_heap(n, heap_windows_everywhere())
}

/// `mem_windows` for a compute program: also from the descriptor heap when heap windows are on
/// by default (`heap_windows`). Only the direct DXIL translator takes them then: the HLSL path
/// keeps the switch (`hlsl_windows`).
pub fn compute_mem_windows() -> u32 {
compute_windows(crate::gpu::uma::get().map_or(1, |u| u.shader_windows() as u32))
}

/// `n` windows as a compute program of this run takes them (`compute_mem_windows`; the keys
/// `xcl shaders --precompile` makes).
pub fn compute_windows(n: u32) -> u32 {
with_heap(n, heap_windows())
}

fn with_heap(n: u32, heap: bool) -> u32 {
if n > 1 && heap && !SWITCH_FORM.with(|s| s.get()) {
n | super::HEAP_WINDOWS | if heap_flat() { super::HEAP_FLAT } else { 0 }
} else {
n
}
}

/// The windows the HLSL path translates a program with: from the heap only with
/// `XCL_HEAP_WINDOWS=1`; by default they are the direct translator's (`compute_mem_windows`).
pub fn hlsl_windows(windows: u32) -> u32 {
if heap_windows_everywhere() {
windows
} else {
windows & !(super::HEAP_WINDOWS | super::HEAP_FLAT)
}
}

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) };
Expand All @@ -109,13 +141,50 @@ pub fn in_switch_form<R>(f: impl FnOnce() -> R) -> R {

/// 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.
/// instead of root UAVs, unless the views could not be made (no shared heap: then root UAVs, as
/// before). `XCL_HEAP_WINDOWS=1`: every stage; `=0`: none. By default on an NVIDIA adapter for the
/// compute programs the direct DXIL translator makes (`compute_mem_windows`), in `HEAP_FLAT`
/// form. Graphics stages keep root UAVs by default, as the other GPUs: the heap form is not
/// measured there. A pipeline the driver refuses with heap windows (E_OUTOFMEMORY, #156) is built
/// with root UAVs (`with_switch_fallback`).
pub fn heap_windows() -> bool {
heap_windows_by(heap_windows_env(), ADAPTER_VENDOR.load(std::sync::atomic::Ordering::Relaxed)) && !crate::hle::d3d12x::console_heap::window_views_failed()
}

/// `heap_windows` before the views: `XCL_HEAP_WINDOWS` when set, otherwise on for NVIDIA.
fn heap_windows_by(env: Option<bool>, vendor: u32) -> bool {
env.unwrap_or(vendor == NVIDIA)
}

/// `XCL_HEAP_WINDOWS=1`: heap windows for every stage (`heap_windows`).
pub fn heap_windows_everywhere() -> bool {
heap_windows_env() == Some(true) && heap_windows()
}

/// `XCL_HEAP_WINDOWS`: `1` on, `0` off, otherwise the adapter's default.
fn heap_windows_env() -> Option<bool> {
static ENV: OnceLock<Option<bool>> = OnceLock::new();
*ENV.get_or_init(|| match std::env::var("XCL_HEAP_WINDOWS").as_deref().map(str::trim) {
Ok("1") => Some(true),
Ok("0") => Some(false),
_ => None,
})
}

const NVIDIA: u32 = 0x10DE;
/// PCI vendor id of the adapter the title's device (or `xcl shaders`' bench) runs on; 0 before.
static ADAPTER_VENDOR: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);

/// The adapter's PCI vendor id (`DXGI_ADAPTER_DESC1::VendorId`), for `heap_windows`' default.
pub fn set_adapter_vendor(vendor: u32) {
ADAPTER_VENDOR.store(vendor, std::sync::atomic::Ordering::Relaxed);
}

/// With heap windows, the direct DXIL translator reads a compute stage's heap windows without
/// a branch per access (`HEAP_FLAT`); `XCL_HEAP_FLAT=0`: with the guarded branch.
pub fn heap_flat() -> 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()
*ENV.get_or_init(|| !std::env::var("XCL_HEAP_FLAT").is_ok_and(|v| v.trim() == "0"))
}

/// A static sampler of a translated program: (S#, comparison) – see `Translation`.
Expand All @@ -141,7 +210,8 @@ pub fn console_to_dxil(blob: &[u8], stage: Stage, sampler_base: u32) -> Result<C
/// (`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> {
console_to_dxil_in(blob, stage, sampler_base, split_wave64, mem_windows())
let windows = if stage == Stage::Compute { compute_mem_windows() } else { mem_windows() };
console_to_dxil_in(blob, stage, sampler_base, split_wave64, windows)
}

/// Global in-memory cache for translated shaders shared by `console_to_dxil_in` and `console_mesh`.
Expand Down Expand Up @@ -612,7 +682,7 @@ fn compile_console_shader(blob: &[u8], stage: Stage, sampler_base: u32, windows:
Err(e) => direct_fallback(if stage == Stage::Vertex { "VS" } else { "PS" }, &e),
}
}
let (mut t, profile) = console_translation(blob, stage, sampler_base, windows, split_wave64)?;
let (mut t, profile) = console_translation(blob, stage, sampler_base, hlsl_windows(windows), split_wave64)?;
if enormous(stage, t.hlsl.len()) && !crate::gpu::dxil::kernel::enabled() {
if dxc::defer() {
return Err("DXIL not compiled yet".into());
Expand Down Expand Up @@ -1384,6 +1454,39 @@ fn abi_signature(dev: &ID3D12Device, graphics: bool, samplers: &[StaticSampler],
}
}

#[cfg(test)]
mod heap_window_default_tests {
use super::*;

#[test]
fn heap_windows_by_default_on_nvidia_only() {
assert!(heap_windows_by(None, NVIDIA));
for vendor in [0, 0x1002, 0x8086, 0x1414] {
assert!(!heap_windows_by(None, vendor), "{vendor:#x}");
}
for vendor in [0, NVIDIA, 0x1002] {
assert!(heap_windows_by(Some(true), vendor));
assert!(!heap_windows_by(Some(false), vendor));
}
}

/// By default (heap windows not for every stage) a compute program with heap windows takes
/// them flat; the HLSL path and the switch form take the switch.
#[test]
fn default_heap_windows_are_flat_and_for_the_direct_form_only() {
if heap_windows_env().is_some() || std::env::var_os("XCL_HEAP_FLAT").is_some() {
println!("XCL_HEAP_WINDOWS / XCL_HEAP_FLAT set – skipping");
return;
}
let heap = super::super::HEAP_WINDOWS | super::super::HEAP_FLAT;
assert_eq!(with_heap(4, true), 4 | heap);
assert_eq!(with_heap(1, true), 1);
assert_eq!(with_heap(4, heap_windows_everywhere()), 4, "graphics stages: the switch");
assert_eq!(hlsl_windows(4 | heap), 4);
assert_eq!(in_switch_form(|| with_heap(4, true)), 4);
}
}

#[cfg(test)]
mod slab_tests {
use super::dispatch_slabs;
Expand Down
78 changes: 78 additions & 0 deletions crates/xcl/src/gpu/recomp/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4258,6 +4258,84 @@ fn memory_windows_reject_out_of_uma_aliasing(heap: bool) {
assert_eq!(*word(w1 + 0x3000), CANARY1, "out-of-UMA global_atomic_inc must not clobber w1");
}

/// Heap windows read without a branch (`HEAP_FLAT`, the direct translator): over 4 windows, the
/// same registers as the switch over root UAVs and as the guarded heap form, for scalar loads,
/// a V# load and per-lane global loads whose lanes pick different windows, some outside UMA
/// (read 0) and some not active (keep their old values).
#[test]
fn gpu_heap_flat_reads_match_the_switch_form() {
use crate::gpu::dxil::kernel::{translate, KernelOptions};
if !gpu_ready() {
return;
}
let arena = crate::gpu::uma::Uma::with_windows(4, 1 << 20).unwrap();
let w: Vec<u64> = (0..4).map(|k| arena.window(k).0 as u64).collect();
let base_hi = (w[0] >> 32) as u32;
let word = |a: u64| unsafe { &mut *(a as *mut u32) };
for (k, &wk) in w.iter().enumerate() {
*word(wk + 0x40) = 0xA0 + k as u32;
// 65 words: lane 63's dwordx2 reads the 65th
for l in 0..65u64 {
*word(wk + 0x100 + 4 * l) = (k as u32 + 1) * 1000 + l as u32;
}
}
let glbl = |n: &'static str, f: &[(&str, u64)]| -> (&'static str, &'static str, Vec<(&'static str, u64)>, Option<u32>) {
(n, "ENC_FLAT_GLBL", f.iter().map(|&(a, b)| (unsafe { std::mem::transmute::<&str, &'static str>(a) }, b)).collect(), None)
};
let list = vec![
("S_LOAD_DWORD", "ENC_SMEM", vec![("SDATA", 30), ("SBASE", 1), ("OFFSET", 0)], None), // s[2:3] → window 2
("S_LOAD_DWORD", "ENC_SMEM", vec![("SDATA", 31), ("SBASE", 2), ("OFFSET", 0)], None), // s[4:5] → outside UMA: 0
("S_BUFFER_LOAD_DWORDX4", "ENC_SMEM", vec![("SDATA", 24), ("SBASE", 4), ("OFFSET", 4)], None), // V# s[8:11] in window 3
// lanes 33.. active from here
("V_CMPX_LT_U32", "ENC_VOPC", vec![("SRC0", 160), ("VSRC1", 0)], None),
("BUFFER_LOAD_DWORD", "ENC_MUBUF", vec![("VDATA", 7), ("VADDR", 0), ("SRSRC", 3), ("SOFFSET", 128), ("IDXEN", 1)], None), // V# s[12:15] in window 1
glbl("GLOBAL_LOAD_DWORD", &[("VDST", 6), ("ADDR", 4), ("SADDR", 0x7D), ("OFFSET", 0)]), // v[4:5]: window lane % 4, or outside
glbl("GLOBAL_LOAD_DWORDX2", &[("VDST", 8), ("ADDR", 10), ("SADDR", 16), ("OFFSET", 0)]), // s[16:17] + v10: window 0
];
let refs: Vec<(&str, &str, &[(&str, u64)], Option<u32>)> = list.iter().map(|(a, b, c, d)| (*a, *b, c.as_slice(), *d)).collect();
let p = prog(&refs);
let mut st = KernelState::default();
st.sgpr[2..4].copy_from_slice(&[0x40, base_hi + 2]);
st.sgpr[4..6].copy_from_slice(&[0x40, base_hi + 6]);
st.sgpr[8..12].copy_from_slice(&[0x100, (base_hi + 3) & 0xFFFF, 0x400, 0]);
st.sgpr[12..16].copy_from_slice(&[0x100, (base_hi + 1) & 0xFFFF | 4 << 16, 64, 0]);
st.sgpr[16..18].copy_from_slice(&[0x100, base_hi]);
for (l, r) in st.vgpr.iter_mut().enumerate() {
let l = l as u32;
r[0] = l;
r[4] = 0x100 + 4 * l;
r[5] = if l % 8 == 7 { base_hi + 5 } else { base_hi + l % 4 };
for k in 6..10 {
r[k] = 0x7777_7777;
}
r[10] = 4 * l;
}
let split = runner::split_wave64();
let run = |windows: u32| {
let dxil = translate(&p, KernelOptions { wave64: true, split, mem_windows: windows, sampler_base: 0 }).unwrap_or_else(|e| panic!("windows {windows:#x}: {e}"));
runner::run_in_arena(&dxil, &st, &arena).unwrap()
};
let switch = run(4);
let flat = run(4 | super::HEAP_WINDOWS | super::HEAP_FLAT);
let guarded = run(4 | super::HEAP_WINDOWS);
assert_eq!((switch.sgpr[30], switch.sgpr[31]), (0xA2, 0), "s_load: window 2, outside UMA");
assert_eq!(switch.sgpr[24..28], [4001, 4002, 4003, 4004], "s_buffer_load_dwordx4 from window 3");
for l in 0..64u32 {
let v = &switch.vgpr[l as usize];
let (old, active) = (0x7777_7777, l > 32);
assert_eq!(v[7], if active { 2000 + l } else { old }, "lane {l}: buffer_load from window 1");
let global = if l % 8 == 7 { 0 } else { (l % 4 + 1) * 1000 + l };
assert_eq!(v[6], if active { global } else { old }, "lane {l}: global_load from window {}", l % 4);
assert_eq!(v[8..10], if active { [1000 + l, 1001 + l] } else { [old, old] }, "lane {l}: global_load_dwordx2 from window 0");
}
for (name, r) in [("heap flat", &flat), ("heap guarded", &guarded)] {
assert_eq!(r.sgpr[..32], switch.sgpr[..32], "{name}: SGPRs");
for l in 0..64 {
assert_eq!(r.vgpr[l][..10], switch.vgpr[l][..10], "{name}: lane {l}");
}
}
}

#[test]
fn gpu_window_at_32bit_carry_edge_cases() {
if !gpu_ready() {
Expand Down
2 changes: 1 addition & 1 deletion crates/xcl/src/gpu/uma.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ pub(crate) fn configured_runtime_windows() -> usize {
crate::xlog_warn!("UMA: XCL_UMA_WINDOWS={val:?} must be 4, 8, or 16 – using {MAX_WINDOWS}");
return MAX_WINDOWS;
}
if n > MAX_WINDOWS && !crate::gpu::recomp::pso::heap_windows() {
if n > MAX_WINDOWS && !crate::gpu::recomp::pso::heap_windows_everywhere() {
crate::xlog_warn!("UMA: XCL_UMA_WINDOWS={n} requires XCL_HEAP_WINDOWS=1 – using {MAX_WINDOWS}");
return MAX_WINDOWS;
}
Expand Down
Loading
Loading