shader: cheaper SRT walks for flattened reads and block conditions #1322

Closed
github-bot wants to merge 5 commits from gh-pr/1322/head into gh-pr/1322/base
Owner

@⁠NeySlim on GitHub · 2026-10-09 18:09 UTC · original
NeySlim:perf/srt-flat-reads → main · +1310 −196 · 6 files · 5 commits · closed without merging

Stacked on #1287: it changes the compiled-node SRT walker added there. The branch holds the commits of #1287, then the two new commits.

Problem

Every draw and dispatch refreshes the flattened SRT of its shaders through the SRT walker. In God of War Ragnarök (PPSA08332, 05.005) that is 3,600 to 4,700 stage walks per frame depending on the scene, and a walk reads about 74 SRT DWORDs. In the six large plans I dumped from the game, every flattened SRT slot is such a read: a LoadAddressU32 at a constant offset below a GetAddressResource whose address DWORDs are user data; the constant-buffer reads (ReadConstBuffer) have the same shape with four handle DWORDs.

Each of these reads goes through EvaluateRef, EvaluateNodeRef, the kind dispatch of EvaluateNode, then EvaluateRawRead, which fetches the handle DWORDs through a capturing lambda. On a synthetic plan shaped like the game's (96 SRT reads, a dozen descriptors), a walk executes about 41,700 instructions.

Block conditions go through Evaluate(Value), which resolves the value, looks up and checks its node and refreshes the walker's pointers on every walk; the walker refreshes its pointers again after each block. Large plans in this game have up to 264 blocks.

Change

  • shader: read flattened SRT DWORDs without the walker dispatch: when a plan's SRT reads are compiled, a scalar-address or constant-buffer DWORD read with a constant offset operand records its handle DWORDs and its aligned offset (WalkerRead, one per SRT read root). RefreshFlatBuffer evaluates such a root directly with the steps EvaluateNodeRef and EvaluateRawRead take for that node shape: the same memo entry and in-progress mark, the handle DWORDs evaluated in the same order, the same address and bounds checks (a helper now shared with EvaluateRawRead), the same reader. A root of another shape, a walker with an active EXEC mask, or a clean read reaching a walker that delegates it keeps the generic path.
  • shader: compile SRT block conditions once per plan: block conditions become walker roots like the SRT reads and the descriptor DWORDs (walker_conditions): compiled on first use, compared with the plan's condition on each walk so that a replaced condition is followed, and dropped with the other compiled nodes. Compiling a root refreshes the walker's pointers, so the refresh after each block is no longer needed.

The walker's results, reads and failures do not change. On the synthetic plan above, a walk now executes about 32,000 instructions (24,300 instead of 35,600 when the plan does not capture its reads).

Test

  • TestFlatReadsKeepReadSemantics (resource_materialization_tests): scalar-address reads (unaligned table pointer, unaligned offset operand, negative immediate, a handle whose address DWORDs are themselves SRT reads) and a constant-buffer read (unaligned base and offset operand, records and fourth DWORD read from memory through the handle only). A recording reader checks the flattened values, the addresses read and their order, that the reads were prepared for the direct path, a later walk with changed memory, failed reads (an SRT DWORD, the buffer's fourth DWORD) that stop the walk, the bounds of a buffer without a stride (4 and 11 records rejected, 12 accepted), and an address below zero rejected before reading.
  • TestCleanFlatReadsUseTheStrictReader: in a plan that captures its reads (it branches on a value read from memory), the flat reads feeding a written buffer are clean. They go through the strict reader once each (the branch reuses their memo), the other flat read through the ordinary reader, and all three are captured.
  • TestNegativeBufferImmediateIsNotRead: a constant-buffer read below its base is not prepared and is not read, even with bounds that would accept it.
  • TestRecompiledWalkerFollowsBlockConditions: after a replaced SRT read recompiles the plan's nodes, the block condition is compiled again and follows the memory.
  • TestReplacedBlockConditionIsFollowed (resource_tracking_tests): a replaced block condition, then the original one, are followed by the next walks.

Without their checks on walker_reads, these cases also pass on #1287 alone. Mutation check: each of these changes fails a case: an unaligned base (scalar or buffer), a dropped offset operand (scalar or buffer), either half of the buffer bounds check, an ignored stride, a buffer read taken as a scalar one, a read that bypasses the reader, the memo entry left unset, the records and fourth DWORD evaluated in the other order or the fourth DWORD skipped, the reads not prepared, a negative buffer immediate prepared, a condition root reused without comparing it with the plan's condition or kept when the nodes are recompiled. A direct path that skips the 48-bit address check of buffer reads fails TestBufferReadPastAddressSpaceFails from #1287.

Validation

Linux, Ryzen AI Max+ 395, Radeon 8060S, Mesa RADV 26.2.3.

In God of War Ragnarök from a new game, on main with my open PRs (#1287 among them):

  • Each materialization run twice on the same inputs, with and without the change, in random order, and the two results compared: 42 million walks in a 13-minute session, no difference. The first run of a walk is the normal case. It took 6.45 µs instead of 6.81 µs on average in the cutscene (-5 %) and 6.11 µs instead of 6.61 µs in gameplay (-8 %): 1.4 ± 0.5 and 1.9 ± 0.2 ms less GPU command thread time per frame (3,650 and 3,830 walks per frame). The second run, with the walk's data in cache, takes 480 to 520 ns less (-19 %). Most of a walk's time is cache misses on the walker's own data, which this change does not remove.
  • Alternating the change every 5 s within a session, without the double runs: frame time and materialization time per frame stay within the noise (cutscene: frame 53.2 -> 53.0 ms ± 0.7, materialization 27.8 -> 27.4 ms ± 0.5; gameplay ± 3.5 ms).

On this branch:

  • resource_materialization_tests, resource_tracking_tests, scalar_provenance_tests and shader_cfg_tests pass.
  • shader_recompiler_compute_tests, one case per process: same results as main (602 of 612 cases pass; the same 10 fail on both with this RADV setup).
  • With a local check (not in this PR) that redoes every materialization without the direct path, on the reads of the first one, and compares the reads, the results and the captured ranges: no difference in these tests and the GPU suite (50,000 materializations, 10,000 reads through the direct path).

Not tested on Windows or macOS. The change is platform-independent C++. The two [[gnu::noinline]] hints, already used elsewhere in the tree, keep the slow paths out of line; the small result struct comes back in registers on System V x86-64 and through memory on Windows x64.

AI use

I used Claude Code (AI agent) to measure the walker, write the change and the tests, and run the measurements and tests above on my machine. I reviewed the diff and the results before opening this PR.

**@⁠NeySlim** on GitHub · 2026-10-09 18:09 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1322) `NeySlim:perf/srt-flat-reads` → `main` · +1310 −196 · 6 files · 5 commits · closed without merging Stacked on #1287: it changes the compiled-node SRT walker added there. The branch holds the commits of #1287, then the two new commits. ## Problem Every draw and dispatch refreshes the flattened SRT of its shaders through the SRT walker. In God of War Ragnarök (PPSA08332, 05.005) that is 3,600 to 4,700 stage walks per frame depending on the scene, and a walk reads about 74 SRT DWORDs. In the six large plans I dumped from the game, every flattened SRT slot is such a read: a `LoadAddressU32` at a constant offset below a `GetAddressResource` whose address DWORDs are user data; the constant-buffer reads (`ReadConstBuffer`) have the same shape with four handle DWORDs. Each of these reads goes through `EvaluateRef`, `EvaluateNodeRef`, the kind dispatch of `EvaluateNode`, then `EvaluateRawRead`, which fetches the handle DWORDs through a capturing lambda. On a synthetic plan shaped like the game's (96 SRT reads, a dozen descriptors), a walk executes about 41,700 instructions. Block conditions go through `Evaluate(Value)`, which resolves the value, looks up and checks its node and refreshes the walker's pointers on every walk; the walker refreshes its pointers again after each block. Large plans in this game have up to 264 blocks. ## Change - `shader: read flattened SRT DWORDs without the walker dispatch`: when a plan's SRT reads are compiled, a scalar-address or constant-buffer DWORD read with a constant offset operand records its handle DWORDs and its aligned offset (`WalkerRead`, one per SRT read root). `RefreshFlatBuffer` evaluates such a root directly with the steps `EvaluateNodeRef` and `EvaluateRawRead` take for that node shape: the same memo entry and in-progress mark, the handle DWORDs evaluated in the same order, the same address and bounds checks (a helper now shared with `EvaluateRawRead`), the same reader. A root of another shape, a walker with an active EXEC mask, or a clean read reaching a walker that delegates it keeps the generic path. - `shader: compile SRT block conditions once per plan`: block conditions become walker roots like the SRT reads and the descriptor DWORDs (`walker_conditions`): compiled on first use, compared with the plan's condition on each walk so that a replaced condition is followed, and dropped with the other compiled nodes. Compiling a root refreshes the walker's pointers, so the refresh after each block is no longer needed. The walker's results, reads and failures do not change. On the synthetic plan above, a walk now executes about 32,000 instructions (24,300 instead of 35,600 when the plan does not capture its reads). ## Test - `TestFlatReadsKeepReadSemantics` (`resource_materialization_tests`): scalar-address reads (unaligned table pointer, unaligned offset operand, negative immediate, a handle whose address DWORDs are themselves SRT reads) and a constant-buffer read (unaligned base and offset operand, records and fourth DWORD read from memory through the handle only). A recording reader checks the flattened values, the addresses read and their order, that the reads were prepared for the direct path, a later walk with changed memory, failed reads (an SRT DWORD, the buffer's fourth DWORD) that stop the walk, the bounds of a buffer without a stride (4 and 11 records rejected, 12 accepted), and an address below zero rejected before reading. - `TestCleanFlatReadsUseTheStrictReader`: in a plan that captures its reads (it branches on a value read from memory), the flat reads feeding a written buffer are clean. They go through the strict reader once each (the branch reuses their memo), the other flat read through the ordinary reader, and all three are captured. - `TestNegativeBufferImmediateIsNotRead`: a constant-buffer read below its base is not prepared and is not read, even with bounds that would accept it. - `TestRecompiledWalkerFollowsBlockConditions`: after a replaced SRT read recompiles the plan's nodes, the block condition is compiled again and follows the memory. - `TestReplacedBlockConditionIsFollowed` (`resource_tracking_tests`): a replaced block condition, then the original one, are followed by the next walks. Without their checks on `walker_reads`, these cases also pass on #1287 alone. Mutation check: each of these changes fails a case: an unaligned base (scalar or buffer), a dropped offset operand (scalar or buffer), either half of the buffer bounds check, an ignored stride, a buffer read taken as a scalar one, a read that bypasses the reader, the memo entry left unset, the records and fourth DWORD evaluated in the other order or the fourth DWORD skipped, the reads not prepared, a negative buffer immediate prepared, a condition root reused without comparing it with the plan's condition or kept when the nodes are recompiled. A direct path that skips the 48-bit address check of buffer reads fails `TestBufferReadPastAddressSpaceFails` from #1287. ## Validation Linux, Ryzen AI Max+ 395, Radeon 8060S, Mesa RADV 26.2.3. In God of War Ragnarök from a new game, on main with my open PRs (#1287 among them): - Each materialization run twice on the same inputs, with and without the change, in random order, and the two results compared: 42 million walks in a 13-minute session, no difference. The first run of a walk is the normal case. It took 6.45 µs instead of 6.81 µs on average in the cutscene (-5 %) and 6.11 µs instead of 6.61 µs in gameplay (-8 %): 1.4 ± 0.5 and 1.9 ± 0.2 ms less GPU command thread time per frame (3,650 and 3,830 walks per frame). The second run, with the walk's data in cache, takes 480 to 520 ns less (-19 %). Most of a walk's time is cache misses on the walker's own data, which this change does not remove. - Alternating the change every 5 s within a session, without the double runs: frame time and materialization time per frame stay within the noise (cutscene: frame 53.2 -> 53.0 ms ± 0.7, materialization 27.8 -> 27.4 ms ± 0.5; gameplay ± 3.5 ms). On this branch: - `resource_materialization_tests`, `resource_tracking_tests`, `scalar_provenance_tests` and `shader_cfg_tests` pass. - `shader_recompiler_compute_tests`, one case per process: same results as main (602 of 612 cases pass; the same 10 fail on both with this RADV setup). - With a local check (not in this PR) that redoes every materialization without the direct path, on the reads of the first one, and compares the reads, the results and the captured ranges: no difference in these tests and the GPU suite (50,000 materializations, 10,000 reads through the direct path). Not tested on Windows or macOS. The change is platform-independent C++. The two `[[gnu::noinline]]` hints, already used elsewhere in the tree, keep the slow paths out of line; the small result struct comes back in registers on System V x86-64 and through memory on Windows x64. ## AI use I used Claude Code (AI agent) to measure the walker, write the change and the tests, and run the measurements and tests above on my machine. I reviewed the diff and the results before opening this PR.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:53:06 +00:00
github-bot closed this pull request 2026-11-26 09:53:06 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-09 18:14 UTC · original · edited 2026-10-09 18:37 UTC

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: a89766ab-c90e-47b7-ab8e-f1d5deff2fb8

📥 Commits

Reviewing files that changed from the base of the PR and between 3bc5536248c0012a5852ced618a42464ece1cc36 and ae744a5c15.


📒 Files selected for processing (2)
  • src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp
  • tests/ResourceMaterializationTests.cpp

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



📝 Walkthrough

Walkthrough

Resource plans now store compiled walker data, and SrtWalker evaluates roots through compiled references with memoization. The walker refreshes compiled state when SRT roots change and validates raw-read addresses and buffer bounds. New tests cover walker updates, lazy evaluation, control-flow conditions, and memory-read behavior.

Suggested reviewers: nmzik


Priority: ➖ Normal

Change: Refactor

Merge Risk: ⚪ Minimal · up to ae744

The previously identified out-of-range read is guarded, and no remaining issue identified here prevents merging after normal checks.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 44.62% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 65 functions across 6 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Title check Passed The title clearly and concisely describes the main change: reducing the cost of SRT walks for flattened reads and block conditions.
Description check Passed The description is directly related to the changeset. It explains the optimization, preserved behavior, tests, performance measurements, and validation limits.


  • 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-09 18:14 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1322#issuecomment-6086652417) · edited 2026-10-09 18:37 UTC <!-- This is an auto-generated comment: summarize by coderabbit.ai --> <!-- review_stack_entry_start --> <a href="https://app.coderabbit.ai/change-stack/KytyPS5/KytyPS5/pull/1322?scope=ghh_OusAJGA4HG8ljoOV0wJvVx8NmnZIjc2DdjmxOu0xZWA&amp;cs_source=review_comment"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui-dark.svg?v=2" alt="Review in Change Stack →" width="220" height="32"></a> <!-- review_stack_entry_end --> <!-- recent_review_start --> No actionable comments were generated in the recent review. 🎉 <details> <summary>ℹ️ Recent review info</summary> <details> <summary>⚙️ Run configuration</summary> - **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `a89766ab-c90e-47b7-ab8e-f1d5deff2fb8` <hr> </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 3bc5536248c0012a5852ced618a42464ece1cc36 and ae744a5c15a459d9d11277e9413e400edb950608. <hr> </details> <details> <summary>📒 Files selected for processing (2)</summary> * `src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp` * `tests/ResourceMaterializationTests.cpp` <hr> </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 2 remain after this review. <hr> </details> --- <!-- recent_review_end --> <!-- walkthrough_start --> <details> <summary>📝 Walkthrough</summary> ## Walkthrough Resource plans now store compiled walker data, and `SrtWalker` evaluates roots through compiled references with memoization. The walker refreshes compiled state when SRT roots change and validates raw-read addresses and buffer bounds. New tests cover walker updates, lazy evaluation, control-flow conditions, and memory-read behavior. **Suggested reviewers:** `nmzik` <hr> </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ➖ Normal <!-- change_assessment_commit:"ae744a5c15a459d9d11277e9413e400edb950608" --> **Change:** Refactor <!-- change_assessment_end --> <!-- final_review_risk_start --> **Merge Risk:** **⚪ Minimal** · up to `ae744` <!-- final_review_risk_coverage:{"sourceCommitId":"ae744a5c15a459d9d11277e9413e400edb950608","coveredCommitId":"ae744a5c15a459d9d11277e9413e400edb950608","kind":"reviewed"} --> The previously identified out-of-range read is guarded, and no remaining issue identified here prevents merging after normal checks. <!-- final_review_risk_end --> <!-- pre_merge_checks_walkthrough_start --> <details> <summary>🚥 Pre-merge checks | ✅ 4 | ❌ 1</summary> ### ❌ Failed checks (1 warning) | Check name | Status | Explanation | Resolution | | :---------------- | :----------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :--------------------------------------------------------------------------------- | | Docstring Coverage | ![Warning](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-warning.svg) | Docstring coverage is 44.62% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 65 functions across 6 files. | Write docstrings for the functions missing them to satisfy the coverage threshold. | <details> <summary>✅ Passed checks (4 passed)</summary> | Check name | Status | Explanation | | :------------------------ | :--------------------------------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Linked Issues check | ![Passed](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. | | Title check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The title clearly and concisely describes the main change: reducing the cost of SRT walks for flattened reads and block conditions. | | Description check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The description is directly related to the changeset. It explains the optimization, preserved behavior, tests, performance measurements, and validation limits. | <hr> </details> <hr> </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=1322)! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. <details> <summary>❤️ Share</summary> - [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai) - [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai) - [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai) - [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code) <hr> </details> <sub>Comment `@coderabbitai help` to get the list of available commands.</sub> <!-- tips_end -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-09 18:14 UTC · original · edited 2026-10-09 18:37 UTC
On src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp line 117 (outdated):

@@ -71,6 +71,52 @@ bool AddSignedAddress(uint64_t base, int64_t offset, uint64_t& result) {
 	return true;
 }
 
+// DWORD-aligned base address of a read handle's address DWORDs.
+uint64_t ReadBase(uint64_t low, uint64_t high) {
+	return ((high << 32u) | static_cast<uint32_t>(low)) & AddressMask & ~uint64_t {3};
+}
+
+// Byte offset of a scalar-address DWORD read: aligned immediate plus aligned offset operand.
+int64_t ScalarReadOffset(uint32_t immediate, uint64_t offset) {
+	return (static_cast<int64_t>(static_cast<int32_t>(immediate)) & ~int64_t {3}) +
+	       static_cast<int64_t>(static_cast<uint32_t>(offset) & ~3u);
+}
+
+// Byte offset of a constant-buffer DWORD read, for a non-negative immediate.
+uint64_t BufferReadOffset(uint32_t immediate, uint64_t offset) {
+	return (uint64_t {immediate} & ~uint64_t {3}) + (static_cast<uint32_t>(offset) & ~3u);
+}
+
+// A DWORD at byte_offset lies within the buffer: stride (in high) times records, or records
+// bytes without a stride.
+bool BufferDwordInBounds(uint64_t byte_offset, uint64_t high, uint64_t records) {
+	const auto stride = (static_cast<uint32_t>(high) >> 16u) & 0x3fffu;
+	const auto size = stride == 0u ? static_cast<uint64_t>(static_cast<uint32_t>(records))
+	                               : static_cast<uint64_t>(stride) * static_cast<uint32_t>(records);
+	return byte_offset <= size && size - byte_offset >= sizeof(uint32_t);
+}
+
+// Byte offset of a scalar-address or constant-buffer DWORD read.
+int64_t RawReadOffset(bool buffer, uint32_t immediate, uint64_t offset) {
+	return buffer ? static_cast<int64_t>(BufferReadOffset(immediate, offset))
+	              : ScalarReadOffset(immediate, offset);
+}
+
+// Address of a raw DWORD read: within the buffer's records, or a scalar address that does not
+// leave the address space.
+bool RawReadAddress(bool buffer, int64_t offset, uint64_t low, uint64_t high, uint64_t records,
+                    uint64_t& address) {
+	if (!buffer) {
+		return AddSignedAddress(ReadBase(low, high), offset, address);
+	}
+	const auto byte_offset = static_cast<uint64_t>(offset);
+	if (!BufferDwordInBounds(byte_offset, high, records)) {
+		return false;
+	}
+	address = ReadBase(low, high) + byte_offset;
+	return true;

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Reject buffer DWORD addresses that leave the 48-bit address space.

For scalar reads, AddSignedAddress rejects results above AddressMask. For buffer reads, the code adds byte_offset to ReadBase(low, high) without the same check. BufferDwordInBounds allows byte_offset up to about 0x3fff * 0xffffffff, which is about 2^46. A guest descriptor with a base near 2^48 therefore produces an address above AddressMask.

ReadWord then passes that address to read_memory. If read_memory is null, it copies directly from the unchecked host address with memcpy. ReadScalarTable in ResourceMaterialization.cpp already rejects offset > AddressMask - base. Both EvaluateRawRead and ComputeFastRead call RawReadAddress, so one check fixes both paths.

🛡️ Proposed fix
--- "a/src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp"
+++ "b/src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp"
@@ -109,12 +109,11 @@
 	if (!buffer) {
 		return AddSignedAddress(ReadBase(low, high), offset, address);
 	}
 	const auto byte_offset = static_cast<uint64_t>(offset);
 	if (!BufferDwordInBounds(byte_offset, high, records)) {
 		return false;
 	}
-	address = ReadBase(low, high) + byte_offset;
-	return true;
+	return AddSignedAddress(ReadBase(low, high), offset, address);
 }
 
 bool IsRawRead(const ResourcePlan& values, const Inst& inst) {
📝 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.

	const auto byte_offset = static_cast<uint64_t>(offset);
	if (!BufferDwordInBounds(byte_offset, high, records)) {
		return false;
	}
	return AddSignedAddress(ReadBase(low, high), offset, address);

✅ Confirmed as addressed by @⁠NeySlim

**@⁠coderabbitai[bot]** on GitHub · 2026-10-09 18:14 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1322#discussion_r4233208609) · edited 2026-10-09 18:37 UTC On `src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp` line 117 (outdated): ```diff @@ -71,6 +71,52 @@ bool AddSignedAddress(uint64_t base, int64_t offset, uint64_t& result) { return true; } +// DWORD-aligned base address of a read handle's address DWORDs. +uint64_t ReadBase(uint64_t low, uint64_t high) { + return ((high << 32u) | static_cast<uint32_t>(low)) & AddressMask & ~uint64_t {3}; +} + +// Byte offset of a scalar-address DWORD read: aligned immediate plus aligned offset operand. +int64_t ScalarReadOffset(uint32_t immediate, uint64_t offset) { + return (static_cast<int64_t>(static_cast<int32_t>(immediate)) & ~int64_t {3}) + + static_cast<int64_t>(static_cast<uint32_t>(offset) & ~3u); +} + +// Byte offset of a constant-buffer DWORD read, for a non-negative immediate. +uint64_t BufferReadOffset(uint32_t immediate, uint64_t offset) { + return (uint64_t {immediate} & ~uint64_t {3}) + (static_cast<uint32_t>(offset) & ~3u); +} + +// A DWORD at byte_offset lies within the buffer: stride (in high) times records, or records +// bytes without a stride. +bool BufferDwordInBounds(uint64_t byte_offset, uint64_t high, uint64_t records) { + const auto stride = (static_cast<uint32_t>(high) >> 16u) & 0x3fffu; + const auto size = stride == 0u ? static_cast<uint64_t>(static_cast<uint32_t>(records)) + : static_cast<uint64_t>(stride) * static_cast<uint32_t>(records); + return byte_offset <= size && size - byte_offset >= sizeof(uint32_t); +} + +// Byte offset of a scalar-address or constant-buffer DWORD read. +int64_t RawReadOffset(bool buffer, uint32_t immediate, uint64_t offset) { + return buffer ? static_cast<int64_t>(BufferReadOffset(immediate, offset)) + : ScalarReadOffset(immediate, offset); +} + +// Address of a raw DWORD read: within the buffer's records, or a scalar address that does not +// leave the address space. +bool RawReadAddress(bool buffer, int64_t offset, uint64_t low, uint64_t high, uint64_t records, + uint64_t& address) { + if (!buffer) { + return AddSignedAddress(ReadBase(low, high), offset, address); + } + const auto byte_offset = static_cast<uint64_t>(offset); + if (!BufferDwordInBounds(byte_offset, high, records)) { + return false; + } + address = ReadBase(low, high) + byte_offset; + return true; ``` **🩺 Stability & Availability** | **🟡 Minor** | **⚡ Quick win** **Reject buffer DWORD addresses that leave the 48-bit address space.** For scalar reads, `AddSignedAddress` rejects results above `AddressMask`. For buffer reads, the code adds `byte_offset` to `ReadBase(low, high)` without the same check. `BufferDwordInBounds` allows `byte_offset` up to about `0x3fff * 0xffffffff`, which is about 2^46. A guest descriptor with a base near 2^48 therefore produces an address above `AddressMask`. `ReadWord` then passes that address to `read_memory`. If `read_memory` is null, it copies directly from the unchecked host address with `memcpy`. `ReadScalarTable` in `ResourceMaterialization.cpp` already rejects `offset > AddressMask - base`. Both `EvaluateRawRead` and `ComputeFastRead` call `RawReadAddress`, so one check fixes both paths. <details> <summary>🛡️ Proposed fix</summary> ```diff --- "a/src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp" +++ "b/src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp" @@ -109,12 +109,11 @@ if (!buffer) { return AddSignedAddress(ReadBase(low, high), offset, address); } const auto byte_offset = static_cast<uint64_t>(offset); if (!BufferDwordInBounds(byte_offset, high, records)) { return false; } - address = ReadBase(low, high) + byte_offset; - return true; + return AddSignedAddress(ReadBase(low, high), offset, address); } bool IsRawRead(const ResourcePlan& values, const Inst& inst) { ``` </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 const auto byte_offset = static_cast<uint64_t>(offset); if (!BufferDwordInBounds(byte_offset, high, records)) { return false; } return AddSignedAddress(ReadBase(low, high), offset, address); ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:cf9bb6ea5ebf662fb37123cd --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Confirmed as addressed by @⁠NeySlim <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-09 18:14 UTC · original · reviewed

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: f37752a7-61e7-481f-8de4-2fbc1cd23526
📥 Commits

Reviewing files that changed from the base of the PR and between c1926f915d and 3bc5536248c0012a5852ced618a42464ece1cc36.

📒 Files selected for processing (6)
  • src/graphics/shader/recompiler/ir/ShaderIR.h
  • src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp
  • src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp
  • src/graphics/shader/recompiler/ir/passes/SrtWalker.h
  • tests/ResourceMaterializationTests.cpp
  • tests/ResourceTrackingTests.cpp

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

**@⁠coderabbitai[bot]** on GitHub · 2026-10-09 18:14 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1322#pullrequestreview-5473766631) · **reviewed** **Actionable comments posted: 1** --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> - **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `f37752a7-61e7-481f-8de4-2fbc1cd23526` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between c1926f915d2a3f743e1dd482a3b7ff09d750bca6 and 3bc5536248c0012a5852ced618a42464ece1cc36. </details> <details> <summary>📒 Files selected for processing (6)</summary> * `src/graphics/shader/recompiler/ir/ShaderIR.h` * `src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp` * `src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp` * `src/graphics/shader/recompiler/ir/passes/SrtWalker.h` * `tests/ResourceMaterializationTests.cpp` * `tests/ResourceTrackingTests.cpp` </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 6 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=c58fd059-124a-42cb-9e02-d60de967503e attempt=017128a8-e8ed-46d2-84f3-82798e594eb4 batch=1/1 -->
Author
Owner

@⁠NeySlim on GitHub · 2026-10-09 18:33 UTC · original
On src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp line 117 (outdated):

@@ -71,6 +71,52 @@ bool AddSignedAddress(uint64_t base, int64_t offset, uint64_t& result) {
 	return true;
 }
 
+// DWORD-aligned base address of a read handle's address DWORDs.
+uint64_t ReadBase(uint64_t low, uint64_t high) {
+	return ((high << 32u) | static_cast<uint32_t>(low)) & AddressMask & ~uint64_t {3};
+}
+
+// Byte offset of a scalar-address DWORD read: aligned immediate plus aligned offset operand.
+int64_t ScalarReadOffset(uint32_t immediate, uint64_t offset) {
+	return (static_cast<int64_t>(static_cast<int32_t>(immediate)) & ~int64_t {3}) +
+	       static_cast<int64_t>(static_cast<uint32_t>(offset) & ~3u);
+}
+
+// Byte offset of a constant-buffer DWORD read, for a non-negative immediate.
+uint64_t BufferReadOffset(uint32_t immediate, uint64_t offset) {
+	return (uint64_t {immediate} & ~uint64_t {3}) + (static_cast<uint32_t>(offset) & ~3u);
+}
+
+// A DWORD at byte_offset lies within the buffer: stride (in high) times records, or records
+// bytes without a stride.
+bool BufferDwordInBounds(uint64_t byte_offset, uint64_t high, uint64_t records) {
+	const auto stride = (static_cast<uint32_t>(high) >> 16u) & 0x3fffu;
+	const auto size = stride == 0u ? static_cast<uint64_t>(static_cast<uint32_t>(records))
+	                               : static_cast<uint64_t>(stride) * static_cast<uint32_t>(records);
+	return byte_offset <= size && size - byte_offset >= sizeof(uint32_t);
+}
+
+// Byte offset of a scalar-address or constant-buffer DWORD read.
+int64_t RawReadOffset(bool buffer, uint32_t immediate, uint64_t offset) {
+	return buffer ? static_cast<int64_t>(BufferReadOffset(immediate, offset))
+	              : ScalarReadOffset(immediate, offset);
+}
+
+// Address of a raw DWORD read: within the buffer's records, or a scalar address that does not
+// leave the address space.
+bool RawReadAddress(bool buffer, int64_t offset, uint64_t low, uint64_t high, uint64_t records,
+                    uint64_t& address) {
+	if (!buffer) {
+		return AddSignedAddress(ReadBase(low, high), offset, address);
+	}
+	const auto byte_offset = static_cast<uint64_t>(offset);
+	if (!BufferDwordInBounds(byte_offset, high, records)) {
+		return false;
+	}
+	address = ReadBase(low, high) + byte_offset;
+	return true;

Confirmed, thanks. The same unchecked addition was already in EvaluateRawRead of #1287 (and in the interpreter on main), so the fix is its own commit in #1287, 1d5801e7: a buffer DWORD whose address leaves the 48-bit address space now fails before reading, like a scalar read. TestBufferReadPastAddressSpaceFails covers it and fails without the check. This branch is rebased on it: RawReadAddress now ends with AddSignedAddress for both kinds of reads (43ff904d), and a direct path that skips the check also fails that test.

**@⁠NeySlim** on GitHub · 2026-10-09 18:33 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1322#discussion_r4233364647) On `src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp` line 117 (outdated): ```diff @@ -71,6 +71,52 @@ bool AddSignedAddress(uint64_t base, int64_t offset, uint64_t& result) { return true; } +// DWORD-aligned base address of a read handle's address DWORDs. +uint64_t ReadBase(uint64_t low, uint64_t high) { + return ((high << 32u) | static_cast<uint32_t>(low)) & AddressMask & ~uint64_t {3}; +} + +// Byte offset of a scalar-address DWORD read: aligned immediate plus aligned offset operand. +int64_t ScalarReadOffset(uint32_t immediate, uint64_t offset) { + return (static_cast<int64_t>(static_cast<int32_t>(immediate)) & ~int64_t {3}) + + static_cast<int64_t>(static_cast<uint32_t>(offset) & ~3u); +} + +// Byte offset of a constant-buffer DWORD read, for a non-negative immediate. +uint64_t BufferReadOffset(uint32_t immediate, uint64_t offset) { + return (uint64_t {immediate} & ~uint64_t {3}) + (static_cast<uint32_t>(offset) & ~3u); +} + +// A DWORD at byte_offset lies within the buffer: stride (in high) times records, or records +// bytes without a stride. +bool BufferDwordInBounds(uint64_t byte_offset, uint64_t high, uint64_t records) { + const auto stride = (static_cast<uint32_t>(high) >> 16u) & 0x3fffu; + const auto size = stride == 0u ? static_cast<uint64_t>(static_cast<uint32_t>(records)) + : static_cast<uint64_t>(stride) * static_cast<uint32_t>(records); + return byte_offset <= size && size - byte_offset >= sizeof(uint32_t); +} + +// Byte offset of a scalar-address or constant-buffer DWORD read. +int64_t RawReadOffset(bool buffer, uint32_t immediate, uint64_t offset) { + return buffer ? static_cast<int64_t>(BufferReadOffset(immediate, offset)) + : ScalarReadOffset(immediate, offset); +} + +// Address of a raw DWORD read: within the buffer's records, or a scalar address that does not +// leave the address space. +bool RawReadAddress(bool buffer, int64_t offset, uint64_t low, uint64_t high, uint64_t records, + uint64_t& address) { + if (!buffer) { + return AddSignedAddress(ReadBase(low, high), offset, address); + } + const auto byte_offset = static_cast<uint64_t>(offset); + if (!BufferDwordInBounds(byte_offset, high, records)) { + return false; + } + address = ReadBase(low, high) + byte_offset; + return true; ``` Confirmed, thanks. The same unchecked addition was already in `EvaluateRawRead` of #1287 (and in the interpreter on main), so the fix is its own commit in #1287, 1d5801e7: a buffer DWORD whose address leaves the 48-bit address space now fails before reading, like a scalar read. `TestBufferReadPastAddressSpaceFails` covers it and fails without the check. This branch is rebased on it: `RawReadAddress` now ends with `AddSignedAddress` for both kinds of reads (43ff904d), and a direct path that skips the check also fails that test.
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-09 18:37 UTC · original
On src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp line 117 (outdated):

@@ -71,6 +71,52 @@ bool AddSignedAddress(uint64_t base, int64_t offset, uint64_t& result) {
 	return true;
 }
 
+// DWORD-aligned base address of a read handle's address DWORDs.
+uint64_t ReadBase(uint64_t low, uint64_t high) {
+	return ((high << 32u) | static_cast<uint32_t>(low)) & AddressMask & ~uint64_t {3};
+}
+
+// Byte offset of a scalar-address DWORD read: aligned immediate plus aligned offset operand.
+int64_t ScalarReadOffset(uint32_t immediate, uint64_t offset) {
+	return (static_cast<int64_t>(static_cast<int32_t>(immediate)) & ~int64_t {3}) +
+	       static_cast<int64_t>(static_cast<uint32_t>(offset) & ~3u);
+}
+
+// Byte offset of a constant-buffer DWORD read, for a non-negative immediate.
+uint64_t BufferReadOffset(uint32_t immediate, uint64_t offset) {
+	return (uint64_t {immediate} & ~uint64_t {3}) + (static_cast<uint32_t>(offset) & ~3u);
+}
+
+// A DWORD at byte_offset lies within the buffer: stride (in high) times records, or records
+// bytes without a stride.
+bool BufferDwordInBounds(uint64_t byte_offset, uint64_t high, uint64_t records) {
+	const auto stride = (static_cast<uint32_t>(high) >> 16u) & 0x3fffu;
+	const auto size = stride == 0u ? static_cast<uint64_t>(static_cast<uint32_t>(records))
+	                               : static_cast<uint64_t>(stride) * static_cast<uint32_t>(records);
+	return byte_offset <= size && size - byte_offset >= sizeof(uint32_t);
+}
+
+// Byte offset of a scalar-address or constant-buffer DWORD read.
+int64_t RawReadOffset(bool buffer, uint32_t immediate, uint64_t offset) {
+	return buffer ? static_cast<int64_t>(BufferReadOffset(immediate, offset))
+	              : ScalarReadOffset(immediate, offset);
+}
+
+// Address of a raw DWORD read: within the buffer's records, or a scalar address that does not
+// leave the address space.
+bool RawReadAddress(bool buffer, int64_t offset, uint64_t low, uint64_t high, uint64_t records,
+                    uint64_t& address) {
+	if (!buffer) {
+		return AddSignedAddress(ReadBase(low, high), offset, address);
+	}
+	const auto byte_offset = static_cast<uint64_t>(offset);
+	if (!BufferDwordInBounds(byte_offset, high, records)) {
+		return false;
+	}
+	address = ReadBase(low, high) + byte_offset;
+	return true;

@NeySlim Thanks for the fix and the regression-test details. The supplied RawReadAddress now checks buffer bounds, then calls AddSignedAddress for both read kinds. This addresses the unchecked addition in both EvaluateRawRead and ComputeFastRead.


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

✅ Review thread resolved.

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-09 18:37 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1322#discussion_r4233397506) On `src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp` line 117 (outdated): ```diff @@ -71,6 +71,52 @@ bool AddSignedAddress(uint64_t base, int64_t offset, uint64_t& result) { return true; } +// DWORD-aligned base address of a read handle's address DWORDs. +uint64_t ReadBase(uint64_t low, uint64_t high) { + return ((high << 32u) | static_cast<uint32_t>(low)) & AddressMask & ~uint64_t {3}; +} + +// Byte offset of a scalar-address DWORD read: aligned immediate plus aligned offset operand. +int64_t ScalarReadOffset(uint32_t immediate, uint64_t offset) { + return (static_cast<int64_t>(static_cast<int32_t>(immediate)) & ~int64_t {3}) + + static_cast<int64_t>(static_cast<uint32_t>(offset) & ~3u); +} + +// Byte offset of a constant-buffer DWORD read, for a non-negative immediate. +uint64_t BufferReadOffset(uint32_t immediate, uint64_t offset) { + return (uint64_t {immediate} & ~uint64_t {3}) + (static_cast<uint32_t>(offset) & ~3u); +} + +// A DWORD at byte_offset lies within the buffer: stride (in high) times records, or records +// bytes without a stride. +bool BufferDwordInBounds(uint64_t byte_offset, uint64_t high, uint64_t records) { + const auto stride = (static_cast<uint32_t>(high) >> 16u) & 0x3fffu; + const auto size = stride == 0u ? static_cast<uint64_t>(static_cast<uint32_t>(records)) + : static_cast<uint64_t>(stride) * static_cast<uint32_t>(records); + return byte_offset <= size && size - byte_offset >= sizeof(uint32_t); +} + +// Byte offset of a scalar-address or constant-buffer DWORD read. +int64_t RawReadOffset(bool buffer, uint32_t immediate, uint64_t offset) { + return buffer ? static_cast<int64_t>(BufferReadOffset(immediate, offset)) + : ScalarReadOffset(immediate, offset); +} + +// Address of a raw DWORD read: within the buffer's records, or a scalar address that does not +// leave the address space. +bool RawReadAddress(bool buffer, int64_t offset, uint64_t low, uint64_t high, uint64_t records, + uint64_t& address) { + if (!buffer) { + return AddSignedAddress(ReadBase(low, high), offset, address); + } + const auto byte_offset = static_cast<uint64_t>(offset); + if (!BufferDwordInBounds(byte_offset, high, records)) { + return false; + } + address = ReadBase(low, high) + byte_offset; + return true; ``` `@NeySlim` Thanks for the fix and the regression-test details. The supplied `RawReadAddress` now checks buffer bounds, then calls `AddSignedAddress` for both read kinds. This addresses the unchecked addition in both `EvaluateRawRead` and `ComputeFastRead`. --- <!-- This is an auto-generated comment: tweet message by coderabbit.ai --> If you found this review helpful, would you consider giving us a shout-out on [X](https://twitter.com/intent/tweet?related=CodeRabbitAI&text=%40coderabbitai%20caught%20a%20buffer-read%20address%20overflow%20that%20could%20bypass%2048-bit%20bounds%20and%20reach%20unchecked%20memory.%20One%20shared%20guard%20fixes%20both%20paths%3B%20regression-tested.%20Try%20CodeRabbit%20%F0%9F%9B%A1%EF%B8%8F%F0%9F%94%8D&url=https%3A%2F%2Fgithub.com%2FKytyPS5%2FKytyPS5%2Fpull%2F1322%23discussion_r4233208609)? Thank you for using CodeRabbit! <!-- end of auto-generated comment: tweet message by coderabbit.ai --> ✅ Review thread resolved. _You are interacting with an AI system._ <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠NeySlim on GitHub · 2026-10-12 15:17 UTC · original

Closing as well, it sits on top of #1287. Covered by #1456.

**@⁠NeySlim** on GitHub · 2026-10-12 15:17 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1322#issuecomment-6127170437) Closing as well, it sits on top of #1287. Covered by #1456.

Pull request closed

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