Skip to content

fix(agc): order wave LDS accesses with memory barriers on MoltenVK - #10858

Merged
oneandonlydean merged 1 commit into
boykopovar:mainfrom
maximilianfv:fix/agc-moltenvk-wave-lds-memory-barriers
Nov 2, 2026
Merged

oneandonlydean merged 1 commit into
boykopovar:mainfrom
maximilianfv:fix/agc-moltenvk-wave-lds-memory-barriers

Conversation

@maximilianfv

Copy link
Copy Markdown
Contributor

What

Under MoltenVK, agc_driver_lds_tree_reduction and agc_driver_lds_subword_store_branch read LDS before another wave had written it. This makes SubgroupControlBarrierUsable (SubgroupBarrier.hpp) return false for VK_DRIVER_ID_MOLTENVK as well, so MoltenVK takes the subgroup-scope OpMemoryBarrier path that AMD's proprietary driver already uses (#8134). WorkgroupScopeFenceUsable does not change: MoltenVK keeps workgroup-scope fences, and the subword store test passes with them.

Cause, from a MoltenVK shader dump: the recompiler orders one guest wave's LDS accesses with OpControlBarrier (Subgroup execution scope, Workgroup memory scope) inside the branch after s_cbranch_execz. SPIRV-Cross's CompilerMSL::emit_barrier takes the wider of the execution and memory scopes and emits threadgroup_barrier(mem_flags::mem_threadgroup). The tree-reduction dump has 22 threadgroup_barriers for the guest's 5 s_barriers. Waves that skip the branch pair their next barrier with another wave's extra one and read LDS before it is written: the tree reduction read 904, and the subword store read changing garbage. With this change the subgroup-scope OpMemoryBarrier becomes a simdgroup-scope atomic_thread_fence with no execution barrier. That relies on a 32-lane simdgroup running in lockstep, which Metal does not guarantee; the new debt entry "Wave LDS ordering on MoltenVK" in docs/dev/debt/shader.md records this.

The agc_subgroup_barrier driver table (tests/SubgroupBarrier.cpp) used one usable flag for both functions. MoltenVK now differs between the two (false, true), so the flag is split into controlBarrier and workgroupFence. Every other row keeps the old value in both fields.

On Linux and Windows the generated code does not change: the driver ID is never MoltenVK there.

Prior art and credit:

Tested

Apple M1 Pro, macOS 27.0.1, x86_64 build under Rosetta 2, Vulkan through MoltenVK 1.4.2 from the LunarG Vulkan SDK 1.4.363. main does not build on macOS by itself, so I tested on mugurc's macOS series (ci/macos-series-2, 27e9689) merged with main at 522e32e. The tree also carried other open macOS fixes (#10419 build parts, #10540, #10562, #10641, #10642, #10650, #10651, #10652) and one of my unopened test fixes (agc_driver_graphics). Only this change was toggled between the runs. I tested before rebasing onto current main; the rebased diff is the same.

Both sides: ANYPS5_REQUIRE_VULKAN=1 ANYPS5_NO_SHADER_CACHE=1 VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation ctest --test-dir build -R '^(agc_subgroup_barrier|agc_driver_lds_.*)$' -E 'audio_in|voice' -V (16 tests), three runs each.

  • Without: 14/16 passed in each run; agc_driver_lds_subword_store_branch and agc_driver_lds_tree_reduction failed.
  • With: 16/16 passed in each run.
  • Validation: neither log has the was not found but was requested by env var VK_INSTANCE_LAYERS line, and both have 0 Validation Error lines.

Not run on Linux or Windows: the generated code does not change there, and agc_subgroup_barrier is a table check that does not depend on the host. Not tested with any title.

Checklist

  • Based on current main; no other open PR implements the same functions
  • One topic per PR; follow-ups go in a new PR
  • No comments in code except technical debt
  • Unimplemented paths throw (NotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file
  • No notes, investigation .md files or images added to the repository (attach them to this PR)
  • New third-party code is a submodule built from source
  • Generic behaviour, not specific to one title
  • Depends on: none
  • Fixes: none
  • Unblocks: none
  • GPUs tested: Apple M1 Pro, MoltenVK 1.4.2 (Vulkan SDK 1.4.363), macOS 27.0.1
  • AI-assisted: yes

🤖 Generated with Claude Code

SPIRV-Cross widens a barrier's execution scope to its memory scope, so
the subgroup-scope OpControlBarrier with workgroup memory semantics
that orders one wave's LDS accesses becomes a threadgroup_barrier.
Emitted inside a branch only some waves take, those barriers paired
with other waves' barriers, and agc_driver_lds_tree_reduction and
agc_driver_lds_subword_store_branch read LDS before it was written.
MoltenVK now takes the memory-barrier path AMD's proprietary driver
already uses.

Co-authored-by: Himansh Raj <67262056+iamthehimansh@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@MarcZX10 MarcZX10 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment-only review of exact head 5138b1b1d25664561055b3b5b5810d9780dd93cb.

The failure mechanism is plausible and the change makes the two MoltenVK regression tests pass in the reported M1 Pro setup. I am not approving yet because the new VK_DRIVER_ID_MOLTENVK policy applies the fence-only path to every MoltenVK device, while the evidence is one M1 Pro and the debt entry itself says the path relies on 32-lane SIMD-group lockstep that Metal does not guarantee. Apple's guidance says SIMD-group size varies by GPU and advises querying it at runtime; it also distinguishes simdgroup_barrier (which waits for all threads in the SIMD group) from a memory fence. See Apple's SIMD-group and synchronization guidance.

Could you clarify whether SubgroupControlBarrierUsable is reached only when MoltenVK's reported Vulkan subgroup size matches the assumed guest wave size, and what evidence supports the fence-only lowering on other MoltenVK GPUs? If the current evidence only establishes M1 Pro, please consider limiting the policy to a supported subgroup/device condition or documenting the exact tested support boundary. I have not independently run the Metal/Vulkan tests; the three-run results and generated shader observations are author-reported.

AI-assisted review: yes.

@github-actions

github-actions Bot commented Oct 25, 2026 •

Copy link
Copy Markdown

Some comparisons could not be completed because a pull request conflicts with the base branch. Review these shared files manually before concluding that there is no overlap.

Pull request Shared files not compared
PR 5021 docs/dev/debt/shader.md
PR 5371 docs/dev/debt/shader.md
PR 6235 docs/dev/debt/shader.md
PR 6280 docs/dev/debt/shader.md
PR 6412 docs/dev/debt/shader.md
PR 6488 docs/dev/debt/shader.md
PR 6924 docs/dev/debt/shader.md
PR 7085 docs/dev/debt/shader.md
PR 7223 docs/dev/debt/shader.md
PR 7392 docs/dev/debt/shader.md
PR 7410 docs/dev/debt/shader.md
PR 7684 docs/dev/debt/shader.md
PR 8004 docs/dev/debt/shader.md
PR 9020 docs/dev/debt/shader.md
PR 9335 docs/dev/debt/shader.md
PR 9387 docs/dev/debt/shader.md
PR 9748 docs/dev/debt/shader.md
PR 10000 docs/dev/debt/shader.md
PR 10233 docs/dev/debt/shader.md
PR 10489 docs/dev/debt/shader.md
PR 10556 docs/dev/debt/shader.md
PR 10846 docs/dev/debt/shader.md
PR 10867 docs/dev/debt/shader.md
PR 11483 docs/dev/debt/shader.md
PR 12548 docs/dev/debt/shader.md
PR 12790 docs/dev/debt/shader.md
PR 12944 docs/dev/debt/shader.md
PR 14212 docs/dev/debt/shader.md
PR 14692 docs/dev/debt/shader.md
PR 14853 docs/dev/debt/shader.md
PR 14871 docs/dev/debt/shader.md

@github-actions github-actions Bot added docs agc libSceAgc* labels Oct 25, 2026
@maximilianfv

Copy link
Copy Markdown
Contributor Author

Thanks. Answers from the code at this head (5138b1b1d2):

When the fence-only path is reached. Only when WaveLdsScope returns subgroup scope (SpirvEmitter.cpp#L63-L74). That needs all of these:

  • a compute shader that writes LDS;
  • a workgroup larger than one guest wave;
  • a 32-lane host subgroup that matches a wave32 program, or a wave64 program run at two lanes per invocation on a 32-lane host.

The host subgroup size is the device's reported subgroupSize, or 32 when subgroupSizeControl lets compute pipelines require 32 (VulkanDevice.cpp#L1963-L1970, #L3792). A MoltenVK device that is not 32 lanes wide and cannot require 32 never takes the new branch, so it keeps what it had before this PR. Single-wave workgroups use workgroup scope (#L69) and are also unaffected.

Evidence. M1 Pro only (MoltenVK 1.4.2, macOS 27). I have no other Apple GPU and no Intel or AMD Mac to test on. The debt entry states this boundary and the lockstep assumption.

What Metal gets. In the shaders dumped from the M1 Pro run, every new barrier is atomic_thread_fence(mem_flags::mem_threadgroup, memory_order_seq_cst, thread_scope_simdgroup). SPIRV-Cross (CompilerMSL::emit_barrier) emits that form only for MSL 3.2 and later. For older MSL it emits the same OpMemoryBarrier(Subgroup) as simdgroup_barrier(mem_flags::mem_threadgroup). On those targets the barrier needs the whole SIMD group to reach it. That is the same subgroup-uniform control flow that the OpControlBarrier(Subgroup, …) other drivers get already requires, so this PR does not add that assumption. I have not run a pre-3.2 target.

@ycbuzi

ycbuzi commented Oct 26, 2026

Copy link
Copy Markdown
Contributor

A Windows build and run of this head: Windows 11 Home 10.0.26200, WinLibs GCC 15.2.0 r7 (MinGW-w64 UCRT), Release. 5138b1b1d2 merged onto main 4e43321bd6 with no conflicts.

  • agc_subgroup_barrier passes, 2 of 2. It's a CPU-side test (driver IDs through the recompiler, no device opened), so this checks the MinGW build and the table, not a GPU.
  • Control: with main's SubgroupBarrier.hpp, it fails with driver 14: expected subgroup control barriers to be unusable, the MoltenVK case.
  • The change only adds VK_DRIVER_ID_MOLTENVK to SubgroupControlBarrierUsable, so the NVIDIA and AMD Windows drivers get the same answer as before.

AI-assisted: yes (Claude Code)

@jotitadev jotitadev left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A second Apple GPU (M2 Max) on a main-based tree, with both MoltenVK builds. The other runs here are Windows, where the change is a no-op.

Machine: Apple M2 Max, macOS 27.2, x86_64 Release build under Rosetta 2.
Tree: main b986c11a34 + the open macOS PRs needed to build and open a device (#10366, #7631, #10659, #10660, #11249, #11358, #10669, #10552, #7804, #10676, #11447, #11437, #11554, #11705) + this PR at 5138b1b1d2 (clean merge). Control: the same tree without this PR. ANYPS5_NO_SHADER_CACHE=1, -j1 --timeout 30.
Drivers: MoltenVK 1.4.2 (LunarG SDK 1.4.363.0) and MoltenVK main + SPIRV-Cross #2704.

Without With (3 runs)
agc_driver_lds_tree_reduction fails on both drivers: "round 0: thread 32 (wave 1) read 904, expected 32896" passes 3/3 on both drivers
agc_driver_lds_subword_store_branch passes, 6/6 on each driver passes 3/3 on both drivers
agc_subgroup_barrier passes passes
  • The tree-reduction failure is the same value you saw on the M1 Pro (904), so that one reproduces on a second Apple GPU and on MoltenVK main.
  • The subword store branch test did not fail here without the change (1 + 5 repeated runs per driver). On this machine it does not show the garbage reads, so it is weaker evidence for the fence-only path than the tree reduction.
  • Full ^agc suite, 1037 tests, MoltenVK 1.4.2: 41 failures without, 40 with. lds_tree_reduction is the only difference, so nothing new fails.
  • Validation layer (VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation, SDK 1.4.363.0, loader output shows it inserted) on the three tests: no VUID- on either side.

GPUs tested: Apple M2 Max (MoltenVK 1.4.2 and MoltenVK main + #2704)

Written with AI assistance (Claude Code). I ran the builds and tests above on my machine.

@TechLevelZero

TechLevelZero commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

✅ NVIDIA GPU test: passed

PR head 5138b1b merged onto main 0836dfd · tested 2026-11-01 01:22 UTC · 20 min

GPU NVIDIA RTX 2000 Ada Generation, driver 595.99.02, Vulkan 1.4.329
Host Ubuntu 26.04.1 LTS, kernel 7.0.0-38-generic, container ubuntu:24.04
Logs build and test logs for this run
Build ✅ passed (Release, -DANYPS5_ENABLE_SPIRV_TOOLS=ON)
Tests ✅ 2,395 passed · 5 failed (0 new, 4 also fail on main, 1 unstable on main) · 44 skipped (ANYPS5_REQUIRE_VULKAN=1)
Test setup CPU-only tests without a GPU; GPU tests (and any CPU-only test that failed or skipped without one) once on the GPU with VK_LAYER_KHRONOS_validation and ANYPS5_NO_SHADER_CACHE=1; main ran the same way
Test selection 2,444 of 3,087 tests run: the ones this change can reach, chosen by tools/select_tests.py from main's build graph
Vulkan validation ✅ no new validation IDs vs main (924 tests run on the GPU)
Slow tests (>30 s, GPU tests timed with validation layers) ⚠️ agc_driver_lookup_log_fits_build 55.1 s, ⚠️ agc_driver_pipeline_journal 49.4 s, ⚠️ agc_driver_graphics_maps_fallback 31.0 s, ⚠️ agc_driver_graphics 30.7 s
Unstable on main (1, these also failed in recent main runs on this machine; not counted against this PR)
agc_submit_progress_no_timeline: failed in 9 of the last 10 main runs
Failing on main too (4, not counted against this PR)
agc_driver_idle_store_yields
agc_driver_image_table
guest_mmap_executable
guest_socket_options_multicast
Validation IDs already present on main (5 IDs in 476 tests)
VUID-VkDeviceCreateInfo-pNext-pNext (476 tests): agc_driver, agc_driver_address_passes, agc_driver_alias_copy_label, agc_driver_alpha_to_coverage, agc_driver_array_layer_target, agc_driver_bc_block_copy, agc_driver_bda_anchor_reads, agc_driver_bda_span_reads, and 468 more
VUID-vkCmdCopyImage-srcImage-01548 (7 tests): agc_driver_depth_clear_hle, agc_driver_depth_plane_buffer_memory, agc_driver_depth_plane_partial_store, agc_driver_depth_plane_sampling, agc_driver_depth_storage_dispatch, agc_driver_depth_surface_from_storage, agc_driver_dispatch_move_depth
VUID-vkCmdCopyImage-srcImage-01551 (7 tests): agc_driver_depth_clear_hle, agc_driver_depth_plane_buffer_memory, agc_driver_depth_plane_partial_store, agc_driver_depth_plane_sampling, agc_driver_depth_storage_dispatch, agc_driver_depth_surface_from_storage, agc_driver_dispatch_move_depth
VUID-VkPipelineColorBlendStateCreateInfo-pAttachments-00605 (1 test): agc_driver_prepared_exports
VUID-VkShaderModuleCreateInfo-pCode-08737 (1 test): agc_driver_image_sample_derivatives
Skipped (44)
agc_driver_bda_reads_shadowed_results: skipped, the device reports watched host memory written when it imports or reads it
agc_driver_bda_reads_shadowed_results_per_build: skipped, the device reports watched host memory written when it imports or reads it
agc_driver_sample_order_grid_reference: skipped, the device does not keep depth drawn at custom sample locations at those locations, even after a transition that names them: the composite of uniform renders holds the guest's depth in 0 of 3005 sloped samples, so no path can be compared with it bit for bit
agc_host_import_sparse: skipped, host imports are unavailable: /dev/udmabuf is not accessible
agc_import_settle_initial_dcc: skipped, the device has no deferred settle of host imports: imports under 1 MiB wait for one only on Windows
agc_unit_shadow_completion_store: skipped, the device reports watched host memory written when it imports or reads it
guest_http_uri_locale: 
guest_net_ctl: skipped, the host has no IPv4 address
guest_video_out_color_space: skipped, no display or Vulkan device: SDL_InitSubSystem(VIDEO | GAMECONTROLLER) failed: wayland,x11 not available
guest_video_out_hdr: skipped, no display or Vulkan device: SDL_InitSubSystem(VIDEO | GAMECONTROLLER) failed: wayland,x11 not available
guest_video_out_high_frame_rate: skipped, no display or Vulkan device: SDL_InitSubSystem(VIDEO | GAMECONTROLLER) failed: wayland,x11 not available
guest_video_out_output_mode: skipped, no display or Vulkan device: SDL_InitSubSystem(VIDEO | GAMECONTROLLER) failed: wayland,x11 not available
guest_video_out_resolution_status: skipped, no display or Vulkan device: SDL_InitSubSystem(VIDEO | GAMECONTROLLER) failed: wayland,x11 not available
guest_video_out_wqhd_detection: skipped, no display or Vulkan device: SDL_InitSubSystem(VIDEO | GAMECONTROLLER) failed: wayland,x11 not available
video_out_flip_aftergpu: skipped, no display or Vulkan device: DisplayWindow: Vulkan support is either not configured in SDL or not available in current SDL video driver (offscreen) or platform
video_out_flip_backtoback: skipped, no display or Vulkan device: DisplayWindow: Vulkan support is either not configured in SDL or not available in current SDL video driver (offscreen) or platform
video_out_flip_controls: skipped, no display or Vulkan device: DisplayWindow: Vulkan support is either not configured in SDL or not available in current SDL video driver (offscreen) or platform
video_out_flip_cpuflip: skipped, no display or Vulkan device: DisplayWindow: Vulkan support is either not configured in SDL or not available in current SDL video driver (offscreen) or platform
video_out_flip_cpuflip_in_order: skipped, no display or Vulkan device: DisplayWindow: Vulkan support is either not configured in SDL or not available in current SDL video driver (offscreen) or platform
video_out_flip_dcc: skipped, no display or Vulkan device: DisplayWindow: Vulkan support is either not configured in SDL or not available in current SDL video driver (offscreen) or platform
video_out_flip_deferred: skipped, no display or Vulkan device: DisplayWindow: Vulkan support is either not configured in SDL or not available in current SDL video driver (offscreen) or platform
video_out_flip_eop: skipped, no display or Vulkan device: DisplayWindow: Vulkan support is either not configured in SDL or not available in current SDL video driver (offscreen) or platform
video_out_flip_eop_aftergpu: skipped, no display or Vulkan device: DisplayWindow: Vulkan support is either not configured in SDL or not available in current SDL video driver (offscreen) or platform
video_out_flip_eop_main: skipped, no display or Vulkan device: DisplayWindow: Vulkan support is either not configured in SDL or not available in current SDL video driver (offscreen) or platform
video_out_flip_fresh: skipped, no display or Vulkan device: DisplayWindow: Vulkan support is either not configured in SDL or not available in current SDL video driver (offscreen) or platform
video_out_f
Reproduce
git fetch origin 5138b1b1d25664561055b3b5b5810d9780dd93cb 0836dfdf4fecb1e0326100c490476e15d3a74da5
git checkout 0836dfdf4fecb1e0326100c490476e15d3a74da5 && git merge --no-ff 5138b1b1d25664561055b3b5b5810d9780dd93cb
git submodule update --init --recursive
cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=ON -DANYPS5_ENABLE_SPIRV_TOOLS=ON
cmake --build build && cmake --build build --target libs
VK_DRIVER_FILES=/nonexistent/icd.json ctest --test-dir build -E '^(agc|shader|recompiler|videoout|video_out|guest_video_out|vulkan)|gpu' --timeout 120 --parallel 32 --output-on-failure
ANYPS5_REQUIRE_VULKAN=1 ANYPS5_NO_SHADER_CACHE=1 VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation \
  ctest --test-dir build -R '^(agc|shader|recompiler|videoout|video_out|guest_video_out|vulkan)|gpu' --timeout 120 --parallel 4 --output-on-failure
# failures are then re-run alone: --timeout 360 --parallel 2; new validation IDs: the test alone, twice, --parallel 1

Automated build and test on a contributor's NVIDIA machine; it does not replace upstream CI. A new comment is posted for each new push. Full logs.

@frankea

frankea commented Nov 1, 2026

Copy link
Copy Markdown
Contributor

The same mispairing reproduces on an Apple M5 Max (macOS 27.0.1, MoltenVK 1.4.2 from Vulkan SDK 1.4.363.0, MSL 4.0, x86_64 build under Rosetta 2). On main cd087bd, agc_driver_lds_tree_reduction reads 904 (expected 32896) in 5 of 5 runs. Unlike jotitadev's M2 Max, agc_driver_lds_subword_store_branch fails here too: thread 64 (wave 2) reads 0 (expected 65536), 5 of 5 runs. With this PR's two code files applied to main, both pass 3 of 3.

On MarcZX10's point about the fence: there is a form that keeps an execution barrier. If the wave barrier gets subgroup memory scope, OpControlBarrier(Subgroup, Subgroup, AcquireRelease | WorkgroupMemory) (what GLSL subgroupBarrier() compiles to, limited to workgroup memory), SPIRV-Cross no longer widens it to the threadgroup, and it becomes simdgroup_barrier at every MSL version. Translated with the SDK's spirv-cross (vulkan-sdk-1.4.357.0-39) from the SPIR-V MoltenVK received for one test, with --msl-argument-buffers --msl-argument-buffer-tier 1:

SPIR-V wave barrier MSL 2.1, 2.2, 2.3, 3.0, 3.1 MSL 3.2, 4.0
OpControlBarrier(Subgroup, Subgroup, 0x108) simdgroup_barrier simdgroup_barrier
OpMemoryBarrier(Subgroup, 0x108) (this PR) simdgroup_barrier atomic_thread_fence(..., thread_scope_simdgroup)
OpControlBarrier(Subgroup, Workgroup, 0x108) (main) threadgroup_barrier threadgroup_barrier

The fence at MSL 3.2 and later comes from SPIRV-Cross 27d209e (KhronosGroup/SPIRV-Cross#2487, May 2025), which matches the atomic_thread_fence in your M1 Pro dumps. The widening to the wider scope is exe_scope = min(exe_scope, mem_scope) in CompilerMSL::emit_barrier (L11013, the revision MoltenVK 1.4.2 pins), so with both scopes at Subgroup it picks simdgroup_barrier (L11029).

I have this form on a local branch: a target flag set only for MoltenVK, a changed barrier choice in EmitStructuredBlock, and a new test, agc_driver_wave_lds_barrier_pairing (hand-encoded: lane 0 of wave 0 stores an LDS word inside an s_cbranch_execz branch after a 4096-iteration delay, then every wave reads it after s_barrier; wave64 at two lanes per invocation with 128 and 256 threads, wave32 with 64 and 256). On the M5 Max the new test fails on main in 5 of 5 runs, with every lane of waves 1..n stale. It passes 3 of 3 with this PR's change and 5 of 5 with the subgroup memory scope. On an RTX 4090 (driver 616.92, Windows 11) it passes on main and with the branch. On GT7's radix sort, replayed on MoltenVK, both forms turn passes that lose records into permutations, with identical output.

Only one of the two should be merged. Would you rather take the subgroup-memory-scope form into this PR (I can push the branch, and a Co-authored-by line is enough credit), or should I open mine as a PR that replaces this one? Either works for me.

AI-assisted: yes (Claude Code)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agc libSceAgc* docs

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants