raytracing: Software RT with --raytracing #1559

Open
github-bot wants to merge 25 commits from github-bot/gh-1559 into main AGit
Owner

@⁠defektu on GitHub · 2026-10-16 15:46 UTC · original
defektu:pr/mfgt-raytracing → main · +5001 −260 · 68 files · 25 commits · open

Part of getting My First Gran Turismo (PPSA24156) running with ray tracing (reflections). This PR adds --raytracing (off by default) and the compute path behind it. Draft.

Dependencies: the title does not start on main alone. It needs the tessellation lowering (#1032) and mixed sample counts / EQAA (#1035) first; neither is part of this PR. #1032 is based on d7974dc7 ("Fix scalar buffer reads across sparse guest mappings"), which main has since reverted (d01633e1): test this PR with #1032 and #1035 merged on top of current main, not on a base that still has d7974dc7.

What it does

The game's ray tracing kernels are compute shaders that call a table of about 290 shader functions, chosen by the GPU at run time.

  • The table is inlined into call groups with shared function bodies (one dispatch per group and z slice), instead of one giant shader.
  • Descriptors behind GPU-selected call tables are tracked and materialized: candidate lists are padded to a fixed size so the program does not change with the table's contents, and raw dword loads and stores go through GPU-selected buffer descriptors.
  • Pipelines compile on worker threads (KYTY_RT_COMPILE_SLOTS, default 12, 1..16). A dispatch waits for its pipeline, because skipping one leaves its part of the image unlit (the reflections).
  • A kernel only inlines the functions the GPU has been seen to call. When the GPU calls one that has no copy, the kernel is retranslated with it (at most every 5 s per kernel). The functions learned this way are kept across runs (by the hash of their bodies, in _PipelineCache/rtfn_*.txt).
  • While a retranslated kernel compiles, its previous program keeps running (see the design note in the comments).
  • A loop watchdog keeps a runaway kernel from hanging the GPU.
  • Everything ray tracing specific is keyed on the program being a call-table kernel, not on the --raytracing switch, so other titles are not affected by the option.
  • Supporting fixes: 64-bit buffer atomic add, scaled and packed-float image formats, S_CODE_END, image creation fallback, buffers outside mapped memory (bound as null with a warning), unaligned read-only storage buffers (copied to an aligned stream range, with a warning).

Known gaps

  • The first launch compiles about a hundred large pipelines in the driver, tens of seconds to minutes each (longest seen: 257 s), so it takes many minutes with a cold pipeline cache and driver cache. Later launches are much faster. Each concurrent compile holds gigabytes (16 slots peaked at about 16 GB, 12 slots about 27 GB for the whole process); lower KYTY_RT_COMPILE_SLOTS on small machines. Retranslation adds a few pipelines while the scene reveals new functions (about 110 in total in a long run).
  • Steady state is roughly 430 to 450 ms per frame on an RTX 5060 Ti.
  • The SCC "any lane" branch semantics that waterfall loops need are only applied to call-table kernels. Applying them to every program broke descriptor tracking in shader_recompiler_compute_tests.
  • One long run on the combined tree ended in a GPU hang (ErrorDeviceLost in MasterSemaphore::Wait) about 5 minutes after a kernel was retranslated several times in a row; the log was repeating RT calls: unexpected call table stride=16 records=4578. I do not know yet whether that is related to the fallback described above or was always there.

Testing: Windows (Release, clang-cl). On main at 5dec5231 with this PR: resource_tracking_tests, resource_materialization_tests, scalar_provenance_tests, shader_cfg_tests and shader_recompiler_compute_tests pass. With #1032 and #1035 merged on top, the game shows the reflections (109 pipelines compiled, 12 retranslations in a long run).

🤖 Generated with Claude Code

**@⁠defektu** on GitHub · 2026-10-16 15:46 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1559) `defektu:pr/mfgt-raytracing` → `main` · +5001 −260 · 68 files · 25 commits · open Part of getting My First Gran Turismo (PPSA24156) running with ray tracing (reflections). This PR adds `--raytracing` (off by default) and the compute path behind it. **Draft.** **Dependencies:** the title does not start on `main` alone. It needs the tessellation lowering (#1032) and mixed sample counts / EQAA (#1035) first; neither is part of this PR. #1032 is based on d7974dc7 ("Fix scalar buffer reads across sparse guest mappings"), which `main` has since reverted (d01633e1): test this PR with #1032 and #1035 merged on top of current `main`, not on a base that still has d7974dc7. **What it does** The game's ray tracing kernels are compute shaders that call a table of about 290 shader functions, chosen by the GPU at run time. - The table is inlined into call groups with shared function bodies (one dispatch per group and z slice), instead of one giant shader. - Descriptors behind GPU-selected call tables are tracked and materialized: candidate lists are padded to a fixed size so the program does not change with the table's contents, and raw dword loads and stores go through GPU-selected buffer descriptors. - Pipelines compile on worker threads (`KYTY_RT_COMPILE_SLOTS`, default 12, 1..16). A dispatch waits for its pipeline, because skipping one leaves its part of the image unlit (the reflections). - A kernel only inlines the functions the GPU has been seen to call. When the GPU calls one that has no copy, the kernel is retranslated with it (at most every 5 s per kernel). The functions learned this way are kept across runs (by the hash of their bodies, in `_PipelineCache/rtfn_*.txt`). - While a retranslated kernel compiles, its previous program keeps running (see the design note in the comments). - A loop watchdog keeps a runaway kernel from hanging the GPU. - Everything ray tracing specific is keyed on the program being a call-table kernel, not on the `--raytracing` switch, so other titles are not affected by the option. - Supporting fixes: 64-bit buffer atomic add, scaled and packed-float image formats, `S_CODE_END`, image creation fallback, buffers outside mapped memory (bound as null with a warning), unaligned read-only storage buffers (copied to an aligned stream range, with a warning). **Known gaps** - The first launch compiles about a hundred large pipelines in the driver, tens of seconds to minutes each (longest seen: 257 s), so it takes many minutes with a cold pipeline cache and driver cache. Later launches are much faster. Each concurrent compile holds gigabytes (16 slots peaked at about 16 GB, 12 slots about 27 GB for the whole process); lower `KYTY_RT_COMPILE_SLOTS` on small machines. Retranslation adds a few pipelines while the scene reveals new functions (about 110 in total in a long run). - Steady state is roughly 430 to 450 ms per frame on an RTX 5060 Ti. - The SCC "any lane" branch semantics that waterfall loops need are only applied to call-table kernels. Applying them to every program broke descriptor tracking in `shader_recompiler_compute_tests`. - One long run on the combined tree ended in a GPU hang (`ErrorDeviceLost` in `MasterSemaphore::Wait`) about 5 minutes after a kernel was retranslated several times in a row; the log was repeating `RT calls: unexpected call table stride=16 records=4578`. I do not know yet whether that is related to the fallback described above or was always there. **Testing:** Windows (Release, clang-cl). On `main` at 5dec5231 with this PR: `resource_tracking_tests`, `resource_materialization_tests`, `scalar_provenance_tests`, `shader_cfg_tests` and `shader_recompiler_compute_tests` pass. With #1032 and #1035 merged on top, the game shows the reflections (109 pipelines compiled, 12 retranslations in a long run). 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
A predicated register write is a select over U32 register values, so a float chain pays two bitcasts per step. When every
user of a select or phi takes the value back as F32 (or is in the same web), the web is held as F32 and the bitcast pairs
go; users that need integers share one bitcast back. Bitcasts already available in a single-predecessor chain are reused
instead of restarting per block, and the pass repeats until nothing changes. The four largest call-table kernels lose
about 11-17% of their SPIR-V words.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
The aligned dword, the crossing dword and the funnel shift were emitted at every guest read (hundreds per kernel); one
function per width now holds them. Guards that are the constant true no longer emit a branch and phi.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
- Compile per z slice only for call-table kernels (has_inlined_calls); other compute shaders resolve workgroup-z descriptors themselves. This made shader_recompiler_compute_tests dereference a null program.
- Remove the stale k8_8UScaled table entry (component count 0) that shadowed the correct one.
- Packed 10:10:10:2 float: RGB are unsigned E4M6 with a finite exponent-15 range, alpha is UNorm2. Reads decode and stores encode in the shader; the image is backed by r32uint.
With these, shader_recompiler_compute_tests passes.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:59:38 +00:00
Author
Owner

@⁠defektu on GitHub · 2026-10-16 15:48 UTC · original

Takes up upto 15 mins to compile pipelines. It is draft and sometimes drops or recompiles pipelines. So a bit unstable. Beware of that.
gt1559-2
gt1559-1

**@⁠defektu** on GitHub · 2026-10-16 15:48 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1559#issuecomment-6219213740) Takes up upto 15 mins to compile pipelines. It is draft and sometimes drops or recompiles pipelines. So a bit unstable. Beware of that. <img width="346" height="169" alt="gt1559-2" src="https://github.com/user-attachments/assets/267f508d-367e-4ef0-98f2-43055d02431f" /> <img width="348" height="170" alt="gt1559-1" src="https://github.com/user-attachments/assets/a9da73a6-6068-452e-a2a3-9a05a0539ae6" />
Author
Owner

@⁠defektu on GitHub · 2026-10-16 21:14 UTC · original · edited 2026-10-16 21:35 UTC

Design note: a retranslated kernel keeps running its previous program until the new pipeline is compiled

A call-table kernel inlines only the functions the GPU has been seen to call. When the GPU calls a function that has no inlined copy, the kernel is retranslated with that function, and each call group that grew gets a new pipeline. Compiling one of these pipelines takes from seconds to minutes (257 s at worst on an RTX 5060 Ti), and a dispatch that waits for it freezes the game: in a run with a cold pipeline cache the frame counter barely moved for minutes at every retranslation.

This PR therefore keeps the previous program of a retranslated kernel as a fallback. Its dispatches keep running with the old pipeline while the new one compiles on a worker thread; once the new pipeline is ready the dispatches switch to it and the old program is dropped. Without a usable previous program (the first translation of a kernel) a dispatch still waits for its pipeline, because skipping it leaves its part of the image unlit.

The trade-off: for the seconds a retranslated pipeline compiles, a call to a function the old program does not inline takes the same path it took before the retranslation, so that part of the reflections can be missing until the switch. With this the game stayed responsive during retranslations (about 35 frames per 20 s on a cold cache, against a handful before).

Open: one long run on the combined tree (this PR + #1032 + #1035) ended in a GPU hang (ErrorDeviceLost) a few minutes after a kernel was retranslated several times in a row, with the log repeating RT calls: unexpected call table stride=16 records=4578. I have not yet established whether the fallback has anything to do with it, so I am not sure this is the right call. The alternative is to hold the game at every retranslation, which is what the first version of this PR did. Feedback welcome.

Expect crashes, memory leaks and flashing pictures.

**@⁠defektu** on GitHub · 2026-10-16 21:14 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1559#issuecomment-6224820179) · edited 2026-10-16 21:35 UTC **Design note: a retranslated kernel keeps running its previous program until the new pipeline is compiled** A call-table kernel inlines only the functions the GPU has been seen to call. When the GPU calls a function that has no inlined copy, the kernel is retranslated with that function, and each call group that grew gets a new pipeline. Compiling one of these pipelines takes from seconds to minutes (257 s at worst on an RTX 5060 Ti), and a dispatch that waits for it freezes the game: in a run with a cold pipeline cache the frame counter barely moved for minutes at every retranslation. This PR therefore keeps the previous program of a retranslated kernel as a fallback. Its dispatches keep running with the old pipeline while the new one compiles on a worker thread; once the new pipeline is ready the dispatches switch to it and the old program is dropped. Without a usable previous program (the first translation of a kernel) a dispatch still waits for its pipeline, because skipping it leaves its part of the image unlit. The trade-off: for the seconds a retranslated pipeline compiles, a call to a function the old program does not inline takes the same path it took before the retranslation, so that part of the reflections can be missing until the switch. With this the game stayed responsive during retranslations (about 35 frames per 20 s on a cold cache, against a handful before). Open: one long run on the combined tree (this PR + #1032 + #1035) ended in a GPU hang (`ErrorDeviceLost`) a few minutes after a kernel was retranslated several times in a row, with the log repeating `RT calls: unexpected call table stride=16 records=4578`. I have not yet established whether the fallback has anything to do with it, so I am not sure this is the right call. The alternative is to hold the game at every retranslation, which is what the first version of this PR did. Feedback welcome. Expect crashes, memory leaks and flashing pictures.
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-21 21:31 UTC · original

Review in Change Stack →

📝 Walkthrough

The pull request adds an experimental ray-tracing option and implements compute-shader call-table expansion, feedback, resource specialization, and asynchronous pipeline compilation. It also adds packed texture format handling and 64-bit buffer atomics. Vulkan image and descriptor paths gain fallback handling. Shader IR validation, SSA rewriting, and scalar optimization passes are updated, with new tests for these changes.

Suggested reviewers: nmzik, senaxx, claxten10

Priority: ➖ Normal

Change: Feature

Merge Risk: 🟠 High · up to fa1d9

This change breaks compilation on supported Linux and macOS builds, and introduces a descriptor-repair path that can silently corrupt texture/sampler descriptors even with ray tracing disabled. The experimental ray-tracing path also has issues that can run function bodies twice, skip unrelated compute dispatches, and leak shader modules. These should be resolved before merging.

Pre-merge checks: Passed 4 · Inconclusive 1

Failed Failed checks: 1 inconclusive

Check name Status Explanation Resolution
Docstring Coverage Inconclusive Docstring coverage is 20.83% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 216 functions across 50 files. (18 skippe… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Title check Passed The title clearly and concisely identifies the main change: an off-by-default software ray-tracing path controlled by --raytracing.
Description check Passed The description directly explains the ray-tracing option, compute implementation, dependencies, testing, limitations, and known issues. It is fully related to the changeset.
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.
Full details: Docstring Coverage

Explanation

Docstring coverage is 20.83% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 216 functions across 50 files. (18 skipped: 3 unsupported, 15 over the file limit.)

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

  • Autofix · 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-21 21:31 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1559#issuecomment-6327011373) <!-- coderabbit-ai-generated:v1 --> <!-- 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/1559?scope=ghh_OusAJGA4HG8ljoOV0wJvVx8NmnZIjc2DdjmxOu0xZWA&amp;cs_source=review_comment"><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui-dark.svg?v=3"><source media="(prefers-color-scheme: light)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg?v=3"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg?v=3" alt="Review in Change Stack →" height="32"></picture></a> <!-- review_stack_entry_end --> <!-- walkthrough_start --> <details> <summary><strong>📝 Walkthrough</strong></summary> <dl> <dd> The pull request adds an experimental ray-tracing option and implements compute-shader call-table expansion, feedback, resource specialization, and asynchronous pipeline compilation. It also adds packed texture format handling and 64-bit buffer atomics. Vulkan image and descriptor paths gain fallback handling. Shader IR validation, SSA rewriting, and scalar optimization passes are updated, with new tests for these changes. **Suggested reviewers:** `nmzik`, `senaxx`, `claxten10` </dd> </dl> </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ➖ Normal <!-- change_assessment_commit:"fa1d98c6d85a78122a81cd574219cdf5e2c8cead" --> **Change:** Feature <!-- change_assessment_end --> <details> <summary><strong>Merge Risk:</strong> <strong>🟠 High</strong> · up to <code>fa1d9</code></summary> <dl> <dd> <!-- final_review_risk_start --> <!-- final_review_risk_label **Merge Risk:** **🟠 High** · up to `fa1d9` --> <!-- final_review_risk_coverage:{"sourceCommitId":"fa1d98c6d85a78122a81cd574219cdf5e2c8cead","coveredCommitId":"fa1d98c6d85a78122a81cd574219cdf5e2c8cead","kind":"reviewed"} --> This change breaks compilation on supported Linux and macOS builds, and introduces a descriptor-repair path that can silently corrupt texture/sampler descriptors even with ray tracing disabled. The experimental ray-tracing path also has issues that can run function bodies twice, skip unrelated compute dispatches, and leak shader modules. These should be resolved before merging. <!-- final_review_risk_end --> </dd> </dl> </details> <!-- pre_merge_checks_walkthrough_start --> <details> <summary><strong>Pre-merge checks: <sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-passed-14-v2.svg" width="14" height="14" align="middle" alt="Passed" title="Passed"></picture></sup> 4 · <sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-inconclusive-14-v2.svg" width="14" height="14" align="middle" alt="Inconclusive" title="Inconclusive"></picture></sup> 1</strong></summary> <dl> <dd> <strong><sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-failed-14-v2.svg" width="14" height="14" align="middle" alt="Failed" title="Failed"></picture></sup> Failed checks: 1 inconclusive</strong> | Check name | Status | Explanation | Resolution | | :---------------- | :--------------------------------------------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------- | | Docstring Coverage | ![Inconclusive](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-inconclusive.svg) | Docstring coverage is 20.83% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 216 functions across 50 files. (18 skippe… | Write docstrings for the functions missing them to satisfy the coverage threshold. | <details> <summary><strong><sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-passed-14-v2.svg" width="14" height="14" align="middle" alt="Passed" title="Passed"></picture></sup> Passed checks: 4 passed</strong></summary> <dl> <dd> | Check name | Status | Explanation | | :------------------------ | :--------------------------------------------------------------------------------------------: | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Title check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The title clearly and concisely identifies the main change: an off-by-default software ray-tracing path controlled by --raytracing. | | Description check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The description directly explains the ray-tracing option, compute implementation, dependencies, testing, limitations, and known issues. It is fully related to the changeset. | | Linked Issues check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | Check skipped because no linked issues were found for this pull request. | | Out of Scope Changes check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | Check skipped because no linked issues were found for this pull request. | </dd> </dl> </details> <details> <summary><strong>Full details: Docstring Coverage</strong></summary> <dl> <dd> **Explanation** Docstring coverage is 20.83% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 216 functions across 50 files. (18 skipped: 3 unsupported, 15 over the file limit.) **Resolution** Write docstrings for the functions missing them to satisfy the coverage threshold. </dd> </dl> </details> </dd> </dl> </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">Autofix</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=1559)! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. <details> <summary><strong>❤️ Share</strong></summary> <dl> <dd> - [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) </dd> </dl> </details> <sub>Comment `@coderabbitai help` to get the list of available commands.</sub> <!-- tips_end -->
@ -244,0 +272,4 @@
case BufferFormat::k8_8_8_8UScaled: return BufferFormat::k8_8_8_8UNorm;
case BufferFormat::k8_8_8_8SScaled: return BufferFormat::k8_8_8_8SNorm;
case BufferFormat::k16_16_16_16UScaled: return BufferFormat::k16_16_16_16UNorm;
case BufferFormat::k16_16_16_16SScaled: return BufferFormat::k16_16_16_16SNorm;
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-21 21:31 UTC · original

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
# Check how scaled formats are scaled back after the normalized remap.
rg -nP -C4 'Uscaled|Sscaled' src/graphics/shader/recompiler/ --type=cpp -g '!**/tests/**' | head -150
rg -nP -C6 'RawSignedStorageFormat' src/graphics/shader/recompiler --type=cpp | head -80
rg -nP -C3 '255\.0f' src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp

Repository: KytyPS5/KytyPS5

Length of output: 15146


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- gpu_format remap and format info ---'
rg -n -F -C8 -- 'RemapTextureFormat' src/graphics/guest_gpu/gpu_format.cpp src/graphics/guest_gpu/gpu_format.h
rg -n -F -C5 -- 'ImageConversionFormat' src/graphics/shader/recompiler
printf '%s\n' '--- complete UnpackImageTexel and nearby helpers ---'
sed -n '480,600p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp
printf '%s\n' '--- relevant format declarations and materialization ---'
sed -n '1,155p' src/graphics/shader/recompiler/BufferFormat.h
sed -n '1000,1045p' src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp
printf '%s\n' '--- diff for reviewed file against supplied base ---'
git diff --unified=20 5dec523143930e35a6a5a9839f972774420b7958 fa1d98c6d85a78122a81cd574219cdf5e2c8cead -- src/graphics/guest_gpu/gpu_format.cpp

Repository: KytyPS5/KytyPS5

Length of output: 35859


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- exact remap and conversion lines ---'
nl -ba src/graphics/guest_gpu/gpu_format.cpp | sed -n '257,280p'
nl -ba src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp | sed -n '118,124p'
nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp | sed -n '453,478p'
printf '%s\n' '--- unpack functions and their callers ---'
nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp | sed -n '490,590p'
rg -n -F -C5 -- 'UnpackImageTexel(' src/graphics/shader/recompiler
rg -n -F -C5 -- 'UnpackImageGather(' src/graphics/shader/recompiler
printf '%s\n' '--- scalar type and affected format metadata ---'
rg -n -F -C5 -- 'ImageScalarType' src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp
nl -ba src/graphics/shader/recompiler/BufferFormat.h | sed -n '145,235p'

Repository: KytyPS5/KytyPS5

Length of output: 23053


Scale remapped scaled formats by their component range.

RemapTextureFormat maps 16-bit and signed scaled formats to normalized formats. UnpackImageTexel and UnpackImageGather then apply a fixed 255.0f scale. This is correct only for 8-bit unsigned formats. Use a scale derived from component width and signedness, such as 65535.0f for 16-bit unsigned, 127.0f for 8-bit signed, and 32767.0f for 16-bit signed formats.

The conversion guard also rejects Sscaled formats. Allow supported signed scaled conversions through that guard.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-21 21:31 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1559#discussion_r4342191309) <!-- coderabbit-ai-generated:v1 --> **🎯 Functional Correctness** | **🟡 Minor** | **⚡ Quick win** <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash #!/bin/bash # Check how scaled formats are scaled back after the normalized remap. rg -nP -C4 'Uscaled|Sscaled' src/graphics/shader/recompiler/ --type=cpp -g '!**/tests/**' | head -150 rg -nP -C6 'RawSignedStorageFormat' src/graphics/shader/recompiler --type=cpp | head -80 rg -nP -C3 '255\.0f' src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 15146 --- 🏁 Script executed: ```bash set -o pipefail printf '%s\n' '--- gpu_format remap and format info ---' rg -n -F -C8 -- 'RemapTextureFormat' src/graphics/guest_gpu/gpu_format.cpp src/graphics/guest_gpu/gpu_format.h rg -n -F -C5 -- 'ImageConversionFormat' src/graphics/shader/recompiler printf '%s\n' '--- complete UnpackImageTexel and nearby helpers ---' sed -n '480,600p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp printf '%s\n' '--- relevant format declarations and materialization ---' sed -n '1,155p' src/graphics/shader/recompiler/BufferFormat.h sed -n '1000,1045p' src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp printf '%s\n' '--- diff for reviewed file against supplied base ---' git diff --unified=20 5dec523143930e35a6a5a9839f972774420b7958 fa1d98c6d85a78122a81cd574219cdf5e2c8cead -- src/graphics/guest_gpu/gpu_format.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 35859 --- 🏁 Script executed: ```bash set -o pipefail printf '%s\n' '--- exact remap and conversion lines ---' nl -ba src/graphics/guest_gpu/gpu_format.cpp | sed -n '257,280p' nl -ba src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp | sed -n '118,124p' nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp | sed -n '453,478p' printf '%s\n' '--- unpack functions and their callers ---' nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp | sed -n '490,590p' rg -n -F -C5 -- 'UnpackImageTexel(' src/graphics/shader/recompiler rg -n -F -C5 -- 'UnpackImageGather(' src/graphics/shader/recompiler printf '%s\n' '--- scalar type and affected format metadata ---' rg -n -F -C5 -- 'ImageScalarType' src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp nl -ba src/graphics/shader/recompiler/BufferFormat.h | sed -n '145,235p' ``` Repository: KytyPS5/KytyPS5 Length of output: 23053 --- </details> **Scale remapped scaled formats by their component range.** `RemapTextureFormat` maps 16-bit and signed scaled formats to normalized formats. `UnpackImageTexel` and `UnpackImageGather` then apply a fixed `255.0f` scale. This is correct only for 8-bit unsigned formats. Use a scale derived from component width and signedness, such as `65535.0f` for 16-bit unsigned, `127.0f` for 8-bit signed, and `32767.0f` for 16-bit signed formats. The conversion guard also rejects `Sscaled` formats. Allow supported signed scaled conversions through that guard. <!-- fingerprinting:phantom:medusa:beignet55 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:7436613110e07f55a4f2ae47 --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -135,2 +135,2 @@
if (adjustment >= 256 || size > max_range - adjustment) {
EXIT("storage buffer offset adjustment is unsupported\n");
if ((adjustment % sizeof(uint32_t) != 0 && !resource.written) || adjustment >= 256 ||
size > max_range - adjustment) {
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-21 21:31 UTC · original

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
# Check how the shader consumes the packed memory offset and whether unaligned write offsets are handled.
rg -nP -C4 'memory_offset|MemoryOffset' src/graphics/shader/recompiler --type=cpp | head -120

Repository: KytyPS5/KytyPS5

Length of output: 9898


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- descriptors.cpp ---'
nl -ba src/graphics/host_gpu/renderer/pipeline/descriptors.cpp | sed -n '105,185p'
printf '%s\n' '--- descriptor/resource symbols ---'
rg -n -F --glob '*.cpp' --glob '*.h' -e 'buffer_offset' -e 'memory_byte_offsets' -e 'resource.written' -e 'adjustment' src/graphics/host_gpu src/graphics/shader/recompiler | head -240
printf '%s\n' '--- storage-buffer access definitions ---'
rg -n -F --glob '*.cpp' --glob '*.h' -e 'StorageBufferFormat' -e 'EmitStorage' -e 'buffer_offset' src/graphics/shader/recompiler/backend src/graphics/shader/recompiler/ir | head -240

Repository: KytyPS5/KytyPS5

Length of output: 12343


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- memory helper implementation ---'
nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemoryHelpers.cpp | sed -n '136,350p'
printf '%s\n' '--- memory access implementation ---'
nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp | sed -n '245,335p'
nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp | sed -n '430,510p'
nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp | sed -n '1460,1535p'
printf '%s\n' '--- descriptor packing and binding ---'
nl -ba src/graphics/host_gpu/renderer/pipeline/descriptors.cpp | sed -n '830,885p'
printf '%s\n' '--- resource alignment/offset producers ---'
rg -n -F --glob '*.cpp' --glob '*.h' -e 'byte_offset' -e 'MemoryResourceAccess' -e 'alignment' src/graphics/shader/recompiler/ir src/graphics/shader/recompiler/backend/spirv | head -260

Repository: KytyPS5/KytyPS5

Length of output: 39268


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- address and store path ---'
nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp | sed -n '360,415p'
nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp | sed -n '570,665p'
printf '%s\n' '--- BufferByteAddress declaration/definition ---'
rg -n -F --glob '*.cpp' --glob '*.h' -e 'BufferByteAddress' src/graphics/shader/recompiler/backend/spirv src/graphics/shader/recompiler/ir

Repository: KytyPS5/KytyPS5

Length of output: 9279


🏁 Script executed:

nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp | sed -n '70,105p'

Repository: KytyPS5/KytyPS5

Length of output: 2148


Reject non-dword adjustments for written buffers.

A written buffer with a non-dword adjustment below 256 bypasses the guard. The shader adds buffer_offset to the byte address and shifts the result right by two for dword stores. This can target the wrong dword.

🐛 Suggested fix
-	if ((adjustment % sizeof(uint32_t) != 0 && !resource.written) || adjustment >= 256 ||
+	if (adjustment % sizeof(uint32_t) != 0 || adjustment >= 256 ||
	    size > max_range - adjustment) {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

	if (adjustment % sizeof(uint32_t) != 0 || adjustment >= 256 ||
	    size > max_range - adjustment) {
**@⁠coderabbitai[bot]** on GitHub · 2026-10-21 21:31 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1559#discussion_r4342191322) <!-- coderabbit-ai-generated:v1 --> **🎯 Functional Correctness** | **🟡 Minor** | **⚡ Quick win** <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash #!/bin/bash # Check how the shader consumes the packed memory offset and whether unaligned write offsets are handled. rg -nP -C4 'memory_offset|MemoryOffset' src/graphics/shader/recompiler --type=cpp | head -120 ``` Repository: KytyPS5/KytyPS5 Length of output: 9898 --- 🏁 Script executed: ```bash set -o pipefail printf '%s\n' '--- descriptors.cpp ---' nl -ba src/graphics/host_gpu/renderer/pipeline/descriptors.cpp | sed -n '105,185p' printf '%s\n' '--- descriptor/resource symbols ---' rg -n -F --glob '*.cpp' --glob '*.h' -e 'buffer_offset' -e 'memory_byte_offsets' -e 'resource.written' -e 'adjustment' src/graphics/host_gpu src/graphics/shader/recompiler | head -240 printf '%s\n' '--- storage-buffer access definitions ---' rg -n -F --glob '*.cpp' --glob '*.h' -e 'StorageBufferFormat' -e 'EmitStorage' -e 'buffer_offset' src/graphics/shader/recompiler/backend src/graphics/shader/recompiler/ir | head -240 ``` Repository: KytyPS5/KytyPS5 Length of output: 12343 --- 🏁 Script executed: ```bash set -o pipefail printf '%s\n' '--- memory helper implementation ---' nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemoryHelpers.cpp | sed -n '136,350p' printf '%s\n' '--- memory access implementation ---' nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp | sed -n '245,335p' nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp | sed -n '430,510p' nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp | sed -n '1460,1535p' printf '%s\n' '--- descriptor packing and binding ---' nl -ba src/graphics/host_gpu/renderer/pipeline/descriptors.cpp | sed -n '830,885p' printf '%s\n' '--- resource alignment/offset producers ---' rg -n -F --glob '*.cpp' --glob '*.h' -e 'byte_offset' -e 'MemoryResourceAccess' -e 'alignment' src/graphics/shader/recompiler/ir src/graphics/shader/recompiler/backend/spirv | head -260 ``` Repository: KytyPS5/KytyPS5 Length of output: 39268 --- 🏁 Script executed: ```bash set -o pipefail printf '%s\n' '--- address and store path ---' nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp | sed -n '360,415p' nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp | sed -n '570,665p' printf '%s\n' '--- BufferByteAddress declaration/definition ---' rg -n -F --glob '*.cpp' --glob '*.h' -e 'BufferByteAddress' src/graphics/shader/recompiler/backend/spirv src/graphics/shader/recompiler/ir ``` Repository: KytyPS5/KytyPS5 Length of output: 9279 --- 🏁 Script executed: ```bash nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp | sed -n '70,105p' ``` Repository: KytyPS5/KytyPS5 Length of output: 2148 --- </details> **Reject non-dword adjustments for written buffers.** A written buffer with a non-dword `adjustment` below 256 bypasses the guard. The shader adds `buffer_offset` to the byte address and shifts the result right by two for dword stores. This can target the wrong dword. <details> <summary>🐛 Suggested fix</summary> ```diff - if ((adjustment % sizeof(uint32_t) != 0 && !resource.written) || adjustment >= 256 || + if (adjustment % sizeof(uint32_t) != 0 || adjustment >= 256 || size > max_range - adjustment) { ``` </details> <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion if (adjustment % sizeof(uint32_t) != 0 || adjustment >= 256 || size > max_range - adjustment) { ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:beignet55 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:7a09881e172a7a5bf7294b6f --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -346,0 +379,4 @@
input_info.needs_call_passes = passes->second;
return ShaderProgram {};
}
}
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-21 21:31 UTC · original

🚀 Performance & Scalability | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '360,560p' src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp
sed -n '600,660p' src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp

Repository: KytyPS5/KytyPS5

Length of output: 12940


🏁 Script executed:

set -eu
rg -n -F --glob 'pipelineCache.cpp' -e 'lookup_key' -e 'DispatchDirect' src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp
rg -n -F --glob '*.{cpp,h,hpp}' -e 'needs_call_passes' -e 'ProgramCache::Get' -e 'DispatchDirect' src/graphics/host_gpu/renderer | head -200
printf '\n--- declarations and Get owner ---\n'
sed -n '1,180p' src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp
printf '\n--- Get entry context ---\n'
sed -n '300,390p' src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp
printf '\n--- DispatchDirect definitions/callers ---\n'
rg -n -F --glob '*.{cpp,h,hpp}' 'DispatchDirect' src/graphics

Repository: KytyPS5/KytyPS5

Length of output: 20333


🏁 Script executed:

set -eu
printf '%s\n' '--- ProgramKey and ProgramCache declarations ---'
sed -n '640,730p' src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp
rg -n -F --glob '*.{cpp,h,hpp}' -e 'struct ProgramKey' -e 'class ProgramCache' -e 'GetCompute' -e 'GetShader' src/graphics/host_gpu/renderer/pipeline src/graphics/host_gpu/renderer
printf '%s\n' '--- DispatchDirectSlice lookup and call-pass flow ---'
sed -n '254,355p' src/graphics/host_gpu/renderer/renderCompute.cpp
sed -n '540,615p' src/graphics/host_gpu/renderer/renderCompute.cpp

Repository: KytyPS5/KytyPS5

Length of output: 18448


🏁 Script executed:

set -eu
printf '%s\n' '--- ProgramKey ---'
sed -n '220,250p' src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp
printf '%s\n' '--- DispatchDirect wrapper ---'
sed -n '229,254p' src/graphics/host_gpu/renderer/renderCompute.cpp
printf '%s\n' '--- direct slice after initial lookup ---'
sed -n '320,455p' src/graphics/host_gpu/renderer/renderCompute.cpp
printf '%s\n' '--- remainder of direct dispatch slice ---'
sed -n '455,545p' src/graphics/host_gpu/renderer/renderCompute.cpp

Repository: KytyPS5/KytyPS5

Length of output: 13730


Reset lookup_key.variant before the compute requirement lookups.

lookup_key is a reused ProgramCache member. An RT table mismatch can leave variant nonzero. The compute requirement maps use keys with variant == 0, so the probes can miss and fall through to ShaderRecompiler::TranslateProgram. This can cause an unnecessary translation before needs_call_passes is rediscovered. The later call-pass dispatches do not repeat this specific miss because the translation path resets variant to zero.

Suggested fix
--- "a/src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp"
+++ "b/src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp"
@@ -365,8 +365,9 @@
 		lookup_key.hash            = params.hash;
 		lookup_key.user_data_count = params.user_data_count;
 		lookup_key.code_size       = static_cast<uint32_t>(params.code.size());
 		BuildStageStaticKey(input_info, lookup_key.static_state);
+		lookup_key.variant = 0u;
 		if constexpr (std::is_same_v<InputInfo, ShaderComputeInputInfo>) {
 			if (needs_group_z.contains(lookup_key)) {
 				input_info.needs_group_z = true;
 				return ShaderProgram {};
**@⁠coderabbitai[bot]** on GitHub · 2026-10-21 21:31 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1559#discussion_r4342191353) <!-- coderabbit-ai-generated:v1 --> **🚀 Performance & Scalability** | **🟠 Major** | **⚡ Quick win** <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash sed -n '360,560p' src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp sed -n '600,660p' src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 12940 --- 🏁 Script executed: ```bash set -eu rg -n -F --glob 'pipelineCache.cpp' -e 'lookup_key' -e 'DispatchDirect' src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp rg -n -F --glob '*.{cpp,h,hpp}' -e 'needs_call_passes' -e 'ProgramCache::Get' -e 'DispatchDirect' src/graphics/host_gpu/renderer | head -200 printf '\n--- declarations and Get owner ---\n' sed -n '1,180p' src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp printf '\n--- Get entry context ---\n' sed -n '300,390p' src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp printf '\n--- DispatchDirect definitions/callers ---\n' rg -n -F --glob '*.{cpp,h,hpp}' 'DispatchDirect' src/graphics ``` Repository: KytyPS5/KytyPS5 Length of output: 20333 --- 🏁 Script executed: ```bash set -eu printf '%s\n' '--- ProgramKey and ProgramCache declarations ---' sed -n '640,730p' src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp rg -n -F --glob '*.{cpp,h,hpp}' -e 'struct ProgramKey' -e 'class ProgramCache' -e 'GetCompute' -e 'GetShader' src/graphics/host_gpu/renderer/pipeline src/graphics/host_gpu/renderer printf '%s\n' '--- DispatchDirectSlice lookup and call-pass flow ---' sed -n '254,355p' src/graphics/host_gpu/renderer/renderCompute.cpp sed -n '540,615p' src/graphics/host_gpu/renderer/renderCompute.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 18448 --- 🏁 Script executed: ```bash set -eu printf '%s\n' '--- ProgramKey ---' sed -n '220,250p' src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp printf '%s\n' '--- DispatchDirect wrapper ---' sed -n '229,254p' src/graphics/host_gpu/renderer/renderCompute.cpp printf '%s\n' '--- direct slice after initial lookup ---' sed -n '320,455p' src/graphics/host_gpu/renderer/renderCompute.cpp printf '%s\n' '--- remainder of direct dispatch slice ---' sed -n '455,545p' src/graphics/host_gpu/renderer/renderCompute.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 13730 --- </details> **Reset `lookup_key.variant` before the compute requirement lookups.** `lookup_key` is a reused `ProgramCache` member. An RT table mismatch can leave `variant` nonzero. The compute requirement maps use keys with `variant == 0`, so the probes can miss and fall through to `ShaderRecompiler::TranslateProgram`. This can cause an unnecessary translation before `needs_call_passes` is rediscovered. The later call-pass dispatches do not repeat this specific miss because the translation path resets `variant` to zero. <details> <summary>Suggested fix</summary> ```diff --- "a/src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp" +++ "b/src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp" @@ -365,8 +365,9 @@ lookup_key.hash = params.hash; lookup_key.user_data_count = params.user_data_count; lookup_key.code_size = static_cast<uint32_t>(params.code.size()); BuildStageStaticKey(input_info, lookup_key.static_state); + lookup_key.variant = 0u; if constexpr (std::is_same_v<InputInfo, ShaderComputeInputInfo>) { if (needs_group_z.contains(lookup_key)) { input_info.needs_group_z = true; return ShaderProgram {}; ``` </details> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:d869afb6eea9566bb34390e6 --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -355,0 +524,4 @@
programs.erase(programs.find(lookup_key));
entry = programs.end();
break;
}
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-21 21:31 UTC · original

🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Destroy the shader modules of program-cache entries that are erased.

Only ~ProgramCache calls destroyShaderModule, and only for entries that are still in programs. Three new paths drop entries without destroying their Permutation::handle.module:

  • programs.erase(entry) after an entry moves to retired. This one is safe because the entry still exists in retired.
  • retired.erase(kept) at Line 514 and retired.erase(old) in settle (Line 401).
  • programs.erase(programs.find(lookup_key)) at Line 524, when the variant limit is reached.

Every retranslation and every eviction past 16 variants therefore leaks the SPIR-V modules of a large ray-tracing kernel. The PR already notes high memory use.

A module can only be destroyed after any createComputePipelines call that uses it has returned. The detached worker in StartAsyncCompute holds the raw module. Suggested fix:

  • Keep a deferred-destroy list of (program_id, module) pairs.
  • Destroy a module when m_async_compute has no pending job for that ID, or when the job is ready.
  • Release the matching m_compute_pipelines entries for the erased IDs at the same time, or they also stay allocated.
**@⁠coderabbitai[bot]** on GitHub · 2026-10-21 21:31 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1559#discussion_r4342191363) <!-- coderabbit-ai-generated:v1 --> **🩺 Stability & Availability** | **🟠 Major** | **🏗️ Heavy lift** **Destroy the shader modules of program-cache entries that are erased.** Only `~ProgramCache` calls `destroyShaderModule`, and only for entries that are still in `programs`. Three new paths drop entries without destroying their `Permutation::handle.module`: - `programs.erase(entry)` after an entry moves to `retired`. This one is safe because the entry still exists in `retired`. - `retired.erase(kept)` at Line 514 and `retired.erase(old)` in `settle` (Line 401). - `programs.erase(programs.find(lookup_key))` at Line 524, when the variant limit is reached. Every retranslation and every eviction past 16 variants therefore leaks the SPIR-V modules of a large ray-tracing kernel. The PR already notes high memory use. A module can only be destroyed after any `createComputePipelines` call that uses it has returned. The detached worker in `StartAsyncCompute` holds the raw `module`. Suggested fix: - Keep a deferred-destroy list of `(program_id, module)` pairs. - Destroy a module when `m_async_compute` has no pending job for that ID, or when the job is `ready`. - Release the matching `m_compute_pipelines` entries for the erased IDs at the same time, or they also stay allocated. <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:7f02f1a4003015e6d15419e0 --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -495,0 +732,4 @@
std::fprintf(stderr, "RT calls: a pipeline is still compiling at shutdown, ending the process\n");
std::fflush(nullptr);
std::_Exit(0);
}
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-21 21:31 UTC · original

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Do not read the driver cache while a ray-tracing compile is running.

The comment at Lines 1336-1338 says that reading the pipeline cache during a compile crashed the driver. Only TakeAsyncCompute checks g_active_rt_compiles, and two other paths still call Save() without that check:

  • CheckpointDriverCache() calls Save() every 5 minutes from GetGraphicsPipeline and GetComputePipeline. Worker threads may be inside createComputePipelines on the same m_driver_cache at that moment.
  • ~PipelineCache calls Save() at Line 728, before this check. On shutdown during a compile, it reads the cache while the compile is still running.

Move the check into Save() itself so that every caller is covered. The dirty flag keeps the save pending until no compile is active. In the destructor, run the async check before Save().

Proposed fix
void PipelineCache::Save() {
	if (m_driver_cache == nullptr || !m_driver_cache_dirty) return;
	if (g_active_rt_compiles.load() != 0) return; // keep dirty, retry later
	...
}
 PipelineCache::~PipelineCache() {
-	Save();
 	if (std::ranges::any_of(m_async_compute, [](const auto& job) { return !job.second->ready.load(); })) {
 		...
 		std::_Exit(0);
 	}
+	Save();

g_active_rt_compiles only counts threads that have acquired a slot. A small race remains, but these changes remove the deterministic overlap.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-21 21:31 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1559#discussion_r4342191372) <!-- coderabbit-ai-generated:v1 --> **🩺 Stability & Availability** | **🟠 Major** | **⚡ Quick win** **Do not read the driver cache while a ray-tracing compile is running.** The comment at Lines 1336-1338 says that reading the pipeline cache during a compile crashed the driver. Only `TakeAsyncCompute` checks `g_active_rt_compiles`, and two other paths still call `Save()` without that check: - `CheckpointDriverCache()` calls `Save()` every 5 minutes from `GetGraphicsPipeline` and `GetComputePipeline`. Worker threads may be inside `createComputePipelines` on the same `m_driver_cache` at that moment. - `~PipelineCache` calls `Save()` at Line 728, before this check. On shutdown during a compile, it reads the cache while the compile is still running. Move the check into `Save()` itself so that every caller is covered. The dirty flag keeps the save pending until no compile is active. In the destructor, run the async check before `Save()`. <details> <summary>Proposed fix</summary> ```cpp void PipelineCache::Save() { if (m_driver_cache == nullptr || !m_driver_cache_dirty) return; if (g_active_rt_compiles.load() != 0) return; // keep dirty, retry later ... } ``` ```diff PipelineCache::~PipelineCache() { - Save(); if (std::ranges::any_of(m_async_compute, [](const auto& job) { return !job.second->ready.load(); })) { ... std::_Exit(0); } + Save(); ``` </details> `g_active_rt_compiles` only counts threads that have acquired a slot. A small race remains, but these changes remove the deterministic overlap. <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:3cf4b6930e7224412888e867 --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -49,0 +50,4 @@
{Prospero::BufferFormat::k2_10_10_10UNorm, vk::Format::eA2B10G10R10UnormPack32},
{Prospero::BufferFormat::k2_10_10_10SNorm, vk::Format::eA2B10G10R10SnormPack32},
{Prospero::BufferFormat::k2_10_10_10UInt, vk::Format::eA2B10G10R10UintPack32},
{Prospero::BufferFormat::k2_10_10_10SInt, vk::Format::eA2B10G10R10SintPack32},
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-21 21:31 UTC · original

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
# Compare guest channel bit layouts for the aliased formats.
rg -nP -C6 'k10_11_11Float|k2_10_10_10(UNorm|SNorm|UInt|SInt)|k11_11_10Float' src/graphics --type=cpp -g '!**/vulkanCommon.cpp' | head -150

Repository: KytyPS5/KytyPS5

Length of output: 12785


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- gpu format definitions ---'
nl -ba src/graphics/guest_gpu/gpu_format.h | sed -n '1,180p'
nl -ba src/graphics/guest_gpu/gpu_format.cpp | sed -n '1,90p'
printf '%s\n' '--- Vulkan mapping and related host mapping ---'
nl -ba src/graphics/host_gpu/vulkanCommon.cpp | sed -n '1,90p'
nl -ba src/graphics/host_gpu/renderer/image/textureCommon.cpp | sed -n '1,85p'
printf '%s\n' '--- color transform declarations and implementation ---'
rg -n -F -e 'Reverse10_11_11' -e 'ColorTransform' src/graphics/host_gpu/renderer/image src/graphics/host_gpu | head -100

Repository: KytyPS5/KytyPS5

Length of output: 23962


🏁 Script executed:

set -o pipefail
nl -ba src/graphics/guest_gpu/gpu_format.h | sed -n '1,180p'
nl -ba src/graphics/guest_gpu/gpu_format.cpp | sed -n '1,90p'
nl -ba src/graphics/host_gpu/vulkanCommon.cpp | sed -n '35,65p'
nl -ba src/graphics/host_gpu/renderer/image/textureCommon.cpp | sed -n '25,55p'
rg -n -C5 -F -e 'Reverse10_11_11' -e 'ColorTransform' src/graphics/host_gpu/renderer/image src/graphics/host_gpu

Repository: KytyPS5/KytyPS5

Length of output: 44400


🏁 Script executed:

git diff --no-ext-diff 5dec523143930e35a6a5a9839f972774420b7958 fa1d98c6d85a78122a81cd574219cdf5e2c8cead -- src/graphics/host_gpu/vulkanCommon.cpp src/graphics/guest_gpu/gpu_format.cpp src/graphics/host_gpu/renderer/image/textureCommon.cpp src/graphics/host_gpu/renderer/image/imageInfo.h
printf '%s\n' '--- format metadata ---'
rg -n -C12 -F -e 'struct FormatInfo' -e 'component_bit_offset' -e 'k2_10_10_10UNorm' src/graphics/guest_gpu src/graphics/host_gpu
printf '%s\n' '--- transform consumers ---'
rg -n -C8 -F -e 'GetColorTransform()' -e 'ColorTransform::Reverse10_11_11' -e 'ColorMappingBgra' src/graphics/host_gpu

Repository: KytyPS5/KytyPS5

Length of output: 41438


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- ChannelLayout declaration and format helpers ---'
rg -n -C12 -F -e 'enum class ChannelLayout' -e 'ChannelLayout::k2_10_10_10' -e 'ChannelLayout::k10_10_10_2' -e 'vk::Format VulkanFormat' src/graphics
printf '%s\n' '--- VulkanFormat implementation and callers ---'
rg -n -C12 -F -e 'VulkanFormat(' src/graphics/host_gpu src/graphics/guest_gpu

Repository: KytyPS5/KytyPS5

Length of output: 21097


Do not map k2_10_10_10* to eA2B10G10R10*.

DccAlphaOnMsb distinguishes the layouts: k2_10_10_10 has alpha off the most-significant bits, while k10_10_10_2 has alpha on the most-significant bits. eA2B10G10R10* stores 2-bit alpha on the most-significant bits. The current VulkanFormat lookup therefore decodes k2_10_10_10* with the wrong packed layout.

Use integer backing with shader-side decoding for these four formats. The existing ColorMappingBgra and Reverse10_11_11 paths already handle k10_11_11Float.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-21 21:31 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1559#discussion_r4342191377) <!-- coderabbit-ai-generated:v1 --> **🎯 Functional Correctness** | **🟡 Minor** | **⚡ Quick win** <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash #!/bin/bash # Compare guest channel bit layouts for the aliased formats. rg -nP -C6 'k10_11_11Float|k2_10_10_10(UNorm|SNorm|UInt|SInt)|k11_11_10Float' src/graphics --type=cpp -g '!**/vulkanCommon.cpp' | head -150 ``` Repository: KytyPS5/KytyPS5 Length of output: 12785 --- 🏁 Script executed: ```bash set -o pipefail printf '%s\n' '--- gpu format definitions ---' nl -ba src/graphics/guest_gpu/gpu_format.h | sed -n '1,180p' nl -ba src/graphics/guest_gpu/gpu_format.cpp | sed -n '1,90p' printf '%s\n' '--- Vulkan mapping and related host mapping ---' nl -ba src/graphics/host_gpu/vulkanCommon.cpp | sed -n '1,90p' nl -ba src/graphics/host_gpu/renderer/image/textureCommon.cpp | sed -n '1,85p' printf '%s\n' '--- color transform declarations and implementation ---' rg -n -F -e 'Reverse10_11_11' -e 'ColorTransform' src/graphics/host_gpu/renderer/image src/graphics/host_gpu | head -100 ``` Repository: KytyPS5/KytyPS5 Length of output: 23962 --- 🏁 Script executed: ```bash set -o pipefail nl -ba src/graphics/guest_gpu/gpu_format.h | sed -n '1,180p' nl -ba src/graphics/guest_gpu/gpu_format.cpp | sed -n '1,90p' nl -ba src/graphics/host_gpu/vulkanCommon.cpp | sed -n '35,65p' nl -ba src/graphics/host_gpu/renderer/image/textureCommon.cpp | sed -n '25,55p' rg -n -C5 -F -e 'Reverse10_11_11' -e 'ColorTransform' src/graphics/host_gpu/renderer/image src/graphics/host_gpu ``` Repository: KytyPS5/KytyPS5 Length of output: 44400 --- 🏁 Script executed: ```bash git diff --no-ext-diff 5dec523143930e35a6a5a9839f972774420b7958 fa1d98c6d85a78122a81cd574219cdf5e2c8cead -- src/graphics/host_gpu/vulkanCommon.cpp src/graphics/guest_gpu/gpu_format.cpp src/graphics/host_gpu/renderer/image/textureCommon.cpp src/graphics/host_gpu/renderer/image/imageInfo.h printf '%s\n' '--- format metadata ---' rg -n -C12 -F -e 'struct FormatInfo' -e 'component_bit_offset' -e 'k2_10_10_10UNorm' src/graphics/guest_gpu src/graphics/host_gpu printf '%s\n' '--- transform consumers ---' rg -n -C8 -F -e 'GetColorTransform()' -e 'ColorTransform::Reverse10_11_11' -e 'ColorMappingBgra' src/graphics/host_gpu ``` Repository: KytyPS5/KytyPS5 Length of output: 41438 --- 🏁 Script executed: ```bash set -o pipefail printf '%s\n' '--- ChannelLayout declaration and format helpers ---' rg -n -C12 -F -e 'enum class ChannelLayout' -e 'ChannelLayout::k2_10_10_10' -e 'ChannelLayout::k10_10_10_2' -e 'vk::Format VulkanFormat' src/graphics printf '%s\n' '--- VulkanFormat implementation and callers ---' rg -n -C12 -F -e 'VulkanFormat(' src/graphics/host_gpu src/graphics/guest_gpu ``` Repository: KytyPS5/KytyPS5 Length of output: 21097 --- </details> **Do not map `k2_10_10_10*` to `eA2B10G10R10*`.** `DccAlphaOnMsb` distinguishes the layouts: `k2_10_10_10` has alpha off the most-significant bits, while `k10_10_10_2` has alpha on the most-significant bits. `eA2B10G10R10*` stores 2-bit alpha on the most-significant bits. The current `VulkanFormat` lookup therefore decodes `k2_10_10_10*` with the wrong packed layout. Use integer backing with shader-side decoding for these four formats. The existing `ColorMappingBgra` and `Reverse10_11_11` paths already handle `k10_11_11Float`. <!-- fingerprinting:phantom:medusa:beignet55 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:795bfc77260fd040217035b2 --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -1051,0 +1057,4 @@
vk::BufferCreateInfo buffer_info;
buffer_info.size = size;
buffer_info.usage = vk::BufferUsageFlagBits::eShaderDeviceAddress | vk::BufferUsageFlagBits::eStorageBuffer;
auto buffer = graphic_ctx.device.createBuffer(buffer_info).value;
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-21 21:31 UTC · original

🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Retain and release the feedback buffer.

When ray tracing is enabled, CreateVulkan creates a buffer and allocates memory, but both handles remain local. WindowContext::~WindowContext therefore destroys the device without unmapping or releasing them. Store both handles on the context. Clear the published feedback pointers, then unmap, destroy the buffer, and free its memory before destroying the device.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-21 21:31 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1559#discussion_r4342191383) <!-- coderabbit-ai-generated:v1 --> **🩺 Stability & Availability** | **🟠 Major** | **🏗️ Heavy lift** **Retain and release the feedback buffer.** When ray tracing is enabled, `CreateVulkan` creates a buffer and allocates memory, but both handles remain local. `WindowContext::~WindowContext` therefore destroys the device without unmapping or releasing them. Store both handles on the context. Clear the published feedback pointers, then unmap, destroy the buffer, and free its memory before destroying the device. <!-- fingerprinting:phantom:medusa:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:37fc71522d2c97c0d413c215 --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -420,0 +505,4 @@
ctx.state.builder.AddFunction(spv::OpCompositeConstruct, TypeU32Vector(ctx.state, 4), result,
values[0], values[1], values[2], values[3]);
return result;
}
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-21 21:31 UTC · original

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Reject 16-bit data reads for k10_10_10_2Float.

StoreTexel calls EXIT_NOT_IMPLEMENTED for mem.data_bits == 16u with this format. UnpackImageTexel has no equivalent guard.

For this format, ResultVector takes value_class from SampledTextureNumericClass(conversion). That class is Uint, because uint_texture is true in kFormatInfo. For data_bits == 16u, ResultVector then uses its integer pack path. It packs the low 16 bits of each decoded f32 bit pattern. That discards the exponent and the mantissa MSBs. The shader gets wrong values without any error.

Add a guard that matches the store path.

Proposed fix
--- "a/src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp"
+++ "b/src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp"
@@ -490,8 +490,9 @@
 uint32_t UnpackImageTexel(ValueEmitContext& ctx, const IR::MemoryInfo& mem, uint32_t texel) {
 	const auto info = ImageConversionFormat(ctx.state, mem);
 	if (info.format == Prospero::BufferFormat::kInvalid) return texel;
 	if (info.format == Prospero::BufferFormat::k10_10_10_2Float) {
+		EXIT_NOT_IMPLEMENTED(mem.data_bits == 16u);
 		const auto packed = ctx.state.builder.AllocateId();
 		ctx.state.builder.AddFunction(spv::OpCompositeExtract, TypeU32(ctx.state), packed, texel,
 		                              0u);
 		const auto swizzle = ctx.state.program.info.images[mem.resource].shader_swizzle;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

	if (info.format == Prospero::BufferFormat::k10_10_10_2Float) {
		EXIT_NOT_IMPLEMENTED(mem.data_bits == 16u);
		const auto packed = ctx.state.builder.AllocateId();
		ctx.state.builder.AddFunction(spv::OpCompositeExtract, TypeU32(ctx.state), packed, texel,
		                              0u);
		const auto swizzle = ctx.state.program.info.images[mem.resource].shader_swizzle;
		uint32_t   values[4] {};
		for (uint32_t i = 0; i < 4u; ++i) {
			const auto selector = (swizzle >> (i * 3u)) & 7u;
			values[i] = selector >= 4u ? DecodePackedFloatChannel(ctx.state, packed, selector - 4u)
			                           : ConstantU32(ctx.state, selector == 1u ? 0x3f800000u : 0u);
		}
		const auto result = ctx.state.builder.AllocateId();
		ctx.state.builder.AddFunction(spv::OpCompositeConstruct, TypeU32Vector(ctx.state, 4), result,
		                              values[0], values[1], values[2], values[3]);
		return result;
	}
**@⁠coderabbitai[bot]** on GitHub · 2026-10-21 21:31 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1559#discussion_r4342191389) <!-- coderabbit-ai-generated:v1 --> **🎯 Functional Correctness** | **🟡 Minor** | **⚡ Quick win** **Reject 16-bit data reads for `k10_10_10_2Float`.** `StoreTexel` calls `EXIT_NOT_IMPLEMENTED` for `mem.data_bits == 16u` with this format. `UnpackImageTexel` has no equivalent guard. For this format, `ResultVector` takes `value_class` from `SampledTextureNumericClass(conversion)`. That class is `Uint`, because `uint_texture` is `true` in `kFormatInfo`. For `data_bits == 16u`, `ResultVector` then uses its integer pack path. It packs the low 16 bits of each decoded f32 bit pattern. That discards the exponent and the mantissa MSBs. The shader gets wrong values without any error. Add a guard that matches the store path. <details> <summary>Proposed fix</summary> ```diff --- "a/src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp" +++ "b/src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp" @@ -490,8 +490,9 @@ uint32_t UnpackImageTexel(ValueEmitContext& ctx, const IR::MemoryInfo& mem, uint32_t texel) { const auto info = ImageConversionFormat(ctx.state, mem); if (info.format == Prospero::BufferFormat::kInvalid) return texel; if (info.format == Prospero::BufferFormat::k10_10_10_2Float) { + EXIT_NOT_IMPLEMENTED(mem.data_bits == 16u); const auto packed = ctx.state.builder.AllocateId(); ctx.state.builder.AddFunction(spv::OpCompositeExtract, TypeU32(ctx.state), packed, texel, 0u); const auto swizzle = ctx.state.program.info.images[mem.resource].shader_swizzle; ``` </details> <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion if (info.format == Prospero::BufferFormat::k10_10_10_2Float) { EXIT_NOT_IMPLEMENTED(mem.data_bits == 16u); const auto packed = ctx.state.builder.AllocateId(); ctx.state.builder.AddFunction(spv::OpCompositeExtract, TypeU32(ctx.state), packed, texel, 0u); const auto swizzle = ctx.state.program.info.images[mem.resource].shader_swizzle; uint32_t values[4] {}; for (uint32_t i = 0; i < 4u; ++i) { const auto selector = (swizzle >> (i * 3u)) & 7u; values[i] = selector >= 4u ? DecodePackedFloatChannel(ctx.state, packed, selector - 4u) : ConstantU32(ctx.state, selector == 1u ? 0x3f800000u : 0u); } const auto result = ctx.state.builder.AllocateId(); ctx.state.builder.AddFunction(spv::OpCompositeConstruct, TypeU32Vector(ctx.state, 4), result, values[0], values[1], values[2], values[3]); return result; } ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:beignet55 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:29f27daa219ab1d4b2f5c699 --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -519,0 +580,4 @@
found = true;
distinct = 1u;
} else if (!(candidate == result)) {
++distinct;
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-21 21:31 UTC · original

🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

Preserve sampler selection when valid records disagree.

If two records contain different valid samplers, MaterializeHopSampler selects the first and only logs the difference. Calls through the other record then use the first record’s filtering and addressing state, producing incorrect sampling. Represent the sampler choice per record, or decline this specialization rather than silently binding a different sampler.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-21 21:31 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1559#discussion_r4342191403) <!-- coderabbit-ai-generated:v1 --> **🎯 Functional Correctness** | **🟠 Major** | **🏗️ Heavy lift** **Preserve sampler selection when valid records disagree.** If two records contain different valid samplers, `MaterializeHopSampler` selects the first and only logs the difference. Calls through the other record then use the first record’s filtering and addressing state, producing incorrect sampling. Represent the sampler choice per record, or decline this specialization rather than silently binding a different sampler. <!-- fingerprinting:phantom:medusa:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:a5839cc606ddbec4de20aa1f --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -740,0 +845,4 @@
// The record points at the descriptor. A null or unreadable pointer is an unused record: its
// descriptor stays zero and normalization rejects it.
uint64_t target = 0;
if (!ReadPointerPath(indirect, table_base, table_size, table_offset, runtime, target)) return false;
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-21 21:31 UTC · original

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Skip an unreadable pointer-hop record instead of failing the table.

A counted table can contain a record whose pointer path is unreadable. ReadPointerPath then returns false, and this branch fails materialization for the entire resource, although MaterializeHopSampler skips an unreadable candidate and the descriptor read below already permits an empty candidate. Treat that record as null so other valid records remain usable.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-21 21:31 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1559#discussion_r4342191410) <!-- coderabbit-ai-generated:v1 --> **🩺 Stability & Availability** | **🟠 Major** | **⚡ Quick win** **Skip an unreadable pointer-hop record instead of failing the table.** A counted table can contain a record whose pointer path is unreadable. `ReadPointerPath` then returns false, and this branch fails materialization for the entire resource, although `MaterializeHopSampler` skips an unreadable candidate and the descriptor read below already permits an empty candidate. Treat that record as null so other valid records remain usable. <!-- fingerprinting:phantom:medusa:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:d67cccd41ad96aad764205cf --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -965,0 +1149,4 @@
site_class.numeric_class = site.atomic ? Prospero::TextureNumericClass::Uint : Prospero::TextureNumericClass::Float;
site_class.dimension = site.dimension == Decoder::ImageDimension::Unknown ? Decoder::ImageDimension::Dim2D : site.dimension;
site_class.cube = site.cube;
site_class.mip_count = 1u;
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-21 21:31 UTC · original

🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

Do not null valid textures against a hard-coded site class.

For a padded sampled-image table, site_class always requires Float and one mip level. The check at Line 1178 consequently nulls a valid unsigned-integer candidate or a valid multi-mip candidate even when it matches the image operation’s dimension. Derive the required class and mip behavior from a supported site contract, or retain distinct compatible variants.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-21 21:31 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1559#discussion_r4342191420) <!-- coderabbit-ai-generated:v1 --> **🎯 Functional Correctness** | **🟠 Major** | **🏗️ Heavy lift** **Do not null valid textures against a hard-coded site class.** For a padded sampled-image table, `site_class` always requires `Float` and one mip level. The check at Line 1178 consequently nulls a valid unsigned-integer candidate or a valid multi-mip candidate even when it matches the image operation’s dimension. Derive the required class and mip behavior from a supported site contract, or retain distinct compatible variants. <!-- fingerprinting:phantom:medusa:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:233973b77980e160434829f5 --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -3102,0 +3259,4 @@
bool TryMakePointerHop(Inst& handle, const DescriptorSource& descriptor, IndirectDescriptorPlan& plan,
ValueOpcode expected, uint32_t width, uint32_t companion_offset = UINT32_MAX) {
if (handle.GetOpcode() != expected || handle.NumArgs() != width) return false;
plan = {};
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-21 21:31 UTC · original

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

set -eu
printf '%s\n' '--- cited reset and nearby function ---'
nl -ba src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp | sed -n '3180,3315p'
printf '%s\n' '--- read_dwords references ---'
rg -n -F -- 'read_dwords' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp
printf '%s\n' '--- plan_handle references and definition context ---'
rg -n -F -- 'plan_handle' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp
printf '%s\n' '--- diff for cited file ---'
git diff --unified=35 5dec523143930e35a6a5a9839f972774420b7958 fa1d98c6d85a78122a81cd574219cdf5e2c8cead -- src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp

Repository: KytyPS5/KytyPS5

Length of output: 42938


🏁 Script executed:

set -eu
printf '%s\n' '--- Run consumers ---'
nl -ba src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp | sed -n '535,625p'
printf '%s\n' '--- pointer-hop implementation, continuation ---'
nl -ba src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp | sed -n '3259,3180p' 2>/dev/null || true
nl -ba src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp | sed -n '3290,3180p' 2>/dev/null || true
nl -ba src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp | sed -n '3290,3415p'
printf '%s\n' '--- plan consumers and caller ---'
nl -ba src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp | sed -n '2800,3130p'
nl -ba src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp | sed -n '3940,4040p'

Repository: KytyPS5/KytyPS5

Length of output: 38925


🏁 Script executed:

set -eu
printf '%s\n' '--- indirect planning guard ---'
nl -ba src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp | sed -n '3865,3940p'
printf '%s\n' '--- Run plan loop ---'
nl -ba src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp | sed -n '455,570p'
printf '%s\n' '--- collection guard ---'
nl -ba src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp | sed -n '4340,4475p'

Repository: KytyPS5/KytyPS5

Length of output: 17395


Restore read_dwords after resetting the plan.

plan_handle initializes plan.read_dwords before TryMakePointerHop. The helper clears the plan and does not restore the width. A successful non-retained pointer-hop plan can therefore leave its reads unmarked as planning-only and let them reach Collect as ordinary address reads.

🐛 Suggested fix
 		plan = {};
+		plan.read_dwords = width;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

		plan = {};
		plan.read_dwords = width;
**@⁠coderabbitai[bot]** on GitHub · 2026-10-21 21:31 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1559#discussion_r4342191427) <!-- coderabbit-ai-generated:v1 --> **🎯 Functional Correctness** | **🟡 Minor** | **⚡ Quick win** <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash set -eu printf '%s\n' '--- cited reset and nearby function ---' nl -ba src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp | sed -n '3180,3315p' printf '%s\n' '--- read_dwords references ---' rg -n -F -- 'read_dwords' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp printf '%s\n' '--- plan_handle references and definition context ---' rg -n -F -- 'plan_handle' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp printf '%s\n' '--- diff for cited file ---' git diff --unified=35 5dec523143930e35a6a5a9839f972774420b7958 fa1d98c6d85a78122a81cd574219cdf5e2c8cead -- src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 42938 --- 🏁 Script executed: ```bash set -eu printf '%s\n' '--- Run consumers ---' nl -ba src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp | sed -n '535,625p' printf '%s\n' '--- pointer-hop implementation, continuation ---' nl -ba src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp | sed -n '3259,3180p' 2>/dev/null || true nl -ba src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp | sed -n '3290,3180p' 2>/dev/null || true nl -ba src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp | sed -n '3290,3415p' printf '%s\n' '--- plan consumers and caller ---' nl -ba src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp | sed -n '2800,3130p' nl -ba src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp | sed -n '3940,4040p' ``` Repository: KytyPS5/KytyPS5 Length of output: 38925 --- 🏁 Script executed: ```bash set -eu printf '%s\n' '--- indirect planning guard ---' nl -ba src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp | sed -n '3865,3940p' printf '%s\n' '--- Run plan loop ---' nl -ba src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp | sed -n '455,570p' printf '%s\n' '--- collection guard ---' nl -ba src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp | sed -n '4340,4475p' ``` Repository: KytyPS5/KytyPS5 Length of output: 17395 --- </details> **Restore `read_dwords` after resetting the plan.** `plan_handle` initializes `plan.read_dwords` before `TryMakePointerHop`. The helper clears the plan and does not restore the width. A successful non-retained pointer-hop plan can therefore leave its reads unmarked as planning-only and let them reach `Collect` as ordinary address reads. <details> <summary>🐛 Suggested fix</summary> ```diff plan = {}; + plan.read_dwords = width; ``` </details> <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion plan = {}; plan.read_dwords = width; ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:2f0426704a0d417e8703668c --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -3694,0 +4064,4 @@
handle->SetArg(bad_dword, Value(0u));
continue;
}
}
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-21 21:31 UTC · original

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Limit TracesToWaveMask to real lane-mask scratch and enable it only for ray tracing.

TracesToWaveMask walks every operand of every instruction, including memory-load addresses. A typical waterfall descriptor has the form dword = Load(table, FindILsb(Ballot(...)) * stride). That descriptor is selected by the GPU, but this check reaches the Ballot through the address and treats the word as wave-mask scratch. GetHandle then replaces the word with zero in both descriptor and handle.

The comment says the check "keeps a genuinely divergent descriptor failing loudly", but the code does not do that. Before this change, such shaders reached Fail. Now they silently sample with a corrupted image or sampler descriptor.

The block does not check m_program.gpu_selected_call_payloads, so it also runs when --raytracing is off. The image dword 7 rule in Lines 4073-4079 is not gated either.

Suggested fix:

  • Stop the walk at memory reads, ReadFirstLane, and Phi instructions.
  • Accept only a value that is a Ballot, possibly wrapped in bitwise or extract operations.
  • Run these scratch-zeroing rules only when m_program.gpu_selected_call_payloads is set.
Proposed gating
-			if ((expected == ValueOpcode::GetImageResource ||
+			if (m_program.gpu_selected_call_payloads &&
+			    (expected == ValueOpcode::GetImageResource ||
 			     expected == ValueOpcode::GetSamplerResource) &&

In TracesToWaveMask, return false instead of recursing when inst is a memory read (BufferAccessOf, AddressOpcodeInfoOf, or ImageOpcodeInfoOf is not None), a ReadFirstLane, or a Phi.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

			// An image or sampler descriptor word that traces to a subgroup ballot is a stale
			// wave mask left in the register: the fetch reads address/mip data, never a lane
			// mask. Proving the trace keeps a genuinely divergent descriptor failing loudly.
			if (m_program.gpu_selected_call_payloads &&
			    (expected == ValueOpcode::GetImageResource ||
			     expected == ValueOpcode::GetSamplerResource) &&
			    bad_dword < descriptor.dword_count &&
			    !descriptor.dwords[bad_dword].IsImmediate()) {
				std::unordered_set<const Inst*> visited;
				if (TracesToWaveMask(descriptor.dwords[bad_dword], visited, 0u)) {
					descriptor.dwords[bad_dword] = Value(0u);
					handle->SetArg(bad_dword, Value(0u));
					continue;
				}
			}
**@⁠coderabbitai[bot]** on GitHub · 2026-10-21 21:31 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1559#discussion_r4342191438) <!-- coderabbit-ai-generated:v1 --> **🎯 Functional Correctness** | **🟠 Major** | **⚡ Quick win** **Limit `TracesToWaveMask` to real lane-mask scratch and enable it only for ray tracing.** `TracesToWaveMask` walks every operand of every instruction, including memory-load addresses. A typical waterfall descriptor has the form `dword = Load(table, FindILsb(Ballot(...)) * stride)`. That descriptor is selected by the GPU, but this check reaches the `Ballot` through the address and treats the word as wave-mask scratch. `GetHandle` then replaces the word with zero in both `descriptor` and `handle`. The comment says the check "keeps a genuinely divergent descriptor failing loudly", but the code does not do that. Before this change, such shaders reached `Fail`. Now they silently sample with a corrupted image or sampler descriptor. The block does not check `m_program.gpu_selected_call_payloads`, so it also runs when `--raytracing` is off. The image dword 7 rule in Lines 4073-4079 is not gated either. Suggested fix: - Stop the walk at memory reads, `ReadFirstLane`, and `Phi` instructions. - Accept only a value that is a `Ballot`, possibly wrapped in bitwise or extract operations. - Run these scratch-zeroing rules only when `m_program.gpu_selected_call_payloads` is set. <details> <summary>Proposed gating</summary> ```diff - if ((expected == ValueOpcode::GetImageResource || + if (m_program.gpu_selected_call_payloads && + (expected == ValueOpcode::GetImageResource || expected == ValueOpcode::GetSamplerResource) && ``` In `TracesToWaveMask`, return `false` instead of recursing when `inst` is a memory read (`BufferAccessOf`, `AddressOpcodeInfoOf`, or `ImageOpcodeInfoOf` is not `None`), a `ReadFirstLane`, or a `Phi`. </details> <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion // An image or sampler descriptor word that traces to a subgroup ballot is a stale // wave mask left in the register: the fetch reads address/mip data, never a lane // mask. Proving the trace keeps a genuinely divergent descriptor failing loudly. if (m_program.gpu_selected_call_payloads && (expected == ValueOpcode::GetImageResource || expected == ValueOpcode::GetSamplerResource) && bad_dword < descriptor.dword_count && !descriptor.dwords[bad_dword].IsImmediate()) { std::unordered_set<const Inst*> visited; if (TracesToWaveMask(descriptor.dwords[bad_dword], visited, 0u)) { descriptor.dwords[bad_dword] = Value(0u); handle->SetArg(bad_dword, Value(0u)); continue; } } ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:8ae7ff43e84a802c4a1bd1c5 --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -582,0 +637,4 @@
std::memcpy(destination, reinterpret_cast<const void*>(address), words * sizeof(uint32_t));
return true;
} __except (1) {
return false;
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-21 21:31 UTC · original

🎯 Functional Correctness | 🔴 Critical | 🏗️ Heavy lift

Replace the Windows-only guest-memory read on non-Windows builds.

ReadGuestWords uses __try and __except without a platform guard. The same file has a POSIX pthread path, but a non-Windows compiler cannot compile this Windows SEH block. Provide a supported non-Windows memory-read implementation or guard the SEH implementation with a platform-specific alternative.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-21 21:31 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1559#discussion_r4342191447) <!-- coderabbit-ai-generated:v1 --> **🎯 Functional Correctness** | **🔴 Critical** | **🏗️ Heavy lift** **Replace the Windows-only guest-memory read on non-Windows builds.** `ReadGuestWords` uses `__try` and `__except` without a platform guard. The same file has a POSIX `pthread` path, but a non-Windows compiler cannot compile this Windows SEH block. Provide a supported non-Windows memory-read implementation or guard the SEH implementation with a platform-specific alternative. <!-- fingerprinting:phantom:medusa:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:112d4a360471d7013b87489c --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -582,0 +947,4 @@
for (const auto low: all_functions) {
if (functions.size() >= RtCallGroupMinimum) break;
functions.insert(low);
}
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-21 21:31 UTC · original

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Do not execute padding functions in another call group.

When a group has fewer than four functions, this loop inserts functions from all_functions regardless of CallGroupOf. The compare chain then executes those functions in their own group and in the padded group. A function with a store or atomic operation can apply its effect twice for one call. Keep the descriptor-resolution padding without making foreign-group bodies executable.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-21 21:31 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1559#discussion_r4342191455) <!-- coderabbit-ai-generated:v1 --> **🗄️ Data Integrity & Integration** | **🟠 Major** | **🏗️ Heavy lift** **Do not execute padding functions in another call group.** When a group has fewer than four functions, this loop inserts functions from `all_functions` regardless of `CallGroupOf`. The compare chain then executes those functions in their own group and in the padded group. A function with a store or atomic operation can apply its effect twice for one call. Keep the descriptor-resolution padding without making foreign-group bodies executable. <!-- fingerprinting:phantom:medusa:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:8dee42e5fe9f570333362e55 --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -582,0 +1308,4 @@
return opcode_word | (static_cast<uint32_t>(delta) & 0xffffu);
};
// the call becomes a branch to the first chunk's entry chain
out[return_index - 1u] = branch_word(0xbf820000u, return_index - 1u, chunks[0].entry);
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-21 21:31 UTC · original

🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

Check the call-to-entry branch range.

branch_word retains only the low 16 bits of the signed branch displacement. If the original program is large, or an earlier call-site expansion has already appended enough code, chunks[0].entry can be more than 32,767 words from this call. The rewritten call then branches to the wrong instruction. Reject that layout or place a reachable relay near the call; apply the same range check to return relays.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-21 21:31 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1559#discussion_r4342191463) <!-- coderabbit-ai-generated:v1 --> **🎯 Functional Correctness** | **🟠 Major** | **🏗️ Heavy lift** **Check the call-to-entry branch range.** `branch_word` retains only the low 16 bits of the signed branch displacement. If the original program is large, or an earlier call-site expansion has already appended enough code, `chunks[0].entry` can be more than 32,767 words from this call. The rewritten call then branches to the wrong instruction. Reject that layout or place a reachable relay near the call; apply the same range check to return relays. <!-- fingerprinting:phantom:medusa:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:58e56deded3c6a42cbff950d --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -595,3 +1470,3 @@
Decoder::DecodeProgram(code, source.decoded);
}
if (source.decoded.has_swap_pc) {
if (source.decoded.has_swap_pc && !RtOwnsCalls(options)) {
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-21 21:31 UTC · original

🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

Keep the existing scalar-call linking path for non-RT compute shaders.

With --raytracing, RtOwnsCalls bypasses PrepareCallTarget for every compute shader with S_SWAPPC_B64. The existing RefreshShaderSource path supports scalar leaf calls, but an unrelated call that ExpandOneCall cannot expand now reaches uses_function_calls and has its dispatch skipped. Select RT ownership from an eligible call-table form rather than the global flag and compute stage alone.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-21 21:31 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1559#discussion_r4342191467) <!-- coderabbit-ai-generated:v1 --> **🎯 Functional Correctness** | **🟠 Major** | **🏗️ Heavy lift** **Keep the existing scalar-call linking path for non-RT compute shaders.** With `--raytracing`, `RtOwnsCalls` bypasses `PrepareCallTarget` for *every* compute shader with `S_SWAPPC_B64`. The existing `RefreshShaderSource` path supports scalar leaf calls, but an unrelated call that `ExpandOneCall` cannot expand now reaches `uses_function_calls` and has its dispatch skipped. Select RT ownership from an eligible call-table form rather than the global flag and compute stage alone. <!-- fingerprinting:phantom:medusa:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:0428251991682a9657191b95 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-21 21:31 UTC · original · reviewed

Actionable comments posted: 17


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: e3430fea-7310-48ba-80e5-db0f8fd994da
📥 Commits

Reviewing files that changed from the base of the PR and between 5dec523143 and fa1d98c6d8.

📒 Files selected for processing: 68
  • CMakeLists.txt
  • src/common/emulatorConfig.cpp
  • src/common/emulatorConfig.h
  • src/graphics/guest_gpu/gpu_format.cpp
  • src/graphics/host_gpu/renderer/image/image.cpp
  • src/graphics/host_gpu/renderer/pipeline/descriptors.cpp
  • src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp
  • src/graphics/host_gpu/renderer/pipeline/pipelineCache.h
  • src/graphics/host_gpu/renderer/pipeline/shaders.cpp
  • src/graphics/host_gpu/renderer/render.h
  • src/graphics/host_gpu/renderer/renderCompute.cpp
  • src/graphics/host_gpu/vulkanCommon.cpp
  • src/graphics/presentation/window/vulkanWindow.cpp
  • src/graphics/shader/recompiler/RtFeedback.h
  • src/graphics/shader/recompiler/ShaderRecompiler.cpp
  • src/graphics/shader/recompiler/ShaderRecompiler.h
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterBvh.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterFlow.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterHelpers.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterInstructions.h
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemoryHelpers.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterModule.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp
  • src/graphics/shader/recompiler/frontend/decode/MemoryOps.cpp
  • src/graphics/shader/recompiler/frontend/decode/ScalarAluOps.cpp
  • src/graphics/shader/recompiler/frontend/decode/ShaderDecoder.cpp
  • src/graphics/shader/recompiler/frontend/decode/ShaderDecoder.h
  • src/graphics/shader/recompiler/frontend/translate/Memory.cpp
  • src/graphics/shader/recompiler/frontend/translate/Scalar.cpp
  • src/graphics/shader/recompiler/frontend/translate/Translate.cpp
  • src/graphics/shader/recompiler/frontend/translate/Translate.h
  • src/graphics/shader/recompiler/frontend/translate/Translator.h
  • src/graphics/shader/recompiler/ir/Block.cpp
  • src/graphics/shader/recompiler/ir/Program.cpp
  • src/graphics/shader/recompiler/ir/ShaderIR.h
  • src/graphics/shader/recompiler/ir/Value.cpp
  • src/graphics/shader/recompiler/ir/opcodes/ValueOpcodes.cpp
  • src/graphics/shader/recompiler/ir/opcodes/ValueOpcodes.inc
  • src/graphics/shader/recompiler/ir/passes/ConstantPropagation.cpp
  • src/graphics/shader/recompiler/ir/passes/ConstantPropagation.h
  • src/graphics/shader/recompiler/ir/passes/DynamicBuffer.cpp
  • src/graphics/shader/recompiler/ir/passes/DynamicBuffer.h
  • src/graphics/shader/recompiler/ir/passes/PhiWebs.cpp
  • src/graphics/shader/recompiler/ir/passes/PhiWebs.h
  • src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp
  • src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp
  • src/graphics/shader/recompiler/ir/passes/ShaderInfoCollection.cpp
  • src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp
  • src/graphics/shader/recompiler/ir/passes/SrtWalker.h
  • src/graphics/shader/recompiler/ir/passes/SsaRewrite.cpp
  • src/graphics/shader/shader.cpp
  • src/graphics/shader/shader.h
  • src/kernel/memory.cpp
  • src/kernel/memory.h
  • src/launcher/forms/configuration_edit_dialog.ui
  • src/launcher/include/configuration.h
  • src/launcher/src/configuration.cpp
  • src/launcher/src/configurationEditDialog.cpp
  • src/launcher/src/mainDialog.cpp
  • src/main.cpp
  • tests/RaytracingConfigStub.cpp
  • tests/ResourceTrackingTests.cpp
  • tests/ScalarProvenanceTests.cpp
  • tests/ShaderRecompilerComputeTests.cpp
  • tests/shaderCfgTests.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.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-21 21:31 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1559#pullrequestreview-5606498573) · **reviewed** <!-- coderabbit-ai-generated:v1 --> **Actionable comments posted: 17** --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> - **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `e3430fea-7310-48ba-80e5-db0f8fd994da` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 5dec523143930e35a6a5a9839f972774420b7958 and fa1d98c6d85a78122a81cd574219cdf5e2c8cead. </details> <details> <summary>📒 Files selected for processing: 68</summary> * `CMakeLists.txt` * `src/common/emulatorConfig.cpp` * `src/common/emulatorConfig.h` * `src/graphics/guest_gpu/gpu_format.cpp` * `src/graphics/host_gpu/renderer/image/image.cpp` * `src/graphics/host_gpu/renderer/pipeline/descriptors.cpp` * `src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp` * `src/graphics/host_gpu/renderer/pipeline/pipelineCache.h` * `src/graphics/host_gpu/renderer/pipeline/shaders.cpp` * `src/graphics/host_gpu/renderer/render.h` * `src/graphics/host_gpu/renderer/renderCompute.cpp` * `src/graphics/host_gpu/vulkanCommon.cpp` * `src/graphics/presentation/window/vulkanWindow.cpp` * `src/graphics/shader/recompiler/RtFeedback.h` * `src/graphics/shader/recompiler/ShaderRecompiler.cpp` * `src/graphics/shader/recompiler/ShaderRecompiler.h` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterBvh.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterFlow.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterHelpers.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterInstructions.h` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemoryHelpers.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterModule.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp` * `src/graphics/shader/recompiler/frontend/decode/MemoryOps.cpp` * `src/graphics/shader/recompiler/frontend/decode/ScalarAluOps.cpp` * `src/graphics/shader/recompiler/frontend/decode/ShaderDecoder.cpp` * `src/graphics/shader/recompiler/frontend/decode/ShaderDecoder.h` * `src/graphics/shader/recompiler/frontend/translate/Memory.cpp` * `src/graphics/shader/recompiler/frontend/translate/Scalar.cpp` * `src/graphics/shader/recompiler/frontend/translate/Translate.cpp` * `src/graphics/shader/recompiler/frontend/translate/Translate.h` * `src/graphics/shader/recompiler/frontend/translate/Translator.h` * `src/graphics/shader/recompiler/ir/Block.cpp` * `src/graphics/shader/recompiler/ir/Program.cpp` * `src/graphics/shader/recompiler/ir/ShaderIR.h` * `src/graphics/shader/recompiler/ir/Value.cpp` * `src/graphics/shader/recompiler/ir/opcodes/ValueOpcodes.cpp` * `src/graphics/shader/recompiler/ir/opcodes/ValueOpcodes.inc` * `src/graphics/shader/recompiler/ir/passes/ConstantPropagation.cpp` * `src/graphics/shader/recompiler/ir/passes/ConstantPropagation.h` * `src/graphics/shader/recompiler/ir/passes/DynamicBuffer.cpp` * `src/graphics/shader/recompiler/ir/passes/DynamicBuffer.h` * `src/graphics/shader/recompiler/ir/passes/PhiWebs.cpp` * `src/graphics/shader/recompiler/ir/passes/PhiWebs.h` * `src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp` * `src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp` * `src/graphics/shader/recompiler/ir/passes/ShaderInfoCollection.cpp` * `src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp` * `src/graphics/shader/recompiler/ir/passes/SrtWalker.h` * `src/graphics/shader/recompiler/ir/passes/SsaRewrite.cpp` * `src/graphics/shader/shader.cpp` * `src/graphics/shader/shader.h` * `src/kernel/memory.cpp` * `src/kernel/memory.h` * `src/launcher/forms/configuration_edit_dialog.ui` * `src/launcher/include/configuration.h` * `src/launcher/src/configuration.cpp` * `src/launcher/src/configurationEditDialog.cpp` * `src/launcher/src/mainDialog.cpp` * `src/main.cpp` * `tests/RaytracingConfigStub.cpp` * `tests/ResourceTrackingTests.cpp` * `tests/ScalarProvenanceTests.cpp` * `tests/ShaderRecompilerComputeTests.cpp` * `tests/shaderCfgTests.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> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=be71e848-723a-4425-835e-67f826b81f18 attempt=c0960edb-51d0-4169-ab09-e49494fc1778 batch=1/1 -->
Author
Owner

@⁠ew-sudo on GitHub · 2026-10-26 19:45 UTC · original

Tested this PR on Gran Turismo 7 (PPSA01317), RTX 4070 Laptop. GT7's garage uses a ray tracing kernel with a call table of 12 hit functions. Without this PR, main stops in FindScalarDefinition (the call target is path-dependent). With it, the table is found (group 0/12 inlines 4 of 12 known functions), the 13 pipelines compile, and the car renders correctly in the garage. It needed two small changes, both below.

1. A function return encoded as S_SWAPPC_B64 NULL, s[14:15]. GT7's hit functions return with befd210e instead of S_SETPC_B64 s[14:15] (be80200e). FindFunctionExtent did not see the end of the function, decoded the data after it (0x30306c73, ASCII) and stopped with unsupported scalar source operand 0x73. Treating both encodings as a return fixes it in the three places that look for SetPcWordS14:

diff
diff --git a/src/graphics/shader/recompiler/ShaderRecompiler.cpp b/src/graphics/shader/recompiler/ShaderRecompiler.cpp
index a66f254b..5e06527c 100644
--- a/src/graphics/shader/recompiler/ShaderRecompiler.cpp
+++ b/src/graphics/shader/recompiler/ShaderRecompiler.cpp
@@ -604,6 +604,12 @@ void PrepareCallTarget(ShaderSource& source, const CompileOptions& options) {
 // back to the instruction after the call. Only a single call site is supported.
 constexpr uint32_t SwapPcWordS14S14 = 0xbe8e210eu;
 constexpr uint32_t SetPcWordS14     = 0xbe80200eu;
+// S_SWAPPC_B64 NULL, s[14:15] discards the return PC, so it returns like S_SETPC_B64 s[14:15]
+// (Gran Turismo 7's hit functions end this way).
+constexpr uint32_t SwapPcNullWordS14 = 0xbefd210eu;
+constexpr bool     IsReturnWord(uint32_t word) {
+	return word == SetPcWordS14 || word == SwapPcNullWordS14;
+}
 // SOPC s_cmp_eq_u32 (opcode 0x06) with SSRC0 = 255, so the literal is the first operand and follows in
 // the next dword, and SSRC1 = 14, the register the call put the function address in.
 constexpr uint32_t CmpEqLiteralS14  = 0xbf060effu;
@@ -661,7 +667,7 @@ size_t FindFunctionExtent(std::span<const uint32_t> body) {
 		Decoder::DecodeInstruction(body, index, inst);
 		index += inst.word_count;
 		if (Decoder::IsDirectBranch(inst.opcode)) max_target = std::max(max_target, inst.branch_target);
-		if ((inst.raw[0] == SetPcWordS14 || inst.opcode == Decoder::Opcode::S_ENDPGM) &&
+		if ((IsReturnWord(inst.raw[0]) || inst.opcode == Decoder::Opcode::S_ENDPGM) &&
 		    index * sizeof(uint32_t) > max_target) {
 			return index;
 		}
@@ -1208,7 +1214,7 @@ bool ExpandOneCall(const CompileOptions& options, std::span<const uint32_t> code
 				return false;
 			}
 			relocated[index] = function.body.size();
-			if (inst.raw[0] == SetPcWordS14) {
+			if (IsReturnWord(inst.raw[0])) {
 				for (const auto& reg: saved_regs)
 					function.body.push_back(MovRegSS(reg.clobbered, reg.saved));
 				++returns;
@@ -1353,7 +1359,7 @@ bool ExpandOneCall(const CompileOptions& options, std::span<const uint32_t> code
 				Decoder::Instruction inst;
 				Decoder::DecodeInstruction(body, index, inst);
 				const size_t at = first + index;
-				if (inst.raw[0] == SetPcWordS14) {
+				if (IsReturnWord(inst.raw[0])) {
 					out[at] = branch_word(0xbf820000u, at, chunk.ret);
 				}
 				index += inst.word_count;

2. GPU-selected images and samplers in RT kernels (workaround, not a real fix). Kernel 0x5d8fac8c06b94572 loads the T# and S# of the hit object's material through a chain of pointers (LoadAddressU32(GetAddressResource(LoadAddressU32(...)))), so resource tracking stops with GetImageResource dword 0 is not a valid runtime value (then the same for GetSamplerResource). As a stopgap, in call-table kernels only, such a descriptor becomes a null image or the zero sampler. The kernel then runs, but reflected objects lose their texture. A real fix would read the descriptor in the shader; I left that to you since it is your design.

diff
diff --git a/src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp b/src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp
index 51e2ee91..904195ec 100644
--- a/src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp
+++ b/src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp
@@ -4077,6 +4077,32 @@ private:
 				handle->SetArg(bad_dword, Value(0u));
 				continue;
 			}
+			// In a ray tracing kernel, an image (or sampler) whose descriptor the GPU finds through pointers
+			// in memory (the material of the object a ray hit) cannot be known here. Sample it
+			// as a null image instead of stopping: the kernel runs, those reads return zero.
+			// KYTY_RT_NULL_IMAGES=0 keeps the failure.
+			static const bool rt_null_images = [] {
+				const char* value = std::getenv("KYTY_RT_NULL_IMAGES");
+				return value == nullptr || value[0] != '0';
+			}();
+			if (rt_null_images &&
+			    (expected == ValueOpcode::GetImageResource ||
+			     expected == ValueOpcode::GetSamplerResource) &&
+			    m_program.gpu_selected_call_payloads) {
+				// A sampler found the same way becomes the zero sampler (point filtering, wrap).
+				std::fprintf(stderr,
+				             "RT images: hash=0x%016llx pc=0x%08x %s descriptor dword %u is "
+				             "GPU-selected; %s\n",
+				             static_cast<unsigned long long>(m_program.shader_hash), pc,
+				             expected == ValueOpcode::GetImageResource ? "image" : "sampler", bad_dword,
+				             expected == ValueOpcode::GetImageResource ? "sampled as a null image"
+				                                                       : "replaced by the zero sampler");
+				for (uint32_t word = 0; word < descriptor.dword_count; ++word) {
+					descriptor.dwords[word] = Value(0u);
+					if (word < handle->NumArgs()) handle->SetArg(word, Value(0u));
+				}
+				continue;
+			}
 			std::string trace;
 			{
 				// Diagnostic: the opcode tree behind the bad dword.

Also seen: RT calls: only 2 free SGPRs for the call saves (s83 not preserved) on this kernel.

Performance: below 1 fps in the garage once the pipelines are compiled, and about 70 s of RT pipeline compiles on the first visit.

Notes:

  • The test also included #1032 (tessellation) and main's EQAA approximation 5f29374d, which this PR's base predates.
  • GT7 stopped in a race with #1032 alone, so the tessellation for GT7 is in #1919.
  • On current main, GT7 also needs #1918.

What is still missing (for a real fix)

  • GPU-selected descriptors: the null image / zero sampler in change 2 is only a stopgap. Reflections of other objects are wrong (no texture). The T#/S# should be loaded in the shader from the address the kernel computes, for example through a descriptor heap or a buffer-backed descriptor path.
  • Register saves around calls: only 2 free SGPRs for the call saves (s83 not preserved) means some state may not survive a call. It did not show visibly in the garage, but results may be wrong.
  • Performance: below 1 fps in the garage, with 12 call groups each in its own dispatch and the BVH traversed node by node. It is unplayable as is.
  • Compile time: about 70 s of RT pipeline compiles (4 to 19 s each) on the first garage visit.
  • Base: this PR conflicts with current main (about 20 files in the recompiler). Change 1 is small and should carry over after a rebase.
**@⁠ew-sudo** on GitHub · 2026-10-26 19:45 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1559#issuecomment-6425702777) Tested this PR on **Gran Turismo 7 (PPSA01317)**, RTX 4070 Laptop. GT7's garage uses a ray tracing kernel with a call table of 12 hit functions. Without this PR, main stops in `FindScalarDefinition` (the call target is path-dependent). With it, the table is found (`group 0/12 inlines 4 of 12 known functions`), the 13 pipelines compile, and the car renders correctly in the garage. It needed two small changes, both below. **1. A function return encoded as `S_SWAPPC_B64 NULL, s[14:15]`.** GT7's hit functions return with `befd210e` instead of `S_SETPC_B64 s[14:15]` (`be80200e`). `FindFunctionExtent` did not see the end of the function, decoded the data after it (`0x30306c73`, ASCII) and stopped with `unsupported scalar source operand 0x73`. Treating both encodings as a return fixes it in the three places that look for `SetPcWordS14`: <details><summary>diff</summary> ```diff diff --git a/src/graphics/shader/recompiler/ShaderRecompiler.cpp b/src/graphics/shader/recompiler/ShaderRecompiler.cpp index a66f254b..5e06527c 100644 --- a/src/graphics/shader/recompiler/ShaderRecompiler.cpp +++ b/src/graphics/shader/recompiler/ShaderRecompiler.cpp @@ -604,6 +604,12 @@ void PrepareCallTarget(ShaderSource& source, const CompileOptions& options) { // back to the instruction after the call. Only a single call site is supported. constexpr uint32_t SwapPcWordS14S14 = 0xbe8e210eu; constexpr uint32_t SetPcWordS14 = 0xbe80200eu; +// S_SWAPPC_B64 NULL, s[14:15] discards the return PC, so it returns like S_SETPC_B64 s[14:15] +// (Gran Turismo 7's hit functions end this way). +constexpr uint32_t SwapPcNullWordS14 = 0xbefd210eu; +constexpr bool IsReturnWord(uint32_t word) { + return word == SetPcWordS14 || word == SwapPcNullWordS14; +} // SOPC s_cmp_eq_u32 (opcode 0x06) with SSRC0 = 255, so the literal is the first operand and follows in // the next dword, and SSRC1 = 14, the register the call put the function address in. constexpr uint32_t CmpEqLiteralS14 = 0xbf060effu; @@ -661,7 +667,7 @@ size_t FindFunctionExtent(std::span<const uint32_t> body) { Decoder::DecodeInstruction(body, index, inst); index += inst.word_count; if (Decoder::IsDirectBranch(inst.opcode)) max_target = std::max(max_target, inst.branch_target); - if ((inst.raw[0] == SetPcWordS14 || inst.opcode == Decoder::Opcode::S_ENDPGM) && + if ((IsReturnWord(inst.raw[0]) || inst.opcode == Decoder::Opcode::S_ENDPGM) && index * sizeof(uint32_t) > max_target) { return index; } @@ -1208,7 +1214,7 @@ bool ExpandOneCall(const CompileOptions& options, std::span<const uint32_t> code return false; } relocated[index] = function.body.size(); - if (inst.raw[0] == SetPcWordS14) { + if (IsReturnWord(inst.raw[0])) { for (const auto& reg: saved_regs) function.body.push_back(MovRegSS(reg.clobbered, reg.saved)); ++returns; @@ -1353,7 +1359,7 @@ bool ExpandOneCall(const CompileOptions& options, std::span<const uint32_t> code Decoder::Instruction inst; Decoder::DecodeInstruction(body, index, inst); const size_t at = first + index; - if (inst.raw[0] == SetPcWordS14) { + if (IsReturnWord(inst.raw[0])) { out[at] = branch_word(0xbf820000u, at, chunk.ret); } index += inst.word_count; ``` </details> **2. GPU-selected images and samplers in RT kernels (workaround, not a real fix).** Kernel `0x5d8fac8c06b94572` loads the T# and S# of the hit object's material through a chain of pointers (`LoadAddressU32(GetAddressResource(LoadAddressU32(...)))`), so resource tracking stops with `GetImageResource dword 0 is not a valid runtime value` (then the same for `GetSamplerResource`). As a stopgap, in call-table kernels only, such a descriptor becomes a null image or the zero sampler. The kernel then runs, but reflected objects lose their texture. A real fix would read the descriptor in the shader; I left that to you since it is your design. <details><summary>diff</summary> ```diff diff --git a/src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp b/src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp index 51e2ee91..904195ec 100644 --- a/src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp +++ b/src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp @@ -4077,6 +4077,32 @@ private: handle->SetArg(bad_dword, Value(0u)); continue; } + // In a ray tracing kernel, an image (or sampler) whose descriptor the GPU finds through pointers + // in memory (the material of the object a ray hit) cannot be known here. Sample it + // as a null image instead of stopping: the kernel runs, those reads return zero. + // KYTY_RT_NULL_IMAGES=0 keeps the failure. + static const bool rt_null_images = [] { + const char* value = std::getenv("KYTY_RT_NULL_IMAGES"); + return value == nullptr || value[0] != '0'; + }(); + if (rt_null_images && + (expected == ValueOpcode::GetImageResource || + expected == ValueOpcode::GetSamplerResource) && + m_program.gpu_selected_call_payloads) { + // A sampler found the same way becomes the zero sampler (point filtering, wrap). + std::fprintf(stderr, + "RT images: hash=0x%016llx pc=0x%08x %s descriptor dword %u is " + "GPU-selected; %s\n", + static_cast<unsigned long long>(m_program.shader_hash), pc, + expected == ValueOpcode::GetImageResource ? "image" : "sampler", bad_dword, + expected == ValueOpcode::GetImageResource ? "sampled as a null image" + : "replaced by the zero sampler"); + for (uint32_t word = 0; word < descriptor.dword_count; ++word) { + descriptor.dwords[word] = Value(0u); + if (word < handle->NumArgs()) handle->SetArg(word, Value(0u)); + } + continue; + } std::string trace; { // Diagnostic: the opcode tree behind the bad dword. ``` </details> Also seen: `RT calls: only 2 free SGPRs for the call saves (s83 not preserved)` on this kernel. Performance: below 1 fps in the garage once the pipelines are compiled, and about 70 s of RT pipeline compiles on the first visit. Notes: - The test also included #1032 (tessellation) and main's EQAA approximation 5f29374d, which this PR's base predates. - GT7 stopped in a race with #1032 alone, so the tessellation for GT7 is in https://git.gtahub.st/github/KytyPS5--KytyPS5/pulls/1919. - On current main, GT7 also needs #1918. ### What is still missing (for a real fix) - **GPU-selected descriptors**: the null image / zero sampler in change 2 is only a stopgap. Reflections of other objects are wrong (no texture). The T#/S# should be loaded in the shader from the address the kernel computes, for example through a descriptor heap or a buffer-backed descriptor path. - **Register saves around calls**: `only 2 free SGPRs for the call saves (s83 not preserved)` means some state may not survive a call. It did not show visibly in the garage, but results may be wrong. - **Performance**: below 1 fps in the garage, with 12 call groups each in its own dispatch and the BVH traversed node by node. It is unplayable as is. - **Compile time**: about 70 s of RT pipeline compiles (4 to 19 s each) on the first garage visit. - **Base**: this PR conflicts with current main (about 20 files in the recompiler). Change 1 is small and should carry over after a rebase.
This pull request has changes conflicting with the target branch.
  • src/graphics/host_gpu/renderer/pipeline/descriptors.cpp
  • src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp
  • src/graphics/host_gpu/renderer/pipeline/pipelineCache.h
  • src/graphics/host_gpu/renderer/pipeline/shaders.cpp
  • src/graphics/host_gpu/renderer/render.h
  • src/graphics/host_gpu/renderer/renderCompute.cpp
  • src/graphics/shader/recompiler/ShaderRecompiler.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterInstructions.h
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp
  • src/graphics/shader/recompiler/frontend/decode/MemoryOps.cpp
  • src/graphics/shader/recompiler/frontend/decode/ShaderDecoder.cpp
  • src/graphics/shader/recompiler/frontend/translate/Memory.cpp
  • src/graphics/shader/recompiler/frontend/translate/Scalar.cpp
  • src/graphics/shader/recompiler/frontend/translate/Translate.cpp
  • src/graphics/shader/recompiler/ir/Program.cpp
  • src/graphics/shader/recompiler/ir/ShaderIR.h
  • src/graphics/shader/recompiler/ir/Value.cpp
  • src/graphics/shader/recompiler/ir/opcodes/ValueOpcodes.cpp
  • src/graphics/shader/recompiler/ir/passes/ConstantPropagation.cpp
  • src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp
  • src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp
  • src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp
  • src/graphics/shader/recompiler/ir/passes/SsaRewrite.cpp
  • src/graphics/shader/shader.cpp
  • src/kernel/memory.cpp
  • src/kernel/memory.h
  • src/launcher/include/configuration.h
  • src/launcher/src/configuration.cpp
  • src/launcher/src/configurationEditDialog.cpp
  • src/launcher/src/mainDialog.cpp
  • src/main.cpp
  • tests/ResourceTrackingTests.cpp
  • tests/ShaderRecompilerComputeTests.cpp
View command line instructions

Manual merge helper

Use this merge commit message when completing the merge manually.

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin '+refs/pull/1559/head:github-bot/gh-1559'
git switch 'github-bot/gh-1559'

Merge

Merge the changes and update on Forgejo.
git switch 'main'
git merge --no-ff 'github-bot/gh-1559'
git switch 'github-bot/gh-1559'
git rebase 'main'
git switch 'main'
git merge --ff-only 'github-bot/gh-1559'
git switch 'github-bot/gh-1559'
git rebase 'main'
git switch 'main'
git merge --no-ff 'github-bot/gh-1559'
git switch 'main'
git merge --squash 'github-bot/gh-1559'
git switch 'main'
git merge --ff-only 'github-bot/gh-1559'
git switch 'main'
git merge 'github-bot/gh-1559'
git push origin 'main'
This discussion has been locked. Commenting is limited to contributors.
No description provided.