shader: translate for Metal without descriptor aliasing, graphics subgroups, or 64-bit atomics #2270
No reviewers
Labels
No labels
bug
documentation
duplicate
enhancement
GPU
GUI
help wanted
question
Shaders
Video
wontfix
No milestone
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
github/KytyPS5--KytyPS5!2270
Loading…
Reference in a new issue
No description provided.
Delete branch "github-bot/gh-2270"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
@bengidev on GitHub · 2026-11-14 07:08 UTC · original
bengidev:macos-metal-shaders→main· +295 −55 · 17 files · 4 commits · openStacked on #2269 — that device-enablement PR is the first commit here; only the three
shader commits below are new. (If #2269 lands first, this diff shrinks to them
automatically.)
With #2269 a Metal-backed device is accepted and
agcboots, but the first pipelinesstill fail. Three translation gaps, each blocking the next, all on MoltenVK 1.4.2 and
KosmicKrisp:
1. Descriptor aliasing → one binding per buffer element width
DefineDescriptorsdeclared up to four variables for one buffer array (buffers,buffers_u8,buffers_u16,buffers_u64, pluslds_dwords/lds_qwordsfor sharedmemory) and aliased them onto one binding with
OpDecorate ... Aliased. Vulkan permitsit, MSL does not.
Each width variant now has its own
DescriptorBindingKind, appended afterSharedMemorysoSamplers(51) and the group stride keep their values; a variant isonly counted when the program uses that width; the host write loop binds every variant to
the same buffer. The storage-buffer pool grows to 32k because one set can now hold four
buffer arrays.
2. Subgroup builtins in graphics stages → single-lane model
Kyty emits
OpGroupNonUniformBallotfor the launch/exec masks and loadsgl_SubgroupInvocationIDwhenever a stage asks for a lane id; Metal forbids both invertex and pixel functions (same root cause as #1427).
GraphicContextreports whether the device carries subgroup builtins in graphics stages(false on macOS) and
Profile::graphics_subgroupscarries it into the emitter. Where itis false, graphics stages use a single-lane model:
EmitLiveMask,EmitSourceLaneActive,EmitSubgroupLaneActiveBooland the lane-id load all go through oneEmitSingleLaneBallotthat emits{predicate, 0, 0, 0}, and the existing lane-maskprojection folds the membership tests to the scalar predicate. A vertex or pixel
invocation has no defined wave anyway, so this does not change what those stages compute.
3. 64-bit buffer atomics → 32-bit word atomics
The coherent 64-bit pair load now lowers to a plain load when the device reports
shaderBufferInt64Atomics = false(initialised 64-bit values do not need atomicity), andEmitBufferAtomic64— the single choke point for everyBufferAtomic*64opcode — fallsback to word atomics on the u32 alias: add/sub carry and borrow into the high word,
and/or/xor act per word, and min/max/swap/compare-exchange read both words, merge them and
write both halves back through one
OpAtomicExchange. Results are packed back into the64-bit type, so the IR still sees a single value and only shaders that use 64-bit atomics
are affected.
Result
Apple M1 Max / macOS 26.7 / x86_64 under Rosetta, bundled MoltenVK 1.4.2. Madden NFL 26
(PPSA26127, 01.016.000) now compiles its shader set (VS 17 | PS 26 | CS 100), creates its
pipelines and reaches the main menu — the rendered stadium background, Quick Play /
Franchise / Ultimate Team / Superstar tiles, the PSN sign-in prompt, the Accessibility
first-run screen. The only emulation warning left is the same tolerated one reported on
Linux (
TEMPORARY COMPUTE DISPATCH SKIP ... unsupported GPU-selected callable target).Not fast yet: 11–15 fps on the menu (M1 Max), with the perf overlay attributing
904 ms/s to CPU waits on the GPU and 616 ms/s to DCC/CMASK emulation, and with Kyty +
MoltenVK both running as x86_64 under Rosetta. No perf work in this PR.
Caveats
ShaderIR::DescriptorBindingKindgrew from 58 to 62 entries, which changes the shaderstore layout;
BuildStamp()already keys cached records to the executable.emulated accesses — it is a read-modify-write with a barrier, correct for single-writer
patterns and documented in the code.
so nothing changes on RADV/Turnip where subgroup ops in graphics stages work.
Metal rejects subgroup builtins and intrinsics in vertex and pixel functions: MoltenVK and KosmicKrisp both fail pipeline creation with "Subgroup builtins are not available in this type of function" as soon as a vertex shader touches gl_SubgroupInvocationID, and the ballot that builds the launch/exec masks is such a touch. A vertex or pixel invocation has no defined wave anyway, and the ballots Kyty emits for those stages only ask "is this lane in the launched set". GraphicContext now reports whether the device carries subgroup builtins in graphics stages (false on macOS) and Profile carries it into the emitter; where it is false the graphics stages emit a single-lane model: the lane id reads as 0 and ballot(predicate) becomes {predicate, 0, 0, 0}, so the existing lane-mask projection folds to the scalar predicate instead of loading a builtin. Profile grows two fields (int64_atomics, graphics_subgroups) which changes the shader store records, but BuildStamp() keys those to the executable.@coderabbitai[bot] on GitHub · 2026-11-14 07:17 UTC · original
Walkthrough
The changes add optional Vulkan feature handling and pass feature availability into renderer and SPIR-V configuration. SPIR-V emission adds single-lane graphics behavior and a two-word fallback for buffer 64-bit atomics. Descriptor handling adds buffer-width and shared-memory descriptor kinds. Gen5 driver initialization retries DMEM mapping without a fixed address and uses the returned address for the binding-table base.
Suggested reviewers:
nmzik,senaxxChange: Bug fix
Merge Risk:
Moderate · up to
17246This adds Metal support, but several new paths can produce wrong 64-bit atomic results, invalid shaders, or invalid descriptor writes on affected Apple devices. Other platforms are largely unaffected. These issues should be fixed before merge, or explicitly accepted given the reported single-title verification.
Pre-merge checks:
4
Full details: Title check
Explanation
The title names the main change: translating shaders for Metal by removing descriptor aliasing, adding a single-lane model for graphics subgroups, and emulating 64-bit buffer atomics. The changeset matches each of these three parts, including per-width descriptor bindings, the single-lane ballot path, and the 32-bit word atomic fallback. The title is long (94 characters), but it stays specific and relevant.
Full details: Description check
Explanation
The description is directly related to the changeset. It explains the three shader translation gaps and the fixes for each: descriptor aliasing, subgroup builtins in graphics stages, and 64-bit buffer atomics. It also covers the affected files, the storage-buffer pool increase, the DescriptorBindingKind change, and the test result on Madden NFL 26.
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
@ -251,3 +265,3 @@"descriptorBindingPartiallyBound");check_feature(features13.robustImageAccess, "robustImageAccess");check_feature(robustness2.nullDescriptor, "nullDescriptor");check_optional_feature(robustness2.nullDescriptor, "nullDescriptor");@coderabbitai[bot] on GitHub · 2026-11-14 07:17 UTC · original
Null image writes need a valid fallback when
nullDescriptoris disabled.Apple devices that lack
nullDescriptornow pass the optional check atvulkanWindow.cpp:267, and device creation leaves the feature disabled. The image heap still writes element 0 with a null image view atimageHeap.cpp:119-122andimageHeap.cpp:531-539. Unbound textures also write null image views throughMakeImageInfoatdescriptors.cpp:74-78anddescriptors.cpp:1088. WithoutnullDescriptor, these descriptor writes are invalid and can lead to undefined behavior when a shader reads them.Before accepting these devices, bind a valid placeholder image view for element 0 and for unbound textures when
nullDescriptoris disabled. Resolve the conflicting selection comment atvulkanWindow.cpp:670-672as part of the same change.@ -257,3 +271,3 @@check_feature(device_features2.features.depthBiasClamp, "depthBiasClamp");check_feature(device_features2.features.shaderClipDistance, "shaderClipDistance");check_feature(device_features2.features.shaderCullDistance, "shaderCullDistance");check_optional_feature(device_features2.features.shaderCullDistance, "shaderCullDistance");@coderabbitai[bot] on GitHub · 2026-11-14 07:17 UTC · original
Gate cull-distance outputs on
shaderCullDistance.On Apple,
shaderCullDistanceis now optional and stays disabled when the device does not report it. A guest shader that exports cull distance still produces aCullDistanceoutput.DefineOutputsthen createscull_distance_variable, andDefineModulerequiresCapabilityCullDistancefor it. No check in the emitter or output path suppresses this. The Vulkan specification requiresshaderCullDistancefor theCullDistancecapability, so pipeline creation can fail for such a shader on these devices.Pass the device feature state into output lowering. When the feature is unavailable, the emitter must not declare
CullDistanceor creategl_CullDistance. Handle the cull-distance stores inspirvEmitterFlow.cppthe same way. Choose the fallback for the cull-distance data before implementing this change.@ -1421,0 +1449,4 @@const auto dword = Binary(state, spv::OpShiftRightLogical, TypeU32(state), byte_address,ConstantU32(state, 2u));return EmitValueOrDefaultIfCondition(state, EmitMemoryElementInBounds(state, resource, dword), TypeU64(state),@coderabbitai[bot] on GitHub · 2026-11-14 07:17 UTC · original
Bounds-check the high word of the emulated 64-bit atomic.
The guard at line 1452 checks only
dword. The emulated path also writesdword + 1. Whendwordis the last dword of the descriptor range, the check passes and the high-word atomic writes past the range. Both words are written in the same guarded block, so the write is not prevented.Check both indices before either word changes:
Suggested fix
Committable suggestion
@ -1421,0 +1474,4 @@const auto carry = Select(state, TypeU32(state),Binary(state, spv::OpULessThan, TypeBool(state), low_old, low_new),ConstantU32(state, 1u), ConstantU32(state, 0u));@coderabbitai[bot] on GitHub · 2026-11-14 07:17 UTC · original
Calculate addition carry from the low-word sum.
For
BufferAtomicIAdd64,low_old < low_newdoes not detect overflow. Starting from zero and adding one setscarryto one, so the stored value becomes0x0000000100000001. Starting from0xffffffffand adding one misses the required carry.For addition, compare the wrapped low-word sum with
low_old. Keeplow_old < low_newonly for subtraction borrow.@ -1421,0 +1504,4 @@low_new = EmitCompositeExtractU64(state, merged, IR::Value(0u));high_new = EmitCompositeExtractU64(state, merged, IR::Value(1u));low_old = EmitAtomicWord(state, spv::OpAtomicExchange, low_pointer, low_new);high_old = EmitAtomicWord(state, spv::OpAtomicExchange, high_pointer, high_new);@coderabbitai[bot] on GitHub · 2026-11-14 07:17 UTC · original
Serialize the complete emulated 64-bit exchange.
Two concurrent
BufferAtomicSwap64operations can leave a value that neither operation supplied. Starting from zero, let A swap in0x0000000000000001and B swap in0x0000000100000000. The order A-low, B-low, B-high, A-high leaves zero.Atomic exchanges on each word do not make the pair atomic. Use synchronized whole-operation emulation, or reject unsupported operations rather than silently permit mixed-word results. The same serialization must cover other emulated accesses to the element.
@ -775,1 +782,3 @@state.builder.RequireCapability(spv::CapabilityInt64Atomics);if (state.profile.int64_atomics) {state.builder.RequireCapability(spv::CapabilityInt64Atomics);}@coderabbitai[bot] on GitHub · 2026-11-14 07:17 UTC · original
Do not remove
Int64Atomicswhile shared atomics remain native.When
profile.int64_atomicsis false andinfo.shared_int64_atomicsis true, this branch omitsInt64Atomics. However,EmitSharedAtomic64inspirvEmitterMemory.cpp, Lines 1542-1587, still emits native 64-bit atomic instructions. Those instructions requireInt64Atomics, so this path produces invalid SPIR-V. (registry.khronos.org)Handle shared atomic support separately. Emulate or reject unsupported shared operations before emission; retain the capability when native shared operations remain.
@ -4095,3 +4108,3 @@0xbefc03ff, 0x8a6ca000, 0xbf920009, 0xbefd210e,};const auto base = DriverDmemBase + AgcDmemOffset;const auto base = driver_dmem_base + AgcDmemOffset;@coderabbitai[bot] on GitHub · 2026-11-14 07:17 UTC · original
Derive the DMEM test addresses from the actual driver mapping.
CheckAgcSystemTablehard-codes0x0fe0000000as the driver base. When the fixed mapping is refused,Gen5Driver::Initialize()maps the driver DMEM at a different address. The test can then fail its mapping check at lines 54333-54340. Its reads and writes attable_address(lines 54345 and 54354-54357) also target the old address.Expose the mapped base from the driver, or query it, and derive
driver_baseandtable_addressfrom that value. The currentg_driver_dmemstate does not retain the base address. Keep the descriptor layout assertions relative to the returned base.@coderabbitai[bot] on GitHub · 2026-11-14 07:17 UTC · original · reviewed
Actionable comments posted: 7
b8fb2dd4-40ed-4868-aa02-add0107b28fcReviewing files that changed from the base of the PR and between
11d834dd82and17246cda5c.src/graphics/host_gpu/graphicContext.hsrc/graphics/host_gpu/renderer/image/imageView.cppsrc/graphics/host_gpu/renderer/pipeline/descriptorHeap.cppsrc/graphics/host_gpu/renderer/pipeline/descriptors.cppsrc/graphics/host_gpu/renderer/pipeline/pipelineCache.cppsrc/graphics/host_gpu/renderer/pipeline/shaders.cppsrc/graphics/presentation/window/vulkanWindow.cppsrc/graphics/shader/recompiler/backend/spirv/SpirvEmitter.hsrc/graphics/shader/recompiler/backend/spirv/spirvEmitterFlow.cppsrc/graphics/shader/recompiler/backend/spirv/spirvEmitterHelpers.cppsrc/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.hsrc/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cppsrc/graphics/shader/recompiler/backend/spirv/spirvEmitterModule.cppsrc/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cppsrc/graphics/shader/recompiler/ir/Serialize.hsrc/graphics/shader/recompiler/ir/ShaderIR.hsrc/libs/agc.cppIncluded review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.
@chaseb64 on GitHub · 2026-11-25 07:00 UTC · original
Hey @bengidev,
While testing the shader translation changes in this PR, I identified two narrow-integer rewrites that produce incorrect 8-bit and 16-bit zero-extension results.
I have a small six-line production patch with separate regression tests that apply cleanly against
17246cda5cf1.I personally reviewed the explanation and ran the focused regression tests on my M5 Pro MacBook. The baseline reproduced the defect, and the patched version passed.
Additional testing on a physical NVIDIA L4 across 1,041 input pairs produced the following results:
Both full CFG suites still encounter the same existing descriptor assertion. Game-specific behavior and independent verification of the raw GPU evidence archive remain outstanding.
Would you be interested in incorporating the correction into this PR? I can provide the isolated patch, regression tests and supporting validation evidence.
AI disclosure: AI-assisted using OpenAI Codex (GPT-6.2 Sol for physical GPU validation; [insert other contributing models from the review package]). I personally reviewed the explanation and reproduced the focused regression on macOS.
View command line instructions
Manual merge helper
Use this merge commit message when completing the merge manually.
Checkout
From your project repository, check out a new branch and test the changes.Merge
Merge the changes and update on Forgejo.