cfg_structure / rdna2spirv: unwrap tautological %pc guards in structured CFGs (ms_wave_info_s3 AMD crash, SHADER-STRUCTURED-PC-UNWRAP) #808
No reviewers
Labels
No labels
accessibility
bug
documentation
duplicate
enhancement
good first issue
help wanted
invalid
missing claim
needs rebase
question
wontfix
No milestone
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
github/ubiquitarianism--leonida!808
Loading…
Reference in a new issue
No description provided.
Delete branch "gh-pr/808/head"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
@whoalin1 on GitHub · 2026-11-24 14:03 UTC · original
whoalin1:shader-structured-pc-unwrap→main· +337 −79 · 7 files · 4 commits · merged 2026-11-25 16:46 UTCClaim: #14 (
SHADER-STRUCTURED-PC-UNWRAP)Problem
On AMD's proprietary Windows Vulkan driver (
24.10.24, LLPC, AMD Ryzen 5 7600 RDNA2 iGPU, native wave64),ms_wave_info_s3segfaults (0xC0000005) duringvkCreateGraphicsPipelines.In
ms_wave_info_s3.asm,blk0conditionally skipsblk1(MSG_GS_ALLOC_REQ), and bothblk0andblk1converge atblk2(s_barrier).cfg_structure.structure()wrapsblk2in("guard", 2, [("block", 2)]), emittingOpBranchConditionalaround%blk2'sOpControlBarriereven though%pc == 2is tautologically true on every incoming path.--wave64-emulate(e.g., 32-wide NVIDIA GPUs),wave64_emulate_opt._unwrap_known_pc_guardsalready unwrapped that guard, soms_wave_info_s3passed there.rdna2spirv.capped_tree()usedcfg_structure.structure()directly without unwrapping tautological%pcguards, leavingOpControlBarrierinside conditional control flow and crashing AMD Windows LLPC (0xC0000005).Fix
tools/cfg_structure.py: addunwrap_known_pc_guards(tree, out_pcs, entry_pc=0)(moved fromtools/wave64_emulate_opt.py, keepingcfg_structure.structure()unchanged for callers like_drop_sink_block).tools/wave64_emulate_opt.py: delegate_unwrap_known_pc_guardsdirectly tocfg_structure.unwrap_known_pc_guards.tools/rdna2spirv.py(capped_tree): applycfg_structure.unwrap_known_pc_guardsto structured trees before computing nesting depth, so bothassemble()andneeds_barrier_rounds()see post-dominating merge/barrier blocks at top level.tests/test_cfg_structure.py: addtest_unwrap_known_pc_guards(single-arm if-then, diamond, loop exit, early-exit guard preservation) and differentially checkunwrap_known_pc_guardsacross all 18,228 random reducible graphs × 6 seeds.tests/test_translate.py: assert%blk2inms_wave_info_s3is emitted without a conditional%pcguard before itsOpControlBarrier.docs/design.md: document the pass in the Control flow contract row.Verification (before/after on
main47c651174,LEONIDA_VK_VALIDATION=1)LEONIDA_PC_TAIL_UBO=1):main):ms_wave_info_s3FAIL (vk_harnesscrash0xC0000005)ms_wave_info_s3PASS (4096/4096 pixels exact, 0 validation errors);cs_barrier_divergent,cs_barrier_early_end,cs_barrier_loop3/3 PASSms_wave_info_s3PASS (4096/4096 pixels exact, 0 validation errors);cs_barrier_*3/3 PASSpython -I tests/test_cfg_structure.py— 18,228 random reducible graphs × 6 seeds (both structured and unwrapped trees matchwalk()), plus shape & deep-chain testspython -I tests/test_runner_calls_all_tests.py— 3/3 OKpython -I tests/test_cfg_run_limit.py— 4/4 OKpytest tests/test_translate.py— 669 passedunittest discover -s tests/semantic -p test_wave64_emulate_opt.py— 31/31 OKunittest discover -s tests/semantic -p "test_*barrier*.py"— 53/53 OKunittest discover -s tests/semantic -p "test_exec*.py"— 2/2 OKunittest discover -s tests/semantic -p "test_ms_*.py"— 6/6 OKpython -I tests/test_text_write_line_endings.py— 3/3 OKpython -I scripts/check_no_game_data.py ...— clean (rc=0)AI-assisted (Gemini 4 Neon).
cfg_structure.structure() wraps post-dominating join blocks after a diamond or loop in a ('guard', g, ...) node even when %pc == g is tautologically true on every incoming path. wave64_emulate_opt._unwrap_known_pc_guards already unwraps these guards for --wave64-emulate, which is why ms_wave_info_s3 passed on 32-wide NVIDIA GPUs while crashing with 0xC0000005 on native wave64 AMD RDNA2 Windows (driver 24.10.24, LLPC) where blk2's OpControlBarrier stayed trapped inside a conditional OpBranchConditional. Move unwrap_known_pc_guards into tools/cfg_structure.py (reused by wave64_emulate_opt with zero duplication) and apply it in rdna2spirv.capped_tree() so both assemble() and needs_barrier_rounds() see post-dominating join blocks at top level. SHADER-STRUCTURED-PC-UNWRAP Co-Authored-By: Gemini 4 Neon <[email protected]>@qhukz13 on GitHub · 2026-11-24 15:30 UTC · original · reviewed
Checked 185220e4a (Linux, CPU only, no game files). Merges cleanly with current
main.The moved logic holds up:
tests/test_cfg_structure.py: OK (18,228 random graphs).--wave64-emulatethe pass now runs twice (incapped_tree, then inwave64_emulate_optat line 1501). On 19,689 random structured graphs a secondunwrap_known_pc_guardsnever changed the tree, so that is safe.unwrap_known_pc_guards, run againsttest_cfg_structure.py: four are caught (unwrapping whengis only one of the possible values, keepinghpossible after a loop, dropping the skip path at a guard exit, ignoringskip_pcin the sibling-guard merge). One survives: starting a loop body fromcur_pcinstead ofcur_pc | {h}. That looks equivalent if a structured loop is always entered with%pc == h; a line saying so, or a graph showing otherwise, would settle it.The thing I would ask for: until now this pass only ran under
--wave64-emulate; with thecapped_treecall it rewrites the tree of every structured shader on native wave32/wave64 too, andcapped_treealso feedsneeds_barrier_roundsand theMAX_STRUCTURED_DEPTHfallback. The verification coversms_wave_info_s3and the threecs_barrier_*fixtures on hardware plus the unit tests, but not the corpus. Per AGENTS.md ("count over the whole corpus"), could you add before/after numbers over the game's listings: translated andspirv-val-valid counts, how many modules' SPIR-V changes, and how many shaders change their barrier-rounds or depth-fallback decision? A shader that leaves barrier rounds because its barrier is now top-level is the intended effect, but the count would show it is only that.@whoalin1 on GitHub · 2026-11-24 15:36 UTC · original
Thanks for the thorough review and mutation testing, @qhukz13!
Loop entry
cur_pc | {h}: Added a clarifying comment intools/cfg_structure.py(6c52f6c44). In any tree produced bycfg_structure.structure(),lbody[0]is always(block, h), which immediately overwritescur_pcwithout_pcs[h]— keepingcur_pc | {h}is defensive so back-edge iterations stay sound even ifunwrap_known_pc_guardsis ever called on a non-structure()tree.Corpus before/after counts: I do not have the retail 1.0.2.1 game files / shader corpus on this machine, so I cannot run the 26,503-shader corpus count myself — if a reviewer with a local corpus build can run a before/after check against
47c651174, I'd really appreciate it.What I did measure before/after (
47c651174vs this branch) across all 258 synthetic shaders inruntime/test/shaders/:258/258→258/258spirv-valvalid:258/258→258/25813modules (cs_bench_mix,cs_w64x_branch,cs_w64x_chain_barrier,cs_w64x_mask_reuse2,cs_w64x_sbarrier,cs_w64x_wg128_branches,cs_wm_scc_rfl,ms_wave_info_s3,ps_far_branch,ps_mandelbrot,ps_scc,ps_scc_mask32,ps_uniform_branch)control_flow(barrier-rounds / depth-fallback) changed:0198/249 passed, 49 skipped(exact parity withmain; only the two known #31tfefixtures fail, and all 13 changed shaders pass).@towade on GitHub · 2026-11-24 18:22 UTC · original
checked:
6c52f6c44(the same two patches as the current headcc7b94777, pergit range-diff; only the base moved) on RDNA4 with native wave64, as a regression check: AMD Radeon RX 9070 XT (gfx1201, AMD Windows driver 32.0.32029.2010, LLPC), Windows 11 26300,main3aa975421with this PR merged,scripts/run_gpu_tests.pywithllvm-mc21.1.8.ms_wave_info_s3: passes onmainand with this PR, native and withLEONIDA_W64_EMULATE=1(4096/4096 pixels exact). This driver neither crashes nor gives a wrong value onmain(the RX 9070 XT record ingpu-test-results/from 23 November still lists a wrong value there; currentmainpasses), so I can't confirm the fix itself here, only that the unwrapped guard is fine on RDNA4.cfg_structurefor every shader: full GPU suite, native: 207 pass, 16 skipped, identical test by test onmainand with this PR; no test fails for another reason. 29 pixel-shader tests did not run because I had not builtvk_texture_test,vk_bindless_testandvk_sampler_test.AI-assisted (Claude Code).
@towade on GitHub · 2026-11-24 18:42 UTC · original
Follow-up to my check above: I built
vk_texture_test,vk_bindless_testandvk_sampler_testand ran the full GPU suite again, natively on the same RX 9070 XT (AMD 32.0.32029.2010), onmain3aa975421and with this PR merged. Result: 236 of 252 pass, 16 skipped, 0 fail on both, identical test by test, so the 29 pixel-shader tests that had not run pass too.AI-assisted (Claude Code).
@Sangonapou on GitHub · 2026-11-24 18:45 UTC · original
Tested cc7b9477 on NVIDIA GeForce RTX 3080 Ti Laptop (Ampere, subgroup 32..32), NVIDIA 621.24, Vulkan 1.4.357, Windows 11 Pro (build 26300): pass, the 32-wide side of @towade's RDNA4 regression check
Runtime built at this head with
scripts\build_runtime.ps1(MSVC 19.51);llvm-mc23.1.6, SPIRV-Tools 2026.4. No game files.tests/test_cfg_structure.py:ok: 18228 graphs structured and run, 1772 irreducible (1755 split-structured, 17 capped), 12692 with loops.LEONIDA_W64_EMULATE=1235/252 passed, 17 skipped, 0 failed.@adrianmjim on GitHub · 2026-11-24 21:42 UTC · original
Reviewed cc7b94777 applied onto main
66d4f5aa3, and ran it on an AMD Radeon RX 7900 XT. The GPU results are below. Before that, a CPU-only repro of a miscompile the move to the native path introduces.The unwrap drops a guard when the last block ends in a conditional branch
capped_treebuildsout_pcs[b] = set(succ[b])(tools/rdna2spirv.py, the new code around line 18093) and addsENDonly whensucc[b]is empty. A last block that ends in a conditional branch, with nos_endpgmafter it, getsfall = [], sosuccis[tgt](around line 17790/17798). But emission storesOpSelect(cond, tgt, len(blocks))into%pc(around line 18026), so%pccan also be past the end.cfg_structure.unwrap_known_pc_guardsthen believes%pcis alwaystgtafter the loop and removes a guard it needs.wave64_emulate_opt.pyalready handles this (main, lines 1551-1563): it adds-1(END) when the tail has one raw edge and its terminator is a conditional branch. That rule did not come along when the function moved tocfg_structureand the native path.Hand-written wave32 compute shader (no game data).
s4ands5come from the push constants ands[0:3]is a raw buffer V#:succis[[2, 1], [], [0]]. main's structured tree is[loop 0 [b0, guard 2 [b2]], guard 1 [b1]]; with this PR it is[loop 0 [b0, guard 2 [b2]], block 1]. On thetests/semanticinterpreter (spirv_mini_interp.run_workgroup, 32 invocations;test_loop_ballot_barrier.run_compute_workgroupgives the same):s4 = 0, s5 = 0, B2 runs, the branch is not taken, and the program ends. With this PR,%pcis 3, the loop exits, and%blk1runs unguarded.spirv-val, so this is a semantic difference only.--dispatch-loopform matches the ISA on both trees.ENDtoout_pcs[2]makes the PR's output byte-identical to main's for this shader, and all three cases match the ISA. I tried it as an in-memory patch ofcapped_tree; I did not touch the tree.capped_tree(succ)only seessucc. So the set probably has to be computed intranslate()fromraw_edgesand the terminator, aswave64_emulate_opt.pydoes, and passed to bothcapped_treecalls.ENDto all of them would undo the unwrap this PR is for.How exposed this is: all 392 listings in the repository end in
s_endpgm, so none of them hits it. A listing has to end in a conditional branch with nothing after it. I did not check the game corpus.tests/test_cfg_structure.pybuildsout_pcsfromsucctoo, so its random graphs never contain this edge. A semantic test with this shader, and atest_unwrap_known_pc_guardscase[[2,1],[],[0]]without_pcs[2] = {0, END}that keepsguard 1, would cover it.GPU, RX 7900 XT
AMD Radeon RX 7900 XT (RDNA3, gfx1100), AMD driver 32.0.32029.2010 (26.11.2), Windows 11 build 26300, Vulkan SDK 1.4.363.0, llvm-mc 23.1.5, test programs from a
main66d4f5aa3build.66d4f5aa3scripts/run_gpu_tests.py, whole suite--filter ms_wave_info_s3, native wave64, 3 runs--filter ms_wave_info_s3,LEONIDA_W64_EMULATE=1On this card and driver,
ms_wave_info_s3already passes natively onmain, so the crash or wrong output this PR targets does not reproduce here. That is different from the RX 9070 XT record on the same driver, which was taken at5d74c27. The PR causes no regression on RDNA3.No game files.
@whoalin1 on GitHub · 2026-11-24 21:56 UTC · original
Great catch, @adrianmjim — thank you both for the RX 7900 XT verification and for spotting that!
Fixed in
b630a9b1e:tools/rdna2spirv.py: Added_block_out_pcs(blocks, raw_edges, succ)(matchingwave64_emulate_opt.py) so any block withlen(raw_edges[b]) == 1whose terminator is a conditional branch (op in BRANCHES and op != s_branch, i.e. the last block with no following block, or asplit_irreducibleclone of it) includescfg_structure.ENDalongsidesucc[b]. Stored it ong.out_pcsbeforeneeds_barrier_rounds()and passed it tocapped_tree(succ, out_pcs)at both call sites (needs_barrier_rounds()andassemble()).tools/cfg_structure.py&tools/wave64_emulate_opt.py: While tracing this, I also caught the sibling case incfg_structure.structure()where a last-block conditional branch directly dominates its single explicit target (succ = [[2], [], [1]],out_pcs[2] = {1, END}): line 161 previously skipped the guard on block 1 beforeunwrap_known_pc_guards()even ran.structure(succ, out_pcs=None)now checksset(out_pcs[x]) == {below[0][1]}whenout_pcsis provided, and bothcapped_tree()andwave64_emulate_opt.plan_structured_emulation()passout_pcs.tests/test_cfg_structure.py: added both the loop back-edge falloff case ([[2, 1], [], [0]],out_pcs[2] = {0, END}) and the non-loop dominated-target falloff case ([[2], [], [1]],out_pcs[2] = {1, END}).tests/semantic/test_structured_pc_unwrap.py: end-to-end semantic execution test covering your exact 9-instruction loop shader across(s4=1, s5=0),(s4=0, s5=1), and(s4=0, s5=0)(matching--dispatch-loopand ISA —(0, 0)performs no store), the non-loop variant in both wave32 structured and--wave64-emulatestructured, and the post-dominating joins_barrierunwrap case.Verified locally on
b630a9b1e:tests/test_cfg_structure.py(18,228 graphs + unit tests): passtests/semantic/test_structured_pc_unwrap.py: 3/3 passtests/semantic/test_wave64_emulate_opt.py: 31/31 passtests/test_translate.py: 675/675 passtests/test_runner_calls_all_tests.py(3/3),tests/test_ci_registration.py(15/15),tests/test_text_write_line_endings.py(3/3),scripts/check_no_game_data.py: passscripts/run_gpu_tests.py --filter ms_wave_info_s3(spirv-val+LEONIDA_VK_VALIDATION=1):4096/4096 pixels exacton both AMD Ryzen 5 7600 RDNA2 iGPU (24.10.24,LEONIDA_PC_TAIL_UBO=1) and NVIDIA RTX 4070 SUPER (610.88).@towade on GitHub · 2026-11-24 22:42 UTC · original · edited 2026-11-24 22:45 UTC
checked: the corpus before/after count asked for above, native path, no
--wave64-emulate. Before =3aa975421(this branch's merge base withmain, not47c651174), after =b630a9b1e. Windows 11 26300, 14 shards ofrdna2spirv.py --no-asmplus--merge, SPIRV-Tools from Vulkan SDK 1.4.363.0. CPU only, no GPU run. Counts only.3aa975421b630a9b1espirv-valcontrol_flow: structured / straight line / barrier rounds / dispatch loop.spvbytescontrol_flow(andlds_bytesin 34 of them)So nothing is lost or newly rejected. The change touches most of the structured modules. The 36 modules that move from
barrier roundstostructuredare all compute shaders.What the bytes change is (opcode counts, not a GPU check):
OpBranchConditional. In total there are 113,289 → 102,936OpBranchConditionaland 111,864 → 101,510OpSelectionMerge, about 9 % fewer. Loads also drop slightly (−0.8 %).OpLoopMergeandOpSelectstay the same, which is what removing the guards should look like.barrier rounds→structuredcompute shaders. They have moreOpLoopMergeand barriers than the rounds lowering produced.OpControlBarrierafter and 9 have fewer (2 → 1). All 9 are among the 36barrier rounds→structuredmodules, and each of their listings contains exactly ones_barrier. The rounds lowering emitted it twice, the structured path emits it once. I don't see a lost barrier in that.The falloff case from the review above. I checked the corpus for it: all 26,503 listings end in
s_endpgm(last instruction of each listing), so no game shader ends in a conditional branch with nothing after it. The fix inb630a9b1etherefore shouldn't change any corpus module through that edge directly; clones fromsplit_irreducibleI didn't look for.Not checked: the corpus with
--wave64-emulate, running any of the changed modules on a GPU, and the pipeline-library, FSPX and BVH sets.AI-assisted (Claude Code).
@adrianmjim on GitHub · 2026-11-25 07:54 UTC · original
Rechecked at
8e5cf5aef, merged ontomain42537e7b6(CPU) and run on the RX 7900 XT (GPU, below).The fix works. My earlier repro now matches the ISA in all three cases, structured and
--dispatch-loop. The structured output has the same control flow as the in-memory patch I tried, withguard 1kept.tests/semantic/test_structured_pc_unwrap.pypasses 3/3,tests/test_cfg_structure.pypasses (18,228 graphs), andtests/semantic/test_wave64_emulate_opt.pyis OK.The
plan_structured_emulationhalf of the fix also matters. Without exec folds, this wave64 shader runs wrongly onmainand correctly with this PR:With
s4 = 0, the branch is not taken and the program ends, so nothing is stored. In--wave64-emulatestructured form withfind_local_exec_foldsdisabled,mainstores 0x3333 and 0x4444 in all 64 lanes, and this PR stores nothing.One path the fix does not reach yet: exec-fold regions
With exec folds on, as they are by default, the same shader still stores 0x3333 and 0x4444 with
s4 = 0, on bothmainand this PR, in the structured and dispatch emulate forms.find_local_exec_foldsreturns{0: run 1, skip 3, region [1, 2, 4]}, so the region contains the last block. A variant whose last block branches straight toskip(last: s_cmp_eq_u32 s4, 1; s_cbranch_scc1 skip) wrongly stores 0x4444 withs4 = 0.s4 = 0, 64 lanes,--wave64-emulatemain42537e7b6find_local_exec_foldsreturns none), structuredThis is the same missing
ENDedge, intools/wave64_emulate_opt.py's fold path, and it predates this PR:find_local_exec_foldsworks only fromsucc, which has noENDedge for the last block, so_postdominators(succ)can acceptskipas its post-dominator.succ = [tgt]) gets into the region.sub_succis built fromsucc, andcfg_structure.structure(sub_succ)is still called withoutout_pcs.%pc = skip, so "the program is over" becomes "continue at skip".Passing
out_pcsthere too, and refusing a fold whose region contains a block that can writeEND, would probably cover it. As with the original case, every listing in the repository ends ins_endpgm, so the corpus is unlikely to hit it. It fits in this PR or in a follow-up; your call.The repro drives
test_loop_ballot_barrier._translate_cs(..., threads=64, emulate=True)andrun_compute_workgroup, withfind_local_exec_foldswrapped to switch folds off. No game data.GPU, RX 7900 XT
AMD Radeon RX 7900 XT (RDNA3, gfx1100), AMD driver 32.0.32029.2010 (26.11.2), Windows 11 build 26300, Vulkan SDK 1.4.363.0, llvm-mc 23.1.5. Test programs come from a
main42537e7b6build; this PR changes no C++.main42537e7b6scripts/run_gpu_tests.py, whole suite--filter ms_wave_info_s3, native, 3 runs--filter ms_wave_info_s3,LEONIDA_W64_EMULATE=1The one failure is
cs_imgatomic_exton both, the fixture problem #1518 fixes. No regression on RDNA3.No game files.
@whoalin1 on GitHub · 2026-11-25 08:06 UTC · original
Thanks again for the thorough recheck and full RX 7900 XT pass, @adrianmjim!
Since the exec-fold sibling fix was only two lines, I folded it into this PR as
33431d6fe:tools/wave64_emulate_opt.py(find_local_exec_folds): reject any blockuin the region walk wherelen(raw_edges[u]) == 1 and terms[u][0] == br and terms[u][1] != s_branch(matching the existingnot succ[u]guard), so a region that can fall off the end toENDis never folded into a region whose exit unconditionally sets%pc = skip.tests/semantic/test_structured_pc_unwrap.py: addedtest_wave64_emulate_exec_fold_refuses_last_block_cbranch_falloffcovering both of your variants (s_cbranch_scc1 Xands_cbranch_scc1 skip) with default folds enabled in both structured and--dispatch-loop--wave64-emulatemodes (s4=0-> no store,s4=1-> expected stores).Verified locally on
33431d6fe:tests/semantic/test_structured_pc_unwrap.py: 4/4 passtests/semantic/test_wave64_emulate_opt.py: 31/31 passtests/test_cfg_structure.py: 18,228 graphs + unit tests passtests/test_runner_calls_all_tests.py(3/3),tests/test_ci_registration.py(16/16),scripts/check_no_game_data.py: pass.@adrianmjim on GitHub · 2026-11-25 12:48 UTC · original
Rechecked at
33431d6fe(CPU, thetests/semanticinterpreter, Windows 11; no game files). The fold gap is closed.Both wave64 shaders from my last comment, the "dominated X" form and the "to skip" form, under
--wave64-emulate, with folds on as by default:find_local_exec_foldss4 = 0s4 = 18e5cf5aef(before){0: run 1, skip 3, region [1, 2, 4]}33431d6fe{}, the region is refusedThat holds in the structured and dispatch emulate forms, and for the "to skip" variant:
s4 = 0no store,s4 = 10x4444. The original non-emulated END repro still matches the ISA in all three cases.test_structured_pc_unwrap.pyandtest_wave64_emulate_opt.pypass.Thanks for picking that up.
@aslan2142 on GitHub · 2026-11-25 16:46 UTC · original
Merged. Thank you, @whoalin1, and thanks to @adrianmjim for the fall-off bug, and to @qhukz13 and @towade for the corpus counts.
main+ this branch. The newtest_structured_pc_unwrapfails onmain(5 failures, 2 errors) and passes here.test_cfg_structure(18,228 graphs) andtest_wave64_emulate_optpass.linux-gpu-toolsjob failed, and GitHub hasn't released its logs yet. I ran the same step (scripts/run_gpu_tests.py, native build, llvmpipe) onmainand onmain+ this branch: the results are identical, 176/264 pass on both, and the same one test fails on both (cs_imgatomic_ext, which already fails onmain). So this change adds no GPU-test failure.structure()now takesout_pcs.main9e7720c9e+33431d6fe: the semantic suite passes (490 files, 6,292 tests, 0 files failed);test_cfg_structure,test_translate (pytest; 2 failing as on main)pass; the 14 docs and writer tests pass;check_no_game_data.pyis clean on the 7 changed files.AI-assisted (Claude Code, Claude Opus 5.5).