fix(shader): narrow a goto junction Phi to the arm its branch allows #14636
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/14636"
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?
Imported from boykopovar/AnyPS5. Originally posted by zaryabzip on 2026-11-01T16:42:32Z.
What
A new pass,
GotoPhiRefiner, removes a resource-planning stop that the structurizer's goto-variable junctions cause.The problem. When the structurizer can't clone a region, it routes control through one junction block and a goto variable. That happens in
routeThroughJunctionfor an entered region, and inrouteLoopExitsfor a loop whose exits share no post-dominator. A value that differs between the routed paths becomes a Phi at the junction, next to the Bool Phi of the goto variable, and a branch on that Bool Phi then picks the next region. Below that branch only the arms whose goto value matches can arrive, but SSA keeps the whole Phi. A descriptor address read there is a Phi of the right pointer and the other paths' values. The SRT walk can't evaluate that, and the shader stops withGetImageResource dword 0 is not a valid runtime value.What the pass does. It runs just before the SRT walk. If it replaces anything, dead code elimination runs again.
The disk cache format moves to 68. A
shader.mddebt entry records which merges stay unnarrowed.Where it showed up. In Little Nightmares (PPSA10737, discussion #6275), on
main+ #7395 + #9749 + #10000, compute shader0x200c340000stopped at pc 0x119b8. Its address merged the call site's constant-buffer values (0x444 + 8/0xc) with scratch values from the other linked callees. With this pass the shader prepares and the address is the call site's value. The title then stops in the driver, because the module is 6.2M words; that is #13538's problem. On plainmain, this title's shaders stop earlier and still need #9749 and #10000, so this PR unblocks nothing on its own. The new test shows the case directly.GotoJunctionDescriptor.cppbuilds a 64-wide compute program:s[16:17]from user datas[4:5]and leaves early ons_cmp_eq_u32 s8, s6;s_buffer_load_dwordx2and loops;routeLoopExitsbuilds a goto-variable junction;s[16:17]and runsimage_load.The test checks that one image is planned and that each of its eight dwords is read through the SRT from a
LoadAddressU32whose address isGetUserDataofs4ands5, not a Phi.GotoJunctionGuards.cppbuilds IR by hand and runs the pass directly. Each guard gets a check that fails when that guard is removed:Two twin checks show the same shapes being narrowed when the guards allow it.
Overlap:
git merge-treeagainstmainand every open pull request finds conflicts only on theFormatVersionline ofShaderDiskCache.hpp, with the 19 open PRs that also move the disk-cache format. Following the ladder in #10846, this PR takes 68, the next free number: open PRs hold 51–52, 54, 56–60 and 62–67, with #8939 at 66 and #9457 at 67.Tested
Windows 11 (WinLibs GCC 15.2.0) and Ubuntu 24.04 on WSL2 (GCC 13.3.0), on
mainf2d874c1fd, at a commit with the same code and test as the head (only the debt entry's wording changed since).agc_goto_junction_descriptor, 3 runs each:mainwith only the test, it fails 3 of 3 on both hosts withGetImageResource dword 0 is not a valid runtime value; chain: LoadAddressU32@pc=0x0000003c(GetAddressResource(Phi(GetUserData(Void), ReadConst(GetSrtResource, Immediate)), Phi(...)), ...).agc_goto_junction_guards: pass 3 of 3 on both hosts. In a mutation check, removing each guard fails only its own check:agc_*suite, Windows only, RTX 3060 Laptop GPU, NVIDIA 617.42,ANYPS5_NO_SHADER_CACHE=1:main: 1202 passed and 9 skipped, of 1211.agc_shader_replay --prepare):0x200c340000prepares, where before it stopped at pc 0x119b8. On this PR's head447e80bde4with #7395, #9749 and #13538's opt-in switches (unset) onmain5b1d381d5a, it is 7,046,975 SPIR-V words; at0eac5c8070with #9749 onmain4f41f4c375, 7,045,511. An earlier, pre-PR version of the pass gave 6,222,886, which this description used to quote;0x2010fa0000still prepared, with 479,939 words, and theagc_*suite showed no change;vkCreateComputePipelineswith-13. That is the module-size problem tracked in #13538, not a resource refusal (run).tools/check_conventions.pypasses.38fc45950f, after the stale-fact check was dropped:GotoPhiRefiner.cppbuilds with no warnings;mainmerge, by me ate92fa373fe, which containsmain4977f64052(comment): on Windows (WinLibs GCC 15.2.0 r7, Release) and on WSL2 (GCC 13.3.0, Release), bothagc_goto_junctiontests pass,ctest -R shaderpasses 112 of 112 and 104 of 104, and the 37 CPU-side tests pass 37 of 37. The merge keepsFormatVersion68 overmain's 57.main4977f64052with the GPU pull requests listed in #4697 andlimitCalleesraised to 256 locally. These areagc_shader_replay --preparereplays of the 29 compute shaders that were refused, not a game run:e92fa373fe(comment), all 29 still stop withGetImageResource dword 0 is not a valid runtime value. In 28 of them, one use of the pointer Phi is narrowed, but a deeper use at pc 0x19420 is not, because one round stops atMaxRefinementDepth.8e5b82d0f2(comment), those 28 get past the refusal and stop onimage resource limit exceeded(ShaderInfo::MaxImages, outside this PR), so none prepares yet.0x120aed7f00still stops at pc 0x19f8, which has a different cause. The mean replay time per shader went from 41 s to 51 s, with 7 replays in parallel.agc_goto_junction_guardspasses 3 of 3 there.8e5b82d0f2(comment). On Windows (WinLibs GCC 15.2.0 r7, Release) and on WSL2 (GCC 13.3.0, Release), bothagc_goto_junctiontests pass 3 of 3,ctest -R shaderpasses 112 of 112 and 104 of 104, and the 37 CPU-side tests pass 37 of 37. Withe92fa373fe'sGotoPhiRefiner.cpp,agc_goto_junction_guardsfails only "deep junction chain" (Windows). No warnings inGotoPhiRefiner.cpporGotoJunctionGuards.cpp.mainmerge, by me at1560cfdef0, which mergesmain095ff72367(comment). On Windows (WinLibs GCC 15.2.0 r7, Release) and on WSL2 (GCC 13.3.0, Release), each set run once: bothagc_goto_junctiontests pass,ctest -R shaderpasses 117 of 117 and 109 of 109, and the 37 CPU-side tests pass 37 of 37. The merge keepsFormatVersion68 overmain's 60. No warnings inGotoPhiRefiner.cpp,GotoJunctionDescriptor.cpporGotoJunctionGuards.cpp.agc_add_default_testturns it off.Checklist
main; no other open PR implements the same functionsNotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file.mdfiles or images added to the repository (attach them to this PR)Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-02T07:20:40Z.
Review: COMMENTED
Reviewed — no blocking findings from the read; the guards test was built but did not run on Windows
This PR adds
GotoPhiRefiner, a shader optimization that narrows a goto junction Phi to the arm its branch allows, wired intoPrepareResourceProgramafter the first dead-code pass. I read the new pass and its header in full, and the wiring. The Windows CTest run passed the descriptor test. The guards test was compiled and linked on Windows, but it is not in the CTest selection, so it has no hosted pass.What I ran
5ab18d0ce2f9a4e44eb332d809872dcb671a041b; basef2d874c1fdccf781c0fa5d86619bb5dd8894b958. 10 files, +638/-1:Optimization/src/GotoPhiRefiner.cpp(+293, new),Optimization/include/Optimization/GotoPhiRefiner.hpp(+20, new),Recompiler.cpp(+5),ShaderDiskCache.hpp(FormatVersion50 to 68), the recompiler CMake line, two AGC driver test sources and their CMake fragments, and a debt line.Recompiler.cpp: when the refiner replaces any operand, dead-code elimination runs again.GotoJunctionDescriptor.cpp(103 lines) andGotoJunctionGuards.cpp(197 lines) were not read in full.agc_goto_junction_descriptor(Test #1828) passed, andconventions_env_reference_test_a_name_the_pull_request_does_not_touch_is_not_reported(Test #182) passed. The log showsagc_goto_junction_guards_tests.exelinked, and it is not in the selection.tests/…cpp, which the helper's literal match did not find. The Windows build compiled both.Results
agc_goto_junction_descriptor(hosted, Windows)agc_goto_junction_guards_tests(hosted, Windows)library-portability(hosted)Read-only check output
Precheck was not run: no PR-head code is run here. Diff check: passed. Conventions: passed. Stack check: passed, no declared dependencies, no errors. ABI audit: not applicable. Hosted:
gh api repos/boykopovar/AnyPS5/commits/5ab18d0ce2f9a4e44eb332d809872dcb671a041b/check-runs, and the Windows job log.Negative control
Not run here. A negative control needs a local build and run of the shader tests, and code from this head is not run here.
Findings
Blocking
None from the code read.
Non-blocking
Recompiler.cppruns the refiner for every shader that goes throughPrepareResourceProgram, so a defect would reach every shader that uses a goto junction. The only hosted pass is the descriptor test. The guards test (197 lines) was not in the Windows selection, so nothing hosted exercises the junction guards. A run ofagc_goto_junction_guards_testsat this head would close that gap.Sources
github.com/boykopovar/AnyPS5@5ab18d0ce2/core/shader/recompiler/Optimization/src/GotoPhiRefiner.cppgithub.com/boykopovar/AnyPS5@5ab18d0ce2/core/shader/recompiler/Optimization/include/Optimization/GotoPhiRefiner.hppgithub.com/boykopovar/AnyPS5@5ab18d0ce2/core/shader/recompiler/Recompiler.cppwindowson5ab18d0ce2Not verified
GotoJunctionDescriptor.cppandGotoJunctionGuards.cpp.To get this to a good state
agc_goto_junction_guards_testsat this head in hosted CI. Nothing else blocking.Imported from boykopovar/AnyPS5. Originally posted by XairRrR on 2026-11-03T11:55:29Z.
Review: CHANGES_REQUESTED
Reviewed — changes requested
The build, the conventions check, both new tests, the negative control and the guard mutations all pass. But a small hand-built IR graph shows that
GotoPhiRefinerfollows a nested guard Phi at a loop header and replaces a Phi with a value from a later loop iteration, which is a miscompile.What I ran
Head
78e43aa03f1b7950af802cb55875f4092671b883,main4f41f4c375f5abb487dbd184fbc150f31994d762, merged with--no-ffas3be69c42c664ce529c76ffe7f5a0f96a9a36b324. Debian 13 VM (Xeon Gold 6136, AVX2), GCC 14.2.0, Vulkan through lavapipe (Mesa 26.1.6).Results
git diff --checkcheck_conventions.pymainagc_goto_junction_descriptoragc_goto_junction_guardsagc_driver_native_depth_uniform_planesThe script reported
VUID-vkCmdDispatch-groupCountX-00386as new onagc_driver_native_depth_uniform_planes, but that test was not in the older baseline (d1ae628bc2), because it reachedmainlater. I ran the test with the validation layer on the merged tree and again withRecompiler.cppandShaderDiskCache.hpprestored frommain, which takes the refiner out of the pipeline. Both runs give the same 8VUID-vkCmdDispatch-groupCountX-00386lines, so they come frommain. The layer loaded in both runs: neither log has a "was not found but was requested" line.Mutation results (guards test)
GotoPhiRefiner.cppThis matches what the author reported in the discussion.
Negative control
I restored
core/shader/recompiler/Recompiler.cppandShaderDiskCache.hppfrommain. That keeps the new pass compiled but no longer called.agc_goto_junction_descriptorthen fails with the stop described in the PR:agc_goto_junction_guardscalls the pass directly, so this revert does not affect it. Its control is the mutation table above. After all of this, the files were restored to the merged tree, rebuilt and retested (both pass), andgit status --porcelainis empty.Findings
Blocking
1. The nested guard Phi path picks a back-edge value that has been redefined since the inner junction ran. See
GotoPhiRefiner.cpplines 255–259.When an outer junction's guard arm is a Phi of the same block as the value arm,
RestrictArmsrestricts the inner Phi and returns the arm value it selects. That arm value is what the inner Phi received when the inner block was entered. If the inner block is a loop header and the selected arm comes from the latch, the defining instruction runs again between the inner header and the outer junction. The current value is then a different iteration's value.The later checks do not catch this:
To probe this, I temporarily added the following check to
GotoJunctionGuards.cpp, using the file's own helpers:Below the true branch,
mergedisinnerPhi: the counter of the previous iteration, which iscounter - 1. The pass replaces it withcounter:The pass runs on every shader in
PrepareResourceProgram. It rewrites any non-Bool Phi operand, not only descriptor chains. A miscompile like this gives silently wrong values instead of a stop. I did not check whether the structurizer currently emits this exact shape (a goto guard Phi at a loop header that feeds an outer junction). The pass is written as a general IR rewrite, though, so it has to be sound on valid IR.Suggested fix: in the nested case, accept a selected value only if its definition block dominates the inner Phi's block (immediates are always fine), or reject any arm whose predecessor is dominated by the inner Phi's block (a back edge). With that dominance condition, the definition cannot run again between the inner junction and the outer one: the inner block dominates the outer junction's predecessor, so the definition can't reach that predecessor without passing the inner block again. Please also add the graph above as a regression check in
GotoJunctionGuards.cpp.Non-blocking
None.
Not verified
routeThroughJunctionorrouteLoopExitsin practice. I did not run real title shaders oragc_shader_replay.0x200c340000) result in the description, which needs #7395, #9749 and #10000 on top.agc_*suite. I ran only the selected tests and the touched tests listed above.To get this to a good state
RestrictArmsso a selected value can't have been redefined after the inner junction, for example with the dominance condition above.GotoJunctionGuards.cpp. It should leavemergedin place, and it should fail without the fix.Imported from boykopovar/AnyPS5. Originally posted by XairRrR on 2026-11-03T12:17:28Z.
Review: APPROVED
Re-checked — approved
Commit
0eac5c8070adds two conditions to the nested-guard branch ofRestrictArms, which closes the loop-header miscompile from my last review. The new "loop header inner junction" check fails without the fix and passes with it.What changed since my last review
0eac5c8070. The previous five commits are unchanged, per the range-diff.GotoPhiRefiner.cpplines 255–266 now requires two things before it narrows through an inner junction:GotoJunctionGuards.cppaddsCheckLoopHeaderInnerJunction. It is the graph from my last review, and it requires thatmergedis left in place.What I ran
Head
0eac5c8070969ea7ffa6b5725678d82be7ee4f1d,main4f41f4c375f5abb487dbd184fbc150f31994d762, merged treecedd8e001c67b76b700a8e2cd306b91713d913df.git diff --checkcheck_conventions.pymainagc_goto_junction_descriptoragc_goto_junction_guards(6 checks)git status --porcelainis empty; both tests pass againNegative control output
Validation: the script again lists
VUID-vkCmdDispatch-groupCountX-00386as new onagc_driver_native_depth_uniform_planes, marked "(test not run on main)". In my last review I showed that this VUID comes frommain: it shows up the same way with the refiner taken out of the pipeline. This push changes only the body ofRestrictArms, not the pipeline, so it is not a finding. I did not rerun that comparison at this head.Previous findings
CheckLoopHeaderInnerJunction(GotoJunctionGuards.cpp:175). It passes at the head and fails with the refiner from the previous head.New findings
Blocking
None.
Non-blocking
None. One observation: no test pins the condition that the inner junction dominates the predecessor (mutation A passes). On valid SSA it already holds: the outer guard Phi's arm from P is the inner guard Phi, and a Phi operand must dominate its incoming predecessor. The test helper runs
ValidateProgrambefore the pass, so no valid graph can reach this branch with the condition false. It is a cheap defensive check, and it's fine as it is.Not verified
0x200c340000still prepares with the stricter condition. It was not posted at the time of this review, and I did not runagc_shader_replayor any title shaders.agc_*suite; only the tests the script selected and the two new tests ran.agc_driver_native_depth_uniform_planesat this head (it was checked at the previous head; see above).Imported from boykopovar/AnyPS5. Originally posted by XairRrR on 2026-11-03T12:48:13Z.
Review: APPROVED
Re-checked — approved
The only change is commit
0a68c34c10. It removes the check that the inner junction dominates the edge into the outer one. My last review called that check defensive and said valid SSA already guarantees it. The strict-dominance condition that fixes the loop-header case is still there and still tested.What changed since my last review
0a68c34c10. The range-diff shows the previous six commits unchanged.GotoPhiRefiner.cpplines 255–264, thefrom/Dominates(block, from)test is gone. The nested-guard branch now only needs the inner block to be indexed. Then the selected value's definition must strictly dominate the inner junction.0eac5c8070, plus a Little Nightmares replay:0x200c340000still prepares, with the same word counts with or without the fix. I accept these as author-reported.What I ran
Head
0a68c34c101094622d75fed71f63cfa1bad453a2,main4f41f4c375f5abb487dbd184fbc150f31994d762, merged treeb2744169eb04f8035a4b5c39b63aed0c7249d9bf.git diff --checkcheck_conventions.pymainagc_goto_junction_descriptoragc_goto_junction_guards78e43aa03f)git status --porcelainis emptyNegative control output
Previous findings
My last review had no blocking or non-blocking findings.
Observation: no test pinned the predecessor-dominance condition. No longer applies, because the condition was removed. The author's reasoning holds:
IrProgram.cpplines 783–786 rejects a Phi operand whose definition neither dominates its incoming predecessor nor sits in it. The arm is a Phi of the inner block, so the inner block dominates the predecessor P (or is P). My earlier soundness argument still works for every reachable P:For a predecessor that is unreachable from entry, the old code returned
nullptrand the new code may continue. That arm never runs, andRefinedstill requires the replacement to dominate the use, so this does not change results.New findings
Blocking
None.
Non-blocking
None.
Not verified
agc_shader_replayor any title shaders.agc_*suite; only the tests the script selected and the two junction tests ran.