Skip to content

Translator: structured --wave64-emulate and acyclic single-write execz folding (#884) - #2089

Open
edwin042331-hue wants to merge 4 commits into
ItsNotRexed:mainfrom
edwin042331-hue:perf/wave64-emulate-structured
Open

edwin042331-hue wants to merge 4 commits into
ItsNotRexed:mainfrom
edwin042331-hue:perf/wave64-emulate-structured

Conversation

@edwin042331-hue

Copy link
Copy Markdown
Contributor

Follow-up to #1904 and #1905 targeting the remaining --wave64-emulate OpSwitch blow-up on Issue #884 (the ~11,150 cases remaining in cs_screenprobes_activate / cs_screenprobes_target and ~1,727–1,795 cases in #22496 / #21097 after #1905).

Stacking note: Built on top of #1904 (iterative flat cfg_structure) and #1905 (tools/wave64_emulate_opt.py), which are required so multi-thousand-block emulated CFGs structure iteratively at O(1) depth without hitting Python's recursion limit. Once #1904 and #1905 land, I will rebase this PR onto main so the diff contains only the PR 3 commits.

What changes

  1. Acyclic single-write-per-domain s_cbranch_execz folding (tools/wave64_emulate_opt.py, tools/rdna2spirv.py):
    • Relaxes find_local_exec_folds so an acyclic lane-local s_cbranch_execz/execnz region may contain an EXEC-masked store/atomic (buffer_store*, tbuffer_store*, global_store*, flat_store*, image_store*, ds_write*, *_atomic*) when that instruction is the sole access to its memory domain ("mem" or "lds") inside the region.
    • Emits any required x_memory_order split/barrier in uniform control flow before if (%active) (handling WAR/WAW/RAW) and records (kind, "w") after the merge label, with zero splits/barriers inside divergent control flow (asserted at translate time).
  2. Structured --wave64-emulate emission (plan_structured_emulation, control_flow = "emulated wave64 structured"):
    • Eliminates the giant global K_{1,N} round-loop OpSwitch on multi-superblock reducible wave64 compute/mesh CFGs (when no wave64 32-bit half-mask scc_nonzero writes live SCC; straight-line / single-superblock shaders stay on x_scheduler):
    • Single-wave (<= 64 threads, mode = "inline_all"): All wave-uniform branches are workgroup-uniform, so the entire post-fold cfg_structure tree emits inline with direct OpControlBarriers (0 OpSwitch cases, 0 x_spill variables, 0 scheduler OpAtomicIAdds) and an exact 4-bit forward dirty_in fixed point ordering cross-block and loop-carried RAW/WAR/WAW hazards.
    • Multi-wave (> 64 threads, mode = "structured_hybrid"): When no non-top-level guard/loop contains s_barrier (divergent s_barrier like cs_barrier_divergent falls back cleanly to "emulated wave64 rounds"), unwraps post-dominating spine guards whose predecessors are already emitted, runs top-level spine blocks and barrier-free guards/loops (including live-out scalars, single-write stores, EXEC-widening, s_cbranch_vccz/nz, and read-only s_cbranch_scc loops) inline with 0 OpSwitch, and isolates any remaining wave-divergent barrier regions into tiny local x_mini_scheduler loops (or a tail_scheduler at early s_endpgm).
  3. Contract docs & build cache (docs/design.md, make_game.py):
    • Adds wave64_emulate_opt.py to make_game.TRANSLATION_SOURCES (fixing tests/test_shader_stage_resume.py).
    • Updates docs/design.md (Wave64 emulation (--wave64-emulate) row).

Verification (CPU-only; no local spirv-val, llvm-mc, GPU harness, or game files)

  • python -I tests/semantic/test_wave64_emulate_opt.py -v: 18/18 OK (adds single-store WAR/RAW ordering on 64 & 128 threads, 64- & 40-thread partial-wave inline_all with 0 OpSwitch and loop-carried WAR, 128-thread structured_hybrid with inline sync-free live-out scalar + local mini_scheduler + top-level s_barrier cross-wave LDS exchange bit-exact vs baseline, and multi-wave divergent s_barrier fallback).
  • python -I -m unittest discover -s tests/semantic -p "test_*.py": 1,662 passed, 0 failed (skipped=2).
  • python -I tests/semantic/test_w64x_scalar_load_order.py -v: 5/5 OK; tests/semantic/test_valu_permlane16.py: 16/16 OK; tests/test_shader_stage_resume.py: 39/39 OK; tests/test_split_big_switch.py: OK (1 skipped, no spirv-as).
  • python -I tools/cf_diff.py --programs 50 --seed 1 --wave 64: 50/50 pass, 0 mismatch.
  • 120-program random wave64 A/B differential fuzzer across 40 (partial wave), 64, 128, and 256 threads (mixing loads, single/multi stores, live-out scalars, vccz, wave-divergent v_readlane/loops, top-level s_barrier, and early s_endpgm) + structural SPIR-V SSA/CFG/OpPhi checker: 120/120 bit-identical vs baseline x_scheduler, OpSwitch cases 4,149 -> 318 (-92.3%), dynamic barriers 3,503 -> 1,431 (-59.1%).
  • 15/15 wave64 compute fixtures in tests/semantic/fixtures/disasm/: 15/15 A/B bit-identical.
  • Synthetic worst-case 2,000-step ScreenProbes-shaped shader (500 loads + 500 single stores + 500 un-foldable live-out scalars + 500 if/else diamonds):
    • 64 threads: OpSwitch cases 2,002 -> 0, x_spills = 0 (1.37 s translate).
    • 128 threads (multi-wave): OpSwitch cases 2,002 -> 0, x_spills = 0 (1.66 s translate).
  • Not verified locally: spirv-as/spirv-val, llvm-mc, GPU execution, or real game corpus modules (cs_screenprobes_activate, cs_screenprobes_target, #22496, #21097).

Claimed in #1902. AI-assisted.

@ElsCiber

Copy link
Copy Markdown

GPU check of #2089 on NVIDIA Turing (32-wide subgroups): no regressions; the 7 shaders that switch to the new structured path all pass. AI-assisted.

  • GPU: NVIDIA GeForce GTX 1660 SUPER, 6 GB (Turing, subgroup 32..32), driver 621.14 (Vulkan 1.4.357)
  • CPU: AMD Ryzen 5 3600
  • OS: Windows 11 Pro 26300
  • Tools: llvm-mc 23.1.6 (conda-forge llvm-tools), Vulkan SDK 1.4.363.0, MSVC (VS Build Tools 2022), Python 3.14.6
  • PR head 1a40ad22, base main at 4eb6155 (an ancestor of the head). The PR changes nothing under runtime/ or scripts/, so both runs use test programs built from 4eb6155.

python -I scripts/run_gpu_tests.py:

run translated / spirv-val result
main, LEONIDA_W64_EMULATE unset 185 / 185 136/180 passed, 44 skipped, 0 failed
#2089, LEONIDA_W64_EMULATE unset 185 / 185 136/180 passed, 44 skipped, 0 failed
main, LEONIDA_W64_EMULATE=1 185 / 185 167/180 passed, 13 skipped, 0 failed
#2089, LEONIDA_W64_EMULATE=1 185 / 185 167/180 passed, 13 skipped, 0 failed

Every test has the same status on main and on the PR in both modes. With emulation on, control_flow in spirv/index.json moves 7 shaders from emulated wave64 rounds to emulated wave64 structured: cs_w64x_branch, cs_w64x_mask_reuse2, cs_w64x_sbarrier, cs_w64x_wg128_branches, cs_wm_half_ops, cs_wm_scc_rfl and cs_bench_mix. All six that check.py judges pass; cs_bench_mix is a benchmark shader with no check. Without emulation the 30 wave64 compute tests skip, as docs/testing.md expects on 32-wide hardware.

CPU checks on the PR head: tests/semantic/test_wave64_emulate_opt.py 19/19 OK, tests/test_cfg_structure.py OK (18228 graphs). The full tests/semantic suite passes on main (1671 tests, 2 skipped); I didn't run the full suite again on the PR head.

Not covered: game-corpus shaders (cs_screenprobes_* and the others in #884). No game files were used.

@CharlyRien

Copy link
Copy Markdown

Code review of 1a40ad2 (first read at 4d9ef4e, the bug reproduces on both), AI-assisted. Checked on the repo's semantic interpreter (tests/semantic) against the base commit's emulation, with synthetic RDNA2 programs only.

1. s_cmovk_i32 is missing from _SCC_IMPLICIT_READS, so SCC is treated as dead before it, and wave64 emulation gives wrong results (proved).

tools/wave64_emulate_opt.py: _SCC_IMPLICIT_READS lists s_cselect_*, s_cmov_b32/b64, s_addc/subb and the SCC branches, but not s_cmovk_i32. The translator does read %scc for it (rdna2spirv.py, the op in ("s_cmov_b32", "s_cmovk_i32") branch), and tests/semantic/test_salu_cmov.py documents that read. Two consequences:

  • scc_live_outs sees SCC as dead before an s_cmovk_i32, so scc_from_mask returns early, a 64-bit mask op emits no cross-half vote, and s_cmovk reads a stale SCC:
    s_mov_b32 s14, 222
    v_cmp_eq_u32_e64 s[10:11], 50, v0
    s_and_saveexec_b64 s[12:13], s[10:11]   ; SCC = 1 on hardware (lane 50 active)
    s_cmovk_i32 s14, 0x6f
    s_mov_b64 exec, -1
    v_mov_b32 v5, s14  ; store v5 per lane
    
    64 threads, --wave64-emulate, lanes 0–3, 50, 63:
    • this PR: [222, 222, 222, 222, 222, 222] (0 OpAtomicOr votes)
    • base 6a6704df: [111, 111, 111, 111, 111, 111] (1 vote), which matches hardware
  • _scalar_liveness uses the same reads_scc, so an execz fold is accepted even when the region writes SCC and an s_cmovk_i32 reads it after the join. Lanes that skipped the region keep their own SCC, and one wave ends up with two values in a scalar register:
    s_cmp_eq_u32 s14, 222                    ; SCC = 1
    v_cmp_lt_u32_e64 s[6:7], 40, v0
    s_and_saveexec_b64 s[8:9], s[6:7]
    s_cbranch_execz SKIP
    s_cmp_eq_u32 s14, 0                      ; SCC = 0 inside the region
    ...
    SKIP: s_mov_b64 exec, -1
    s_cmovk_i32 s14, 0x6f
    
    Hardware runs the region (lanes 41–63 are active), so s14 = 222 everywhere. With this PR at 64 and 128 threads, lanes 0–40 get 111 and lanes 41–63 get 222. Base: 222 everywhere.

Fix: add s_cmovk_i32 to _SCC_IMPLICIT_READS. A test that iterates over every opcode the translator reads %scc for would keep the two lists in sync.

2. Verification notes (minor):

  • tools/cf_diff.py --wave 64, cited as verification, only generates ps_cf_* pixel shaders and never passes --wave64-emulate, so it doesn't exercise this PR.
  • test_multiwave_structured_hybrid_* compares the new path with the old emulated scheduler, not with values derived from the ISA.
  • The interpreter runs invocations in index order between barriers, so a missing ordering barrier only shows up in some lane orders.

Checked and found correct (with the fix above aside):

  • EXEC stays off in folded regions: the saveexec, wrexec, s_and/andn2/or/xor/mov_b64 and v_cmpx "zero pairs" cases, with widening forms rejected.
  • Fold blockers: cross-lane ops, mask_writes VGPR stores, s_buffer_atomic, scalar stores, exp, s_sendmsg, divergent execnz loops, s_endpgm in the region, and a scalar live at the join.
  • Memory ordering around a fold.
  • All 20 SCC writers checked really write %scc.
  • The 3-slot mask ring and parity data slots across mixed inline/mini-scheduler rounds.
  • The multi-wave fallbacks (nested s_barrier, early s_endpgm).

Differential fuzz, PR vs base emulation: about 2,900 random programs at 40, 64 and 128 threads (execz folds, other-half loads, LDS, v_readlane, scalar loops, top-level barriers, wave-divergent branches, vccz, s_load, returning atomics, s_cselect after mask ops, v_cmpx, early s_endpgm), with 0 mismatches. s_cmovk_i32 wasn't in the generator. Not run: 192 threads, and the GPU suite for this head.

@Faterek

Faterek commented Nov 22, 2026

Copy link
Copy Markdown
Contributor

Tested 1a40ad2 on AMD Radeon RX 9070 XT (RADV GFX1201), Mesa 26.2.6-arch3.1, Linux 7.3.4-1-cachyos: pass (GPU tests + spirv-val on real emulated wave64 compute shaders; note RADV pipeline compile time below).

  • python3 -I tests/semantic/test_wave64_emulate_opt.py -v: 18/18 passed.
  • LEONIDA_W64_EMULATE=1 python3 -I scripts/run_gpu_tests.py: 167/167 passed (13 skipped), all translated shaders pass spirv-val.
  • Real 1.0.2.1 corpus (--wave64-emulate, counts and timings only, no shader names or text):
    • Largest emulated wave64 CS (31,055 KiB disasm): control_flow='emulated wave64 structured', 0 OpSwitch / 0 cases, 47,048 KiB .spv, translate 6.84s, spirv-as 2.13s, spirv-val PASS (4.93s). (Single-threaded vk_pipeline_check on RADV timed out at 180s on this 47 MiB module, which is expected given RADV's multi-minute compile time on this size in RADV 27.0.0-devel SIGFPEs on two wave64-emulated compute shaders (vfx_proj_decal_hit_detection) #1721.)
    • Second largest emulated wave64 CS (9,709 KiB disasm): control_flow='emulated wave64 structured', 0 OpSwitch / 0 cases, 3,838 KiB .spv, translate 0.97s, spirv-as 0.24s, spirv-val PASS (0.74s).

AI-assisted.

@Thatters

Copy link
Copy Markdown
Contributor

Full-corpus translation check on my own 1.0.2.1 copy: no regression in translated or spirv-val counts. These are from 4d9ef4eb against its base 6a6704df, both --wave64-emulate; your head is now 1a40ad22, with the conflict fix and the transfer_superblock change on top.

base 6a6704df #2089 4d9ef4eb
translated / pass spirv-val 26,487 / 26,487 of 26,503 26,487 / 26,487
per-shard totals (6 shards) identical identical
entries only on one side 0 0
control_flow changed 799 cs: emulated wave64 rounds → emulated wave64 structured (no other stage)
byte-identical .spv 5,281; 21,206 differ
wall time, 6 shards each, both runs side by side 2,601 s 2,359 s
  • The 16 modules that don't translate are the same 16 on both sides.
  • The 21,206 changed modules are presumably cfg_structure: make structuring iterative and flatten dominated tail continuations #1904's iterative structuring re-ordering blocks well beyond the 799. That's harmless for correctness by these counts, but it means every existing pipeline cache misses after this lands, so the next pipelines stage on any machine recompiles almost everything. That may be worth a line in the PR description.
  • The one module I compiled from these 799, the larger giant, compiles on NVIDIA now (2,667 s, 12.0 GB peak, on #884). The other 798 aren't compiled here yet. @CharlyRien's semantic finding above is a separate correctness question that counts can't catch.

AI-assisted; counts only, no game data.

@ElsCiber

Copy link
Copy Markdown

@edwin042331-hue this now conflicts with main (49475796) in two places. I resolved them locally by keeping both sides, and the merge still passes on the GTX 1660 SUPER. AI-assisted.

tools/rdna2spirv.py, after g.bar_rounds = needs_barrier_rounds(...): main added g.fit_shared_memory() (SHADER-309). I kept your folds / plan_structured_emulation block and put g.fit_shared_memory() right after it, before g.x_seg = .... fit_shared_memory only reads x_buf_bytes() (sized from x_sizes()), and the plan doesn't read the LDS size, so the order between the two doesn't matter.

docs/design.md: main's Wave64 emulation (--wave64-emulate) row is your row's text without your additions (the merged-row cleanup), so I kept your row as it is. main also adds a new Workgroup memory limit (SHADER-309) row right after it, and I kept that too.

Checks on the merged tree, with the runtime rebuilt from it (GTX 1660 SUPER, driver 621.14, Windows 11 Pro 26300, llvm-mc 23.1.6, Vulkan SDK 1.4.363.0):

  • run_gpu_tests.py: 190 / 190 translated and spirv-val-valid. LEONIDA_W64_EMULATE=1: 170/185 passed, 15 skipped, 0 failed. Default: 139/185 passed, 46 skipped, 0 failed.
  • The same 7 shaders take emulated wave64 structured, and the 6 that check.py judges pass.
  • The 2 extra skips compared with my earlier run (ps_m2_array, ps_m3_query) are new tests from main that the d3d12_* ctest programs run.
  • tests/semantic/test_wave64_emulate_opt.py, tests/test_cfg_structure.py and tests/semantic/test_cs_shared_memory_limit.py: OK.
  • python -m unittest discover -s tests/semantic on the merged tree: 2586 tests, OK (3 skipped).

@edwin042331-hue

Copy link
Copy Markdown
Contributor Author

Thanks @CharlyRien, @ElsCiber, @Faterek, and @Thatters for the thorough reviews, GPU runs (GTX 1660 SUPER & RX 9070 XT), 2,900-program differential fuzzing, and full 26,503-shader corpus verification!

Pushed 0c3774ab (and 5131dece / 355e67cb on #1905):

  1. s_cmovk_i32 implicit SCC read (@CharlyRien): Added "s_cmovk_i32" to _SCC_IMPLICIT_READS in tools/wave64_emulate_opt.py. Also audited all %m0 and %vcc loads in tools/rdna2spirv.py and added "v_movrel", "v_swaprel" to _scalar_rw's implicit M0 read set.
  2. Sync guard & tests (@CharlyRien):
    • Added test_s_cmovk_i32_keeps_scc_live_and_blocks_execz_fold (covering both the s_and_saveexec_b64 -> s_cmovk_i32 vote case and the 64/128-thread s_cbranch_execz fold blocker, plus a static sync check verifying that every s_* opcode loading %scc in tools/rdna2spirv.py satisfies wave64_emulate_opt.reads_scc()).
    • Added test_m0_implicit_read_in_v_movrel_blocks_execz_fold.
    • Added reverse_order=True execution to run_emulated_workgroup and direct ISA-derived expected-value checks across all 128 lanes in test_multiwave_structured_hybrid_zero_switch_and_local_mini_scheduler (21/21 unit tests pass).
  3. Merged main (ec8ec4c9, @ElsCiber): Resolved the tools/rdna2spirv.py (g.fit_shared_memory()), docs/design.md (SHADER-309 row), and make_game.py (TRANSLATION_SOURCES) conflicts cleanly on both Translator: elide dead SCC votes and fold safe lane-local execz regions under --wave64-emulate (#884) #1905 and Translator: structured --wave64-emulate and acyclic single-write execz folding (#884) #2089.

AI-assisted.

@Proudnoob4

Copy link
Copy Markdown
Contributor

RTX 4080 / NVIDIA 621.01: the larger giant still fails to compile at 0c3774ab under a 24 GiB cap. AI-assisted; counts only, no game data.

Setup: GeForce RTX 4080 (Ada, 16 GB), driver 621.01, Windows 10 22H2 (19045), 32 GB RAM. I translated the two ScreenProbes giants from my own 1.0.2.1 copy with --wave64-emulate. Pipeline creation used vk_pipeline_check from bb2e1842 with --jobs 1, one module per process and no cache file. A job object caps the checker's committed memory, because an uncapped compile of main's form pushed this machine to 109.6 GB of system commit (#884).

PR head module translation cap result wall peak commit
1a40ad22 larger (ActivateProbes) spirv-val pass, 0 OpSwitch, 4,090 barriers 16 GiB NVVM compilation failed: 3 1,313 s 16.00 GiB
1a40ad22 smaller (ActivateProbesTarget) spirv-val pass, 0 OpSwitch, 4,073 barriers 16 GiB NVVM compilation failed: 3 1,321 s 16.00 GiB
0c3774ab larger spirv-val pass, 0 OpSwitch, 4,090 barriers, 47.7 MB 24 GiB NVVM compilation failed: 3 1,905 s 24.00 GiB

Each run reached its cap, then NVVM reported the failure (checker exit 1, no crash). On this GPU and driver, the structured form still needs more than 24 GiB for the larger giant, and memory climbs early. The 1a40ad22 runs reached 16 GiB within 22 min, and one sample at 0c3774ab showed 11.7 GiB private after 328 s of checker CPU time. @Thatters measured the opposite curve on RTX 5070 Ti / 621.24 at 4d9ef4eb: about 3 GB for 30 min, a 12.0 GB peak, and a successful compile. The difference could be the driver (621.01 vs 621.24), the architecture (Ada vs Blackwell) or the revision. I can't separate them on this machine. Uncapped behaviour here is unmeasured.

The smaller giant at 0c3774ab is queued under the same cap; I'll add its result. When the helper-OpFunction version of the x_round sequences is pushed, I can run it the same way.

@edwin042331-hue
edwin042331-hue force-pushed the perf/wave64-emulate-structured branch from bc9fb7b to de5d616 Compare November 22, 2026 20:04
@edwin042331-hue

Copy link
Copy Markdown
Contributor Author

@Proudnoob4 @Thatters Pushed 1551d2cc (merged with main at de5d616a) with the helper-OpFunction outlining and two structural reductions targeting the remaining NVVM SROA/Mem2Reg memory and compile-time bottleneck on the two ScreenProbes giants:

  1. Known-%pc post-dominating spine-guard unwrapping (_unwrap_known_pc_guards in tools/wave64_emulate_opt.py):
    • Previously, inline_all (x_lanes == 64, used by both cs_screenprobes_activate and cs_screenprobes_target) passed cfg_structure.structure's tree directly to place_structured without unwrapping post-dominating spine guards ("guard", g, ...) (nor did structured_hybrid unwrap spine guards inside loops or nested regions).
    • Because %pc is a Function-scope OpVariable, LLVM/NVVM's SROA/Mem2Reg promotes %pc in the same pass as %vgpr[0..255] and %sgpr[0..127], before if (%pc == g) can be constant-folded. Every wrapped spine block therefore appeared to Mem2Reg as a 2-predecessor diamond merge point across a convergent OpControlBarrier, forcing ~384 redundant Phi nodes at every spine join block (~1M+ redundant Phi nodes across the ~3,000+ spine blocks in ScreenProbes).
    • _unwrap_known_pc_guards tracks the exact finite set of values %pc can hold before each tree item (including early-s_endpgm sentinels) and unwraps any ("guard", g, body) where cur_pc == {g} at top level, inside loops, and inside nested guards.
  2. Barrier-free helper OpFunction outlining for inline x_round pre-barrier setup (Gen._ensure_x_pre_fn in tools/rdna2spirv.py):
    • Outlines the ~20-30 instructions of ring-buffer slot clearing (sn = (it + 1) % 3), mask/data slot indexing, and pre-barrier %x_buf store / OpAtomicOr into module-level helper functions (%x_pre_vote_fn, %x_pre_data_fn, %x_pre_mask_fn, %x_pre_both_fn) while keeping OpControlBarrier directly at the callsite in %main (so NVVM's convergent-barrier legalization does not force-inline the helper back into %main).
    • Specializes single-wave workgroups (w == 1, x_lanes == 64) where %x_wave == 0 and %x_wbase == 0, and drops the dead high-word mask load on 1-bit g_vote exchanges, shrinking each g_vote / g_shuffle callsite in %main from ~31 instructions to 7-8 instructions.
  3. Align _classify_block_body with Gen.x_memory_order:
    • Read-only image_sample*, image_gather*, and image_bvh* queries (which Gen.x_memory_order does not order against buffer/image stores) no longer increment mem_ops in _classify_block_body, allowing acyclic single-store s_cbranch_execz regions that also sample a texture or intersect a BVH node to fold inline behind if (%active).

Measured Impact & Verification

  • On the 2,000-step ScreenProbes benchmark (inline_all, 64 threads, 500 live-out scalar diamonds + v_readfirstlane_b32), OpSelectionMerge count drops by 500 (all 500 post-dominating spine guards unwrapped), OpLabel count drops by 1,000, and the assembled .spv binary (tools/spirv_asm.py) shrinks by ~20,000 words.
  • Locally verified (CPU + tools/spirv_asm.py, no spirv-val/llvm-mc/corpus on this machine):
    • python -I -W error::ResourceWarning tests/semantic/test_wave64_emulate_opt.py: 22/22 PASS (including test_known_pc_guard_unwrap_and_x_pre_helper_functions with inline OpFunctionCall expansion in the lockstep workgroup interpreter and binary spirv_asm.assemble check)
    • 120-program wave64 differential fuzzer (40/64/128/256 threads) & 15/15 wave64 compute fixtures: 100% bit-exact

AI-assisted.

@Proudnoob4

Copy link
Copy Markdown
Contributor

@edwin042331-hue I'm testing de5d616a on the RTX 4080 / 621.01 now, with the same setup as above: each module alone, 24 GiB cap, larger giant first. While it compiles, here are the structural counts for the real modules from my 1.0.2.1 copy (--wave64-emulate, all pass spirv-val):

ActivateProbes 0c3774ab ActivateProbes de5d616a Target 0c3774ab Target de5d616a
bytes 47,734,780 44,278,236 (−7.2%) 47,532,068 44,080,916 (−7.3%)
OpFunction / OpFunctionCall 3 / 3,311 5 / 7,395 3 / 3,296 4 / 7,367
OpLabel 38,486 38,478 38,105 38,096
OpSelectionMerge 12,760 12,755 12,600 12,595
OpPhi 16,486 16,486 16,465 16,465
OpControlBarrier 4,090 4,090 4,073 4,073

On the real giants, the known-%pc guard unwrap removes only 5 OpSelectionMerge and 8-9 OpLabel each. Your 2,000-step benchmark showed 500 and 1,000. The size drop comes from the x_round outlining. If the unwrap is meant to reach the ~3,000 spine blocks here, the real trees probably don't match the benchmark's shape.

#2089 also moves the two #884 InstanceCulling BatchCull CS from emulated wave64 rounds to structured: 2 → 725 / 844 OpControlBarrier, and OpVariable 725 / 826 → 25 / 26. Their compiles are queued after the giants. AI-assisted; counts only.

@edwin042331-hue

edwin042331-hue commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor Author

@Proudnoob4 Great catch on those structural counts (12,760 -> 12,755 OpSelectionMerge) — your table immediately pinpointed why _unwrap_known_pc_guards only reached 5 guards on the real giants at de5d616a:

  • In #1904, cfg_structure.structure hoists the post-dominating spine continuation below[-1] ((guard, g_next, ...)) of a guarded block out into the enclosing parent_list to keep nesting flat.
  • Whenever a shader (or a natural loop header) starts with an early-exit branch (e.g. 0 -> {1, B_end} or a loop header h -> {body, loop_exit}), the enclosing list (root or lbody) has skip_pc = {B_end} (or {loop_exit}).
  • At de5d616a, (guard, 1, gbody_1) closed as soon as gbody_1's local items finished, unioning its singleton exit {g_next} with skip_pc ({g_next, B_end}) in parent_list before inspecting the hoisted (guard, g_next, ...) in parent_list. That kept B_end / loop_exit in cur_pc across every hoisted spine guard in root and inside every header-exit loop, preventing all of them from unwrapping.

Pushed 70e739fd adding guard-spine coalescing at the end of a guard frame in _unwrap_known_pc_guards: when a guard g finishes its body with a singleton cur_pc == {nxt_g} and the next item in parent_q is the hoisted (guard, nxt_g, nxt_body) with nxt_g not in skip_pc, nxt_body is pulled directly into g and unwrapped in place (since nxt_g not in skip_pc proves nxt_g is unreachable when g was skipped, and cur_pc == {nxt_g} proves nxt_g always runs when g was taken). On an early-exit + 200-diamond chain (and header-exit loop), that drops the spine guards from 0 unwrapped at de5d616a to 100% unwrapped while keeping nesting depth flat (depth = 2).

Verified locally with test_wave64_emulate_opt.py (22/22 OK) and the 120-program wave64 workgroup fuzzer (120/120 bit-identical). AI-assisted.

@Proudnoob4

Copy link
Copy Markdown
Contributor

@edwin042331-hue Two results on the RTX 4080 / 621.01 (each module alone, 24 GiB cap). AI-assisted; counts only.

de5d616a (outlining only), larger giant: NVVM compilation failed: 3 at the cap after 1,781 s (0c3774ab: 1,905 s). So the outlining alone doesn't get it under 24 GiB here.

70e739fd: the coalescing works on the real giants. All four modules pass spirv-val:

de5d616a 70e739fd change
ActivateProbes OpSelectionMerge 12,755 9,800 −2,955
ActivateProbes OpLabel 38,478 32,568 −5,910
ActivateProbes bytes 44,278,236 44,018,196 −0.6%
Target OpSelectionMerge 12,595 9,648 −2,947
Target OpLabel 38,096 32,202 −5,894
InstanceCulling Prop / Tree OpSelectionMerge 1,101 / 1,299 977 / 1,148 −124 / −151

That's about 2,950 spine guards unwrapped per giant (two labels each), in line with your ~3,000 estimate. OpPhi in the SPIR-V is unchanged (16,486 / 16,465), as expected, since the saving you're after is in NVVM's Mem2Reg. The 70e739fd larger-giant compile started at 20:39 UTC. If the memory curve doesn't change, it would reach the cap around 21:10. The smaller giant and both InstanceCulling modules follow.

@Proudnoob4

Copy link
Copy Markdown
Contributor

@edwin042331-hue 70e739fd, larger giant, RTX 4080 / 621.01, alone with a 24 GiB cap: NVVM compilation failed: 3 at the cap after 1,940 s. AI-assisted; counts only.

head change larger giant
0c3774ab structured, 0 OpSwitch cap after 1,905 s
de5d616a + x_round outlining (−7.2% size) cap after 1,781 s
70e739fd + spine-guard coalescing (−2,955 OpSelectionMerge) cap after 1,940 s

So on this card and driver, neither reduction changes the outcome; the time to the cap stays within about 8%. Memory also climbs early here: one 0c3774ab sample was already 11.7 GiB after 328 s of checker CPU time. @Thatters measured about 3 GB for the first 30 min on RTX 5070 Ti / 621.24. That points at the driver or the architecture more than at the module. An Ada card on 621.24, or a Blackwell card on 621.01, would separate the two.

The smaller giant at 70e739fd is compiling now, and I'm sampling its memory every 30 s (8.64 GiB at 6 min). I'll post the curve. It can be compared with 0c3774ab, which I stopped at 15.83 GiB after 19 min.

@Proudnoob4

Copy link
Copy Markdown
Contributor

RTX 4080 / NVIDIA 621.01 / Windows 10 19045, translator 70e739fd, checker bb2e1842. One pipeline per process, no cache file, 24 GiB process-commit cap. AI-assisted; counts only.

Smaller ScreenProbes pipeline: spirv-val passed and the module has zero OpSwitch, but pipeline creation failed with NVVM compilation failed: 3 (exit 1) after 1,996 s, at 24.00 GiB peak commit. The private-memory sampler started at 363 s: 8.64 GiB at 363 s, 11.95 at 1,143 s, 16.51 at 1,803 s, and 24.00 at 1,983 s. The 0c3774ab run was manually stopped at about 19 min (15.83 GiB private), so there is no completed A/B for that revision. Both giants fail individually at the cap on this setup; uncapped behavior at 70e739fd is unmeasured.

InstanceCulling BatchCull is a different story. Same input shaders and checker, each compiled alone:

Pipeline bb2e1842 translation 70e739fd translation
Prop pass, 612 s / 10.79 GiB pass, 8 s / 0.30 GiB
Tree pass, 932 s / 19.64 GiB pass, 11 s / 0.41 GiB

These are pipeline-creation times and peak process commit, not shader execution or output-correctness tests. The two older isolated peaks do not establish that the peaks overlapped or caused the 8-job failure in #884.

ItsNotRexed added a commit that referenced this pull request Nov 22, 2026
# Conflicts:
#	docs/design.md
dev-ewann pushed a commit to dev-ewann/Leonida that referenced this pull request Nov 22, 2026
- shader_disasm: prune stale listings against every input, not the --skip-existing remainder (a resumed run
  deleted every listing it had just reused).
- progress_dashboard: a drive-letter path is never inside the repository off Windows (it printed user names);
  its own read_text helper is read_utf8, so the encoding check does not take it for pathlib's.
- Translator tests follow this round's rules: desc_lookup's BroadcastFirst in the typed-load condition walker;
  resinfo sizes are 0 past the last level and a 2D depth word is 0 (SHADER-388); SHADER-315 constant folding in
  the perm and i16 tests; ItsNotRexed#2089's structured wave64 emulation.
- test_semantic_translator_use: 57 oracle-only files merged before it are DEBT; test_spirv_tools_required is
  allowed (CI meta-test).
- Test fixes: image_fuzz fake writes the programs, preflight follows c506d00's loader hint rule, feature_scan
  reads the first line of a pytest-decorated message, w64_graphics wording.
- docs: rows merged again in design.md, README.md, d3d12_vulkan.md; GameInput table rebuilt from ItsNotRexed#3172's rows;
  orphan rows in models.md and embedded_shaders.md; repeated bullets; anchors; a flag not on main.
- Repo rules: stdout guard on 14 programs; LF writes; csv lineterminator in bink_play.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@edwin042331-hue

Copy link
Copy Markdown
Contributor Author

Thank you @Proudnoob4 for the A/B measurements on InstanceCulling_CS_{Prop,Tree}_BatchCull and the memory-sampler trace on the two ScreenProbes giants (70e739fd)!

Seeing the two InstanceCulling pipelines from #884 drop by 76.5x – 84.7x in compile time and 36x – 48x in peak RAM:

  • InstanceCulling_CS_Prop_BatchCull: 612 s / 10.79 GiB -> 8 s / 0.30 GiB
  • InstanceCulling_CS_Tree_BatchCull: 932 s / 19.64 GiB -> 11 s / 0.41 GiB

and seeing the hoisted guard-spine coalescing unwrap 2,955 OpSelectionMerges (-5,910 OpLabels) in ActivateProbes and 2,947 (-5,894 OpLabels) in ActivateProbesTarget confirmed the CFG side works as designed.

Why ActivateProbes still hit the 24 GiB cap on RTX 4080 (621.01): the 3,281 dynamic buffer_load_format_* callsites (16,405 of 16,486 OpPhis in %main)

Cross-referencing your structural table (OpFunction / OpFunctionCall = 3 / 3,311, OpPhi = 16,486 / 16,465, OpSelectionMerge = 9,800 / 9,648, OpLabel = 32,568 / 32,202) pinpointed where the remaining bulk of %main's SSA web comes from:

  • ActivateProbes has 3,281 dynamic-format buffer_load_format_* callsites (3,266 in ActivateProbesTarget).
  • main (aa2988cc, merged here in 09c2b895) replaced the two per-load FORMATS byte-size select loops with %fmt_size_tab, cutting the module from 52.4 MB to 29.8 MB on main.
  • However, even after %fmt_size_tab, every single one of those 3,281 dynamic buffer_load_format_* callsites still inlined into %main:
    1. 1 OpSelectionMerge, 2 OpLabels (_do / _end), 5 PSB OpLoads, and 5 OpPhis (3,281 x 5 = 16,405 OpPhis — 99.5% of all 16,486 OpPhis in ActivateProbes — plus 6,562 basic blocks in %main),
    2. the 4-dword byte-shift unpack window, _FLOAT_FMT_MASKS lookup, in_b component masking, 4-channel DST_SEL swizzle, and (for d16 loads) is_signed / is_norm / is_f32 / saturate_int16 / d16_norm_f16 narrowing (~125 instructions per f32 callsite, ~450 per d16 callsite), and
    3. the ~85-instruction runtime-V# buffer_address(elem=fmt) swizzled address + 4-mode OOB_SELECT bounds check.

What 5f1a95b8 does

  1. Outlines the dynamic buffer_load_format body (fixed_fmt is None) into %buf_load_fmt_f32_fn and %buf_load_fmt_d16_fn:
    • Takes (%ulong addr, %uint d3, %uint in_b_u, %uint cond_u) -> %v4uint_fmt.
    • For 32-bit loads (%buf_load_fmt_f32_fn), returns (out0, out1, out2, out3).
    • For d16 loads (%buf_load_fmt_d16_fn), returns (h0, p01, h2, p23) so d16_x, d16_xy, d16_xyz, and d16_xyzw each extract 1 or 2 components at the callsite with write_lo16 / dst.
  2. Outlines runtime-V# (lit1 is None and lit3 is None) buffer_address(elem=fmt) + load dispatch into %buf_load_fmt_rsrc_{f32|d16}_{idx}_{soff0}_fn:
    • Collapses each of the 3,281 dynamic buffer_load_format_* callsites in %main to a single OpFunctionCall (~15 instructions at the callsite instead of ~240–530).
    • Eliminates 16,405 OpPhis (16,486 -> ~81, -99.5%), 3,281 OpSelectionMerges (9,800 -> ~6,519, -33.5%), and 6,562 OpLabels (32,568 -> ~26,006, -20.1%) from %main in ActivateProbes (and 16,330 OpPhis / 3,266 OpSelectionMerges / 6,532 OpLabels in ActivateProbesTarget).

Verification

  • python -I -W error::ResourceWarning tests/semantic/test_wave64_emulate_opt.py — 23/23 PASS (including test_dynamic_buffer_load_format_outlining, lockstep 64-lane workgroup execution across f32, uint, d16_x, d16_xyz, d16_xyzw, OOB DST_SEL=1, and binary assembly via tools/spirv_asm.py)
  • python -I -W error::ResourceWarning tests/semantic/test_buffer_load_format.py — 34/34 PASS
  • python -I -W error::ResourceWarning tests/semantic/test_buffer_oob_dst_sel.py — 5/5 PASS
  • python -I -W error::ResourceWarning tests/semantic/test_buffer_format_narrow_int.py — 3/3 PASS
  • python -I -W error::ResourceWarning tests/semantic/test_buffer_tbuffer_format_d16.py — 7/7 PASS
  • python -I -W error::ResourceWarning tests/semantic/test_tbuffer_load_format.py — 10/10 PASS
  • python -I -W error::ResourceWarning tests/semantic/test_norm_decode.py — 6/6 PASS
  • test_buffer_swizzle, test_feature_scan, test_rdna2spirv_xdxr_rules, test_docs_repo_paths, test_design_contract_rows — 21/21 PASS
  • Not run locally: spirv-val, llvm-mc, Vulkan GPU hardware pipeline creation, or the proprietary GTA VI shader dump.

AI-assisted.

@ElsCiber

Copy link
Copy Markdown

Rerun on the current head 5f1a95b8 (it contains main aa2988cc, so no local merge), same GTX 1660 SUPER / driver 621.14 / Windows 11 Pro 26300 / llvm-mc 23.1.6 / Vulkan SDK 1.4.363.0, runtime rebuilt from each tree. No regressions against main aa2988cc. AI-assisted.

tree run_gpu_tests.py default LEONIDA_W64_EMULATE=1
main aa2988cc 164/210 passed, 46 skipped, 0 failed 195/210 passed, 15 skipped, 0 failed
#2089 5f1a95b8 164/210 passed, 46 skipped, 0 failed 195/210 passed, 15 skipped, 0 failed
  • 214 / 214 translated and spirv-val-valid on both. Every test has the same status on main and the PR in both modes.
  • With emulation, 7 test shaders take emulated wave64 structured and 31 take emulated wave64 rounds, the same on both trees.
  • tests/semantic/test_wave64_emulate_opt.py: OK. Full tests/semantic on the PR head: 7457 tests; the only failures are the ones main aa2988cc already has, the same counts in the same three files on both trees: test_loop_ballot_barrier (3 failures, 2 errors), test_mutations (2), test_cmp_class_f64 (2). That's the known red main from Coordinating who works on what (21) (moved to #4257) #4084, each claimed with a fix PR open, so it's not from this PR. (test_vcmp16_opsel errored only because spirv-as wasn't on PATH in that run; it passes with the SDK on PATH.)

These are the synthetic fixtures only. Your outlining and coalescing commits target the corpus giants, which I can't test without game files; this run only shows they don't break the hand-written wave64 tests on a 32-wide NVIDIA part.

@ligmaSec ligmaSec left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Independent Linux test at 5f1a95b8 versus d0835dd9, with Mesa 26.1.6 RADV targeting GFX1201 via Mesa's DRM shim. All inputs are hand-written synthetic RDNA2. Each pipeline build used the same vk_pipeline_check, one worker in a fresh process, MESA_SHADER_CACHE_DISABLE=true, and an 8 GiB address-space limit.

Dynamic typed-load outlining

The fixture accumulates the result of repeated buffer_load_format_x instructions with distinct offsets and a runtime V# descriptor. All four module sizes (8, 32, 128, and 512 loads) translate and pass Vulkan 1.2 spirv-val on both trees.

Workload Main SPIR-V / cold pipeline time PR SPIR-V / cold pipeline time
128 loads 521,036 B / 7.274 s median (7.075–7.323) 111,900 B / 7.360 s median (7.144–7.694)
512 loads 1,981,772 B / 100 s timeout 331,548 B / 100 s timeout

Three interleaved samples per build at 128 loads. Median peak RSS was 185.3 MiB on main and 184.4 MiB with outlining. At 512 loads, one bounded run per build reached the timeout. The same 512-load fixture compiled in 3.40 s with a separate single-component decoder prototype.

This is a large reduction in SPIR-V stored on disk. RADV inlines the helper functions before optimization, which is consistent with the similar time and memory at 128 loads. The bounds and format differential gave 5,120 bit-identical words against main across the 128 descriptor formats, eight destination selectors and five byte offsets. The 23 emulation tests and 156 buffer tests also passed.

Control flow already available on main

Separately, I measured the default structured emulation against the same translator with --dispatch-loop. A two-wave synthetic workgroup repeatedly evaluates an EXEC mask, conditionally updates a wave-wide scalar, runs two dependent integer multiply/add pairs on active lanes, and uses the scalar after restoring EXEC.

Workload Structured Forced round scheduler
512 EXECZ branches 0.633–0.677 s, 126 MiB RSS, 0 switch cases 10.222–12.789 s, 687 MiB RSS, 1,537 switch cases
2,048 EXECZ branches 5.709 s, 339 MiB RSS, 0 switch cases 60 s timeout, 2,528 MiB RSS at timeout, 6,145 switch cases

Both modes pass spirv-val. On llvmpipe, both returned 128/128 expected words in each of six dispatches with 32 or 128 branches and three starting masks, including one with different outcomes across the two waves. These separate fixtures show a cold-compile improvement from structured lowering where it applies. The typed-load-only result still points to the cost of the decoder after inlining.

AI-assisted. No physical GPU or game files used.

Mesa 26.3.1 and llvmpipe follow-up

I built Mesa 26.3.1 RADV and its matching DRM shim from source to match the Mesa release in #4315. One new cold sample per build on the same GFX1201 target confirmed the direction of both results.

Workload Measured pipeline creation (peak process RSS)
128 typed loads Main 6.901 s (142 MiB), outlining 7.336 s (149 MiB), single-component decoder 0.492 s (39 MiB)
512 EXECZ branches Main structured 0.638 s (88 MiB), main forced rounds 7.939 s (650 MiB)

I also built and ran five checked-in GPU fixtures on llvmpipe with wave64 emulation enabled. The official harness verified the complete expected output for cs_fmt_1010102, cs_fmt_int_narrow, cs_fmt_sint32, cs_fmt_xy_xyz and cs_fmt_d16_xyz on both trees.

Combined decoder and outlining

Research commit 4efad11f applies the single-component decoder inside this head's outlined helper. It keeps the address, bounds and memory-access path shared with other loads and uses a distinct helper key for non-D16 buffer_load_format_x. D16 and wider loads use the existing helpers.

Synthetic typed loads Standalone decoder: SPIR-V / RADV 26.3.1 cold compile Combined: SPIR-V / RADV 26.3.1 cold compile
128 491,336 B / 0.441 s median (0.403–0.495) 88,072 B / 0.475 s median (0.427–0.479)
512 1,932,088 B / 3.811 s median (3.634–4.230) 307,704 B / 3.706 s median (3.626–3.858)
3,280 12,282,104 B / 116.527 s 1,855,480 B / 113.705 s

Three interleaved runs at 128 and 512 loads. One run per build at 3,280 loads, with 3,119 MiB and 3,112 MiB peak RSS respectively. The combined build retains the compile-time gain while storing a smaller module. All measured binaries passed spirv-val.

On the 32-load fixture, RADV's ACO stats reported 43,011 native instructions and 1,430 spilled SGPRs for both main and outlining alone. Both single-component variants emitted 5,704 instructions and reported zero spills. This is compiler output from the DRM-shim target.

The Intel Xe2 (BMG) Mesa 26.1.6 ANV compiler accepted the wave64-emulated, 128-byte push-constant build. With 128 loads, main and outlining alone reached a 45 s timeout, while both decoder variants compiled in 3.91 s. One run per build, via Intel's DRM shim.

Verification includes 24 wave64 emulation tests, 157 buffer semantic tests, all 5,120 format/selector/offset reference outputs, and the five llvmpipe fixtures above. An exhaustive llvmpipe dispatch over each 16-bit input value gave 131,072/131,072 exact UNORM16/SNORM16 results, matching main, outlining alone, and the arithmetic CPU reference. These checks are synthetic. The effect on either large game pipeline still needs a local replay.

ItsNotRexed added a commit that referenced this pull request Nov 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants