fix(rdna2spirv): include END in out_pcs for trailing conditional branches

A conditional branch in the last basic block (no fallthrough block, so
len(raw_edges[b]) == 1) emits OpSelect(%cond, tgt, len(blocks)) and can
leave %pc at either tgt or cfg_structure.END.

Compute exact per-block out_pcs in rdna2spirv._block_out_pcs (matching
wave64_emulate_opt), pass it through capped_tree() into both
cfg_structure.structure() (so single-target fall-off-the-end blocks also
keep their dominated target guard) and unwrap_known_pc_guards(), and
pass compact_out_pcs into cfg_structure.structure() in wave64_emulate_opt.

Add unit and semantic regression tests covering both the loop back-edge
repro reported in review and the non-loop dominated-target variant.

Co-Authored-By: Gemini 4 Neon <noreply@google.com>
This commit is contained in:
whoalin1
2026-11-24 23:56:36 +02:00
parent 53ef382d70
commit 8e5cf5aef1
5 changed files with 191 additions and 17 deletions

View File

@ -0,0 +1,137 @@
"""Semantic regression tests for structured %pc guard unwrapping (SHADER-STRUCTURED-PC-UNWRAP).
Pure Python stdlib only (no llvm-mc, spirv-val, GPU, or game data). Verifies end-to-end translation
and execution of synthetic hand-written RDNA2 compute shaders where the last basic block ends in a
conditional branch with no trailing s_endpgm (fallthrough writes %pc = len(blocks) = END):
1. Loop whose back-edge is a conditional branch at the very end of the shader (succ = [[2, 1], [], [0]],
out_pcs[2] = {0, END}): exiting the loop leaves %pc in {1, END}, so guard 1 must stay and a
not-taken back-edge must terminate without executing block 1.
2. Non-loop conditional branch at the very end of the shader whose single explicit target is
immediately dominated by it (succ = [[2], [], [1]], out_pcs[2] = {1, END}): both native
structured control flow and --wave64-emulate structured control flow must keep guard 1.
3. Single-arm if-then join (0 -> {2, 1}, 1 -> {2}, 2 -> []) with s_barrier in block 2: block 2
unwraps to top level so wave32 compute does not falsely fall back to barrier rounds.
"""
import os
import sys
import unittest
HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(os.path.dirname(HERE))
TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")
sys.dont_write_bytecode = True
for _p in (HERE, TOOLS_DIR):
if _p not in sys.path:
sys.path.insert(0, _p)
import rdna2spirv # noqa: E402
from test_loop_ballot_barrier import VSHARP, _translate_cs, run_compute_workgroup # noqa: E402
class StructuredPcUnwrapSemanticTest(unittest.TestCase):
def test_loop_last_block_cbranch_falloff_keeps_exit_guard(self):
"""Loop back-edge in the last block with no s_endpgm after it: falling off the end must NOT run block 1."""
prog = [
"head:",
"s_cmp_eq_u32 s4, 0",
"s_cbranch_scc1 tail",
"v_lshlrev_b32_e32 v2, 2, v0",
"v_mov_b32_e32 v1, 0x1111",
"buffer_store_dword v1, v2, s[0:3], 0 offen",
"s_endpgm",
"tail:",
"s_mov_b32 s4, 1",
"s_cmp_eq_u32 s5, 1",
"s_cbranch_scc1 head",
]
spv_struct, gen_struct = _translate_cs("cs_cbranch_falloff_loop", prog, threads=32, structured=True)
spv_disp, gen_disp = _translate_cs("cs_cbranch_falloff_loop_disp", prog, threads=32, structured=False)
self.assertEqual(gen_struct.control_flow, "structured")
self.assertEqual(gen_disp.control_flow, "dispatch loop")
self.assertEqual(gen_struct.succ, [[2, 1], [], [0]])
self.assertEqual(gen_struct.out_pcs[2], frozenset({0, -1}))
tree, _ = rdna2spirv.capped_tree(gen_struct.succ, gen_struct.out_pcs)
self.assertEqual(tree, [
("loop", 0, [("block", 0), ("guard", 2, [("block", 2)])]),
("guard", 1, [("block", 1)]),
])
cases = [
(1, 0, [0x1111] * 32), # B0 falls into B1 -> stores 0x1111
(0, 1, [0x1111] * 32), # B0 -> B2 (s4=1, back-edge taken) -> B0 -> B1 -> stores 0x1111
(0, 0, [0] * 32), # B0 -> B2 (back-edge not taken -> falls off end) -> no store
]
for s4, s5, want in cases:
with self.subTest(s4=s4, s5=s5):
pc = VSHARP + [s4, s5]
mem_s = run_compute_workgroup(spv_struct, 32, 32, push_constants=pc)
mem_d = run_compute_workgroup(spv_disp, 32, 32, push_constants=pc)
got_s = [mem_s.get(4 * t, 0) for t in range(32)]
got_d = [mem_d.get(4 * t, 0) for t in range(32)]
self.assertEqual(got_d, want)
self.assertEqual(got_s, want)
def test_nonloop_last_block_cbranch_falloff_keeps_dominated_target_guard(self):
"""Last block ending in s_cbranch_scc1 to its single dominated target (no s_endpgm) must keep its guard."""
prog = [
"s_branch tail",
"do_store:",
"v_lshlrev_b32_e32 v2, 2, v0",
"v_mov_b32_e32 v1, 0x2222",
"buffer_store_dword v1, v2, s[0:3], 0 offen",
"s_endpgm",
"tail:",
"s_cmp_eq_u32 s4, 1",
"s_cbranch_scc1 do_store",
]
for mode, threads, sg_sz, emulate in (
("w32_structured", 32, 32, False),
("w64_emulate", 64, 32, True),
):
# Include a 64-bit exec op in the wave64 case so rdna2spirv classifies the shader as wave64
# and exercises wave64_emulate_opt.plan_structured_emulation().
mode_prog = (["s_mov_b64 s[10:11], exec"] + prog) if emulate else prog
spv, gen = _translate_cs(f"cs_cbranch_falloff_{mode}", mode_prog, threads=threads, emulate=emulate)
if emulate:
self.assertEqual(gen.control_flow, "emulated wave64 structured")
else:
self.assertEqual(gen.control_flow, "structured")
tree, _ = rdna2spirv.capped_tree(gen.succ, gen.out_pcs)
self.assertEqual(tree, [("block", 0), ("block", 2), ("guard", 1, [("block", 1)])])
for s4, want_val in ((1, 0x2222), (0, 0)):
with self.subTest(mode=mode, s4=s4):
mem = run_compute_workgroup(spv, threads, sg_sz, push_constants=VSHARP + [s4])
self.assertEqual([mem.get(4 * t, 0) for t in range(threads)], [want_val] * threads)
def test_postdominating_join_barrier_unwraps_to_top_level(self):
"""A post-dominating merge block after a single-arm branch unwraps to top level (no false barrier rounds)."""
prog = [
"v_lshlrev_b32_e32 v2, 2, v0",
"v_mov_b32_e32 v1, 1",
"s_cmp_eq_u32 s4, 0",
"s_cbranch_scc1 join",
"v_mov_b32_e32 v1, 2",
"join:",
"ds_write_b32 v2, v1",
"s_waitcnt lgkmcnt(0)",
"s_barrier",
"ds_read_b32 v3, v2",
"s_waitcnt lgkmcnt(0)",
"buffer_store_dword v3, v2, s[0:3], 0 offen",
"s_endpgm",
]
spv, gen = _translate_cs("cs_join_barrier_unwrap", prog, threads=64, lds_bytes=256, emulate=False)
self.assertFalse(gen.bar_rounds)
self.assertEqual(gen.control_flow, "structured")
tree, _ = rdna2spirv.capped_tree(gen.succ, gen.out_pcs)
self.assertEqual(tree, [("block", 0), ("guard", 1, [("block", 1)]), ("block", 2)])
for s4, want_val in ((0, 1), (1, 2)):
with self.subTest(s4=s4):
mem = run_compute_workgroup(spv, 64, 32, push_constants=VSHARP + [s4])
self.assertEqual([mem.get(4 * t, 0) for t in range(64)], [want_val] * 64)
if __name__ == "__main__":
unittest.main()

View File

@ -255,10 +255,11 @@ def test_deep_sequential_chains_stay_flat_and_iterative():
def test_unwrap_known_pc_guards():
def unwrap(succ):
tree = S.structure(succ)
def unwrap(succ, out_pcs=None):
if out_pcs is None:
out_pcs = {b: (set(succ[b]) if succ[b] else {S.END}) for b in range(len(succ))}
tree = S.structure(succ, out_pcs=out_pcs)
assert tree is not None
out_pcs = {b: (set(succ[b]) if succ[b] else {S.END}) for b in range(len(succ))}
return S.unwrap_known_pc_guards(tree, out_pcs)
# Single-arm if-then (ms_wave_info_s3 shape: 0 -> {2, 1}, 1 -> {2}, 2 -> []): join block 2 unwraps to top level.
@ -270,6 +271,18 @@ def test_unwrap_known_pc_guards():
assert unwrap([[0, 1], []]) == [("loop", 0, [("block", 0)]), ("block", 1)]
# Early exit in arm 1 (0 -> {1, 2}, 1 -> [], 2 -> []): both arms MUST remain guarded (pc may be END).
assert unwrap([[1, 2], [], []]) == [("block", 0), ("guard", 2, [("block", 2)]), ("guard", 1, [("block", 1)])]
# Conditional branch in the last block with no s_endpgm after it (fallthrough writes END):
# loop body block 2 has succ [0] but out_pcs {0, END}, so exiting loop 0 leaves pc in {1, END};
# guard 1 MUST stay so falling off the end does not execute block 1.
assert unwrap([[2, 1], [], [0]], out_pcs={0: {2, 1}, 1: {S.END}, 2: {0, S.END}}) == [
("loop", 0, [("block", 0), ("guard", 2, [("block", 2)])]),
("guard", 1, [("block", 1)]),
]
# Non-loop conditional branch falling off the end whose single explicit target is immediately dominated by it:
# block 2 has succ [1] and out_pcs {1, END}, so structure() and unwrap MUST both keep guard 1.
assert unwrap([[2], [], [1]], out_pcs={0: {2}, 1: {S.END}, 2: {1, S.END}}) == [
("block", 0), ("block", 2), ("guard", 1, [("block", 1)]),
]
if __name__ == "__main__":

View File

@ -80,7 +80,7 @@ def _dominators(rpo, preds):
return idom, pos
def structure(succ):
def structure(succ, out_pcs=None):
rpo, back, preds = _order(succ)
idom, pos = _dominators(rpo, preds)
@ -158,7 +158,8 @@ def structure(succ):
out_list.append(("loop", x, lbody))
else:
out_list.append(("block", x))
if kind == "b" and len(below) == 1 and list(succ[x]) == [below[0][1]]:
if (kind == "b" and len(below) == 1 and list(succ[x]) == [below[0][1]]
and (out_pcs is None or set(out_pcs[x]) == {below[0][1]})):
stack.append(("emit", out_list, parent_list, below[0], depth))
else:
hoist = (parent_list is not None and below

View File

@ -398,6 +398,7 @@ class Gen:
# single defining plain v_mov of it); valid I/J sources (SHADER-177)
self.blocks = [] # per basic block: list of SPIR-V lines (dispatch-loop form), empty = straight-line
self.succ = [] # per basic block: the blocks it can go to next (none = the program ends there)
self.out_pcs = None # per basic block: exact set of %pc values written (including cfg_structure.END)
self.desc_fn = None # lines of the descriptor-lookup function, once an instruction needs it
self.tbuffer_norm_fns: dict[int, list[str]] = {} # one exact quotient per used magnitude width
self.fmt_fn = None # lines of the typed-buffer format-decode function, once a dynamic-format load needs it
@ -16276,7 +16277,7 @@ def assemble(gen):
helpers.extend(function)
for function in gen.x_round_fns.values():
helpers.extend(function)
tree, nesting = (capped_tree(gen.succ) if gen.blocks and not gen.emulate and not gen.bar_rounds
tree, nesting = (capped_tree(gen.succ, gen.out_pcs) if gen.blocks and not gen.emulate and not gen.bar_rounds
else (None, None))
if nesting is not None:
gen.nesting = nesting
@ -18055,6 +18056,7 @@ def translate(path):
g.cu(n)
raw_edges = split_edges
succ = [list(dict.fromkeys(e)) for e in raw_edges]
g.out_pcs = _block_out_pcs(blocks, raw_edges, succ)
g.vm_latch = stage == "ps" and exec_changes_after_vm(blocks, succ)
g.park_masks((blocks, succ))
halves_analysis(g, blocks, succ)
@ -18334,15 +18336,33 @@ def finish_module(g):
return spirv_loop_guard.add_guards(text, LOOP_LIMIT)
def capped_tree(succ):
def _block_out_pcs(blocks, raw_edges, succ):
"""Possible `%pc` values each basic block can store (`cfg_structure.END` when the block can end the shader).
A conditional branch with no fallthrough block (`len(raw_edges[b]) == 1`, i.e. the last block or a split clone
of it) emits `OpSelect %uint cond tgt len(blocks)` and therefore writes either `tgt` or `END`."""
out_pcs = {}
for b, blk in enumerate(blocks):
pcs = set(succ[b])
if not pcs:
pcs.add(cfg_structure.END)
elif len(raw_edges[b]) == 1:
last = next((i for i in blk if base_op(i["op"]) == "s_endpgm" or base_op(i["op"]) in BRANCHES), None)
if last is not None and base_op(last["op"]) in BRANCHES and base_op(last["op"]) != "s_branch":
pcs.add(cfg_structure.END)
out_pcs[b] = frozenset(pcs)
return out_pcs
def capped_tree(succ, out_pcs=None):
"""(tree, nesting): the structured tree for `succ` and its depth, or (None, None) under --dispatch-loop or when
cfg_structure can't structure it; tree is None (nesting still the measured depth) when it nests deeper than
MAX_STRUCTURED_DEPTH. assemble() emits exactly this tree, and needs_barrier_rounds() decides from the same one
(SHADER-427 review): a barrier in a tree that falls back to the dispatch loop isn't at a structured top level."""
tree = cfg_structure.structure(succ) if STRUCTURED else None
if out_pcs is None:
out_pcs = {b: (set(succ[b]) if succ[b] else {cfg_structure.END}) for b in range(len(succ))}
tree = cfg_structure.structure(succ, out_pcs=out_pcs) if STRUCTURED else None
if tree is None:
return None, None
out_pcs = {b: (set(succ[b]) if succ[b] else {cfg_structure.END}) for b in range(len(succ))}
tree = cfg_structure.unwrap_known_pc_guards(tree, out_pcs)
nesting = cfg_structure.depth(tree)
if MAX_STRUCTURED_DEPTH and nesting > MAX_STRUCTURED_DEPTH:
@ -18370,7 +18390,7 @@ def needs_barrier_rounds(g, blocks, succ):
break
if not with_barrier:
return False
tree, _ = capped_tree(succ) # the tree assemble() emits: over MAX_STRUCTURED_DEPTH it's the dispatch loop
tree, _ = capped_tree(succ, g.out_pcs) # the tree assemble() emits: over MAX_STRUCTURED_DEPTH it's the dispatch loop
top = {it[1] for it in tree if it[0] == "block"} if tree is not None else set()
return not with_barrier <= top

View File

@ -1549,23 +1549,26 @@ def plan_structured_emulation(blocks, raw_edges, succ, folds, fold_chain, absorb
eff_succ[b] = nxt
eff_succ_compact.append([eff_idx[s] for s in nxt])
compact_tree = cfg_structure.structure(eff_succ_compact)
if compact_tree is None:
return None
tree = _map_tree_ids(compact_tree, eff_blocks)
out_pcs = {}
for b in eff_blocks:
tail = chain_of[b][-1]
s = set(eff_succ[b])
if not s:
s.add(-1)
s.add(cfg_structure.END)
elif tail not in folds and len(raw_edges[tail]) == 1:
last = active_blocks[tail][-1] if active_blocks[tail] else None
op = base_op(last["op"]) if last is not None else None
if op in BRANCHES and op != "s_branch":
s.add(-1)
s.add(cfg_structure.END)
out_pcs[b] = frozenset(s)
compact_out_pcs = {
eff_idx[b]: frozenset(eff_idx[p] if p != cfg_structure.END else cfg_structure.END for p in pcs)
for b, pcs in out_pcs.items()
}
compact_tree = cfg_structure.structure(eff_succ_compact, out_pcs=compact_out_pcs)
if compact_tree is None:
return None
tree = _map_tree_ids(compact_tree, eff_blocks)
tree = _unwrap_known_pc_guards(tree, out_pcs, eff_blocks[0])
# Precompute per-superblock instruction summaries (for dirty transfer, sync-free check, s_barrier, s_endpgm).