From d7ced02e660191c1574a17b05a3ebf1608e62118 Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Tue, 24 Nov 2026 18:41:30 -0500 Subject: [PATCH 1/4] Recompiler: cover SCC from complemented SAVEEXEC forms ANDN1 and ORN1 only occur in EXEC forms, which record lane SCC before the plain bitwise path. Remove the unreachable ANDN1 plain case and exercise both real encodings across an EXEC restore. --- crates/xcl/src/gpu/recomp/lane_masks.rs | 3 ++- crates/xcl/src/gpu/recomp/lower.rs | 21 +++++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/gpu/recomp/lane_masks.rs b/crates/xcl/src/gpu/recomp/lane_masks.rs index 44b1e8a81..d1f22f9df 100644 --- a/crates/xcl/src/gpu/recomp/lane_masks.rs +++ b/crates/xcl/src/gpu/recomp/lane_masks.rs @@ -557,7 +557,8 @@ impl<'a> Lanes<'a> { // A bitwise scalar instruction can mix a tracked mask and an SGPR // holding a number. The lowering extracts each lane's bit of that // number. Its unknown bits must not turn the result's SCC uniform. - if matches!(op, "AND" | "OR" | "XOR" | "ANDN2" | "ORN2" | "ANDN1" | "NAND" | "NOR" | "XNOR") + // ANDN1 and ORN1 occur only in the EXEC forms handled above. + if matches!(op, "AND" | "OR" | "XOR" | "ANDN2" | "ORN2" | "NAND" | "NOR" | "XNOR") && (sd == Some(EXEC) || (s0 < 128 && a.is_some()) || (s1 < 128 && b.is_some())) { a = Some(self.need(st, d, s0, block)?); diff --git a/crates/xcl/src/gpu/recomp/lower.rs b/crates/xcl/src/gpu/recomp/lower.rs index ca82cf429..de79a6220 100644 --- a/crates/xcl/src/gpu/recomp/lower.rs +++ b/crates/xcl/src/gpu/recomp/lower.rs @@ -3191,6 +3191,27 @@ pub(crate) mod tests { out } + #[test] + fn complemented_saveexec_replaces_the_previous_uniform_scc() { + // ANDN1 with full EXEC and ORN1 with empty EXEC both produce ~s8. + // Restoring EXEC with MOV leaves that SCC live for all lanes. + const FULL: I = ("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 193)]); + const EMPTY: I = ("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 128)]); + for (op, exec) in [("S_ANDN1_SAVEEXEC_B32", FULL), ("S_ORN1_SAVEEXEC_B32", EMPTY)] { + let insts = decode(&[ + ("S_CMP_EQ_U32", "ENC_SOPC", &[("SSRC0", 128), ("SSRC1", 128)]), + exec, + (op, "ENC_SOP1", &[("SDST", 4), ("SSRC0", 8)]), + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 193)]), + ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 1)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 135)]), + ENDPGM, + ]); + let err = lower_kernel(&insts, false, Interp::default()).err().expect("varying mask"); + assert!(err.contains("any lane of a mask"), "{op}: {err}"); + } + } + /// A branch or a scalar select on whether any lane of a mask is set decides for the whole /// wave on the console: with lanes in EXEC that lack the bit (VCC = lanes 0–15, EXEC = all), /// each lane deciding by its own bit would differ in lanes 16–31, so the program is refused From 0fea4211920d7ca75265caba33e9c8f15f3ba72b Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:41:28 -0500 Subject: [PATCH 2/4] Recompiler: keep scalar state across proven per-lane paths A lane can use a dominating definition while it remains in every loop containing the write. A native wave32 loop header can also read its sole latch's definition on the back edge if no enclosing loop can carry an earlier value to the entry. Preserve the final zero SCC and mask on the sole empty-EXEC exit of a WREXEC self-loop. Check the reads in nested arms, lanes leaving a loop at different iterations and a read of the counter after exit. Compare both shrinking-loop kernels with HLSL on the GPU. --- README.md | 2 + crates/xcl/src/gpu/recomp/lane_masks.rs | 24 +++- crates/xcl/src/gpu/recomp/lower.rs | 146 +++++++++++++++++++++++- crates/xcl/src/gpu/recomp/lower_dxil.rs | 30 +++++ 4 files changed, 198 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 19fc5755f..d060fce33 100644 --- a/README.md +++ b/README.md @@ -153,6 +153,8 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder `XCL_PSO_TRACE=1` logs every driver compile. A huge compute program the driver refuses is logged with the driver's verdict (`the driver refused the compute PSO of record HASH … with 0x…`): its dispatches are skipped. +- With `XCL_DIRECT_DXIL=1` and `XCL_PER_LANE=1`, eligible wave32 compute loops can use + per-lane control flow even when the next iteration reads the preceding iteration's scalar counter. - With `XCL_DRED=1`, a D3D12 device removal logs GPU breadcrumbs in `xcl.log`. XCL examines up to 4,096 command lists and reports up to 64 unfinished lists, starting with those on which the GPU completed at least one operation. diff --git a/crates/xcl/src/gpu/recomp/lane_masks.rs b/crates/xcl/src/gpu/recomp/lane_masks.rs index d1f22f9df..445999314 100644 --- a/crates/xcl/src/gpu/recomp/lane_masks.rs +++ b/crates/xcl/src/gpu/recomp/lane_masks.rs @@ -275,6 +275,25 @@ pub struct Summary { /// blocks the entry reaches: every block after its forward predecessors) pub blocks: Vec, pub order: Vec, + /// each block's immediate dominator (the entry's is itself; `usize::MAX`: not reached), and + /// for each block: Some(blocks of its loop) when it heads one + pub idom: Vec, + pub body: Vec>>, +} + +impl Summary { + /// Whether block a dominates block b (b reached from the entry). + pub fn dominates(&self, a: usize, mut b: usize) -> bool { + loop { + if b == a { + return true; + } + if b == 0 || self.idom[b] == usize::MAX { + return false; + } + b = self.idom[b]; + } + } } /// Whether `d` reads SCC as a non-branch input (either implicitly via `OPR_SSRC_SPECIAL_SCC` @@ -313,6 +332,7 @@ struct Lanes<'a> { preds: Vec>, /// reverse postorder, and for each block: Some(blocks of its loop) when it heads one order: Vec, + idom: Vec, body: Vec>>, /// per instruction: SGPRs it overwrites (`x64_masks::uses`), SGPRs it may change, whether /// it writes SCC @@ -448,7 +468,7 @@ impl<'a> Lanes<'a> { (written, kill, d.ienc.operands.iter().any(|o| o.output && o.ty == "OPR_SSRC_SPECIAL_SCC")) }) .collect(); - Ok(Lanes { insts, wave64, launch, wave_branches: false, bdd: Bdd::new(), atoms: HashMap::new(), born: Vec::new(), blocks, succ, preds, order, body, effects }) + Ok(Lanes { insts, wave64, launch, wave_branches: false, bdd: Bdd::new(), atoms: HashMap::new(), born: Vec::new(), blocks, succ, preds, order, idom, body, effects }) } fn atom(&mut self, a: Atom, block: usize) -> R { @@ -938,6 +958,8 @@ impl<'a> Lanes<'a> { }) .collect(); sum.order = self.order.clone(); + sum.idom = self.idom.clone(); + sum.body = self.body.clone(); Ok(sum) } } diff --git a/crates/xcl/src/gpu/recomp/lower.rs b/crates/xcl/src/gpu/recomp/lower.rs index de79a6220..048af33b2 100644 --- a/crates/xcl/src/gpu/recomp/lower.rs +++ b/crates/xcl/src/gpu/recomp/lower.rs @@ -176,6 +176,9 @@ struct Lower<'a, I: Ir> { /// inside a coalesced guarded run's own block: only lanes with EXEC set enter, so writes /// need no per-instruction guard unguarded: bool, + /// per IR block of the program: its analysis block, and whether it is a coalesced run's + /// block (only the lanes with their EXEC bit enter it) + place: Vec>, /// the IR block each mask bit was written in, and the mask bits read (block, value) def_block: std::collections::HashMap, lane_uses: Vec<(usize, I::V)>, @@ -1033,7 +1036,9 @@ impl<'a, I: Ir> Lower<'a, I> { /// Whether a lane reading mask bit v in block c may see its own stale bit: v (or a phi /// operand reaching it) was written in another block that not every lane passed through. /// The hardware's whole-wave write left the absent lanes' bits 0 there; this lane kept its - /// own older one. EXEC is not concerned: an absent lane's bit is 0 in both. + /// own older one. EXEC is not concerned: an absent lane's bit is 0 in both. Unless that + /// block dominates c and c is in every loop it is in: then every lane reading in c passed + /// the write, in the same pass as the wave's last one. fn stale(&self, c: usize, v: I::V) -> bool { let mut seen = HashSet::new(); let mut work = vec![v]; @@ -1046,7 +1051,7 @@ impl<'a, I: Ir> Lower<'a, I> { Some(ops) => work.extend_from_slice(ops), None => { if let Some(&b) = self.def_block.get(&v) { - if self.def_owner[b] != self.use_owner[c] && self.partial[b] { + if self.def_owner[b] != self.use_owner[c] && self.partial[b] && !self.passed(b, c) { return true; } } @@ -1056,6 +1061,32 @@ impl<'a, I: Ir> Lower<'a, I> { false } + /// Whether a read in c can use a definition from w without seeing an older iteration + /// or a value from a lane that skipped w. Kernel ABI stores have no program block. + fn passed(&self, w: usize, c: usize) -> bool { + let (Some((bw, run)), Some((bc, _))) = (self.place[w], self.place[c]) else { + return false; + }; + if run { + // a coalesced run's block: only the lanes with their EXEC bit pass it + return false; + } + let sum = self.sum; + if sum.dominates(bw, bc) { + return sum.body.iter().flatten().all(|inside| !inside[bw] || inside[bc]); + } + // At the header's first execution the latch has never run. Every lane that + // returns to the header passed the sole latch on its preceding iteration. + // An enclosing loop could carry a value of this latch into another entry, + // and a nested loop at the write could leave an earlier iteration's value. + if self.wave64 || self.graphics { + return false; + } + let Some(body) = &sum.body[bc] else { return false }; + body[bw] && sum.blocks[bc].preds.iter().filter(|&&p| body[p]).all(|&p| p == bw) + && sum.body.iter().enumerate().all(|(h, other)| h == bc || !other.as_ref().is_some_and(|inside| inside[bw])) + } + /// Whether v is (or is a phi reaching) `marker`. fn reaches(&self, v: I::V, marker: I::V) -> bool { let mut seen = HashSet::new(); @@ -1128,6 +1159,22 @@ fn partial_blocks(sum: &Summary) -> Vec { partial } +/// The WREXEC destination when wave32 block b can only be reached by exhausting a +/// self-loop's EXEC. Both the mask it copied and SCC are then zero for the console +/// wave, including lanes that left the loop on an earlier iteration. +fn empty_loop_wrexec(sum: &Summary, insts: &[Decoded], b: usize) -> Option { + let [pred] = sum.blocks[b].preds[..] else { return None }; + let block = &sum.blocks[pred]; + if pred == b || block.succ != [(pred, Edge::Taken), (b, Edge::NotTaken)] { + return None; + } + let [.., write, branch] = &insts[block.insts.clone()] else { return None }; + if branch.inst.name != "S_CBRANCH_EXECNZ" || !write.inst.name.ends_with("_WREXEC_B32") { + return None; + } + rdna2::field_value(write.enc, &write.words, "SDST").map(|r| r as u8) +} + /// Lowers a kernel-mode program (far jumps resolved) into `ir`, which gets it complete, with /// the mask registers whose value at the end may differ from the console's: written in a block /// some lanes skipped, so those lanes still hold their own older bits (`stale`). Nothing reads @@ -1199,8 +1246,10 @@ fn lower_with(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I, s let mut partial = vec![false; count]; let mut def_owner: Vec = (0..count).collect(); let mut use_owner: Vec = (0..count).collect(); + let mut place = vec![None; count]; for (b, p) in partial_blocks(&sum).into_iter().enumerate() { partial[blk(b)] = p; + place[blk(b)] = Some((b, false)); for &(_, s, c) in &splits[b] { partial[s] = true; partial[c] = p; @@ -1208,6 +1257,8 @@ fn lower_with(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I, s use_owner[s] = blk(b); def_owner[c] = blk(b); use_owner[c] = blk(b); + place[s] = Some((b, true)); + place[c] = Some((b, false)); } } let ends: Vec = sum.order.iter().copied().filter(|&b| sum.blocks[b].succ.is_empty()).collect(); @@ -1260,6 +1311,7 @@ fn lower_with(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I, s def_owner, use_owner, unguarded: false, + place, def_block: std::collections::HashMap::new(), lane_uses: Vec::new(), dpp_src: None, @@ -1409,6 +1461,15 @@ fn lower_with(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I, s if !sealed[ib] { sealed[ib] = seal_ready(&mut l, &done, ib); } + if !graphics && !wave64 { + if let Some(r) = empty_loop_wrexec(&sum, insts, b) { + let zero = l.ir.boolean(false); + l.write_scc(ib, zero); + if r != 125 { + l.write_bit(ib, r, zero); + } + } + } if b == 0 && !pixel { // the analysis takes the lanes that start the program as its EXEC (a PS keeps the // launch EXEC from its start: there the analysis does not know it) @@ -2214,6 +2275,25 @@ pub(crate) mod tests { ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 129), ("VSRC1", 1)]), ENDPGM, ]; + /// v_cmp_gt_u32 vcc, 16, v0; s_and_saveexec s0, vcc; s_cbranch_execz L; s_mov s4, 5; + /// v_cmp_gt_u32 vcc, 8, v0; s_and_saveexec s1, vcc; s_cbranch_execz M; v_mov v1, 7; + /// M: exec |= s1; v_cndmask v3, 0, v0, vcc; v_add v2, s4, v3; L: exec |= s0: s4, VCC and s1 + /// are written in the lanes below 16 and read by them past the inner if + pub(crate) const REGION_DIAMOND: &[I] = &[ + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 144), ("VSRC1", 0)]), + ("S_AND_SAVEEXEC_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]), + ("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", 8)]), + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 133)]), + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 136), ("VSRC1", 0)]), + ("S_AND_SAVEEXEC_B32", "ENC_SOP1", &[("SDST", 1), ("SSRC0", 106)]), + ("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", 1)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 135)]), + ("S_OR_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 1)]), + ("V_CNDMASK_B32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 128), ("VSRC1", 0)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 4), ("VSRC1", 3)]), + ("S_OR_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]), + ENDPGM, + ]; /// s_mov s0, exec; L: v_add v1, v1, 1; v_cmp_ge_u32 vcc, v1, v0; exec &= ~vcc; /// s_cbranch_execnz L; exec |= s0 → v1 = max(1, lane) pub(crate) const LEAVING_LOOP: &[I] = &[ @@ -2225,6 +2305,34 @@ pub(crate) mod tests { ("S_OR_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]), ENDPGM, ]; + // Each surviving lane records the scalar counter before the latch increments it. + pub(crate) const LATCH_COUNTER: &[I] = &[ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 126)]), + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 1), ("SSRC0", 128)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 1)]), + ("V_CMP_LT_U32", "ENC_VOPC", &[("SRC0", 1), ("VSRC1", 0)]), + ("S_AND_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 106)]), + ("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", 2)]), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 1), ("SSRC1", 129)]), + ("S_BRANCH", "ENC_SOPP", &[("SIMM16", 0xFFFA)]), + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 0)]), + ENDPGM, + ]; + // Save the remaining lanes in s4 and retire a different group each iteration. + // Once the wave exits, the scalar select reads the SCC of its last WREXEC. + pub(crate) const EMPTY_LOOP_SCC: &[I] = &[ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 126)]), + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 126)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 129), ("VSRC1", 1)]), + ("V_CMP_GE_U32", "ENC_VOPC", &[("SRC0", V + 1), ("VSRC1", 0)]), + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 106)]), + ("S_ANDN2_WREXEC_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 4)]), + ("S_CBRANCH_EXECNZ", "ENC_SOPP", &[("SIMM16", 0xFFFB)]), + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 0)]), + ("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 2), ("SSRC0", 135), ("SSRC1", 139)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 2)]), + ENDPGM, + ]; /// s1 = 0; L: s1 += 3; v1 += 1; s_cmp_lt_u32 s1, 12; s_cbranch_scc1 L pub(crate) const UNIFORM_LOOP: &[I] = &[ ("S_MOV_B32", "ENC_SOP1", &[("SDST", 1), ("SSRC0", 128)]), @@ -3498,6 +3606,38 @@ pub(crate) mod tests { assert_eq!((s[0], s[126]), (u32::MAX, u32::MAX), "saved and restored EXEC"); } + #[test] + fn a_value_written_in_a_lane_region_is_read_in_it_past_an_inner_if() { + // the writes dominate the reads and no loop is left between: accepted + let (s, v) = state(32); + let (_, v) = run(REGION_DIAMOND, false, &s, &v); + for (l, regs) in v.iter().enumerate() { + let (v1, v3) = if l < 8 { (7, l as u32) } else { (0, 0) }; + let want = if l < 16 { (v1, 5 + v3, v3) } else { (0, 0, 0) }; + assert_eq!((regs[1], regs[2], regs[3]), want, "lane {l}"); + } + // written in the loop the lanes leave one by one, read after it: refused + let mut lines = LEAVING_LOOP.to_vec(); + lines.insert(6, ("V_CNDMASK_B32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 128), ("VSRC1", 0)])); + let err = lower_kernel(&decode(&lines), false, Interp::default()).err().expect("refused"); + assert!(err.contains("some lanes were elsewhere"), "{err}"); + // written in the arm some lanes skip, read after the join: refused + let mut lines = SKIPPED_IF.to_vec(); + lines[2] = ("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", 2)]); + lines.insert(3, ("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 133)])); + lines.insert(6, ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 4), ("VSRC1", 1)])); + let err = lower_kernel(&decode(&lines), false, Interp::default()).err().expect("refused"); + assert!(err.contains("some lanes were elsewhere"), "{err}"); + } + + #[test] + fn the_latch_counter_can_still_be_stale_after_the_loop() { + let mut lines = LATCH_COUNTER.to_vec(); + lines.insert(lines.len() - 1, ("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 1)])); + let err = lower_kernel(&decode(&lines), false, Interp::default()).err().expect("refused"); + assert!(err.contains("some lanes were elsewhere"), "{err}"); + } + #[test] fn lanes_leave_a_loop_one_by_one() { let (s, v) = state(32); @@ -3657,7 +3797,7 @@ pub(crate) mod tests { runner::skip_test(if !gpu_waves() { "no GPU with 32-lane waves" } else { "no DXC" }); return; } - for (name, lines) in [("straight", STRAIGHT), ("skipped if", SKIPPED_IF), ("leaving loop", LEAVING_LOOP), ("uniform loop", UNIFORM_LOOP), ("memory", MEMORY)] { + for (name, lines) in [("straight", STRAIGHT), ("skipped if", SKIPPED_IF), ("region diamond", REGION_DIAMOND), ("leaving loop", LEAVING_LOOP), ("uniform loop", UNIFORM_LOOP), ("memory", MEMORY)] { let bytes: Vec = lines.iter().flat_map(|(n, e, f)| rdna2::encode(n, e, f, None).unwrap()).collect(); let (s, v) = state(32); let mut st = runner::KernelState::default(); diff --git a/crates/xcl/src/gpu/recomp/lower_dxil.rs b/crates/xcl/src/gpu/recomp/lower_dxil.rs index 2c200c788..8ad2c4f05 100644 --- a/crates/xcl/src/gpu/recomp/lower_dxil.rs +++ b/crates/xcl/src/gpu/recomp/lower_dxil.rs @@ -561,6 +561,7 @@ mod tests { for (name, lines) in [ ("straight", STRAIGHT), ("skipped if", SKIPPED_IF), + ("region diamond", REGION_DIAMOND), ("leaving loop", LEAVING_LOOP), ("uniform loop", UNIFORM_LOOP), ("memory", MEMORY), @@ -640,6 +641,35 @@ mod tests { } } + #[test] + fn shrinking_loops_agree_with_the_hlsl_path_on_the_gpu() { + if !gpu() { return; } + if dxc::location().is_err() { + runner::skip_test("no DXC"); + return; + } + let (s, v) = state(32); + let mut st = runner::KernelState::default(); + st.sgpr.copy_from_slice(&s); + for (lane, regs) in v.iter().enumerate() { + st.vgpr[lane][..regs.len()].copy_from_slice(regs); + } + for (lines, output) in [(LATCH_COUNTER, 1), (EMPTY_LOOP_SCC, 2)] { + let bytes: Vec = lines.iter().flat_map(encode_line).collect(); + let hlsl = translate(&bytes, &Options { wave64: false, ..Default::default() }).unwrap(); + assert!(hlsl.complete(), "{:?}", hlsl.unsupported_why); + let reference = dxc::compile(&hlsl.hlsl, "main", "cs_6_6", &[]).unwrap(); + let (dxil, _) = super::kernel(&decode(lines), false).unwrap(); + let reference = runner::run(&reference, &st, &[]).unwrap(); + let direct = runner::run(&dxil, &st, &[]).unwrap(); + for lane in 0..32 { + let expected = if output == 1 { lane as u32 } else { 11 }; + assert_eq!(reference.vgpr[lane][output], expected, "HLSL lane {lane}"); + assert_eq!(direct.vgpr[lane][output], expected, "per-lane DXIL lane {lane}"); + } + } + } + /// The integer programs of `lower`'s tests, as `f32_programs_on_the_gpu`. #[test] fn integer_programs_on_the_gpu() { From aa5c51e068bc5ee1cbcc45eae2d3244c1207afc1 Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Tue, 24 Nov 2026 18:42:16 -0500 Subject: [PATCH 3/4] Recompiler: stop dominance walks at the dominator-tree root Use the same root and unreachable checks when constructing loop bodies and proving stale reads. Test a nonzero entry. The existing two-entry cycle test exercises the irreducibility refusal before a summary reaches the lowering. --- crates/xcl/src/gpu/recomp/lane_masks.rs | 45 ++++++++++++++----------- crates/xcl/src/gpu/recomp/lower.rs | 1 + 2 files changed, 26 insertions(+), 20 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/lane_masks.rs b/crates/xcl/src/gpu/recomp/lane_masks.rs index 445999314..42f3f55e6 100644 --- a/crates/xcl/src/gpu/recomp/lane_masks.rs +++ b/crates/xcl/src/gpu/recomp/lane_masks.rs @@ -283,16 +283,8 @@ pub struct Summary { impl Summary { /// Whether block a dominates block b (b reached from the entry). - pub fn dominates(&self, a: usize, mut b: usize) -> bool { - loop { - if b == a { - return true; - } - if b == 0 || self.idom[b] == usize::MAX { - return false; - } - b = self.idom[b]; - } + pub fn dominates(&self, a: usize, b: usize) -> bool { + dominates(&self.idom, a, b) } } @@ -310,6 +302,19 @@ fn reads_scc(d: &Decoded) -> bool { .any(|f| rdna2::field_value(d.enc, &d.words, f) == Some(253)) } +fn dominates(idom: &[usize], a: usize, mut b: usize) -> bool { + while idom[b] != usize::MAX { + if b == a { + return true; + } + if idom[b] == b { + break; + } + b = idom[b]; + } + false +} + /// Executed with the lane's EXEC bit (VOPC and the lane reads / writes are mask producers). fn is_vector(d: &Decoded) -> bool { let n = d.inst.name; @@ -430,22 +435,13 @@ impl<'a> Lanes<'a> { break; } } - let dominates = |h: usize, mut b: usize| loop { - if b == h { - return true; - } - if b == 0 { - return false; - } - b = idom[b]; - }; let mut body: Vec>> = vec![None; n]; for &h in &order { for &(p, _) in &preds[h] { if rpo[p] < rpo[h] { continue; } - if !dominates(h, p) { + if !dominates(&idom, h, p) { return Err("irreducible control flow"); } let inside = body[h].get_or_insert_with(|| vec![false; n]); @@ -1117,6 +1113,15 @@ mod tests { assert_eq!((s.vector, s.guarded.len(), s.lane_branches), (2, 1, 1)); } + #[test] + fn dominance_ends_at_the_entry_even_when_it_is_not_block_zero() { + // 2 is the entry, 0 its child, 1 its grandchild. Block 3 is unreachable. + let idom = [2, 0, 2, usize::MAX]; + assert!(dominates(&idom, 2, 1)); + assert!(!dominates(&idom, 1, 0)); + assert!(!dominates(&idom, 3, 3)); + } + #[test] fn unsupported_control_flow_is_refused() { // a loop entered at two places diff --git a/crates/xcl/src/gpu/recomp/lower.rs b/crates/xcl/src/gpu/recomp/lower.rs index 048af33b2..6f86a342a 100644 --- a/crates/xcl/src/gpu/recomp/lower.rs +++ b/crates/xcl/src/gpu/recomp/lower.rs @@ -1072,6 +1072,7 @@ impl<'a, I: Ir> Lower<'a, I> { return false; } let sum = self.sum; + // Lanes::new rejects irreducible control flow before constructing the loop bodies. if sum.dominates(bw, bc) { return sum.body.iter().flatten().all(|inside| !inside[bw] || inside[bc]); } From c4f00e535803d4096d500b6bece1bec3c81ef26b Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:02:01 -0500 Subject: [PATCH 4/4] Recompiler: propagate proven empty loop exits into lane-mask analysis --- crates/xcl/src/gpu/recomp/lane_masks.rs | 41 +++++++++++++++++++--- crates/xcl/src/gpu/recomp/lower.rs | 46 ++++++++++++------------- 2 files changed, 58 insertions(+), 29 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/lane_masks.rs b/crates/xcl/src/gpu/recomp/lane_masks.rs index 42f3f55e6..f66e98408 100644 --- a/crates/xcl/src/gpu/recomp/lane_masks.rs +++ b/crates/xcl/src/gpu/recomp/lane_masks.rs @@ -256,6 +256,8 @@ pub struct Block { pub preds: Vec, /// it ends in a branch on a lane mask: each lane takes it on its own bit pub lane_branch: bool, + /// WREXEC destination to reset along with SCC on a proven empty wave32 loop exit. + pub(super) empty_loop_wrexec: Option, } /// What the analysis found in a program. @@ -819,13 +821,34 @@ impl<'a> Lanes<'a> { Ok((reach, st)) } - fn analyze(mut self) -> R { + /// WREXEC copied the final EXEC to its destination and set SCC to any(EXEC). + /// With this sole predecessor, the whole wave reaches b only once EXEC is empty. + fn empty_loop_wrexec(&self, b: usize) -> Option { + let &[(pred, _)] = self.preds[b].as_slice() else { return None }; + if pred == b || self.succ[pred] != [(pred, Edge::Taken), (b, Edge::NotTaken)] { + return None; + } + let (start, end) = self.blocks[pred]; + let [.., write, branch] = &self.insts[start..end] else { return None }; + if branch.inst.name != "S_CBRANCH_EXECNZ" || !write.inst.name.ends_with("_WREXEC_B32") { + return None; + } + rdna2::field_value(write.enc, &write.words, "SDST").map(|r| r as u8) + } + + fn analyze(mut self, repair_empty_exits: bool) -> R { let n = self.blocks.len(); let mut entry = State { regs: vec![None; 128], scc: None }; entry.regs[EXEC] = Some(match self.launch { LaunchExec::All => TRUE, LaunchExec::Unknown => self.atom(Atom::Launch, 0)?, }); + let mut empty_exits = vec![None; n]; + if repair_empty_exits && !self.wave64 { + for &b in &self.order { + empty_exits[b] = self.empty_loop_wrexec(b); + } + } let mut forced = HashSet::new(); let mut reach = vec![FALSE; n]; let mut ins: Vec> = vec![None; n]; @@ -850,7 +873,13 @@ impl<'a> Lanes<'a> { if !std::mem::take(&mut dirty[b]) { continue; } - let (r, st) = if b == 0 { (TRUE, entry.clone()) } else { self.join(b, &outs, &forced, false)? }; + let (r, mut st) = if b == 0 { (TRUE, entry.clone()) } else { self.join(b, &outs, &forced, false)? }; + if let Some(dst) = empty_exits[b] { + st.scc = Some((FALSE, SccKind::Uniform)); + if dst != 125 { + st.regs[dst as usize] = Some(FALSE); + } + } if ins[b].as_ref() == Some(&st) && reach[b] == r { continue; } @@ -951,6 +980,7 @@ impl<'a> Lanes<'a> { succ: self.succ[b].clone(), preds: self.preds[b].iter().map(|p| p.0).collect(), lane_branch: lane_branch[b], + empty_loop_wrexec: empty_exits[b], }) .collect(); sum.order = self.order.clone(); @@ -967,16 +997,17 @@ pub fn analyze(insts: &[Decoded], wave64: bool) -> R { /// Analyses a decoded program (far jumps resolved) that starts with EXEC as `launch` says. pub fn analyze_launch(insts: &[Decoded], wave64: bool, launch: LaunchExec) -> R { - analyze_branches(insts, wave64, launch, false) + // Without a lowering stage, rely only on facts that hold without exit repairs. + analyze_branches(insts, wave64, launch, false, false) } -pub(super) fn analyze_branches(insts: &[Decoded], wave64: bool, launch: LaunchExec, wave_branches: bool) -> R { +pub(super) fn analyze_branches(insts: &[Decoded], wave64: bool, launch: LaunchExec, wave_branches: bool, repair_empty_exits: bool) -> R { if insts.is_empty() { return Ok(Summary::default()); } let mut lanes = Lanes::new(insts, wave64, launch)?; lanes.wave_branches = wave_branches; - lanes.analyze() + lanes.analyze(repair_empty_exits) } /// Decodes and analyses a program. diff --git a/crates/xcl/src/gpu/recomp/lower.rs b/crates/xcl/src/gpu/recomp/lower.rs index 6f86a342a..27d14999c 100644 --- a/crates/xcl/src/gpu/recomp/lower.rs +++ b/crates/xcl/src/gpu/recomp/lower.rs @@ -1160,22 +1160,6 @@ fn partial_blocks(sum: &Summary) -> Vec { partial } -/// The WREXEC destination when wave32 block b can only be reached by exhausting a -/// self-loop's EXEC. Both the mask it copied and SCC are then zero for the console -/// wave, including lanes that left the loop on an earlier iteration. -fn empty_loop_wrexec(sum: &Summary, insts: &[Decoded], b: usize) -> Option { - let [pred] = sum.blocks[b].preds[..] else { return None }; - let block = &sum.blocks[pred]; - if pred == b || block.succ != [(pred, Edge::Taken), (b, Edge::NotTaken)] { - return None; - } - let [.., write, branch] = &insts[block.insts.clone()] else { return None }; - if branch.inst.name != "S_CBRANCH_EXECNZ" || !write.inst.name.ends_with("_WREXEC_B32") { - return None; - } - rdna2::field_value(write.enc, &write.words, "SDST").map(|r| r as u8) -} - /// Lowers a kernel-mode program (far jumps resolved) into `ir`, which gets it complete, with /// the mask registers whose value at the end may differ from the console's: written in a block /// some lanes skipped, so those lanes still hold their own older bits (`stale`). Nothing reads @@ -1223,7 +1207,7 @@ fn lower_with(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I, s // Ballots reconstruct every bit only when the entire console wave is present. let wave_branches = matches!(stage, Stage::Compute(cs) if cs.threads.iter().product::() % (if wave64 { 64 } else { 32 }) == 0) && !ir.whole_needs_exchange(); - let sum = lane_masks::analyze_branches(insts, wave64, launch, wave_branches).map_err(|e| e.to_string())?; + let sum = lane_masks::analyze_branches(insts, wave64, launch, wave_branches, !graphics).map_err(|e| e.to_string())?; let n = sum.blocks.len(); if n == 0 { return Err("empty program".into()); @@ -1462,13 +1446,11 @@ fn lower_with(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I, s if !sealed[ib] { sealed[ib] = seal_ready(&mut l, &done, ib); } - if !graphics && !wave64 { - if let Some(r) = empty_loop_wrexec(&sum, insts, b) { - let zero = l.ir.boolean(false); - l.write_scc(ib, zero); - if r != 125 { - l.write_bit(ib, r, zero); - } + if let Some(r) = sum.blocks[b].empty_loop_wrexec { + let zero = l.ir.boolean(false); + l.write_scc(ib, zero); + if r != 125 { + l.write_bit(ib, r, zero); } } if b == 0 && !pixel { @@ -3631,6 +3613,22 @@ pub(crate) mod tests { assert!(err.contains("some lanes were elsewhere"), "{err}"); } + #[test] + fn empty_wrexec_loop_repairs_the_mask_and_scc_only_on_exhaustion() { + let (s, v) = state(32); + let (s, v) = run(EMPTY_LOOP_SCC, false, &s, &v); + assert_eq!(s[4], 0); + assert!(v.iter().all(|regs| regs[2] == 11)); + + // Falling through EXECZ instead means at least one bit is still set. + let mut lines = EMPTY_LOOP_SCC.to_vec(); + lines[6] = ("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", 0xFFFB)]); + let insts = decode(&lines); + let sum = lane_masks::analyze_branches(&insts, false, lane_masks::LaunchExec::All, false, true).unwrap(); + assert!(sum.blocks.iter().all(|b| b.empty_loop_wrexec.is_none())); + assert!(lower_kernel(&insts, false, Interp::default()).is_err()); + } + #[test] fn the_latch_counter_can_still_be_stale_after_the_loop() { let mut lines = LATCH_COUNTER.to_vec();