shader: route oversized read-only raw buffers through direct addressing #978

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

@⁠MehmetCambaz on GitHub · 2026-10-02 15:32 UTC · original
MehmetCambaz:fix/direct-bda-oversized-raw-loads → main · +680 −18 · 9 files · 1 commits · closed without merging

Summary

Kyty exits when a shader binds a raw buffer descriptor whose range does not fit in one Vulkan storage-buffer view. The usual trigger is the RDNA2 maximal-range idiom, a constant NUM_RECORDS = -1 (0xFFFFFFFF). With a STRIDE of 2 or more over a guest mapping of 4 GiB or more, NativeStorageBuffer stops with storage buffer range is unsupported.

This PR reads a buffer resource through the BDA page table instead of a storage view when its NUM_RECORDS is a compile-time constant above 0x7FFFFFFF and every access through it is a raw load.

  • Shader side: the shader evaluates the V# itself (address, OOB_SELECT bounds, ADD_TID), reusing the code of GPU-selected descriptor loads.
  • Host side: the host only materializes the guest window, so its pages are in the page table before the dispatch.

The PR also fixes the BDA page lookup. Today get_bda_pointer maps some addresses outside both guest memory regions onto other pages' page-table entries, so such an address can read another page's data. This also affects existing GLOBAL/FLAT and GPU-selected loads.

The change is deliberately read-only. A resource with any store, atomic, formatted or typed access keeps its storage view and today's behavior. Writable direct windows need GPU write reporting first.

Current-main rebase

This branch has been rebased onto current upstream/main at dc3cd2d2c9d537156894871a91ff22b30ec3a1a8. The implementation was reconciled with the current GPU-selected descriptor, indirect scalar-buffer, and native 64-bit addressing infrastructure. No code from open PRs #931 or #976 was incorporated.

Problem

For the storage-view path, RenderExecutor::FindBuffers sizes a buffer with ShaderBufferResource::GetSize():

  • NUM_RECORDS bytes when STRIDE is 0;
  • STRIDE × NUM_RECORDS bytes otherwise.

It then clamps that size to the contiguous guest mapping at the base (ClampRangeSize). NativeStorageBuffer binds the result as one view and exits if it exceeds maxStorageBufferRange.

Quantity Value
Range declared by a constant NUM_RECORDS = 0xFFFFFFFF 0xFFFFFFFF bytes at STRIDE 0 or 1; about 16 GiB at STRIDE 4
maxStorageBufferRange a uint32_t, so at most 0xFFFFFFFF; Vulkan only requires 2^27
Bytes a shader can address from one descriptor base 2^32 (MUBUF byte offsets are 32-bit)

For a NUM_RECORDS = -1 descriptor with a STRIDE of 2 or more, any mapping of 4 GiB or more gives a clamped range of at least 2^32 bytes. No device can bind that, even though a shader can address at most 2^32 bytes of it. Devices that report a smaller limit exit the same way with smaller mappings.

0x80000000 is the smallest NUM_RECORDS at which a STRIDE of 2 declares 2^32 bytes. The stride usually isn't known at compile time, because dword 1 also carries the base address.

An observation from the test system (RTX 4070, driver 610.47), which reports maxStorageBufferRange = 0xFFFFFFFF: compute-shader stores through views of 2 GiB or more were silently dropped, with no validation message, while the same stores through views of up to 0x7FFFFFFF bytes landed. The fix does not depend on this.

Root cause

Oversized raw descriptors. Resource tracking gives every host-trackable buffer V# a storage view, whatever its declared range. Only V#s whose dwords are not host-trackable, the GPU-selected ResourceKind::IndirectBuffer case, are evaluated in the shader and read through the BDA page table. A constant maximal-range descriptor is host-trackable, so it always gets a view, and that view's size is exactly what does not fit.

BDA lookup of non-guest addresses. Guest memory is two regions, and GuestRange::Valid accepts only ranges inside one of them:

  • the lower address space, [0, LOWER_ADDRESS_SIZE), which is 1 TiB;
  • extended memory, [kExtendedMemoryBase, kExtendedMemoryBase + kExtendedMemorySize), which runs from 8 TiB to 8.5 TiB.

The BDA page table is dense over both, in 16 KiB pages: the first 2^26 entries cover the lower address space and the next 2^25 cover extended memory. get_bda_pointer (DefineGetBdaPointer) rebases only addresses at or above kExtendedMemoryBase, truncates the page index to 32 bits, and never checks that the address is guest memory. As a result:

  • Hole addresses. An address in [LOWER_ADDRESS_SIZE, kExtendedMemoryBase) is not rebased. LOWER_ADDRESS_SIZE + x indexes the entry of kExtendedMemoryBase + x for x < 512 GiB, and runs past the end of the table beyond that.
  • Addresses past extended memory. Their page index wraps when it is converted to 32 bits. For example, 2^46 + (kExtendedMemoryBase − LOWER_ADDRESS_SIZE) + y indexes the lower-space page of y.

If the aliased page is cached, the load returns its data. If not, the lookup records a page fault for the aliased page, and the host caches that unrelated page. GLOBAL/FLAT loads, GPU-selected buffer loads and BVH node reads all use this lookup.

Implementation

Resource routing (ResourceTracking)

AllowsDirectAddressing marks a buffer access eligible when all of the following hold:

  • the handle's NUM_RECORDS operand resolves to an immediate above MaxStorageViewRecords (0x7FFFFFFF);
  • the access is a read (BUFFER_LOAD_* or S_BUFFER_LOAD);
  • the access is neither formatted nor typed.

ResolveDirectAddressing runs after collection. It marks a resource direct only if every access through it is eligible, setting MemoryInfo::direct_address, BufferResource::direct_address and the program's uses_dma. A resource is therefore either entirely view-bound or entirely direct.

CompileProgram keeps the V# operands of direct handles, as it already does for GPU-selected handles. Other bound handles still have their operands zeroed.

Host binding (descriptors.cpp)

FindBuffers bounds every buffer range to 2^32 bytes, the most a 32-bit offset can reach. View-bound resources are unaffected, because a range that large already exits.

For a direct resource, NativeStorageBuffer obtains the window from the buffer cache without the written flag and binds the null buffer. The window's pages are registered in the BDA page table, and its CPU-dirty pages are uploaded, before the dispatch. Nothing is marked GPU-modified and no image is invalidated, as for a read-only view of the same range. The reads need no new barriers: the global memory barriers the renderer already places around dispatches cover BDA accesses.

Shader-side addressing (spirvEmitterMemory.cpp)

V# evaluation. DescriptorComponents is the V# evaluation LoadIndirectBuffer used to do inline: base, STRIDE, swizzle, index stride, ADD_TID, SOFFSET, and the bounds of each OOB_SELECT mode. It now takes the access width, so byte and 16-bit accesses are bounds-checked at their own size. LoadIndirectBuffer passes 4 bytes and is otherwise unchanged.

Vector loads. EmitLoadMemory sends direct accesses to DirectLoad, which handles byte, 16-bit, dword and dword x2–x4 loads:

  • each dword component is bounds-checked on its own, as RDNA2 does for raw vectors;
  • dword loads read the dword holding the byte address, like the view path;
  • sub-dword loads use LoadBda, including a 16-bit load that spans two dwords;
  • GLC/DLC loads (MemoryInfo::coherent) are emitted as Volatile.

Scalar loads. EmitReadConstBuffer sends direct S_BUFFER_LOADs to DirectScalarLoad, which reads the dword the ScalarBuffer view would. Base and offset have their two low bits ignored, and the dword must lie within (STRIDE == 0 ? 1 : STRIDE) × NUM_RECORDS bytes.

Safeguards:

  • an out-of-bounds component returns 0 without touching memory;
  • PrepareMemoryResourceAccess exits if a direct access ever reaches the view path;
  • AnalyzeProgramRequirements enables the subgroup invocation id that ADD_TID needs.

BDA address validation (DefineGetBdaPointer)

get_bda_pointer now decides whether the address lies in the lower address space or in extended memory, the same windows GuestRange::Valid accepts, before using its page index.

  • Other addresses return null without recording a fault, so the load reads 0.
  • Guest addresses behave as before, including the fault record for a missing page.

Why only loads

The view path takes ownership of a written resource coarsely: ObtainBuffer with the written flag adds the whole bound range to the GPU-modified ranges, and NativeStorageBuffer invalidates every image overlapping it.

For a direct window that range can be 4 GiB, while the shader may write only a few pages. Every untouched page would become GPU-owned and be downloaded on later CPU access or unmap. Every image in the window would be invalidated, including render targets the shader never touched.

An earlier writable version of this change showed both effects: render targets inside the window were reloaded from stale buffer contents, and unmapping a written 4 GiB window crashed in the synchronous download path in 7 of 8 full test-suite runs.

Correct writes need the GPU to report the pages direct stores actually wrote. Atomics would also need a BDA atomic path, and formatted or typed accesses need format conversion.

Before / after

Historical before/after results from the original e317465d base and the pre-rebase branch. In BdaRejectsAddressesOutsideGuestRanges, the test's page table maps three guest pages to sentinel data:

  • 0x88776655 and 0xa1a2a3a4 at kExtendedMemoryBase + 0 and + 4;
  • 0x44332211 as the last dword of the lower address space;
  • 0xb1b2b3b4 at 0x1_1000_0000.
Case upstream main this PR
Read-only NUM_RECORDS = -1, STRIDE 4, 4 GiB mapping (DirectAddressOversizedRawAccess) exits while binding: storage buffer range is unsupported reads the guest data: 0x11223344 (GLC dword), 0x33 (byte), 0x5eed1234 at +0x80000100, 0x70b0f00d at +0xFFFFFFF0, 0x11223344 (S_BUFFER_LOAD)
GLOBAL load at LOWER_ADDRESS_SIZE + 4 (hole) 0xa1a2a3a4, the dword at kExtendedMemoryBase + 4 0
GLOBAL load at 0x4701_1000_0000 (past extended memory) 0xb1b2b3b4, the dword at 0x1_1000_0000 0
GLOBAL dword at LOWER_ADDRESS_SIZE − 2 (crosses into the hole) 0x66554433; the upper half comes from kExtendedMemoryBase 0x00004433
GLOBAL load at 2^64 − 2 (wraps the address space) indexes past the end of the page table, which is undefined (it read 0x00004433 here) 0

In the same test both builds agree on the remaining cases: the valid extended and lower-space dwords read 0xa1a2a3a4 and 0xb1b2b3b4, and an unmapped guest page reads 0.

Tests

New tests in shader_recompiler_compute_tests (also selectable with --direct-address-only):

Test Coverage
DirectAddressOversizedRawAccess End to end through CommandProcessor, FindBuffers, NativeStorageBuffer and the buffer cache. A 4 GiB read-only window, plus a one-page written output using the same idiom, which keeps its storage view. Data is read back from guest memory. Fails on main.
BdaRejectsAddressesOutsideGuestRanges The address cases above, through GLOBAL loads. Fails on main.
DirectAddressRawLoads Dword (including via the MUBUF immediate offset), dword x4, byte, 16-bit (one spanning two dwords) and GLC loads. Requires physical pointers and Volatile in the SPIR-V.
DirectAddressExtendedMemoryLoads The same loads with a base in extended memory.
DirectAddressBounds NUM_RECORDS = 0x80000010: an in-bounds dword, a dword x2 with an out-of-bounds second dword, an out-of-bounds dword, the last valid byte, and 16-bit loads inside and across the bound.
DirectAddressScalarLoad S_BUFFER_LOAD with SOFFSET plus an immediate, and through a base whose two low bits are set.

Every case except the first runs its SPIR-V on the GPU against a page table the test builds itself.

On main, DirectAddressRawLoads fails only its SPIR-V requirement, because the resource is still a storage view there. It documents the routing rather than a data bug.

resource_tracking_tests:

  • 0xFFFFFFFF and 0x80000000 loads become direct and are registered as read-only;
  • 0x7FFFFFFF and a runtime NUM_RECORDS keep the view;
  • a store, an atomic, a formatted load, and a load plus a store on one resource all keep the view.

Current rebased validation

Validation was rerun on the rebased head a919940a9b6a936b2ae8cf148c6b7c24485d3d86:

  • resource_tracking_tests.exe — pass.
  • shader_recompiler_compute_tests.exe --direct-address-only — pass.
  • shader_recompiler_compute_tests.exe --indirect-buffer-only — pass.
  • The focused runs with VK_LAYER_KHRONOS_validation produced no validation messages.
  • The shared indirect-buffer neighbor suite also passed on pristine current main for comparison.
  • git diff --check upstream/main...HEAD — pass.

The earlier full-suite, CTest-wide, and Tetris Forever results were run before this rebase and are retained as historical evidence only; they are not claimed as current-head validation.

Scope and limitations

  • Unrouted accesses. Store, atomic, formatted and typed accesses keep the storage view. A resource that needs them over a range too large for a view still exits as before.
  • Compile-time decision. Routing is decided at compile time from a constant NUM_RECORDS. A runtime NUM_RECORDS, or a constant at or below 0x7FFFFFFF even with a large STRIDE, keeps the view path.
  • Small mappings. A routed resource takes the direct path even over a small mapping. It reads the same guest bytes, with one page-table lookup per access.
  • First bind. The first bind uploads the CPU-dirty part of the window, up to 4 GiB, through the existing buffer-cache upload.
  • Teardown. The exit surfaced while bringing up Teardown (PPSA15246). Its PM4-generator compute shader writes through such a descriptor, so that case is outside this PR and still stops at the same exit.
  • #690 turns V#s whose dwords are not host-trackable into dynamic buffers resolved per lane. A host-trackable constant -1 descriptor is not one of them, so it keeps the view path and the exit there. This PR covers that case and uses none of #690's code.
  • #931 adds stores through V#s read from a descriptor table. It also adds the GPU write reporting and CPU-dirty-aware publication that direct stores would need. This PR adds no stores, write tracking or ownership changes. Writable direct windows can build on that mechanism once it is merged.
  • #931 and #976 also edit LoadIndirectBuffer, and #931 also edits DefineGetBdaPointer. #931's BdaPageIndex keeps the unchecked packing described above. Whichever PR lands second needs a mechanical rebase.

AI usage

AI assistance was used for investigation, rebase support, and testing. The contributor reviewed the final diff and current-head validation results before updating this PR.

**@⁠MehmetCambaz** on GitHub · 2026-10-02 15:32 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/978) `MehmetCambaz:fix/direct-bda-oversized-raw-loads` → `main` · +680 −18 · 9 files · 1 commits · closed without merging ## Summary Kyty exits when a shader binds a raw buffer descriptor whose range does not fit in one Vulkan storage-buffer view. The usual trigger is the RDNA2 maximal-range idiom, a constant `NUM_RECORDS = -1` (`0xFFFFFFFF`). With a `STRIDE` of 2 or more over a guest mapping of 4 GiB or more, `NativeStorageBuffer` stops with `storage buffer range is unsupported`. This PR reads a buffer resource through the BDA page table instead of a storage view when its `NUM_RECORDS` is a compile-time constant above `0x7FFFFFFF` and every access through it is a raw load. - **Shader side:** the shader evaluates the V# itself (address, `OOB_SELECT` bounds, `ADD_TID`), reusing the code of GPU-selected descriptor loads. - **Host side:** the host only materializes the guest window, so its pages are in the page table before the dispatch. The PR also fixes the BDA page lookup. Today `get_bda_pointer` maps some addresses outside both guest memory regions onto other pages' page-table entries, so such an address can read another page's data. This also affects existing GLOBAL/FLAT and GPU-selected loads. The change is deliberately read-only. A resource with any store, atomic, formatted or typed access keeps its storage view and today's behavior. Writable direct windows need GPU write reporting first. ## Current-main rebase This branch has been rebased onto current `upstream/main` at `dc3cd2d2c9d537156894871a91ff22b30ec3a1a8`. The implementation was reconciled with the current GPU-selected descriptor, indirect scalar-buffer, and native 64-bit addressing infrastructure. No code from open PRs #931 or #976 was incorporated. ## Problem For the storage-view path, `RenderExecutor::FindBuffers` sizes a buffer with `ShaderBufferResource::GetSize()`: - `NUM_RECORDS` bytes when `STRIDE` is 0; - `STRIDE × NUM_RECORDS` bytes otherwise. It then clamps that size to the contiguous guest mapping at the base (`ClampRangeSize`). `NativeStorageBuffer` binds the result as one view and exits if it exceeds `maxStorageBufferRange`. | Quantity | Value | |---|---| | Range declared by a constant `NUM_RECORDS = 0xFFFFFFFF` | `0xFFFFFFFF` bytes at `STRIDE` 0 or 1; about 16 GiB at `STRIDE` 4 | | `maxStorageBufferRange` | a `uint32_t`, so at most `0xFFFFFFFF`; Vulkan only requires 2^27 | | Bytes a shader can address from one descriptor base | 2^32 (MUBUF byte offsets are 32-bit) | For a `NUM_RECORDS = -1` descriptor with a `STRIDE` of 2 or more, any mapping of 4 GiB or more gives a clamped range of at least 2^32 bytes. No device can bind that, even though a shader can address at most 2^32 bytes of it. Devices that report a smaller limit exit the same way with smaller mappings. `0x80000000` is the smallest `NUM_RECORDS` at which a `STRIDE` of 2 declares 2^32 bytes. The stride usually isn't known at compile time, because dword 1 also carries the base address. An observation from the test system (RTX 4070, driver 610.47), which reports `maxStorageBufferRange = 0xFFFFFFFF`: compute-shader stores through views of 2 GiB or more were silently dropped, with no validation message, while the same stores through views of up to `0x7FFFFFFF` bytes landed. The fix does not depend on this. ## Root cause **Oversized raw descriptors.** Resource tracking gives every host-trackable buffer V# a storage view, whatever its declared range. Only V#s whose dwords are not host-trackable, the GPU-selected `ResourceKind::IndirectBuffer` case, are evaluated in the shader and read through the BDA page table. A constant maximal-range descriptor is host-trackable, so it always gets a view, and that view's size is exactly what does not fit. **BDA lookup of non-guest addresses.** Guest memory is two regions, and `GuestRange::Valid` accepts only ranges inside one of them: - the lower address space, `[0, LOWER_ADDRESS_SIZE)`, which is 1 TiB; - extended memory, `[kExtendedMemoryBase, kExtendedMemoryBase + kExtendedMemorySize)`, which runs from 8 TiB to 8.5 TiB. The BDA page table is dense over both, in 16 KiB pages: the first 2^26 entries cover the lower address space and the next 2^25 cover extended memory. `get_bda_pointer` (`DefineGetBdaPointer`) rebases only addresses at or above `kExtendedMemoryBase`, truncates the page index to 32 bits, and never checks that the address is guest memory. As a result: - **Hole addresses.** An address in `[LOWER_ADDRESS_SIZE, kExtendedMemoryBase)` is not rebased. `LOWER_ADDRESS_SIZE + x` indexes the entry of `kExtendedMemoryBase + x` for `x` < 512 GiB, and runs past the end of the table beyond that. - **Addresses past extended memory.** Their page index wraps when it is converted to 32 bits. For example, `2^46 + (kExtendedMemoryBase − LOWER_ADDRESS_SIZE) + y` indexes the lower-space page of `y`. If the aliased page is cached, the load returns its data. If not, the lookup records a page fault for the aliased page, and the host caches that unrelated page. GLOBAL/FLAT loads, GPU-selected buffer loads and BVH node reads all use this lookup. ## Implementation ### Resource routing (`ResourceTracking`) `AllowsDirectAddressing` marks a buffer access eligible when all of the following hold: - the handle's `NUM_RECORDS` operand resolves to an immediate above `MaxStorageViewRecords` (`0x7FFFFFFF`); - the access is a read (`BUFFER_LOAD_*` or `S_BUFFER_LOAD`); - the access is neither formatted nor typed. `ResolveDirectAddressing` runs after collection. It marks a resource direct only if every access through it is eligible, setting `MemoryInfo::direct_address`, `BufferResource::direct_address` and the program's `uses_dma`. A resource is therefore either entirely view-bound or entirely direct. `CompileProgram` keeps the V# operands of direct handles, as it already does for GPU-selected handles. Other bound handles still have their operands zeroed. ### Host binding (`descriptors.cpp`) `FindBuffers` bounds every buffer range to 2^32 bytes, the most a 32-bit offset can reach. View-bound resources are unaffected, because a range that large already exits. For a direct resource, `NativeStorageBuffer` obtains the window from the buffer cache without the written flag and binds the null buffer. The window's pages are registered in the BDA page table, and its CPU-dirty pages are uploaded, before the dispatch. Nothing is marked GPU-modified and no image is invalidated, as for a read-only view of the same range. The reads need no new barriers: the global memory barriers the renderer already places around dispatches cover BDA accesses. ### Shader-side addressing (`spirvEmitterMemory.cpp`) **V# evaluation.** `DescriptorComponents` is the V# evaluation `LoadIndirectBuffer` used to do inline: base, `STRIDE`, swizzle, index stride, `ADD_TID`, `SOFFSET`, and the bounds of each `OOB_SELECT` mode. It now takes the access width, so byte and 16-bit accesses are bounds-checked at their own size. `LoadIndirectBuffer` passes 4 bytes and is otherwise unchanged. **Vector loads.** `EmitLoadMemory` sends direct accesses to `DirectLoad`, which handles byte, 16-bit, dword and dword x2–x4 loads: - each dword component is bounds-checked on its own, as RDNA2 does for raw vectors; - dword loads read the dword holding the byte address, like the view path; - sub-dword loads use `LoadBda`, including a 16-bit load that spans two dwords; - GLC/DLC loads (`MemoryInfo::coherent`) are emitted as `Volatile`. **Scalar loads.** `EmitReadConstBuffer` sends direct `S_BUFFER_LOAD`s to `DirectScalarLoad`, which reads the dword the ScalarBuffer view would. Base and offset have their two low bits ignored, and the dword must lie within `(STRIDE == 0 ? 1 : STRIDE) × NUM_RECORDS` bytes. **Safeguards:** - an out-of-bounds component returns 0 without touching memory; - `PrepareMemoryResourceAccess` exits if a direct access ever reaches the view path; - `AnalyzeProgramRequirements` enables the subgroup invocation id that `ADD_TID` needs. ### BDA address validation (`DefineGetBdaPointer`) `get_bda_pointer` now decides whether the address lies in the lower address space or in extended memory, the same windows `GuestRange::Valid` accepts, before using its page index. - **Other addresses** return null without recording a fault, so the load reads 0. - **Guest addresses** behave as before, including the fault record for a missing page. ### Why only loads The view path takes ownership of a written resource coarsely: `ObtainBuffer` with the written flag adds the whole bound range to the GPU-modified ranges, and `NativeStorageBuffer` invalidates every image overlapping it. For a direct window that range can be 4 GiB, while the shader may write only a few pages. Every untouched page would become GPU-owned and be downloaded on later CPU access or unmap. Every image in the window would be invalidated, including render targets the shader never touched. An earlier writable version of this change showed both effects: render targets inside the window were reloaded from stale buffer contents, and unmapping a written 4 GiB window crashed in the synchronous download path in 7 of 8 full test-suite runs. Correct writes need the GPU to report the pages direct stores actually wrote. Atomics would also need a BDA atomic path, and formatted or typed accesses need format conversion. ## Before / after Historical before/after results from the original `e317465d` base and the pre-rebase branch. In `BdaRejectsAddressesOutsideGuestRanges`, the test's page table maps three guest pages to sentinel data: - `0x88776655` and `0xa1a2a3a4` at `kExtendedMemoryBase + 0` and `+ 4`; - `0x44332211` as the last dword of the lower address space; - `0xb1b2b3b4` at `0x1_1000_0000`. | Case | upstream `main` | this PR | |---|---|---| | Read-only `NUM_RECORDS = -1`, `STRIDE` 4, 4 GiB mapping (`DirectAddressOversizedRawAccess`) | exits while binding: `storage buffer range is unsupported` | reads the guest data: `0x11223344` (GLC dword), `0x33` (byte), `0x5eed1234` at `+0x80000100`, `0x70b0f00d` at `+0xFFFFFFF0`, `0x11223344` (`S_BUFFER_LOAD`) | | GLOBAL load at `LOWER_ADDRESS_SIZE + 4` (hole) | `0xa1a2a3a4`, the dword at `kExtendedMemoryBase + 4` | `0` | | GLOBAL load at `0x4701_1000_0000` (past extended memory) | `0xb1b2b3b4`, the dword at `0x1_1000_0000` | `0` | | GLOBAL dword at `LOWER_ADDRESS_SIZE − 2` (crosses into the hole) | `0x66554433`; the upper half comes from `kExtendedMemoryBase` | `0x00004433` | | GLOBAL load at `2^64 − 2` (wraps the address space) | indexes past the end of the page table, which is undefined (it read `0x00004433` here) | `0` | In the same test both builds agree on the remaining cases: the valid extended and lower-space dwords read `0xa1a2a3a4` and `0xb1b2b3b4`, and an unmapped guest page reads `0`. ## Tests New tests in `shader_recompiler_compute_tests` (also selectable with `--direct-address-only`): | Test | Coverage | |---|---| | `DirectAddressOversizedRawAccess` | End to end through `CommandProcessor`, `FindBuffers`, `NativeStorageBuffer` and the buffer cache. A 4 GiB read-only window, plus a one-page written output using the same idiom, which keeps its storage view. Data is read back from guest memory. Fails on `main`. | | `BdaRejectsAddressesOutsideGuestRanges` | The address cases above, through GLOBAL loads. Fails on `main`. | | `DirectAddressRawLoads` | Dword (including via the MUBUF immediate offset), dword x4, byte, 16-bit (one spanning two dwords) and GLC loads. Requires physical pointers and `Volatile` in the SPIR-V. | | `DirectAddressExtendedMemoryLoads` | The same loads with a base in extended memory. | | `DirectAddressBounds` | `NUM_RECORDS = 0x80000010`: an in-bounds dword, a dword x2 with an out-of-bounds second dword, an out-of-bounds dword, the last valid byte, and 16-bit loads inside and across the bound. | | `DirectAddressScalarLoad` | `S_BUFFER_LOAD` with `SOFFSET` plus an immediate, and through a base whose two low bits are set. | Every case except the first runs its SPIR-V on the GPU against a page table the test builds itself. On `main`, `DirectAddressRawLoads` fails only its SPIR-V requirement, because the resource is still a storage view there. It documents the routing rather than a data bug. `resource_tracking_tests`: - `0xFFFFFFFF` and `0x80000000` loads become direct and are registered as read-only; - `0x7FFFFFFF` and a runtime `NUM_RECORDS` keep the view; - a store, an atomic, a formatted load, and a load plus a store on one resource all keep the view. ## Current rebased validation Validation was rerun on the rebased head `a919940a9b6a936b2ae8cf148c6b7c24485d3d86`: - `resource_tracking_tests.exe` — pass. - `shader_recompiler_compute_tests.exe --direct-address-only` — pass. - `shader_recompiler_compute_tests.exe --indirect-buffer-only` — pass. - The focused runs with `VK_LAYER_KHRONOS_validation` produced no validation messages. - The shared indirect-buffer neighbor suite also passed on pristine current main for comparison. - `git diff --check upstream/main...HEAD` — pass. The earlier full-suite, CTest-wide, and Tetris Forever results were run before this rebase and are retained as historical evidence only; they are not claimed as current-head validation. ## Scope and limitations - **Unrouted accesses.** Store, atomic, formatted and typed accesses keep the storage view. A resource that needs them over a range too large for a view still exits as before. - **Compile-time decision.** Routing is decided at compile time from a constant `NUM_RECORDS`. A runtime `NUM_RECORDS`, or a constant at or below `0x7FFFFFFF` even with a large `STRIDE`, keeps the view path. - **Small mappings.** A routed resource takes the direct path even over a small mapping. It reads the same guest bytes, with one page-table lookup per access. - **First bind.** The first bind uploads the CPU-dirty part of the window, up to 4 GiB, through the existing buffer-cache upload. - **Teardown.** The exit surfaced while bringing up Teardown (PPSA15246). Its PM4-generator compute shader writes through such a descriptor, so that case is outside this PR and still stops at the same exit. ## Related work - **#690** turns V#s whose dwords are not host-trackable into dynamic buffers resolved per lane. A host-trackable constant `-1` descriptor is not one of them, so it keeps the view path and the exit there. This PR covers that case and uses none of #690's code. - **#931** adds stores through V#s read from a descriptor table. It also adds the GPU write reporting and CPU-dirty-aware publication that direct stores would need. This PR adds no stores, write tracking or ownership changes. Writable direct windows can build on that mechanism once it is merged. - **#931 and #976** also edit `LoadIndirectBuffer`, and #931 also edits `DefineGetBdaPointer`. #931's `BdaPageIndex` keeps the unchecked packing described above. Whichever PR lands second needs a mechanical rebase. ## AI usage AI assistance was used for investigation, rebase support, and testing. The contributor reviewed the final diff and current-head validation results before updating this PR.
A raw buffer descriptor whose NUM_RECORDS is a compile-time constant
above 0x7FFFFFFF, such as the RDNA2 maximal-range idiom NUM_RECORDS = -1,
can declare more guest memory than one storage view holds. With a nonzero
stride over a mapping of 4 GiB or more, binding exits with "storage
buffer range is unsupported": maxStorageBufferRange is a 32-bit limit.
Views below that limit are not reliable either: an RTX 4070 (driver
610.47) advertises 0xFFFFFFFF but silently drops accesses through views
of 2 GiB or more.

When every access through such a resource is a raw load, resource
tracking now routes it to direct (BDA) guest addressing instead. The host
still materializes the guest window, bounded to the 4 GiB a 32-bit buffer
offset can reach. That uploads it and enters its pages into the BDA page
table, but binds no view. The window is not written, so buffer ownership
and image state stay as they would be for a read-only view.

A resource with any store, atomic, formatted or typed access keeps its
storage view, as before. Direct stores would need the GPU to report the
pages it wrote; without that, the whole window, up to 4 GiB, would become
GPU-written and every image inside it would be invalidated.

The shader evaluates the V# of these loads with the addressing and
OOB_SELECT bounds code of GPU-selected descriptor loads, now shared and
parameterized by access width:

- Dword loads read the dword that holds the byte address, like the view
  path.
- GLC/DLC loads stay volatile.
- S_BUFFER_LOAD reads the dword the ScalarBuffer view would.
- Compilation keeps the descriptor dwords of these handles instead of
  zeroing them, because the shader reads them.

The BDA page lookup now resolves only guest addresses in the lower
address space or extended memory, like GuestRange::Valid. An address in
the hole above the lower address space used to index extended memory,
and an address beyond extended memory wrapped its 32-bit page index onto
a lower page, so such loads read another page's data. They now resolve
as missing, without recording a fault.

Tests: the routing and storage-view fallback cases in
resource_tracking_tests; DirectAddressOversizedRawAccess (end to end over
a 4 GiB window), DirectAddressRawLoads, DirectAddressExtendedMemoryLoads,
DirectAddressBounds, DirectAddressScalarLoad and
BdaRejectsAddressesOutsideGuestRanges in shader_recompiler_compute_tests.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:39:07 +00:00
github-bot closed this pull request 2026-11-26 09:39:07 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-02 15:38 UTC · original · edited 2026-10-05 18:30 UTC

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

📝 Walkthrough

Walkthrough

The recompiler marks eligible oversized raw reads for direct guest addressing. The SPIR-V backend emits bounded direct-address loads and validates guest address ranges. The host materializes the requested guest-memory range, capped at 4 GiB. New tests cover routing, load widths, bounds, invalid addresses, and end-to-end reads across a 4 GiB mapping.

Suggested reviewers: nmzik

Priority: ➖ Normal

Change: Bug fix

Merge Risk: 🔵 Low · up to a9199

Scalar buffer reads that request coherent access through a direct-address buffer lose their volatile semantics. This is a small, bounded issue that is straightforward to fix before or soon after merge.

Security Architecture Review

Security architecture risk: 🔵 Low · up to a9199

Oversized reads gain a new execution path with explicit address checks and no added write authority. No introduced security defect was established, but concurrent-update and recovery behavior remains partly unverified.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — Guest-controlled descriptor addresses and access operands influence reads through a shared guest-memory page table. The physical addresses come from registered host-owned GPU allocations, not directly from guest-supplied physical pointers. Exposure is therefore tied to registered guest-memory backing and guest addressing semantics; the inspected files do not establish finer asset isolation.

Trust Boundaries and Controls

  • observed — Direct addressing requires an immediate oversized U32 record count and exclusively raw, untyped reads across every tracked access to the resource. Any tracked store, atomic, formatted or typed access prevents the entire resource from taking this route.
  • observed — Raw direct loads apply access-active, format-valid and guest descriptor bounds conditions. Pointer conversion and physical loads occur only for nonzero translated pointers. Cross-dword subword reads translate the second dword independently. Valid architectural addresses without backing return zero and record a page fault.

Resilience and Maintainability Implications

  • inferred — Pre-rebind synchronization and completion-gated allocation destruction counter the suspected stale-owner or immediate-free failure. However, the general obtain helper can return stream storage for small CPU-dirty reads, which the direct branch ignores. The normal synchronization path mitigates that mismatch; late-dirty interleavings and complete fault recovery remain unresolved rather than demonstrated failures.

Hardening Proposals

  • proposed — Make direct-read preparation explicitly require the registered page-table backing allocation, its synchronization and its lifetime through dispatch completion, without relying on storage-view stream substitution. This would strengthen the ownership contract; it is hardening, not an observed defect.
🚥 Pre-merge checks | ✅ 4 | ❓ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ❓ Inconclusive Docstring coverage is 25.81% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 31 functions across 8 files. (1 skipped: … 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 summarizes the main change: routing oversized read-only raw buffers through direct addressing.
Description check ✅ Passed The description explains the storage-view failure, the direct-addressing approach, its limits, and the added tests. It is directly related to the changeset.
Full details: Docstring Coverage

Explanation

Docstring coverage is 25.81% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 31 functions across 8 files. (1 skipped: 1 too large.)

  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Autopilot is currently an internal CodeRabbit preview.


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-02 15:38 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/978#issuecomment-5955836276) · edited 2026-10-05 18:30 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/978?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> Navigate logical layers of code changes, visualize relationships, and explore their blast radius. <!-- review_stack_entry_end --> <!-- walkthrough_start --> <details> <summary>📝 Walkthrough</summary> ## Walkthrough The recompiler marks eligible oversized raw reads for direct guest addressing. The SPIR-V backend emits bounded direct-address loads and validates guest address ranges. The host materializes the requested guest-memory range, capped at 4 GiB. New tests cover routing, load widths, bounds, invalid addresses, and end-to-end reads across a 4 GiB mapping. **Suggested reviewers:** `nmzik` </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ➖ Normal <!-- change_assessment_commit:"a919940a9b6a936b2ae8cf148c6b7c24485d3d86" --> **Change:** Bug fix <!-- change_assessment_end --> <!-- final_review_risk_start --> **Merge Risk:** _🔵 Low_ · up to `a9199` <!-- final_review_risk_coverage:{"sourceCommitId":"a919940a9b6a936b2ae8cf148c6b7c24485d3d86","coveredCommitId":"a919940a9b6a936b2ae8cf148c6b7c24485d3d86","kind":"reviewed"} --> Scalar buffer reads that request coherent access through a direct-address buffer lose their volatile semantics. This is a small, bounded issue that is straightforward to fix before or soon after merge. <!-- final_review_risk_end --> <!-- architecture_review_start --> ### Security Architecture Review **Security architecture risk:** _🔵 Low_ · up to `a9199` Oversized reads gain a new execution path with explicit address checks and no added write authority. No introduced security defect was established, but concurrent-update and recovery behavior remains partly unverified. **Retained concerns** No architecture-level concerns identified. <details> <summary>Security review details</summary> **Security Blast Radius** - _inferred_ — Guest-controlled descriptor addresses and access operands influence reads through a shared guest-memory page table. The physical addresses come from registered host-owned GPU allocations, not directly from guest-supplied physical pointers. Exposure is therefore tied to registered guest-memory backing and guest addressing semantics; the inspected files do not establish finer asset isolation. **Trust Boundaries and Controls** - _observed_ — Direct addressing requires an immediate oversized U32 record count and exclusively raw, untyped reads across every tracked access to the resource. Any tracked store, atomic, formatted or typed access prevents the entire resource from taking this route. - _observed_ — Raw direct loads apply access-active, format-valid and guest descriptor bounds conditions. Pointer conversion and physical loads occur only for nonzero translated pointers. Cross-dword subword reads translate the second dword independently. Valid architectural addresses without backing return zero and record a page fault. **Resilience and Maintainability Implications** - _inferred_ — Pre-rebind synchronization and completion-gated allocation destruction counter the suspected stale-owner or immediate-free failure. However, the general obtain helper can return stream storage for small CPU-dirty reads, which the direct branch ignores. The normal synchronization path mitigates that mismatch; late-dirty interleavings and complete fault recovery remain unresolved rather than demonstrated failures. **Hardening Proposals** - _proposed_ — Make direct-read preparation explicitly require the registered page-table backing allocation, its synchronization and its lifetime through dispatch completion, without relying on storage-view stream substitution. This would strengthen the ownership contract; it is hardening, not an observed defect. </details> <!-- architecture_review_end --> <!-- pre_merge_checks_walkthrough_start --> <details> <summary>🚥 Pre-merge checks | ✅ 4 | ❓ 1</summary> ### ❌ Failed checks (1 inconclusive) | Check name | Status | Explanation | Resolution | | :----------------: | :------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------- | | Docstring Coverage | ❓ Inconclusive | Docstring coverage is 25.81% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 31 functions across 8 files. (1 skipped: … | Write docstrings for the functions missing them to satisfy the coverage threshold. | <details> <summary>✅ Passed checks (4 passed)</summary> | Check name | Status | Explanation | | :------------------------: | :------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------- | | Linked Issues check | ✅ Passed | Check skipped because no linked issues were found for this pull request. | | Out of Scope Changes check | ✅ Passed | Check skipped because no linked issues were found for this pull request. | | Title check | ✅ Passed | The title clearly summarizes the main change: routing oversized read-only raw buffers through direct addressing. | | Description check | ✅ Passed | The description explains the storage-view failure, the direct-addressing approach, its limits, and the added tests. It is directly related to the changeset. | </details> <details> <summary>Full details: Docstring Coverage</summary> **Explanation** Docstring coverage is 25.81% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 31 functions across 8 files. (1 skipped: 1 too large.) </details> </details> <!-- pre_merge_checks_walkthrough_end --> <!-- autopilot:start --> - [ ] <!-- {"checkboxId":"2708ad07-9f24-4260-9c11-7dc76a49f2e3"} --> <strong title="Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts">Autopilot</strong> · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts > Autopilot is currently an internal CodeRabbit preview. <!-- autopilot:end --> <!-- tips_start --> --- Thanks for using [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=KytyPS5/KytyPS5&utm_content=978)! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. <details> <summary>❤️ Share</summary> - [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai) - [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai) - [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai) - [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code) </details> <sub>Comment `@coderabbitai help` to get the list of available commands.</sub> <!-- tips_end -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-02 15:38 UTC · original · edited 2026-10-05 18:29 UTC
On src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp line 928 (outdated):

@@ -830,12 +850,82 @@ uint32_t LoadIndirectBuffer(ValueEmitContext& ctx, const IR::Inst& inst, uint32_
 		    Select(state, TypeBool(state),
 		           Binary(state, spv::OpIEqual, TypeBool(state), mode, ConstantU32(state, 2)),
 		           nonzero(records), raw_bounds));
-		const auto guest =
+		result[component].address =
 		    Binary(state, spv::OpIAdd, TypeScalarU64(state), base,
 		           Unary(state, spv::OpUConvert, TypeScalarU64(state), address.byte));
-		values[component] = LoadBda(ctx, guest, AndCondition(state, valid_format, in_bounds), 32u);
+		result[component].active = AndCondition(state, valid_format, in_bounds);
+	}
+	return result;
+}
+
+uint32_t LoadIndirectBuffer(ValueEmitContext& ctx, const IR::Inst& inst, uint32_t components) {
+	const auto              parts = DescriptorComponents(ctx, inst, components, 4u);
+	std::array<uint32_t, 4> values {};
+	for (uint32_t component = 0; component < components; component++) {
+		values[component] = LoadBda(ctx, parts[component].address, parts[component].active, 32u);
 	}
-	return ConstructU32Composite(state, components, values);
+	return ConstructU32Composite(ctx.state, components, values);
+}
+
+uint32_t AlignDownToDword(EmitterState& state, uint32_t address) {
+	return Binary(state, spv::OpBitwiseAnd, TypeScalarU64(state), address,
+	              ConstantDeviceAddress(state, ~uint64_t {3}));
+}
+
+// Raw loads through a direct-address resource. A DWORD load reads the dword holding the byte
+// address, like the storage-view path.
+uint32_t DirectLoad(ValueEmitContext& ctx, const IR::Inst& inst, uint32_t components,
+                    uint32_t bits) {
+	auto&      state = ctx.state;
+	const auto type  = components == 1u ? TypeU32(state) : TypeU32Composite(state, components);
+	const auto zero =
+	    components == 1u ? ConstantU32(state, 0) : ConstantU32CompositeZero(state, components);
+	const auto coherent = ctx.Memory(inst).coherent;
+	return EmitValueOrDefaultIfCondition(
+	    state, ctx.Arg(inst, inst.NumArgs() - 1), type, zero, [&]() {
+		    const auto              parts = DescriptorComponents(ctx, inst, components, bits / 8u);
+		    std::array<uint32_t, 4> values {};
+		    for (uint32_t component = 0; component < components; component++) {
+			    const auto address = bits == 32u ? AlignDownToDword(state, parts[component].address)
+			                                     : parts[component].address;
+			    values[component]  = LoadBda(ctx, address, parts[component].active, bits, coherent);
+		    }
+		    return components == 1u ? values[0] : ConstructU32Composite(state, components, values);
+	    });
+}
+
+// S_BUFFER_LOAD through a direct-address resource reads the dword the ScalarBuffer view path
+// reads. Scalar memory ignores the two low address bits, so that dword starts at the aligned
+// base plus the aligned offset, and it must lie within the descriptor's byte span,
+// (STRIDE == 0 ? 1 : STRIDE) * NUM_RECORDS. RDNA3 ISA 8.1.2 states this span for scalar
+// buffer reads; the RDNA2 guide's version of the formula leaves out the STRIDE factor.
+uint32_t DirectScalarLoad(ValueEmitContext& ctx, const IR::Inst& inst) {
+	auto&       state   = ctx.state;
+	const auto& handle  = *inst.Arg(0).ResolveInstruction();
+	const auto  word1   = ctx.Arg(handle, 1);
+	const auto  records = ctx.Arg(handle, 2);
+	const auto  aligned = ConstantU32(state, ~3u);
+	const auto  base    = DeviceAddressFromWords(
+	    state, Binary(state, spv::OpBitwiseAnd, TypeU32(state), ctx.Arg(handle, 0), aligned),
+	    EmitBitFieldUExtract(state, word1, ConstantU32(state, 0), ConstantU32(state, 16)));
+	const auto stride =
+	    EmitBitFieldUExtract(state, word1, ConstantU32(state, 16), ConstantU32(state, 14));
+	const auto unit =
+	    Select(state, TypeU32(state),
+	           Binary(state, spv::OpIEqual, TypeBool(state), stride, ConstantU32(state, 0)),
+	           ConstantU32(state, 1), stride);
+	const auto span   = Binary(state, spv::OpIMul, TypeScalarU64(state),
+	                           Unary(state, spv::OpUConvert, TypeScalarU64(state), unit),
+	                           Unary(state, spv::OpUConvert, TypeScalarU64(state), records));
+	const auto offset = Unary(state, spv::OpUConvert, TypeScalarU64(state),
+	                          Binary(state, spv::OpBitwiseAnd, TypeU32(state),
+	                                 Binary(state, spv::OpIAdd, TypeU32(state), ctx.Arg(inst, 1),
+	                                        ConstantU32(state, ctx.Memory(inst).offset)),
+	                                 aligned));
+	const auto end    = Binary(state, spv::OpIAdd, TypeScalarU64(state), offset,
+	                           ConstantDeviceAddress(state, sizeof(uint32_t)));
+	return LoadBda(ctx, Binary(state, spv::OpIAdd, TypeScalarU64(state), base, offset),
+	               Binary(state, spv::OpULessThanEqual, TypeBool(state), end, span), 32u);

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Pass coherent to LoadBda in DirectScalarLoad.

DirectLoad forwards ctx.Memory(inst).coherent. DirectScalarLoad uses the default value false. A GLC scalar buffer read on a direct-address resource therefore loses the volatile access semantics that the storage-view path applies through PrepareStorageBufferResourceAccess.

Proposed fix
 	return LoadBda(ctx, Binary(state, spv::OpIAdd, TypeScalarU64(state), base, offset),
-	               Binary(state, spv::OpULessThanEqual, TypeBool(state), end, span), 32u);
+	               Binary(state, spv::OpULessThanEqual, TypeBool(state), end, span), 32u,
+	               ctx.Memory(inst).coherent);
📝 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.

	return LoadBda(ctx, Binary(state, spv::OpIAdd, TypeScalarU64(state), base, offset),
	               Binary(state, spv::OpULessThanEqual, TypeBool(state), end, span), 32u,
	               ctx.Memory(inst).coherent);
**@⁠coderabbitai[bot]** on GitHub · 2026-10-02 15:38 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/978#discussion_r4167286492) · edited 2026-10-05 18:29 UTC On `src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp` line 928 (outdated): ```diff @@ -830,12 +850,82 @@ uint32_t LoadIndirectBuffer(ValueEmitContext& ctx, const IR::Inst& inst, uint32_ Select(state, TypeBool(state), Binary(state, spv::OpIEqual, TypeBool(state), mode, ConstantU32(state, 2)), nonzero(records), raw_bounds)); - const auto guest = + result[component].address = Binary(state, spv::OpIAdd, TypeScalarU64(state), base, Unary(state, spv::OpUConvert, TypeScalarU64(state), address.byte)); - values[component] = LoadBda(ctx, guest, AndCondition(state, valid_format, in_bounds), 32u); + result[component].active = AndCondition(state, valid_format, in_bounds); + } + return result; +} + +uint32_t LoadIndirectBuffer(ValueEmitContext& ctx, const IR::Inst& inst, uint32_t components) { + const auto parts = DescriptorComponents(ctx, inst, components, 4u); + std::array<uint32_t, 4> values {}; + for (uint32_t component = 0; component < components; component++) { + values[component] = LoadBda(ctx, parts[component].address, parts[component].active, 32u); } - return ConstructU32Composite(state, components, values); + return ConstructU32Composite(ctx.state, components, values); +} + +uint32_t AlignDownToDword(EmitterState& state, uint32_t address) { + return Binary(state, spv::OpBitwiseAnd, TypeScalarU64(state), address, + ConstantDeviceAddress(state, ~uint64_t {3})); +} + +// Raw loads through a direct-address resource. A DWORD load reads the dword holding the byte +// address, like the storage-view path. +uint32_t DirectLoad(ValueEmitContext& ctx, const IR::Inst& inst, uint32_t components, + uint32_t bits) { + auto& state = ctx.state; + const auto type = components == 1u ? TypeU32(state) : TypeU32Composite(state, components); + const auto zero = + components == 1u ? ConstantU32(state, 0) : ConstantU32CompositeZero(state, components); + const auto coherent = ctx.Memory(inst).coherent; + return EmitValueOrDefaultIfCondition( + state, ctx.Arg(inst, inst.NumArgs() - 1), type, zero, [&]() { + const auto parts = DescriptorComponents(ctx, inst, components, bits / 8u); + std::array<uint32_t, 4> values {}; + for (uint32_t component = 0; component < components; component++) { + const auto address = bits == 32u ? AlignDownToDword(state, parts[component].address) + : parts[component].address; + values[component] = LoadBda(ctx, address, parts[component].active, bits, coherent); + } + return components == 1u ? values[0] : ConstructU32Composite(state, components, values); + }); +} + +// S_BUFFER_LOAD through a direct-address resource reads the dword the ScalarBuffer view path +// reads. Scalar memory ignores the two low address bits, so that dword starts at the aligned +// base plus the aligned offset, and it must lie within the descriptor's byte span, +// (STRIDE == 0 ? 1 : STRIDE) * NUM_RECORDS. RDNA3 ISA 8.1.2 states this span for scalar +// buffer reads; the RDNA2 guide's version of the formula leaves out the STRIDE factor. +uint32_t DirectScalarLoad(ValueEmitContext& ctx, const IR::Inst& inst) { + auto& state = ctx.state; + const auto& handle = *inst.Arg(0).ResolveInstruction(); + const auto word1 = ctx.Arg(handle, 1); + const auto records = ctx.Arg(handle, 2); + const auto aligned = ConstantU32(state, ~3u); + const auto base = DeviceAddressFromWords( + state, Binary(state, spv::OpBitwiseAnd, TypeU32(state), ctx.Arg(handle, 0), aligned), + EmitBitFieldUExtract(state, word1, ConstantU32(state, 0), ConstantU32(state, 16))); + const auto stride = + EmitBitFieldUExtract(state, word1, ConstantU32(state, 16), ConstantU32(state, 14)); + const auto unit = + Select(state, TypeU32(state), + Binary(state, spv::OpIEqual, TypeBool(state), stride, ConstantU32(state, 0)), + ConstantU32(state, 1), stride); + const auto span = Binary(state, spv::OpIMul, TypeScalarU64(state), + Unary(state, spv::OpUConvert, TypeScalarU64(state), unit), + Unary(state, spv::OpUConvert, TypeScalarU64(state), records)); + const auto offset = Unary(state, spv::OpUConvert, TypeScalarU64(state), + Binary(state, spv::OpBitwiseAnd, TypeU32(state), + Binary(state, spv::OpIAdd, TypeU32(state), ctx.Arg(inst, 1), + ConstantU32(state, ctx.Memory(inst).offset)), + aligned)); + const auto end = Binary(state, spv::OpIAdd, TypeScalarU64(state), offset, + ConstantDeviceAddress(state, sizeof(uint32_t))); + return LoadBda(ctx, Binary(state, spv::OpIAdd, TypeScalarU64(state), base, offset), + Binary(state, spv::OpULessThanEqual, TypeBool(state), end, span), 32u); ``` _🎯 Functional Correctness_ | _🟡 Minor_ | _⚡ Quick win_ **Pass `coherent` to `LoadBda` in `DirectScalarLoad`.** `DirectLoad` forwards `ctx.Memory(inst).coherent`. `DirectScalarLoad` uses the default value `false`. A GLC scalar buffer read on a direct-address resource therefore loses the volatile access semantics that the storage-view path applies through `PrepareStorageBufferResourceAccess`. <details> <summary>Proposed fix</summary> ```diff return LoadBda(ctx, Binary(state, spv::OpIAdd, TypeScalarU64(state), base, offset), - Binary(state, spv::OpULessThanEqual, TypeBool(state), end, span), 32u); + Binary(state, spv::OpULessThanEqual, TypeBool(state), end, span), 32u, + ctx.Memory(inst).coherent); ``` </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 return LoadBda(ctx, Binary(state, spv::OpIAdd, TypeScalarU64(state), base, offset), Binary(state, spv::OpULessThanEqual, TypeBool(state), end, span), 32u, ctx.Memory(inst).coherent); ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:7aea27def49f00fefceb01dd --> <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-02 15:38 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: 4647ebac-8847-4494-9530-348e5aafba0a

📥 Commits

Reviewing files that changed from the base of the PR and between e317465d8a and 7a81c02d71f040b8391dcd63a1caf3f9afcda4fa.

📒 Files selected for processing (9)
  • src/graphics/host_gpu/renderer/pipeline/descriptors.cpp
  • src/graphics/shader/recompiler/ShaderRecompiler.cpp
  • src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemoryHelpers.cpp
  • src/graphics/shader/recompiler/ir/ShaderIR.h
  • src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp
  • tests/ResourceTrackingTests.cpp
  • tests/ShaderRecompilerComputeTests.cpp

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

**@⁠coderabbitai[bot]** on GitHub · 2026-10-02 15:38 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/978#pullrequestreview-5393740980) · **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**: `4647ebac-8847-4494-9530-348e5aafba0a` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between e317465d8a773b33482ad367ad2f856154c8bc6d and 7a81c02d71f040b8391dcd63a1caf3f9afcda4fa. </details> <details> <summary>📒 Files selected for processing (9)</summary> * `src/graphics/host_gpu/renderer/pipeline/descriptors.cpp` * `src/graphics/shader/recompiler/ShaderRecompiler.cpp` * `src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemoryHelpers.cpp` * `src/graphics/shader/recompiler/ir/ShaderIR.h` * `src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp` * `tests/ResourceTrackingTests.cpp` * `tests/ShaderRecompilerComputeTests.cpp` </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
Author
Owner

@⁠MehmetCambaz on GitHub · 2026-10-05 18:19 UTC · original
On src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp line 928 (outdated):

@@ -830,12 +850,82 @@ uint32_t LoadIndirectBuffer(ValueEmitContext& ctx, const IR::Inst& inst, uint32_
 		    Select(state, TypeBool(state),
 		           Binary(state, spv::OpIEqual, TypeBool(state), mode, ConstantU32(state, 2)),
 		           nonzero(records), raw_bounds));
-		const auto guest =
+		result[component].address =
 		    Binary(state, spv::OpIAdd, TypeScalarU64(state), base,
 		           Unary(state, spv::OpUConvert, TypeScalarU64(state), address.byte));
-		values[component] = LoadBda(ctx, guest, AndCondition(state, valid_format, in_bounds), 32u);
+		result[component].active = AndCondition(state, valid_format, in_bounds);
+	}
+	return result;
+}
+
+uint32_t LoadIndirectBuffer(ValueEmitContext& ctx, const IR::Inst& inst, uint32_t components) {
+	const auto              parts = DescriptorComponents(ctx, inst, components, 4u);
+	std::array<uint32_t, 4> values {};
+	for (uint32_t component = 0; component < components; component++) {
+		values[component] = LoadBda(ctx, parts[component].address, parts[component].active, 32u);
 	}
-	return ConstructU32Composite(state, components, values);
+	return ConstructU32Composite(ctx.state, components, values);
+}
+
+uint32_t AlignDownToDword(EmitterState& state, uint32_t address) {
+	return Binary(state, spv::OpBitwiseAnd, TypeScalarU64(state), address,
+	              ConstantDeviceAddress(state, ~uint64_t {3}));
+}
+
+// Raw loads through a direct-address resource. A DWORD load reads the dword holding the byte
+// address, like the storage-view path.
+uint32_t DirectLoad(ValueEmitContext& ctx, const IR::Inst& inst, uint32_t components,
+                    uint32_t bits) {
+	auto&      state = ctx.state;
+	const auto type  = components == 1u ? TypeU32(state) : TypeU32Composite(state, components);
+	const auto zero =
+	    components == 1u ? ConstantU32(state, 0) : ConstantU32CompositeZero(state, components);
+	const auto coherent = ctx.Memory(inst).coherent;
+	return EmitValueOrDefaultIfCondition(
+	    state, ctx.Arg(inst, inst.NumArgs() - 1), type, zero, [&]() {
+		    const auto              parts = DescriptorComponents(ctx, inst, components, bits / 8u);
+		    std::array<uint32_t, 4> values {};
+		    for (uint32_t component = 0; component < components; component++) {
+			    const auto address = bits == 32u ? AlignDownToDword(state, parts[component].address)
+			                                     : parts[component].address;
+			    values[component]  = LoadBda(ctx, address, parts[component].active, bits, coherent);
+		    }
+		    return components == 1u ? values[0] : ConstructU32Composite(state, components, values);
+	    });
+}
+
+// S_BUFFER_LOAD through a direct-address resource reads the dword the ScalarBuffer view path
+// reads. Scalar memory ignores the two low address bits, so that dword starts at the aligned
+// base plus the aligned offset, and it must lie within the descriptor's byte span,
+// (STRIDE == 0 ? 1 : STRIDE) * NUM_RECORDS. RDNA3 ISA 8.1.2 states this span for scalar
+// buffer reads; the RDNA2 guide's version of the formula leaves out the STRIDE factor.
+uint32_t DirectScalarLoad(ValueEmitContext& ctx, const IR::Inst& inst) {
+	auto&       state   = ctx.state;
+	const auto& handle  = *inst.Arg(0).ResolveInstruction();
+	const auto  word1   = ctx.Arg(handle, 1);
+	const auto  records = ctx.Arg(handle, 2);
+	const auto  aligned = ConstantU32(state, ~3u);
+	const auto  base    = DeviceAddressFromWords(
+	    state, Binary(state, spv::OpBitwiseAnd, TypeU32(state), ctx.Arg(handle, 0), aligned),
+	    EmitBitFieldUExtract(state, word1, ConstantU32(state, 0), ConstantU32(state, 16)));
+	const auto stride =
+	    EmitBitFieldUExtract(state, word1, ConstantU32(state, 16), ConstantU32(state, 14));
+	const auto unit =
+	    Select(state, TypeU32(state),
+	           Binary(state, spv::OpIEqual, TypeBool(state), stride, ConstantU32(state, 0)),
+	           ConstantU32(state, 1), stride);
+	const auto span   = Binary(state, spv::OpIMul, TypeScalarU64(state),
+	                           Unary(state, spv::OpUConvert, TypeScalarU64(state), unit),
+	                           Unary(state, spv::OpUConvert, TypeScalarU64(state), records));
+	const auto offset = Unary(state, spv::OpUConvert, TypeScalarU64(state),
+	                          Binary(state, spv::OpBitwiseAnd, TypeU32(state),
+	                                 Binary(state, spv::OpIAdd, TypeU32(state), ctx.Arg(inst, 1),
+	                                        ConstantU32(state, ctx.Memory(inst).offset)),
+	                                 aligned));
+	const auto end    = Binary(state, spv::OpIAdd, TypeScalarU64(state), offset,
+	                           ConstantDeviceAddress(state, sizeof(uint32_t)));
+	return LoadBda(ctx, Binary(state, spv::OpIAdd, TypeScalarU64(state), base, offset),
+	               Binary(state, spv::OpULessThanEqual, TypeBool(state), end, span), 32u);

Thanks for flagging this. I traced the current memory-info path after rebasing onto main. S_BUFFER_LOAD is classified as ResourceKind::ScalarBuffer, while MemoryInfo::coherent is populated for the applicable non-atomic ResourceKind::Buffer accesses. As a result, a coherent request cannot currently reach DirectScalarLoad through this scalar path. The direct vector path does forward its reachable coherent state to LoadBda, where it emits the corresponding volatile access. I therefore left the scalar path unchanged.

**@⁠MehmetCambaz** on GitHub · 2026-10-05 18:19 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/978#discussion_r4187299721) On `src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp` line 928 (outdated): ```diff @@ -830,12 +850,82 @@ uint32_t LoadIndirectBuffer(ValueEmitContext& ctx, const IR::Inst& inst, uint32_ Select(state, TypeBool(state), Binary(state, spv::OpIEqual, TypeBool(state), mode, ConstantU32(state, 2)), nonzero(records), raw_bounds)); - const auto guest = + result[component].address = Binary(state, spv::OpIAdd, TypeScalarU64(state), base, Unary(state, spv::OpUConvert, TypeScalarU64(state), address.byte)); - values[component] = LoadBda(ctx, guest, AndCondition(state, valid_format, in_bounds), 32u); + result[component].active = AndCondition(state, valid_format, in_bounds); + } + return result; +} + +uint32_t LoadIndirectBuffer(ValueEmitContext& ctx, const IR::Inst& inst, uint32_t components) { + const auto parts = DescriptorComponents(ctx, inst, components, 4u); + std::array<uint32_t, 4> values {}; + for (uint32_t component = 0; component < components; component++) { + values[component] = LoadBda(ctx, parts[component].address, parts[component].active, 32u); } - return ConstructU32Composite(state, components, values); + return ConstructU32Composite(ctx.state, components, values); +} + +uint32_t AlignDownToDword(EmitterState& state, uint32_t address) { + return Binary(state, spv::OpBitwiseAnd, TypeScalarU64(state), address, + ConstantDeviceAddress(state, ~uint64_t {3})); +} + +// Raw loads through a direct-address resource. A DWORD load reads the dword holding the byte +// address, like the storage-view path. +uint32_t DirectLoad(ValueEmitContext& ctx, const IR::Inst& inst, uint32_t components, + uint32_t bits) { + auto& state = ctx.state; + const auto type = components == 1u ? TypeU32(state) : TypeU32Composite(state, components); + const auto zero = + components == 1u ? ConstantU32(state, 0) : ConstantU32CompositeZero(state, components); + const auto coherent = ctx.Memory(inst).coherent; + return EmitValueOrDefaultIfCondition( + state, ctx.Arg(inst, inst.NumArgs() - 1), type, zero, [&]() { + const auto parts = DescriptorComponents(ctx, inst, components, bits / 8u); + std::array<uint32_t, 4> values {}; + for (uint32_t component = 0; component < components; component++) { + const auto address = bits == 32u ? AlignDownToDword(state, parts[component].address) + : parts[component].address; + values[component] = LoadBda(ctx, address, parts[component].active, bits, coherent); + } + return components == 1u ? values[0] : ConstructU32Composite(state, components, values); + }); +} + +// S_BUFFER_LOAD through a direct-address resource reads the dword the ScalarBuffer view path +// reads. Scalar memory ignores the two low address bits, so that dword starts at the aligned +// base plus the aligned offset, and it must lie within the descriptor's byte span, +// (STRIDE == 0 ? 1 : STRIDE) * NUM_RECORDS. RDNA3 ISA 8.1.2 states this span for scalar +// buffer reads; the RDNA2 guide's version of the formula leaves out the STRIDE factor. +uint32_t DirectScalarLoad(ValueEmitContext& ctx, const IR::Inst& inst) { + auto& state = ctx.state; + const auto& handle = *inst.Arg(0).ResolveInstruction(); + const auto word1 = ctx.Arg(handle, 1); + const auto records = ctx.Arg(handle, 2); + const auto aligned = ConstantU32(state, ~3u); + const auto base = DeviceAddressFromWords( + state, Binary(state, spv::OpBitwiseAnd, TypeU32(state), ctx.Arg(handle, 0), aligned), + EmitBitFieldUExtract(state, word1, ConstantU32(state, 0), ConstantU32(state, 16))); + const auto stride = + EmitBitFieldUExtract(state, word1, ConstantU32(state, 16), ConstantU32(state, 14)); + const auto unit = + Select(state, TypeU32(state), + Binary(state, spv::OpIEqual, TypeBool(state), stride, ConstantU32(state, 0)), + ConstantU32(state, 1), stride); + const auto span = Binary(state, spv::OpIMul, TypeScalarU64(state), + Unary(state, spv::OpUConvert, TypeScalarU64(state), unit), + Unary(state, spv::OpUConvert, TypeScalarU64(state), records)); + const auto offset = Unary(state, spv::OpUConvert, TypeScalarU64(state), + Binary(state, spv::OpBitwiseAnd, TypeU32(state), + Binary(state, spv::OpIAdd, TypeU32(state), ctx.Arg(inst, 1), + ConstantU32(state, ctx.Memory(inst).offset)), + aligned)); + const auto end = Binary(state, spv::OpIAdd, TypeScalarU64(state), offset, + ConstantDeviceAddress(state, sizeof(uint32_t))); + return LoadBda(ctx, Binary(state, spv::OpIAdd, TypeScalarU64(state), base, offset), + Binary(state, spv::OpULessThanEqual, TypeBool(state), end, span), 32u); ``` Thanks for flagging this. I traced the current memory-info path after rebasing onto main. `S_BUFFER_LOAD` is classified as `ResourceKind::ScalarBuffer`, while `MemoryInfo::coherent` is populated for the applicable non-atomic `ResourceKind::Buffer` accesses. As a result, a coherent request cannot currently reach `DirectScalarLoad` through this scalar path. The direct vector path does forward its reachable coherent state to `LoadBda`, where it emits the corresponding volatile access. I therefore left the scalar path unchanged.
@ -941,0 +981,4 @@
// GPU-selected scalar buffer load.
uint32_t DirectScalarLoad(ValueEmitContext& ctx, const IR::Inst& inst) {
return LoadIndirectScalarBuffer(ctx, inst);
}
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-05 18:23 UTC · original

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Pass coherent through DirectScalarLoad.

DirectLoad forwards ctx.Memory(inst).coherent to LoadBda. DirectScalarLoad calls LoadIndirectScalarBuffer, which calls LoadBdaDword with the default coherent = false. A GLC scalar buffer read on a direct-address resource therefore loses volatile semantics. The storage-view path keeps them through PrepareStorageBufferResourceAccess.

Add a coherent parameter to LoadIndirectScalarBuffer. Pass ctx.Memory(inst).coherent from DirectScalarLoad. Leave the IndirectBuffer caller on the default.

Proposed fix
-uint32_t LoadIndirectScalarBuffer(ValueEmitContext& ctx, const IR::Inst& inst) {
+uint32_t LoadIndirectScalarBuffer(ValueEmitContext& ctx, const IR::Inst& inst,
+                                  bool coherent = false) {
@@
-		    return LoadBdaDword(ctx, Binary(state, spv::OpIAdd, TypeU64(state), base, offset));
+		    return LoadBdaDword(ctx, Binary(state, spv::OpIAdd, TypeU64(state), base, offset),
+		                        coherent);
@@
 uint32_t DirectScalarLoad(ValueEmitContext& ctx, const IR::Inst& inst) {
-	return LoadIndirectScalarBuffer(ctx, inst);
+	return LoadIndirectScalarBuffer(ctx, inst, ctx.Memory(inst).coherent);
 }
**@⁠coderabbitai[bot]** on GitHub · 2026-10-05 18:23 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/978#discussion_r4187336847) _🎯 Functional Correctness_ | _🟡 Minor_ | _⚡ Quick win_ **Pass `coherent` through `DirectScalarLoad`.** `DirectLoad` forwards `ctx.Memory(inst).coherent` to `LoadBda`. `DirectScalarLoad` calls `LoadIndirectScalarBuffer`, which calls `LoadBdaDword` with the default `coherent = false`. A GLC scalar buffer read on a direct-address resource therefore loses volatile semantics. The storage-view path keeps them through `PrepareStorageBufferResourceAccess`. Add a `coherent` parameter to `LoadIndirectScalarBuffer`. Pass `ctx.Memory(inst).coherent` from `DirectScalarLoad`. Leave the `IndirectBuffer` caller on the default. <details> <summary>Proposed fix</summary> ```diff -uint32_t LoadIndirectScalarBuffer(ValueEmitContext& ctx, const IR::Inst& inst) { +uint32_t LoadIndirectScalarBuffer(ValueEmitContext& ctx, const IR::Inst& inst, + bool coherent = false) { @@ - return LoadBdaDword(ctx, Binary(state, spv::OpIAdd, TypeU64(state), base, offset)); + return LoadBdaDword(ctx, Binary(state, spv::OpIAdd, TypeU64(state), base, offset), + coherent); @@ uint32_t DirectScalarLoad(ValueEmitContext& ctx, const IR::Inst& inst) { - return LoadIndirectScalarBuffer(ctx, inst); + return LoadIndirectScalarBuffer(ctx, inst, ctx.Memory(inst).coherent); } ``` </details> <!-- fingerprinting:phantom:poseidon:beignet55 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:fa5f68378fc633c83de33adc --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-05 18:23 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: 06043368-8015-4dd9-8708-4a9992c89d59
📥 Commits

Reviewing files that changed from the base of the PR and between 7a81c02d71f040b8391dcd63a1caf3f9afcda4fa and a919940a9b.

📒 Files selected for processing (9)
  • src/graphics/host_gpu/renderer/pipeline/descriptors.cpp
  • src/graphics/shader/recompiler/ShaderRecompiler.cpp
  • src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemoryHelpers.cpp
  • src/graphics/shader/recompiler/ir/ShaderIR.h
  • src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp
  • tests/ResourceTrackingTests.cpp
  • tests/ShaderRecompilerComputeTests.cpp

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

**@⁠coderabbitai[bot]** on GitHub · 2026-10-05 18:23 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/978#pullrequestreview-5418873362) · **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**: `06043368-8015-4dd9-8708-4a9992c89d59` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 7a81c02d71f040b8391dcd63a1caf3f9afcda4fa and a919940a9b6a936b2ae8cf148c6b7c24485d3d86. </details> <details> <summary>📒 Files selected for processing (9)</summary> * `src/graphics/host_gpu/renderer/pipeline/descriptors.cpp` * `src/graphics/shader/recompiler/ShaderRecompiler.cpp` * `src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemoryHelpers.cpp` * `src/graphics/shader/recompiler/ir/ShaderIR.h` * `src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp` * `tests/ResourceTrackingTests.cpp` * `tests/ShaderRecompilerComputeTests.cpp` </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-05 18:30 UTC · original
On src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp line 928 (outdated):

@@ -830,12 +850,82 @@ uint32_t LoadIndirectBuffer(ValueEmitContext& ctx, const IR::Inst& inst, uint32_
 		    Select(state, TypeBool(state),
 		           Binary(state, spv::OpIEqual, TypeBool(state), mode, ConstantU32(state, 2)),
 		           nonzero(records), raw_bounds));
-		const auto guest =
+		result[component].address =
 		    Binary(state, spv::OpIAdd, TypeScalarU64(state), base,
 		           Unary(state, spv::OpUConvert, TypeScalarU64(state), address.byte));
-		values[component] = LoadBda(ctx, guest, AndCondition(state, valid_format, in_bounds), 32u);
+		result[component].active = AndCondition(state, valid_format, in_bounds);
+	}
+	return result;
+}
+
+uint32_t LoadIndirectBuffer(ValueEmitContext& ctx, const IR::Inst& inst, uint32_t components) {
+	const auto              parts = DescriptorComponents(ctx, inst, components, 4u);
+	std::array<uint32_t, 4> values {};
+	for (uint32_t component = 0; component < components; component++) {
+		values[component] = LoadBda(ctx, parts[component].address, parts[component].active, 32u);
 	}
-	return ConstructU32Composite(state, components, values);
+	return ConstructU32Composite(ctx.state, components, values);
+}
+
+uint32_t AlignDownToDword(EmitterState& state, uint32_t address) {
+	return Binary(state, spv::OpBitwiseAnd, TypeScalarU64(state), address,
+	              ConstantDeviceAddress(state, ~uint64_t {3}));
+}
+
+// Raw loads through a direct-address resource. A DWORD load reads the dword holding the byte
+// address, like the storage-view path.
+uint32_t DirectLoad(ValueEmitContext& ctx, const IR::Inst& inst, uint32_t components,
+                    uint32_t bits) {
+	auto&      state = ctx.state;
+	const auto type  = components == 1u ? TypeU32(state) : TypeU32Composite(state, components);
+	const auto zero =
+	    components == 1u ? ConstantU32(state, 0) : ConstantU32CompositeZero(state, components);
+	const auto coherent = ctx.Memory(inst).coherent;
+	return EmitValueOrDefaultIfCondition(
+	    state, ctx.Arg(inst, inst.NumArgs() - 1), type, zero, [&]() {
+		    const auto              parts = DescriptorComponents(ctx, inst, components, bits / 8u);
+		    std::array<uint32_t, 4> values {};
+		    for (uint32_t component = 0; component < components; component++) {
+			    const auto address = bits == 32u ? AlignDownToDword(state, parts[component].address)
+			                                     : parts[component].address;
+			    values[component]  = LoadBda(ctx, address, parts[component].active, bits, coherent);
+		    }
+		    return components == 1u ? values[0] : ConstructU32Composite(state, components, values);
+	    });
+}
+
+// S_BUFFER_LOAD through a direct-address resource reads the dword the ScalarBuffer view path
+// reads. Scalar memory ignores the two low address bits, so that dword starts at the aligned
+// base plus the aligned offset, and it must lie within the descriptor's byte span,
+// (STRIDE == 0 ? 1 : STRIDE) * NUM_RECORDS. RDNA3 ISA 8.1.2 states this span for scalar
+// buffer reads; the RDNA2 guide's version of the formula leaves out the STRIDE factor.
+uint32_t DirectScalarLoad(ValueEmitContext& ctx, const IR::Inst& inst) {
+	auto&       state   = ctx.state;
+	const auto& handle  = *inst.Arg(0).ResolveInstruction();
+	const auto  word1   = ctx.Arg(handle, 1);
+	const auto  records = ctx.Arg(handle, 2);
+	const auto  aligned = ConstantU32(state, ~3u);
+	const auto  base    = DeviceAddressFromWords(
+	    state, Binary(state, spv::OpBitwiseAnd, TypeU32(state), ctx.Arg(handle, 0), aligned),
+	    EmitBitFieldUExtract(state, word1, ConstantU32(state, 0), ConstantU32(state, 16)));
+	const auto stride =
+	    EmitBitFieldUExtract(state, word1, ConstantU32(state, 16), ConstantU32(state, 14));
+	const auto unit =
+	    Select(state, TypeU32(state),
+	           Binary(state, spv::OpIEqual, TypeBool(state), stride, ConstantU32(state, 0)),
+	           ConstantU32(state, 1), stride);
+	const auto span   = Binary(state, spv::OpIMul, TypeScalarU64(state),
+	                           Unary(state, spv::OpUConvert, TypeScalarU64(state), unit),
+	                           Unary(state, spv::OpUConvert, TypeScalarU64(state), records));
+	const auto offset = Unary(state, spv::OpUConvert, TypeScalarU64(state),
+	                          Binary(state, spv::OpBitwiseAnd, TypeU32(state),
+	                                 Binary(state, spv::OpIAdd, TypeU32(state), ctx.Arg(inst, 1),
+	                                        ConstantU32(state, ctx.Memory(inst).offset)),
+	                                 aligned));
+	const auto end    = Binary(state, spv::OpIAdd, TypeScalarU64(state), offset,
+	                           ConstantDeviceAddress(state, sizeof(uint32_t)));
+	return LoadBda(ctx, Binary(state, spv::OpIAdd, TypeScalarU64(state), base, offset),
+	               Binary(state, spv::OpULessThanEqual, TypeBool(state), end, span), 32u);
🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
rg -n -C5 --glob '*.{cpp,h}' '\bcoherent\s*=|\.coherent\b|ResourceKind::ScalarBuffer' src/graphics/shader/recompiler/frontend src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp

Length of output: 14171


@MehmetCambaz Thanks for the clarification. The current code supports your explanation.

In src/graphics/shader/recompiler/frontend/translate/Memory.cpp, Line 93 classifies scalar buffer loads as ResourceKind::ScalarBuffer. Lines 132–133 set MemoryInfo::coherent only for non-atomic ResourceKind::Buffer accesses with GLC or DLC.

Therefore, DirectScalarLoad cannot receive coherent == true through this path. DirectLoad already forwards the reachable coherent state. My finding does not apply, so I withdraw it. No scalar-path change is needed.


✏️ Learnings added
Learnt from: MehmetCambaz
Repo: KytyPS5/KytyPS5 PR: 978
File: src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp:0-0
Timestamp: 2026-10-05T18:30:08.282Z
Learning: In KytyPS5's C++ shader recompiler, src/graphics/shader/recompiler/frontend/translate/Memory.cpp classifies S_BUFFER_LOAD as ResourceKind::ScalarBuffer. MemoryInfo::coherent is populated only for non-atomic ResourceKind::Buffer accesses with decoded.glc or decoded.dlc. Thus, coherent state cannot reach DirectScalarLoad through the scalar buffer path in src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp. DirectLoad forwards the reachable vector-buffer coherent state to the BDA load helpers.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

✅ Review thread resolved.

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-05 18:30 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/978#discussion_r4187397029) On `src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp` line 928 (outdated): ```diff @@ -830,12 +850,82 @@ uint32_t LoadIndirectBuffer(ValueEmitContext& ctx, const IR::Inst& inst, uint32_ Select(state, TypeBool(state), Binary(state, spv::OpIEqual, TypeBool(state), mode, ConstantU32(state, 2)), nonzero(records), raw_bounds)); - const auto guest = + result[component].address = Binary(state, spv::OpIAdd, TypeScalarU64(state), base, Unary(state, spv::OpUConvert, TypeScalarU64(state), address.byte)); - values[component] = LoadBda(ctx, guest, AndCondition(state, valid_format, in_bounds), 32u); + result[component].active = AndCondition(state, valid_format, in_bounds); + } + return result; +} + +uint32_t LoadIndirectBuffer(ValueEmitContext& ctx, const IR::Inst& inst, uint32_t components) { + const auto parts = DescriptorComponents(ctx, inst, components, 4u); + std::array<uint32_t, 4> values {}; + for (uint32_t component = 0; component < components; component++) { + values[component] = LoadBda(ctx, parts[component].address, parts[component].active, 32u); } - return ConstructU32Composite(state, components, values); + return ConstructU32Composite(ctx.state, components, values); +} + +uint32_t AlignDownToDword(EmitterState& state, uint32_t address) { + return Binary(state, spv::OpBitwiseAnd, TypeScalarU64(state), address, + ConstantDeviceAddress(state, ~uint64_t {3})); +} + +// Raw loads through a direct-address resource. A DWORD load reads the dword holding the byte +// address, like the storage-view path. +uint32_t DirectLoad(ValueEmitContext& ctx, const IR::Inst& inst, uint32_t components, + uint32_t bits) { + auto& state = ctx.state; + const auto type = components == 1u ? TypeU32(state) : TypeU32Composite(state, components); + const auto zero = + components == 1u ? ConstantU32(state, 0) : ConstantU32CompositeZero(state, components); + const auto coherent = ctx.Memory(inst).coherent; + return EmitValueOrDefaultIfCondition( + state, ctx.Arg(inst, inst.NumArgs() - 1), type, zero, [&]() { + const auto parts = DescriptorComponents(ctx, inst, components, bits / 8u); + std::array<uint32_t, 4> values {}; + for (uint32_t component = 0; component < components; component++) { + const auto address = bits == 32u ? AlignDownToDword(state, parts[component].address) + : parts[component].address; + values[component] = LoadBda(ctx, address, parts[component].active, bits, coherent); + } + return components == 1u ? values[0] : ConstructU32Composite(state, components, values); + }); +} + +// S_BUFFER_LOAD through a direct-address resource reads the dword the ScalarBuffer view path +// reads. Scalar memory ignores the two low address bits, so that dword starts at the aligned +// base plus the aligned offset, and it must lie within the descriptor's byte span, +// (STRIDE == 0 ? 1 : STRIDE) * NUM_RECORDS. RDNA3 ISA 8.1.2 states this span for scalar +// buffer reads; the RDNA2 guide's version of the formula leaves out the STRIDE factor. +uint32_t DirectScalarLoad(ValueEmitContext& ctx, const IR::Inst& inst) { + auto& state = ctx.state; + const auto& handle = *inst.Arg(0).ResolveInstruction(); + const auto word1 = ctx.Arg(handle, 1); + const auto records = ctx.Arg(handle, 2); + const auto aligned = ConstantU32(state, ~3u); + const auto base = DeviceAddressFromWords( + state, Binary(state, spv::OpBitwiseAnd, TypeU32(state), ctx.Arg(handle, 0), aligned), + EmitBitFieldUExtract(state, word1, ConstantU32(state, 0), ConstantU32(state, 16))); + const auto stride = + EmitBitFieldUExtract(state, word1, ConstantU32(state, 16), ConstantU32(state, 14)); + const auto unit = + Select(state, TypeU32(state), + Binary(state, spv::OpIEqual, TypeBool(state), stride, ConstantU32(state, 0)), + ConstantU32(state, 1), stride); + const auto span = Binary(state, spv::OpIMul, TypeScalarU64(state), + Unary(state, spv::OpUConvert, TypeScalarU64(state), unit), + Unary(state, spv::OpUConvert, TypeScalarU64(state), records)); + const auto offset = Unary(state, spv::OpUConvert, TypeScalarU64(state), + Binary(state, spv::OpBitwiseAnd, TypeU32(state), + Binary(state, spv::OpIAdd, TypeU32(state), ctx.Arg(inst, 1), + ConstantU32(state, ctx.Memory(inst).offset)), + aligned)); + const auto end = Binary(state, spv::OpIAdd, TypeScalarU64(state), offset, + ConstantDeviceAddress(state, sizeof(uint32_t))); + return LoadBda(ctx, Binary(state, spv::OpIAdd, TypeScalarU64(state), base, offset), + Binary(state, spv::OpULessThanEqual, TypeBool(state), end, span), 32u); ``` <details> <summary>🧩 Analysis chain</summary> 🏁 Script executed: ```shell #!/bin/bash rg -n -C5 --glob '*.{cpp,h}' '\bcoherent\s*=|\.coherent\b|ResourceKind::ScalarBuffer' src/graphics/shader/recompiler/frontend src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp ``` Length of output: 14171 --- </details> `@MehmetCambaz` Thanks for the clarification. The current code supports your explanation. In `src/graphics/shader/recompiler/frontend/translate/Memory.cpp`, Line 93 classifies scalar buffer loads as `ResourceKind::ScalarBuffer`. Lines 132–133 set `MemoryInfo::coherent` only for non-atomic `ResourceKind::Buffer` accesses with GLC or DLC. Therefore, `DirectScalarLoad` cannot receive `coherent == true` through this path. `DirectLoad` already forwards the reachable coherent state. My finding does not apply, so I withdraw it. No scalar-path change is needed. --- <details> <summary>✏️ Learnings added</summary> ``` Learnt from: MehmetCambaz Repo: KytyPS5/KytyPS5 PR: 978 File: src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp:0-0 Timestamp: 2026-10-05T18:30:08.282Z Learning: In KytyPS5's C++ shader recompiler, src/graphics/shader/recompiler/frontend/translate/Memory.cpp classifies S_BUFFER_LOAD as ResourceKind::ScalarBuffer. MemoryInfo::coherent is populated only for non-atomic ResourceKind::Buffer accesses with decoded.glc or decoded.dlc. Thus, coherent state cannot reach DirectScalarLoad through the scalar buffer path in src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp. DirectLoad forwards the reachable vector-buffer coherent state to the BDA load helpers. ``` > Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure [review instructions](https://docs.coderabbit.ai/guides/review-instructions). You can manage existing learnings in the [app](https://app.coderabbit.ai/learnings). </details> ✅ Review thread resolved. _You are interacting with an AI system._ <!-- This is an auto-generated reply by CodeRabbit -->

Pull request closed

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