Skip to content
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,8 @@ next to `xcl.exe`, directly next to `xcl.exe`, in `%LOCALAPPDATA%\XCL\D3D12\`, o
64-lane waves, most for groups of several waves; wave64 vertex and pixel shaders that read lanes 32–63
can still differ there. With `XCL_DIRECT_DXIL=1` and `XCL_PER_LANE=1`, compute groups
made up of complete native waves can use the per-lane form for branches on whole-wave masks.
With direct DXIL on NVIDIA, `XCL_DXIL_OUTLINE=1` lets compute shaders share a scalar-load function when its
addressing form and width occur at four or more emitted sites. The switch defaults to off. Other adapters keep scalar loads inline.
Test results on other GPUs: [#42](https://github.com/ivall/xcl/issues/42).

```powershell
Expand Down
13 changes: 13 additions & 0 deletions crates/xcl/src/gpu/adapter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
//! (`gpu::recomp::runner`), so the GPU tests can be run on each adapter of a machine in turn.

use std::fmt;
use std::sync::OnceLock;

use windows::Win32::Graphics::Dxgi::*;

Expand Down Expand Up @@ -115,6 +116,18 @@ pub(crate) fn select_indices<S: AsRef<str>>(names: &[S], sel: &Selector) -> Vec<
Vec::new()
}

/// The title may fall back to another adapter while opening its D3D12 device.
pub(crate) static TITLE_VENDOR: OnceLock<u32> = OnceLock::new();

/// Offline shaders and the test runner select the first matching hardware adapter.
pub(crate) fn shader_vendor() -> Option<u32> {
static OFFLINE_VENDOR: OnceLock<Option<u32>> = OnceLock::new();
TITLE_VENDOR.get().copied().or_else(|| *OFFLINE_VENDOR.get_or_init(|| {
let factory: IDXGIFactory6 = unsafe { CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)) }.ok()?;
candidates(&factory, &Selector::from_env_or("auto")).first().map(|(_, d)| d.VendorId)
}))
}

/// The adapter's name from its description.
pub fn name(desc: &DXGI_ADAPTER_DESC1) -> String {
let n = desc.Description.iter().position(|&c| c == 0).unwrap_or(desc.Description.len());
Expand Down
167 changes: 167 additions & 0 deletions crates/xcl/src/gpu/dxil/core_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -831,3 +831,170 @@ fn raw_loads_in_root_windows_respect_exec_and_bounds() {
}
}
}

fn scalar_load_fixture() -> Vec<u8> {
prog(&[
("S_BUFFER_LOAD_DWORDX4", "ENC_SMEM", &[("SDATA", 24), ("SBASE", 4), ("SOFFSET", 125)], None),
("S_LOAD_DWORDX2", "ENC_SMEM", &[("SDATA", 28), ("SBASE", 4), ("SOFFSET", 125)], None),
("S_BUFFER_LOAD_DWORDX4", "ENC_SMEM", &[("SDATA", 32), ("SBASE", 4), ("OFFSET", 4), ("SOFFSET", 125)], None),
("S_BUFFER_LOAD_DWORDX4", "ENC_SMEM", &[("SDATA", 40), ("SBASE", 4), ("OFFSET", 8), ("SOFFSET", 125)], None),
("S_BUFFER_LOAD_DWORDX4", "ENC_SMEM", &[("SDATA", 44), ("SBASE", 4), ("OFFSET", 12), ("SOFFSET", 125)], None),
("S_LOAD_DWORDX2", "ENC_SMEM", &[("SDATA", 48), ("SBASE", 4), ("OFFSET", 4), ("SOFFSET", 125)], None),
("S_LOAD_DWORDX2", "ENC_SMEM", &[("SDATA", 50), ("SBASE", 4), ("OFFSET", 8), ("SOFFSET", 125)], None),
("S_LOAD_DWORDX2", "ENC_SMEM", &[("SDATA", 52), ("SBASE", 4), ("OFFSET", 12), ("SOFFSET", 125)], None),
])
}

#[test]
fn scalar_load_threshold_counts_emitted_sites_per_shape() {
let threshold = super::lower_mem::MIN_OUTLINE_SITES;
let opts = KernelOptions { wave64: false, split: false, mem_windows: 4, sampler_base: 0 };
for n in [threshold - 1, threshold] {
let mut code = Vec::new();
for site in 0..n {
for _ in 0..2 {
// The second load of the same address is a reload hit.
code.extend(encode("S_LOAD_DWORDX2", "ENC_SMEM", &[("SDATA", 24), ("SBASE", 4),
("OFFSET", u64::from(site) * 4), ("SOFFSET", 125)], None).unwrap());
}
}
code.extend(prog(&[("S_BUFFER_LOAD_DWORDX2", "ENC_SMEM", &[("SDATA", 36), ("SBASE", 4), ("SOFFSET", 125)], None)]));
let blob = super::kernel::translate_outline_fixture(&code, opts, true).unwrap();
let ir = super::validate::disassemble(&blob).unwrap();
assert_eq!(ir.contains("@xcl_scalar_load_2("), n == threshold);
assert!(!ir.contains("@xcl_buffer_load_2("));
}
}

#[test]
fn scalar_load_outlining_requires_nvidia() {
assert!(super::kernel::outline_supported(Some(0x10de)));
for vendor in [Some(0x1002), Some(0x8086), Some(0x1414), None] {
assert!(!super::kernel::outline_supported(vendor));
}
}

#[test]
fn outlined_scalar_loads_validate() {
for windows in [1, 4, 0x104] {
let opts = KernelOptions { wave64: true, split: true, mem_windows: windows, sampler_base: 0 };
let blob = super::kernel::translate_outline_fixture(&scalar_load_fixture(), opts, true).unwrap();
super::validate::validate(&blob).unwrap();
let ir = super::validate::disassemble(&blob).unwrap();
for name in ["@xcl_buffer_load_4(", "@xcl_scalar_load_2("] {
let definition = ir.lines().find(|l| l.starts_with("define internal void") && l.contains(name)).expect("wide load helper");
assert!(definition.contains("[16 x i32]* noalias"), "{definition}");
}
}
}

fn outline_fixture_applies(vendor: Option<u32>) -> bool {
if vendor.is_none() {
crate::gpu::recomp::runner::skip_test("could not identify the GPU for scalar-load outlining");
return false;
}
if !super::kernel::outline_supported(vendor) {
use std::io::Write;
let thread = std::thread::current();
let _ = writeln!(std::io::stderr(), "SKIPPED {}: NVIDIA-only scalar-load fixture", thread.name().unwrap_or("?"));
return false;
}
true
}

#[test]
fn outlined_scalar_loads_strict_vendor_exclusion() {
// Isolate XCL_REQUIRE_GPU from the other tests running in this process.
const CHILD: &str = "XCL_TEST_OUTLINE_VENDOR_CHILD";
if std::env::var_os(CHILD).is_some() {
assert!(!outline_fixture_applies(Some(0x1002)));
assert!(outline_fixture_applies(Some(0x10de)));
assert!(std::panic::catch_unwind(|| outline_fixture_applies(None)).is_err());
return;
}
for mode in ["wave64", "mesh"] {
let test = std::thread::current();
let output = std::process::Command::new(std::env::current_exe().unwrap())
.args(["--exact", test.name().unwrap()])
.env(CHILD, "1").env("XCL_REQUIRE_GPU", mode)
.output().unwrap();
assert!(output.status.success(), "{mode}: {}{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr));
}
}

#[test]
fn outlined_scalar_loads_match_inline_at_view_end() {
if !outline_fixture_applies(crate::gpu::adapter::shader_vendor()) {
return;
}
use crate::gpu::recomp::runner::{self, KernelState};
let (wave32, native64) = match (runner::wave32_supported(), runner::wave64_supported()) {
(Ok(a), Ok(b)) => (a, b),
(Err(e), _) | (_, Err(e)) => return runner::skip_test(&e),
};
if !wave32 && !native64 {
return runner::skip_test("no wave32 or wave64 GPU");
}
let memory: Vec<u32> = (0..32).map(|i| 0xabc0_0000 + i).collect();
for (wave64, split) in [(false, false), (true, true), (true, false)] {
if (wave64 && !split && !native64) || ((!wave64 || split) && !wave32) { continue; }
let opts = KernelOptions { wave64, split, mem_windows: 1, sampler_base: 0 };
let blobs = [false, true].map(|enabled| super::kernel::translate_outline_fixture(&scalar_load_fixture(), opts, enabled).unwrap());
for (lo, hi) in [(u32::MAX, 0), (0, 0x7f), (1, 0)] {
let mut state = KernelState::default();
state.sgpr[126..128].copy_from_slice(&[lo, hi]);
state.sgpr[8..12].copy_from_slice(&[16, 0, 10, 0]);
let [a, b] = blobs.each_ref().map(|dxil| runner::run(dxil, &state, &memory).unwrap());
assert_eq!(a.raw, b.raw);
assert_eq!(&b.sgpr[24..28], &[memory[4], memory[5], memory[6], 0]);
assert_eq!(&b.sgpr[32..36], &[memory[5], memory[6], 0, 0]);
}
}
}

#[test]
fn outlined_scalar_loads_preserve_distinct_image_descriptors() {
if !outline_fixture_applies(crate::gpu::adapter::shader_vendor()) {
return;
}
use crate::gpu::recomp::runner::{self, KernelState, TestTexture, TexDim};
use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32_UINT;

if !runner::wave32_supported().unwrap_or(false) {
return runner::skip_test("no wave32 GPU");
}

// Keep four different descriptor indices live across calls to the same eight-word helper.
let mut code = Vec::new();
let mut memory = Vec::new();
for i in 0..4 {
code.extend(encode("S_LOAD_DWORDX8", "ENC_SMEM", &[("SDATA", 16 + 8 * i), ("SBASE", 4), ("OFFSET", 32 * i), ("SOFFSET", 125)], None).unwrap());
memory.extend_from_slice(&[2 * i as u32, 20 << 20, 0, 9 << 28, 0, 0, 0, 0]);
}
for i in 0..4 {
code.extend(encode("IMAGE_STORE", "ENC_MIMG", &[("VDATA", 4 + i), ("VADDR", 0), ("SRSRC", 4 + 2 * i), ("DMASK", 1), ("DIM", 1), ("UNORM", 1)], None).unwrap());
}
code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap());
let textures: Vec<_> = (0..4).map(|_| TestTexture {
dim: TexDim::D2, format: DXGI_FORMAT_R32_UINT, width: 32, height: 1, depth: 1,
texel_bytes: 4, data: vec![0; 128], uav: true,
}).collect();
let mut state = KernelState::default();
for (lane, vgprs) in state.vgpr.iter_mut().enumerate() {
vgprs[0] = lane as u32;
for i in 0..4 { vgprs[4 + i] = 0x12340000 + (i as u32) * 32 + lane as u32; }
}
let opts = KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 };
for outline in [false, true] {
let dxil = super::kernel::translate_outline_fixture(&code, opts, outline).unwrap();
let result = runner::run_with(&dxil, &state, &memory, &textures, &[]).unwrap();
assert_eq!(result.textures.len(), textures.len());
for (i, bytes) in result.textures.iter().enumerate() {
assert_eq!(bytes.len(), 32 * 4);
for (lane, texel) in bytes.chunks_exact(4).enumerate() {
let expected = 0x12340000 + i as u32 * 32 + lane as u32;
assert_eq!(u32::from_le_bytes(texel.try_into().unwrap()), expected, "outline={outline} texture={i} lane={lane}");
}
}
}
}
44 changes: 43 additions & 1 deletion crates/xcl/src/gpu/dxil/kernel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,24 @@ pub fn translate_compute_on(code: &[u8], o: KernelOptions, cs: &CsInterface, wav
translate_entry(code, o, Entry::Compute(cs.clone()), compact_mode(), None, tables)
}

pub(super) fn outline_supported(vendor: Option<u32>) -> bool {
vendor == Some(0x10de) // NVIDIA
}

pub(crate) fn outline_enabled() -> bool {
if !std::env::var("XCL_DXIL_OUTLINE").is_ok_and(|v| v == "1") {
return false;
}
if outline_supported(crate::gpu::adapter::shader_vendor()) {
return true;
}
static WARN: std::sync::Once = std::sync::Once::new();
WARN.call_once(|| {
crate::xlog_warn!("XCL_DXIL_OUTLINE=1 requires an NVIDIA adapter. Using inline scalar loads.");
});
false
}

fn translate_entry(
code: &[u8],
o: KernelOptions,
Expand All @@ -158,11 +176,12 @@ fn translate_entry(
) -> Result<Kernel, String> {
// SSA construction recurses along the CFG (one level per guarded memory access between
// a register's definition and its use): a thread with a large stack for big programs
let outline = matches!(entry, Entry::Kernel | Entry::Compute(_)) && outline_enabled();
let code = code.to_vec();
std::thread::Builder::new()
.name("xcl-dxil-translate".into())
.stack_size(256 << 20)
.spawn(move || translate_on_this_thread(&code, o, entry, compact, nest, tables))
.spawn(move || translate_on_this_thread(&code, o, entry, compact, nest, tables, outline))
.map_err(|e| format!("translator thread: {e}"))?
.join()
.map_err(|e| {
Expand All @@ -186,13 +205,19 @@ fn mem_windows(s: &mut Shader, mem_windows: u32, coherent: bool) -> (Vec<RawUav>
((0..n).map(|k| if coherent { s.raw_uav_coherent(2 + k, 0) } else { s.raw_uav(2 + k, 0) }).collect(), None)
}

#[cfg(test)]
pub(super) fn translate_outline_fixture(code: &[u8], o: KernelOptions, outline: bool) -> Result<Vec<u8>, String> {
translate_on_this_thread(code, o, Entry::Kernel, Some(false), None, 0, outline).map(|k| k.dxil)
}

fn translate_on_this_thread(
code: &[u8],
o: KernelOptions,
entry: Entry,
compact: Option<bool>,
nest: Option<super::compact::Nest>,
tables: usize,
outline: bool,
) -> Result<Kernel, String> {
let geo = match &entry {
Entry::Geometry(g) => Some(g.clone()),
Expand Down Expand Up @@ -336,6 +361,22 @@ fn translate_on_this_thread(
// scalar loads the program repeats keep their first values (compute programs and kernels:
// the other stages enter their code by edges the CFG does not hold)
let reloads = if follow_loads { super::reload::analyze(&cfg) } else { Default::default() };
if outline && follow_loads {
// Compact lowering emits each representative once and does not substitute reloads.
let mut count_block = |b: usize| {
for &i in &cfg.blocks[b].insts {
if plan.is_none() && reloads.get(b, i).is_some_and(|r| r.available) { continue; }
if let Some((buffer, words)) = super::lower_mem::scalar_load_shape(cfg.insts[i].inst.name) {
lw.scalar_load_sites[buffer as usize][words.ilog2() as usize] += 1;
}
}
};
if let Some(p) = &plan {
for &r in &p.rep { count_block(p.order[r]); }
} else {
for &b in &cfg.rpo { count_block(b); }
}
}
let mut gs_entry: Option<usize> = None;
if let Some(p) = &plan {
match nest {
Expand Down Expand Up @@ -553,6 +594,7 @@ impl Lw {
guard_override: None,
mask_override: None,
local_masks: false,
scalar_load_sites: [[0; 5]; 2],
exchange_error: None,
pc: 0,
};
Expand Down
1 change: 1 addition & 0 deletions crates/xcl/src/gpu/dxil/lower.rs
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,7 @@ pub struct Lw {
/// when it is never read whole. Set by a caller that reads back only each lane's own bit
/// (the per-lane form's bridge), so no exchange meets the other half.
pub local_masks: bool,
pub scalar_load_sites: [[u32; 5]; 2],
}

impl Lw {
Expand Down
Loading
Loading