feat(recompiler): reuse pure IR values recomputed in dominated blocks #4948

Merged
fdfawef324 merged 1 commit from upstream-pr/4948 into main 2026-10-14 11:59:06 +00:00
fdfawef324 commented 2026-10-13 06:00:50 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by fdfawef324 on 2026-10-13T06:00:50Z.


What

The IR pipeline has no value numbering, and SPIRV-Tools (whose redundancy elimination would remove the repeats) is off by default (ANYPS5_ENABLE_SPIRV_TOOLS=OFF). So a pure value is emitted again every time the translator rebuilds it. The biggest repeat comes from float operands: in f32 denormal-flush mode every FP instruction flushes each of its sources, and checks each source for NaN, even when the previous instruction already did the same for that register.

RedundantValueEliminator runs in compileVariant just before emission. It walks the dominator tree. When a value has the same opcode, result type, flags and operands as a value earlier in the same block or in a dominating block, its uses are pointed at that earlier value. Block branch conditions, indirect targets and dynamic reads that named a replaced value are redirected too. A block that the entry does not reach throws; the emitter's IR validation already rejects such a program.

What may be merged, and why that keeps semantics

Merged opcodes (the allow-list in Recomputable):

  • bitcasts U16/F16 and U32/F32; conversions U8/U16 to and from U32, F16 to and from F32, S32/U32 to and from F32
  • CompositeConstruct*, CompositeExtract*
  • FPAbs32, FPNeg32, FPSaturate32, BitFieldInsert, BitFieldUExtract, BitFieldSExtract, SelectU1/U32/F32
  • integer add, sub and mul (32 and 64 bit), SMulHi, UMulHi, IAbs32, shifts, and/or/xor/not, BitReverse32, BitCount32/64, FindUMsb32/64, FindILsb32, integer min/max, integer compares, LogicalOr/And/Xor/Not
  • float ordered and unordered compares, FPIsNan32, FPAdd/Sub/Mul/Fma/Mad/Min/Max32, FPFloor/Ceil/Trunc/Fract/RoundEven32

Why merging these is sound:

  • No side effects and no hidden inputs. Each one is a function of its operands only. None reads memory, a register, EXEC, the lane id or another lane, and none writes anything. Two of them with the same opcode, type and flags and the same SSA operands give the same result. None of them reads EXEC implicitly: an IR value sees EXEC only as an explicit operand.
  • The float mode is fixed per program. The translator throws on any runtime MODE change: s_round_mode or s_setreg changing the rounding fields, and s_denorm_mode. So a float op computes the same function everywhere in a program. Every f32 add, sub, mul and fma is emitted with NoContraction, so the driver cannot fuse a shared multiply differently at each use.
  • NaN and signed zero. Operands are compared by SSA identity, never by value, so the rules NaN != NaN and +0 == -0 never come into play. Immediates are compared by type and bit pattern. So x + 0.0 and x + -0.0, which differ for x = -0.0, stay apart, and so do NaN constants with different payloads. Operand order is not canonicalised, so a * b and b * a stay apart.
  • Dominance. The table is scoped by a dominator-tree walk, so the kept value is defined on every path to the use. A value in a loop body is not reused after the loop. A value in one arm of a branch is not reused in the other arm or after the merge. The emitter's ValidateProgram(..., true) checks that every definition still dominates its uses.

Not merged, and why:

  • Loads (buffer, image, address, shared, scratch, vector window): memory can change between two equal loads, through stores, atomics, other invocations or barriers. No load is merged, even with nothing in between.
  • Stores, atomics, Barrier, Waitcnt, exports and every other op with side effects.
  • Cross-lane and wave-level ops (ReadLane, ReadFirstLane, Ballot, DPP, swizzle, permlane), LaneId, and EXEC/VCC/SCC reads: their result depends on EXEC or on other lanes, and those can change between two ops that look equal.
  • Phis: the result depends on the incoming edge.

These figures come from the Demon's Souls (PPSA01342) cold-boot compute programs that take 11 s to 400 s in vkCreateComputePipelines on NVIDIA. Each was replayed from its APS5_DUMP_SHADERS request with agc_shader_replay, once at this PR and once with the pass call removed (which is main):

Program RDNA instructions SPIR-V words, main SPIR-V words, this PR
0x2488f2000 3291 734262 670486
0x2488dc500 3123 689811 628323
0x2488d5500 3089 688301 626242
0x2488c1600 3014 677289 617892
0x2488baa00 2996 676497 616368
0x2488eab00 3072 674586 618681
0x2488e3800 3054 674320 618110
0x2488cea00 2865 627997 573690
0x2488c8100 2847 626939 572542
0x2488b4200 2817 617565 565242
0x2488adc00 2798 617059 564431
0x24892bb00 3123 525289 480800
all 66 replayable requests 12735297 11706468 (-8.1%)

The other 17 of the 83 requests fail resource analysis, with the same message on main and on this PR.

This removes about 9% of the size of these programs, but it is not what makes them giant. Notes on the size:

  • On main, these 12 programs have 168 to 226 words per RDNA instruction (154 to 206 with this PR). Across all 66 programs the ratio is not constant. It runs from 103 (0x248a20500: 22 instructions, 2268 words) to about 1210 (0x2489ed100: 120 instructions, 145276 words on main, 137949 with this PR). So size does not grow linearly with length across the whole set. 0x2489ed100 is far above the trend and is not examined here.
  • On 0x2488d5500, the structurizer clones nothing (each code byte belongs to exactly one IR block). The 3 loops stay loops (3 OpLoopMerge). There is no s_swappc_b64, so no user-data callees are linked.
  • On 0x2488d5500, turning off the f32 denormal-flush emulation gave 461667 words, and turning off NaN propagation as well gave 353568. These came from temporary local switches on the previous base, which are not part of this PR, and they were not remeasured. APS5_SINGLE_LANE=all gives 368101 words. It runs one guest lane per invocation, instead of the two that wave64 needs on a 32-lane NVIDIA subgroup.

Those costs come from exact RDNA float semantics and the wave64 layout, so this PR leaves them alone.

On 0x2488d5500, spirv-opt --redundancy-elimination --eliminate-dead-code-aggressive (built from 3rdparty/SPIRV-Tools) took main's 688301 words and this PR's 626242 words to the same 608293 words. This was measured on the previous base.

Word counts are module sizes, not speed. This PR claims no frame-rate or pipeline-creation-time change, and pipeline creation was not measured.

Tested

OS Windows Server 2025, RTX 3060, GCC 15.2, build-dev Release, ANYPS5_ENABLE_SPIRV_TOOLS=OFF, rebased on main ea2bbefb2. The measurements below were taken on main 7e181fcc3; after the rebase onto ea2bbefb2 only agc_redundant_value_elimination was rebuilt and re-run, and it passes.

  • New agc_redundant_value_elimination test, IR cases.
    • Cases that must merge: repeats in one block, in a dominated block, and in a loop body under its header; the same NaN constant; a replaced branch condition, which is redirected.
    • Cases that must not merge: a sibling block, after a loop, other immediates, operands, opcodes, operand order, flags, result type, immediate type, +0 against -0, two NaN payloads, lane id, ReadFirstLane, ReadLane, DPP, swizzle, shared loads (with nothing, a store or a barrier between them), shared atomics, phis.
    • An unreachable block throws. With RedundantValueEliminator.cpp from the previous revision, which visited unreachable blocks, this case fails.
  • The same test also recompiles a small wave64 compute shader. The shader reads one VGPR in three v_mul_f32 and a v_add_f32 and stores the result. The test checks that no pure SPIR-V instruction in a block repeats an earlier one with the same type and operands. It no longer pins a word count.
    • With the pass call removed it fails (16 repeats in a 1910-word module). With the call it passes (0 repeats, 1640 words).
    • SPIRV-Tools on (as in Linux CI): I could not build with -DANYPS5_ENABLE_SPIRV_TOOLS=ON here, because configuring needs an FFmpeg download that fails on this machine. Instead I ran both modules through spirv-opt with the default pass list from SpirvOptimizer.cpp. Both come out at 1518 words with 0 repeats, so the check also holds there. In that build the check cannot tell whether the pass ran, because SPIRV-Tools removes the repeats itself.
  • agc_shader_replay over all 83 requests, at this PR and with the pass call removed, gives the table above. The same 17 requests fail with the same messages in both builds. All 66 modules from both builds pass spirv-opt --target-env=vulkan1.3 validation, and a module with one operand id corrupted is rejected.
  • ctest -R "^(agc_|shader_)" -j 4 (the libSceAgcDriver and shader recompiler sets, all 385 executables built): 463 tests, none failed, agc_driver_stencil_ref_export skipped.
  • python -I tools/check_test_registration.py build-dev: 750 test executables, 0 built and not run, none new.
  • Not run: any title, the test sets of other libraries, a real ANYPS5_ENABLE_SPIRV_TOOLS=ON build, Linux/lavapipe, AMD, pipeline creation timing.

Checklist

  • Based on current main; no other open PR implements the same functions
  • One topic per PR; follow-ups go in a new PR
  • No comments in code except technical debt
  • Unimplemented paths throw (NotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file
  • No notes, investigation .md files or images added to the repository (attach them to this PR)
  • New third-party code is a submodule built from source
  • Generic behaviour, not specific to one title
  • Depends on: none
  • Unblocks: none
  • GPUs tested: NVIDIA GeForce RTX 3060 12 GB, driver 591.86 (32.0.15.9186), Vulkan 1.4.325, Windows Server 2025 10.0.26100
  • AI-assisted: yes

🤖 Generated with Claude Code

<!-- greyfinch-sync:boykopovar/AnyPS5:issue:4839066768 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/4948). Originally posted by [fdfawef324](https://github.com/fdfawef324) on 2026-10-13T06:00:50Z. --- ### What The IR pipeline has no value numbering, and SPIRV-Tools (whose redundancy elimination would remove the repeats) is off by default (`ANYPS5_ENABLE_SPIRV_TOOLS=OFF`). So a pure value is emitted again every time the translator rebuilds it. The biggest repeat comes from float operands: in f32 denormal-flush mode every FP instruction flushes each of its sources, and checks each source for NaN, even when the previous instruction already did the same for that register. `RedundantValueEliminator` runs in `compileVariant` just before emission. It walks the dominator tree. When a value has the same opcode, result type, flags and operands as a value earlier in the same block or in a dominating block, its uses are pointed at that earlier value. Block branch conditions, indirect targets and dynamic reads that named a replaced value are redirected too. A block that the entry does not reach throws; the emitter's IR validation already rejects such a program. #### What may be merged, and why that keeps semantics Merged opcodes (the allow-list in `Recomputable`): - bitcasts U16/F16 and U32/F32; conversions U8/U16 to and from U32, F16 to and from F32, S32/U32 to and from F32 - `CompositeConstruct*`, `CompositeExtract*` - `FPAbs32`, `FPNeg32`, `FPSaturate32`, `BitFieldInsert`, `BitFieldUExtract`, `BitFieldSExtract`, `SelectU1/U32/F32` - integer add, sub and mul (32 and 64 bit), `SMulHi`, `UMulHi`, `IAbs32`, shifts, and/or/xor/not, `BitReverse32`, `BitCount32/64`, `FindUMsb32/64`, `FindILsb32`, integer min/max, integer compares, `LogicalOr/And/Xor/Not` - float ordered and unordered compares, `FPIsNan32`, `FPAdd/Sub/Mul/Fma/Mad/Min/Max32`, `FPFloor/Ceil/Trunc/Fract/RoundEven32` Why merging these is sound: - **No side effects and no hidden inputs.** Each one is a function of its operands only. None reads memory, a register, EXEC, the lane id or another lane, and none writes anything. Two of them with the same opcode, type and flags and the same SSA operands give the same result. None of them reads EXEC implicitly: an IR value sees EXEC only as an explicit operand. - **The float mode is fixed per program.** The translator throws on any runtime MODE change: `s_round_mode` or `s_setreg` changing the rounding fields, and `s_denorm_mode`. So a float op computes the same function everywhere in a program. Every f32 add, sub, mul and fma is emitted with `NoContraction`, so the driver cannot fuse a shared multiply differently at each use. - **NaN and signed zero.** Operands are compared by SSA identity, never by value, so the rules NaN != NaN and +0 == -0 never come into play. Immediates are compared by type and bit pattern. So `x + 0.0` and `x + -0.0`, which differ for `x = -0.0`, stay apart, and so do NaN constants with different payloads. Operand order is not canonicalised, so `a * b` and `b * a` stay apart. - **Dominance.** The table is scoped by a dominator-tree walk, so the kept value is defined on every path to the use. A value in a loop body is not reused after the loop. A value in one arm of a branch is not reused in the other arm or after the merge. The emitter's `ValidateProgram(..., true)` checks that every definition still dominates its uses. Not merged, and why: - Loads (buffer, image, address, shared, scratch, vector window): memory can change between two equal loads, through stores, atomics, other invocations or barriers. No load is merged, even with nothing in between. - Stores, atomics, `Barrier`, `Waitcnt`, exports and every other op with side effects. - Cross-lane and wave-level ops (`ReadLane`, `ReadFirstLane`, `Ballot`, DPP, swizzle, permlane), `LaneId`, and EXEC/VCC/SCC reads: their result depends on EXEC or on other lanes, and those can change between two ops that look equal. - Phis: the result depends on the incoming edge. These figures come from the Demon's Souls (PPSA01342) cold-boot compute programs that take 11 s to 400 s in `vkCreateComputePipelines` on NVIDIA. Each was replayed from its `APS5_DUMP_SHADERS` request with `agc_shader_replay`, once at this PR and once with the pass call removed (which is main): | Program | RDNA instructions | SPIR-V words, main | SPIR-V words, this PR | |---|---:|---:|---:| | 0x2488f2000 | 3291 | 734262 | 670486 | | 0x2488dc500 | 3123 | 689811 | 628323 | | 0x2488d5500 | 3089 | 688301 | 626242 | | 0x2488c1600 | 3014 | 677289 | 617892 | | 0x2488baa00 | 2996 | 676497 | 616368 | | 0x2488eab00 | 3072 | 674586 | 618681 | | 0x2488e3800 | 3054 | 674320 | 618110 | | 0x2488cea00 | 2865 | 627997 | 573690 | | 0x2488c8100 | 2847 | 626939 | 572542 | | 0x2488b4200 | 2817 | 617565 | 565242 | | 0x2488adc00 | 2798 | 617059 | 564431 | | 0x24892bb00 | 3123 | 525289 | 480800 | | all 66 replayable requests | | 12735297 | 11706468 (-8.1%) | The other 17 of the 83 requests fail resource analysis, with the same message on main and on this PR. This removes about 9% of the size of these programs, but it is not what makes them giant. Notes on the size: - On main, these 12 programs have 168 to 226 words per RDNA instruction (154 to 206 with this PR). Across all 66 programs the ratio is not constant. It runs from 103 (0x248a20500: 22 instructions, 2268 words) to about 1210 (0x2489ed100: 120 instructions, 145276 words on main, 137949 with this PR). So size does not grow linearly with length across the whole set. 0x2489ed100 is far above the trend and is not examined here. - On 0x2488d5500, the structurizer clones nothing (each code byte belongs to exactly one IR block). The 3 loops stay loops (3 `OpLoopMerge`). There is no `s_swappc_b64`, so no user-data callees are linked. - On 0x2488d5500, turning off the f32 denormal-flush emulation gave 461667 words, and turning off NaN propagation as well gave 353568. These came from temporary local switches on the previous base, which are not part of this PR, and they were not remeasured. `APS5_SINGLE_LANE=all` gives 368101 words. It runs one guest lane per invocation, instead of the two that wave64 needs on a 32-lane NVIDIA subgroup. Those costs come from exact RDNA float semantics and the wave64 layout, so this PR leaves them alone. On 0x2488d5500, `spirv-opt --redundancy-elimination --eliminate-dead-code-aggressive` (built from `3rdparty/SPIRV-Tools`) took main's 688301 words and this PR's 626242 words to the same 608293 words. This was measured on the previous base. Word counts are module sizes, not speed. This PR claims no frame-rate or pipeline-creation-time change, and pipeline creation was not measured. ### Tested OS Windows Server 2025, RTX 3060, GCC 15.2, `build-dev` Release, `ANYPS5_ENABLE_SPIRV_TOOLS=OFF`, rebased on main ea2bbefb2. The measurements below were taken on main 7e181fcc3; after the rebase onto ea2bbefb2 only `agc_redundant_value_elimination` was rebuilt and re-run, and it passes. - New `agc_redundant_value_elimination` test, IR cases. - Cases that must merge: repeats in one block, in a dominated block, and in a loop body under its header; the same NaN constant; a replaced branch condition, which is redirected. - Cases that must not merge: a sibling block, after a loop, other immediates, operands, opcodes, operand order, flags, result type, immediate type, +0 against -0, two NaN payloads, lane id, `ReadFirstLane`, `ReadLane`, DPP, swizzle, shared loads (with nothing, a store or a barrier between them), shared atomics, phis. - An unreachable block throws. With `RedundantValueEliminator.cpp` from the previous revision, which visited unreachable blocks, this case fails. - The same test also recompiles a small wave64 compute shader. The shader reads one VGPR in three `v_mul_f32` and a `v_add_f32` and stores the result. The test checks that no pure SPIR-V instruction in a block repeats an earlier one with the same type and operands. It no longer pins a word count. - With the pass call removed it fails (16 repeats in a 1910-word module). With the call it passes (0 repeats, 1640 words). - SPIRV-Tools on (as in Linux CI): I could not build with `-DANYPS5_ENABLE_SPIRV_TOOLS=ON` here, because configuring needs an FFmpeg download that fails on this machine. Instead I ran both modules through `spirv-opt` with the default pass list from `SpirvOptimizer.cpp`. Both come out at 1518 words with 0 repeats, so the check also holds there. In that build the check cannot tell whether the pass ran, because SPIRV-Tools removes the repeats itself. - `agc_shader_replay` over all 83 requests, at this PR and with the pass call removed, gives the table above. The same 17 requests fail with the same messages in both builds. All 66 modules from both builds pass `spirv-opt --target-env=vulkan1.3` validation, and a module with one operand id corrupted is rejected. - `ctest -R "^(agc_|shader_)" -j 4` (the libSceAgcDriver and shader recompiler sets, all 385 executables built): 463 tests, none failed, `agc_driver_stencil_ref_export` skipped. - `python -I tools/check_test_registration.py build-dev`: 750 test executables, 0 built and not run, none new. - Not run: any title, the test sets of other libraries, a real `ANYPS5_ENABLE_SPIRV_TOOLS=ON` build, Linux/lavapipe, AMD, pipeline creation timing. ### Checklist - [x] Based on current `main`; no other open PR implements the same functions - [x] One topic per PR; follow-ups go in a new PR - [x] No comments in code except [technical debt](https://github.com/boykopovar/AnyPS5/blob/main/docs/dev/CONVENTIONS.md) - [x] Unimplemented paths throw (`NotImplemented_nid_no_patch`); silent stubs are listed under Silent stubs in their library's [technical debt](https://github.com/boykopovar/AnyPS5/tree/main/docs/dev/debt) file - [x] No notes, investigation `.md` files or images added to the repository (attach them to this PR) - [x] New third-party code is a submodule built from source - [x] Generic behaviour, not specific to one title - [x] Depends on: none - [x] Unblocks: none - [x] GPUs tested: NVIDIA GeForce RTX 3060 12 GB, driver 591.86 (32.0.15.9186), Vulkan 1.4.325, Windows Server 2025 10.0.26100 - [x] AI-assisted: yes 🤖 Generated with [Claude Code](https://claude.com/claude-code)
xXPBSXx commented 2026-10-13 08:40:05 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by xXPBSXx on 2026-10-13T08:40:05Z.


Windows test (MinGW GCC 15.2, Release, Windows 10, RTX 4080 SUPER). Built on main 534451426 together with six other open GPU PRs (their own commits applied, no merge conflicts), so only the tests that belong to this PR say something about it:

  • tests/RedundantValueElimination.cpp, which ctest runs as agc_redundant_value_elimination: 3 of 3 runs passed.

Not tested: no game run. The batch was built once, not per PR; nothing failed, so no bisect was needed.

AI-assisted (Claude Code).

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6141702024 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/4948#issuecomment-6141702024). Originally posted by [xXPBSXx](https://github.com/xXPBSXx) on 2026-10-13T08:40:05Z. --- Windows test (MinGW GCC 15.2, Release, Windows 10, RTX 4080 SUPER). Built on main `534451426` together with six other open GPU PRs (their own commits applied, no merge conflicts), so only the tests that belong to this PR say something about it: - `tests/RedundantValueElimination.cpp`, which `ctest` runs as `agc_redundant_value_elimination`: 3 of 3 runs passed. Not tested: no game run. The batch was built once, not per PR; nothing failed, so no bisect was needed. AI-assisted (Claude Code).
MarcZX10 commented 2026-10-13 13:59:16 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-13T13:59:16Z.


I built the PR's agc_redundant_value_elimination_tests target on Linux with GCC 12.2, Release, and BUILD_TESTING=ON. CTest agc_redundant_value_elimination passes (1/1).

This validates the focused eliminator suite. I did not run the vkQuake capture or measure its SPIR-V size or pipeline compile time.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6147261588 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/4948#issuecomment-6147261588). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-13T13:59:16Z. --- I built the PR's `agc_redundant_value_elimination_tests` target on Linux with GCC 12.2, Release, and `BUILD_TESTING=ON`. CTest `agc_redundant_value_elimination` passes (1/1). This validates the focused eliminator suite. I did not run the vkQuake capture or measure its SPIR-V size or pipeline compile time.
adriadam10 commented 2026-10-14 11:08:25 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-14T11:08:25Z.


Checked the opcode allow-list (pure, no hidden inputs), the key (opcode, type, flags, SSA operands / immediate bits), the dominator-scoped table and the unreachable-block throw. agc_redundant_value_elimination passes on the PR merged onto main and fails with the pass call removed. Merging once the full Build is green.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6166967470 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/4948#issuecomment-6166967470). Originally posted by [adriadam10](https://github.com/adriadam10) on 2026-10-14T11:08:25Z. --- Checked the opcode allow-list (pure, no hidden inputs), the key (opcode, type, flags, SSA operands / immediate bits), the dominator-scoped table and the unreachable-block throw. `agc_redundant_value_elimination` passes on the PR merged onto main and fails with the pass call removed. Merging once the full Build is green.
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
boykopovar/AnyPS5!4948
No description provided.