Skip to content
Draft
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: 7 additions & 1 deletion crates/xcl/src/gpu/dxil/kernel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,10 +159,16 @@ fn translate_entry(
// 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 code = code.to_vec();
#[cfg(test)]
let no_select_fold = super::module::NO_SELECT_FOLD.with(|c| c.get());
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 || {
#[cfg(test)]
super::module::NO_SELECT_FOLD.with(|c| c.set(no_select_fold));
translate_on_this_thread(&code, o, entry, compact, nest, tables)
})
.map_err(|e| format!("translator thread: {e}"))?
.join()
.map_err(|e| {
Expand Down
2 changes: 2 additions & 0 deletions crates/xcl/src/gpu/dxil/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,5 @@ mod msaa_tests;
mod round_tests;
#[cfg(test)]
mod geometry_tests;
#[cfg(test)]
mod select_tests;
2 changes: 2 additions & 0 deletions crates/xcl/src/gpu/dxil/module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ use std::collections::HashMap;
use super::bitstream::{signed, BitWriter};

mod opt;
#[cfg(test)]
pub(crate) use opt::NO_SELECT_FOLD;
pub(super) mod split;

// ---------------------------------------------------------------- types
Expand Down
168 changes: 167 additions & 1 deletion crates/xcl/src/gpu/dxil/module/opt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,12 @@ impl Op {
}
}

#[cfg(test)]
thread_local! {
/// Tests can compare emitted code with the guarded-select fold disabled.
pub(crate) static NO_SELECT_FOLD: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

/// How an instruction may be merged with an identical one.
#[derive(PartialEq)]
enum Cse {
Expand Down Expand Up @@ -610,7 +616,7 @@ impl Module {
/// Cleans up the entry function (see the module docs of `opt`). Values
/// keep their identities; replaced ones simply lose their uses.
///
/// `XCL_DXIL_NO_OPT=phi,cse,dce,merge` (any subset, or `all`) skips passes, for bisecting.
/// `XCL_DXIL_NO_OPT=phi,cse,select,dce,merge` (any subset, or `all`) skips passes, for bisecting.
pub fn optimize(&mut self) {
let off = std::env::var("XCL_DXIL_NO_OPT").unwrap_or_default();
let skip = |p: &str| off.split(',').any(|x| x.trim() == p || x.trim() == "all");
Expand Down Expand Up @@ -788,6 +794,14 @@ impl Module {
}
}

#[cfg(test)]
let skip_select = NO_SELECT_FOLD.with(|c| c.get());
#[cfg(not(test))]
let skip_select = false;
if !skip("select") && !skip_select {
self.fold_guarded_selects(&order, &repl);
}

// dead instructions: live = side effects, terminators and their operands, transitively
let (i64t, f64t) = self.existing_i64_f64();
let wide: Vec<Ty> = i64t.into_iter().chain(f64t).collect();
Expand Down Expand Up @@ -890,6 +904,115 @@ impl Module {
}
}

/// Whether `op` computes each lane from only that lane's operands. Operations whose
/// evaluation observes other lanes, memory, or undefined integer division operands are
/// deliberately excluded.
fn lane_local(&self, op: &Op, ty: Ty) -> bool {
match op {
Op::Bin(BinOp::UDiv | BinOp::URem, ..) => false,
Op::Bin(BinOp::SDiv | BinOp::SRem, ..) => self.is_float(ty),
Op::Bin(..) | Op::Cast(..) | Op::Cmp(..) | Op::Select(..) | Op::Extract(..) => true,
Op::Call(f, args) => {
let d = &self.funcs[*f as usize];
d.attrs == FnAttrs::ReadNone
&& d.name.starts_with("dx.op.")
&& args.first().and_then(|&a| self.const_u64(a)).is_some_and(|id| matches!(id, 6..=56 | 101 | 102 | 124..=132))
}
_ => false,
}
}

/// Reads through `select(c, current, old)` only where the value is ultimately observed
/// under the same `c`. This removes guest-EXEC preservation arms from chains of lane-local
/// operations without changing inactive lanes. Phis and non-lane-local operations observe
/// all lanes and stop the fold.
fn fold_guarded_selects(&mut self, order: &[u32], repl: &[Option<Value>]) {
#[derive(Clone, Copy, PartialEq)]
enum Seen {
Unused,
Where(Value),
All,
}
fn meet(s: &mut Seen, by: Seen) {
*s = match (*s, by) {
(x, Seen::Unused) => x,
(Seen::Unused, y) => y,
(Seen::Where(a), Seen::Where(b)) if a == b => Seen::Where(a),
_ => Seen::All,
}
}

let live = |i: u32| repl[i as usize].is_none();
let mut seen = vec![Seen::Unused; self.insts.len()];
for &b in order {
for &i in &self.blocks[b as usize] {
if let (true, Op::Phi(inc)) = (live(i), &self.insts[i as usize].op) {
for &(v, _) in inc {
if let Value::Inst(j) = v {
seen[j as usize] = Seen::All;
}
}
}
}
}
for &b in order.iter().rev() {
for &i in self.blocks[b as usize].iter().rev() {
if !live(i) {
continue;
}
let (op, ty) = (&self.insts[i as usize].op, self.insts[i as usize].ty);
if matches!(op, Op::Phi(_)) {
continue;
}
let me = if self.lane_local(op, ty) { seen[i as usize] } else { Seen::All };
if me == Seen::Unused {
continue;
}
let mut by = |v: Value, s: Seen| {
if let Value::Inst(j) = v {
meet(&mut seen[j as usize], s);
}
};
match *op {
Op::Select(c, a, b) => {
by(c, me);
by(a, Seen::Where(c));
by(b, me);
}
_ => op.for_each_operand(|v| by(v, me)),
}
}
}
for &b in order {
for k in 0..self.blocks[b as usize].len() {
let i = self.blocks[b as usize][k];
let (op, ty) = (&self.insts[i as usize].op, self.insts[i as usize].ty);
if !live(i) || seen[i as usize] == Seen::Unused || !self.lane_local(op, ty) {
continue;
}
let me = seen[i as usize];
let outer_condition = if let Op::Select(c, ..) = *op { Some(c) } else { None };
let mut op = op.clone();
let mut pos = 0;
op.map_operands(|mut v| {
let at = pos;
pos += 1;
while let Value::Inst(j) = v {
let Op::Select(c, t, f) = self.insts[j as usize].op else { break };
v = match (outer_condition, at) {
(Some(outer), 1) if outer == c => t,
(Some(outer), 2) if outer == c => f,
_ if me == Seen::Where(c) => t,
_ => break,
};
}
v
});
self.insts[i as usize].op = op;
}
}
}

/// Simplifies the CFG to a fixed point:
/// 1. Collapses degenerate `CondBr(_, t, t)` and `Switch` cases matching the default target.
/// 2. Bypasses empty trampoline blocks (`[Br(t)]`) whenever `t`'s phis allow it.
Expand Down Expand Up @@ -1584,6 +1707,48 @@ mod tests {
let order: Vec<u32> = m.block_layout().0.into_iter().map(|b| b as u32).collect();
assert!(m.uses_well_formed(&order));
}
#[test]
fn guarded_selects_fold_only_for_same_condition_lane_local_uses() {
let mut m = Module::new();
m.define_entry("main");
let entry = m.entry_block();
m.set_block(entry);

let void = m.void();
let i32t = m.i32();
let src_ty = m.func_ty(i32t, &[]);
let src = m.declare("dx.op.waveGetLaneIndex", src_ty, FnAttrs::ReadNone);
let sink_ty = m.func_ty(void, &[i32t]);
let sink = m.declare("dx.op.storeOutput.i32", sink_ty, FnAttrs::NoUnwind);

let x = m.call(src, &[]);
let (one, three, five, sentinel) = (m.i32c(1), m.i32c(3), m.i32c(5), m.i32c(0xA5A5_5A5A));
let exec = m.cmp(Pred::ULt, x, five);
let old = m.bin(BinOp::Xor, x, sentinel);
let current = m.bin(BinOp::Add, x, one);
let saved = m.select(exec, current, old);
let product = m.bin(BinOp::Mul, saved, three);
let guarded = m.select(exec, product, saved);

// A second preserved value is read by an all-lane observer and must remain intact.
let must_stay = m.select(exec, current, x);
let all_lane_use = m.bin(BinOp::Sub, must_stay, one);
m.call(sink, &[guarded]);
m.call(sink, &[all_lane_use]);
m.ret();
m.optimize();

let Value::Inst(guarded_i) = guarded else { panic!() };
let Value::Inst(product_i) = product else { panic!() };
assert!(matches!(m.insts[guarded_i as usize].op, Op::Select(c, t, f) if c == exec && t == product && f == old));
assert!(matches!(m.insts[product_i as usize].op, Op::Bin(BinOp::Mul, a, b, 0) if (a, b) == (current, three) || (a, b) == (three, current)));
let body = &m.blocks[entry.0 as usize];
let present = |v: Value| matches!(v, Value::Inst(i) if body.contains(&i));
assert!(!present(saved), "the EXEC-preservation select should have no uses");
assert!(present(must_stay), "an all-lane use must retain its preservation select");
let order: Vec<u32> = m.block_layout().0.into_iter().map(|b| b as u32).collect();
assert!(m.uses_well_formed(&order));
}
}

#[cfg(test)]
Expand Down Expand Up @@ -1755,4 +1920,5 @@ mod int_minmax_tests {
assert_eq!(r.vgpr[l][5], a.min(b), "med3_u32(v0, 0, v1) lane {l}");
}
}

}
95 changes: 95 additions & 0 deletions crates/xcl/src/gpu/dxil/select_tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
//! GPU equivalence for the guarded-select fold, including inactive lanes.

use super::kernel::{translate, KernelOptions};
use super::module::NO_SELECT_FOLD;
use crate::gpu::rdna2::encode;
use crate::gpu::recomp::runner::{self, KernelState};

const V: u64 = 256;

fn program(list: &[(&str, &str, &[(&str, u64)])]) -> Vec<u8> {
let mut code = Vec::new();
for (name, encoding, fields) in list {
code.extend(encode(name, encoding, fields, None).unwrap_or_else(|e| panic!("{name}: {e}")));
}
code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap());
code
}

fn translate_with_fold(code: &[u8], options: KernelOptions, enabled: bool) -> Vec<u8> {
NO_SELECT_FOLD.with(|c| c.set(!enabled));
let result = translate(code, options);
NO_SELECT_FOLD.with(|c| c.set(false));
result.unwrap_or_else(|e| panic!("translate (select fold {enabled}): {e}"))
}

#[test]
fn gpu_guarded_select_fold_preserves_inactive_lanes() {
match (runner::adapter(), runner::wave64_programs_supported()) {
(Ok(_), Ok(true)) => {}
(adapter, _) => return runner::skip_test(if adapter.is_err() { "no GPU" } else { "no wave64" }),
}
let code = program(&[
("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 0)]),
("V_MUL_LEGACY_F32", "ENC_VOP2", &[("VDST", 4), ("SRC0", V), ("VSRC1", 1)]),
("V_ADD_F32", "ENC_VOP2", &[("VDST", 4), ("SRC0", V + 4), ("VSRC1", 2)]),
("V_FMA_F32", "ENC_VOP3", &[("VDST", 5), ("SRC0", V + 4), ("SRC1", V + 3), ("SRC2", V + 4)]),
("V_MUL_F32", "ENC_VOP2", &[("VDST", 4), ("SRC0", V + 5), ("VSRC1", 4)]),
("V_CMP_GT_F32", "ENC_VOPC", &[("SRC0", V + 4), ("VSRC1", 5)]),
("V_CNDMASK_B32", "ENC_VOP2", &[("VDST", 6), ("SRC0", V + 4), ("VSRC1", 5)]),
("V_READLANE_B32", "ENC_VOP3", &[("VDST", 20), ("SRC0", V + 4), ("SRC1", 131)]),
("V_READLANE_B32", "ENC_VOP3", &[("VDST", 21), ("SRC0", V + 6), ("SRC1", 137)]),
("S_AND_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 2)]),
("V_SUB_F32", "ENC_VOP2", &[("VDST", 4), ("SRC0", V + 4), ("VSRC1", 6)]),
("V_MAX_F32", "ENC_VOP2", &[("VDST", 7), ("SRC0", V + 4), ("VSRC1", 0)]),
("V_MOV_B32", "ENC_VOP1", &[("VDST", 8), ("SRC0", V + 4)]),
("V_MOV_B32", "VOP1_VOP_DPP16", &[("VDST", 9), ("SRC0", 0xFA), ("VSRC0", 4), ("DPP_CTRL", 0x111), ("ROW_MASK", 0xF), ("BANK_MASK", 0xF)]),
("V_READLANE_B32", "ENC_VOP3", &[("VDST", 22), ("SRC0", V + 4), ("SRC1", 133)]),
("V_MUL_LEGACY_F32", "ENC_VOP2", &[("VDST", 6), ("SRC0", V + 6), ("VSRC1", 6)]),
("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 10)]),
("V_ADD_F32", "ENC_VOP2", &[("VDST", 10), ("SRC0", V + 4), ("VSRC1", 6)]),
("V_MUL_LEGACY_F32", "ENC_VOP2", &[("VDST", 11), ("SRC0", V + 7), ("VSRC1", 8)]),
]);
const EDGE: [u32; 12] = [0x7FC0_1234, 0, 0x8000_0000, 0x7F80_0000, 0xFF80_0000, 1, 0x807F_FFFF, 0x3FC0_0000, 0xC000_0000, 0x3F80_0000, 0x4120_0000, 0xBE80_0000];
let mut state = KernelState::default();
let mut random = 0x9E37_79B9_7F4A_7C15u64;
for (lane, regs) in state.vgpr.iter_mut().enumerate() {
for word in regs.iter_mut().take(4) {
random ^= random << 13;
random ^= random >> 7;
random ^= random << 17;
*word = if random % 3 == 0 { random as u32 } else { EDGE[(random >> 8) as usize % EDGE.len()] };
}
for (reg, word) in regs.iter_mut().enumerate().skip(4).take(8) {
*word = 0xA000_0000 | (lane as u32) << 8 | reg as u32;
}
}
(state.sgpr[0], state.sgpr[1]) = (0xF0F0_5A3C, 0x0FF0_C3A5);
(state.sgpr[2], state.sgpr[3]) = (0x3333_FF0F, 0xFFFF_3333);

let mut ran = 0;
for (wave64, split) in [(false, false), (true, true), (true, false)] {
if wave64 && !split && runner::wave64_supported() != Ok(true) {
continue;
}
let options = KernelOptions { wave64, split, mem_windows: 1, sampler_base: 0 };
let (before, after) = (translate_with_fold(&code, options, false), translate_with_fold(&code, options, true));
assert!(after.len() < before.len(), "wave64 {wave64} split {split}: nothing folded ({} -> {} B)", before.len(), after.len());
let a = runner::run(&before, &state, &[]).expect("GPU run before fold");
let b = runner::run(&after, &state, &[]).expect("GPU run after fold");
let lanes = if wave64 { 64 } else { 32 };
for lane in 0..lanes {
assert_eq!(a.vgpr[lane][..12], b.vgpr[lane][..12], "wave64 {wave64} split {split}: lane {lane}");
let active = (state.sgpr[lane / 32] >> (lane % 32)) & 1 != 0;
if !active {
for reg in [4, 5, 7, 8] {
assert_eq!(b.vgpr[lane][reg], state.vgpr[lane][reg], "wave64 {wave64} split {split}: inactive lane {lane} v{reg}");
}
}
}
assert_eq!(a.sgpr, b.sgpr, "wave64 {wave64} split {split}: SGPRs");
assert_eq!(a.scc, b.scc, "wave64 {wave64} split {split}: SCC");
ran += 1;
}
assert!(ran >= 2);
}