shader: track GPU-selected buffer stores through a bounded descriptor table (GTA V crash) #2501

Open
github-bot wants to merge 1 commit from github-bot/gh-2501 into main AGit
Owner

@⁠taklaciwiz-maker on GitHub · 2026-11-21 21:05 UTC · original
taklaciwiz-maker:gta-v-shader-fix → main · +164 −18 · 3 files · 1 commits · open

Fixes #2277. That report has the same exit, on PPSA04263.

Problem

GTA V (PPSA04264, 01.011.001) exits during the first mission with:

shader resource tracking: hash=0xe777d90ed493bd6c stage=compute pc=0x0000093c buffer descriptor is not
a valid runtime value; GPU-selected access requires a scalar, raw 8/16-bit, raw DWORD x1/x2/x3/x4,
or formatted X load

The compute shader runs a waterfall loop:

  1. v_readfirstlane picks a key from a per-lane value. That value comes from an unbounded buffer load
    (BUFFER_LOAD_DWORD v0, v31, s12 ... idxen offset:52).
  2. S_BUFFER_LOAD_DWORDX4 s0, s8, key << 4 loads a V# from a 16-byte-stride table.
  3. BUFFER_STORE_DWORD ... offen writes through that V#.

TryMakeIndirectBuffer accepts this store pattern only through the legacy-store path. That path needs the
key to be a loop-bounded material index (BoundedSelectedIndex). Here the key has no bound, so tracking
fails.

The load path already handles this shape with table_scalar: the table V# bounds every reachable
descriptor.

Changes (3 files, +164/-18, against main 39936ff, clang-format 22 applied to the changed lines)

  1. ResourceTracking.cpp, TryMakeIndirectBuffer:
    • Applies to a legacy store table of 4-DWORD, 16-byte-stride rows.
    • When the material-key matching fails (UniformizedMaterialValue / IndexedMaterialRead /
      BoundedSelectedIndex), it falls back to table_scalar, as the load path does.
    • A key that is not a ReadFirstLane result is still rejected.
  2. ResourceMaterialization.cpp / ShaderIR.h, row limit:
    • The table in this scene has 131072 rows (2 MiB).
    • Added MaxIndirectScalarTableRows = 262144, used only for table_scalar scans.
    • The general MaxIndirectDescriptorProbes is unchanged; index proofs also use it.
  3. NormalizeIndirectBuffer:
    • Applies to a candidate that is non-indexed (offen only), unswizzled and unformatted, with
      OOB_SELECT = 0. Example: 66ec0000,00040002,00017bb0,00014204, stride 4, 97200 records.
    • Such a candidate is rewritten to raw byte bounds: stride 1, records = stride × records, OOB 3.
    • Direct buffers treat this descriptor as [base, base + stride * records).
    • I did not verify the exact RDNA2 behaviour of OOB_SELECT = 0 with stride 4 for raw offsets, so
      this may be more permissive than hardware.
  4. Scan performance:
    • MaterializeResources runs on every FindModule, so the 131072-row scan ran on every dispatch:
      ~26–30 ms each, ~500 scans/min, about 2 FPS.
    • The flat table is now read in one ReadScalarTable call instead of one call per row.
    • ResourcePlan::scan_cache (ScanCacheEntry, buffer resources only) stores the candidates and
      mapping of each scan.
    • Cache key: the table geometry (base, size, first, step, count), the root descriptor and an XXH3 hash
      of the table bytes. When all of them match, the stored result is replayed.
    • Measured: 2894 of 2910 scans hit the cache, at 0.22 ms per hit vs ~26 ms per miss.

Results

  • The crash is gone. The mission plays with correct visuals in the scenes I tested.
  • FPS went from a crash, to ~2 FPS with the uncached scan, to 12–13 FPS with the cache. Hardware:
    RTX 5070 / Ryzen 5 7600X.
  • The remaining low FPS is not caused by this change. The same waits appear on buffers this shader does
    not touch; see my comment in #2277.
  • I developed and measured this on a21fd80, then rebased it onto 39936ff with no conflicts.
  • Re-tested on 39936ff, on a build that also has a separate HTile fix and native_rt=true:
    • The prologue (Ludendorff bank) plays through the hostages, the vault charge and the alarm corridor,
      about 7 minutes with no crash.
    • 0xe777d90ed493bd6c is translated several times with no tracking error.
    • 11–13 FPS. The log has only the known MSAA sample-location warnings.

Caveats

  • With table_scalar, every distinct descriptor in the table is bound as a written storage buffer on every
    dispatch. This scene has 7 of them, up to 41 MB each. All of them are marked GPU-modified in full,
    although each waterfall iteration writes only one. This is correct but coarse.
  • The OOB_SELECT = 0 normalization (item 3) should be checked against hardware.
  • I tested one game and one area only.
  • The large GTA integration PR #2469 also touches ResourceTracking.cpp and ResourceMaterialization.cpp.
    I did not check whether it fixes this crash in a different way.

🤖 Generated with Claude Code

**@⁠taklaciwiz-maker** on GitHub · 2026-11-21 21:05 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2501) `taklaciwiz-maker:gta-v-shader-fix` → `main` · +164 −18 · 3 files · 1 commits · open Fixes #2277. That report has the same exit, on PPSA04263. ## Problem GTA V (PPSA04264, 01.011.001) exits during the first mission with: ``` shader resource tracking: hash=0xe777d90ed493bd6c stage=compute pc=0x0000093c buffer descriptor is not a valid runtime value; GPU-selected access requires a scalar, raw 8/16-bit, raw DWORD x1/x2/x3/x4, or formatted X load ``` The compute shader runs a waterfall loop: 1. `v_readfirstlane` picks a key from a per-lane value. That value comes from an unbounded buffer load (`BUFFER_LOAD_DWORD v0, v31, s12 ... idxen offset:52`). 2. `S_BUFFER_LOAD_DWORDX4 s0, s8, key << 4` loads a V# from a 16-byte-stride table. 3. `BUFFER_STORE_DWORD ... offen` writes through that V#. `TryMakeIndirectBuffer` accepts this store pattern only through the legacy-store path. That path needs the key to be a loop-bounded material index (`BoundedSelectedIndex`). Here the key has no bound, so tracking fails. The load path already handles this shape with `table_scalar`: the table V# bounds every reachable descriptor. ## Changes (3 files, +164/-18, against main 39936ff, clang-format 22 applied to the changed lines) 1. **`ResourceTracking.cpp`, `TryMakeIndirectBuffer`:** - Applies to a legacy store table of 4-DWORD, 16-byte-stride rows. - When the material-key matching fails (`UniformizedMaterialValue` / `IndexedMaterialRead` / `BoundedSelectedIndex`), it falls back to `table_scalar`, as the load path does. - A key that is not a `ReadFirstLane` result is still rejected. 2. **`ResourceMaterialization.cpp` / `ShaderIR.h`, row limit:** - The table in this scene has 131072 rows (2 MiB). - Added `MaxIndirectScalarTableRows = 262144`, used only for `table_scalar` scans. - The general `MaxIndirectDescriptorProbes` is unchanged; index proofs also use it. 3. **`NormalizeIndirectBuffer`:** - Applies to a candidate that is non-indexed (`offen` only), unswizzled and unformatted, with `OOB_SELECT = 0`. Example: `66ec0000,00040002,00017bb0,00014204`, stride 4, 97200 records. - Such a candidate is rewritten to raw byte bounds: stride 1, records = stride × records, OOB 3. - Direct buffers treat this descriptor as `[base, base + stride * records)`. - I did not verify the exact RDNA2 behaviour of `OOB_SELECT = 0` with stride 4 for raw offsets, so this may be more permissive than hardware. 4. **Scan performance:** - `MaterializeResources` runs on every `FindModule`, so the 131072-row scan ran on every dispatch: ~26–30 ms each, ~500 scans/min, about 2 FPS. - The flat table is now read in one `ReadScalarTable` call instead of one call per row. - `ResourcePlan::scan_cache` (`ScanCacheEntry`, buffer resources only) stores the candidates and mapping of each scan. - Cache key: the table geometry (base, size, first, step, count), the root descriptor and an XXH3 hash of the table bytes. When all of them match, the stored result is replayed. - Measured: 2894 of 2910 scans hit the cache, at 0.22 ms per hit vs ~26 ms per miss. ## Results - The crash is gone. The mission plays with correct visuals in the scenes I tested. - FPS went from a crash, to ~2 FPS with the uncached scan, to 12–13 FPS with the cache. Hardware: RTX 5070 / Ryzen 5 7600X. - The remaining low FPS is not caused by this change. The same waits appear on buffers this shader does not touch; see my comment in #2277. - I developed and measured this on a21fd80, then rebased it onto 39936ff with no conflicts. - Re-tested on 39936ff, on a build that also has a separate HTile fix and `native_rt=true`: - The prologue (Ludendorff bank) plays through the hostages, the vault charge and the alarm corridor, about 7 minutes with no crash. - `0xe777d90ed493bd6c` is translated several times with no tracking error. - 11–13 FPS. The log has only the known MSAA sample-location warnings. ## Caveats - With `table_scalar`, every distinct descriptor in the table is bound as a written storage buffer on every dispatch. This scene has 7 of them, up to 41 MB each. All of them are marked GPU-modified in full, although each waterfall iteration writes only one. This is correct but coarse. - The `OOB_SELECT = 0` normalization (item 3) should be checked against hardware. - I tested one game and one area only. - The large GTA integration PR #2469 also touches `ResourceTracking.cpp` and `ResourceMaterialization.cpp`. I did not check whether it fixes this crash in a different way. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
GTA V (PPSA04263/PPSA04264) exits with a shader resource tracking error at hash 0xe777d90ed493bd6c pc 0x93c: a waterfall loop stores through a V# loaded from a 16-byte-stride table with an unbounded key. Fall back to table_scalar for such legacy store tables, as the load path does, raise the row limit for table_scalar scans, normalize OOB_SELECT 0 raw candidates, and cache table scan results by table geometry and content hash.

Fixes #2277

Co-Authored-By: Claude Opus 5.5 <[email protected]>
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 10:21:30 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-21 21:17 UTC · original

Explain Change →

Walkthrough

The changes add a row limit and scan-result cache for indirect scalar descriptor tables. Materialization normalizes eligible indirect buffers and can bulk-read descriptor tables, reuse cached scan results, and store results after a cache miss. Resource tracking now falls back to scalar-table selection in specified cases where indirect-buffer matching or bounded-index proof is unavailable.

Suggested reviewers: nmzik, claxten10

Change: Bug fix · Severity of issue fixed: Medium

Merge Risk: Moderate · up to 0c2d9

This change lets GTA V shaders that select buffer descriptors through a table compile instead of failing. As written, the descriptor normalization can permit out-of-range stores that the original buffer bounds would drop. The new bulk table read can also cause the renderer to exit for certain buffer layouts that previously worked, and cold scans of very large tables may be slow. Resolve the bounds and read-capture issues before merging, or explicitly accept them.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: GPU-selected buffer stores are tracked through a bounded descriptor table (table_scalar fallback), with the GTA V crash as context. The raw summary and objectives desc…
Description check Passed The description is detailed and on-topic. It explains the GTA V crash, the waterfall-loop store pattern, and the TryMakeIndirectBuffer fallback. It also covers the row limit, the NormalizeIndirectBuff…
Linked Issues check Passed Issue #2277 is the only active direct target. Its requirement is that GTA V (PPSA04263) boots past shader resource tracking and does not stop with the error for hash 0xe777d90ed493bd6c, stage=compute,…
Out of Scope Changes check Passed The changes fall into four groups. (1) ResourceTracking.cpp: the table_scalar fallback. This is the direct fix for the reported error. (2) ResourceMaterialization.cpp and ShaderIR.h: MaxIndirectScalar…
Full details: Title check

Explanation

The title names the main change: GPU-selected buffer stores are tracked through a bounded descriptor table (table_scalar fallback), with the GTA V crash as context. The raw summary and objectives describe the same fallback in ResourceTracking.cpp, plus the row limit, normalization, and scan cache, which the title does not mention. The title is specific and matches the primary change.

Full details: Description check

Explanation

The description is detailed and on-topic. It explains the GTA V crash, the waterfall-loop store pattern, and the TryMakeIndirectBuffer fallback. It also covers the row limit, the NormalizeIndirectBuffer change, the XXH3-keyed scan cache, test results, and caveats. These match the raw summary and PR objectives.

Full details: Linked Issues check

Explanation

Issue #2277 is the only active direct target. Its requirement is that GTA V (PPSA04263) boots past shader resource tracking and does not stop with the error for hash 0xe777d90ed493bd6c, stage=compute, pc=0x0000093c. The PR changes TryMakeIndirectBuffer in ResourceTracking.cpp. The diff confirms that when material-key matching fails, the legacy store path now calls scalar_table() and sets indirect.table_scalar = true instead of returning false. The ReadFirstLane check still rejects keys that are not ReadFirstLane results. The hash and pc in the issue match the failure the PR addresses. The PR author reports that the crash is gone and that the prologue ran for about 7 minutes on PPSA04264 with the same shader hash. That is the same title and shader, but not the PPSA04263 serial named in the issue. The check is therefore satisfied by code and reported runtime evidence. No test was added in the diff. The evidence is the author's report, not a test in this PR.

Full details: Out of Scope Changes check

Explanation

The changes fall into four groups. (1) ResourceTracking.cpp: the table_scalar fallback. This is the direct fix for the reported error. (2) ResourceMaterialization.cpp and ShaderIR.h: MaxIndirectScalarTableRows (262144) applies only to table_scalar scans. The fallback needs this limit because the reported table has 131072 rows. This is connected to the fix. (3) NormalizeIndirectBuffer: rewrites non-indexed, unswizzled, unformatted raw candidates with OOB_SELECT = 0 to byte bounds. It applies to all matching buffers, not only this shader. The connection to the crash is indirect. The PR states that the RDNA2 behavior was not verified and may be more permissive than hardware. (4) Scan cache (ScanCacheEntry, ResourcePlan::scan_cache, XXH3 hashing, bulk ReadScalarTable). This addresses the cost of the new scan that runs on every FindModule call after the fix. The issue does not request a performance change. The cache is connected to the fix, so it is not shown to be unrelated. The PR objectives list all four groups as intended work. Group (3) carries an unverified hardware risk that the author discloses. It is not a demonstrated unrelated change.

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

**@⁠coderabbitai[bot]** on GitHub · 2026-11-21 21:17 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2501#issuecomment-7069371439) <!-- 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/2501?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-buttons-v1/explain-change-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-stack-buttons-v1/explain-change.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-buttons-v1/explain-change.svg" alt="Explain Change →" height="32"></picture></a> <!-- review_stack_entry_end --> <!-- walkthrough_start --> <details> <summary><strong>Walkthrough</strong></summary> <dl> <dd> <br> The changes add a row limit and scan-result cache for indirect scalar descriptor tables. Materialization normalizes eligible indirect buffers and can bulk-read descriptor tables, reuse cached scan results, and store results after a cache miss. Resource tracking now falls back to scalar-table selection in specified cases where indirect-buffer matching or bounded-index proof is unavailable. **Suggested reviewers:** `nmzik`, `claxten10` </dd> </dl> </details> <!-- walkthrough_end --> <!-- change_assessment_start --> <!-- change_assessment_commit:"0c2d9d7e9180c465f0b59d2461b30d74bd056e7c" --> <!-- change_assessment_priority:{"version":1,"urgency":"p2","manual":false} --> **Change:** Bug fix · **Severity of issue fixed:** Medium <!-- change_assessment_end --> <details> <summary><strong>Merge Risk:</strong> <strong><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/risk-normal-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Moderate</strong> · up to <code>0c2d9</code></summary> <dl> <dd> <br> <!-- final_review_risk_start --> <!-- final_review_risk_label **Merge Risk:** **🟡 Moderate** · up to `0c2d9` --> <!-- final_review_risk_coverage:{"sourceCommitId":"0c2d9d7e9180c465f0b59d2461b30d74bd056e7c","coveredCommitId":"0c2d9d7e9180c465f0b59d2461b30d74bd056e7c","kind":"reviewed"} --> This change lets GTA V shaders that select buffer descriptors through a table compile instead of failing. As written, the descriptor normalization can permit out-of-range stores that the original buffer bounds would drop. The new bulk table read can also cause the renderer to exit for certain buffer layouts that previously worked, and cold scans of very large tables may be slow. Resolve the bounds and read-capture issues before merging, or explicitly accept them. <!-- 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</strong></summary> <dl> <dd> <br> | Check name | Status | Explanation | | :------------------------ | :--------------------------------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Title check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The title names the main change: GPU-selected buffer stores are tracked through a bounded descriptor table (table_scalar fallback), with the GTA V crash as context. The raw summary and objectives desc… | | Description check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The description is detailed and on-topic. It explains the GTA V crash, the waterfall-loop store pattern, and the TryMakeIndirectBuffer fallback. It also covers the row limit, the NormalizeIndirectBuff… | | Linked Issues check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | Issue `#2277` is the only active direct target. Its requirement is that GTA V (PPSA04263) boots past shader resource tracking and does not stop with the error for hash 0xe777d90ed493bd6c, stage=compute,… | | Out of Scope Changes check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The changes fall into four groups. (1) ResourceTracking.cpp: the table_scalar fallback. This is the direct fix for the reported error. (2) ResourceMaterialization.cpp and ShaderIR.h: MaxIndirectScalar… | <details> <summary><strong>Full details: Title check</strong></summary> <dl> <dd> <br> **Explanation** The title names the main change: GPU-selected buffer stores are tracked through a bounded descriptor table (table_scalar fallback), with the GTA V crash as context. The raw summary and objectives describe the same fallback in ResourceTracking.cpp, plus the row limit, normalization, and scan cache, which the title does not mention. The title is specific and matches the primary change. </dd> </dl> </details> <details> <summary><strong>Full details: Description check</strong></summary> <dl> <dd> <br> **Explanation** The description is detailed and on-topic. It explains the GTA V crash, the waterfall-loop store pattern, and the TryMakeIndirectBuffer fallback. It also covers the row limit, the NormalizeIndirectBuffer change, the XXH3-keyed scan cache, test results, and caveats. These match the raw summary and PR objectives. </dd> </dl> </details> <details> <summary><strong>Full details: Linked Issues check</strong></summary> <dl> <dd> <br> **Explanation** Issue `#2277` is the only active direct target. Its requirement is that GTA V (PPSA04263) boots past shader resource tracking and does not stop with the error for hash 0xe777d90ed493bd6c, stage=compute, pc=0x0000093c. The PR changes TryMakeIndirectBuffer in ResourceTracking.cpp. The diff confirms that when material-key matching fails, the legacy store path now calls scalar_table() and sets indirect.table_scalar = true instead of returning false. The ReadFirstLane check still rejects keys that are not ReadFirstLane results. The hash and pc in the issue match the failure the PR addresses. The PR author reports that the crash is gone and that the prologue ran for about 7 minutes on PPSA04264 with the same shader hash. That is the same title and shader, but not the PPSA04263 serial named in the issue. The check is therefore satisfied by code and reported runtime evidence. No test was added in the diff. The evidence is the author's report, not a test in this PR. </dd> </dl> </details> <details> <summary><strong>Full details: Out of Scope Changes check</strong></summary> <dl> <dd> <br> **Explanation** The changes fall into four groups. (1) ResourceTracking.cpp: the table_scalar fallback. This is the direct fix for the reported error. (2) ResourceMaterialization.cpp and ShaderIR.h: MaxIndirectScalarTableRows (262144) applies only to table_scalar scans. The fallback needs this limit because the reported table has 131072 rows. This is connected to the fix. (3) NormalizeIndirectBuffer: rewrites non-indexed, unswizzled, unformatted raw candidates with OOB_SELECT = 0 to byte bounds. It applies to all matching buffers, not only this shader. The connection to the crash is indirect. The PR states that the RDNA2 behavior was not verified and may be more permissive than hardware. (4) Scan cache (ScanCacheEntry, ResourcePlan::scan_cache, XXH3 hashing, bulk ReadScalarTable). This addresses the cost of the new scan that runs on every FindModule call after the fix. The issue does not request a performance change. The cache is connected to the fix, so it is not shown to be unrelated. The PR objectives list all four groups as intended work. Group (3) carries an unverified hardware risk that the author discloses. It is not a demonstrated unrelated change. </dd> </dl> </details> </dd> </dl> </details> <!-- pre_merge_checks_walkthrough_end --> <!-- tips_start --> Thanks for using [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=KytyPS5/KytyPS5&utm_content=2501)! 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> <br> - [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> <!-- tips_end -->
@ -231,0 +242,4 @@
}
value.dwords[1] = (value.dwords[1] & ~(0x3fffu << 16u)) | (1u << 16u);
value.dwords[2] = static_cast<uint32_t>(bytes);
value.dwords[3] |= 3u << 28u;
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-21 21:17 UTC · original

Major · Data Integrity & Integration · Heavy lift

Preserve the original structured-buffer bounds.

For stride=16, NumRecords=4 and OOB_SELECT=0, a non-indexed store at byte offset 32 must be dropped. RDNA2 checks offset against stride. This rewrite instead creates a 64-byte raw range with OOB_SELECT=3, which admits that store. Preserve the original bounds when normalizing the descriptor. In-bounds stores must remain valid. (amd.com)

**@⁠coderabbitai[bot]** on GitHub · 2026-11-21 21:17 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2501#discussion_r4655052403) <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Data Integrity & Integration** · **Heavy lift** **Preserve the original structured-buffer bounds.** For stride=16, NumRecords=4 and OOB_SELECT=0, a non-indexed store at byte offset 32 must be dropped. RDNA2 checks offset against stride. This rewrite instead creates a 64-byte raw range with OOB_SELECT=3, which admits that store. Preserve the original bounds when normalizing the descriptor. In-bounds stores must remain valid. ([amd.com](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf)) <!-- fingerprinting:phantom:medusa:wombat61 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:a44e43c215fdbcbf5e8e5958 --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -732,0 +747,4 @@
const uint64_t row_limit =
indirect.table_scalar ? MaxIndirectScalarTableRows : MaxIndirectDescriptorProbes;
if (child_count == 0u || (!image_heap && count * child_count > row_limit))
return failed("candidate count", fmt::format("rows={} limit={}", count, row_limit));
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-21 21:17 UTC · original

Minor · Performance & Scalability · Quick win

Replace the linear child search in intern_candidate with a keyed ordinal lookup.

intern_candidate searches all existing children with std::find for each candidate. A cold scan of distinct descriptors therefore costs n(n-1)/2 comparisons. The raised table_scalar row limit allows n up to 262144, which gives 34,359,607,296 comparisons. A content change also misses the scan cache and repeats the full scan.

Add an ordinal map keyed by the same equality used for the root check. Assign ordinals in first-seen order, and keep the existing root-descriptor check and the specializations push for new children. Lookups then become amortized constant time per candidate.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-21 21:17 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2501#discussion_r4655052406) <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Performance & Scalability** · **Quick win** **Replace the linear child search in `intern_candidate` with a keyed ordinal lookup.** `intern_candidate` searches all existing children with `std::find` for each candidate. A cold scan of distinct descriptors therefore costs n(n-1)/2 comparisons. The raised `table_scalar` row limit allows n up to 262144, which gives 34,359,607,296 comparisons. A content change also misses the scan cache and repeats the full scan. Add an ordinal map keyed by the same equality used for the root check. Assign ordinals in first-seen order, and keep the existing root-descriptor check and the `specializations` push for new children. Lookups then become amortized constant time per candidate. <!-- fingerprinting:phantom:medusa:beignet55 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:3368193d14cafecb73825fea --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -740,0 +761,4 @@
if (!image_heap && pointer == nullptr && count > 16u && table_size >= 4u &&
table_size <= (uint64_t {64} << 20u)) {
heap_words.resize(table_size / 4u);
bulk_table = ReadScalarTable(table_base, table_size, 0u, runtime, heap_words);
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-21 21:17 UTC · original

Major · Stability & Availability · Quick win

Do not capture unused table bytes as descriptor dependencies.

With a 4096-byte table and 17 selected 16-byte rows, this read captures the unused tail too. SrtReadCapture records the full span. If a separate sentinel write buffer starts at table_base+1024, RenderExecutor::FindBuffers now exits with "scalar resource reads overlap a shader buffer write". The previous row reads did not overlap that writer. Keep dependency capture limited to the descriptor words, or retain row reads when bulk capture would change alias checks. (raw.githubusercontent.com)

**@⁠coderabbitai[bot]** on GitHub · 2026-11-21 21:17 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2501#discussion_r4655052408) <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Stability & Availability** · **Quick win** **Do not capture unused table bytes as descriptor dependencies.** With a 4096-byte table and 17 selected 16-byte rows, this read captures the unused tail too. `SrtReadCapture` records the full span. If a separate sentinel write buffer starts at table_base+1024, `RenderExecutor::FindBuffers` now exits with `"scalar resource reads overlap a shader buffer write"`. The previous row reads did not overlap that writer. Keep dependency capture limited to the descriptor words, or retain row reads when bulk capture would change alias checks. ([raw.githubusercontent.com](https://raw.githubusercontent.com/KytyPS5/KytyPS5/0c2d9d7e9180c465f0b59d2461b30d74bd056e7c/src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp)) <!-- fingerprinting:phantom:medusa:wombat61 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:db786f965a899ce338caedcb --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

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

Actionable comments posted: 3

Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 39936ffa39 and 0c2d9d7e91.

Files selected for processing: 3

  • src/graphics/shader/recompiler/ir/ShaderIR.h
  • src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp
  • src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp

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

**@⁠coderabbitai[bot]** on GitHub · 2026-11-21 21:17 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2501#pullrequestreview-6008230694) · **reviewed** <!-- coderabbit-ai-generated:v1 --> **Actionable comments posted: 3** <h6> <details> <summary><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/info.svg" width="12" height="12" align="absmiddle" alt=""></picture> Review info</summary> <dl> <dd> <br> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog.svg" width="16" height="16" align="absmiddle" alt=""></picture> Run configuration</summary> <dl> <dd> <br> - **Source mode**: Auto - **Repository**: [KytyPS5/KytyPS5](<https://github.com/KytyPS5/KytyPS5>) - **Branch**: [main](<https://github.com/KytyPS5/KytyPS5/tree/main>) - **File**: [.coderabbit.yaml](<https://github.com/KytyPS5/KytyPS5/blob/39936ffa39237997080f8d169370667ca63d12fa/.coderabbit.yaml>) - **Commit**: [39936ff](<https://github.com/KytyPS5/KytyPS5/commit/39936ffa39237997080f8d169370667ca63d12fa>) - **Layers**: Repository YAML - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `f250f814-6abf-487e-90a8-b605f4026311` </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal.svg" width="16" height="16" align="absmiddle" alt=""></picture> Commits</summary> <dl> <dd> <br> Reviewing files that changed from the base of the PR and between 39936ffa39237997080f8d169370667ca63d12fa and 0c2d9d7e9180c465f0b59d2461b30d74bd056e7c. </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner.svg" width="16" height="16" align="absmiddle" alt=""></picture> Files selected for processing: 3</summary> <dl> <dd> <br> * `src/graphics/shader/recompiler/ir/ShaderIR.h` * `src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp` * `src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp` </dd> </dl> </details> **Included review availability:** This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review. </dd> </dl> </details> </h6> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=8d4d3c65-1421-4595-ad3d-f67652074a79 attempt=88dd5f83-2b6a-443d-82c9-b28cb0bdc222 batch=1/1 -->
Author
Owner

@⁠theantipopau on GitHub · 2026-11-23 01:20 UTC · original

Review: scan cache and GPU-modified range handling

Read against 39936ffa. The scan cache is correct for this shape — I traced the replay path and could not break it — but the invalidation story is weaker than the description implies, one key component is dead, and most of the 41 MB cost is paid by code this PR does not touch, on every dispatch, including the dispatches the cache is supposed to make cheap.

What holds

  • Key completeness. table_base/table_size/first/step/count/read_dwords/dword_count/source_index/resource_index cover every input that changes children. normalize closes over plan-static state only: NormalizeIndirectBuffer reads resource.formatted/read/written/max_byte_extent, and ApplyResourceSpecialization does not rewrite those. affine needs no separate field because a non-affine scan is exactly first=0, step=4.
  • Replay fidelity. Children are already unique by intern_candidate's dedup over [children_begin, end), so replaying them without dedup yields the same ordinals. mapping is a relative slice re-inserted at the new mapping_offset. The no-children case stores a 2-word mapping and then hits resize(mapping_offset) on both paths, so flattened_srt ends the same length either way.
  • count * child_count <= 262144 makes static_cast<uint32_t>(count) safe.
  • Bulk equals per-row. ReadTable zero-fills words.subspan(count), and the bulk branch reproduces that with std::min<size_t>(read_dwords, available).

Four fixes

1. content_hash hashes the CPU backing, not what the GPU sees. ReadShaderGuestMemory is TryReadBufferBacking — no GPU-dirty download. "The table bytes did not change" therefore only means "the CPU copy did not change". Not a new bug (the scan reads the same backing, so cache and scan agree), but the hash cannot invalidate on a GPU write to the table — the exact case the ScanCacheEntry comment claims to cover. Harmless here only because the store targets the children.

2. cache_key.root is always {0,0,0,0}. descriptors[resource_index] = {.dword_count = dword_count} (line 721) zeroes it before the key is built (line 784), so the root contributes nothing and root_dword_count is the constant dword_count already in the key. Capture the root dwords before line 721, or drop both fields and fix the comment — as written, "the root descriptor ... is part of the key" is a false safety signal.

3. MaxIndirectScalarTableRows is not scoped to the new fallback. row_limit keys off indirect.table_scalar, which pre-existing load-path sites also set (ResourceTracking.cpp:3205, 3301, 3306, 3553). Those go from 65,536 rows to 262,144 — 4x more descriptors and specializations on shaders unrelated to this crash. Use a separate flag (store_table_scalar) set only in scalar_table() and gate the bigger budget on it.

4. The OOB_SELECT = 0 rewrite is the only semantic change, and it is narrower than the caveat suggests. For a raw V#, GetSize() == stride * NumRecords, so stride=4/records=97200 and stride=1/bytes=388800 describe the same extent. The rewrite only changes OOB_SELECT 0 -> 3. That is defensible (0 means no bounds check at all) but it does drop accesses past stride * records that hardware would have allowed. Worth a differential dump rather than a code reading.

Minor: cache_eligible requires descriptors.size() == children_begin, so only the first indirect buffer source materialized in a call is ever cached. Fine, but the comment does not say so.

The hit still copies and hashes the whole table

bulk_table = ReadScalarTable(...) and XXH3_64bits(...) both run unconditionally, before the cache lookup. The 0.22 ms hit is 2 MiB of guest-backed copy plus 2 MiB of hashing, every dispatch — all of it spent proving the table is unchanged rather than scanning it.

The bulk read is also sized from the V# size, not the scanned extent. With table_maximum set, count can be far below table_size: the read then covers up to 64 MiB, and if any of it is uncommitted ReadScalarTable fails and bulk_table goes false — silently back to the per-row path and the 26-30 ms this change exists to remove. Clamping to first + (count - 1) * step + read_dwords * 4 fixes both the waste and the cliff.

The 41 MB is a per-dispatch full-range mark, not a write

Every dispatch, RebindBuffers -> NativeStorageBuffer -> ObtainBuffer(is_written = resource.written) once per child, and each one:

  • ForEachUploadRange(is_written=true) -> ChangeState<Gpu, true> over the whole [base, base+41MB): 11 tracker regions, RegionBits(~bits, start, end) + SetRange + changed.None() each. The first mark does the real watcher work; every later dispatch redoes the bit work and the region locks for nothing, because changed is empty and UpdateProtection is skipped.
  • m_gpu_modified_ranges.Add(41 MB).
  • InvalidateMemoryFromGPU(address, 41 MB), which takes the texture-cache lock and walks the images in that range. Seven children means a 287 MB range query over the image table per dispatch, under a global lock, at roughly 500 dispatches/min. That is the part I would expect to matter most, and it is invisible in the FPS attribution.

Second order: because the whole range is GPU-dirty, any guest write anywhere in those 41 MB takes the InvalidateRegion flush path, and any read downloads the full range.

Concrete fixes, cheapest first

  1. Skip the redundant re-mark. In ForEachUploadRange, if IsRegionGpuModified(vaddr, size) is already true, skip the Iterate GPU-mark pass. Semantics are identical (changed is empty) and it removes the per-dispatch page walk and region locks for every repeatedly-bound written buffer in the emulator, not just this shader.
  2. Gate the texture invalidation on the state change. Re-invalidating a range that is already GPU-dirty is a no-op that costs a global lock plus a 41 MB scan. Hoist it behind the same "just became dirty" test, or drop it — BufferCache::MappedMemoryWrite already invalidates on the exact written range.
  3. Clamp the bulk read to the scanned extent.
  4. Swap the hash for a write epoch if the hit should be O(1) and sound for GPU writes: add a monotonic epoch to RegionManager, bumped on ChangeState<Cpu, true> and on the GPU-dirty mark, and key the cache on the epoch of the region(s) covering the table instead of content_hash. A 2 MiB table is one region, so validity becomes an O(1) compare — no 2 MiB copy, no hash, no collision risk, and it actually invalidates when the GPU writes the table. That is roughly 20 lines on top of this change.

If the epoch is too invasive here, 1-3 are small and local and recover most of the cost.

One more: scan_cache is mutable and written through const ResourcePlan&. The class comment says the owning renderer serializes access, so it is safe today, but it is now persisted state rather than per-call scratch like material_keys/selector_keys. Worth a comment, or taking the plan by non-const reference so the mutation is visible at the call site.

**@⁠theantipopau** on GitHub · 2026-11-23 01:20 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2501#issuecomment-7089067777) ## Review: scan cache and GPU-modified range handling Read against `39936ffa`. The scan cache is correct for this shape — I traced the replay path and could not break it — but the invalidation story is weaker than the description implies, one key component is dead, and most of the 41 MB cost is paid by code this PR does not touch, on every dispatch, including the dispatches the cache is supposed to make cheap. ### What holds - **Key completeness.** `table_base/table_size/first/step/count/read_dwords/dword_count/source_index/resource_index` cover every input that changes `children`. `normalize` closes over plan-static state only: `NormalizeIndirectBuffer` reads `resource.formatted/read/written/max_byte_extent`, and `ApplyResourceSpecialization` does not rewrite those. `affine` needs no separate field because a non-affine scan is exactly `first=0, step=4`. - **Replay fidelity.** Children are already unique by `intern_candidate`'s dedup over `[children_begin, end)`, so replaying them without dedup yields the same ordinals. `mapping` is a relative slice re-inserted at the new `mapping_offset`. The no-children case stores a 2-word mapping and then hits `resize(mapping_offset)` on both paths, so `flattened_srt` ends the same length either way. - **`count * child_count <= 262144`** makes `static_cast<uint32_t>(count)` safe. - **Bulk equals per-row.** `ReadTable` zero-fills `words.subspan(count)`, and the bulk branch reproduces that with `std::min<size_t>(read_dwords, available)`. ### Four fixes **1. `content_hash` hashes the CPU backing, not what the GPU sees.** `ReadShaderGuestMemory` is `TryReadBufferBacking` — no GPU-dirty download. "The table bytes did not change" therefore only means "the CPU copy did not change". Not a new bug (the scan reads the same backing, so cache and scan agree), but the hash cannot invalidate on a GPU write to the table — the exact case the `ScanCacheEntry` comment claims to cover. Harmless here only because the store targets the children. **2. `cache_key.root` is always `{0,0,0,0}`.** `descriptors[resource_index] = {.dword_count = dword_count}` (line 721) zeroes it before the key is built (line 784), so the root contributes nothing and `root_dword_count` is the constant `dword_count` already in the key. Capture the root dwords before line 721, or drop both fields and fix the comment — as written, "the root descriptor ... is part of the key" is a false safety signal. **3. `MaxIndirectScalarTableRows` is not scoped to the new fallback.** `row_limit` keys off `indirect.table_scalar`, which pre-existing load-path sites also set (`ResourceTracking.cpp:3205, 3301, 3306, 3553`). Those go from 65,536 rows to 262,144 — 4x more descriptors and specializations on shaders unrelated to this crash. Use a separate flag (`store_table_scalar`) set only in `scalar_table()` and gate the bigger budget on it. **4. The `OOB_SELECT = 0` rewrite is the only semantic change, and it is narrower than the caveat suggests.** For a raw V#, `GetSize() == stride * NumRecords`, so `stride=4/records=97200` and `stride=1/bytes=388800` describe the same extent. The rewrite only changes OOB_SELECT 0 -> 3. That is defensible (0 means no bounds check at all) but it does *drop* accesses past `stride * records` that hardware would have allowed. Worth a differential dump rather than a code reading. Minor: `cache_eligible` requires `descriptors.size() == children_begin`, so only the first indirect buffer source materialized in a call is ever cached. Fine, but the comment does not say so. ### The hit still copies and hashes the whole table `bulk_table = ReadScalarTable(...)` and `XXH3_64bits(...)` both run unconditionally, before the cache lookup. The 0.22 ms hit is 2 MiB of guest-backed copy plus 2 MiB of hashing, every dispatch — all of it spent proving the table is unchanged rather than scanning it. The bulk read is also sized from the **V# size**, not the scanned extent. With `table_maximum` set, `count` can be far below `table_size`: the read then covers up to 64 MiB, and if any of it is uncommitted `ReadScalarTable` fails and `bulk_table` goes false — silently back to the per-row path and the 26-30 ms this change exists to remove. Clamping to `first + (count - 1) * step + read_dwords * 4` fixes both the waste and the cliff. ### The 41 MB is a per-dispatch full-range mark, not a write Every dispatch, `RebindBuffers` -> `NativeStorageBuffer` -> `ObtainBuffer(is_written = resource.written)` once per child, and each one: - `ForEachUploadRange(is_written=true)` -> `ChangeState<Gpu, true>` over the whole `[base, base+41MB)`: 11 tracker regions, `RegionBits(~bits, start, end)` + `SetRange` + `changed.None()` each. The first mark does the real watcher work; every later dispatch redoes the bit work and the region locks for nothing, because `changed` is empty and `UpdateProtection` is skipped. - `m_gpu_modified_ranges.Add(41 MB)`. - `InvalidateMemoryFromGPU(address, 41 MB)`, which takes the texture-cache lock and walks the images in that range. Seven children means a **287 MB range query over the image table per dispatch**, under a global lock, at roughly 500 dispatches/min. That is the part I would expect to matter most, and it is invisible in the FPS attribution. Second order: because the whole range is GPU-dirty, any guest write anywhere in those 41 MB takes the `InvalidateRegion` flush path, and any read downloads the full range. ### Concrete fixes, cheapest first 1. **Skip the redundant re-mark.** In `ForEachUploadRange`, if `IsRegionGpuModified(vaddr, size)` is already true, skip the `Iterate` GPU-mark pass. Semantics are identical (`changed` is empty) and it removes the per-dispatch page walk and region locks for every repeatedly-bound written buffer in the emulator, not just this shader. 2. **Gate the texture invalidation on the state change.** Re-invalidating a range that is already GPU-dirty is a no-op that costs a global lock plus a 41 MB scan. Hoist it behind the same "just became dirty" test, or drop it — `BufferCache::MappedMemoryWrite` already invalidates on the exact written range. 3. **Clamp the bulk read** to the scanned extent. 4. **Swap the hash for a write epoch** if the hit should be O(1) *and* sound for GPU writes: add a monotonic `epoch` to `RegionManager`, bumped on `ChangeState<Cpu, true>` and on the GPU-dirty mark, and key the cache on the epoch of the region(s) covering the table instead of `content_hash`. A 2 MiB table is one region, so validity becomes an O(1) compare — no 2 MiB copy, no hash, no collision risk, and it actually invalidates when the GPU writes the table. That is roughly 20 lines on top of this change. If the epoch is too invasive here, 1-3 are small and local and recover most of the cost. One more: `scan_cache` is `mutable` and written through `const ResourcePlan&`. The class comment says the owning renderer serializes access, so it is safe today, but it is now persisted state rather than per-call scratch like `material_keys`/`selector_keys`. Worth a comment, or taking the plan by non-const reference so the mutation is visible at the call site.
This pull request has changes conflicting with the target branch.
  • src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.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/2501/head:github-bot/gh-2501'
git switch 'github-bot/gh-2501'

Merge

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