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
19 changes: 19 additions & 0 deletions crates/xcl/src/gpu/recomp/emit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,12 @@ pub(super) struct Em {
/// LDS arrival barrier (`xcl_s_barrier`) so RDNA2 early `s_endpgm`, `LOOP_GUARD` exits,
/// or split-wave64 desyncs cannot permanently hang an NVIDIA SM at `bar.sync`.
safe_barrier: bool,
/// seed pc → the `WaveActive*` intrinsic suffix ("Min"/"Max"/"BitOr") for a recognised
/// whole-wave reduction (`recognize_whole_wave_reductions`)
pub reductions: BTreeMap<u64, &'static str>,
/// pcs of the reduction's DPP / permlane / readlane steps, suppressed in favour of the
/// wave intrinsic (their `WaveReadLaneAt` reads unlaunched lanes as 0, not the identity)
pub skip: BTreeSet<u64>,
}

/// Instructions without an effect in this execution model.
Expand Down Expand Up @@ -593,6 +599,8 @@ impl Em {
dynamic_f16_rm: false,
track_frexp_denorm: false,
safe_barrier: false,
reductions: BTreeMap::new(),
skip: BTreeSet::new(),
}
}

Expand Down Expand Up @@ -981,6 +989,10 @@ impl Em {
let mut flow = Flow::Next;
let mut i = 0;
while i < block.len() {
if self.skip.contains(&block[i].pc) {
i += 1;
continue;
}
if self.x64() {
if let Some(consumed) = self.try_emit_x64_reduction_tail(&block[i..]) {
i += consumed;
Expand Down Expand Up @@ -4003,6 +4015,13 @@ impl Em {
// the value straight into the write (a named temporary is one more local per
// instruction – tens of thousands on big programs at -O0)
self.vwrite(d, &dst, &format!("({res})"));
// recognised whole-wave reduction: reduce the seed over the launched lanes with the
// wave intrinsic (the DPP / permlane / readlane steps are skipped; they read lanes the
// rasterizer did not launch as 0 instead of the identity, which breaks `min`).
if let (Some(op), Dst::V(n)) = (self.reductions.get(&d.pc).copied(), &dst) {
let v = self.vreg(*n);
self.line(&format!("{v} = WaveActive{op}({v});"));
}
Ok(())
}

Expand Down
153 changes: 153 additions & 0 deletions crates/xcl/src/gpu/recomp/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1374,6 +1374,156 @@ pub(crate) fn constant_samplers(insts: &[Decoded], leaders: &BTreeSet<u64>) -> B
out
}

/// The `WaveActive*` suffix for a reduction op, or None if the instruction is not one.
fn reduction_op(name: &str) -> Option<&'static str> {
match name {
"V_MIN_U32" => Some("Min"),
"V_MAX_U32" => Some("Max"),
"V_OR_B32" => Some("BitOr"),
_ => None,
}
}

/// Recognise the whole-wave reduction idiom a `v_min_u32` / `v_max_u32` / `v_or_b32` reduction
/// lowers to — seed `v_cndmask_b32` (identity for the lanes outside the mask), three DPP8 xor
/// steps, a DPP16 row_mirror, `v_permlanex16`, a `v_readlane` of lane 32 and a final
/// `v_readlane` of lane 0. Returns `(seed pc → WaveActive suffix, pcs to suppress)`. Those
/// steps read lanes the rasterizer did not launch as 0 instead of the identity, so a `min`
/// (identity -1) would come back 0 in a partial wave; emitting `WaveActive*` over the seed's
/// launched lanes is exact.
fn recognize_whole_wave_reductions(insts: &[Decoded]) -> (BTreeMap<u64, &'static str>, BTreeSet<u64>) {
let mut reductions = BTreeMap::new();
let mut skip = BTreeSet::new();
let n = insts.len();
'outer: for i in 0..n {
let seed = &insts[i];
if seed.inst.name != "V_CNDMASK_B32" {
continue;
}
let (sr, sw) = rdna2::vgpr_uses(seed);
// the seed reads exactly one VGPR (the value): its identity is a constant, not a register
if sw.len() != 1 || sr.len() != 1 {
continue;
}
let s = sw[0];
if i + 9 >= n {
continue;
}
let mut op: Option<&'static str> = None;
// 3 × DPP8 op, each an xor step (1, 2, 4)
const XOR: [[u64; 8]; 3] = [[1, 0, 3, 2, 5, 4, 7, 6], [2, 3, 0, 1, 6, 7, 4, 5], [4, 5, 6, 7, 0, 1, 2, 3]];
for k in 1..=3 {
let d = &insts[i + k];
let o = reduction_op(d.inst.name);
if o.is_none() || d.variant != rdna2::Variant::Dpp8 {
continue 'outer;
}
if let Some(prev) = op {
if prev != o.unwrap() {
continue 'outer;
}
}
op = o;
let Some(e) = emit::ext_encoding(d) else { continue 'outer };
for (idx, want) in XOR[k - 1].iter().enumerate() {
if rdna2::field_value(e, &d.words, &format!("LANE_SEL_{idx}")) != Some(*want) {
continue 'outer;
}
}
let (r, w) = rdna2::vgpr_uses(d);
if w != vec![s] || !r.contains(&s) {
continue 'outer;
}
}
// DPP16 op
{
let d = &insts[i + 4];
let o = reduction_op(d.inst.name);
if o.is_none() || o.unwrap() != op.unwrap() || d.variant != rdna2::Variant::Dpp16 {
continue 'outer;
}
if emit::ext_encoding(d).and_then(|e| rdna2::field_value(e, &d.words, "DPP_CTRL")) != Some(0x140) {
continue 'outer;
}
let (r, w) = rdna2::vgpr_uses(d);
if w != vec![s] || !r.contains(&s) {
continue 'outer;
}
}
// v_permlanex16
{
let d = &insts[i + 5];
if d.inst.name != "V_PERMLANEX16_B32" {
continue 'outer;
}
let (r, _w) = rdna2::vgpr_uses(d);
if !r.contains(&s) {
continue 'outer;
}
}
// op: s = op(s, permlane result)
{
let d = &insts[i + 6];
let o = reduction_op(d.inst.name);
if o.is_none() || o.unwrap() != op.unwrap() {
continue 'outer;
}
let (r, w) = rdna2::vgpr_uses(d);
if w != vec![s] || !r.contains(&s) {
continue 'outer;
}
}
// v_readlane lane 32 (its VDST is not a tracked VGPR write, so only check the read)
{
let d = &insts[i + 7];
if d.inst.name != "V_READLANE_B32" {
continue 'outer;
}
if rdna2::field_value(d.enc, &d.words, "SRC1").map(|v| v & 63) != Some(32) {
continue 'outer;
}
let (r, _w) = rdna2::vgpr_uses(d);
if !r.contains(&s) {
continue 'outer;
}
}
// op: s = op(s, lane32)
{
let d = &insts[i + 8];
let o = reduction_op(d.inst.name);
if o.is_none() || o.unwrap() != op.unwrap() {
continue 'outer;
}
let (r, w) = rdna2::vgpr_uses(d);
if w != vec![s] || !r.contains(&s) {
continue 'outer;
}
}
// final v_readlane lane 0 (kept: reads the already-reduced seed)
{
let d = &insts[i + 9];
if d.inst.name != "V_READLANE_B32" {
continue 'outer;
}
if rdna2::field_value(d.enc, &d.words, "SRC1").map(|v| v & 63) != Some(0) {
continue 'outer;
}
let (r, _w) = rdna2::vgpr_uses(d);
if !r.contains(&s) {
continue 'outer;
}
}
reductions.insert(seed.pc, op.unwrap());
// Suppress only the within-half reduction (3 × DPP8 + DPP16 + v_permlanex16 + op);
// the `v_readlane` lane 32 + op + `v_readlane` lane 0 that combine the two 32-lane
// halves of a wave64 are kept (they use the upper-lane / exchange handling).
for k in 1..=6 {
skip.insert(insts[i + k].pc);
}
}
(reductions, skip)
}

pub fn translate(code: &[u8], opt: &Options) -> Result<Translation, String> {
let program = code;
let normalized;
Expand Down Expand Up @@ -1421,6 +1571,9 @@ pub fn translate(code: &[u8], opt: &Options) -> Result<Translation, String> {
}
}
let mut em = emit::Em::new(opt.clone());
let (reductions, skip) = recognize_whole_wave_reductions(&insts);
em.reductions = reductions;
em.skip = skip;
em.configure_round_modes(&insts, branches == 0);
em.static_ss = constant_samplers(&insts, &leaders);
// split wave64: masks only read lane by lane skip the halves' exchange (geometry mode
Expand Down
139 changes: 139 additions & 0 deletions crates/xcl/src/gpu/recomp/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2484,6 +2484,145 @@ fn gpu_wave64_ps_whole_wave_reductions() {
}
}

/// The whole-wave reduction the wave64 PS reduction tests use: the identity for the lanes
/// outside the mask, then DPP8 xor 1/2/4, DPP16 row_mirror, `v_permlanex16`, and the two
/// `v_readlane` steps that join the 32-lane halves and read the total.
fn whole_wave_reduce(op: &str, identity: u64, out: u64) -> Vec<u8> {
let mut c = vec![
ins("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 30), ("SSRC0", 193)], None),
ins("S_AND_B64", "ENC_SOP2", &[("SDST", 10), ("SSRC0", 18), ("SSRC1", 30)], None),
ins("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", identity), ("SRC1", V + 13), ("SRC2", 10)], None),
];
let names = ["LANE_SEL_0", "LANE_SEL_1", "LANE_SEL_2", "LANE_SEL_3", "LANE_SEL_4", "LANE_SEL_5", "LANE_SEL_6", "LANE_SEL_7"];
for sel in [[1u64, 0, 3, 2, 5, 4, 7, 6], [2, 3, 0, 1, 6, 7, 4, 5], [4, 5, 6, 7, 0, 1, 2, 3]] {
let mut f = vec![("VDST", 6u64), ("SRC0", 0xE9), ("VSRC0", 6), ("VSRC1", 6)];
f.extend(names.iter().copied().zip(sel));
c.push(ins(op, "VOP2_VOP_DPP8", &f, None));
}
c.extend([
ins(op, "VOP2_VOP_DPP16", &[("VDST", 6), ("SRC0", 0xFA), ("VSRC0", 6), ("VSRC1", 6), ("DPP_CTRL", 0x140), ("ROW_MASK", 0xF), ("BANK_MASK", 0xF)], None),
ins("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", 7), ("SRC0", V + 6), ("SRC1", 128), ("SRC2", 128)], None),
ins(op, "ENC_VOP2", &[("VDST", 6), ("SRC0", V + 7), ("VSRC1", 6)], None),
ins("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 6), ("SRC1", 128 + 32)], None),
ins(op, "ENC_VOP2", &[("VDST", 6), ("SRC0", 10), ("VSRC1", 6)], None),
ins("V_READLANE_B32", "ENC_VOP3", &[("VDST", out), ("SRC0", V + 6), ("SRC1", 128)], None),
ins("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 30)], None),
]);
c.concat()
}

/// The reduction with tunable selectors/lanes/identity, for the recognition negative tests.
fn reduction_variant(
op: &str,
identity: u64,
out: u64,
dpp8: [[u64; 8]; 3],
dpp16_ctrl: u64,
rl32: u64,
rl0: u64,
) -> Vec<u8> {
let mut c = vec![
ins("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 30), ("SSRC0", 193)], None),
ins("S_AND_B64", "ENC_SOP2", &[("SDST", 10), ("SSRC0", 18), ("SSRC1", 30)], None),
ins("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", identity), ("SRC1", V + 13), ("SRC2", 10)], None),
];
let names = ["LANE_SEL_0", "LANE_SEL_1", "LANE_SEL_2", "LANE_SEL_3", "LANE_SEL_4", "LANE_SEL_5", "LANE_SEL_6", "LANE_SEL_7"];
for sel in dpp8 {
let mut f = vec![("VDST", 6u64), ("SRC0", 0xE9), ("VSRC0", 6), ("VSRC1", 6)];
f.extend(names.iter().copied().zip(sel));
c.push(ins(op, "VOP2_VOP_DPP8", &f, None));
}
c.extend([
ins(op, "VOP2_VOP_DPP16", &[("VDST", 6), ("SRC0", 0xFA), ("VSRC0", 6), ("VSRC1", 6), ("DPP_CTRL", dpp16_ctrl), ("ROW_MASK", 0xF), ("BANK_MASK", 0xF)], None),
ins("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", 7), ("SRC0", V + 6), ("SRC1", 128), ("SRC2", 128)], None),
ins(op, "ENC_VOP2", &[("VDST", 6), ("SRC0", V + 7), ("VSRC1", 6)], None),
ins("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 6), ("SRC1", rl32)], None),
ins(op, "ENC_VOP2", &[("VDST", 6), ("SRC0", 10), ("VSRC1", 6)], None),
ins("V_READLANE_B32", "ENC_VOP3", &[("VDST", out), ("SRC0", V + 6), ("SRC1", rl0)], None),
ins("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 30)], None),
]);
c.concat()
}

/// Decode raw instruction bytes into `Vec<Decoded>` (the way `translate` does).
fn decode_insts(code: &[u8]) -> Vec<crate::gpu::rdna2::Decoded> {
let mut insts = Vec::new();
let mut off = 0usize;
while off + 4 <= code.len() {
let d = crate::gpu::rdna2::decode(&code[off..], off as u64).unwrap();
off += d.len;
insts.push(d);
}
insts
}

/// Negative tests for `recognize_whole_wave_reductions`: a canonical reduction is recognised
/// (once), and any variant that changes the DPP8 selectors, the DPP16 control, a `v_readlane`
/// lane, or the seed identity (making it a register) is rejected.
#[test]
fn recognize_rejects_wrong_reduction_variants() {
const XOR: [[u64; 8]; 3] = [[1, 0, 3, 2, 5, 4, 7, 6], [2, 3, 0, 1, 6, 7, 4, 5], [4, 5, 6, 7, 0, 1, 2, 3]];
let count = |code: Vec<u8>| super::recognize_whole_wave_reductions(&decode_insts(&code)).0.len();

// canonical min reduction
assert_eq!(count(reduction_variant("V_MIN_U32", 193, 40, XOR, 0x140, 128 + 32, 128)), 1);

// wrong DPP8 selector (xor3 instead of xor1 in the first step)
let xor3 = [[3u64, 2, 1, 0, 7, 6, 5, 4], XOR[1], XOR[2]];
assert_eq!(count(reduction_variant("V_MIN_U32", 193, 40, xor3, 0x140, 128 + 32, 128)), 0);

// wrong DPP16 control (row_half_mirror instead of row_mirror)
assert_eq!(count(reduction_variant("V_MIN_U32", 193, 40, XOR, 0x141, 128 + 32, 128)), 0);

// wrong v_readlane lane 32 (16 instead of 32)
assert_eq!(count(reduction_variant("V_MIN_U32", 193, 40, XOR, 0x140, 128 + 16, 128)), 0);

// wrong final v_readlane lane 0 (1 instead of 0)
assert_eq!(count(reduction_variant("V_MIN_U32", 193, 40, XOR, 0x140, 128 + 32, 128 + 1)), 0);

// wrong seed identity (a VGPR instead of a constant)
assert_eq!(count(reduction_variant("V_MIN_U32", V + 7, 40, XOR, 0x140, 128 + 32, 128)), 0);
}

/// A wave64 PS that runs the `min` reduction over the odd pixels of a PARTIAL wave: the
/// rasterizer leaves most lanes of the wave unlaunched, and the reduction's DPP / permlane /
/// readlane steps read those lanes as 0 instead of the min identity (-1), so the min comes
/// back 0 instead of the true minimum. Drawn as a small triangle (three quads) that leaves
/// lanes 12..31 and the whole upper half unlaunched.
#[test]
fn gpu_wave64_ps_partial_wave_min() {
if !gpu_ready() {
return;
}
let code = program_of(&[
// v12 = pixel number y·16 + x, v13 = v12 + 1, s[18:19] = the odd pixels.
ins("V_CVT_U32_F32", "ENC_VOP1", &[("VDST", 10), ("SRC0", V + 2)], None),
ins("V_CVT_U32_F32", "ENC_VOP1", &[("VDST", 11), ("SRC0", V + 3)], None),
ins("V_LSHL_ADD_U32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 11), ("SRC1", 128 + 4), ("SRC2", V + 10)], None),
ins("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 13), ("SRC0", 129), ("VSRC1", 12)], None),
ins("V_AND_B32", "ENC_VOP2", &[("VDST", 14), ("SRC0", 129), ("VSRC1", 12)], None),
ins("V_CMP_NE_U32", "ENC_VOPC", &[("SRC0", 128), ("VSRC1", 14)], None),
ins("S_MOV_B64", "ENC_SOP1", &[("SDST", 18), ("SSRC0", 106)], None),
whole_wave_reduce("V_MIN_U32", 193, 40),
// v20 = the min as float, v23 = 1.0f (a covered-pixel marker).
ins("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 20), ("SRC0", 40)], None),
ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 23), ("SRC0", 242)], None),
ins("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 0xF), ("VSRC0", 20), ("VSRC1", 20), ("VSRC2", 20), ("VSRC3", 23), ("DONE", 1), ("VM", 1)], None),
]);
// A small triangle: pixels (0,0),(1,0),(2,0),(0,1),(1,1),(0,2) – three quads. The odd
// pixels are (1,0) and (1,1) with v13 = 2 and 18, so the true minimum is 2.
let px = draw_console(None, Some(&code), &[[0.0, 0.0], [3.2, 0.0], [0.0, 3.2]]);
let covered: Vec<(usize, &[f32; 4])> = px.iter().enumerate().filter(|(_, p)| p[3] == 1.0).collect();
println!("gpu_wave64_ps_partial_wave_min: {} covered pixels", covered.len());
for (i, p) in &covered {
println!(" pixel {i}: min={} (want 2.0)", p[0]);
}
assert!(!covered.is_empty(), "the small triangle should cover pixels");
for (i, p) in covered {
assert_eq!(p[0], 2.0, "pixel {i}: min over the odd pixels of a partial wave");
}
}

/// SGPR spill slots in lanes 0..47 of a VGPR (`spill_slots`) in a wave64 PS: slots ≥ 32 do
/// not exist in a 32-lane wave, and a slot in a lane that was not launched is lost in a
/// partial wave (a primitive's edge). Drawn over the whole target and as a 6-pixel triangle.
Expand Down
Loading