Skip to content
Merged
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
2 changes: 1 addition & 1 deletion docs/design.md

Large diffs are not rendered by default.

186 changes: 186 additions & 0 deletions tests/semantic/test_structured_pc_unwrap.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
"""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)

def test_wave64_emulate_exec_fold_refuses_last_block_cbranch_falloff(self):
"""A wave64 s_cbranch_execz region containing a trailing conditional branch (no s_endpgm) must NOT be
folded into a region that unconditionally continues at `skip`: falling off the end must terminate."""
prog_to_x = [
"s_mov_b64 s[10:11], exec",
"s_cbranch_execz skip",
"s_branch last",
"X:",
"v_lshlrev_b32_e32 v2, 2, v0",
"v_mov_b32_e32 v1, 0x3333",
"buffer_store_dword v1, v2, s[0:3], 0 offen",
"s_branch skip",
"skip:",
"v_lshlrev_b32_e32 v2, 2, v0",
"v_mov_b32_e32 v1, 0x4444",
"buffer_store_dword v1, v2, s[0:3], 0 offen offset:256",
"s_endpgm",
"last:",
"s_cmp_eq_u32 s4, 1",
"s_cbranch_scc1 X",
]
prog_to_skip = [
"s_mov_b64 s[10:11], exec",
"s_cbranch_execz skip",
"s_branch last",
"skip:",
"v_lshlrev_b32_e32 v2, 2, v0",
"v_mov_b32_e32 v1, 0x4444",
"buffer_store_dword v1, v2, s[0:3], 0 offen offset:256",
"s_endpgm",
"last:",
"s_cmp_eq_u32 s4, 1",
"s_cbranch_scc1 skip",
]
for name, prog, want_taken_x, want_taken_skip in (
("branch_to_x", prog_to_x, 0x3333, 0x4444),
("branch_to_skip", prog_to_skip, 0, 0x4444),
):
for structured in (True, False):
spv, _ = _translate_cs(
f"cs_fold_falloff_{name}_{int(structured)}",
prog, threads=64, emulate=True, structured=structured,
)
for s4, exp_x, exp_skip in ((0, 0, 0), (1, want_taken_x, want_taken_skip)):
with self.subTest(case=name, structured=structured, 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)], [exp_x] * 64)
self.assertEqual([mem.get(256 + 4 * t, 0) for t in range(64)], [exp_skip] * 64)


if __name__ == "__main__":
unittest.main()
39 changes: 39 additions & 0 deletions tests/test_cfg_structure.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,10 +146,17 @@ def split_choose(b, _orig=orig, _ns=new_succ, _seed=seed, _v=visits):
loops += '"loop"' in repr(tree).replace("'", '"')
placed = blocks_in(tree)
assert len(placed) == len(set(placed)), f"a block is placed twice: {succ}"
out_pcs = {b: (set(succ[b]) if succ[b] else {S.END}) for b in range(len(succ))}
utree = S.unwrap_known_pc_guards(tree, out_pcs)
uplaced = blocks_in(utree)
assert len(uplaced) == len(set(uplaced)) and set(uplaced) == set(placed), (
f"unwrap changed block set for {succ}: {placed} vs {uplaced}")
for seed in range(6):
want = walk(succ, chooser(succ, seed), 200)
got = S.run(tree, chooser(succ, seed), 200)
assert got == want, f"graph {succ} seed {seed}: tree ran {got}, graph runs {want}"
ugot = S.run(utree, chooser(succ, seed), 200)
assert ugot == want, f"unwrapped graph {succ} seed {seed}: tree ran {ugot}, graph runs {want}"
assert structured > 5000 and refused > 1000 and loops > 2000, (structured, refused, loops)
assert split_ok > 1000 and split_ok + split_cap == refused, (split_ok, split_cap, refused)
return structured, refused, loops, split_ok, split_cap
Expand Down Expand Up @@ -247,10 +254,42 @@ def test_deep_sequential_chains_stay_flat_and_iterative():
assert got == want


def test_unwrap_known_pc_guards():
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
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.
assert unwrap([[2, 1], [2], []]) == [("block", 0), ("guard", 1, [("block", 1)]), ("block", 2)]
# Diamond (0 -> {1, 2}, 1 -> {3}, 2 -> {3}, 3 -> []): join block 3 unwraps to top level.
assert unwrap([[1, 2], [3], [3], []]) == [("block", 0), ("guard", 2, [("block", 2)]),
("guard", 1, [("block", 1)]), ("block", 3)]
# Loop exit (0 -> {0, 1}, 1 -> []): block 1 unwraps to top level because exiting loop 0 proves pc == 1.
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__":
test_depth()
test_shapes()
test_deep_sequential_chains_stay_flat_and_iterative()
test_unwrap_known_pc_guards()
structured, refused, loops, split_ok, split_cap = _check_random_graphs()
print(f"ok: {structured} graphs structured and run, {refused} irreducible "
f"({split_ok} split-structured, {split_cap} capped), {loops} with loops")
5 changes: 5 additions & 0 deletions tests/test_translate.py
Original file line number Diff line number Diff line change
Expand Up @@ -1392,6 +1392,11 @@ def test_mesh_s3_wave_id_emits_local_index_shift_and_bfe(make_shader):
asm = shader.translate()
shader.validate(asm)
assert "%wave = OpShiftRightLogical %uint %lidx %c6" in asm
# SHADER-STRUCTURED-PC-UNWRAP: blk2 post-dominates blk0/blk1 and carries s_barrier, so its tautological
# pc == 2 guard must be unwrapped (keeping OpControlBarrier in uniform top-level control flow for AMD LLPC).
blk2_pos = asm.index("%blk2 = OpLabel")
before_blk2 = asm[asm.index("%blk1 = OpLabel"):blk2_pos]
assert "OpBranchConditional" not in before_blk2, before_blk2
assert "%mwi = OpShiftLeftLogical %uint %wave %c18" in asm
assert "OpStore %s3p %mwi" in asm
assert "OpBitFieldUExtract %uint" in asm
Expand Down
68 changes: 66 additions & 2 deletions tools/cfg_structure.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -158,7 +158,8 @@ def member(x, region):
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
Expand Down Expand Up @@ -347,3 +348,66 @@ def run(tree, choose, limit):
else:
stack.pop()
return trace


def unwrap_known_pc_guards(tree, out_pcs, entry_pc=0):
"""Unwrap `("guard", g, body)` nodes whenever abstract interpretation proves `%pc == g` on all incoming paths.

`structure()` wraps post-dominating join blocks after a diamond or loop in `("guard", g, ...)`. When every
incoming path guarantees `%pc == g` (e.g. a merge block with `s_barrier` after a wave-divergent branch like
`ms_wave_info_s3`), unwrapping the tautological guard keeps `OpControlBarrier` in uniform top-level control
flow (avoiding an AMD Windows LLPC 0xC0000005 pipeline-creation crash in MeshEXT and preventing false
`needs_barrier_rounds` triggers) and avoids redundant `%pc` merge phis.

`out_pcs[b]` is the finite set of `%pc` values block `b` may write (`{END}` when `b` terminates).
"""
root_out = []
stack = [[collections.deque(tree), root_out, {entry_pc}, None]]
while stack:
frame = stack[-1]
q, dst, cur_pc, tag = frame
if not q:
if len(stack) > 1 and tag[0] == "guard" and len(cur_pc) == 1:
nxt_g = next(iter(cur_pc))
skip_pc = tag[3]
parent_q = stack[-2][0]
if parent_q and parent_q[0][0] == "guard" and parent_q[0][1] == nxt_g and nxt_g not in skip_pc:
for child in reversed(parent_q.popleft()[2]):
q.appendleft(child)
continue
stack.pop()
if not stack:
break
parent = stack[-1]
if tag[0] == "guard":
_, g, child_dst, skip_pc = tag
parent[1].append(("guard", g, child_dst))
parent[2] = skip_pc | cur_pc
else:
_, h, child_dst = tag
parent[1].append(("loop", h, child_dst))
parent[2] = cur_pc - {h}
continue
it = q.popleft()
kind = it[0]
if kind == "block":
b = it[1]
dst.append(it)
frame[2] = set(out_pcs[b])
elif kind == "guard":
g, gbody = it[1], it[2]
if cur_pc == {g}:
for child in reversed(gbody):
q.appendleft(child)
else:
child_dst = []
skip_pc = set(cur_pc)
skip_pc.discard(g)
stack.append([collections.deque(gbody), child_dst, {g}, ("guard", g, child_dst, skip_pc)])
else:
h, lbody = it[1], it[2]
child_dst = []
# In a structure() tree lbody[0] is always ("block", h), which overwrites cur_pc with out_pcs[h];
# keep cur_pc | {h} defensively so back-edge iterations stay sound even on non-structure() trees.
stack.append([collections.deque(lbody), child_dst, set(cur_pc) | {h}, ("loop", h, child_dst)])
return root_out
Loading
Loading