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
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 @@ -513,6 +534,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 @@ -83,6 +83,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 @@ -1499,7 +1504,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
16 changes: 14 additions & 2 deletions crates/xcl/src/gpu/recomp/pso.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,9 +77,14 @@ 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`).
pub fn mem_windows() -> u32 {
let n = crate::gpu::uma::get().map_or(1, |u| u.shader_windows() as u32);
windows_for(crate::gpu::uma::get().map_or(1, |u| u.shader_windows() as u32))
}

/// `n` windows as this run's programs take them (`mem_windows`; also the keys
/// `xcl shaders --precompile` makes, so they are the ones the runtime looks up).
pub fn windows_for(n: u32) -> u32 {
if n > 1 && heap_windows() && !SWITCH_FORM.with(|s| s.get()) {
n | super::HEAP_WINDOWS
n | super::HEAP_WINDOWS | if heap_flat() { super::HEAP_FLAT } else { 0 }
} else {
n
}
Expand Down Expand Up @@ -115,6 +120,13 @@ pub fn heap_windows() -> bool {
*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()
}

/// `XCL_HEAP_FLAT=1` (with heap windows): the direct DXIL translator reads a compute stage's heap
/// windows without a branch per access (`HEAP_FLAT`). Opt-in while it is measured.
pub fn heap_flat() -> bool {
static ENV: OnceLock<bool> = OnceLock::new();
*ENV.get_or_init(|| std::env::var("XCL_HEAP_FLAT").is_ok_and(|v| v.trim() == "1"))
}

/// A static sampler of a translated program: (S#, comparison) – see `Translation`.
pub type StaticSampler = ([u32; 4], bool);

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
42 changes: 34 additions & 8 deletions crates/xcl/src/shaders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -914,12 +914,7 @@ pub fn run(path: &Path, args: &[String]) -> i32 {
return 2;
}
};
// the runtime's memory windows: from the descriptor heap with `XCL_HEAP_WINDOWS=1`
// (`pso::mem_windows`), as `--precompile`
let runtime_windows = || {
let windows = opts.windows;
if windows > 1 && recomp::pso::heap_windows() { windows | recomp::HEAP_WINDOWS } else { windows }
};
let runtime_windows = || runtime_windows(opts.windows);
let top = opts.top;
let json = opts.json;
let compile = opts.compile;
Expand Down Expand Up @@ -991,6 +986,12 @@ pub fn run(path: &Path, args: &[String]) -> i32 {
print(path, &what, agg, top, json, t0, compile)
}

/// The runtime's memory windows (`pso::windows_for`, which `pso::mem_windows` takes too), as
/// `--precompile`, `--export-hlsl` and `--measure-pso` key and translate the programs.
fn runtime_windows(windows: u32) -> u32 {
recomp::pso::windows_for(windows)
}

#[cfg(test)]
fn parse_record_hash(s: &str) -> Result<u64, String> {
crate::cli::parse_hex_u64_str(s)
Expand Down Expand Up @@ -1092,7 +1093,7 @@ fn export_hlsl(input: &Input, dir: &Path, min_kb: usize, count: usize, windows:
println!(
"{written} program(s) written to {} (split wave64: {split}, {} windows{}, {failures} failure(s))",
dir.display(),
windows & !recomp::HEAP_WINDOWS,
windows & !(recomp::HEAP_WINDOWS | recomp::HEAP_FLAT),
if windows & recomp::HEAP_WINDOWS != 0 { " from the descriptor heap" } else { "" }
);
if written == wanted { 0 } else {
Expand Down Expand Up @@ -1623,7 +1624,7 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option<bool>, on
"precompiling {n} shaders into {} ({} compile threads; {} memory windows{}{})",
recomp::dxc::cache_dir().display(),
recomp::dxc::compile_threads(),
windows & !recomp::HEAP_WINDOWS,
windows & !(recomp::HEAP_WINDOWS | recomp::HEAP_FLAT),
if windows & recomp::HEAP_WINDOWS != 0 { " from the descriptor heap" } else { "" },
if split { ", split wave64 for a GPU with 32-lane waves" } else { "" }
);
Expand Down Expand Up @@ -2070,6 +2071,31 @@ fn print(path: &Path, what: &str, agg: Agg, top: usize, json: bool, t0: std::tim

#[cfg(test)]
mod tests {
/// `--precompile` keys its programs with the runtime's windows: with `XCL_HEAP_WINDOWS=1
/// XCL_HEAP_FLAT=1` they carry `HEAP_FLAT`, as `pso::mem_windows` does. The switches are
/// read once (`OnceLock`), so each setting runs in a new process.
#[test]
fn precompile_windows_are_the_runtimes() {
use crate::gpu::recomp::{pso, HEAP_FLAT, HEAP_WINDOWS};
const RUN: &str = "XCL_TEST_PRECOMPILE_WINDOWS";
if let Ok(want) = std::env::var(RUN) {
assert_eq!(super::runtime_windows(4), pso::windows_for(4));
assert_eq!(super::runtime_windows(4), want.parse::<u32>().unwrap());
return;
}
for (flat, want) in [("1", 4 | HEAP_WINDOWS | HEAP_FLAT), ("0", 4 | HEAP_WINDOWS)] {
let out = std::process::Command::new(std::env::current_exe().unwrap())
.args(["--exact", "shaders::tests::precompile_windows_are_the_runtimes", "--nocapture"])
.env(RUN, want.to_string())
.env("XCL_HEAP_WINDOWS", "1")
.env("XCL_HEAP_FLAT", flat)
.output()
.unwrap();
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(out.status.success() && stdout.contains("1 passed"), "XCL_HEAP_FLAT={flat}: {stdout}\n{}", String::from_utf8_lossy(&out.stderr));
}
}

/// `--used-only` keeps a compute program exactly when the runtime noted its pipeline: the
/// key of a pipeline of that one shader, as `real::shaders_key` makes it.
#[test]
Expand Down
Loading