fix(shader): drop module constants nothing references after specialization #5315
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/5315"
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 AlxcBTW on 2026-10-13T17:02:04Z.
What
Two pipeline variants of one program that differ only in a folded specialization value now produce the same SPIR-V. The second variant is then served by the pipeline cache instead of a cold compile.
buildSpecializedModulematerializes a variant's specialization values asOpConstant, andSpecializeSpirvfolds them into the code. The folding left the materialized constants in the module with no use.Image channel selectors (
RuntimeImageSwizzle) are such values. So two variants of a program whose only difference was an image's channel order, 4,5,6,7 vs 6,5,4,7, had identical code but different SPIR-V, and the second one was created and compiled again.removeUnusedConstantsnow also removes scalar and null module constants (OpConstant,OpConstantTrue/False,OpConstantNull) that no instruction references any more.OpConstantCompositeis not removed:VisitIdOperandscounts a composite's own result id as a reference, so a composite and its members always stay.Runalready drops the names and decorations of removed ids.Evidence from Sword of the Sea (PPSA25344), loading on a cold cache, compute programs of 100k+ SPIR-V words. Every pipeline's SPIR-V was dumped (
APS5_DUMP_COMPUTE_PIPELINES) and diffed withspirv-dis --raw-id:OpConstantvalues that nothing in the module uses: each id occurs once, at its definition. The values are 4/5/6/7 in another order. The 15th pair is a real variant (10,738 differing lines).Test change: agc_formatted_buffer_once
@adriadam10, this touches the bound from
56d5a4985. That bound checks that a formatted load from a descriptor with a known format does not carry every format's decoder in registration form, measured against the specialized module.This change shrinks both modules, the specialized one more, so the ratio between them moves. Sizes in words, from this PR's fork CI and from
main0214069e3on the same runners:mainmainThe bound moves from 1.5x to 1.6x of the specialized module. A registration module that kept every decoder would be about as large as the GPU-selected compute module, about 14,000 words on current
main(13,897; it was 85,945 when this PR was opened, before #3656), so 1.6x still catches it.I first tried bounding the registration module against a vertex module with a GPU-selected descriptor instead, which would have measured the property directly. The recompiler rejects that request in both forms ("buffer specialization has an unsupported format"), so the test keeps its original comparison.
Tested
agc_shader_disk_cache, newverifySpecializationDropsDeadConstants:OpNameare gone;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 oneandonlydean on 2026-10-14T06:18:57Z.
Conflicts with main in
tests/ShaderDiskCache.cpp; please rebase.The description says the cold-load before/after follows as a comment; it isn't here yet. Please add it (main against main plus this PR, same machine and scene), since the gain is the reason for the change.
Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-14T21:33:21Z.
Still needs the rebase for
tests/ShaderDiskCache.cpp(10-14) and the cold-load before/after the description promises: main against main plus this PR, same machine and scene.Imported from boykopovar/AnyPS5. Originally posted by AlxcBTW on 2026-10-15T18:38:21Z.
@oneandonlydean rebased onto
main03c4cb5e7.Conflict.
tests/ShaderDiskCache.cpp:mainadded the resource plan fixtures at the place where this PR addsverifySpecializationDropsDeadConstants. Both are kept, the new test stays right afterverifySpecializationLiveness. The#include <set>was not used by the file and is gone.SpirvSpecialization.cppandFormattedBufferOnce.cppappliedwithout changes.
tools/check_conventions.py --base origin/mainpasses.Tests (fork, Linux, lavapipe, SPIRV-Tools on, all 605
agc_tests):agc_driver_mesh_index_cacheaborts withLLVM ERROR: Cannot emit physreg copy instructioninside llvmpipe's JIT.main03c4cb5e7(run 38781698319): the same test aborts the same way, 604 pass. It is not related to this change.agc_shader_disk_cache(with the new test),agc_formatted_buffer_once,agc_spirv_module,agc_spirv_optimizerandthe other recompiler tests pass in both runs.
libsandrelinkertargets compile (fork run 38781966955, MinGW). The Windows ctest run was not repeated on this base.Sizes in
agc_formatted_buffer_once, words, Linux with SPIRV-Tools, measured on the rebased tree:main03c4cb5e7The 1.6x bound is still needed: 1.5x of 1126 is 1689 words and the registration module has 1739; 1.6x gives 1801. The
GPU-selected compute module is 13,897 words now (it was 85,945 when this PR was opened; #3656 decodes it from a format
table), so "tens of thousands of words" in the description no longer fits. A registration module that kept the decoders of
every format would be about as large as that compute module, roughly 14,000 words, far above 1801.
Cold load. The Sword of the Sea dump the description was written against is gone, so the before/after runs on Minecraft Dungeons II (PPSA16064) at its title screen, one machine (RTX 5070 Laptop 8 GB, NVIDIA 617.42, Windows 11),
main03c4cb5e7againstmainplus this PR, four alternating cold rows with the shader cache emptied before each. It is queued on the lab machine tonight; the numbers follow in the next comment.Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-17T00:41:25Z.
The rebase is right, both tests kept. The
agc_driver_mesh_index_cachellvmpipe abort also happens onmain, so it isn't this PR. The size table is useful (specialized vertex 1348 to 1126 words, compute with a known descriptor 1209 to 987). What's left is the four alternating cold rows with the cache emptied before each.Imported from boykopovar/AnyPS5. Originally posted by AlxcBTW on 2026-10-17T05:45:18Z.
Cold-load numbers from Minecraft Dungeons II (PPSA16064) on Windows 11, NVIDIA GeForce RTX 5070 Laptop GPU (617.42): two rows per arm,
mainand this PR alternating, each with an empty AnyPS5 shader cache, boot to the title.vk-pipelinescache fileSo the change does what it says: the two specializations that differed only in constants nothing references now share one module, and the modules are 10 % smaller. The 15.7 s in the PR's first row is the NVIDIA driver compiling the new modules once: the driver keeps its own cache outside the row's
LOCALAPPDATA, so themainrows started with modules it had already seen, and the PR's second row is back at 0.7 s. That row does not measure the change, and I'd not claim a load-time win from these numbers; the gain is fewer and smaller modules.AI-assisted: yes (Claude Code)
Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-19T10:54:55Z.
@AlxcBTW Since your 15 Oct rebase,
maingained3e1f932d41(#6176, "share folded SPIR-V constants and drop identity bitcasts"). It already removes unused folded constants, but it keeps the definitions that undecoded consumers (subgroup and extended instructions) still name.Merged onto current
main, this PR's sweep doesn't keep those, so two tests fail:main'sagc_spirv_optimizer: "specialization kept an unreferenced folded constant or lost a referenced one"verifySpecializationDropsDeadConstantsinagc_shader_disk_cache: "variants that differ only in a folded constant specialized to different SPIR-V"With
main'sSpirvSpecialization.cpp, the optimizer test passes. The text merge is clean, so CI on the old base doesn't show this.Could you rebase onto current
main, keep the constants thatmain's removal keeps, and show both tests passing? Please also say what this PR still adds on top of3e1f932d41, for example module word counts before and after onmain. Thanks!Imported from boykopovar/AnyPS5. Originally posted by THEMANnt on 2026-10-26T13:50:24Z.
Review: APPROVED
Reviewed
1ea471b57089against merge base03c4cb5e78e0. Recommend approval; no actionable finding in the complete three-file patch.The iterative cleanup removes unused specialized constants and associated metadata while retaining referenced array lengths and the composite operands preserved by the current visitor. Reviewed the specialization-to-cache/compilation flow and the adjusted formatted-buffer size bound.
Validation: Built
agc_shader_disk_cache_testson candidate and base with Windows GCC 15.3; both CTest runs pass. An additional review-only harness passes checks for dead scalar/bool/null constants, consumed-value/name removal, retained array/composite operands, unchanged input and idempotence. Its initially incorrect composite-removal expectation was corrected before the final passing run; no production source was changed.Scope:
ANYPS5_ENABLE_SPIRV_TOOLS=0, so no independent SPIR-V validator ran. No local Linux/lavapipe execution; hosted product jobs were skipped. The baseline's original-suite pass is not a failing-old-code regression control.Imported from boykopovar/AnyPS5. Originally posted by jotitadev on 2026-10-27T08:25:36Z.
Review: COMMENTED
Follow-up to my merge-skew note above, now with
ANYPS5_ENABLE_SPIRV_TOOLS=ON(that build did not have it). Linux, i7-8700, Ubuntu 26.04, GCC 15.2, Release. Head1ea471b57merged with--no-ffontomain8df2c3ed0. lavapipe (Mesa 26.0.3).The disk-cache fix from my earlier comment does not cover the optimizer test @oneandonlydean mentioned:
agc_shader_disk_cacheagc_spirv_optimizer(+_full,_none)mainmain+ this PRmain+ this PR + the 6-lineSpirvSpecialization.cppfixOnly one check fails in
testSpecializedConstantsAreShared: "specialization kept an unreferenced folded constant or lost a referenced one" (constants.size() == 5u). The module itself is fine:ValidateAndOptimizeSpirvaccepts it and every other check in that test passes (sharing, no bitcasts or copies,lane + 23, stable second pass).The two missing constants are not folded ones.
mainleaves%one = 1and%three = 3from the source in place (it only drops unreferenced constants that the folding itself materialized), so the test expects 1, 2, 3, 7, 8. This PR's sweep also removes original module constants that nothing references, so the output has 2, 7, 8. That is the intended effect of the PR, so it comes down to which behaviourmainwants:3u, ormain'sremoveUnusedConstantsalready removes.With the disk-cache fix plus
5u→3u, the^agcsuite on lavapipe with SPIRV-Tools ON (1053 tests, display/flip/lds_atomics64 excluded) matchesmain: 1051/1053, failing onlyagc_driver_multisample_retirementandagc_driver_guest_memory_lifetime_converted, which fail onmaintoo.GPUs tested: lavapipe (Mesa 26.0.3) for everything above. On
main, the 10 tests that only exist with SPIRV-Tools ON also pass on an RTX 3070 (NVIDIA 595.99.02).Written with AI assistance (Claude Code). I ran the builds and tests above on my machine.
Imported from boykopovar/AnyPS5. Originally posted by BunnyFl on 2026-11-04T18:14:01Z.
Review: CHANGES_REQUESTED
@AlxcBTW the new
verifySpecializationDropsDeadConstantsfails once this PR is merged into currentmain(runs below). So onmain, the two variants in the test still specialize to different SPIR-V.What I ran: head
1ea471b570merged ontomain9ab6a281ea(clean merge,e4a39e6cd3). Windows 11, WinLibs GCC 15.2.0, AMD RX 9070 XT,ANYPS5_REQUIRE_VULKAN=1 ANYPS5_NO_SHADER_CACHE=1 VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation:agc_formatted_buffer_oncepasses.agc_shader_disk_cachefails withvariants that differ only in a folded constant specialized to different SPIR-V.main'sSpirvSpecialization.cpprestored, it fails the same way.VUID-errors and no missing-layer lines in either run.03c4cb5e78):agc_shader_disk_cachepasses. So the failure comes from whatmainhas changed inSpirvSpecialization.cppsince then (13 commits, merges included).Why, as far as I read it (
main9ab6a281ea):emplace(SpirvSpecialization.cpp#L394).foldturns an instruction into a constant whose value is already canonical, it records an alias to that id (#L623).shareConstants(#L849) then rewrites the uses to the canonical id.Runcalls it (#L428) beforeremoveUnusedConstants(#L431).%6and the selected constant is%7 = 4. With selector 4,%6and%7both hold 4, and%6is emitted first. By theemplaceat #L394 above, the foldedOpSelectthen aliases to%6, and the store reads%6. With selector 6, the store reads%7.OpConstant %3 %6 4plusOpStore %8 %6, againstOpConstant %3 %7 4plusOpStore %8 %7.module(4u)tomodule(8u), which gives selector 8, a value no other constant in the test module has.agc_shader_disk_cachethen passes. That fits the explanation above.The channel selectors from the description (4, 5, 6, 7) are the kind of values that may equal another constant in a real module, so the cache misses may persist on
mainfor those programs. I haven't checked that on a real module. For the fix, one option is to make the canonical id independent of the selector's value. For example, re-number the surviving constants after removal, or prefer the constant that the folded instruction's own operands name. Either way, the test needs to pass on the merge with currentmain.Also checked:
pr_overlap.py --branchon the head: no conflicting lines or shared exports. 20 PRs that conflict withmainshare files and couldn't be compared. The only one onSpirvSpecialization.cppis #8004, which moves helpers nearVisitInputsand doesn't touchremoveUnusedConstantsor the constant sharing.OpConstantCompositeis not removed, but the loop does include it in the opcodes it removes. Whether a composite is ever unreferenced depends onVisitIdOperands, which I haven't read through.Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-23T03:06:51Z.
Review: APPROVED
Reviewed — looks good
Nothing blocks this change; the implementation and focused regression test support the stated dead-constant cleanup.
What I ran
Reviewed head
1ea471b57089e902583e51e5cf8aa0a7b8a6a5c2usingrepo_read.pyto inspect the prepared diff and relevant code. No commands or tests were run in this review.Results
Findings
Blocking
None.
Non-blocking
None.
Not verified
Did not run tests or independently verify the reported CI and game performance measurements. Read all three changed files:
FormattedBufferOnce.cpp,ShaderDiskCache.cpp, andSpirvSpecialization.cpp. No changed files were excluded;files.jsonwas not available through the reader.To get this to a good state
Nothing is required.
Pull request closed