add dynamic buffer descriptor support, enhance memory operations, and add compute tests #690

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

@⁠bipinkrish on GitHub · 2026-09-18 03:28 UTC · original
bipinkrish:feat/dynamic-buffer-descriptors → main · +787 −117 · 9 files · 7 commits · closed without merging

This pull request introduces runtime support for dynamic buffer descriptors and volatile buffer access in the SPIR-V shader backend, along with comprehensive GPU compute test fixtures verifying functionality on native Vulkan hardware.

1. Dynamic Buffer Descriptors

  • Addressing Math: Implemented DynamicBufferByteAddress and DynamicBufferGuestAddress to resolve dynamic 4-dword buffer descriptors (V#) loaded into SGPRs at runtime.
  • Descriptor Flags:
    • add_tid: Incorporates gl_SubgroupInvocationID into the index when bit 23 of dword3 is set.
    • swizzle_enabled: Implements cache-line swizzled address arithmetic matching BufferByteAddress using index_stride from dword3 and bit 31 of dword1.
  • SPIR-V Built-in Setup: Added requirements.subgroup_local_invocation_id = true in SpirvEmitter.cpp for dynamic buffers to ensure gl_SubgroupInvocationID is properly declared in module interfaces.
  • Analysis & Pipeline: Correctly skips static resource binding specialization for dynamic buffers in SpirvEmitter.cpp and ResourceMaterialization.cpp.

2. Memory Operations & BDA Refinements

  • Volatile Operations: Updated BDA accessors (LoadBdaDword, LoadBdaAddress, StoreBdaDword, StoreBdaSubword) with is_volatile flags, applying SPIR-V MemoryAccessVolatileMask and device atomic memory barriers.
  • Subword Stores: Refined StoreBdaSubword to handle 16-bit unaligned boundary crossing (split into 8-bit operations) and atomic bitwise RMW updates for byte/halfword operations.
  • Compute Command Flushing: Ensured proper scheduler command flushing after compute dispatches in renderCompute.cpp.

3. Native GPU Compute Tests (ShaderRecompilerComputeTests.cpp)

Added 4 new compute test fixtures running against real Vulkan discrete hardware:

  1. DynamicBufferLoadStore: Tests dynamic descriptor loading (S_BUFFER_LOAD_DWORDX4), 32-bit dynamic load/store (BUFFER_LOAD_DWORD/BUFFER_STORE_DWORD), and subword byte operations (BUFFER_LOAD_UBYTE/BUFFER_STORE_BYTE).
  2. DynamicBufferLoadStoreDwordX4: Tests 128-bit 4-component vector dynamic load and store (BUFFER_LOAD_DWORDX4/BUFFER_STORE_DWORDX4).
  3. DynamicBufferStoreAddTid: Tests dynamic store with add_tid = 1 across 32 threads, verifying each lane dynamically indexes its record via gl_SubgroupInvocationID.
  4. DynamicBufferLoadStoreSwizzle: Tests dynamic load and store with swizzle_enabled = 1 and index_stride, verifying swizzled byte addressing against host buffers.

AI usage

This investigation and Implementation for this is done by an AI agent, reviewed and tested manually

**@⁠bipinkrish** on GitHub · 2026-09-18 03:28 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/690) `bipinkrish:feat/dynamic-buffer-descriptors` → `main` · +787 −117 · 9 files · 7 commits · closed without merging This pull request introduces runtime support for dynamic buffer descriptors and volatile buffer access in the SPIR-V shader backend, along with comprehensive GPU compute test fixtures verifying functionality on native Vulkan hardware. #### 1. Dynamic Buffer Descriptors - **Addressing Math**: Implemented `DynamicBufferByteAddress` and `DynamicBufferGuestAddress` to resolve dynamic 4-dword buffer descriptors (`V#`) loaded into SGPRs at runtime. - **Descriptor Flags**: - **`add_tid`**: Incorporates `gl_SubgroupInvocationID` into the index when bit 23 of `dword3` is set. - **`swizzle_enabled`**: Implements cache-line swizzled address arithmetic matching `BufferByteAddress` using `index_stride` from `dword3` and bit 31 of `dword1`. - **SPIR-V Built-in Setup**: Added `requirements.subgroup_local_invocation_id = true` in `SpirvEmitter.cpp` for dynamic buffers to ensure `gl_SubgroupInvocationID` is properly declared in module interfaces. - **Analysis & Pipeline**: Correctly skips static resource binding specialization for dynamic buffers in `SpirvEmitter.cpp` and `ResourceMaterialization.cpp`. #### 2. Memory Operations & BDA Refinements - **Volatile Operations**: Updated BDA accessors (`LoadBdaDword`, `LoadBdaAddress`, `StoreBdaDword`, `StoreBdaSubword`) with `is_volatile` flags, applying SPIR-V `MemoryAccessVolatileMask` and device atomic memory barriers. - **Subword Stores**: Refined `StoreBdaSubword` to handle 16-bit unaligned boundary crossing (split into 8-bit operations) and atomic bitwise RMW updates for byte/halfword operations. - **Compute Command Flushing**: Ensured proper scheduler command flushing after compute dispatches in `renderCompute.cpp`. #### 3. Native GPU Compute Tests (`ShaderRecompilerComputeTests.cpp`) Added 4 new compute test fixtures running against real Vulkan discrete hardware: 1. `DynamicBufferLoadStore`: Tests dynamic descriptor loading (`S_BUFFER_LOAD_DWORDX4`), 32-bit dynamic load/store (`BUFFER_LOAD_DWORD`/`BUFFER_STORE_DWORD`), and subword byte operations (`BUFFER_LOAD_UBYTE`/`BUFFER_STORE_BYTE`). 2. `DynamicBufferLoadStoreDwordX4`: Tests 128-bit 4-component vector dynamic load and store (`BUFFER_LOAD_DWORDX4`/`BUFFER_STORE_DWORDX4`). 3. `DynamicBufferStoreAddTid`: Tests dynamic store with `add_tid = 1` across 32 threads, verifying each lane dynamically indexes its record via `gl_SubgroupInvocationID`. 4. `DynamicBufferLoadStoreSwizzle`: Tests dynamic load and store with `swizzle_enabled = 1` and `index_stride`, verifying swizzled byte addressing against host buffers. --- ### AI usage This investigation and Implementation for this is done by an AI agent, reviewed and tested manually
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:29:57 +00:00
github-bot closed this pull request 2026-11-26 09:29:57 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-18 03:42 UTC · original · edited 2026-09-30 07:24 UTC

Review Change StackReview 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: 8336d170-2a2a-4d3c-b8c9-3d2e04835564

📥 Commits

Reviewing files that changed from the base of the PR and between 9cb933c3e4 and a1b3eedd0c.

📒 Files selected for processing (3)
  • src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp
  • tests/ShaderRecompilerComputeTests.cpp
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp

Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.


📝 Walkthrough

Walkthrough

The change adds dynamic_buffer and glc metadata to memory operations. Resource tracking detects dynamic descriptor origins and preserves them as DMA-backed buffers. SPIR-V emission supports dynamic-buffer BDA loads, stores, wide accesses, formatted accesses, and 32-bit atomics. Volatile operations emit barriers. Unsupported dynamic operations fail explicitly. Compute tests cover descriptor addressing, add_tid, swizzling, and wide transfers. DispatchDirect waits for scheduled command execution.

Suggested reviewers: nmzik

Priority: ➖ Normal

Change: Feature

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 1.79% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 56 functions across 8 files. (1 skipped: 1… 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 changes: dynamic buffer descriptor support, memory operation improvements, and compute tests. It is specific and related to the changeset.
Description check ✅ Passed The description directly explains the dynamic buffer support, volatile memory operations, SPIR-V changes, scheduler flushing, and added compute tests. It is detailed and related to the changeset.
Full details: Docstring Coverage

Explanation

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


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-09-18 03:42 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/690#issuecomment-5724819814) · edited 2026-09-30 07:24 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/690#gh-light-mode-only"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg" alt="Review Change Stack" width="202" height="32"></a><a href="https://app.coderabbit.ai/change-stack/KytyPS5/KytyPS5/pull/690#gh-dark-mode-only"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui-dark.svg" alt="Review Change Stack" width="202" 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**: `8336d170-2a2a-4d3c-b8c9-3d2e04835564` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 9cb933c3e44612b4fd21a3a6b6b205aac1eea828 and a1b3eedd0cb9a5d5b0c5d6c56d3a12d842138696. </details> <details> <summary>📒 Files selected for processing (3)</summary> * `src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp` * `tests/ShaderRecompilerComputeTests.cpp` </details> <details> <summary>🚧 Files skipped from review as they are similar to previous changes (1)</summary> * src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp </details> **Included review availability:** Your plan provides up to 10 included reviews per hour; 8 remain after this review. </details> --- <!-- recent_review_end --> <!-- walkthrough_start --> <details> <summary>📝 Walkthrough</summary> ## Walkthrough The change adds `dynamic_buffer` and `glc` metadata to memory operations. Resource tracking detects dynamic descriptor origins and preserves them as DMA-backed buffers. SPIR-V emission supports dynamic-buffer BDA loads, stores, wide accesses, formatted accesses, and 32-bit atomics. Volatile operations emit barriers. Unsupported dynamic operations fail explicitly. Compute tests cover descriptor addressing, `add_tid`, swizzling, and wide transfers. `DispatchDirect` waits for scheduled command execution. **Suggested reviewers:** `nmzik` </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ➖ Normal <!-- change_assessment_commit:"a1b3eedd0cb9a5d5b0c5d6c56d3a12d842138696" --> **Change:** Feature <!-- change_assessment_end --> <!-- pre_merge_checks_walkthrough_start --> <details> <summary>🚥 Pre-merge checks | ✅ 4 | ❌ 1</summary> ### ❌ Failed checks (1 warning) | Check name | Status | Explanation | Resolution | | :----------------: | :--------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------- | | Docstring Coverage | ⚠️ Warning | Docstring coverage is 1.79% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 56 functions across 8 files. (1 skipped: 1… | 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 changes: dynamic buffer descriptor support, memory operation improvements, and compute tests. It is specific and related to the changeset. | | Description check | ✅ Passed | The description directly explains the dynamic buffer support, volatile memory operations, SPIR-V changes, scheduler flushing, and added compute tests. It is detailed and related to the changeset. | </details> <details> <summary>Full details: Docstring Coverage</summary> **Explanation** Docstring coverage is 1.79% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 56 functions across 8 files. (1 skipped: 1 too large.) </details> </details> <!-- pre_merge_checks_walkthrough_end --> <!-- tips_start --> --- Thanks for using [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=KytyPS5/KytyPS5&utm_content=690)! 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 -->
@ -393,6 +397,7 @@ void RenderExecutor::DispatchDirect(uint64_t submit_id, CommandBuffer& buffer,
// The removed host fence also ordered read-only dispatches before later writers.
ShaderAccessBarrier(vk_buffer, vk::PipelineStageFlagBits::eComputeShader);
ResetBindings();
m_context.GetCommandScheduler().FlushAndWait();
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-18 03:42 UTC · original · edited 2026-09-18 03:59 UTC

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- renderCompute.cpp relevant symbols ---'
rg -n -C 12 'TryConsumeComputeImageClear|ClearImageFromBuffer|ClearImage|FlushAndWait|DispatchDirect' src/graphics/host_gpu/renderer/renderCompute.cpp
printf '%s\n' '--- helper definitions and declarations ---'
rg -n -C 8 '(^|[[:space:]])(ClearImageFromBuffer|ClearImage)[[:space:]]*\(' src
printf '%s\n' '--- candidate files ---'
git ls-files | rg '(^|/)(renderCompute\.cpp|.*(cache|Cache|command|Command).*\.(cpp|h|hpp))$' | head -80

Repository: KytyPS5/KytyPS5

Length of output: 18986


🤖 get_repo_knowledge executed:

get_repo_knowledge KytyPS5/KytyPS5 /tmp/coderabbit-repo-knowledge/kytyps5-kytyps5-b6cddd0b/architecture

Length of output: 6888


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- texture clear implementations ---'
sed -n '1450,1605p' src/graphics/host_gpu/renderer/cache/textureCache.cpp
printf '%s\n' '--- ClearImageFromBuffer references and nearby implementation ---'
rg -n -C 20 'ClearImageFromBuffer' src/graphics/host_gpu/renderer/cache/textureCache.cpp src/graphics/host_gpu/renderer/cache/textureCache.h
printf '%s\n' '--- scheduler FlushAndWait contract ---'
rg -n -C 20 'FlushAndWait|PopPendingOperations|Current\(' src/graphics/host_gpu/renderer/commandScheduler.h src/graphics/host_gpu/renderer/commandScheduler.cpp
printf '%s\n' '--- command-buffer execution declarations ---'
rg -n -C 8 'class CommandBuffer|EndRendering|GetCommandBuffer|vk::CommandBuffer|Submit|Flush' src/graphics/host_gpu/renderer | head -240

Repository: KytyPS5/KytyPS5

Length of output: 50371


Synchronize the image-clear fast path. When TryConsumeComputeImageClear returns true, TextureCache::ClearImage records Vulkan clear work through the active CommandBuffer; ClearImageFromBuffer calls it before returning true. DispatchDirect then returns at lines 274-277 without calling FlushAndWait(), so the clear can remain incomplete when the caller continues. Move the wait to the shared successful path or add it before this return.

✅ Addressed in commits de1545e to cf51df7

**@⁠coderabbitai[bot]** on GitHub · 2026-09-18 03:42 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/690#discussion_r4043615453) · edited 2026-09-18 03:59 UTC _🩺 Stability & Availability_ | _🟠 Major_ | _⚡ Quick win_ <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash #!/bin/bash set -eu printf '%s\n' '--- renderCompute.cpp relevant symbols ---' rg -n -C 12 'TryConsumeComputeImageClear|ClearImageFromBuffer|ClearImage|FlushAndWait|DispatchDirect' src/graphics/host_gpu/renderer/renderCompute.cpp printf '%s\n' '--- helper definitions and declarations ---' rg -n -C 8 '(^|[[:space:]])(ClearImageFromBuffer|ClearImage)[[:space:]]*\(' src printf '%s\n' '--- candidate files ---' git ls-files | rg '(^|/)(renderCompute\.cpp|.*(cache|Cache|command|Command).*\.(cpp|h|hpp))$' | head -80 ``` Repository: KytyPS5/KytyPS5 Length of output: 18986 --- 🤖 get_repo_knowledge executed: `get_repo_knowledge KytyPS5/KytyPS5 /tmp/coderabbit-repo-knowledge/kytyps5-kytyps5-b6cddd0b/architecture` Length of output: 6888 --- 🏁 Script executed: ```bash #!/bin/bash set -eu printf '%s\n' '--- texture clear implementations ---' sed -n '1450,1605p' src/graphics/host_gpu/renderer/cache/textureCache.cpp printf '%s\n' '--- ClearImageFromBuffer references and nearby implementation ---' rg -n -C 20 'ClearImageFromBuffer' src/graphics/host_gpu/renderer/cache/textureCache.cpp src/graphics/host_gpu/renderer/cache/textureCache.h printf '%s\n' '--- scheduler FlushAndWait contract ---' rg -n -C 20 'FlushAndWait|PopPendingOperations|Current\(' src/graphics/host_gpu/renderer/commandScheduler.h src/graphics/host_gpu/renderer/commandScheduler.cpp printf '%s\n' '--- command-buffer execution declarations ---' rg -n -C 8 'class CommandBuffer|EndRendering|GetCommandBuffer|vk::CommandBuffer|Submit|Flush' src/graphics/host_gpu/renderer | head -240 ``` Repository: KytyPS5/KytyPS5 Length of output: 50371 --- </details> **Synchronize the image-clear fast path.** When `TryConsumeComputeImageClear` returns true, `TextureCache::ClearImage` records Vulkan clear work through the active `CommandBuffer`; `ClearImageFromBuffer` calls it before returning true. `DispatchDirect` then returns at lines 274-277 without calling `FlushAndWait()`, so the clear can remain incomplete when the caller continues. Move the wait to the shared successful path or add it before this return. <!-- fingerprinting:phantom:triton:caracal --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:dd3e20df158cac2a8e02b9c5 --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commits de1545e to cf51df7
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-18 03:42 UTC · original · edited 2026-09-18 03:48 UTC
On src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp line 301 (outdated):

@@ -179,61 +178,176 @@ uint32_t GetBdaPointer(ValueEmitContext& ctx, uint32_t address) {
 	return result;
 }
 
-uint32_t LoadBdaDword(ValueEmitContext& ctx, uint32_t address) {
-	auto&      state   = ctx.state;
-	const auto bda     = GetBdaPointer(ctx, address);
+uint32_t LoadBdaDword(ValueEmitContext& ctx, uint32_t address, bool is_volatile = false) {
+	auto&      state = ctx.state;
+	const auto bda   = GetBdaPointer(ctx, address);
 	const auto present =
 	    Binary(state, spv::OpINotEqual, TypeBool(state), bda, ConstantDeviceAddress(state, 0));
 	return EmitValueOrZeroIfCondition(state, present, [&]() {
+		if (is_volatile) {
+			EmitDeviceAtomicMemoryBarrier(state);
+		}
 		const auto pointer = state.builder.AllocateId();
 		state.builder.AddFunction(spv::OpConvertUToPtr, TypePhysicalU32Pointer(state), pointer,
 		                          bda);
 		const auto         value     = state.builder.AllocateId();
 		constexpr uint32_t alignment = sizeof(uint32_t);
-		state.builder.AddFunction(spv::OpLoad, TypeU32(state), value, pointer,
-		                          spv::MemoryAccessAlignedMask, alignment);
+		const uint32_t     access_mask =
+		    is_volatile ? (spv::MemoryAccessAlignedMask | spv::MemoryAccessVolatileMask)
+		                : spv::MemoryAccessAlignedMask;
+		state.builder.AddFunction(spv::OpLoad, TypeU32(state), value, pointer, access_mask,
+		                          alignment);
 		return value;
 	});
 }
 
+uint32_t LoadBdaAddress(ValueEmitContext& ctx, uint32_t address, uint32_t bits,
+                        bool is_volatile = false) {
+	auto&      state   = ctx.state;
+	const auto aligned = Binary(state, spv::OpBitwiseAnd, TypeScalarU64(state), address,
+	                            ConstantDeviceAddress(state, ~uint64_t {3}));
+	const auto first   = LoadBdaDword(ctx, aligned, is_volatile);
+	const auto byte =
+	    Binary(state, spv::OpBitwiseAnd, TypeU32(state),
+	           Unary(state, spv::OpUConvert, TypeU32(state), address), ConstantU32(state, 3));
+	const auto crosses =
+	    bits == 8u ? ConstantBool(state, false)
+	               : Binary(state, bits == 16u ? spv::OpUGreaterThan : spv::OpINotEqual,
+	                        TypeBool(state), byte, ConstantU32(state, bits == 16u ? 2u : 0u));
+	const auto second = EmitValueOrZeroIfCondition(state, crosses, [&]() {
+		return LoadBdaDword(ctx,
+		                    Binary(state, spv::OpIAdd, TypeScalarU64(state), aligned,
+		                           ConstantDeviceAddress(state, sizeof(uint32_t))),
+		                    is_volatile);
+	});
+	const auto shift =
+	    Binary(state, spv::OpShiftLeftLogical, TypeU32(state), byte, ConstantU32(state, 3));
+	const auto upper_shift =
+	    Binary(state, spv::OpShiftLeftLogical, TypeU32(state),
+	           Binary(state, spv::OpBitwiseAnd, TypeU32(state),
+	                  Binary(state, spv::OpISub, TypeU32(state), ConstantU32(state, 4), byte),
+	                  ConstantU32(state, 3)),
+	           ConstantU32(state, 3));
+	const auto merged =
+	    Binary(state, spv::OpBitwiseOr, TypeU32(state),
+	           Binary(state, spv::OpShiftRightLogical, TypeU32(state), first, shift),
+	           Binary(state, spv::OpShiftLeftLogical, TypeU32(state), second, upper_shift));
+	return bits == 32u ? merged
+	                   : Binary(state, spv::OpBitwiseAnd, TypeU32(state), merged,
+	                            ConstantU32(state, bits == 8u ? 0xffu : 0xffffu));
+}
+
 uint32_t LoadBda(ValueEmitContext& ctx, const IR::Inst& inst, const IR::MemoryInfo& mem,
-	             uint32_t bits) {
+                 uint32_t bits) {
 	auto&      state   = ctx.state;
 	const auto address = GuestAddress(ctx, inst, mem);
 	const auto active  = ctx.Arg(inst, inst.NumArgs() - 1);
-	return EmitValueOrZeroIfCondition(state, active, [&]() {
-		const auto aligned = Binary(state, spv::OpBitwiseAnd, TypeScalarU64(state), address,
-		                            ConstantDeviceAddress(state, ~uint64_t {3}));
-		const auto first   = LoadBdaDword(ctx, aligned);
+	return EmitValueOrZeroIfCondition(
+	    state, active, [&]() { return LoadBdaAddress(ctx, address, bits, mem.glc); });
+}
+
+void StoreBdaDword(ValueEmitContext& ctx, uint32_t address, uint32_t data,
+                   bool is_volatile = false) {
+	auto&      state = ctx.state;
+	const auto bda   = GetBdaPointer(ctx, address);
+	const auto present =
+	    Binary(state, spv::OpINotEqual, TypeBool(state), bda, ConstantDeviceAddress(state, 0));
+	EmitIfCondition(state, present, [&]() {
+		const auto pointer = state.builder.AllocateId();
+		state.builder.AddFunction(spv::OpConvertUToPtr, TypePhysicalU32Pointer(state), pointer,
+		                          bda);
+		constexpr uint32_t alignment = sizeof(uint32_t);
+		const uint32_t     access_mask =
+		    is_volatile ? (spv::MemoryAccessAlignedMask | spv::MemoryAccessVolatileMask)
+		                : spv::MemoryAccessAlignedMask;
+		state.builder.AddFunction(spv::OpStore, pointer, data, access_mask, alignment);
+		if (is_volatile) {
+			EmitDeviceAtomicMemoryBarrier(state);
+		}
+	});
+}
+
+void StoreBdaSubword(ValueEmitContext& ctx, uint32_t address, uint32_t bits, uint32_t data) {
+	auto&      state   = ctx.state;
+	const auto aligned = Binary(state, spv::OpBitwiseAnd, TypeScalarU64(state), address,
+	                            ConstantDeviceAddress(state, ~uint64_t {3}));
+	const auto bda     = GetBdaPointer(ctx, aligned);
+	const auto present =
+	    Binary(state, spv::OpINotEqual, TypeBool(state), bda, ConstantDeviceAddress(state, 0));
+	EmitIfCondition(state, present, [&]() {
+		const auto pointer = state.builder.AllocateId();
+		state.builder.AddFunction(spv::OpConvertUToPtr, TypePhysicalU32Pointer(state), pointer,
+		                          bda);
+		constexpr uint32_t alignment = sizeof(uint32_t);
+		const auto         old       = state.builder.AllocateId();
+		state.builder.AddFunction(spv::OpLoad, TypeU32(state), old, pointer,
+		                          spv::MemoryAccessAlignedMask, alignment);
 		const auto byte =
 		    Binary(state, spv::OpBitwiseAnd, TypeU32(state),
 		           Unary(state, spv::OpUConvert, TypeU32(state), address), ConstantU32(state, 3));
-		const auto crosses =
-		    bits == 8u ? ConstantBool(state, false)
-		               : Binary(state, bits == 16u ? spv::OpUGreaterThan : spv::OpINotEqual,
-		                        TypeBool(state), byte, ConstantU32(state, bits == 16u ? 2u : 0u));
-		const auto second = EmitValueOrZeroIfCondition(state, crosses, [&]() {
-			return LoadBdaDword(ctx, Binary(state, spv::OpIAdd, TypeScalarU64(state), aligned,
-			                                ConstantDeviceAddress(state, sizeof(uint32_t))));
-		});
 		const auto shift =
 		    Binary(state, spv::OpShiftLeftLogical, TypeU32(state), byte, ConstantU32(state, 3));
-		const auto upper_shift =
-		    Binary(state, spv::OpShiftLeftLogical, TypeU32(state),
-		           Binary(state, spv::OpBitwiseAnd, TypeU32(state),
-		                  Binary(state, spv::OpISub, TypeU32(state), ConstantU32(state, 4), byte),
-		                  ConstantU32(state, 3)),
-		           ConstantU32(state, 3));
-		const auto merged =
-		    Binary(state, spv::OpBitwiseOr, TypeU32(state),
-		           Binary(state, spv::OpShiftRightLogical, TypeU32(state), first, shift),
-		           Binary(state, spv::OpShiftLeftLogical, TypeU32(state), second, upper_shift));
-		return bits == 32u ? merged
-		                   : Binary(state, spv::OpBitwiseAnd, TypeU32(state), merged,
-		                            ConstantU32(state, bits == 8u ? 0xffu : 0xffffu));
+		const auto mask   = Binary(state, spv::OpShiftLeftLogical, TypeU32(state),
+		                           ConstantU32(state, bits == 8u ? 0xffu : 0xffffu), shift);
+		const auto value  = Binary(state, spv::OpShiftLeftLogical, TypeU32(state),
+		                           Binary(state, spv::OpBitwiseAnd, TypeU32(state), data,
+		                                  ConstantU32(state, bits == 8u ? 0xffu : 0xffffu)),
+		                           shift);
+		const auto merged = Binary(state, spv::OpBitwiseOr, TypeU32(state),
+		                           Binary(state, spv::OpBitwiseAnd, TypeU32(state), old,
+		                                  Unary(state, spv::OpNot, TypeU32(state), mask)),
+		                           value);
+		state.builder.AddFunction(spv::OpStore, pointer, merged, spv::MemoryAccessAlignedMask,
+		                          alignment);

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

🔎 Supported by static analysis

🏁 Script executed:

sed -n '170,360p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp
sed -n '600,690p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp
rg -n 'StoreBdaSubword|StoreSubwordInBounds|AtomicUpdate|StoreSubwordPrepared' src/graphics/shader/recompiler/backend/spirv

Repository: KytyPS5/KytyPS5

Length of output: 16308


🏁 Script executed:

#!/bin/bash
sed -n '500,545p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h
sed -n '560,715p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp
rg -n -C 4 'StoreSubword\(|StoreByte|StoreShort|StoreDword|StoreBdaSubword|dynamic_buffer|MemoryInfo' src/graphics/shader/recompiler | head -n 500

Repository: KytyPS5/KytyPS5

Length of output: 50371


🏁 Script executed:

#!/bin/bash
sed -n '520,575p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h
sed -n '95,125p' src/graphics/shader/recompiler/frontend/translate/Memory.cpp
sed -n '425,512p' src/graphics/shader/recompiler/frontend/translate/Memory.cpp

Repository: KytyPS5/KytyPS5

Length of output: 7280


Handle 16-bit stores that cross a dword boundary. BUFFER_STORE passes the raw buffer address to the dynamic path, and StoreSubword forwards it to StoreBdaSubword without an alignment guard. When address & 3 == 3, the 16-bit mask and value become 0xffff << 24; only the low byte fits in the first dword, and no store updates the next dword. Split this case into two byte merges, updating both aligned dwords with separate BDA presence checks.

✅ Addressed in commits de1545e to e94eaed

**@⁠coderabbitai[bot]** on GitHub · 2026-09-18 03:42 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/690#discussion_r4043615461) · edited 2026-09-18 03:48 UTC On `src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp` line 301 (outdated): ```diff @@ -179,61 +178,176 @@ uint32_t GetBdaPointer(ValueEmitContext& ctx, uint32_t address) { return result; } -uint32_t LoadBdaDword(ValueEmitContext& ctx, uint32_t address) { - auto& state = ctx.state; - const auto bda = GetBdaPointer(ctx, address); +uint32_t LoadBdaDword(ValueEmitContext& ctx, uint32_t address, bool is_volatile = false) { + auto& state = ctx.state; + const auto bda = GetBdaPointer(ctx, address); const auto present = Binary(state, spv::OpINotEqual, TypeBool(state), bda, ConstantDeviceAddress(state, 0)); return EmitValueOrZeroIfCondition(state, present, [&]() { + if (is_volatile) { + EmitDeviceAtomicMemoryBarrier(state); + } const auto pointer = state.builder.AllocateId(); state.builder.AddFunction(spv::OpConvertUToPtr, TypePhysicalU32Pointer(state), pointer, bda); const auto value = state.builder.AllocateId(); constexpr uint32_t alignment = sizeof(uint32_t); - state.builder.AddFunction(spv::OpLoad, TypeU32(state), value, pointer, - spv::MemoryAccessAlignedMask, alignment); + const uint32_t access_mask = + is_volatile ? (spv::MemoryAccessAlignedMask | spv::MemoryAccessVolatileMask) + : spv::MemoryAccessAlignedMask; + state.builder.AddFunction(spv::OpLoad, TypeU32(state), value, pointer, access_mask, + alignment); return value; }); } +uint32_t LoadBdaAddress(ValueEmitContext& ctx, uint32_t address, uint32_t bits, + bool is_volatile = false) { + auto& state = ctx.state; + const auto aligned = Binary(state, spv::OpBitwiseAnd, TypeScalarU64(state), address, + ConstantDeviceAddress(state, ~uint64_t {3})); + const auto first = LoadBdaDword(ctx, aligned, is_volatile); + const auto byte = + Binary(state, spv::OpBitwiseAnd, TypeU32(state), + Unary(state, spv::OpUConvert, TypeU32(state), address), ConstantU32(state, 3)); + const auto crosses = + bits == 8u ? ConstantBool(state, false) + : Binary(state, bits == 16u ? spv::OpUGreaterThan : spv::OpINotEqual, + TypeBool(state), byte, ConstantU32(state, bits == 16u ? 2u : 0u)); + const auto second = EmitValueOrZeroIfCondition(state, crosses, [&]() { + return LoadBdaDword(ctx, + Binary(state, spv::OpIAdd, TypeScalarU64(state), aligned, + ConstantDeviceAddress(state, sizeof(uint32_t))), + is_volatile); + }); + const auto shift = + Binary(state, spv::OpShiftLeftLogical, TypeU32(state), byte, ConstantU32(state, 3)); + const auto upper_shift = + Binary(state, spv::OpShiftLeftLogical, TypeU32(state), + Binary(state, spv::OpBitwiseAnd, TypeU32(state), + Binary(state, spv::OpISub, TypeU32(state), ConstantU32(state, 4), byte), + ConstantU32(state, 3)), + ConstantU32(state, 3)); + const auto merged = + Binary(state, spv::OpBitwiseOr, TypeU32(state), + Binary(state, spv::OpShiftRightLogical, TypeU32(state), first, shift), + Binary(state, spv::OpShiftLeftLogical, TypeU32(state), second, upper_shift)); + return bits == 32u ? merged + : Binary(state, spv::OpBitwiseAnd, TypeU32(state), merged, + ConstantU32(state, bits == 8u ? 0xffu : 0xffffu)); +} + uint32_t LoadBda(ValueEmitContext& ctx, const IR::Inst& inst, const IR::MemoryInfo& mem, - uint32_t bits) { + uint32_t bits) { auto& state = ctx.state; const auto address = GuestAddress(ctx, inst, mem); const auto active = ctx.Arg(inst, inst.NumArgs() - 1); - return EmitValueOrZeroIfCondition(state, active, [&]() { - const auto aligned = Binary(state, spv::OpBitwiseAnd, TypeScalarU64(state), address, - ConstantDeviceAddress(state, ~uint64_t {3})); - const auto first = LoadBdaDword(ctx, aligned); + return EmitValueOrZeroIfCondition( + state, active, [&]() { return LoadBdaAddress(ctx, address, bits, mem.glc); }); +} + +void StoreBdaDword(ValueEmitContext& ctx, uint32_t address, uint32_t data, + bool is_volatile = false) { + auto& state = ctx.state; + const auto bda = GetBdaPointer(ctx, address); + const auto present = + Binary(state, spv::OpINotEqual, TypeBool(state), bda, ConstantDeviceAddress(state, 0)); + EmitIfCondition(state, present, [&]() { + const auto pointer = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpConvertUToPtr, TypePhysicalU32Pointer(state), pointer, + bda); + constexpr uint32_t alignment = sizeof(uint32_t); + const uint32_t access_mask = + is_volatile ? (spv::MemoryAccessAlignedMask | spv::MemoryAccessVolatileMask) + : spv::MemoryAccessAlignedMask; + state.builder.AddFunction(spv::OpStore, pointer, data, access_mask, alignment); + if (is_volatile) { + EmitDeviceAtomicMemoryBarrier(state); + } + }); +} + +void StoreBdaSubword(ValueEmitContext& ctx, uint32_t address, uint32_t bits, uint32_t data) { + auto& state = ctx.state; + const auto aligned = Binary(state, spv::OpBitwiseAnd, TypeScalarU64(state), address, + ConstantDeviceAddress(state, ~uint64_t {3})); + const auto bda = GetBdaPointer(ctx, aligned); + const auto present = + Binary(state, spv::OpINotEqual, TypeBool(state), bda, ConstantDeviceAddress(state, 0)); + EmitIfCondition(state, present, [&]() { + const auto pointer = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpConvertUToPtr, TypePhysicalU32Pointer(state), pointer, + bda); + constexpr uint32_t alignment = sizeof(uint32_t); + const auto old = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpLoad, TypeU32(state), old, pointer, + spv::MemoryAccessAlignedMask, alignment); const auto byte = Binary(state, spv::OpBitwiseAnd, TypeU32(state), Unary(state, spv::OpUConvert, TypeU32(state), address), ConstantU32(state, 3)); - const auto crosses = - bits == 8u ? ConstantBool(state, false) - : Binary(state, bits == 16u ? spv::OpUGreaterThan : spv::OpINotEqual, - TypeBool(state), byte, ConstantU32(state, bits == 16u ? 2u : 0u)); - const auto second = EmitValueOrZeroIfCondition(state, crosses, [&]() { - return LoadBdaDword(ctx, Binary(state, spv::OpIAdd, TypeScalarU64(state), aligned, - ConstantDeviceAddress(state, sizeof(uint32_t)))); - }); const auto shift = Binary(state, spv::OpShiftLeftLogical, TypeU32(state), byte, ConstantU32(state, 3)); - const auto upper_shift = - Binary(state, spv::OpShiftLeftLogical, TypeU32(state), - Binary(state, spv::OpBitwiseAnd, TypeU32(state), - Binary(state, spv::OpISub, TypeU32(state), ConstantU32(state, 4), byte), - ConstantU32(state, 3)), - ConstantU32(state, 3)); - const auto merged = - Binary(state, spv::OpBitwiseOr, TypeU32(state), - Binary(state, spv::OpShiftRightLogical, TypeU32(state), first, shift), - Binary(state, spv::OpShiftLeftLogical, TypeU32(state), second, upper_shift)); - return bits == 32u ? merged - : Binary(state, spv::OpBitwiseAnd, TypeU32(state), merged, - ConstantU32(state, bits == 8u ? 0xffu : 0xffffu)); + const auto mask = Binary(state, spv::OpShiftLeftLogical, TypeU32(state), + ConstantU32(state, bits == 8u ? 0xffu : 0xffffu), shift); + const auto value = Binary(state, spv::OpShiftLeftLogical, TypeU32(state), + Binary(state, spv::OpBitwiseAnd, TypeU32(state), data, + ConstantU32(state, bits == 8u ? 0xffu : 0xffffu)), + shift); + const auto merged = Binary(state, spv::OpBitwiseOr, TypeU32(state), + Binary(state, spv::OpBitwiseAnd, TypeU32(state), old, + Unary(state, spv::OpNot, TypeU32(state), mask)), + value); + state.builder.AddFunction(spv::OpStore, pointer, merged, spv::MemoryAccessAlignedMask, + alignment); ``` _🗄️ Data Integrity & Integration_ | _🟠 Major_ | _🏗️ Heavy lift_ <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash sed -n '170,360p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp sed -n '600,690p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp rg -n 'StoreBdaSubword|StoreSubwordInBounds|AtomicUpdate|StoreSubwordPrepared' src/graphics/shader/recompiler/backend/spirv ``` Repository: KytyPS5/KytyPS5 Length of output: 16308 --- 🏁 Script executed: ```bash #!/bin/bash sed -n '500,545p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h sed -n '560,715p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp rg -n -C 4 'StoreSubword\(|StoreByte|StoreShort|StoreDword|StoreBdaSubword|dynamic_buffer|MemoryInfo' src/graphics/shader/recompiler | head -n 500 ``` Repository: KytyPS5/KytyPS5 Length of output: 50371 --- 🏁 Script executed: ```bash #!/bin/bash sed -n '520,575p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h sed -n '95,125p' src/graphics/shader/recompiler/frontend/translate/Memory.cpp sed -n '425,512p' src/graphics/shader/recompiler/frontend/translate/Memory.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 7280 --- </details> **Handle 16-bit stores that cross a dword boundary.** `BUFFER_STORE` passes the raw buffer address to the dynamic path, and `StoreSubword` forwards it to `StoreBdaSubword` without an alignment guard. When `address & 3 == 3`, the 16-bit mask and value become `0xffff << 24`; only the low byte fits in the first dword, and no store updates the next dword. Split this case into two byte merges, updating both aligned dwords with separate BDA presence checks. <!-- fingerprinting:phantom:medusa:quokka --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:32efddfa4b79c083748da298 --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commits de1545e to e94eaed
Author
Owner

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

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (1)

🟠 Major · Handle dynamic_buffer before resource descriptor resolution. · spirvEmitterMemory.cpp:1118-1175

src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp:1118-1175
🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Handle dynamic_buffer before resource descriptor resolution.

ResourceTracking::Collect marks a dynamic descriptor and returns before it patches mem.resource. EmitBufferAtomic64 directly calls PrepareStorageBufferResourceAccess. EmitBufferFloatAtomic reaches it through EmitAtomicUpdate and EmitAtomicAccess. EmitReadConstBuffer sets mem.kind to ScalarBuffer and reaches it through PrepareMemoryResourceAccess.

ResourceForDescriptor searches the buffer descriptor group for the stale mem.resource. If it is absent, ExitDescriptorBindingFailure aborts emission. If it matches a static resource, the emitter selects that resource's descriptor element and accesses the wrong buffer.

Route these operations through supported BDA paths, or reject dynamic_buffer explicitly.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Advanced

Run ID: 7a7e8763-f299-4dcd-8f86-fb643a733b31

📥 Commits

Reviewing files that changed from the base of the PR and between 104530eafc and b23ee5aa8d.

📒 Files selected for processing (7)
  • src/graphics/host_gpu/renderer/renderCompute.cpp
  • src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp
  • src/graphics/shader/recompiler/frontend/translate/Memory.cpp
  • src/graphics/shader/recompiler/ir/ShaderIR.h
  • src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp
  • src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp

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

**@⁠coderabbitai[bot]** on GitHub · 2026-09-18 03:42 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/690#pullrequestreview-5244028453) · **reviewed** **Actionable comments posted: 2** > [!CAUTION] > Some comments are outside the diff and can’t be posted inline due to GitHub limitations. > > **⚠️ Outside diff range comments (1)** > > <details> > <summary><em>🟠 Major</em> · Handle <code>dynamic_buffer</code> before resource descriptor resolution. · <code>spirvEmitterMemory.cpp:1118-1175</code></summary><blockquote> > > `src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp:1118-1175` > _🩺 Stability & Availability_ | _🟠 Major_ | _🏗️ Heavy lift_ > > **Handle `dynamic_buffer` before resource descriptor resolution.** > > `ResourceTracking::Collect` marks a dynamic descriptor and returns before it patches `mem.resource`. `EmitBufferAtomic64` directly calls `PrepareStorageBufferResourceAccess`. `EmitBufferFloatAtomic` reaches it through `EmitAtomicUpdate` and `EmitAtomicAccess`. `EmitReadConstBuffer` sets `mem.kind` to `ScalarBuffer` and reaches it through `PrepareMemoryResourceAccess`. > > `ResourceForDescriptor` searches the buffer descriptor group for the stale `mem.resource`. If it is absent, `ExitDescriptorBindingFailure` aborts emission. If it matches a static resource, the emitter selects that resource's descriptor element and accesses the wrong buffer. > > Route these operations through supported BDA paths, or reject `dynamic_buffer` explicitly. > > <!-- cr-comment:v1:df27d26f1a2a49e999b7d907 --> > > </blockquote></details> --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> **Configuration used**: Path: .coderabbit.yaml **Review profile**: CHILL **Plan**: Advanced **Run ID**: `7a7e8763-f299-4dcd-8f86-fb643a733b31` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 104530eafcc4c5eb2e33959488ce7472e1484482 and b23ee5aa8d070fe0c7d206a769705f84af436572. </details> <details> <summary>📒 Files selected for processing (7)</summary> * `src/graphics/host_gpu/renderer/renderCompute.cpp` * `src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp` * `src/graphics/shader/recompiler/frontend/translate/Memory.cpp` * `src/graphics/shader/recompiler/ir/ShaderIR.h` * `src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp` * `src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp` </details> **Included review availability:** Your plan provides up to 10 included reviews per hour; 9 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-18 04:08 UTC · original · edited 2026-09-19 08:44 UTC
On src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp line 271 (outdated):

@@ -179,61 +178,226 @@ uint32_t GetBdaPointer(ValueEmitContext& ctx, uint32_t address) {
 	return result;
 }
 
-uint32_t LoadBdaDword(ValueEmitContext& ctx, uint32_t address) {
-	auto&      state   = ctx.state;
-	const auto bda     = GetBdaPointer(ctx, address);
+uint32_t LoadBdaDword(ValueEmitContext& ctx, uint32_t address, bool is_volatile = false) {
+	auto&      state = ctx.state;
+	const auto bda   = GetBdaPointer(ctx, address);
 	const auto present =
 	    Binary(state, spv::OpINotEqual, TypeBool(state), bda, ConstantDeviceAddress(state, 0));
 	return EmitValueOrZeroIfCondition(state, present, [&]() {
+		if (is_volatile) {
+			EmitDeviceAtomicMemoryBarrier(state);
+		}
 		const auto pointer = state.builder.AllocateId();
 		state.builder.AddFunction(spv::OpConvertUToPtr, TypePhysicalU32Pointer(state), pointer,
 		                          bda);
 		const auto         value     = state.builder.AllocateId();
 		constexpr uint32_t alignment = sizeof(uint32_t);
-		state.builder.AddFunction(spv::OpLoad, TypeU32(state), value, pointer,
-		                          spv::MemoryAccessAlignedMask, alignment);
+		const uint32_t     access_mask =
+		    is_volatile ? (spv::MemoryAccessAlignedMask | spv::MemoryAccessVolatileMask)
+		                : spv::MemoryAccessAlignedMask;
+		state.builder.AddFunction(spv::OpLoad, TypeU32(state), value, pointer, access_mask,
+		                          alignment);
 		return value;
 	});
 }
 
+uint32_t LoadBdaAddress(ValueEmitContext& ctx, uint32_t address, uint32_t bits,
+                        bool is_volatile = false) {
+	auto&      state   = ctx.state;
+	const auto aligned = Binary(state, spv::OpBitwiseAnd, TypeScalarU64(state), address,
+	                            ConstantDeviceAddress(state, ~uint64_t {3}));
+	const auto first   = LoadBdaDword(ctx, aligned, is_volatile);
+	const auto byte =
+	    Binary(state, spv::OpBitwiseAnd, TypeU32(state),
+	           Unary(state, spv::OpUConvert, TypeU32(state), address), ConstantU32(state, 3));
+	const auto crosses =
+	    bits == 8u ? ConstantBool(state, false)
+	               : Binary(state, bits == 16u ? spv::OpUGreaterThan : spv::OpINotEqual,
+	                        TypeBool(state), byte, ConstantU32(state, bits == 16u ? 2u : 0u));
+	const auto second = EmitValueOrZeroIfCondition(state, crosses, [&]() {
+		return LoadBdaDword(ctx,
+		                    Binary(state, spv::OpIAdd, TypeScalarU64(state), aligned,
+		                           ConstantDeviceAddress(state, sizeof(uint32_t))),
+		                    is_volatile);
+	});
+	const auto shift =
+	    Binary(state, spv::OpShiftLeftLogical, TypeU32(state), byte, ConstantU32(state, 3));
+	const auto upper_shift =
+	    Binary(state, spv::OpShiftLeftLogical, TypeU32(state),
+	           Binary(state, spv::OpBitwiseAnd, TypeU32(state),
+	                  Binary(state, spv::OpISub, TypeU32(state), ConstantU32(state, 4), byte),
+	                  ConstantU32(state, 3)),
+	           ConstantU32(state, 3));
+	const auto merged =
+	    Binary(state, spv::OpBitwiseOr, TypeU32(state),
+	           Binary(state, spv::OpShiftRightLogical, TypeU32(state), first, shift),
+	           Binary(state, spv::OpShiftLeftLogical, TypeU32(state), second, upper_shift));
+	return bits == 32u ? merged
+	                   : Binary(state, spv::OpBitwiseAnd, TypeU32(state), merged,
+	                            ConstantU32(state, bits == 8u ? 0xffu : 0xffffu));
+}
+
 uint32_t LoadBda(ValueEmitContext& ctx, const IR::Inst& inst, const IR::MemoryInfo& mem,
-	             uint32_t bits) {
+                 uint32_t bits) {
 	auto&      state   = ctx.state;
 	const auto address = GuestAddress(ctx, inst, mem);
 	const auto active  = ctx.Arg(inst, inst.NumArgs() - 1);
-	return EmitValueOrZeroIfCondition(state, active, [&]() {
-		const auto aligned = Binary(state, spv::OpBitwiseAnd, TypeScalarU64(state), address,
-		                            ConstantDeviceAddress(state, ~uint64_t {3}));
-		const auto first   = LoadBdaDword(ctx, aligned);
+	return EmitValueOrZeroIfCondition(
+	    state, active, [&]() { return LoadBdaAddress(ctx, address, bits, mem.glc); });
+}
+
+void StoreBdaDword(ValueEmitContext& ctx, uint32_t address, uint32_t data,
+                   bool is_volatile = false) {
+	auto&      state = ctx.state;
+	const auto bda   = GetBdaPointer(ctx, address);
+	const auto present =
+	    Binary(state, spv::OpINotEqual, TypeBool(state), bda, ConstantDeviceAddress(state, 0));
+	EmitIfCondition(state, present, [&]() {
+		const auto pointer = state.builder.AllocateId();
+		state.builder.AddFunction(spv::OpConvertUToPtr, TypePhysicalU32Pointer(state), pointer,
+		                          bda);
+		constexpr uint32_t alignment = sizeof(uint32_t);
+		const uint32_t     access_mask =
+		    is_volatile ? (spv::MemoryAccessAlignedMask | spv::MemoryAccessVolatileMask)
+		                : spv::MemoryAccessAlignedMask;
+		state.builder.AddFunction(spv::OpStore, pointer, data, access_mask, alignment);
+		if (is_volatile) {
+			EmitDeviceAtomicMemoryBarrier(state);
+		}
+	});
+}
+
+void StoreBdaSubword(ValueEmitContext& ctx, uint32_t address, uint32_t bits, uint32_t data) {
+	auto& state = ctx.state;

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Propagate mem.glc to BDA subword stores.

StoreBdaSubword has no volatility argument. Dynamic U8 and U16 stores therefore emit non-volatile loads and stores with no device barrier, even when mem.glc is set. This differs from StoreBdaDword, which receives and applies mem.glc.

Pass mem.glc into StoreBdaSubword. Apply the volatile access mask and device synchronization to its BDA memory operations.

Also applies to: 300-301, 315-316

✅ Addressed in commit ef7a6e5

**@⁠coderabbitai[bot]** on GitHub · 2026-09-18 04:08 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/690#discussion_r4043726382) · edited 2026-09-19 08:44 UTC On `src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp` line 271 (outdated): ```diff @@ -179,61 +178,226 @@ uint32_t GetBdaPointer(ValueEmitContext& ctx, uint32_t address) { return result; } -uint32_t LoadBdaDword(ValueEmitContext& ctx, uint32_t address) { - auto& state = ctx.state; - const auto bda = GetBdaPointer(ctx, address); +uint32_t LoadBdaDword(ValueEmitContext& ctx, uint32_t address, bool is_volatile = false) { + auto& state = ctx.state; + const auto bda = GetBdaPointer(ctx, address); const auto present = Binary(state, spv::OpINotEqual, TypeBool(state), bda, ConstantDeviceAddress(state, 0)); return EmitValueOrZeroIfCondition(state, present, [&]() { + if (is_volatile) { + EmitDeviceAtomicMemoryBarrier(state); + } const auto pointer = state.builder.AllocateId(); state.builder.AddFunction(spv::OpConvertUToPtr, TypePhysicalU32Pointer(state), pointer, bda); const auto value = state.builder.AllocateId(); constexpr uint32_t alignment = sizeof(uint32_t); - state.builder.AddFunction(spv::OpLoad, TypeU32(state), value, pointer, - spv::MemoryAccessAlignedMask, alignment); + const uint32_t access_mask = + is_volatile ? (spv::MemoryAccessAlignedMask | spv::MemoryAccessVolatileMask) + : spv::MemoryAccessAlignedMask; + state.builder.AddFunction(spv::OpLoad, TypeU32(state), value, pointer, access_mask, + alignment); return value; }); } +uint32_t LoadBdaAddress(ValueEmitContext& ctx, uint32_t address, uint32_t bits, + bool is_volatile = false) { + auto& state = ctx.state; + const auto aligned = Binary(state, spv::OpBitwiseAnd, TypeScalarU64(state), address, + ConstantDeviceAddress(state, ~uint64_t {3})); + const auto first = LoadBdaDword(ctx, aligned, is_volatile); + const auto byte = + Binary(state, spv::OpBitwiseAnd, TypeU32(state), + Unary(state, spv::OpUConvert, TypeU32(state), address), ConstantU32(state, 3)); + const auto crosses = + bits == 8u ? ConstantBool(state, false) + : Binary(state, bits == 16u ? spv::OpUGreaterThan : spv::OpINotEqual, + TypeBool(state), byte, ConstantU32(state, bits == 16u ? 2u : 0u)); + const auto second = EmitValueOrZeroIfCondition(state, crosses, [&]() { + return LoadBdaDword(ctx, + Binary(state, spv::OpIAdd, TypeScalarU64(state), aligned, + ConstantDeviceAddress(state, sizeof(uint32_t))), + is_volatile); + }); + const auto shift = + Binary(state, spv::OpShiftLeftLogical, TypeU32(state), byte, ConstantU32(state, 3)); + const auto upper_shift = + Binary(state, spv::OpShiftLeftLogical, TypeU32(state), + Binary(state, spv::OpBitwiseAnd, TypeU32(state), + Binary(state, spv::OpISub, TypeU32(state), ConstantU32(state, 4), byte), + ConstantU32(state, 3)), + ConstantU32(state, 3)); + const auto merged = + Binary(state, spv::OpBitwiseOr, TypeU32(state), + Binary(state, spv::OpShiftRightLogical, TypeU32(state), first, shift), + Binary(state, spv::OpShiftLeftLogical, TypeU32(state), second, upper_shift)); + return bits == 32u ? merged + : Binary(state, spv::OpBitwiseAnd, TypeU32(state), merged, + ConstantU32(state, bits == 8u ? 0xffu : 0xffffu)); +} + uint32_t LoadBda(ValueEmitContext& ctx, const IR::Inst& inst, const IR::MemoryInfo& mem, - uint32_t bits) { + uint32_t bits) { auto& state = ctx.state; const auto address = GuestAddress(ctx, inst, mem); const auto active = ctx.Arg(inst, inst.NumArgs() - 1); - return EmitValueOrZeroIfCondition(state, active, [&]() { - const auto aligned = Binary(state, spv::OpBitwiseAnd, TypeScalarU64(state), address, - ConstantDeviceAddress(state, ~uint64_t {3})); - const auto first = LoadBdaDword(ctx, aligned); + return EmitValueOrZeroIfCondition( + state, active, [&]() { return LoadBdaAddress(ctx, address, bits, mem.glc); }); +} + +void StoreBdaDword(ValueEmitContext& ctx, uint32_t address, uint32_t data, + bool is_volatile = false) { + auto& state = ctx.state; + const auto bda = GetBdaPointer(ctx, address); + const auto present = + Binary(state, spv::OpINotEqual, TypeBool(state), bda, ConstantDeviceAddress(state, 0)); + EmitIfCondition(state, present, [&]() { + const auto pointer = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpConvertUToPtr, TypePhysicalU32Pointer(state), pointer, + bda); + constexpr uint32_t alignment = sizeof(uint32_t); + const uint32_t access_mask = + is_volatile ? (spv::MemoryAccessAlignedMask | spv::MemoryAccessVolatileMask) + : spv::MemoryAccessAlignedMask; + state.builder.AddFunction(spv::OpStore, pointer, data, access_mask, alignment); + if (is_volatile) { + EmitDeviceAtomicMemoryBarrier(state); + } + }); +} + +void StoreBdaSubword(ValueEmitContext& ctx, uint32_t address, uint32_t bits, uint32_t data) { + auto& state = ctx.state; ``` _🎯 Functional Correctness_ | _🟠 Major_ | _⚡ Quick win_ **Propagate `mem.glc` to BDA subword stores.** `StoreBdaSubword` has no volatility argument. Dynamic U8 and U16 stores therefore emit non-volatile loads and stores with no device barrier, even when `mem.glc` is set. This differs from `StoreBdaDword`, which receives and applies `mem.glc`. Pass `mem.glc` into `StoreBdaSubword`. Apply the volatile access mask and device synchronization to its BDA memory operations. Also applies to: 300-301, 315-316 <!-- fingerprinting:phantom:poseidon:tapir --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:9fbb55ed8ba06b73df0e7cf1 --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commit ef7a6e5
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-18 04:08 UTC · original · edited 2026-09-19 08:44 UTC
On src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp line 316 (outdated):

@@ -179,61 +178,226 @@ uint32_t GetBdaPointer(ValueEmitContext& ctx, uint32_t address) {
 	return result;
 }
 
-uint32_t LoadBdaDword(ValueEmitContext& ctx, uint32_t address) {
-	auto&      state   = ctx.state;
-	const auto bda     = GetBdaPointer(ctx, address);
+uint32_t LoadBdaDword(ValueEmitContext& ctx, uint32_t address, bool is_volatile = false) {
+	auto&      state = ctx.state;
+	const auto bda   = GetBdaPointer(ctx, address);
 	const auto present =
 	    Binary(state, spv::OpINotEqual, TypeBool(state), bda, ConstantDeviceAddress(state, 0));
 	return EmitValueOrZeroIfCondition(state, present, [&]() {
+		if (is_volatile) {
+			EmitDeviceAtomicMemoryBarrier(state);
+		}
 		const auto pointer = state.builder.AllocateId();
 		state.builder.AddFunction(spv::OpConvertUToPtr, TypePhysicalU32Pointer(state), pointer,
 		                          bda);
 		const auto         value     = state.builder.AllocateId();
 		constexpr uint32_t alignment = sizeof(uint32_t);
-		state.builder.AddFunction(spv::OpLoad, TypeU32(state), value, pointer,
-		                          spv::MemoryAccessAlignedMask, alignment);
+		const uint32_t     access_mask =
+		    is_volatile ? (spv::MemoryAccessAlignedMask | spv::MemoryAccessVolatileMask)
+		                : spv::MemoryAccessAlignedMask;
+		state.builder.AddFunction(spv::OpLoad, TypeU32(state), value, pointer, access_mask,
+		                          alignment);
 		return value;
 	});
 }
 
+uint32_t LoadBdaAddress(ValueEmitContext& ctx, uint32_t address, uint32_t bits,
+                        bool is_volatile = false) {
+	auto&      state   = ctx.state;
+	const auto aligned = Binary(state, spv::OpBitwiseAnd, TypeScalarU64(state), address,
+	                            ConstantDeviceAddress(state, ~uint64_t {3}));
+	const auto first   = LoadBdaDword(ctx, aligned, is_volatile);
+	const auto byte =
+	    Binary(state, spv::OpBitwiseAnd, TypeU32(state),
+	           Unary(state, spv::OpUConvert, TypeU32(state), address), ConstantU32(state, 3));
+	const auto crosses =
+	    bits == 8u ? ConstantBool(state, false)
+	               : Binary(state, bits == 16u ? spv::OpUGreaterThan : spv::OpINotEqual,
+	                        TypeBool(state), byte, ConstantU32(state, bits == 16u ? 2u : 0u));
+	const auto second = EmitValueOrZeroIfCondition(state, crosses, [&]() {
+		return LoadBdaDword(ctx,
+		                    Binary(state, spv::OpIAdd, TypeScalarU64(state), aligned,
+		                           ConstantDeviceAddress(state, sizeof(uint32_t))),
+		                    is_volatile);
+	});
+	const auto shift =
+	    Binary(state, spv::OpShiftLeftLogical, TypeU32(state), byte, ConstantU32(state, 3));
+	const auto upper_shift =
+	    Binary(state, spv::OpShiftLeftLogical, TypeU32(state),
+	           Binary(state, spv::OpBitwiseAnd, TypeU32(state),
+	                  Binary(state, spv::OpISub, TypeU32(state), ConstantU32(state, 4), byte),
+	                  ConstantU32(state, 3)),
+	           ConstantU32(state, 3));
+	const auto merged =
+	    Binary(state, spv::OpBitwiseOr, TypeU32(state),
+	           Binary(state, spv::OpShiftRightLogical, TypeU32(state), first, shift),
+	           Binary(state, spv::OpShiftLeftLogical, TypeU32(state), second, upper_shift));
+	return bits == 32u ? merged
+	                   : Binary(state, spv::OpBitwiseAnd, TypeU32(state), merged,
+	                            ConstantU32(state, bits == 8u ? 0xffu : 0xffffu));
+}
+
 uint32_t LoadBda(ValueEmitContext& ctx, const IR::Inst& inst, const IR::MemoryInfo& mem,
-	             uint32_t bits) {
+                 uint32_t bits) {
 	auto&      state   = ctx.state;
 	const auto address = GuestAddress(ctx, inst, mem);
 	const auto active  = ctx.Arg(inst, inst.NumArgs() - 1);
-	return EmitValueOrZeroIfCondition(state, active, [&]() {
-		const auto aligned = Binary(state, spv::OpBitwiseAnd, TypeScalarU64(state), address,
-		                            ConstantDeviceAddress(state, ~uint64_t {3}));
-		const auto first   = LoadBdaDword(ctx, aligned);
+	return EmitValueOrZeroIfCondition(
+	    state, active, [&]() { return LoadBdaAddress(ctx, address, bits, mem.glc); });
+}
+
+void StoreBdaDword(ValueEmitContext& ctx, uint32_t address, uint32_t data,
+                   bool is_volatile = false) {
+	auto&      state = ctx.state;
+	const auto bda   = GetBdaPointer(ctx, address);
+	const auto present =
+	    Binary(state, spv::OpINotEqual, TypeBool(state), bda, ConstantDeviceAddress(state, 0));
+	EmitIfCondition(state, present, [&]() {
+		const auto pointer = state.builder.AllocateId();
+		state.builder.AddFunction(spv::OpConvertUToPtr, TypePhysicalU32Pointer(state), pointer,
+		                          bda);
+		constexpr uint32_t alignment = sizeof(uint32_t);
+		const uint32_t     access_mask =
+		    is_volatile ? (spv::MemoryAccessAlignedMask | spv::MemoryAccessVolatileMask)
+		                : spv::MemoryAccessAlignedMask;
+		state.builder.AddFunction(spv::OpStore, pointer, data, access_mask, alignment);
+		if (is_volatile) {
+			EmitDeviceAtomicMemoryBarrier(state);
+		}
+	});
+}
+
+void StoreBdaSubword(ValueEmitContext& ctx, uint32_t address, uint32_t bits, uint32_t data) {
+	auto& state = ctx.state;
+	if (bits == 16u) {
+		const auto byte =
+		    Binary(state, spv::OpBitwiseAnd, TypeU32(state),
+		           Unary(state, spv::OpUConvert, TypeU32(state), address), ConstantU32(state, 3));
+		const auto unaligned =
+		    Binary(state, spv::OpIEqual, TypeBool(state), byte, ConstantU32(state, 3));
+		EmitIfElseCondition(
+		    state, unaligned,
+		    [&]() {
+			    StoreBdaSubword(ctx, address, 8u, data);
+			    const auto next_addr = Binary(state, spv::OpIAdd, TypeScalarU64(state), address,
+			                                  ConstantDeviceAddress(state, 1));
+			    const auto high_byte = Binary(state, spv::OpShiftRightLogical, TypeU32(state), data,
+			                                  ConstantU32(state, 8));
+			    StoreBdaSubword(ctx, next_addr, 8u, high_byte);
+		    },
+		    [&]() {
+			    const auto aligned = Binary(state, spv::OpBitwiseAnd, TypeScalarU64(state), address,
+			                                ConstantDeviceAddress(state, ~uint64_t {3}));
+			    const auto bda     = GetBdaPointer(ctx, aligned);
+			    const auto present = Binary(state, spv::OpINotEqual, TypeBool(state), bda,
+			                                ConstantDeviceAddress(state, 0));
+			    EmitIfCondition(state, present, [&]() {
+				    const auto pointer = state.builder.AllocateId();
+				    state.builder.AddFunction(spv::OpConvertUToPtr, TypePhysicalU32Pointer(state),
+				                              pointer, bda);
+				    constexpr uint32_t alignment = sizeof(uint32_t);
+				    const auto         old       = state.builder.AllocateId();
+				    state.builder.AddFunction(spv::OpLoad, TypeU32(state), old, pointer,
+				                              spv::MemoryAccessAlignedMask, alignment);
+				    const auto shift = Binary(state, spv::OpShiftLeftLogical, TypeU32(state), byte,
+				                              ConstantU32(state, 3));
+				    const auto mask  = Binary(state, spv::OpShiftLeftLogical, TypeU32(state),
+				                              ConstantU32(state, 0xffffu), shift);
+				    const auto value = Binary(state, spv::OpShiftLeftLogical, TypeU32(state),
+				                              Binary(state, spv::OpBitwiseAnd, TypeU32(state), data,
+				                                     ConstantU32(state, 0xffffu)),
+				                              shift);
+				    const auto merged =
+				        Binary(state, spv::OpBitwiseOr, TypeU32(state),
+				               Binary(state, spv::OpBitwiseAnd, TypeU32(state), old,
+				                      Unary(state, spv::OpNot, TypeU32(state), mask)),
+				               value);
+				    state.builder.AddFunction(spv::OpStore, pointer, merged,
+				                              spv::MemoryAccessAlignedMask, alignment);

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '250,330p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp
sed -n '760,815p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp
rg -n -C 5 'StoreBdaSubword|AtomicUpdate|OpAtomicCompareExchange|PhysicalStorageBuffer|Int8|Int16' src/graphics/shader/recompiler/backend/spirv

Repository: KytyPS5/KytyPS5

Length of output: 28189


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- BDA subword implementation ---'
sed -n '270,345p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp
printf '%s\n' '--- AtomicUpdate implementation ---'
sed -n '530,575p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h
printf '%s\n' '--- resource-backed subword implementation ---'
sed -n '640,705p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp
printf '%s\n' '--- physical-storage-buffer capability setup ---'
sed -n '585,615p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterModule.cpp
printf '%s\n' '--- relevant project declarations and extensions ---'
rg -n -C 3 'PhysicalStorageBuffer|SPV_KHR_physical_storage_buffer|Vulkan|apiVersion|vulkan|VK_KHR_buffer_device_address|BufferDeviceAddress|AtomicCompareExchange' --glob '*.{cpp,h,hpp,c,cc,md,txt,cmake}' .

Repository: KytyPS5/KytyPS5

Length of output: 50372


🌐 Web query:

SPIR-V OpAtomicCompareExchange PhysicalStorageBuffer storage class Vulkan physical storage buffer atomics

💡 Result:

<search_synthesis>
In Vulkan, you can perform atomic operations, including OpAtomicCompareExchange, on memory accessed via the PhysicalStorageBuffer storage class [1][2]. This is enabled by the SPV_KHR_physical_storage_buffer extension (or its equivalent in later Vulkan core versions) [1][3][4]. Key technical requirements and considerations include: 1. Addressing Model: To use the PhysicalStorageBuffer storage class, the SPIR-V module must use the PhysicalStorageBuffer64 addressing model [1][2]. This requires the PhysicalStorageBufferAddresses capability [1][3]. 2. Atomic Operation Support: The PhysicalStorageBuffer storage class is explicitly included in the list of storage classes that support atomic access in SPIR-V [1][2]. You use standard SPIR-V atomic instructions such as OpAtomicCompareExchange with pointers targeting this storage class [5]. 3. Hardware and Feature Support: The device must support the buffer device address feature (e.g., VkPhysicalDeviceBufferDeviceAddressFeatures::bufferDeviceAddress) [3][6]. 4. Implementation Details: - Atomic operations on PhysicalStorageBuffer pointers are treated similarly to other atomic memory operations in SPIR-V, requiring explicit memory scope (typically Device) and memory semantics (e.g., Acquire, Release, or AcquireRelease) [5][7]. - When generating SPIR-V, the pointer passed to the atomic instruction must be a valid pointer to the PhysicalStorageBuffer storage class [1][3]. If working with raw integer device addresses, you must convert them to a PhysicalStorageBuffer pointer using OpConvertUToPtr before performing the atomic operation [1][8][3]. - Be aware of language-specific or compiler-side issues when handling these pointers, such as ensuring they are treated as valid lvalues if the backend (e.g., SPIRV-Cross for Metal) requires an addressable reference to perform the atomic operation [8].
</search_synthesis>

<source_evidence>

https://github.khronos.org/SPIRV-Registry/extensions/KHR/SPV_KHR_physical_storage_buffer.html This extension adds a new storage class PhysicalStorageBuffer which is similar to StorageBuffer except pointers to the PhysicalStorageBuffer storage class are treated as physical pointer types according to a new addressing model PhysicalStorageBuffer64. This addressing model is a hybrid of logical and physical addressing, with only pointers to PhysicalStorageBuffer storage class being physical, and using 64-bit addresses. It also adds a new capablity PhysicalStorageBufferAddresses and enables a few instructions currently supported for Addresses. ... If the addressing model is not PhysicalStorageBuffer64, then the PhysicalStorageBuffer storage class must not be used. ... Add PhysicalStorageBuffer to the list of storage classes that support atomic access. ... OpVariable must not use a storage class of PhysicalStorageBuffer. ... For variables holding PhysicalStorageBuffer pointers, applying the AliasedPointer decoration on the OpVariable indicates that the PhysicalStorageBuffer pointers are potentially aliased. Applying RestrictPointer is allowed, but has no effect. Variables holding PhysicalStorageBuffer pointers must be decorated as either AliasedPointer or RestrictPointer. ... Add a new row for PhysicalStorageBuffer that is a copy of StorageBuffer. Add PhysicalStorageBuffer everywhere StorageBuffer is used in the "Second Storage Classes" column. ... For the PhysicalStorageBuffer storage class, OpVariable is understood to mean the PhysicalStorageBuffer pointer value(s) stored in the variable. An Aliased PhysicalStorageBuffer pointer stored in a Function variable can potentially alias with other variables in the same function, or with global variables or function parameters. ... | Addressing Model | | Enabling Capabilities | | --- | --- | --- | | 5348 | PhysicalStorageBuffer64 Indicates pointers whose storage classes are PhysicalStorageBuffer are physical pointer types with address width equal to 64 bits, and pointers to all other storage classes are logical. | PhysicalStorageBufferAddresses | ... | Storage Class | | Enabling Capabilities | | --- | --- | --- | | 5349 | PhysicalStorageBuffer Shared externally, readable and writable, visible across all functions in all invocations in all work groups. Graphics storage buffers using physical addressing. | PhysicalStorageBufferAddresses | ... Add PhysicalStorageBuffer to the ... of storage classes for the StorageBuffer16BitAccess, UniformAndStorageBuffer16BitAccess, ... Buffer8BitAccess, and UniformAndStorageBuffer8BitAccess capabilities. ... Modify the OpTypeForwardPointer, OpConvertUToPtr, OpConvertPtrToU, and OpPtrAccessChain instructions to add PhysicalStorageBufferAddresses to their capability lists. ... Modify OpConvertUToPtr to require that the result type must be a physical pointer type. ... Modify OpConvertPtrToU to require that the Pointer operand must have a physical pointer type. ... for physical storage buffer pointers. ... Resolution: Pointers to the PhysicalStorageBuffer storage class don’t quite fit the pre-existing definitions because the pointer is not created by OpVariable, rather it is loaded from memory or generated with OpConvertUToPtr. So we extend the definition of a memory object declaration to include a variable that holds a PhysicalStorageBuffer pointer, and add a way to decorate that the object in the variable is aliased/restrict rather than just the variable itself. https://github.com/KhronosGroup/SPIRV-Registry/blob/main/extensions/KHR/SPV_KHR_physical_storage_buffer.asciidoc This extension adds a new storage class *PhysicalStorageBuffer* which is similar to *StorageBuffer* except pointers to the *PhysicalStorageBuffer* storage class are treated as physical pointer types according to a new addressing model *PhysicalStorageBuffer64*. This addressing model is a hybrid of logical and physical addressing, with only pointers to *PhysicalStorageBuffer* storage class being physical, and using 64-bit addresses. It also adds a new capablity *PhysicalStorageBufferAddresses* and enables a few instructions currently supported for *Addresses*. ... pointer type if the <<Storage ... MemoryObjectDeclaration&`#39`;Memory Object Declaration:&`#39`; An *OpVariable*, or an *OpFunctionParameter* of pointer type, or the contents of an *OpVariable* that holds a pointer to *PhysicalStorageBuffer* <<Storage_Class, storage class>> or holds an array of such pointers. ... If the <<Addressing_Model, addressing model>> is not *PhysicalStorageBuffer64*, then the *PhysicalStorageBuffer* <<Storage_Class, storage class>> must not be used. ... Add *PhysicalStorageBuffer* to the list of <<Storage_Class, storage classes>> that support atomic access. ... *OpVariable* must not use a <<Storage_Class, storage class>> of *PhysicalStorageBuffer*. ... If an *OpVariable*&`#39`;s pointee type is a pointer (or array of pointers) in ... *PhysicalStorageBuffer* <<Storage_Class, storage class>>, then the variable must be decorated with exactly one of *AliasedPointer* or *RestrictPointer*. ... Any pointer value whose <<Storage_Class, storage class>> is *PhysicalStorageBuffer* and that points to a matrix or an array of matrices or a row or element of a matrix must be the result of an *OpAccessChain* or *OpPtrAccessChain* instruction whose base is a structure type (or recursively must be the result of a sequence of only access chains from a structure to the final value). Such a pointer must only be used as the &`#39`;Pointer&`#39`; operand to *OpLoad* or *OpStore*. ... For variables holding *PhysicalStorageBuffer* pointers, applying the *AliasedPointer* decoration on the *OpVariable* indicates that the *PhysicalStorageBuffer* pointers are potentially aliased. Applying *RestrictPointer* is allowed, but has no effect. Variables holding *PhysicalStorageBuffer* pointers must be decorated as either *AliasedPointer* or *RestrictPointer*. ... Add a new row for *PhysicalStorageBuffer* that is a copy of *StorageBuffer*. Add *PhysicalStorageBuffer* everywhere *StorageBuffer* is used in the "Second Storage Classes" column. ... For the *PhysicalStorageBuffer* <<Storage_Class, storage class>>, *OpVariable* is understood to mean the *PhysicalStorageBuffer* pointer value(s) stored in the variable. An *Aliased* *PhysicalStorageBuffer* pointer stored in a *Function* variable can potentially alias with other variables in the same function, or with global variables or function parameters. ... 2+^ ... | 5348 | *PhysicalStorageBuffer64* + ... Indicates pointers whose <<Storage_Class, storage classes>> are *PhysicalStorageBuffer* are physical pointer types with address width equal to 64 bits, and pointers to all other <<Storage_Class, storage classes>> are logical. | *PhysicalStorageBufferAddresses* |==== -- ... 3.7 Storage Class ... ~~~~~~~~~~~~~~~~~ -- [options="header"] |==== 2+^| Storage Class ^| Enabling Capabilities | 5349 | *PhysicalStorageBuffer* + ... Shared externally, readable and writable, visible across all functions in all invocations in all work groups. Graphics storage buffers using physical addressing. | *PhysicalStorageBufferAddresses* |==== -- ... Add *PhysicalStorageBuffer* to the list of storage classes for the *StorageBuffer16BitAccess*, *UniformAndStorageBuffer16BitAccess*, *StorageBuffer8BitAccess*, and *UniformAndStorageBuffer8BitAccess* capabilities. ... Modify the *OpTypeForwardPointer*, *OpConve…[truncated] https://docs.vulkan.org/guide/latest/buffer_device_address.html Buffer Device Address :: Vulkan Documentation Project # Buffer Device Address Buffer Device Address allows you to have a pointer to the`VkBuffer` in your shaders. There are many other usages such as Ray Tracing, GPU Side tooling, etc. This will be more of a technical breakdown of how it works, if you looking for a simple "how do I just use this", then please take a look at the Vulkan Samples. ## Extension The original proposal was done with the`VK_EXT_buffer_device_address` extension. Shortly afterwards,`VK_KHR_buffer_device_address` was added, which had some minor feature differences. Starting in Vulkan 1.2 this has become core and it is very widely available on GPUs on every platform. Starting in Vulkan 1.3 it became required, so if you are using Vulkan 1.3, you are guaranteed support. ### Name alias The naming of this`Buffer Device Address` feature will be different depending on where you look. For GLSL, it is`buffer reference`(see GL_EXT_buffer_reference). This is because syntactically it’s used more like a C++ reference than a pointer. For SPIR-V, it is`PhysicalStorageBuffer`(see SPV_KHR_physical_storage_buffer). The name comes from the fact there was a`StorageBuffer` and now it is "Physical". (`Physical` is from "physical addressing" which is a concept in`Kernel` SPIR-V) If you are coming from DirectX, you will know the feature as`GPU virtual address`. ## Vulkan Side From the Vulkan code, the only 3 things you need to do is Enable the`bufferDeviceAddress` feature. (Also the extension if using Vulkan 1.0 or 1.1) Add`VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT_KHR` when creating your`VkBuffer`. Add`VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT_KHR` when allocating your`VkDeviceMemory`. From here you can use the`vkGetBufferDeviceAddress` call and it will return a`VkDeviceAddress`. This is now your 64-bit pointer to that`VkBuffer` that can be handed down into your shader. For tools, the`vkGetBufferDeviceAddress` function might break assumptions that Vulkan function only return`void` or`VkResult` ## SPIR-V Side If you are using GLSL/HLSL/Slang/etc then the following is all taken care for you! ### Capability The SPIR-V will contain the`OpCapability PhysicalStorageBufferAddresses` instruction that will match up with`VkPhysicalDeviceVulkan12Features::bufferDeviceAddress`(or`VkPhysicalDeviceBufferDeviceAddressFeatures::bufferDeviceAddress`) to let everyone know the device does support this. ### Addressing Model SPIR-V has an Addressing Model that has 3 group of options `Logical`- this is what Vulkan 1.0 uses, it has no concept of pointers `Physical32`/`Physical64`- this for OpenCL `PhysicalStorageBuffer64`- this is what you will use if you are making use of Buffer Device Address ### shaderInt64 Since these`VkDeviceAddress` are represented as 64-bit integer pointers in your shader, you will likely want`shaderInt64` support for your device. Some device migth support`bufferDeviceAddress`, but not`shaderInt64`. The way around this situation is to make everything an`uvec2`(see GL_EXT_buffer_reference_uvec2). ### Alignment See dedicated BDA Alignment chapter. ### Nullptr SPIR-V has a`OpConstantNull`, but that can’t be used with`PhysicalStorageBuffer`. The way around this is to either convert the pointer to an integer with`OpConvertPtrToU` or to a`uvec2` with`OpBitcast`. Vulkan defines the integer value of`0` to be null (as everyone would hopefully expect!). ### Cross stage variables There is still on-going discussion to clarify if/how passing pointers from two stages works (ex. vertex to fragment). The main issue is you may get validation layers errors with the`Location` matching (see https://github.com/KhronosGroup/Vulkan-ValidationLayers/pull/5349). The suggestion is to just pass a`uvec2` or`int64` across stages and re-cast it in your consumer stage. ### OpTypeForwardPointer and infinite loops The`OpTypeForwardPointer` is used to forward reference the type of the pointer. This is useful if the app want…[truncated] https://docs.vulkan.org/spec/latest/chapters/descriptors.html Shaders can also access buffers without going through descriptors by using Physical Storage Buffer Access to access them through 64-bit addresses. ... ### Storage Buffer ... A storage buffer (VK_DESCRIPTOR_TYPE_STORAGE_BUFFER) is a descriptor type associated with a buffer resource directly, described in a shader as a structure with various members that load, store, and atomic operations can be performed on. ... Atomic operations can only be performed on members of certain types as defined in the SPIR-V environment appendix. ... ## Physical Storage Buffer Access ... Buffer device addresses can also be used to access buffer memory in a shader, using the `SPV_KHR_physical_storage_buffer` extension or the equivalent `SPV_EXT_physical_storage_buffer` extension and the `PhysicalStorageBuffer` storage class. For example, this value can be stored in a uniform buffer, and the shader can read the value from the uniform buffer and use it to do a dependent read/write to this buffer. All loads, stores, and atomics in a shader through `PhysicalStorageBuffer` pointers must access addresses in the address range of some buffer. GitHub issue 4983 in microsoft/DirectXShaderCompiler (link omitted to avoid creating a cross-reference) ## [SPIR-V] Atomics can&`#39`;t be used with vk::RawBuffer commands ... Due to some limitations with HLSL involving device addressing, we&`#39`;re making heavy use of HLSL&`#39`;s vk::RawBufferLoad and vk::RawBufferStore commands for our bindless rendering architecture. ... However, I&`#39`;m running into an issue where this effectively makes all atomic operations impossible... ... HLSL&`#39`;s current InterlockedCompareExchange function expects a resource value like a RWStructuredBuffer. And there is currently no way to construct a RWStructuredBuffer from a raw vulkan address. ... I&`#39`;m not sure if this is possible, but it would be ideal if we could construct a RWStructuredBuffer from a vulkan raw device address (and also potentially a size in bytes?) and then be able to use that official resource handle for atomic interlocked HLSL intrinsics... ... Or alternatively, perhaps we could add a vk::RawBufferInterlockedCompareExchange function which would act on the raw vulkan device address itself... ... > > > the whole `vk:::RawBuffer` design seems to be riddled with bugs, the `OpAccessChain`s are not being constructed properly for loads/stores, see `#4986` > > > > This seems mostly irrelevant. What does this have to do with atomics? > > In GLSL you can declare a bunch of nested structs and you can perform an `atomicExchange(buffer_reference.memberBInA.memberCInB.myUint, 45)` without a problem. > > With the way `vk::RawBuffer` currently works, you&`#39`;d have to do all the pointer arithmetic to find out the address from the base pointer to feed as an argument ... > The behavior of GLSL is also mostly irrelevant, as it pertains to how glslc compiles to SPIR-V. > > The HLSL programming language is different from GLSL in how atomics work. In HLSL, we have InterlockedCompareExchange, which requires a "resource" type. > > Hence why we either 1) construct such a resource handle from a raw device address, or 2) implement a vk specific intrinsic that works on the raw device address. > > Re pointer arithmetic, again that is unrelated to this issue. I am assuming that users do their own pointer arithmetic (like we do in a simple templated function wrapping vk::RawBuffer commands) ... > So, if I follow the SPIR-V spec right, we&`#39`;d potentially want to emit something roughly like the following: > > // CHECK: addr:%\d+ = OpLoad %ulong > // CHECK-NEXT: newValue:%\d+ = OpLoad %int %variable > // CHECK-NEXT: comparatorValue:%\d+ = OpLoad %int %comparator > // CHECK-NEXT: buf:%\d+ = OpBitcast %_ptr_PhysicalStorageBuffer_int addr > // CHECK-NEXT: result:%\d+ = OpAtomicCompareExchange buf Device AcquireRelease None newValue comparatorValue > // CHECK-NEXT: OpStore %originalValue result > > For the Scope, since this is a raw device address, I&`#39`;d assume "Device" is the right choice here. For shared memory atomics, those already work in SPIR-V though the built-in InterlockedCompareExchange call. > > I think for the "Equal" memory semantics this should be AcquireRelease, since we exchange when the original value equals the comparator. > > For the "Unequal" memory semantics, per spec this can&`#39`;t be Release or AcquireRelease. I think it should be None then? Since at this point we know the exchange isn&`#39`;t going to happen? ... > > The HLSL programming language is different from GLSL in how atomics work. In HLSL, we have InterlockedCompareExchange, which requires a "resource" type. > > Don&`#39`;t care, you can make whatever API you want as long as it emits the correct DXIL or SPIR-V. > > > Re pointer arithmetic, again that is unrelated to this issue. I am assuming that users do their own pointer arithmetic (like we do in a simple templated function wrapping vk::RawBuffer commands) > > Well thats rather painful compared to how transparent…[truncated]

Citations:


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- complete BDA subword function ---'
sed -n '270,345p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp
printf '%s\n' '--- AtomicUpdate ---'
sed -n '538,572p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h
printf '%s\n' '--- resource-backed subword path ---'
sed -n '650,695p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp
printf '%s\n' '--- BDA-related Vulkan feature setup ---'
rg -n -C 4 'bufferDeviceAddress|buffer_device_address|PhysicalStorageBufferAddresses|uses_dma|RequiredVulkan12Features|VULKAN_TARGET_API_VERSION' \
  src/graphics/presentation/window src/graphics/shader/recompiler src/graphics/host_gpu \
  --glob '*.{cpp,h,hpp}'

Repository: KytyPS5/KytyPS5

Length of output: 30744


🏁 Script executed:

sed -n '330,355p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp

Repository: KytyPS5/KytyPS5

Length of output: 1536


Make BDA subword stores atomic.

Aligned BDA 16-bit stores load one dword, merge the subword, and then perform a plain store. Two invocations can load the same dword and lose one update when they modify different halves.

Use a device-scope compare-exchange loop for this read-modify-write path. Also use it for each byte update produced by an unaligned 16-bit store, because each byte path performs the same dword read-modify-write operation. PhysicalStorageBuffer pointers support this atomic operation.

✅ Addressed in commit ef7a6e5

**@⁠coderabbitai[bot]** on GitHub · 2026-09-18 04:08 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/690#discussion_r4043726386) · edited 2026-09-19 08:44 UTC On `src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp` line 316 (outdated): ```diff @@ -179,61 +178,226 @@ uint32_t GetBdaPointer(ValueEmitContext& ctx, uint32_t address) { return result; } -uint32_t LoadBdaDword(ValueEmitContext& ctx, uint32_t address) { - auto& state = ctx.state; - const auto bda = GetBdaPointer(ctx, address); +uint32_t LoadBdaDword(ValueEmitContext& ctx, uint32_t address, bool is_volatile = false) { + auto& state = ctx.state; + const auto bda = GetBdaPointer(ctx, address); const auto present = Binary(state, spv::OpINotEqual, TypeBool(state), bda, ConstantDeviceAddress(state, 0)); return EmitValueOrZeroIfCondition(state, present, [&]() { + if (is_volatile) { + EmitDeviceAtomicMemoryBarrier(state); + } const auto pointer = state.builder.AllocateId(); state.builder.AddFunction(spv::OpConvertUToPtr, TypePhysicalU32Pointer(state), pointer, bda); const auto value = state.builder.AllocateId(); constexpr uint32_t alignment = sizeof(uint32_t); - state.builder.AddFunction(spv::OpLoad, TypeU32(state), value, pointer, - spv::MemoryAccessAlignedMask, alignment); + const uint32_t access_mask = + is_volatile ? (spv::MemoryAccessAlignedMask | spv::MemoryAccessVolatileMask) + : spv::MemoryAccessAlignedMask; + state.builder.AddFunction(spv::OpLoad, TypeU32(state), value, pointer, access_mask, + alignment); return value; }); } +uint32_t LoadBdaAddress(ValueEmitContext& ctx, uint32_t address, uint32_t bits, + bool is_volatile = false) { + auto& state = ctx.state; + const auto aligned = Binary(state, spv::OpBitwiseAnd, TypeScalarU64(state), address, + ConstantDeviceAddress(state, ~uint64_t {3})); + const auto first = LoadBdaDword(ctx, aligned, is_volatile); + const auto byte = + Binary(state, spv::OpBitwiseAnd, TypeU32(state), + Unary(state, spv::OpUConvert, TypeU32(state), address), ConstantU32(state, 3)); + const auto crosses = + bits == 8u ? ConstantBool(state, false) + : Binary(state, bits == 16u ? spv::OpUGreaterThan : spv::OpINotEqual, + TypeBool(state), byte, ConstantU32(state, bits == 16u ? 2u : 0u)); + const auto second = EmitValueOrZeroIfCondition(state, crosses, [&]() { + return LoadBdaDword(ctx, + Binary(state, spv::OpIAdd, TypeScalarU64(state), aligned, + ConstantDeviceAddress(state, sizeof(uint32_t))), + is_volatile); + }); + const auto shift = + Binary(state, spv::OpShiftLeftLogical, TypeU32(state), byte, ConstantU32(state, 3)); + const auto upper_shift = + Binary(state, spv::OpShiftLeftLogical, TypeU32(state), + Binary(state, spv::OpBitwiseAnd, TypeU32(state), + Binary(state, spv::OpISub, TypeU32(state), ConstantU32(state, 4), byte), + ConstantU32(state, 3)), + ConstantU32(state, 3)); + const auto merged = + Binary(state, spv::OpBitwiseOr, TypeU32(state), + Binary(state, spv::OpShiftRightLogical, TypeU32(state), first, shift), + Binary(state, spv::OpShiftLeftLogical, TypeU32(state), second, upper_shift)); + return bits == 32u ? merged + : Binary(state, spv::OpBitwiseAnd, TypeU32(state), merged, + ConstantU32(state, bits == 8u ? 0xffu : 0xffffu)); +} + uint32_t LoadBda(ValueEmitContext& ctx, const IR::Inst& inst, const IR::MemoryInfo& mem, - uint32_t bits) { + uint32_t bits) { auto& state = ctx.state; const auto address = GuestAddress(ctx, inst, mem); const auto active = ctx.Arg(inst, inst.NumArgs() - 1); - return EmitValueOrZeroIfCondition(state, active, [&]() { - const auto aligned = Binary(state, spv::OpBitwiseAnd, TypeScalarU64(state), address, - ConstantDeviceAddress(state, ~uint64_t {3})); - const auto first = LoadBdaDword(ctx, aligned); + return EmitValueOrZeroIfCondition( + state, active, [&]() { return LoadBdaAddress(ctx, address, bits, mem.glc); }); +} + +void StoreBdaDword(ValueEmitContext& ctx, uint32_t address, uint32_t data, + bool is_volatile = false) { + auto& state = ctx.state; + const auto bda = GetBdaPointer(ctx, address); + const auto present = + Binary(state, spv::OpINotEqual, TypeBool(state), bda, ConstantDeviceAddress(state, 0)); + EmitIfCondition(state, present, [&]() { + const auto pointer = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpConvertUToPtr, TypePhysicalU32Pointer(state), pointer, + bda); + constexpr uint32_t alignment = sizeof(uint32_t); + const uint32_t access_mask = + is_volatile ? (spv::MemoryAccessAlignedMask | spv::MemoryAccessVolatileMask) + : spv::MemoryAccessAlignedMask; + state.builder.AddFunction(spv::OpStore, pointer, data, access_mask, alignment); + if (is_volatile) { + EmitDeviceAtomicMemoryBarrier(state); + } + }); +} + +void StoreBdaSubword(ValueEmitContext& ctx, uint32_t address, uint32_t bits, uint32_t data) { + auto& state = ctx.state; + if (bits == 16u) { + const auto byte = + Binary(state, spv::OpBitwiseAnd, TypeU32(state), + Unary(state, spv::OpUConvert, TypeU32(state), address), ConstantU32(state, 3)); + const auto unaligned = + Binary(state, spv::OpIEqual, TypeBool(state), byte, ConstantU32(state, 3)); + EmitIfElseCondition( + state, unaligned, + [&]() { + StoreBdaSubword(ctx, address, 8u, data); + const auto next_addr = Binary(state, spv::OpIAdd, TypeScalarU64(state), address, + ConstantDeviceAddress(state, 1)); + const auto high_byte = Binary(state, spv::OpShiftRightLogical, TypeU32(state), data, + ConstantU32(state, 8)); + StoreBdaSubword(ctx, next_addr, 8u, high_byte); + }, + [&]() { + const auto aligned = Binary(state, spv::OpBitwiseAnd, TypeScalarU64(state), address, + ConstantDeviceAddress(state, ~uint64_t {3})); + const auto bda = GetBdaPointer(ctx, aligned); + const auto present = Binary(state, spv::OpINotEqual, TypeBool(state), bda, + ConstantDeviceAddress(state, 0)); + EmitIfCondition(state, present, [&]() { + const auto pointer = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpConvertUToPtr, TypePhysicalU32Pointer(state), + pointer, bda); + constexpr uint32_t alignment = sizeof(uint32_t); + const auto old = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpLoad, TypeU32(state), old, pointer, + spv::MemoryAccessAlignedMask, alignment); + const auto shift = Binary(state, spv::OpShiftLeftLogical, TypeU32(state), byte, + ConstantU32(state, 3)); + const auto mask = Binary(state, spv::OpShiftLeftLogical, TypeU32(state), + ConstantU32(state, 0xffffu), shift); + const auto value = Binary(state, spv::OpShiftLeftLogical, TypeU32(state), + Binary(state, spv::OpBitwiseAnd, TypeU32(state), data, + ConstantU32(state, 0xffffu)), + shift); + const auto merged = + Binary(state, spv::OpBitwiseOr, TypeU32(state), + Binary(state, spv::OpBitwiseAnd, TypeU32(state), old, + Unary(state, spv::OpNot, TypeU32(state), mask)), + value); + state.builder.AddFunction(spv::OpStore, pointer, merged, + spv::MemoryAccessAlignedMask, alignment); ``` _🗄️ Data Integrity & Integration_ | _🟠 Major_ | _⚡ Quick win_ <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash sed -n '250,330p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp sed -n '760,815p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp rg -n -C 5 'StoreBdaSubword|AtomicUpdate|OpAtomicCompareExchange|PhysicalStorageBuffer|Int8|Int16' src/graphics/shader/recompiler/backend/spirv ``` Repository: KytyPS5/KytyPS5 Length of output: 28189 --- 🏁 Script executed: ```bash #!/bin/bash set -e printf '%s\n' '--- BDA subword implementation ---' sed -n '270,345p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp printf '%s\n' '--- AtomicUpdate implementation ---' sed -n '530,575p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h printf '%s\n' '--- resource-backed subword implementation ---' sed -n '640,705p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp printf '%s\n' '--- physical-storage-buffer capability setup ---' sed -n '585,615p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterModule.cpp printf '%s\n' '--- relevant project declarations and extensions ---' rg -n -C 3 'PhysicalStorageBuffer|SPV_KHR_physical_storage_buffer|Vulkan|apiVersion|vulkan|VK_KHR_buffer_device_address|BufferDeviceAddress|AtomicCompareExchange' --glob '*.{cpp,h,hpp,c,cc,md,txt,cmake}' . ``` Repository: KytyPS5/KytyPS5 Length of output: 50372 --- 🌐 Web query: `SPIR-V OpAtomicCompareExchange PhysicalStorageBuffer storage class Vulkan physical storage buffer atomics` 💡 Result: <search_synthesis> In Vulkan, you can perform atomic operations, including OpAtomicCompareExchange, on memory accessed via the PhysicalStorageBuffer storage class [1][2]. This is enabled by the SPV_KHR_physical_storage_buffer extension (or its equivalent in later Vulkan core versions) [1][3][4]. Key technical requirements and considerations include: 1. Addressing Model: To use the PhysicalStorageBuffer storage class, the SPIR-V module must use the PhysicalStorageBuffer64 addressing model [1][2]. This requires the PhysicalStorageBufferAddresses capability [1][3]. 2. Atomic Operation Support: The PhysicalStorageBuffer storage class is explicitly included in the list of storage classes that support atomic access in SPIR-V [1][2]. You use standard SPIR-V atomic instructions such as OpAtomicCompareExchange with pointers targeting this storage class [5]. 3. Hardware and Feature Support: The device must support the buffer device address feature (e.g., VkPhysicalDeviceBufferDeviceAddressFeatures::bufferDeviceAddress) [3][6]. 4. Implementation Details: - Atomic operations on PhysicalStorageBuffer pointers are treated similarly to other atomic memory operations in SPIR-V, requiring explicit memory scope (typically Device) and memory semantics (e.g., Acquire, Release, or AcquireRelease) [5][7]. - When generating SPIR-V, the pointer passed to the atomic instruction must be a valid pointer to the PhysicalStorageBuffer storage class [1][3]. If working with raw integer device addresses, you must convert them to a PhysicalStorageBuffer pointer using OpConvertUToPtr before performing the atomic operation [1][8][3]. - Be aware of language-specific or compiler-side issues when handling these pointers, such as ensuring they are treated as valid lvalues if the backend (e.g., SPIRV-Cross for Metal) requires an addressable reference to perform the atomic operation [8]. </search_synthesis> <source_evidence> <source> <title>SPV_KHR_physical_storage_buffer</title> <location>https://github.khronos.org/SPIRV-Registry/extensions/KHR/SPV_KHR_physical_storage_buffer.html</location> <excerpt>This extension adds a new storage class PhysicalStorageBuffer which is similar to StorageBuffer except pointers to the PhysicalStorageBuffer storage class are treated as physical pointer types according to a new addressing model PhysicalStorageBuffer64. This addressing model is a hybrid of logical and physical addressing, with only pointers to PhysicalStorageBuffer storage class being physical, and using 64-bit addresses. It also adds a new capablity PhysicalStorageBufferAddresses and enables a few instructions currently supported for Addresses. ... If the addressing model is not PhysicalStorageBuffer64, then the PhysicalStorageBuffer storage class must not be used. ... Add PhysicalStorageBuffer to the list of storage classes that support atomic access. ... OpVariable must not use a storage class of PhysicalStorageBuffer. ... For variables holding PhysicalStorageBuffer pointers, applying the AliasedPointer decoration on the OpVariable indicates that the PhysicalStorageBuffer pointers are potentially aliased. Applying RestrictPointer is allowed, but has no effect. Variables holding PhysicalStorageBuffer pointers must be decorated as either AliasedPointer or RestrictPointer. ... Add a new row for PhysicalStorageBuffer that is a copy of StorageBuffer. Add PhysicalStorageBuffer everywhere StorageBuffer is used in the &quot;Second Storage Classes&quot; column. ... For the PhysicalStorageBuffer storage class, OpVariable is understood to mean the PhysicalStorageBuffer pointer value(s) stored in the variable. An Aliased PhysicalStorageBuffer pointer stored in a Function variable can potentially alias with other variables in the same function, or with global variables or function parameters. ... | Addressing Model | | Enabling Capabilities | | --- | --- | --- | | 5348 | PhysicalStorageBuffer64 Indicates pointers whose storage classes are PhysicalStorageBuffer are physical pointer types with address width equal to 64 bits, and pointers to all other storage classes are logical. | PhysicalStorageBufferAddresses | ... | Storage Class | | Enabling Capabilities | | --- | --- | --- | | 5349 | PhysicalStorageBuffer Shared externally, readable and writable, visible across all functions in all invocations in all work groups. Graphics storage buffers using physical addressing. | PhysicalStorageBufferAddresses | ... Add PhysicalStorageBuffer to the ... of storage classes for the StorageBuffer16BitAccess, UniformAndStorageBuffer16BitAccess, ... Buffer8BitAccess, and UniformAndStorageBuffer8BitAccess capabilities. ... Modify the OpTypeForwardPointer, OpConvertUToPtr, OpConvertPtrToU, and OpPtrAccessChain instructions to add PhysicalStorageBufferAddresses to their capability lists. ... Modify OpConvertUToPtr to require that the result type must be a physical pointer type. ... Modify OpConvertPtrToU to require that the Pointer operand must have a physical pointer type. ... for physical storage buffer pointers. ... Resolution: Pointers to the PhysicalStorageBuffer storage class don’t quite fit the pre-existing definitions because the pointer is not created by OpVariable, rather it is loaded from memory or generated with OpConvertUToPtr. So we extend the definition of a memory object declaration to include a variable that holds a PhysicalStorageBuffer pointer, and add a way to decorate that the object in the variable is aliased/restrict rather than just the variable itself.</excerpt> </source> <source> <title>extensions/KHR/SPV_KHR_physical_storage_buffer.asciidoc</title> <location>https://github.com/KhronosGroup/SPIRV-Registry/blob/main/extensions/KHR/SPV_KHR_physical_storage_buffer.asciidoc</location> <excerpt>This extension adds a new storage class *PhysicalStorageBuffer* which is similar to *StorageBuffer* except pointers to the *PhysicalStorageBuffer* storage class are treated as physical pointer types according to a new addressing model *PhysicalStorageBuffer64*. This addressing model is a hybrid of logical and physical addressing, with only pointers to *PhysicalStorageBuffer* storage class being physical, and using 64-bit addresses. It also adds a new capablity *PhysicalStorageBufferAddresses* and enables a few instructions currently supported for *Addresses*. ... pointer type if the &lt;&lt;Storage ... [[MemoryObjectDeclaration]]&`#39`;Memory Object Declaration:&`#39`; An *OpVariable*, or an *OpFunctionParameter* of pointer type, or the contents of an *OpVariable* that holds a pointer to *PhysicalStorageBuffer* &lt;&lt;Storage_Class, storage class&gt;&gt; or holds an array of such pointers. ... If the &lt;&lt;Addressing_Model, addressing model&gt;&gt; is not *PhysicalStorageBuffer64*, then the *PhysicalStorageBuffer* &lt;&lt;Storage_Class, storage class&gt;&gt; must not be used. ... Add *PhysicalStorageBuffer* to the list of &lt;&lt;Storage_Class, storage classes&gt;&gt; that support atomic access. ... *OpVariable* must not use a &lt;&lt;Storage_Class, storage class&gt;&gt; of *PhysicalStorageBuffer*. ... If an *OpVariable*&`#39`;s pointee type is a pointer (or array of pointers) in ... *PhysicalStorageBuffer* &lt;&lt;Storage_Class, storage class&gt;&gt;, then the variable must be decorated with exactly one of *AliasedPointer* or *RestrictPointer*. ... Any pointer value whose &lt;&lt;Storage_Class, storage class&gt;&gt; is *PhysicalStorageBuffer* and that points to a matrix or an array of matrices or a row or element of a matrix must be the result of an *OpAccessChain* or *OpPtrAccessChain* instruction whose base is a structure type (or recursively must be the result of a sequence of only access chains from a structure to the final value). Such a pointer must only be used as the &`#39`;Pointer&`#39`; operand to *OpLoad* or *OpStore*. ... For variables holding *PhysicalStorageBuffer* pointers, applying the *AliasedPointer* decoration on the *OpVariable* indicates that the *PhysicalStorageBuffer* pointers are potentially aliased. Applying *RestrictPointer* is allowed, but has no effect. Variables holding *PhysicalStorageBuffer* pointers must be decorated as either *AliasedPointer* or *RestrictPointer*. ... Add a new row for *PhysicalStorageBuffer* that is a copy of *StorageBuffer*. Add *PhysicalStorageBuffer* everywhere *StorageBuffer* is used in the &quot;Second Storage Classes&quot; column. ... For the *PhysicalStorageBuffer* &lt;&lt;Storage_Class, storage class&gt;&gt;, *OpVariable* is understood to mean the *PhysicalStorageBuffer* pointer value(s) stored in the variable. An *Aliased* *PhysicalStorageBuffer* pointer stored in a *Function* variable can potentially alias with other variables in the same function, or with global variables or function parameters. ... 2+^ ... | 5348 | *PhysicalStorageBuffer64* + ... Indicates pointers whose &lt;&lt;Storage_Class, storage classes&gt;&gt; are *PhysicalStorageBuffer* are physical pointer types with address width equal to 64 bits, and pointers to all other &lt;&lt;Storage_Class, storage classes&gt;&gt; are logical. | *PhysicalStorageBufferAddresses* |==== -- ... 3.7 Storage Class ... ~~~~~~~~~~~~~~~~~ -- [options=&quot;header&quot;] |==== 2+^| Storage Class ^| Enabling Capabilities | 5349 | *PhysicalStorageBuffer* + ... Shared externally, readable and writable, visible across all functions in all invocations in all work groups. Graphics storage buffers using physical addressing. | *PhysicalStorageBufferAddresses* |==== -- ... Add *PhysicalStorageBuffer* to the list of storage classes for the *StorageBuffer16BitAccess*, *UniformAndStorageBuffer16BitAccess*, *StorageBuffer8BitAccess*, and *UniformAndStorageBuffer8BitAccess* capabilities. ... Modify the *OpTypeForwardPointer*, *OpConve…[truncated]</excerpt> </source> <source> <title>Buffer Device Address :: Vulkan Documentation Project</title> <location>https://docs.vulkan.org/guide/latest/buffer_device_address.html</location> <excerpt>Buffer Device Address :: Vulkan Documentation Project # Buffer Device Address Buffer Device Address allows you to have a pointer to the`VkBuffer` in your shaders. There are many other usages such as Ray Tracing, GPU Side tooling, etc. This will be more of a technical breakdown of how it works, if you looking for a simple &quot;how do I just use this&quot;, then please take a look at the Vulkan Samples. ## Extension The original proposal was done with the`VK_EXT_buffer_device_address` extension. Shortly afterwards,`VK_KHR_buffer_device_address` was added, which had some minor feature differences. Starting in Vulkan 1.2 this has become core and it is very widely available on GPUs on every platform. Starting in Vulkan 1.3 it became required, so if you are using Vulkan 1.3, you are guaranteed support. ### Name alias The naming of this`Buffer Device Address` feature will be different depending on where you look. For GLSL, it is`buffer reference`(see GL_EXT_buffer_reference). This is because syntactically it’s used more like a C++ reference than a pointer. For SPIR-V, it is`PhysicalStorageBuffer`(see SPV_KHR_physical_storage_buffer). The name comes from the fact there was a`StorageBuffer` and now it is &quot;Physical&quot;. (`Physical` is from &quot;physical addressing&quot; which is a concept in`Kernel` SPIR-V) If you are coming from DirectX, you will know the feature as`GPU virtual address`. ## Vulkan Side From the Vulkan code, the only 3 things you need to do is Enable the`bufferDeviceAddress` feature. (Also the extension if using Vulkan 1.0 or 1.1) Add`VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT_KHR` when creating your`VkBuffer`. Add`VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT_KHR` when allocating your`VkDeviceMemory`. From here you can use the`vkGetBufferDeviceAddress` call and it will return a`VkDeviceAddress`. This is now your 64-bit pointer to that`VkBuffer` that can be handed down into your shader. For tools, the`vkGetBufferDeviceAddress` function might break assumptions that Vulkan function only return`void` or`VkResult` ## SPIR-V Side If you are using GLSL/HLSL/Slang/etc then the following is all taken care for you! ### Capability The SPIR-V will contain the`OpCapability PhysicalStorageBufferAddresses` instruction that will match up with`VkPhysicalDeviceVulkan12Features::bufferDeviceAddress`(or`VkPhysicalDeviceBufferDeviceAddressFeatures::bufferDeviceAddress`) to let everyone know the device does support this. ### Addressing Model SPIR-V has an Addressing Model that has 3 group of options `Logical`- this is what Vulkan 1.0 uses, it has no concept of pointers `Physical32`/`Physical64`- this for OpenCL `PhysicalStorageBuffer64`- this is what you will use if you are making use of Buffer Device Address ### shaderInt64 Since these`VkDeviceAddress` are represented as 64-bit integer pointers in your shader, you will likely want`shaderInt64` support for your device. Some device migth support`bufferDeviceAddress`, but not`shaderInt64`. The way around this situation is to make everything an`uvec2`(see GL_EXT_buffer_reference_uvec2). ### Alignment See dedicated BDA Alignment chapter. ### Nullptr SPIR-V has a`OpConstantNull`, but that can’t be used with`PhysicalStorageBuffer`. The way around this is to either convert the pointer to an integer with`OpConvertPtrToU` or to a`uvec2` with`OpBitcast`. Vulkan defines the integer value of`0` to be null (as everyone would hopefully expect!). ### Cross stage variables There is still on-going discussion to clarify if/how passing pointers from two stages works (ex. vertex to fragment). The main issue is you may get validation layers errors with the`Location` matching (see https://github.com/KhronosGroup/Vulkan-ValidationLayers/pull/5349). The suggestion is to just pass a`uvec2` or`int64` across stages and re-cast it in your consumer stage. ### OpTypeForwardPointer and infinite loops The`OpTypeForwardPointer` is used to forward reference the type of the pointer. This is useful if the app want…[truncated]</excerpt> </source> <source> <title>Resource Descriptors :: Vulkan Documentation Project</title> <location>https://docs.vulkan.org/spec/latest/chapters/descriptors.html</location> <excerpt>Shaders can also access buffers without going through descriptors by using Physical Storage Buffer Access to access them through 64-bit addresses. ... ### Storage Buffer ... A storage buffer (VK_DESCRIPTOR_TYPE_STORAGE_BUFFER) is a descriptor type associated with a buffer resource directly, described in a shader as a structure with various members that load, store, and atomic operations can be performed on. ... Atomic operations can only be performed on members of certain types as defined in the SPIR-V environment appendix. ... ## Physical Storage Buffer Access ... Buffer device addresses can also be used to access buffer memory in a shader, using the `SPV_KHR_physical_storage_buffer` extension or the equivalent `SPV_EXT_physical_storage_buffer` extension and the `PhysicalStorageBuffer` storage class. For example, this value can be stored in a uniform buffer, and the shader can read the value from the uniform buffer and use it to do a dependent read/write to this buffer. All loads, stores, and atomics in a shader through `PhysicalStorageBuffer` pointers must access addresses in the address range of some buffer.</excerpt> </source> <source> <title>[SPIR-V] Atomics can&`#39`;t be used with vk::RawBuffer commands · Issue `#4983` · microsoft/DirectXShaderCompiler</title> <location>GitHub issue 4983 in microsoft/DirectXShaderCompiler (link omitted to avoid creating a cross-reference)</location> <excerpt>## [SPIR-V] Atomics can&`#39`;t be used with vk::RawBuffer commands ... Due to some limitations with HLSL involving device addressing, we&`#39`;re making heavy use of HLSL&`#39`;s vk::RawBufferLoad and vk::RawBufferStore commands for our bindless rendering architecture. ... However, I&`#39`;m running into an issue where this effectively makes all atomic operations impossible... ... HLSL&`#39`;s current InterlockedCompareExchange function expects a resource value like a RWStructuredBuffer. And there is currently no way to construct a RWStructuredBuffer from a raw vulkan address. ... I&`#39`;m not sure if this is possible, but it would be ideal if we could construct a RWStructuredBuffer from a vulkan raw device address (and also potentially a size in bytes?) and then be able to use that official resource handle for atomic interlocked HLSL intrinsics... ... Or alternatively, perhaps we could add a vk::RawBufferInterlockedCompareExchange function which would act on the raw vulkan device address itself... ... &gt; &gt; &gt; the whole `vk:::RawBuffer` design seems to be riddled with bugs, the `OpAccessChain`s are not being constructed properly for loads/stores, see `#4986` &gt; &gt; &gt; &gt; This seems mostly irrelevant. What does this have to do with atomics? &gt; &gt; In GLSL you can declare a bunch of nested structs and you can perform an `atomicExchange(buffer_reference.memberBInA.memberCInB.myUint, 45)` without a problem. &gt; &gt; With the way `vk::RawBuffer` currently works, you&`#39`;d have to do all the pointer arithmetic to find out the address from the base pointer to feed as an argument ... &gt; The behavior of GLSL is also mostly irrelevant, as it pertains to how glslc compiles to SPIR-V. &gt; &gt; The HLSL programming language is different from GLSL in how atomics work. In HLSL, we have InterlockedCompareExchange, which requires a &quot;resource&quot; type. &gt; &gt; Hence why we either 1) construct such a resource handle from a raw device address, or 2) implement a vk specific intrinsic that works on the raw device address. &gt; &gt; Re pointer arithmetic, again that is unrelated to this issue. I am assuming that users do their own pointer arithmetic (like we do in a simple templated function wrapping vk::RawBuffer commands) ... &gt; So, if I follow the SPIR-V spec right, we&`#39`;d potentially want to emit something roughly like the following: &gt; &gt; // CHECK: [[addr:%\d+]] = OpLoad %ulong &gt; // CHECK-NEXT: [[newValue:%\d+]] = OpLoad %int %variable &gt; // CHECK-NEXT: [[comparatorValue:%\d+]] = OpLoad %int %comparator &gt; // CHECK-NEXT: [[buf:%\d+]] = OpBitcast %_ptr_PhysicalStorageBuffer_int [[addr]] &gt; // CHECK-NEXT: [[result:%\d+]] = OpAtomicCompareExchange [[buf]] Device AcquireRelease None [[newValue]] [[comparatorValue]] &gt; // CHECK-NEXT: OpStore %originalValue [[result]] &gt; &gt; For the Scope, since this is a raw device address, I&`#39`;d assume &quot;Device&quot; is the right choice here. For shared memory atomics, those already work in SPIR-V though the built-in InterlockedCompareExchange call. &gt; &gt; I think for the &quot;Equal&quot; memory semantics this should be AcquireRelease, since we exchange when the original value equals the comparator. &gt; &gt; For the &quot;Unequal&quot; memory semantics, per spec this can&`#39`;t be Release or AcquireRelease. I think it should be None then? Since at this point we know the exchange isn&`#39`;t going to happen? ... &gt; &gt; The HLSL programming language is different from GLSL in how atomics work. In HLSL, we have InterlockedCompareExchange, which requires a &quot;resource&quot; type. &gt; &gt; Don&`#39`;t care, you can make whatever API you want as long as it emits the correct DXIL or SPIR-V. &gt; &gt; &gt; Re pointer arithmetic, again that is unrelated to this issue. I am assuming that users do their own pointer arithmetic (like we do in a simple templated function wrapping vk::RawBuffer commands) &gt; &gt; Well thats rather painful compared to how transparent…[truncated]</excerpt> </source> </source_evidence> Citations: - 1: https://github.khronos.org/SPIRV-Registry/extensions/KHR/SPV_KHR_physical_storage_buffer.html - 2: https://github.com/KhronosGroup/SPIRV-Registry/blob/main/extensions/KHR/SPV_KHR_physical_storage_buffer.asciidoc - 3: https://docs.vulkan.org/guide/latest/buffer_device_address.html - 4: https://docs.vulkan.org/spec/latest/chapters/descriptors.html - 5: GitHub issue 4983 in microsoft/DirectXShaderCompiler (link omitted to avoid creating a cross-reference) - 6: https://github.khronos.org/Vulkan-Site/guide/latest/buffer_device_address.html - 7: https://github.khronos.org/Vulkan-Site/spec/latest/appendices/memorymodel.html - 8: GitHub issue 2641 in KhronosGroup/SPIRV-cross (link omitted to avoid creating a cross-reference) --- 🏁 Script executed: ```bash #!/bin/bash set -e printf '%s\n' '--- complete BDA subword function ---' sed -n '270,345p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp printf '%s\n' '--- AtomicUpdate ---' sed -n '538,572p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h printf '%s\n' '--- resource-backed subword path ---' sed -n '650,695p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp printf '%s\n' '--- BDA-related Vulkan feature setup ---' rg -n -C 4 'bufferDeviceAddress|buffer_device_address|PhysicalStorageBufferAddresses|uses_dma|RequiredVulkan12Features|VULKAN_TARGET_API_VERSION' \ src/graphics/presentation/window src/graphics/shader/recompiler src/graphics/host_gpu \ --glob '*.{cpp,h,hpp}' ``` Repository: KytyPS5/KytyPS5 Length of output: 30744 --- 🏁 Script executed: ```bash sed -n '330,355p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 1536 --- </details> **Make BDA subword stores atomic.** Aligned BDA 16-bit stores load one dword, merge the subword, and then perform a plain store. Two invocations can load the same dword and lose one update when they modify different halves. Use a device-scope compare-exchange loop for this read-modify-write path. Also use it for each byte update produced by an unaligned 16-bit store, because each byte path performs the same dword read-modify-write operation. `PhysicalStorageBuffer` pointers support this atomic operation. <!-- fingerprinting:phantom:medusa:quokka --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:918a9e5822068eae4ef354ae --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commit ef7a6e5
Author
Owner

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

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (2)

🟡 Minor · Handle formatted dynamic-buffer accesses. · spirvEmitterMemory.cpp:1352

src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp:1352
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Handle formatted dynamic-buffer accesses.

Formatted buffer opcodes set formatted, while ResourceTracking::Collect independently sets dynamic_buffer for dynamic descriptors. The scalar branches then skip FormattedLoad and FormattedStore and reach LoadWord or StoreWord, whose dynamic paths use raw LoadBdaAddress and StoreBdaDword. This skips format conversion and encoding. Apply formatting in the dynamic BDA path, or reject this combination explicitly.

🟡 Minor · Keep validation for unregistered compute shader addresses. · renderCompute.cpp:231

src/graphics/host_gpu/renderer/renderCompute.cpp:231
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Keep validation for unregistered compute shader addresses. The PM4 handlers accept arbitrary nonzero COMPUTE_PGM_LO and COMPUTE_PGM_HI values. The null check lets such an address reach GetComputeProgram; PrepareProgram then calls ShaderGetMappedData, which terminates through EXIT when the address is absent from g_shader_map. Restore ShaderAddressValid or add an equivalent check before GetComputeProgram.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Advanced

Run ID: 02c52df6-6c73-4f25-8276-0784b243a693

📥 Commits

Reviewing files that changed from the base of the PR and between b23ee5aa8d and cf51df75a9.

📒 Files selected for processing (3)
  • src/graphics/host_gpu/renderer/renderCompute.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp

Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-18 04:08 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/690#pullrequestreview-5244164645) · **reviewed** **Actionable comments posted: 2** > [!CAUTION] > Some comments are outside the diff and can’t be posted inline due to GitHub limitations. > > **⚠️ Outside diff range comments (2)** > > <details> > <summary><em>🟡 Minor</em> · Handle formatted dynamic-buffer accesses. · <code>spirvEmitterMemory.cpp:1352</code></summary><blockquote> > > `src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp:1352` > _🎯 Functional Correctness_ | _🟡 Minor_ | _⚡ Quick win_ > > **Handle formatted dynamic-buffer accesses.** > > Formatted buffer opcodes set `formatted`, while `ResourceTracking::Collect` independently sets `dynamic_buffer` for dynamic descriptors. The scalar branches then skip `FormattedLoad` and `FormattedStore` and reach `LoadWord` or `StoreWord`, whose dynamic paths use raw `LoadBdaAddress` and `StoreBdaDword`. This skips format conversion and encoding. Apply formatting in the dynamic BDA path, or reject this combination explicitly. > > <!-- cr-comment:v1:3eb4926e8072ed602a04ef26 --> > > </blockquote></details> > <details> > <summary><em>🟡 Minor</em> · Keep validation for unregistered compute shader addresses. · <code>renderCompute.cpp:231</code></summary><blockquote> > > `src/graphics/host_gpu/renderer/renderCompute.cpp:231` > _🎯 Functional Correctness_ | _🟡 Minor_ | _⚡ Quick win_ > > **Keep validation for unregistered compute shader addresses.** The PM4 handlers accept arbitrary nonzero `COMPUTE_PGM_LO` and `COMPUTE_PGM_HI` values. The null check lets such an address reach `GetComputeProgram`; `PrepareProgram` then calls `ShaderGetMappedData`, which terminates through `EXIT` when the address is absent from `g_shader_map`. Restore `ShaderAddressValid` or add an equivalent check before `GetComputeProgram`. > > <!-- cr-comment:v1:3339ec11fd3338e6fb23879d --> > > </blockquote></details> --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> **Configuration used**: Path: .coderabbit.yaml **Review profile**: CHILL **Plan**: Advanced **Run ID**: `02c52df6-6c73-4f25-8276-0784b243a693` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between b23ee5aa8d070fe0c7d206a769705f84af436572 and cf51df75a98386b3bb687a685fcb8a8c67082f93. </details> <details> <summary>📒 Files selected for processing (3)</summary> * `src/graphics/host_gpu/renderer/renderCompute.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp` </details> **Included review availability:** Your plan provides up to 10 included reviews per hour; 8 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
Author
Owner

@⁠francoisatt on GitHub · 2026-09-18 17:34 UTC · original

Tested cf51df7 on Windows (native Vulkan, RTX 5080, full clean build).

Full suite: 36/39, no regressions. The three failures are the known SDL link issue (#565), same as on clean main.

Note that no test currently exercises the new dynamic-buffer path on GPU.
If you add a compute fixture that dispatches a dynamic-buffer load/store and checks the readback, I can run it on native Vulkan. Not verified against any title on my side.

**@⁠francoisatt** on GitHub · 2026-09-18 17:34 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/690#issuecomment-5733788869) Tested cf51df7 on Windows (native Vulkan, RTX 5080, full clean build). Full suite: 36/39, no regressions. The three failures are the known SDL link issue (#565), same as on clean main. Note that no test currently exercises the new dynamic-buffer path on GPU. If you add a compute fixture that dispatches a dynamic-buffer load/store and checks the readback, I can run it on native Vulkan. Not verified against any title on my side.
@ -237,0 +427,4 @@
address = Binary(state, spv::OpIAdd, TypeU32(state), address, ctx.Arg(inst, 3));
}
return address;
}
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-19 09:05 UTC · original · edited 2026-09-19 09:27 UTC

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
# Locate the packed stride encoding and every consumer of the swizzle/add_tid bits.
rg -nP -C 6 'StorageBufferPackedStride' src/graphics/shader/recompiler
# Locate where dynamic_buffer is set during resource tracking.
rg -nP -C 8 '\bdynamic_buffer\b' src/graphics/shader/recompiler --glob '!**/spirvEmitterMemory.cpp'

Repository: KytyPS5/KytyPS5

Length of output: 14353


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- dynamic descriptor symbols ---'
rg -n -C 12 'IsDynamicDescriptor|ValidateSource|DynamicBufferByteAddress|BufferByteAddress' src/graphics/shader/recompiler
printf '%s\n' '--- descriptor definitions and packed fields ---'
rg -n -C 10 'packed_stride|swizzle|add_tid|ADD_TID|SWIZZLE' src/graphics/shader/recompiler src

Repository: KytyPS5/KytyPS5

Length of output: 50372


🏁 Script executed:

rg -n -C 15 'IsDynamicDescriptor|ValidateSource|DynamicBufferByteAddress|BufferByteAddress' src/graphics/shader/recompiler

Repository: KytyPS5/KytyPS5

Length of output: 28256


🏁 Script executed:

#!/bin/bash
set -e
rg -n -C 12 'struct ShaderBufferResource|class ShaderBufferResource|PackedStride\(|DecodeBufferDescriptor|descriptor.*stride|Stride\(\)' src/graphics/shader/recompiler src

Repository: KytyPS5/KytyPS5

Length of output: 50371


🏁 Script executed:

rg -n -C 12 'struct ShaderBufferResource|class ShaderBufferResource|PackedStride\(|DecodeBufferDescriptor|descriptor.*stride|Stride\(\)' src/graphics/shader/recompiler src

Repository: KytyPS5/KytyPS5

Length of output: 50371


Preserve descriptor flags in dynamic buffer addresses.

DynamicBufferGuestAddress passes only dword1 to DynamicBufferByteAddress, which extracts only the stride. ShaderBufferResource::SwizzleEnabled() reads dword1 bit 31, and ShaderBufferResource::AddTid() reads dword3 bit 23. Dynamic descriptors can contain both fields. When swizzle or add-thread addressing applies, the dynamic path can compute a different physical byte address from BufferByteAddress. Pass the required descriptor fields and apply the same address handling, or reject unsupported dynamic descriptors explicitly.

✅ Addressed in commits a08acad to a1b3eed

**@⁠coderabbitai[bot]** on GitHub · 2026-09-19 09:05 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/690#discussion_r4052731629) · edited 2026-09-19 09:27 UTC _🎯 Functional Correctness_ | _🟡 Minor_ | _⚡ Quick win_ <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash #!/bin/bash # Locate the packed stride encoding and every consumer of the swizzle/add_tid bits. rg -nP -C 6 'StorageBufferPackedStride' src/graphics/shader/recompiler # Locate where dynamic_buffer is set during resource tracking. rg -nP -C 8 '\bdynamic_buffer\b' src/graphics/shader/recompiler --glob '!**/spirvEmitterMemory.cpp' ``` Repository: KytyPS5/KytyPS5 Length of output: 14353 --- 🏁 Script executed: ```bash #!/bin/bash set -e printf '%s\n' '--- dynamic descriptor symbols ---' rg -n -C 12 'IsDynamicDescriptor|ValidateSource|DynamicBufferByteAddress|BufferByteAddress' src/graphics/shader/recompiler printf '%s\n' '--- descriptor definitions and packed fields ---' rg -n -C 10 'packed_stride|swizzle|add_tid|ADD_TID|SWIZZLE' src/graphics/shader/recompiler src ``` Repository: KytyPS5/KytyPS5 Length of output: 50372 --- 🏁 Script executed: ```bash rg -n -C 15 'IsDynamicDescriptor|ValidateSource|DynamicBufferByteAddress|BufferByteAddress' src/graphics/shader/recompiler ``` Repository: KytyPS5/KytyPS5 Length of output: 28256 --- 🏁 Script executed: ```bash #!/bin/bash set -e rg -n -C 12 'struct ShaderBufferResource|class ShaderBufferResource|PackedStride\(|DecodeBufferDescriptor|descriptor.*stride|Stride\(\)' src/graphics/shader/recompiler src ``` Repository: KytyPS5/KytyPS5 Length of output: 50371 --- 🏁 Script executed: ```bash rg -n -C 12 'struct ShaderBufferResource|class ShaderBufferResource|PackedStride\(|DecodeBufferDescriptor|descriptor.*stride|Stride\(\)' src/graphics/shader/recompiler src ``` Repository: KytyPS5/KytyPS5 Length of output: 50371 --- </details> **Preserve descriptor flags in dynamic buffer addresses.** `DynamicBufferGuestAddress` passes only `dword1` to `DynamicBufferByteAddress`, which extracts only the stride. `ShaderBufferResource::SwizzleEnabled()` reads `dword1` bit 31, and `ShaderBufferResource::AddTid()` reads `dword3` bit 23. Dynamic descriptors can contain both fields. When swizzle or add-thread addressing applies, the dynamic path can compute a different physical byte address from `BufferByteAddress`. Pass the required descriptor fields and apply the same address handling, or reject unsupported dynamic descriptors explicitly. <!-- fingerprinting:phantom:medusa:komodo --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:143195749e621427561b8c7f --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commits a08acad to a1b3eed
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-19 09:05 UTC · original · reviewed

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (2)

🟠 Major · Reject formatted dynamic buffer accesses explicitly. · spirvEmitterMemory.cpp:1353-1374

src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp:1353-1374
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Reject formatted dynamic buffer accesses explicitly. Formatted MUBUF and MTBUF operations can retain both mem.formatted and mem.dynamic_buffer. The dynamic wide-buffer branches use raw BDA dword accesses, and scalar operations bypass FormattedLoad or FormattedStore before reaching the same raw paths. This can return unconverted data or write incorrectly packed data.

Add ctx.Fail for formatted dynamic accesses in the scalar load, scalar store, LoadWideBuffer, and StoreWideBuffer branches until BDA format conversion is implemented.

🟡 Minor · Keep map validation for nonzero CS shader addresses. · renderCompute.cpp:228

src/graphics/host_gpu/renderer/renderCompute.cpp:228
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Keep map validation for nonzero CS shader addresses. A nonzero data_addr is not sufficient. DISPATCH_DIRECT can set an unmapped address through COMPUTE_PGM_LO and COMPUTE_PGM_HI. GetComputeProgram then calls ShaderGetMappedData, which reaches EXIT(... is missing from ShaderMap) for that address. Keep the map-membership check before GetComputeProgram instead of checking only for zero.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml

Review profile: CHILL

Plan: Advanced

Run ID: 317816e4-d0bd-4046-bf7e-426142940adc

📥 Commits

Reviewing files that changed from the base of the PR and between cf51df75a9 and 9cb933c3e4.

📒 Files selected for processing (3)
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp
  • src/graphics/shader/recompiler/frontend/translate/Memory.cpp

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

**@⁠coderabbitai[bot]** on GitHub · 2026-09-19 09:05 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/690#pullrequestreview-5255185673) · **reviewed** **Actionable comments posted: 1** > [!CAUTION] > Some comments are outside the diff and can’t be posted inline due to GitHub limitations. > > **⚠️ Outside diff range comments (2)** > > <details> > <summary><em>🟠 Major</em> · Reject formatted dynamic buffer accesses explicitly. · <code>spirvEmitterMemory.cpp:1353-1374</code></summary><blockquote> > > `src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp:1353-1374` > _🗄️ Data Integrity & Integration_ | _🟠 Major_ | _⚡ Quick win_ > > **Reject formatted dynamic buffer accesses explicitly.** Formatted MUBUF and MTBUF operations can retain both `mem.formatted` and `mem.dynamic_buffer`. The dynamic wide-buffer branches use raw BDA dword accesses, and scalar operations bypass `FormattedLoad` or `FormattedStore` before reaching the same raw paths. This can return unconverted data or write incorrectly packed data. > > Add `ctx.Fail` for formatted dynamic accesses in the scalar load, scalar store, `LoadWideBuffer`, and `StoreWideBuffer` branches until BDA format conversion is implemented. > > <!-- cr-comment:v1:048935421d52654fbed79de8 --> > > </blockquote></details> > <details> > <summary><em>🟡 Minor</em> · Keep map validation for nonzero CS shader addresses. · <code>renderCompute.cpp:228</code></summary><blockquote> > > `src/graphics/host_gpu/renderer/renderCompute.cpp:228` > _🩺 Stability & Availability_ | _🟡 Minor_ | _⚡ Quick win_ > > **Keep map validation for nonzero CS shader addresses.** A nonzero `data_addr` is not sufficient. `DISPATCH_DIRECT` can set an unmapped address through `COMPUTE_PGM_LO` and `COMPUTE_PGM_HI`. `GetComputeProgram` then calls `ShaderGetMappedData`, which reaches `EXIT(... is missing from ShaderMap)` for that address. Keep the map-membership check before `GetComputeProgram` instead of checking only for zero. > > <!-- cr-comment:v1:bfa198546cb47afa219cd516 --> > > </blockquote></details> --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml **Review profile**: CHILL **Plan**: Advanced **Run ID**: `317816e4-d0bd-4046-bf7e-426142940adc` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between cf51df75a98386b3bb687a685fcb8a8c67082f93 and 9cb933c3e44612b4fd21a3a6b6b205aac1eea828. </details> <details> <summary>📒 Files selected for processing (3)</summary> * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp` * `src/graphics/shader/recompiler/frontend/translate/Memory.cpp` </details> **Included review availability:** Your plan provides up to 10 included reviews per hour; 9 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
Author
Owner

@⁠bipinkrish on GitHub · 2026-09-19 09:29 UTC · original

@⁠francoisatt rebased with main and added the test cases you requested

**@⁠bipinkrish** on GitHub · 2026-09-19 09:29 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/690#issuecomment-5740768459) @⁠francoisatt rebased with main and added the test cases you requested
Author
Owner

@⁠francoisatt on GitHub · 2026-09-20 08:41 UTC · original

Thanks for adding them. Ran a1b3eed on Windows (native Vulkan, RTX 5080, driver 596.49, full clean build).

All four new cases pass on GPU:
[compute] DynamicBufferLoadStore ok
[compute] DynamicBufferLoadStoreDwordX4 ok
[compute] DynamicBufferStoreAddTid ok
[compute] DynamicBufferLoadStoreSwizzle ok

The full shader_recompiler_compute_tests run completes with no failure.
Full suite: 36/39, the three failures being the known SDL link issue (#565), same as on clean main.

Not verified: other GPU vendors (NVIDIA only).

**@⁠francoisatt** on GitHub · 2026-09-20 08:41 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/690#issuecomment-5748732652) Thanks for adding them. Ran a1b3eed on Windows (native Vulkan, RTX 5080, driver 596.49, full clean build). All four new cases pass on GPU: [compute] DynamicBufferLoadStore ok [compute] DynamicBufferLoadStoreDwordX4 ok [compute] DynamicBufferStoreAddTid ok [compute] DynamicBufferLoadStoreSwizzle ok The full shader_recompiler_compute_tests run completes with no failure. Full suite: 36/39, the three failures being the known SDL link issue (#565), same as on clean main. Not verified: other GPU vendors (NVIDIA only).
Author
Owner

@⁠DenizSAHIN570 on GitHub · 2026-09-23 19:30 UTC · original

Tested this on Linux with GTA V (PPSA04264): Nobara 44, RX 9070 XT, RADV (Mesa 26.2.2). I saw the Windows/NVIDIA results above, so this is another platform test.

I merged #690 (a1b3eed) onto ba55ba5 (the 2026-09-20 build). It merged cleanly.

Before: loading story mode died with
shader resource tracking: hash=0x6a53456e7ef5d1b0 stage=compute pc=0x0000086c GetBufferResource dword 0 is not a valid runtime value.
Tracing it with a local diagnostic, dword 0 comes from Ballot -> CompositeExtractU32x4 -> ... -> ReadFirstLane -> ReadConstBuffer, the same shape as the GTA V chain in #507 (different shader hash).

After: that error is gone and the run goes much further (72 compute shaders compiled in my run, versus 7–29 when it hit the error before).

The next things I hit were separate: a missing DS opcode (0xa0, DS_WRITE_B8_D16_HI), and after implementing that locally, a GPU hang (ErrorDeviceLost) in a compute shader that doesn't use the dynamic path (dma=0, traced with RADV_DEBUG=hang). I don't think that hang is related to this PR.

Not verified: whether the dynamic-descriptor results render correctly. I only checked that the resource-tracking failure is gone. Only tested on RADV.

I used AI when doing this but everything is done on my machine and verified by me.

**@⁠DenizSAHIN570** on GitHub · 2026-09-23 19:30 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/690#issuecomment-5801496781) Tested this on Linux with GTA V (PPSA04264): Nobara 44, RX 9070 XT, RADV (Mesa 26.2.2). I saw the Windows/NVIDIA results above, so this is another platform test. I merged #690 (a1b3eed) onto ba55ba5 (the 2026-09-20 build). It merged cleanly. Before: loading story mode died with shader resource tracking: hash=0x6a53456e7ef5d1b0 stage=compute pc=0x0000086c GetBufferResource dword 0 is not a valid runtime value. Tracing it with a local diagnostic, dword 0 comes from Ballot -> CompositeExtractU32x4 -> ... -> ReadFirstLane -> ReadConstBuffer, the same shape as the GTA V chain in #507 (different shader hash). After: that error is gone and the run goes much further (72 compute shaders compiled in my run, versus 7–29 when it hit the error before). The next things I hit were separate: a missing DS opcode (0xa0, DS_WRITE_B8_D16_HI), and after implementing that locally, a GPU hang (ErrorDeviceLost) in a compute shader that doesn't use the dynamic path (dma=0, traced with RADV_DEBUG=hang). I don't think that hang is related to this PR. Not verified: whether the dynamic-descriptor results render correctly. I only checked that the resource-tracking failure is gone. Only tested on RADV. I used AI when doing this but everything is done on my machine and verified by me.

Pull request closed

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