shader: skip image remapping for eliminated image instructions #1112

Closed
github-bot wants to merge 1 commit from gh-pr/1112/head into gh-pr/1112/base
Owner

@⁠Nawid3333 on GitHub · 2026-10-06 18:47 UTC · original
Nawid3333:fix/unused-image-remap → main · +50 −2 · 2 files · 1 commits · closed without merging

Problem

A shader whose image instruction ends up unused can abort the whole shader compile with

condition (index >= source_count) is true

in ImageRemap::operator[], called from ApplyResourceSpecialization (ResourceMaterialization.cpp).

Cause

  1. Translation adds one memory_info entry per memory instruction. For an image, resource starts as the descriptor's SGPR number divided by 4.
  2. SSA dead-code elimination deletes image instructions whose result is unused. Their memory_info entries stay in the list.
  3. Resource tracking only gives a real image index to entries of live instructions, so a dead entry keeps its raw SGPR-derived value.
  4. ApplyResourceSpecialization then remaps every image entry. A stale value at or past the number of specialized images trips EXIT_IF(index >= source_count), and the compile aborts.

Any shader can reach this when one of its image results is unused after Kyty's own optimization and the stale value is large enough, e.g. a compute shader whose only image instruction is an unused image_load, or a pixel shader that exports one sample and also has an unused image_load from s[8:15]. I haven't seen a game log with this abort, so this is a robustness fix found through the in-tree tests.

Fix

While the existing per-instruction loop visits image instructions, record which memory_info entries live image instructions reference, and remap only those. The marking happens before the FMASK branch can continue, so a live FMASK read is still marked. GetImageResource flags, buffer image aliases, sampled pairs and indirect roots always refer to live resources and are remapped exactly as before. The EXIT_IF stays in place for live instructions, so a wrong index on a live image still fails loudly.

I checked every other reader of memory_info on current main (SPIR-V emitter, BindingLayout, Program, SrtWalker, Tessellation, ShaderRecompiler): all of them index it through a live instruction's MemoryFlags, so nothing reads the entries this change leaves alone.

How to reproduce

TestNewShaderRecompilerUnusedImageInstructions (added to tests/shaderCfgTests.cpp) covers both cases above:

cmake --build _Build/windows --target shader_cfg_tests
_Build/windows/shader_cfg_tests

With this PR it passes. With only the source change reverted (test kept), it stops with the EXIT_IF above.

Commit

One commit: the fix (+8/−2 in ResourceMaterialization.cpp) and the test (+42). Only the changed lines follow the repo's clang-format hook; the rest of the file is left as it is on main.

Testing

Windows 11, clang-cl 19.1.5, Release, AMD RX 9070 XT, on main d2413fc2:

  • shader_cfg, resource_materialization, resource_tracking pass.
  • Full ctest run (53 tests) plus every --xxx-only mode of shader_recompiler_compute_tests (107 modes), this branch vs. main: identical results.

Before/after on Windows, macOS and Linux (fork CI, https://github.com/Nawid3333/KytyPS5/actions/runs/37545499813): with the source change reverted, the new test stops with the EXIT_IF above on all three; with it, the test passes.

CI on this PR: Windows, Linux and macOS pass (they run resource_tracking and resource_materialization).

  • #937 contains the same idea (a live_image_access vector in 9ab3d7bb, inside "bindless textures behind --bindless"), credit to @⁠itsmemac. It is part of a 51-commit PR that currently conflicts with main and has no regression test for this case; this PR is the standalone version against current main.
  • #690 guards the same loop with if (memory.resource < image_remap.indices.size()). That stops the abort, but it would also silently skip a live image with a bad index, which the EXIT_IF is there to catch; this PR only skips entries of deleted instructions.

If you'd rather fix this at the source instead (for example, marking unpatched image entries dead in resource tracking), I'm happy to rework it that way.

AI use (per the README's AI policy): Claude (Anthropic) diagnosed the root cause, wrote the fix and the test, and ran the testing above on my machine; a second AI pass reviewed the fix adversarially. I reviewed the change and the results before marking this PR ready.

🤖 Generated with Claude Code

**@⁠Nawid3333** on GitHub · 2026-10-06 18:47 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1112) `Nawid3333:fix/unused-image-remap` → `main` · +50 −2 · 2 files · 1 commits · closed without merging ## Problem A shader whose image instruction ends up unused can abort the whole shader compile with ``` condition (index >= source_count) is true ``` in `ImageRemap::operator[]`, called from `ApplyResourceSpecialization` (`ResourceMaterialization.cpp`). ## Cause 1. Translation adds one `memory_info` entry per memory instruction. For an image, `resource` starts as the descriptor's SGPR number divided by 4. 2. SSA dead-code elimination deletes image instructions whose result is unused. Their `memory_info` entries stay in the list. 3. Resource tracking only gives a real image index to entries of live instructions, so a dead entry keeps its raw SGPR-derived value. 4. `ApplyResourceSpecialization` then remaps **every** image entry. A stale value at or past the number of specialized images trips `EXIT_IF(index >= source_count)`, and the compile aborts. Any shader can reach this when one of its image results is unused after Kyty's own optimization and the stale value is large enough, e.g. a compute shader whose only image instruction is an unused `image_load`, or a pixel shader that exports one sample and also has an unused `image_load` from `s[8:15]`. I haven't seen a game log with this abort, so this is a robustness fix found through the in-tree tests. ## Fix While the existing per-instruction loop visits image instructions, record which `memory_info` entries live image instructions reference, and remap only those. The marking happens before the FMASK branch can `continue`, so a live FMASK read is still marked. `GetImageResource` flags, buffer image aliases, sampled pairs and indirect roots always refer to live resources and are remapped exactly as before. The `EXIT_IF` stays in place for live instructions, so a wrong index on a live image still fails loudly. I checked every other reader of `memory_info` on current `main` (SPIR-V emitter, `BindingLayout`, `Program`, `SrtWalker`, `Tessellation`, `ShaderRecompiler`): all of them index it through a live instruction's `MemoryFlags`, so nothing reads the entries this change leaves alone. ## How to reproduce `TestNewShaderRecompilerUnusedImageInstructions` (added to `tests/shaderCfgTests.cpp`) covers both cases above: ``` cmake --build _Build/windows --target shader_cfg_tests _Build/windows/shader_cfg_tests ``` With this PR it passes. With only the source change reverted (test kept), it stops with the `EXIT_IF` above. ## Commit One commit: the fix (+8/−2 in `ResourceMaterialization.cpp`) and the test (+42). Only the changed lines follow the repo's clang-format hook; the rest of the file is left as it is on `main`. ## Testing Windows 11, clang-cl 19.1.5, Release, AMD RX 9070 XT, on `main` d2413fc2: - `shader_cfg`, `resource_materialization`, `resource_tracking` pass. - Full `ctest` run (53 tests) plus every `--xxx-only` mode of `shader_recompiler_compute_tests` (107 modes), this branch vs. `main`: identical results. Before/after on Windows, macOS and Linux (fork CI, https://github.com/Nawid3333/KytyPS5/actions/runs/37545499813): with the source change reverted, the new test stops with the `EXIT_IF` above on all three; with it, the test passes. CI on this PR: Windows, Linux and macOS pass (they run `resource_tracking` and `resource_materialization`). ## Related PRs - **#937** contains the same idea (a `live_image_access` vector in 9ab3d7bb, inside "bindless textures behind --bindless"), credit to @⁠itsmemac. It is part of a 51-commit PR that currently conflicts with `main` and has no regression test for this case; this PR is the standalone version against current `main`. - **#690** guards the same loop with `if (memory.resource < image_remap.indices.size())`. That stops the abort, but it would also silently skip a live image with a bad index, which the `EXIT_IF` is there to catch; this PR only skips entries of deleted instructions. If you'd rather fix this at the source instead (for example, marking unpatched image entries dead in resource tracking), I'm happy to rework it that way. **AI use** (per the README's AI policy): Claude (Anthropic) diagnosed the root cause, wrote the fix and the test, and ran the testing above on my machine; a second AI pass reviewed the fix adversarially. I reviewed the change and the results before marking this PR ready. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
ApplyResourceSpecialization remapped the resource index of every image
memory_info entry, including entries whose instructions dead-code
elimination had already removed. Those entries keep the index derived
from the SGPR operand at translation, so a shader with an unused image
result could hit EXIT_IF(index >= source_count) in ImageRemap and abort
the compile. Only remap entries that a live image instruction still
references; GetImageResource flags, buffer aliases, sampled pairs and
indirect roots always point at live resources and are remapped as
before.

TestNewShaderRecompilerUnusedImageInstructions covers a compute shader
whose only image instruction is an unused image_load and a pixel shader
that exports one sample and also has an unused image_load; it aborts
with the EXIT_IF above without this change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:43:26 +00:00
github-bot closed this pull request 2026-11-26 09:43:26 +00:00
Author
Owner

@⁠Nawid3333 on GitHub · 2026-10-06 20:50 UTC · original

@⁠coderabbitai review

**@⁠Nawid3333** on GitHub · 2026-10-06 20:50 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1112#issuecomment-6025209740) @⁠coderabbitai review
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-06 20:51 UTC · original · edited 2026-10-06 20:54 UTC

✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-06 20:51 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1112#issuecomment-6025211791) · edited 2026-10-06 20:54 UTC <!-- This is an auto-generated reply by CodeRabbit --> <!-- CodeRabbit review command invocation: v2:f04716eb379930b3bcb00f948cea7edbe31939302b05ef46efd89f700ff9e462 --> <details> <summary>✅ Action performed</summary> Review finished. > Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused. </details>
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-06 20:54 UTC · original · edited 2026-10-07 15:25 UTC

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 2d91173c-3946-43b8-8012-0d4cbed8167f
📥 Commits

Reviewing files that changed from the base of the PR and between 97849ee350745af1f3f2fb1bc0efdfc95bdff86d and f016017a3c34895c2e8da75fa9f7621c78d33421.

📒 Files selected for processing (1)
  • src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.


📝 Walkthrough

Walkthrough

ApplyResourceSpecialization now remaps image memory entries only when image instructions reference them, and only when they are image resources that are not planning-only. New tests check resource counts for unused image loads in compute and pixel shaders. Both tests validate SPIR-V.

Priority: ➖ Normal

Change: Bug fix

Merge Risk: ⚪ Minimal · up to f0160

No confirmed merge-blocking issue remains; the change is ready for normal merge checks.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 1 functions across 1 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly and concisely describes the main change: avoiding image remapping for image instructions eliminated by dead-code removal.
Description check ✅ Passed The description is directly related to the changeset. It explains the stale memory entry failure, the remapping fix, the regression tests, and the reported validation.
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-06 20:54 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1112#issuecomment-6025270601) · edited 2026-10-07 15:25 UTC <!-- This is an auto-generated comment: summarize by coderabbit.ai --> <!-- review_stack_entry_start --> <a href="https://app.coderabbit.ai/change-stack/KytyPS5/KytyPS5/pull/1112?scope=ghh_OusAJGA4HG8ljoOV0wJvVx8NmnZIjc2DdjmxOu0xZWA&amp;cs_source=review_comment"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui-dark.svg?v=2" alt="Review in Change Stack →" width="220" height="32"></a> <!-- review_stack_entry_end --> <!-- recent_review_start --> No actionable comments were generated in the recent review. 🎉 <details> <summary>ℹ️ Recent review info</summary> <details> <summary>⚙️ Run configuration</summary> - **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `2d91173c-3946-43b8-8012-0d4cbed8167f` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 97849ee350745af1f3f2fb1bc0efdfc95bdff86d and f016017a3c34895c2e8da75fa9f7621c78d33421. </details> <details> <summary>📒 Files selected for processing (1)</summary> * `src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp` </details> <details> <summary>🚧 Files skipped from review as they are similar to previous changes (1)</summary> * src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review. </details> --- <!-- recent_review_end --> <!-- walkthrough_start --> <details> <summary>📝 Walkthrough</summary> ## Walkthrough `ApplyResourceSpecialization` now remaps image memory entries only when image instructions reference them, and only when they are image resources that are not planning-only. New tests check resource counts for unused image loads in compute and pixel shaders. Both tests validate SPIR-V. </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ➖ Normal <!-- change_assessment_commit:"f016017a3c34895c2e8da75fa9f7621c78d33421" --> **Change:** Bug fix <!-- change_assessment_end --> <!-- final_review_risk_start --> **Merge Risk:** _⚪ Minimal_ · up to `f0160` <!-- final_review_risk_coverage:{"sourceCommitId":"f016017a3c34895c2e8da75fa9f7621c78d33421","coveredCommitId":"f016017a3c34895c2e8da75fa9f7621c78d33421","kind":"reviewed"} --> No confirmed merge-blocking issue remains; the change is ready for normal merge checks. <!-- final_review_risk_end --> <!-- pre_merge_checks_walkthrough_start --> <details> <summary>🚥 Pre-merge checks | ✅ 4 | ❌ 1</summary> ### ❌ Failed checks (1 warning) | Check name | Status | Explanation | Resolution | | :----------------: | :--------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------- | | Docstring Coverage | ⚠️ Warning | Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 1 functions across 1 files. | Write docstrings for the functions missing them to satisfy the coverage threshold. | <details> <summary>✅ Passed checks (4 passed)</summary> | Check name | Status | Explanation | | :------------------------: | :------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Linked Issues check | ✅ Passed | Check skipped because no linked issues were found for this pull request. | | Out of Scope Changes check | ✅ Passed | Check skipped because no linked issues were found for this pull request. | | Title check | ✅ Passed | The title clearly and concisely describes the main change: avoiding image remapping for image instructions eliminated by dead-code removal. | | Description check | ✅ Passed | The description is directly related to the changeset. It explains the stale memory entry failure, the remapping fix, the regression tests, and the reported validation. | </details> </details> <!-- pre_merge_checks_walkthrough_end --> <!-- autopilot:start --> - [ ] <!-- {"checkboxId":"2708ad07-9f24-4260-9c11-7dc76a49f2e3"} --> <strong title="Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts">Autopilot</strong> · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts <!-- autopilot:end --> <!-- tips_start --> --- Thanks for using [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=KytyPS5/KytyPS5&utm_content=1112)! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. <details> <summary>❤️ Share</summary> - [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai) - [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai) - [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai) - [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code) </details> <sub>Comment `@coderabbitai help` to get the list of available commands.</sub> <!-- tips_end -->

Pull request closed

This discussion has been locked. Commenting is limited to contributors.
No description provided.