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
1 change: 1 addition & 0 deletions docs/design.md
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,7 @@ How the generated SPIR-V expects the runtime to work:
| `s_*_saveexec_b32/b64`, `s_andn1/andn2_wrexec_b32/b64` | RDNA2 ISA SOP1. saveexec: `D = EXEC; EXEC = f(S0, EXEC); SCC = (EXEC != 0)`. wrexec: `EXEC = f(S0, EXEC); D = EXEC`. `f` is one of `and`, `or`, `xor`, `andn1` (`~S0 & EXEC`), `andn2` (`S0 & ~EXEC`), `orn1` (`~S0 \| EXEC`), `orn2` (`S0 \| ~EXEC`), `nand`, `nor`, `xnor`, the table in `Gen.EXEC_LOGIC`. The definitions match `tools/cf_ref.py` `_SAVEEXEC`, the FUZZ-8 model. Each invocation holds its own lane's bit (0 or ~0), so `f` is the bitwise op on that bit. A lane EXEC had off becomes active when `f` gives 1 for it (`nand`, `nor`, `orn1`, `orn2`, `xnor`, ...), as on hardware, and SCC is the wave vote. Until 2026-11-22 only `and`/`or`/`andn2_saveexec` and `andn2_wrexec` were translated. CPU-checked by `tests/semantic/test_saveexec_variants.py` (all ten saveexec kinds in wave32 and wave64, both wrexec kinds, partial EXEC and S0, an empty result, every lane against `cf_ref._SAVEEXEC`) and by `tools/cf_diff.py` (300 programs × wave32/64 still pass). Hardware-verified on native RDNA2 (`gfx1036`, Windows 11, driver `32.0.21045.29003`, wave32 & wave64, 0 mismatches): all 10 `saveexec` kinds and both `wrexec` kinds (`andn1`/`andn2`) match bit-for-bit on non-symmetric masks (`src0 = 0x0F0F0F0F`, `exec = 0x33333333` in wave32; `0x0F0F0F0F_00FF00FF` / `0x33333333_55555555` in wave64), zero-result `SCC = 0`, wave64 upper-32-bit-only `new_exec = 0x00000001_00000000` setting `SCC = 1`, and `sdst == src0` register aliasing (`s4, s4` and `s[4:5], s[4:5]`) reading original `src0` before writing old `EXEC` to `sdst`. **Not GPU-verified** for the seven new kinds. Measured on native gfx1100 (single 8-lane workgroup, 36 programs): all ten `saveexec` kinds and both `wrexec` forms follow `f` for three `S0`/`EXEC` pairs, including lanes `EXEC` had off being switched back on (`nand` with `S0=0x03`, `EXEC=0x0F` leaves `0xFFFFFFFC`, activating lanes 4-7), `D` holding the old `EXEC` for `saveexec` and the new one for `wrexec`, and `SCC` the `EXEC != 0` vote. |
| Control flow | Reducible graphs use structured branches and natural loops. Irreducible graphs use the dispatch-loop form, which can also be forced with `--dispatch-loop` for comparisons. The control-flow unit test checks 18,228 generated graphs. Irreducible graphs use node splitting (`cfg_structure.split_irreducible`, up to `min(2*N, N+64)` blocks) and fall back to the dispatch-loop form when capped; it can also be forced with `--dispatch-loop` for comparisons. `cfg_structure.structure`, `cfg_structure.run`, and `rdna2spirv.assemble`'s structured emitter are iterative and hoist each guarded member's dominated tail continuation out of its enclosing guard (exact by strict dominance: no block outside the guard's subtree can target the continuation), keeping `OpSelectionMerge` nesting O(1) on sequential diamond/loop chains instead of nesting O(N) deep and hitting Python's recursion limit on multi-thousand-block shaders (e.g. 2,000 sequential diamonds nest to depth 2 instead of 2,000). The control-flow unit test (`tests/test_cfg_structure.py`) checks 20,000 generated graphs plus 2,000-diamond, 1,200-loop, and 1,500-early-exit chains. `capped_tree()` also runs `cfg_structure.unwrap_known_pc_guards` (shared with `wave64_emulate_opt`) to unwrap tautological `("guard", g, ...)` nodes whenever abstract interpretation proves `%pc == g` on all incoming paths (e.g. post-dominating merge blocks after diamonds and loops); this keeps `ms_wave_info_s3`'s `s_barrier` in uniform top-level control flow (fixing an AMD Windows LLPC `0xC0000005` pipeline-creation crash on AMD Ryzen 5 7600 RDNA2 iGPU driver `24.10.24`, `4096/4096` exact on AMD RDNA2 and RTX 4070 SUPER) and avoids false `needs_barrier_rounds` triggers (`SHADER-STRUCTURED-PC-UNWRAP`). AMD A/B checks compare the two forms for selected pixel shaders with defined test inputs. For shaders that never export colour, the comparison checks pixel coverage. **Nesting is bounded (SHADER-299):** a tree deeper than `MAX_STRUCTURED_DEPTH` (16) is emitted in the dispatch-loop form instead, since `spirv-val` time grows roughly with the cube of the measured nesting depth. **Nesting is bounded (SHADER-299, SHADER-427):** a tree deeper than `MAX_STRUCTURED_DEPTH` (64; `--max-structured-depth N`, 0 = no bound) is emitted in the dispatch-loop form instead, since `spirv-val` time grows roughly with the cube of the measured nesting depth. Before #1904, over the 1.0.2.1 corpus (26,503 modules, `spirv-val` 2026.4): the deepest block of a module is nested 118 constructs deep, 12,963 modules are structured (median 15) and 6,000 of those are deeper than 16; an estimated 85% of the corpus's `spirv-val` time is in modules nested 20 or deeper. Median `spirv-val` time for the same module in each form: depth 20 181 -> 129 ms (1.4x), 30 507 -> 371 (1.4x), 50 1,712 -> 738 (2.3x), 64 2,692 -> 1,163 (2.3x), 77 5,122 -> 1,130 (4.5x), and the deepest (118) 13,683 -> 1,352 ms (10.1x). Depth 5-12 shows no gain (at depth 6 the flat form is slightly slower), which is why the bound first sat at 16. Since #1904 (`cfg_structure` hoists tails) the deepest tree in the corpus is 29: of 12,944 structured modules, 1,031 are deeper than 16 (747 CS, 284 PS), 57 deeper than 20, 24 deeper than 24. For those 1,031 the flat form saves only 12% of `spirv-val` time (1,235 -> 1,091 s summed, slowest module 8.3 -> 5.9 s), while on an RTX 5070 Ti (NVIDIA 621.24) it compiles slower: the 284 pixel shaders 1.67x (827 -> 1,382 s summed, two rounds), four compute modules at depth 19-24 2.0x (297 -> 591 s, 1.6-2.7x each), so the bound now sits above the corpus (SHADER-427). Both forms pass `spirv-val` on a 200-shader slice (200/200 each), and `gen.nesting` records the tree depth. AMD's Windows driver adds a reason to keep the structured form (SHADER-995): on a Radeon gfx1036 iGPU (32.0.21042.62) the dispatch-loop module of `XboxBvhBuilder.dll`'s `LeafRehydration` (tree depth 18, a 581-case switch) takes 34 minutes to create (XXDESIGN), where its structured module is created in 2.9 s; ten other programs of that DLL compile in the dispatch-loop form there in 0.4-40 s, 2.5-5x their structured time ([embedded_shaders.md](embedded_shaders.md), section 7). |
| Loop guard | Each loop counts header visits per invocation and exits through its structured merge at `--loop-limit N` (default 65536, zero disables). Counters reset on entry, including nested EXEC retries and atomic loops. A PC-dispatch visit counts a dispatch iteration. Natural exits within the budget preserve their outputs. Five-star-recomp (b12a952) reported a story-load timeout when the shader input made its exit condition unreachable. |
| Loop guard: a total an invocation | `--loop-total N` (default 1,048,576; 0 = none): on top of each loop's own count, one count of every guarded back edge of an invocation, in a `Private` variable, which no back edge passes once it reaches N. Each loop keeps its own limit and a loop that ends by itself is cut only once a whole invocation has made N visits, but nested loops can no longer multiply their limits (65,536 visits of an inner loop in each of 65,536 visits of the outer one). The case: a loop bound computed by a float divide whose divisor is 0 is +inf, converts to 0xFFFFFFFF, and an inclusive exit test against it never fails once the counter wraps; nested loops of that kind ran at the per-loop limit for seconds a dispatch and the device was lost with no bad address. It changes the translation of every program with a loop, so a shader library takes it when it is translated again. `tests/semantic/test_loop_iteration_guard.py` checks it: two loops that never end stop at the total in both wave sizes, loops that end are untouched, and without a total the per-loop counts multiply. |
| User data | **Push constants, 144 bytes:** dwords 0–31 = initial s0–s31 (the user SGPRs the console driver loads from the root signature: descriptor-table pointers, constants and so on), dwords 32–33 = the 64-bit **heap base**, dwords 34–35 = the **code base**: the Xbox VA where the runtime uploaded this shader's whole FSSM blob. `--mesh-compute` modules add dwords 36–37, the output buffer address (152 bytes; see "Mesh shaders as compute"). `--pc-tail-ubo` keeps only dwords 0–31 here (128 bytes) and moves the rest to a uniform block (see "Push-constant tail as a uniform block"). The runtime has to reproduce the console driver's root-signature-to-user-SGPR mapping; that comes from the exe or driver behaviour. **Mesh shaders** read their root SGPRs through the graphics root window: s16..s31 come from dwords 8..23 (where a VS, PS or GS reads s8..s23), s8..s15 are 0, s0..s7 dwords 0..7; the index records `"root_window": {"sgpr": 16, "dword": 8}` (D3D-448-GRAPHICS, `docs/d3d12_vulkan.md` 3.5). Checked by `tests/semantic/test_ms_root_window.py` (MeshEXT and `--mesh-compute`, CPU interpreter) and `d3d12_mesh_test` (RX 9070 XT). |
| Direct resource heap | In the matched Prop/Tree BatchCull compute signature the two explicit tables and scalar constant occupy s4–s6. Bind the resource heap's uint32 arena-relative byte address at s7 (push-constant byte 28). The program supplies a zero high word and scales the resource index by 32 bytes. Other stages and signatures consume different SGPRs. See [descriptor heaps and the bindless model](d3d12_vulkan.md#34-descriptor-heaps-and-the-bindless-model) for the evidence and graphics examples. |
| Xbox GPU addresses | Shaders build Xbox GPU virtual addresses, and some force the high dword to 0 (descriptor tables in the low 4 GB). Every memory access goes to **heap base + Xbox VA**, so the runtime maps the console's GPU address window into one host buffer-device-address allocation. |
Expand Down
10 changes: 9 additions & 1 deletion make_game.py
Original file line number Diff line number Diff line change
Expand Up @@ -1857,7 +1857,10 @@ def fallback_flags(a) -> tuple[str, ...]:
if descriptor_hash != "fnv1a":
flags += (f"--descriptor-hash={descriptor_hash}",)
limit = getattr(a, "loop_limit", None)
return flags if limit is None else (*flags, f"--loop-limit={limit}")
if limit is not None:
flags = (*flags, f"--loop-limit={limit}")
total = getattr(a, "loop_total", None)
return flags if total is None else (*flags, f"--loop-total={total}")


def recorded_fallback_flags(work: str) -> tuple[str, ...]:
Expand Down Expand Up @@ -3102,6 +3105,9 @@ def main() -> int:
ap.add_argument("--descriptor-hash", choices=("fnv1a", "fnv1a_fmix32"), default="fnv1a",
help="translate all stages for the selected runtime descriptor table hash")
ap.add_argument("--loop-limit", type=int, help="translator loop visit limit (default 65536, 0 disables)")
ap.add_argument("--loop-total", type=int,
help="translator total of loop visits an invocation may make across all its loops, on top of each "
"loop's own limit (default 1048576, 0 = none)")
ap.add_argument("--compact-spirv", action="store_true",
help="run the translator's compact binary pass on all shader libraries (requires spirv-opt)")
ap.add_argument("--no-float-controls", action="store_true",
Expand Down Expand Up @@ -3135,6 +3141,8 @@ def main() -> int:
a = ap.parse_args()
if a.loop_limit is not None and not 0 <= a.loop_limit <= 0xffffffff:
ap.error("--loop-limit must be in 0..4294967295")
if a.loop_total is not None and not 0 <= a.loop_total <= 0xffffffff:
ap.error("--loop-total must be in 0..4294967295")
stages = STAGES
if a.stages is not None:
stages = [s.strip() for s in a.stages.split(",") if s.strip()]
Expand Down
6 changes: 6 additions & 0 deletions tests/semantic/test_control_flow_branches.py
Original file line number Diff line number Diff line change
Expand Up @@ -314,6 +314,7 @@ def __init__(self, spvasm: str):
self.constants: dict[str, int | float | bool | tuple | list] = {}
self.ptr_types: dict[str, tuple[str, str]] = {}
self.var_class: dict[str, str] = {}
self.private_init: dict[str, tuple] = {} # Private globals: (initializer id or None, pointee type)
self.var_box: dict[str, list] = {}
self.pointers: dict[str, tuple] = {}
self.outputs: list[str] = []
Expand Down Expand Up @@ -392,11 +393,16 @@ def _parse(self):
elif cls == "PushConstant":
self.var_box[res] = [None]
self.pointers[res] = ("pc", None)
elif cls == "Private": # the loop guard's total: one per run, from its initializer
self.private_init[res] = (a[2] if len(a) > 2 else None, pointee)

def run(self, max_steps: int = 20000) -> dict[str, tuple]:
values = dict(self.constants)
var_box = dict(self.var_box)
pointers = dict(self.pointers)
for res, (init, pointee) in self.private_init.items():
var_box[res] = [values[init] if init is not None else self.zero(pointee)]
pointers[res] = (var_box[res], 0)

def val(x: str):
if x in values:
Expand Down
5 changes: 4 additions & 1 deletion tests/semantic/test_loop_ballot_barrier.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,10 @@ def _parse_spv(asm):
elif op == "OpVariable":
sc = args[1]
_, elem = ptr_elem[args[0]]
gvars[res] = (sc, elem)
if sc == "Private": # one per invocation, as a function variable (the loop guard's total)
fvars.append((res, elem, args[2] if len(args) > 2 else None))
else:
gvars[res] = (sc, elem)
continue

if op == "OpLabel":
Expand Down
38 changes: 38 additions & 0 deletions tests/semantic/test_loop_iteration_guard.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,3 +73,41 @@ def test_inner_budget_resets_on_each_entry(self):
with patch.object(rdna2spirv, "LOOP_LIMIT", 3):
text, _ = _translate_cs("cs_guard_nested", lines, threads=32)
self.assertEqual(execute(text, 32, 0), [9] * 32)

# Two nested loops that never end (as an inclusive exit against a bound of 0xFFFFFFFF makes them, once the counter
# wraps). With a count per loop the limits multiply: LIMIT visits of the inner loop in each of LIMIT outer visits.
# --loop-total bounds them all together. s9 counts the inner loop's visits.
NEVER = ["s_mov_b32 s8, 0", "s_mov_b32 s9, 0", "outer:", "s_mov_b32 s10, 0",
"inner:", "s_add_u32 s9, s9, 1", "s_add_u32 s10, s10, 1", "s_cmp_eq_u32 s10, 0",
"s_cbranch_scc0 inner", "s_add_u32 s8, s8, 1", "s_cmp_eq_u32 s8, 0", "s_cbranch_scc0 outer",
"v_mov_b32_e32 v1, s9", "v_lshlrev_b32_e32 v2, 2, v0",
"buffer_store_dword v1, v2, s[0:3], 0 offen", "s_endpgm"]

def nested(self, lines, limit, total, lanes=32):
with patch.object(rdna2spirv, "LOOP_LIMIT", limit), patch.object(rdna2spirv, "LOOP_TOTAL", total):
text, _ = _translate_cs("cs_guard_total", lines, threads=lanes, emulate=lanes == 64)
return text, execute(text, lanes, 0)

def test_total_bounds_nested_loops(self):
# Without a total: 50 visits of the inner loop in each of 50 outer visits.
text, words = self.nested(self.NEVER, 50, 0)
self.assertNotIn("%loop_guard_total", text)
self.assertEqual(words, [2500] * 32)
# A total of 40: the first inner run takes 41 visits (the 41st finds the total spent), and the outer loop
# leaves at once after it.
text, words = self.nested(self.NEVER, 50, 40)
self.assertIn("%loop_guard_total", text)
self.assertEqual(words, [41] * 32)
# Emulated wave64: the round scheduler's own loop is guarded too and spends from the same total, so fewer
# visits are left for the program's loops, never more.
text, words = self.nested(self.NEVER, 50, 40, lanes=64)
self.assertIn("%loop_guard_total", text)
self.assertEqual(len(set(words)), 1)
self.assertTrue(0 < words[0] <= 41, words[0])

def test_total_leaves_loops_that_end_alone(self):
# Loops that end by themselves within the total compute what they did: 3 x 3 visits.
lines = [s.replace("s10, 0", "s10, 3").replace("s8, 0", "s8, 3") if s.startswith("s_cmp") else s
for s in self.NEVER]
_, words = self.nested(lines, 50, 16)
self.assertEqual(words, [9] * 32)
2 changes: 2 additions & 0 deletions tests/semantic/test_wave64_emulate_opt.py
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,8 @@ def make_inv(idx, coord):
else:
box = [zero_of(pointee)]
ptrs[res] = (box, 0)
elif cls == "Private": # one per invocation (the loop guard's total), from its initializer
ptrs[res] = ([consts[init_id] if init_id is not None else zero_of(pointee)], 0)
else:
raise NotImplementedError(f"global storage class {cls}")
return {
Expand Down
10 changes: 8 additions & 2 deletions tools/rdna2spirv.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
# differs. docs/design.md "Control flow" has the numbers.
MAX_STRUCTURED_DEPTH = 64
LOOP_LIMIT = spirv_loop_guard.DEFAULT_LIMIT
LOOP_TOTAL = spirv_loop_guard.DEFAULT_TOTAL # --loop-total: the visits of all the loops of an invocation (0: none)
DESCRIPTOR_HASHES = ("fnv1a", "fnv1a_fmix32")
DESCRIPTOR_HASH = "fnv1a"
# --descriptor-table: how the table's entries are read. "plain" is what every module read until the T# dimension
Expand Down Expand Up @@ -18893,7 +18894,7 @@ def finish_module(g):
if OPT_SPIRV:
import spirv_opt
text = spirv_opt.optimize(text)
return spirv_loop_guard.add_guards(text, LOOP_LIMIT)
return spirv_loop_guard.add_guards(text, LOOP_LIMIT, total=LOOP_TOTAL)


def _block_out_pcs(blocks, raw_edges, succ):
Expand Down Expand Up @@ -19802,7 +19803,7 @@ def _out_inside_input(src, out):


def main():
global MAX_SHARED_BYTES, MAX_STRUCTURED_DEPTH, LOOP_LIMIT, DESCRIPTOR_HASH, DESCRIPTOR_TABLE
global MAX_SHARED_BYTES, MAX_STRUCTURED_DEPTH, LOOP_LIMIT, LOOP_TOTAL, DESCRIPTOR_HASH, DESCRIPTOR_TABLE
ap = argparse.ArgumentParser()
ap.add_argument("src")
ap.add_argument("--out", required=True)
Expand Down Expand Up @@ -19874,6 +19875,10 @@ def main():
help="descriptor table entry layout: 'tagged' also carries each image's array kind, recorded as "
"descriptor_table in the module meta (default: tagged; 'plain' is the old layout, for a "
"library that keeps the runtime's old behaviour)")
ap.add_argument("--loop-total", type=spirv_loop_guard.parse_limit, default=spirv_loop_guard.DEFAULT_TOTAL,
metavar="N",
help="the most visits all the loops of an invocation make together, on top of each loop's own "
"limit, so nested loops cannot multiply it (default %(default)s; 0 = none)")
ap.add_argument("--loop-limit", type=spirv_loop_guard.parse_limit, default=spirv_loop_guard.DEFAULT_LIMIT,
help="maximum visits to each loop header, including dispatch loops (default %(default)s, 0 disables)")
ap.add_argument("--max-structured-depth", type=_depth_arg, default=MAX_STRUCTURED_DEPTH, metavar="N",
Expand Down Expand Up @@ -19905,6 +19910,7 @@ def main():
DESCRIPTOR_HASH = a.descriptor_hash
DESCRIPTOR_TABLE = a.descriptor_table
LOOP_LIMIT = a.loop_limit
LOOP_TOTAL = a.loop_total
MAX_STRUCTURED_DEPTH = a.max_structured_depth
global STRUCTURED, WAVE64_EMULATE, WAVE64_GRAPHICS, BARY_FALLBACK, TEXEL_OFFSET_FALLBACK, MESH_COMPUTE, FMA_KHR, SHADER_CLOCK, F16_HALVES, OPT_SPIRV
global PC_TAIL_UBO
Expand Down
Loading
Loading