Skip to content

feat: draw on MoltenVK without barycentrics or unrestricted depth range where exact - #5

Merged
giljakoki merged 2 commits into
mainfrom
claude/dazzling-hamilton-xm8ae9
Oct 12, 2026
Merged

giljakoki merged 2 commits into
mainfrom
claude/dazzling-hamilton-xm8ae9

Conversation

@giljakoki

Copy link
Copy Markdown
Owner

What

Two MoltenVK gaps that stopped titles at their first draws on macOS. Both changes are generic, and devices that have the missing feature behave exactly as before.

Barycentrics without a geometry stage (feat(shader)): fragment-shader barycentrics are off on MoltenVK, because SPIRV-Cross rejects PerVertexKHR. A pixel shader that host interpolation could not serve was therefore emulated through a geometry stage, which Metal does not have, and the draw aborted with "geometry shaders are unavailable". Two patterns no longer need the emulation:

  • An input read only as P0 through v_interp_mov_f32 is declared Flat, so it reads the provoking vertex. In first-vertex mode that is the same vertex the emulation read.
  • I/J copied under the v_interp_p2_f32's own EXEC are accepted as the pair itself.

For the patterns that still need the geometry stage, the recompiler logs [recompile] pixel shader 0x… emulates barycentrics: <reason> once per shader. The draw error also names the shaders, the shader path, the topology and the colour target.

Viewport depth outside [0, 1] without VK_EXT_depth_range_unrestricted (feat(agc-driver)): ResolveHostDepth decides the host viewport depth and depth bounds for each draw.

  • Native: the device has the extension, or the range already lies in [0, 1]. The guest values are kept.
  • Unobserved: the draw cannot see its depth (no depth target; or no depth write, the depth test off or ALWAYS/NEVER, and no POS_Z read). It is drawn with [0, 1], keeping the guest's clip space.
  • Anything else throws with a diagnostic of the raw depth registers, the depth state and the device features.

Without the extension, depth bounds are mapped exactly. Bounds on a device without the depthBounds feature throw, and so do depth clears outside [0, 1]. APS5_NO_DEPTH_RANGE_UNRESTRICTED=1 reproduces the macOS behaviour on other devices. The remap that would draw observed out-of-range depth exactly is not part of this PR.

Tested

  • Linux with lavapipe:
    • Lavapipe has geometry shaders but no barycentrics, so it takes the same barycentric path as the Mac.
    • Each change was reviewed adversarially and fixed before this PR.
    • On the branch before rebasing onto main, all 426 agc, shader and recompiler tests pass or skip except agc_driver_prepared_shaders_registered_workgroup_sync, which fails the same way on main with llvmpipe.
    • New tests:
      • the barycentric emulation unit cases;
      • agc_driver_rect_list_barycentric_emulation;
      • the reordered provoking-vertex render test;
      • the ResolveHostDepth table;
      • agc_driver_host_depth_range in four modes: plain, restricted, restricted with APS5_NO_GPL=1 (the macOS path), and restricted with APS5_VERIFY_DRAW_RECIPE=1.
  • Rebased onto main (9d11f29): the full build and the same test set ran again. Of 428 tests, 427 pass or skip on lavapipe; 58 skip for device features lavapipe lacks. agc_driver_prepared_shaders_registered_workgroup_sync fails as on main. check_conventions.py and check_test_registration.py pass.
  • macOS CI: builds and runs the non-GPU tests. Its Test step runs before the Vulkan SDK is installed, so the GPU render tests skip there and need a manual run on a Mac with MoltenVK.
  • Titles: not yet run on a Mac with these changes.

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 in TechnicalDebt
  • 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
  • AI-assisted: yes

🤖 Generated with Claude Code

https://claude.ai/code/session_01HSL58TWgY3qJuxYjEgaYDE


Generated by Claude Code

…entrics

The driver turns fragment-shader barycentrics off on MoltenVK, because
SPIRV-Cross rejects PerVertexKHR. A pixel shader that
HostInterpolationChecker::Lower rejects is then recompiled with
barycentric emulation, which needs a geometry stage. Metal has none, so
the draw aborts with "geometry shaders are unavailable".

Two patterns do not need the emulation:

- An input read only as P0 through v_interp_mov_f32 holds the value of
  one vertex. Without barycentrics it is now declared Flat, so it reads
  the provoking vertex. In first-vertex mode that is vertex 0, the same
  vertex the geometry stage read. Translation records the P0 reads and
  the other reads of each input, only when fragmentShaderBarycentricEnabled
  is false. One rule, ShaderPixelInputInfo::InputIsFlat(input,
  vertexZeroReads, otherReads), decides flatness for the checker,
  ShaderInfoCollector and the SPIR-V input declarations. Devices with
  barycentrics and the emulated retranslation start from empty masks,
  so their output is unchanged. Such inputs now also render on points,
  lines, rect lists, tessellation and mesh pipelines, which threw before
  because the geometry stage cannot serve them.
- I/J copied to other VGPRs under the EXEC of the v_interp_p2_f32 that
  reads them are the pair itself on every lane the p2 writes. The checker
  now looks through such copies. A copy under any other EXEC is still
  emulated.

Lower now reports why it rejects a shader for the patterns that remain.
The recompiler prints "[recompile] pixel shader 0x... emulates
barycentrics: <reason>" once per shader address and reason, so repeated
preparation of the same shader does not repeat it. The draw error on the
geometry-stage path names the addresses of the pixel shader and the
pipeline's first shader, the shader path, topology, rect-list flag,
colour target and provoking-vertex mode; the text is built only when the
draw fails. One run is then enough to identify the shader and the draw.

GuestPixel in the provoking-vertex render test now takes the input
setting as a parameter. The test draws the guest P0 shader with and
without FLAT_SHADE in first-vertex mode before it skips devices without
last-vertex mode, so a device without last-vertex mode, such as
MoltenVK, draws the new path too. The macOS CI does not run it: its Test
step runs before the Vulkan SDK is installed, so the GPU tests skip
there, and the render tests have to be run by hand on a Mac with
MoltenVK. The unit tests also check that an input read only as P0 that
shares a vertex parameter with an interpolated input stays emulated, and
that the recompiler names a P10 read once as the reason. The new
agc_driver_rect_list_barycentric_emulation test draws a rect list whose
pixel shader reads I/J on a device without barycentrics and checks the
draw error.

The console's choice of vertex for P0 of an input without FLAT_SHADE
has not been measured; docs/dev/TechnicalDebt.md records this, and that
in last-vertex mode such an input takes the last vertex without
barycentrics but vertex 0 on triangle lists with them or under the
geometry-stage emulation, where strips throw.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HSL58TWgY3qJuxYjEgaYDE
…nge_unrestricted

MoltenVK has no VK_EXT_depth_range_unrestricted, so the first draw whose
viewport depth range left [0, 1] aborted the title with "viewport depth
outside [0, 1] requires VK_EXT_depth_range_unrestricted". The message did
not say which registers produced the range or whether the draw could see
its depth at all, so nobody could tell which emulation the title needs.

ResolveHostDepth (Pipeline.hpp) now decides, from the decoded state and
the device features, the viewport depth range and depth bounds the host
draws with:

- Native: the device has the extension, or the range already lies in
  [0, 1]. The guest values are kept.
- Unobserved: the draw cannot see its depth. It has no depth target, or
  it does not write depth and its depth test is off or compares ALWAYS
  or NEVER, and its pixel shader does not load POS_Z. It is drawn with
  the range [0, 1] and the guest's clip space and ZCLIP bits, since
  clipping does not depend on the depth range. A depth bounds test does
  not make a draw observe depth: it compares the depth already stored in
  the target, not the depth the draw produces.
- Every other out-of-range draw throws. The remap that would draw it
  exactly is not part of this change, and neither are the SPIR-V
  ClipDistance capability and separate near and far ZCLIP bits, which
  only the remap would read.

Without the extension, depth bounds are mapped as well. A bounds test on
a device without the depthBounds feature (MoltenVK offers it only on
Apple10-family GPUs) throws "device does not support the depth bounds
test" with the diagnostic below, before any mapping, instead of the
pipeline's bare message. Bounds that can never pass a stored depth in
[0, 1] (min > max, min > 1 or max < 0) become (1, 0) on devices that
accept min > max, which Vulkan allows; on a VK_KHR_portability_subset
device, where Metal's behaviour is unknown, they throw. That deliberately
includes inverted bounds inside [0, 1], which were passed to Metal
unchanged before. Other bounds become (max(min, 0), min(max, 1)). Both
are exact while the stored depth lies in [0, 1], so out-of-range bounds
no longer throw on such devices.

For the stored depth to stay in [0, 1], a depth surface that is cleared
to DB_DEPTH_CLEAR outside [0, 1], at its creation or on an HTILE fast
clear, now throws without the extension, naming the surface, its format
and the value. vkCmdClearDepthStencilImage only takes [0, 1] there, and
the value used to reach it unchecked.

Graphics::Draw and Graphics::DrawWithRecipe apply the resolution to a copy
of the state at entry, so the pipeline lookup, the dynamic viewport and
bounds, the per-draw validation and the recipe a draw-cache hit records
from all use the same host values. The resolution depends only on the
decoded state, whose registers are all in the draw key, and on the
device, so a draw-cache hit resolves as the miss did.

The error now prints the raw PA_CL_CLIP_CNTL, PA_CL_VPORT_ZSCALE,
PA_CL_VPORT_ZOFFSET, PA_SC_VPORT_ZMIN_0/ZMAX_0, DB_RENDER_OVERRIDE,
DB_RENDER_CONTROL and DB_DEPTH_CLEAR words, the decoded range, the depth
target format, the depth test, write, compare and bounds, POS_Z, the
rect-list, mesh and tessellation flags and the device features, depth
bounds included. One run then shows whether the remap, a missing
register write or something else is needed. DecodeState keeps those
words and the POS_Z load in State; DB_RENDER_OVERRIDE (0x003) joins
DrawKeyRegisters, and sameDecode compares the new fields.

APS5_NO_DEPTH_RANGE_UNRESTRICTED=1 leaves the extension off on any
device, like APS5_NO_GPL for pipeline libraries, so the macOS behaviour
can be reproduced on Linux and Windows. The device now records
shaderClipDistance and whether it accepts min > max depth bounds, and the
"Vulkan features" log line adds depthClamp, clipDistance and
invertedDepthBounds.

agc_driver_graphics checks a table of ResolveHostDepth results with the
extension on and off, the bounds mapping with and without min > max
support and without the depthBounds feature, the direct ValidateDepthBounds
failure, the exact diagnostic of a decoded draw, the POS_Z decode and that
Draw and DrawWithRecipe resolve before anything else.
agc_driver_host_depth_range draws through the device into a D32 target
with unobserved [-1, 1] and [1, -1] ranges, depth bounds, an observed
[-1, 1] range and clears to 2 at creation and by HTILE fast clear. It
then submits PM4 to the driver: two equal [-1, 1] draws without a depth
target at clip z -0.5, which must make one draw-cache miss and one hit and
cover the whole target (so the guest's clip space was kept), and a draw
whose pixel shader reads POS_Z, which draws natively and otherwise stops
with the PM4-decoded register words. It runs plain, with
APS5_NO_DEPTH_RANGE_UNRESTRICTED=1, with APS5_NO_GPL=1 as well (the macOS
path), and with APS5_VERIFY_DRAW_RECIPE=1, where the repeated draw's
decode must equal a fresh one and every register read must be in the
draw key. Lavapipe has no depthBounds feature, so the bounds draws are
skipped there. docs/dev/TechnicalDebt.md lists the paths, the throws, the
bounds mapping, the clear check and their assumptions, and
docs/user/MACOS.md says which draws now render on MoltenVK and when depth
bounds and clears stop a title.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HSL58TWgY3qJuxYjEgaYDE

Copy link
Copy Markdown
Owner Author

Handover 2/5: storage-image multisampling on MoltenVK (Hades II's next expected stop)

Handover note: this report was written in a cloud session, read-only, against main at 9d11f29. It was not built or run on a Mac. Paths under /tmp/claude-0/... or scratchpad/ refer to that cloud machine and are not available here. Verify every claim against the code before acting on it.

Design written to /tmp/claude-0/-home-user-AnyPS5-macos/5fe1494a-4d35-554a-a635-e6ebd6cf2b56/scratchpad/hades-storage-msaa/design.md. A lavapipe probe used for section 1.3 is in probe/probe.c in the same directory. Full text follows.

Multisampled storage-image access without shaderStorageImageMultisample (MoltenVK): design

Source read: fork main at 9d11f29a (upstream 8fc53cb3 plus the macOS work), read-only checkout. MoltenVK clone at 67b26826, SPIRV-Cross clone at aa217aeb. Paths are relative to the repository root unless they start with MoltenVK/ or spirv_. Nothing in this design has been built or run. The only thing executed was a probe of the local lavapipe (section 1.3).

0. Summary

  • The message comes from ImageType (core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvDescriptors.cpp:131-135). It fires when a shader declares a storage image (Sampled = 2) of dimension 2D_MSAA or 2D_MSAA_ARRAY and the target's capability list has no StorageImageMultisample. MoltenVK never enables that feature, so the capability is never in the list (section 1.3).
  • Only image_store / image_store_pck and the 32/64-bit image_atomic_* opcodes reach it, and only when their MIMG DIM is 6 or 7 (section 1.4). The T# is not involved. The throw happens while the shader is being prepared at registration. That is before any descriptor exists, because the static image interface takes the dimension from the instruction (section 1.5).
  • A failure at registration is only logged at first (ShaderRegistry.cpp:782). It becomes fatal the first time that shader is used (section 1.2).
  • Fixing the capability on its own changes nothing further down the line. On every device, including Linux with the feature present, any multisampled image access fails later when it is bound:
    • a T# of type 14 or 15 throws in the driver (GuestTextureResource.cpp:38-47);
    • a multisampled image heap has no descriptor image shape (DescriptorBindingBuilder.cpp:79-83);
    • the guest range of a host multisampled target is guarded (MultisampleTarget.cpp:321-330).
      The existing tests assert these failures (section 1.7).
  • The design comes in phases:
    • P0: a APS5_NO_STORAGE_IMAGE_MULTISAMPLE=1 knob, plus honest ImageMSArray handling (it currently claims a feature MoltenVK does not have).
    • P1: an exact "deferred refusal". On a device without the feature, a multisampled storage image compiles with no descriptor. A null T# then behaves as a null descriptor, and a real multisampled T# throws when it is bound. This unblocks registration and lets titles run whose multisampled kernels are never bound.
    • P2: answers (a). Under APS5_MSAA_SINGLE_SAMPLE=1, multisampled images (sampled and storage) are addressed as the one-sample resident image of the target. Sample 0 is exact; every other sample reads as sample 0, and stores to samples other than 0 are dropped. Atomics are allowed only with a constant sample 0. No shaderStorageImageMultisample is needed.
    • P3: answers (b) for the real multisampling path. Loads through a sampled multisampled view are exact on MoltenVK. Stores and atomics need a shadow array with one layer per sample, a compute copy-in, and a per-sample fragment pass to copy back. That is feasible and exact for the formats listed in section 3.4, but it is the most expensive part.
  • Recommendation: P0 + P1 + P2 together (about 7 to 8 days). P3a only when a title needs real multisampling quality and reads multisampled textures. P3b planes only if one also writes them under real multisampling.

1. What fails and why

1.1 The throw

  • ImageType (SpirvDescriptors.cpp:108-140) throws FailEmit("storage image multisampling is unavailable on the target device") at :133. It does so when RdnaImageDimensionInfoFor(image.dimension).multisampled != 0 and sampled == 2, and the target's supportedCapabilities lack StorageImageMultisample. FailEmit adds the prefix SPIR-V module emission failed: (SpirvEmitterHelpers.cpp:17-19).
  • The first call that reaches it is the static heap declaration. That declaration runs for every image heap in the layout, before any instruction is emitted (SpirvEmitterHelpers.cpp:420-429). It picks the heap's runtime mode (:424-427) and calls ImageType (:429).
  • ImageType is called again from:
    • StorageImageDescriptorPointer (SpirvDescriptors.cpp:200-210), used by atomics at SpirvImageEmitter.cpp:1023 and :1044;
    • EmitStorageImageWrite (SpirvDescriptors.cpp:212-234). The multisampled OpImageWrite ... Sample is at :231-234.
  • The dimension table maps Dim2DMsaa and Dim2DMsaaArray to MS = 1 (SpirvDescriptors.cpp:23-24).

1.2 When the title sees it

  • Driver::RegisterShader prepares on a background pool (docs/dev/ARCHITECTURE.md:91-93).
  • A failure is logged as Shader 0x%llx could not be prepared after registration: <error> and stored (core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp:774-793).
  • It is rethrown by AwaitRegisteredPreparation (ShaderRegistry.cpp:128-131) the first time the shader is used:
    • from SourceHandleFor / InvocationFor (:382-383);
    • from ShaderPreparationTransaction::Edit / Read (:207-229).
  • A dispatch wraps the rethrow as compute shader 0x...: ... (Execution/src/Driver/Dispatch/Dispatch.cpp:244-285).
  • So the reported lines "for several compute/pixel shaders (e.g. 0x1405e7800)" match the registration log. From the report alone I cannot tell whether the title then stopped, which needs one of those shaders to be used, or whether those shaders were never dispatched.
  • With APS5_DUMP_SHADERS=1, the registration failure writes shader_<address>.req into the working directory (ShaderRegistry.cpp:31-40, ShaderDiagnostics.cpp:52-70).
  • For the macOS bundle, the working directory is ~/Library/Application Support/AnyPS5/<title id> (tools/package_macos_app.py:36-46). The log is ~/Library/Logs/AnyPS5/<title id>.log.

1.3 Why MoltenVK

  • The driver enables the feature only when the device offers it, and adds the capability only then (core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp:1344-1345). The shader device profile cross-checks this (ShaderDeviceProfile.cpp:51).
  • MoltenVK clears every feature (MoltenVK/MoltenVK/GPUObjects/MVKDevice.mm:2795-2796) and never sets shaderStorageImageMultisample (no assignment anywhere in the clone). It was turned off in 1.0.33 (Docs/Whats_New.md:2148).
  • MoltenVK also reports storageImageSampleCounts = VK_SAMPLE_COUNT_1_BIT (MVKDevice.mm:2898) but sampledImageColorSampleCounts = supportedSampleCounts (:2894).
  • MoltenVK gives a multisampled texture only MTLTextureUsageShaderRead. It reads multisampled textures in its own compute resolve (MVKPixelFormats.mm:647-653).
  • Metal Shading Language allows only access::read on texture2d_ms / texture2d_ms_array. I am quoting this from memory of the MSL specification; it was not checked against a local copy. It is consistent with the MoltenVK facts above.
  • Lavapipe probe (my own program in this directory, probe/probe.c, run with the lvp_icd.json driver):
    • llvmpipe (LLVM 20.1.2, 256 bits): shaderStorageImageMultisample=1;
    • storageImageSampleCounts=0x5 and sampledImageColorSampleCounts=0x5, so only 1 and 4 samples;
    • sampleRateShading=1.
    • Lavapipe therefore needs the knob to stand in for MoltenVK, and the tests must use 4x.

1.4 Guest instructions that lead there

  • The decoder takes DIM from MIMG word0 bits 3-5: 6 is Dim2DMsaa and 7 is Dim2DMsaaArray (core/shader/recompiler/RdnaDecoder/src/RdnaImageOpDecoder.cpp:225-237).
  • Address components are x, y, fragid (3) or x, y, slice, fragid (4) (:239-249).
  • With a multisampled DIM, the decoder rejects sample, gather, get_lod (0x60), the mip loads (0x01-0x05), image_store_mip (0x09) and image_store_mip_pck (0x0b) (:356-359).
  • BY2/BY4 and PCK2/PCK4 require Dim2D (:370-378).

What is left:

MIMG opcode IR op resource class multisampled result
image_load 0x00, image_msaa_load 0x80 ImageRead (msaa_load becomes 4 reads, Translation/src/MemoryInstructions/ImageInstructions.cpp:169-181) Sampled (IntermediateRepresentation/src/IrOpcode.cpp:806-811) OpImageFetch ... Sample on a sampled MS image (SpirvImageEmitter.cpp:975-980); does not need the feature
image_get_resinfo 0x0e ImageQueryDimensions Sampled OpImageQuerySize, w = 0 (SpirvImageEmitter.cpp:418-447)
image_store 0x08, image_store_pck 0x0a ImageWrite (ImageInstructions.cpp:183-199) Storage (IrOpcode.cpp:818-820) OpImageWrite ... Sample (SpirvDescriptors.cpp:231-234), throws
image_atomic_* 0x0f-0x1f (RdnaImageOpDecoder.cpp:110-125) ImageAtomic*32/64 Storage (IrOpcode.cpp:821-848) OpImageTexelPointer ... Sample (SpirvImageEmitter.cpp:1044), throws
  • The "sample index" operand is the last address component, fragid, read by ImageSampleIndex (SpirvImageEmitter.cpp:991-996).
  • On AMD hardware this operand is a fragment index. A shader turns a sample into a fragment by reading FMASK.
  • The recompiler emulates every FMASK read as the identity map: 0x76543210 / 0xfedcba98, so fragment i = sample i (SpirvImageEmitter.cpp:1637-1646). The FMASK mode is chosen for any FMASK format (ResourceMaterializer.cpp:809-812, RdnaDescriptorFormat.cpp:108-110).
  • FMASK is accepted only as a direct 32-bit sampled image_load (ResourceMaterializer.cpp:161-165, ResourceTracker.cpp:1187). A storage access to FMASK throws.
  • So under this emulation, the index a store receives is the sample index.
  • Side bug: 64-bit image atomics pass a constant 0 as Sample even for multisampled images (SpirvImageEmitter.cpp:1023), so they always address sample 0.

1.5 Descriptor shapes

  • The static interface keeps the instruction's dimension. ResourceTracker::AddImage records image.dimension = memory.imageDimension (Optimization/src/ResourceTracker.cpp:1143-1171).
  • RuntimeImageModes copies it into every mode (ResourceMaterializer.cpp:625-676). It adds a plain Dim2DMsaa mode for an MSAA array at :667-671.
  • BindingAllocator puts every mode's heap in the layout (Optimization/src/BindingAllocator.cpp:119-128).
  • So the throw happens with no T# at all.

At bind time:

  • The T# must be type 14 (Color2DMsaa) or 15 (Color2DMsaaArray), word3 bits 28-31 (ResourceMaterializer.cpp:66-68, :82-104).
  • Validation requires BASE_LEVEL = 0, LAST_LEVEL = log2(fragments) in 1..3, and MAX_MIP == LAST_LEVEL (:106-121). That means fragments == samples (no EQAA) unless the descriptor is R128.
  • descriptorDimension returns Dim2DMsaa for type 14 whatever the instruction asked for (:98-101).
  • A null T# (dword0 = 0 and dword1 bits 0-7 = 0, :62-64) selects mode 0 (:783).

1.6 The two multisampling paths and storage access today

Fork fallback, APS5_MSAA_SINGLE_SAMPLE=1.

  • The switch is read at core/libs/prx/libSceAgcDriver/Graphics/src/State.cpp:1261-1270.
  • It sets ColorTarget.guestSamples from CB_COLOR_ATTRIB and keeps samples = 1 (State.cpp:931-939). It does the same for depth (:256-257). The fields are at Graphics/include/State.hpp:66,79.
  • A target with samples == 1 takes the resident path:
    • CachedStorageSurface(context, SurfaceForTarget(color)) (Graphics/src/Draw.cpp:1904-1937);
    • SurfaceForTarget builds a 2D, one-level surface at color.address (Draw.cpp:65-89).
  • So the target's texels live in the same StorageTexture that a storage descriptor of the same surface key would find. The key is address|pipeBankXor, extent, layers and mips, tile mode, dimension, base array and storage format (ShaderResources.cpp:793-797).
  • The recompiler knows nothing about the fallback. No target field carries it (core/shader/recompiler/Recompiler.hpp:214-231).
  • The driver still throws on type 14 and 15: resolveDimension (Graphics/src/GuestTextureResource.cpp:38-47). This matches docs/dev/TechnicalDebt.md:413, "A multisampled texture read (image types 14 and 15 ...) still throws".

Upstream real multisampling.

  • MultisampleTarget creates a host multisampled image with usage COLOR_ATTACHMENT | TRANSFER_DST only (Graphics/src/MultisampleTarget.cpp:46-102, usage at :53). It has one layer (:63) and stays in GENERAL (:84-97).
  • It guards the guest range (:195-202). Texture and storage lookups throw on any overlap: ShaderResources.cpp:517 ("a texture read") and :836 ("a storage image access") call RequireNoMultisampleTarget (MultisampleTarget.cpp:321-330).
  • docs/dev/ARCHITECTURE.md:97 describes the same.

1.7 After the capability: the remaining blockers (all devices)

  • DescriptorBindingBuilder::Prepare runs at materialization (core/shader/recompiler/Recompiler.cpp:637). It sets physical.imageShape = ImageShapeForResource(...) for every active heap (Optimization/src/DescriptorBindingBuilder.cpp:390-394). For a multisampled shape that call throws multisampled image resources have no descriptor image shape (:79-83).
  • A null T# selects mode 0, which has the instruction's MSAA dimension. Nothing in the active test (:356-361) excludes null. By reading only, not executed: a null T# on a multisampled image therefore throws too. If so, the MSAA placeholder heaps (Graphics/src/PlaceholderImages.cpp, docs/dev/TechnicalDebt.md:392) are unreachable.
  • The tests assert the refusal for a sampled 2D MSAA load with a type-14 T#:
    • core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp:3034-3057;
    • tests/execution/MultisampleTraceCapture.cpp:160-161.
  • tests/execution/PreparedShaders.cpp:228-280 checks that storage MSAA compiles when the capability is forced on, and throws when it is removed (:276-279).

1.8 Side finding: ImageMSArray

  • Vulkan ties SPIR-V ImageMSArray to shaderStorageImageMultisample (3rdparty/Vulkan-Headers/registry/vk.xml:31549-31551).
  • SPIR-V needs it only for a storage MS array: Sampled == 2 (3rdparty/SPIRV-Tools/source/val/validate_image.cpp:699-704).
  • The driver advertises it unconditionally (VulkanDevice.cpp:1346).
  • The emitter declares it for sampled MS arrays too (SpirvDescriptors.cpp:136).
  • Graphics validation accepts both capabilities unconditionally (Graphics/src/ShaderValidation.cpp:236-238).
  • So on MoltenVK, a sampled MSAA-array read declares a capability whose feature is disabled. MoltenVK and SPIRV-Cross probably ignore it, but the Vulkan validation layer would flag it. Not observed, only by reading.

2. Requirements from the repository rules

  • No comments (docs/dev/CONVENTIONS.md, enforced by tools/check_conventions.py:13).
  • Paths that are not supported throw.
  • An approximation is opt-in and documented in docs/dev/TechnicalDebt.md.
  • No title names or IDs in code.
  • Environment variables follow the strict style of SingleSampleMultisamplingRequested: =1 enables and any other value throws (State.cpp:1261-1265).

3. Design

3.1 P0: knob and capability honesty

  • VulkanDevice.cpp:1344-1346:
    • Parse APS5_NO_STORAGE_IMAGE_MULTISAMPLE: 1 disables, anything else throws.
    • Set enabled.shaderStorageImageMultisample = available && !knob.
    • Push both StorageImageMultisample and ImageMSArray only when the feature is enabled.
    • Store the result in state for later phases. P3 needs it, and so does validation.
  • SpirvDescriptors.cpp:136: emit ImageMSArray only when sampled == 2. For that case :133 has already required the feature.
  • ShaderValidation.cpp:236-238 and the signature at :550: accept StorageImageMultisample / ImageMSArray only when the device enabled the feature. That needs one more bool parameter, passed from the caller of ValidateShaders.
  • PlaceholderImages.cpp:9-16 (Supported): with the feature off, report multisampled storage shapes as unsupported. This mirrors MoltenVK, where creating an image with MS and STORAGE usage is undetermined (MVKImage.mm has no explicit check; MVKPixelFormats.mm:619-623 would request ShaderWrite).
  • Exact: yes. These changes only make the reported capabilities agree with what the device really enables.

3.2 P1: deferred refusal of multisampled storage on devices without the feature (exact)

Goal: compiling never throws. The refusal happens only when a non-null multisampled T# actually reaches the shader.

  • New field. Add MultisampleAccess multisampleAccess = MultisampleAccess::Native to ImageResource (IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/Resources.hpp:60-100).
    • enum class MultisampleAccess { Native, SingleSample, Refused }.
    • Serialize it in ShaderDiskCache.cpp, next to foldTexelOffsetsOnly (:505-506 write, :612-613 read).
  • Setting it. ResourceMaterializer::ApplyStaticInterface (ResourceMaterializer.cpp:831-889) gets the target facts the same way it gets nativeSampleOffsets today. compileVariant computes them from request.target (Recompiler.cpp:387-392). In the per-image loop (:857-878), for a direct image with an MSAA dimension, resourceClass == Storage, and no StorageImageMultisample in the target, set Refused.
  • Modes. RuntimeImageModes (:625): a Refused image returns exactly one mode: Uint if atomic, otherwise Float; one mip; no conversions.
  • Layout. BindingAllocator.cpp:122-127: skip Refused modes, so there is no heap and no ImageType call.
  • Emission. EmitImage / emitMode (SpirvImageEmitter.cpp:1625-1660) for a Refused mode:
    • ImageWrite emits nothing;
    • atomics define a zero of the result type, the same zero EmitValueOrZeroIfCondition yields when inactive (:1012-1050).
    • These are the null-descriptor semantics: stores are discarded and atomics return 0.
  • Binding. ResourceMaterializer::RuntimeImageMode (:780-783): after the null check (which returns 0), if modes.front().multisampleAccess == Refused, throw. The message names the T# words and the missing feature, plus State.cpp:145's SingleSampleHint once P2 exists. Example: a multisampled storage image (image_store or image_atomic with a 2D MSAA dimension) is bound to a multisampled T#, which needs shaderStorageImageMultisample; the device lacks it.
    • This also covers the validation calls at :404 and :590.
  • Exactness. Exact. Stores, atomics and queries behave the same as on a capable device for every null T#. A non-null T# throws, as an unsupported path should.
  • It also removes the null-descriptor refusal of section 1.7 for these images, because they have no heap.

3.3 P2: (a) single-sample addressing under APS5_MSAA_SINGLE_SAMPLE=1

Plumbing.

  • SpirvTarget.singleSampleMultisampledImages (Recompiler.hpp:214-231).
  • CacheKey.hpp:233-249.
  • RequestSerializer.cpp:735-787: bump the version to 17 and read the field when version >= 17.
  • VulkanDevice::buildTarget (VulkanDevice.cpp:2911-2918) sets it from Graphics::SingleSampleMultisampling() (State.cpp:1267-1270).
  • compileVariant passes it to ApplyStaticInterface.

Static interface (ResourceMaterializer.cpp:857-878). When the flag is set, every direct image with an MSAA dimension becomes SingleSample:

  • Dim2DMsaa becomes Dim2D, and Dim2DMsaaArray becomes Dim2DArray. The address layout stays the instruction's own, because access.mem.imageDimension is untouched.
  • Exception: a storage image with atomics whose sample operand is not the constant 0 in every atomic on that resource becomes Refused (P1 machinery) instead. Detect it with the same scan ApplyStaticInterface already uses for texel offsets (:835-853): GetRdnaImageAddressComponentLayout(flags, AddressDimension.coordinateComponents) and HasImmediate() with value 0.
  • Images in bindless tables keep Native. Storage tables are already rejected (ResourceTracker.cpp:1037-1040).

Modes. In RuntimeImageModes (:640-675), a SingleSample image must not get the extra modes that exist for real 2D, 3D or array images:

  • the 3D volume mode :640-644;
  • the 1D line modes :652-661;
  • the cube mode :672-675;
  • the FMASK mode :710.

It keeps the format modes, including the 11_11_10 conversions at :700-704, because R11G11B10 multisampled targets are common.

Descriptor decode.

  • descriptorDimension / decodeImageDescriptor (:82-104, :133-...): for a SingleSample base, type 14 decodes to Dim2D, and type 15 to Dim2DArray or Dim2D (by wantArray).
  • Any other T# type for a SingleSample image throws. What an MSAA instruction does on a non-MSAA resource on the hardware is unknown.
  • EQAA T#s keep throwing through validImageDescriptor.

Emission.

  • CoordU32 (SpirvImageEmitter.cpp:217-238) already takes min(components(image.dimension), components(instruction dimension)). That gives (x, y) or (x, y, slice) from the MSAA address. No change.
  • EmitReadOp (:959-989): with a non-MS dimension it fetches at LOD LodU32, which is 0 because MSAA ops have no mip (:239-247). No change. Every sample reads the one texel.
  • EmitWriteOp (:998-1010): for SingleSample, the condition becomes exec && sample == 0. The sample is read with the existing address code, which ImageSampleIndex (:991-996) should key on AddressDimension(access), the instruction, rather than access.image.dimension. Use Binary(..., OpLogicalAnd, ...) as :969 does.
  • EmitAtomicOp (:1012-...): SingleSample atomics only exist with a constant sample 0, so OpImageTexelPointer on the 2D image with Sample 0 is already what :1044 emits for a non-MS dimension. No change. Fix :1023 (the 64-bit atomic) to use the sample operand as well.
  • QueryDimensions (:418-447): keep today's MSAA answer, w = 0, when the instruction is multisampled. What image_get_resinfo returns in w for an MSAA resource on the hardware is not determined.

Driver.

  • DecodeTextureResource (GuestTextureResource.cpp:38-47, :52-200): types 14 and 15 are accepted only when SingleSampleMultisampling(). They decode as k2D / k2DArray with:
    • mipCount = allocatedMipCount = 1;
    • baseLevel = lastLevel = 0 (LAST_LEVEL and MAX_MIP encode log2 fragments and log2 samples here, not mips);
    • baseLevel == 0 and LAST_LEVEL == MAX_MIP required.
  • ITERATE_256 (word6 bit 10) keeps throwing (:113).
  • Without the fallback, 14 and 15 keep throwing, with SingleSampleHint added.
  • Nothing else changes in the driver. The one-sample k2D surface at the target's address has the same SurfaceKey as SurfaceForTarget (Draw.cpp:65-89, ShaderResources.cpp:793-797), so the storage or sampled access shares the render target's resident StorageTexture. Two conditions must hold, and the end-to-end test checks them:
    • the T#'s SW_MODE must resolve (GuestTextureResource.cpp:130-139) to the same TextureTileMode as ColorTextureTileMode(color.tileMode);
    • the T# must carry no DCC address. Otherwise MetadataMoved evicts it (ShaderResources.cpp:860-863).

Exact versus approximate (the fallback's model, "every guest sample of a pixel is the one host texel", is the one the CB resolve already uses: TechnicalDebt.md:415):

access rule relation to the guest
image_load / image_msaa_load of sample s read the texel exact for s = 0; approximate for s ≠ 0 (reads sample 0)
image_store to sample 0 write the texel exact for sample 0
image_store to sample s ≠ 0 dropped approximate: the guest's sample s would hold the value. Deterministic, and keeps "every sample reads as sample 0"
image_atomic with constant sample 0 atomic on the texel exact for sample 0
image_atomic with any other sample operand Refused: throws when a multisampled T# is bound unsupported, so it throws
image_get_resinfo width, height, layers, w = 0 (unchanged) w unverified

Rejected alternatives:

  • "Ignore the sample index", so every sample addresses the texel. When invocations write different samples of one pixel, the last writer wins and the result is nondeterministic. Atomics on per-sample counters would count N times.
  • "Require a constant 0" for stores. This would throw on the usual for each sample loop.

Both rules agree whenever a shader writes the same value to every sample of a pixel. Under the fallback this is what happens when the value depends only on what it read, because every read returns the texel. The result is then exact with respect to sample 0.

Further fallback limitations to document:

  • A multisampled surface that no one-sample render target wrote is read from guest memory as one-sample texels, which is not the guest's sample layout. This is the same footprint caveat as TechnicalDebt.md:413.

3.4 P3: (b) real multisampling (MultisampleTarget) with shader access

P3a, loads (exact, every device, MoltenVK included).

  • Add VK_IMAGE_USAGE_SAMPLED_BIT to the target image at MultisampleTarget.cpp:53, after checking sampledImageColorSampleCounts.
  • Add DescriptorImageShape::Image2DMultisample (Recompiler.hpp:324-331). Map it in ImageShapeForResource (DescriptorBindingBuilder.cpp:79-99) and in MatchesGuestDimension (GuestTextureResource.cpp:219-228). Serialize it (ShaderDiskCache.cpp:261-262, 288).
  • In cachedTexture (ShaderResources.cpp:515-517), a type-14 T# whose address, format, extent and samples equal a MultisampleTarget (sameTarget, MultisampleTarget.cpp:20-22) binds that target's view instead of throwing.
  • Add a color-attachment-write to shader-read barrier. The image is already in GENERAL.
  • OpImageFetch ... Sample becomes MSL texture2d_ms<T, access::read>::read(coord, sample). That is allowed in kernels; MoltenVK's own resolve does it (MVKPixelFormats.mm:647-653).
  • MS arrays are not needed, because targets have one layer (MultisampleTarget.cpp:63). MoltenVK does support them (MVKDevice.mm:2504; MSL 2.1 at spirv_msl.cpp:17826-17833).

P3b, stores and atomics.

option feasible exact
Bind the MS image as a storage MS image (devices with the feature: RADV, NVIDIA, lavapipe 4x) yes yes
Alias the MS image's memory as a one-sample array no: Vulkan leaves the MS layout implementation-defined (aliasing gives undefined contents), and Metal texture views cannot change the sample count n/a
Planes: a one-sample 2D array with one layer per sample (STORAGE | SAMPLED, MUTABLE_FORMAT). The shader gets MultisampleAccess::Planes: dimension Dim2DArray, layer = sample (+ slice × N for arrays) yes on MoltenVK yes, with the caveats below
Turn compute stores into rasterization no (scatter, atomics with returns) n/a
Render to planes instead of an MS image (N passes with jittered viewports) technically no: shading would run per sample instead of per pixel

How the planes option works:

  • Copy-in (MS to planes) is a compute pass: texelFetch(ms, xy, s) and imageStore(planes, (xy, s)), both through uint views of equal texel size. This is bit-exact. vkCmdCopyImage cannot be used, because the sample counts differ.
  • Copy-out (planes to MS) is a draw into the MS image as a color attachment. The fragment shader reads SampleId (per-sample shading; sampleRateShading is true on MoltenVK, MVKDevice.mm:2801) and writes texelFetch(planes, (xy, SampleId)).
    • It is bit-exact through a uint attachment view when the device renders that integer format multisampled. That is not determined for Apple GPUs.
    • Otherwise it goes through the image's own format:
      • exact for UNORM up to 16 bits on implementations that round to nearest, which Vulkan recommends but does not require;
      • exact for float formats, apart from NaN payloads and possible fp16 denormal flushing on Apple render targets (not determined);
      • not exact for SNORM, where −1.0 has two encodings.
  • Coherence. MultisampleTarget gets a state {Image, Planes, Both}:
    • storage binding: copy in if needed, then Planes;
    • MultisampleTargetView (draw, Draw.cpp:1906-1912), ResolveMultisampleTarget (MultisampleTarget.cpp:280-300), ApplyFastClear (:107-117) and P3a sampled binding: copy out first if the state is Planes. A fast clear also invalidates the planes.
    • If a shader both reads (sampled) and writes (storage) the same T#, its reads go to the planes as well.
  • Cost estimate (not measured). At 4x 1920×1080 RGBA16F, each direction moves about 66 MB.

Recommendation: implement P3a, plus the direct storage bind on capable devices, when a title needs real multisampling quality. Implement planes only after seeing a title that writes multisampled images under real multisampling. On MoltenVK the fallback (P2) covers storage access with no copies.

4. Files and functions to change

phase file function / place
P0 core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp feature enable :1344-1346 (knob, ImageMSArray only with the feature)
P0 core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvDescriptors.cpp ImageType :136
P0 core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp ValidateShaders :236-238, :550, and its caller
P0 core/libs/prx/libSceAgcDriver/Graphics/src/PlaceholderImages.cpp Supported :9-16
P1 .../IrMetadata/Resources.hpp ImageResource (new enum field)
P1 core/shader/recompiler/Optimization/src/ResourceMaterializer.cpp ApplyStaticInterface :831-889, RuntimeImageModes :625, RuntimeImageMode :780
P1 core/shader/recompiler/Optimization/src/BindingAllocator.cpp place :119-128
P1 core/shader/recompiler/SpirvBackend/src/SpirvImageEmitter.cpp EmitImage / emitMode :1625-1660
P1 core/shader/recompiler/Recompiler.cpp compileVariant :387-392
P1 core/shader/recompiler/ShaderDiskCache.cpp image fields :505, :612
P2 core/shader/recompiler/Recompiler.hpp, CacheKey.hpp, ControlFlow/src/RequestSerializer.cpp target field, key, serialization version 17
P2 ResourceMaterializer.cpp descriptorDimension :82, decodeImageDescriptor :133, modes :640-710
P2 SpirvImageEmitter.cpp ImageSampleIndex :991, EmitWriteOp :998, atomic64 :1023, QueryDimensions :418
P2 VulkanDevice.cpp buildTarget :2911
P2 core/libs/prx/libSceAgcDriver/Graphics/src/GuestTextureResource.cpp resolveDimension :38, DecodeTextureResource :52-200
P3a MultisampleTarget.cpp, ShaderResources.cpp :515-517, DescriptorBindingBuilder.cpp:79-99, Recompiler.hpp:324, GuestTextureResource.cpp:219, ShaderDiskCache.cpp:261,288, the recorder barriers sampled MS bind
P3b the same, plus new copy kernels (compute + fragment), the MultisampleTarget state machine, and MultisampleAccess::Planes in the recompiler planes

5. Tests (Linux, lavapipe)

All of these run under ANYPS5_NO_SHADER_CACHE=1. GPU tests skip with return code 77 when there is no device. Lavapipe offers 1x and 4x, so the tests use 4x.

P0

  • New CTest entry agc_driver_prepared_shaders_no_storage_multisample: agc_driver_prepared_shaders_tests with ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_NO_STORAGE_IMAGE_MULTISAMPLE=1", next to the loop at core/libs/prx/libSceAgcDriver/CMakeLists.txt:1182-1215. It checks that:
    • device.ComputeTarget(32).supportedCapabilities has neither StorageImageMultisample nor ImageMSArray;
    • an invalid knob value throws when the device is created.
  • In tests/execution/PreparedShaders.cpp, a sampled 2D MSAA-array image_load compiles with no OpCapability ImageMSArray. Scan the words as the test at :252-275 does.
  • tests/ShaderDeviceProfile.cpp:100: an ImageMSArray without the feature is refused.

P1

  • PreparedShaders.cpp:276-279 changes. With the capability removed, all five variants (:243-250) prepare. The module has no StorageImageMultisample, no ImageMSArray, no OpImageWrite and no OpImageTexelPointer, and the atomics yield 0.
  • tests/ShaderMemory.cpp, next to verifyMultisampledImageCapture (:3034), for a storage image_store with DIM=6:
    • RuntimeImageMode of a null T# returns 0 and DescriptorBindingBuilder::Prepare creates no binding;
    • with the type-14 descriptor of :3044 it throws the new message.
  • New tests/execution/MultisampleStorage.cpp, modeled on MultisampleTraceCapture.cpp:27-125 (register a compute shader, submit a DCB). Run it under APS5_NO_STORAGE_IMAGE_MULTISAMPLE=1:
    • a dispatch with a null T# completes and leaves the output buffer unchanged;
    • a dispatch with a type-14 T# fails with the new message (ExpectFailure as at :127-136).
  • ShaderDiskCache round trip of the new field, using the pattern at tests/ShaderDiskCache.cpp:827-876.

P2

  • Recompiler-level, no environment needed: with target.singleSampleMultisampledImages = true and the capability removed:
    • the five variants compile to non-MS OpTypeImage;
    • OpImageWrite sits behind OpIEqual(sample, 0), which constant-folds for variants with sample 3 and 2;
    • the atomic variant with sample 0 compiles to Sample 0 on a 2D image;
    • the atomic variant with sample 3 is Refused and throws at Prepare with a type-14 T#.
  • RequestSerializer version 17 round trip, plus the legacy-trailer test at ShaderMemory.cpp:1728. The CacheKey must differ when the flag differs.
  • In tests/Graphics.cpp, singleSampleMultisampleTests (:1817; CTest agc_driver_graphics_single_sample_msaa, CMakeLists.txt:1123-1124): DecodeTextureResource of a type-14 T# gives k2D, 1 mip, lastLevel 0. An EQAA T# throws. Without the variable, the message carries the hint.
  • End to end, tests/execution/MultisampleStorage.cpp single-sample under APS5_MSAA_SINGLE_SAMPLE=1;APS5_NO_STORAGE_IMAGE_MULTISAMPLE=1, and again without the knob to show the path does not depend on the feature:
    1. Draw a 4x color target filled with A, using DrawCommands() from MultisampleTraceCapture.cpp:84-125 with CB_COLOR_ATTRIB NUM_SAMPLES = 2 and PA_SC_AA_CONFIG 4x.
    2. Dispatch threads (x, y, s) that store B_s through image_store DIM=6 to a type-14 T# at the target's address.
    3. Dispatch image_load of sample 2 into a buffer.
    4. Expect the buffer and the guest bytes at the target (one-sample layout) to hold B_0.
    5. Expect one StorageTexture for both, for example through StorageImageCached / the storage counters.
    6. A second case: atomics with a constant sample 0 add exactly once per pixel.

P3

  • On lavapipe with the feature, a render with per-sample distinct values (sample-mask export), then image_load of each sample through P3a, must return them.
  • Under the knob, P3b:
    • the copy-in / copy-out round trip is bit-exact for R8G8B8A8_UNORM, R16G16B16A16_SFLOAT and R32_UINT, and the R8_SNORM −1.0 caveat shows;
    • a compute per-sample store followed by a CB resolve gives the average.

6. Documentation

  • docs/dev/TechnicalDebt.md:413: replace "A multisampled texture read ... still throws" with the P2 rules and the table above. That covers: sample 0 exact; other samples read as sample 0; stores to other samples dropped; atomics only with a constant sample 0, otherwise a throw at bind; ITERATE_256, EQAA and bindless MSAA throw; surfaces not written by a target are read as one-sample texels; resinfo w is unverified.
  • docs/dev/TechnicalDebt.md:392: under P1, multisampled storage without the feature no longer uses a placeholder. A null T# drops stores and returns 0.
  • docs/user/USAGE.md:150-154 (multisampled render targets): with APS5_MSAA_SINGLE_SAMPLE=1, multisampled textures are read and written as the one-sample image.
  • docs/user/MACOS.md:80-90: MoltenVK has no shaderStorageImageMultisample, so titles that write multisampled images need APS5_MSAA_SINGLE_SAMPLE=1.
  • docs/dev/ARCHITECTURE.md:97: P2, and later P3.
  • docs/dev/BUILD.md, tests section: APS5_NO_STORAGE_IMAGE_MULTISAMPLE=1 stands in for MoltenVK on Linux.
  • P3b would get its own TechnicalDebt entry for the format caveats.

7. Effort (one developer, estimates)

phase days
P0 0.5
P1 2
P2 4 to 5 (including the end-to-end test)
P3a 4
P3b direct (capable devices) 2
P3b planes (MoltenVK) 8 to 12

8. What to ask the user to send

  1. The build they ran: the COMMIT file of the package (.github/workflows/macos.yml:131-151), or git rev-parse HEAD.
  2. Whether the title stopped, and if so where. Send the last ~200 lines of ~/Library/Logs/AnyPS5/<title id>.log and every could not be prepared after registration line (all addresses).
  3. One run started with open --env APS5_DUMP_SHADERS=1 Title.app, plus --env APS5_MSAA_SINGLE_SAMPLE=1 if they used it before. Then send the shader_*.req files from ~/Library/Application Support/AnyPS5/<title id>/, at least shader_1405e7800.req.
    • These contain the title's shader code and registers.
    • agc_shader_replay (core/libs/prx/libSceAgcDriver/tools/ShaderReplay.cpp:1-2) can disassemble them on Linux and show DIM, opcode and sample operands.
  4. Whether APS5_MSAA_SINGLE_SAMPLE=1 was set, and whether the title has an anti-aliasing setting that changes anything.
  5. After P1 lands, a run with APS5_TRACE_MSAA=1. Its [msaa] lines print the multisampled T#s with the shader address at capture (Dispatch.cpp:255-257). Today the registration failure is rethrown before capture (Dispatch.cpp:246), so the trace cannot show them yet.

9. Not determined

  • What the failing shaders do: opcodes, DIM, sample operands, stage. This needs the .req dumps.
  • Whether the title binds real multisampled T#s to them at all, with which formats and sample counts, and whether the T#s carry DCC.
  • Whether the run stopped on this error. It is fatal only when one of those shaders is used.
  • The MSL rule that multisampled textures are read-only. I quote it from memory; MoltenVK's behavior agrees with it.
  • Whether MoltenVK or Metal accepts an image with MS and STORAGE usage.
  • Whether Apple GPUs render R32_UINT-class views multisampled, and whether they keep fp16 denormals and NaN payloads in render targets. Both matter for whether P3b is bit-exact.
  • What image_get_resinfo returns in w for MSAA on PS5 hardware.
  • How a PS5 MSAA store behaves when FMASK is not identity. The identity emulation is inferred from the repository; Mesa's radeonsi expands FMASK before shader image stores, which I recall but did not check here.
  • Whether the T# SW_MODE of a fallback target always maps to the target's TextureTileMode, so that the SurfaceKey matches. The P2 end-to-end test settles it.
  • The null-T# refusal in DescriptorBindingBuilder (section 1.7). I found it by reading and did not run it.

Generated by Claude Code

Copy link
Copy Markdown
Owner Author

Handover 3/5: Crash 4 out-of-memory, analysis of the macOS memory path

Handover note: this report was written in a cloud session, read-only, against main at 9d11f29. It was not built or run on a Mac. Paths under /tmp/claude-0/... or scratchpad/ refer to that cloud machine and are not available here. Verify every claim against the code before acting on it.

The harness refused to let me write crash4-memory/analysis.md ("Subagents should return findings as text"), so the full analysis is below. Reference sources I fetched are under /tmp/claude-0/-home-user-AnyPS5-macos/5fe1494a-4d35-554a-a635-e6ebd6cf2b56/scratchpad/crash4-memory/: XNU main f6217f89 in xnu/ and shadPS4 main e0a46675 in shadps4/. The MoltenVK clone used is bary-moltenvk/moltenvk at 67b26826.

Out of memory after grabbing all direct memory on macOS: analysis of the current code (main-ro 9d11f29)

0. Bottom line

  1. Most likely cause (moderate confidence, not confirmed). AnyPS5 uses two fixed numbers: 13824 MiB of direct memory (DirectMemory.hpp:10) and a 448 MiB flexible-memory budget (Export.cpp:41). Nothing reads the title's own memory parameters.
    • On the PS4, a title sets its flexible-memory size in SceKernelMemParam.flexible_memory_size, and the kernel takes that size out of direct memory. shadPS4 does the same (5.1).
    • The reported sequence fits a title that sets a large flexible size (about 5.3 GiB or more). It takes direct memory in halving chunks until the allocation fails, which on AnyPS5 is all 13824 MiB, more than such a title would get on the console. It then asks for its flexible memory.
    • AnyPS5 refuses that request with SCE_KERNEL_ERROR_ENOMEM (0x8002000C) in _mapFlexible, because the budget is 448 MiB (Export.cpp:98-105).
    • Since the merge, the budget is also reduced by the title's own image segments (Export.cpp:99,101), so the next run will hit this limit sooner.
  2. Ruled out for the macOS path in the current code (details in 5.4). None of these turns a request into a clean failed ~5.3 GiB allocation:
    • host RAM or overcommit,
    • MAP_NORESERVE,
    • shared-memory size limits,
    • virtual address space.
  3. The "address-based build copies N MiB … past 6144 MiB" message is a GPU-side abort at draw time, not an out-of-memory error. It is probably the next limit after the memory fix (5.3).
  4. The macOS guest arena is never reserved (GuestArena.cpp:153-185 has only Linux and Windows branches). Every macOS guest mapping goes wherever the host has room.

What I could not determine:

  • I do not have the log ~/Library/Logs/AnyPS5/PPSA02433.log or the title's allocator code.
  • I do not know the title's mem_param value.
  • I do not know whether the PS5 kernel shares one total between direct and flexible memory like the PS4.
  • I could not tell whether the ~5.3 GiB failure was a flexible map, a direct allocation or a Vulkan allocation. The log lines in section 7 settle this.

1. How each call behaves on macOS today

  • sceKernelGetDirectMemorySize: always 0x360000000 (13824 MiB), whatever the host RAM or title parameters (Export.cpp:174-176).

  • sceKernelAvailableDirectMemorySize: the largest free contiguous run in [start, min(end, 13824 MiB)), aligned. With no free run it returns EAGAIN (0x80020023) and sets phys and size to 0 (Export.cpp:142-150, MemoryPool.cpp:75-101).

  • sceKernelAllocateDirectMemory, …Main…, sceKernelMemoryPoolExpand:

    • First fit, lowest address first, stepping through the range by align (MemoryPool.cpp:15-32).
    • When nothing fits it returns EAGAIN and logs nothing (MemoryPool.cpp:31).
    • On success it creates one backing per allocation: shm_open + shm_unlink + ftruncate(len) (DirectMemory.cpp:315-328, 1066-1084).
    • XNU only creates the memory objects; pages are committed when touched (xnu/bsd/kern/posix_shm.c:607-643).
    • The per-object size limit is about 16 TiB (ANON_MAX_SIZE, xnu/osfmk/mach/vm_param.h:245-246).
  • sceKernelMapDirectMemory (also 2, Named, BatchMap op 0): DoMapDirect (DirectMemory.cpp:829-861). With no arena, MapPlaced takes one of three paths:

    • Anywhere: mmap(nullptr, len+align) and trim (DirectMemory.cpp:686-709).
    • At or above a hint: mach_vm_map(VM_FLAGS_ANYWHERE) from the hint (DirectMemory.cpp:183-194, 659-670).
    • Fixed: plain MAP_FIXED, or MapFixedNoReplace with MAP_NO_OVERWRITE (DirectMemory.cpp:648-649).

    Then AddMapping overlays the backing with MAP_SHARED|MAP_FIXED (DirectMemory.cpp:363-369, 521-539) and registers write watching (DirectMemory.cpp:445-460).

  • sceKernelMapFlexibleMemory (also Named, Internal, BatchMap op 3): _mapFlexible (Export.cpp:98-109). If len > 448 MiB − (image segment bytes + live flexible) it does not map and returns ENOMEM, after printing (always, not only with tracing) [memory] flexible memory exhausted: request 0x… with 0x… of 0x1c000000 in use (Export.cpp:103).

  • Flexible size queries: available = 448 − images − used; configured is hard-wired to 448 MiB (Export.cpp:370-382).

  • Image charge on macOS: the MH_EXECUTE image plus *.guest.prx images. For a relinked image only __ELF* segments count, each rounded to 16 KiB (ModuleInfo.cpp:221-244, 454-456).

  • sceKernelReserveVirtualRange: DoReserveVirtual maps PROT_NONE anywhere, at or above a hint, or fixed (DirectMemory.cpp:1037-1064).

  • libc anonymous mmap: goes to DoMapAnon with no budget at all (PosixMemory.cpp:92-104).

Effect of the merge on macOS. It changed only two things:

  • the flexible image charge;
  • the AMM reservation (Apr.cpp:286-308). On macOS it still reserves 2 × 32 GiB wherever the host has room (Apr.cpp:291-298).

DirectMemory.cpp gained only DoMapFileBacked (throws on macOS, DirectMemory.cpp:920-926) and a Windows-only DoMprotect path. The direct-memory path is the same as in the user's earlier build (git diff 2dee5723 9d11f29a).

2. What the title sees

  1. sceKernelGetDirectMemorySize() returns 0x360000000.
  2. After the 300 MiB block at physical address 0 (first fit puts it there), AvailableDirectMemorySize(0, 0x360000000) returns (0x12C00000, 13524 MiB).
  3. The grab loop succeeds until the pool is empty. The pool is a fixed array of 13824 MiB / 16 KiB pages (MemoryPool.cpp:7,152), so the live total cannot exceed 13824 MiB.

The reported sizes do not add up.

  • 300 + 6912 + 3456 + 1728 + 864 + 432 + 216 + 108 = 14016 MiB, which is more than 13824. With the 300 MiB block live, the 216 step must fail (132 MiB left), the 108 step succeeds, and so on.
  • 6912 is exactly 13824 / 2, so the chunk sizes come from GetDirectMemorySize, not from the available size.
  • Either the list is approximate, or the 300 MiB block was released first. The trace lines allocate physical / release physical (DirectMemory.cpp:1083,1092) show which.
  • Either way the title ends up holding all 13824 MiB, and every later direct allocation gets a silent EAGAIN.

Further observations:

  • Chunks are mapped at host-chosen addresses, not inside the PS5 application area 0x2_0000_0000–0xFC_0000_0000 (GuestArena.cpp:40-43).
  • Pages are committed only when touched.
  • The write-watch table costs one byte per host page, about 3.4 MB for 13.5 GiB with 4 KiB pages (GuestWriteWatch.cpp:332-337).
  • Configured flexible memory reads 448 MiB; available reads 448 MiB minus the title's __ELF* segments.

3. The macOS guest arena

  • Never reserved. _base and _end stay 0 (GuestArena.cpp:251-252), so Available() is false (:56-58) and GuestArenaRange reports 0/0 (:299-302).
  • Not used by the macOS mapping code. ArenaAvailable() exists only on Linux (DirectMemory.cpp:568-578). The macOS branches call mmap, munmap and mach_vm_map directly (DirectMemory.cpp:580-595, 648-649, 659-670, 686-709). The AMM falls back to a host placement (Apr.cpp:291-298; docs/dev/TechnicalDebt.md:123). The tests skip the arena checks (core/libs/tests/GuestMemory.cpp:1756-1771).
  • MAP_NORESERVE is irrelevant on macOS. The only use is the Linux TryReserve (GuestArena.cpp:210-228). XNU only lists the flag in its accepted-flags mask and never reads it again (xnu/bsd/kern/kern_mman.c:366).
  • Virtual address space is not a constraint. Rosetta x86_64 has a 47-bit user space, and 13.5 GiB + 64 GiB of AMM + 5.3 GiB fit easily. Not checked on the user's machine.

4. Changes from the merge relevant to this run

  • Image charge on flexible memory. _mapFlexible and AvailableFlexible subtract GuestImageSegmentBytes_nid_no_patch() (Export.cpp:99,101,372-374). For a large eboot, available flexible memory can reach 0 while the image still loads (TechnicalDebt.md:183). Expect the next run to fail at the same point or sooner.
  • No change for macOS in direct size, pool, backing or placement.
  • Guest arena: only the AddressSanitizer offset changed (GuestArena.cpp:35-43).

5. Why a ~5.3 GiB request fails after direct memory runs out (ranked)

5.1 Fixed direct/flexible split; the title's memory parameters are ignored (most likely)

Evidence

  • The two budgets are separate constants (DirectMemory.hpp:10, Export.cpp:41), and configured flexible is hard-wired (Export.cpp:378-382).
  • Nothing reads mem_param; a search for mem_param, MemParam and flexible_memory_size finds nothing. The only process-parameter reader takes libc parameters at 0x38 (ApplicationHeap.cpp:142-143).
  • PS4 layout: OrbisProcParam has libc_param at 0x38 and mem_param at 0x40; OrbisKernelMemParam.flexible_memory_size is at +0x10 (shadps4/src/core/linker.h:18-43).
  • shadPS4 sets flexible memory to that field + 64 MiB base and direct to total − that (linker.cpp:114-147, memory.cpp:55-100). Its default is 512 MiB including the base, so 448 MiB usable (src/core/libraries/kernel/memory.h:15-16), the same as AnyPS5.
  • Numeric hint: 13824 + 448 + 64 = 14336 MiB, exactly 14 GiB. AnyPS5's direct size looks like "a 14 GiB total minus the default flexible size". A title that sets flexible size F would then get about 14272 − F MiB of direct memory on the console; for F ≈ 5.4 GiB that is roughly 8.9 GiB, not 13.5.
  • The described pattern matches: take direct memory until failure, map it, use flexible memory "for the rest". The 5.3 GiB is likely the title's own configured flexible size. It cannot come from AvailableFlexible, which never reports more than 448 MiB.

What is unverified:

  • the PS5 offsets (the libc offset 0x38 matches, which supports them);
  • that the PS5 takes the configured flexible size out of direct memory;
  • the title's value.

Confirming line: [memory] flexible memory exhausted: request 0x15xxxxxxx … (0x150000000 = 5376 MiB ≈ 5.25 GiB).

5.2 A direct allocation after direct memory runs out (same root cause, different call)

A direct or MemoryPoolExpand request gets a silent EAGAIN (MemoryPool.cpp:31). The remedy is the same: match the console's direct and flexible sizes.

How to recognise it:

  • no flexible memory exhausted line;
  • the trace shows allocate physical sizes adding up to 0x360000000;
  • no map anon line of about 5.3 GiB.

5.3 GPU-side Vulkan allocation or abort (possible only if the failure happened during rendering)

Ways the GPU side can fail at this size:

  • Host import refused. The budget is APS5_HOST_IMPORT_MIB, default 6144 (GuestBufferMemory.cpp:634-655). A chunk larger than the 8 MiB window is imported whole (VulkanDevice.cpp:1193; GuestBufferMemory.cpp:570-593), so a 6912 MiB chunk is refused.
  • Heap mirror. The fallback is a Vulkan buffer the size of the range (GuestBufferMemory.cpp:1289-1355). A failure throws AGC graphics: heap mirror of 0x…+0x…: … (:905-913, :1351).
  • MoltenVK size limit. It refuses anything above maxBufferLength (MVKDevice.mm:851,2684; MVKDeviceMemory.mm:245) and logs [mvk-error] VK_ERROR_OUT_OF_DEVICE_MEMORY: vkAllocateMemory(): Could not allocate … of size N bytes (MVKDeviceMemory.mm:447).
  • Copy limit. Copies over APS5_ADDRESS_COPY_MAX_MIB (default 64) call std::abort with FATAL: an address-based build copies … (GuestBufferMemory.cpp:2185-2205, message at :1699-1712).
    • The "6144" in the earlier run means APS5_ADDRESS_COPY_MAX_MIB=6144 was set, or it was the import-budget line (:637-655).
    • Raising the copy limit allows multi-GiB staging buffers, which fail in BufferPool::AllocateMemory (BufferPool.cpp:44-64).

Why this ranks below 5.1: the failure followed the start-up grab of direct memory, and address-based builds happen only at draw or dispatch time. This becomes the likely next limit once 8–13 GiB of GPU-visible direct memory exceeds the 6 GiB import budget. I do not know the M5 Pro's maxBufferLength.

5.4 Ruled out as the cause of a failed ~5.3 GiB allocation

  • Host RAM or overcommit. macOS commits nothing in advance. Running out shows up as swap pressure, the "out of application memory" dialog or a jetsam kill, not a failed mmap. It is still a slowdown risk on 24 GB: 13.5 GiB of guest memory + heap mirrors (budget 24 GiB, GuestBufferMemory.cpp:896-903) + 6 GiB of pinned imports.
  • Shared-memory limits. One ftruncate per object (posix_shm.c:582-586), done once; size limit about 16 TiB (vm_memory_entry.c:338); the only count limit is UINT_MAX users per object (posix_shm.c:141,1021).
  • Virtual address space. See section 3.
  • The 6144 copy limit. It is a FATAL abort, not an out-of-memory error.

6. Fixes, ranked by confidence

Fix 1 — diagnostics (certain value, small)

Problem: the title's memory parameters are never logged, and a failed direct allocation is silent.

Changes:

  • Export.cpp: log once at first use: [memory] process parameters: flexible memory size 0x… (mem_param …), direct 0x…, flexible budget 0x…, image segments 0x… (none when there is no parameter segment).
  • MemoryPool.cpp: PhysicalMemoryPool::Alloc (:31): trace a failed allocation as [memory] direct allocation 0x… in [0x…,0x…) align 0x… failed; largest free 0x…, gated by APS5_TRACE_MEMORY. Expose Trace from DirectMemory.cpp:249-262 through DirectMemory.hpp.
  • Export.cpp: sceKernelAvailableDirectMemorySize: trace the query and its result.
  • Export.cpp: _mapFlexible (:103): add the configured size to the existing message.

Test: in core/libs/tests/GuestMemory.cpp, assert that a failed allocation returns EAGAIN with its output untouched.

Fix 2 — honour the title's flexible size (likely root cause)

2a. Read the title's setting in core/libs/prx/libc/src/ApplicationProcessParameters.cpp:

  • Add a non-throwing FindApplicationProcessParameters_nid_no_patch() that returns null when there is no 0x61000001 segment.
  • Add a pure parser std::optional<std::uint64_t> ConfiguredFlexibleMemoryBytes(const void*):
    • throw on bad magic or size < 0x40 (the checks at ApplicationHeap.cpp:142);
    • return empty when size < 0x48, mem_param (at 0x40) is null, mem_param->size < 0x18, or the pointer at +0x10 is null;
    • otherwise return the value it points to.

2b. Use it in Export.cpp. Replace FLEXIBLE_MEMORY_SIZE with FlexibleMemoryBytes(): the configured value if present, otherwise 448 MiB, with APS5_FLEXIBLE_MEMORY_MIB overriding both. Use it in _mapFlexible, sceKernelAvailableFlexibleMemorySize and sceKernelConfiguredFlexibleMemorySize. The env override alone allows an immediate A/B run.

2c. Take the extra flexible memory out of direct memory. Add DirectMemoryLimit() = DIRECT_MEMORY_SIZE − max(0, FlexibleMemoryBytes() − 448 MiB) with an APS5_DIRECT_MEMORY_MIB override. Use it at:

  • MemoryPool.cpp:21 (Alloc), :79 (LargestFree), :107 (FreeRun);
  • Export.cpp:139 (AllocateMain), :175 (GetDirectMemorySize).

Keep the arrays and the validation sites (Export.cpp:228, DirectMemory.cpp:832, MemoryPool.cpp:41) at the compile-time maximum.

Rules and documentation:

  • 2a/2b follow the title's own request (PS4 semantics). 2c assumes the PS5 shares one 14 GiB total.
  • Both need a docs/dev/TechnicalDebt.md entry next to line 183, stating that the PS5 layout is unmeasured.
  • If 2c counts as an approximation, ship it opt-in via APS5_DIRECT_MEMORY_MIB. Without 2c the title holds 13.5 GiB plus its flexible size, which risks swapping on 24 GB.
  • No title names or IDs in code.

Tests:

  1. A pure parser test over synthetic parameter blocks covering every case above, including a bad magic (throws).
  2. GuestMemory.cpp with ENVIRONMENT APS5_FLEXIBLE_MEMORY_MIB=1024 (set in core/libs/prx/libkernel/CMakeLists.txt:961-969). Assert configured flexible = 1 GiB, a 768 MiB map succeeds and available drops by 768 MiB, and with 2c GetDirectMemorySize == 13824 − 576 MiB.
  3. A test that mimics the title: a 300 MiB block, then halving from GetDirectMemorySize() down to 16 KiB. Assert the sum equals the limit, the next allocation and AvailableDirectMemorySize return EAGAIN with 0/0, and a flexible map of (configured − images) succeeds; release everything. Backing is lazy on Linux (memfd) and macOS (shm).

Fix 3 — macOS file-descriptor leak (certain bug, not this crash)

~PhysicalBacking never closes the per-allocation shared-memory descriptor on macOS (DirectMemory.cpp:352-358, opened at :320). OpenFileLimit is Linux-only (OpenFileLimit.cpp:1), and the launchd soft limit is 256 descriptors.

Fix: ::close(file) under __APPLE__, and enable OpenFileLimit on macOS with min(rlim_max, OPEN_MAX).

Test: 2000 allocate/release cycles, then assert the descriptor count is stable.

Fix 4 — GPU follow-ups (medium confidence they are the next limit)

In GuestBufferMemory.cpp: importAllocation and acquireMirror, refuse or split ranges above the device's maxMemoryAllocationSize before calling vkAllocateMemory. Report the 6144 MiB import budget together with the RAM size.

Test: a mock limit, as in libSceAgcDriver/tests/BufferPool.cpp:357-421.

Fix 5 — hardening without an arena (low priority, separate change)

On macOS, a guest MAP_FIXED without NO_OVERWRITE over a range the guest does not own uses plain MAP_FIXED (DirectMemory.cpp:649) and can overwrite host mappings. Linux guards this at DirectMemory.cpp:638-639.

Fix: use MapFixedNoReplace when !mutation.Covers(...) and throw on EEXIST.

Test: adapt CheckNoOverwriteRejectsHostOccupiedMapping (GuestMemory.cpp:719).

7. What to ask the user for

A. From the existing log (no rerun):

grep -n -E "\[memory\]|flexible memory|[Oo]ut of memory|OOM|Ran out|0x8002000c|0x80020023|FATAL|terminat|uncaught|\[gpu\] host import|heap mirror|\[mvk-error\]|VK_ERROR_OUT_OF|\[bufferpool\]|AMM:" ~/Library/Logs/AnyPS5/PPSA02433.log | tail -n 200
tail -n 150 ~/Library/Logs/AnyPS5/PPSA02433.log

The decisive line is [memory] flexible memory exhausted: request 0x… with 0x… of 0x1c000000 in use. Also ask for the title's own out-of-memory text (bytes and alignment) and the 50 lines before it.

B. Run settings:

  • all APS5_* variables set for that run, in particular APS5_ADDRESS_COPY_MAX_MIB (was it 6144?), APS5_HOST_IMPORT_MIB, APS5_HEAP_MIRROR_MIB and APS5_NO_HOST_IMPORT;
  • the package's COMMIT file and sysctl hw.memsize;
  • whether macOS showed "out of application memory".

C. Rerun with tracing. Start from Terminal; the launcher passes the environment and appends stdout and stderr to the log (tools/package_macos_app.py:36-47):

APS5_TRACE_MEMORY=1 "/path/to/<App>.app/Contents/MacOS/launch"
grep -n "\[memory\]" ~/Library/Logs/AnyPS5/PPSA02433.log | grep -E "allocate physical|release physical|map direct|map anon|reserve |flexible" | tail -n 120

Expected if 5.1 is right: allocate physical lines (DirectMemory.cpp:1083) adding up to 0x360000000, map direct lines (:859), then the flexible line. Failed direct allocations are not traced today; Fix 1 adds that.

D. GPU limits:

vulkaninfo 2>/dev/null | grep -E "maxMemoryAllocationSize|minImportedHostPointerAlignment|heapSize"

E. With Fix 1 and 2b built: the startup line [memory] process parameters: flexible memory size 0x…. Then an A/B run with APS5_FLEXIBLE_MEMORY_MIB=6144; getting past this point confirms 5.1.

8. Side findings (not the cause of this crash)

  • Failed direct allocations are silent (MemoryPool.cpp:31).
  • The macOS descriptor leak (Fix 3).
  • MAP_FIXED can overwrite host mappings because there is no arena (Fix 5).
  • Mapping hints that land on host-occupied memory are moved silently by VM_FLAGS_ANYWHERE (DirectMemory.cpp:184-194), and guest addresses fall outside the PS5 application area.

Generated by Claude Code

Copy link
Copy Markdown
Owner Author

Handover 4/5: preview of the next scheduled sync (mugurc macos-port and upstream)

Handover note: this report was written in a cloud session, read-only, against main at 9d11f29. It was not built or run on a Mac. Paths under /tmp/claude-0/... or scratchpad/ refer to that cloud machine and are not available here. Verify every claim against the code before acting on it.

Sync preview: mugurc/macos-port and upstream main into the fork

I could not write report.md: the harness refuses report files from subagents, so the full report is below. The trial merge exists only in my scratch clone. Nothing was pushed, and the clone's push URL is set to DISABLED-no-push.

Short version:

  • Upstream main (now 7a84b22) merges cleanly into the fork.
  • mugurc's macos-port (now de3ef5d, not b5b12157) conflicts in 15 files, and 6 more files auto-merge wrongly.
  • I resolved the trial merge as recommended below. It passes a Linux syntax-only check of the 20 touched files, but nothing was built or tested on macOS (no macOS SDK here).

How to read the citations:

  • A plain file:line is in the fork's main at 9d11f29 (the main-ro checkout).
  • port: means mugurc/macos-port at de3ef5d.
  • trial: means my resolved merge, commit cf9aec4d in the scratch clone.
  • "Ours" is the fork (main plus upstream). "Theirs" is the port.

Refs as fetched (2026-10-12)

Source Head Notes
fork main 9d11f29 Contains upstream 8fc53cb. The fork's macOS workflow passed on it (run 38187197369). The Build/linux job failed (job 114612023707); I did not find out why.
mugurc macos-port de3ef5d It has moved past b5b12157. New since then: 356e20f (sceKernelRaiseException on macOS), b15a79c (merges upstream up to bca7a29) and de3ef5d (macOS build fixes). b5b12157, 1f02b19 and 79850ed are its ancestors.
upstream main 7a84b22 47 commits (19 PR merges) past 8fc53cb. The port already has all but the last 2.
  • Every network fetch worked.
  • --reference /home/user/AnyPS5-macos was refused because that repository is shallow, so I cloned without it.
  • gh got HTTP 403 on mugurc's Actions, so I could not check the port's CI.

What the next scheduled sync will do

  • Upstream merges cleanly (trial commit 0230e3e7) and changes nothing under .github, so the push with the built-in token (sync-upstream.yml:84) should work.
  • macos-port then conflicts in 15 files. The same 15 conflict whether it is merged before or after upstream.
    • The workflow aborts that merge (sync-upstream.yml:76) and files the upstream-sync issue (sync-upstream.yml:117-125).
    • That issue's "Resolve locally" hint always names the upstream URL (sync-upstream.yml:119), even when the port is what conflicted.
  • Why so many conflicts: the merge has two merge bases, 8fc53cb and 21930ce (an older port merge the fork already contains).
    • The fork and the port each made the same upstream code build on macOS, independently and differently.
    • Only 5 port commits are actually new to the fork: 79850ed, 1f02b19, b5b12157, 356e20f and de3ef5d.

Conflicts and recommended resolution

  1. CMakeLists.txt (2 hunks)
    • Fork: 13e9ca7 (app packager test runs only off Windows) and f7aa9f8 (adds the unfself test).
    • Port: no change of its own; this is just the old placement of the packager test.
    • Take ours.
  2. core/libs/CMakeLists.txt (2 hunks)
    • Both sides add configure_prx_rpath(libc), at different places.
    • Keep exactly one. The trial uses the port's position.
  3. libSceAgcDriver/tests/Graphics.cpp (1 hunk)
    • Fork aae45a7: sets both the guest and the host terminate handler, and has a code comment at Graphics.cpp:2774.
    • Port b5b12157: sets only the host handler on macOS.
    • Take the port's whole descriptorPoolResetFailureTest body (port: Graphics.cpp:2474-2487). Resolving the hunk alone leaves a duplicate previous and a stray #endif.
  4. libc/include/general/AsmFunction.hpp (fork modified it, port deleted it)
    • The fork keeps a stub that includes AsmMacros.hpp; the port deleted it.
    • Delete it. After the merge every file that used it includes AsmMacros.hpp directly.
  5. AsmMacros.hpp
    • The macros are identical. The fork adds three comment lines (AsmMacros.hpp:4-6).
    • Take theirs (repository rule: no comments).
  6. AtomicSharedPtr.hpp
    • Fork 73db78e: compare-exchange checks the owner as well as the pointer, adds the weak variant, and frees the old value after unlocking.
    • Port b5b12157: compares the pointer only and frees the old value under the lock.
    • Take ours, minus the comment at lines 33-34. The only caller is GuestBufferMemory.cpp:2106.
  7. RuntimeSupport.cpp
    • The fork dropped #include <cinttypes>; the port kept it, as upstream does.
    • Take theirs. Both sides already moved strtoimax/strtoumax to Strings.cpp:184.
  8. DirectoryDescriptor.cpp
    • Same F_GETPATH call on both sides; the fork sizes the buffer with MAXPATHLEN (line 165), the port with PATH_MAX.
    • Take ours, and delete the port's duplicate include block for <climits>/<fcntl.h>, which auto-merged at the top of the file.
  9. ModuleInfo.cpp (3 hunks)
    • Fork: all three module-info calls throw "not implemented" on macOS (lines 387-401). It also has its own Mach-O based guest-segment counting (lines 211-244).
    • Port 1f02b19 and de3ef5d: macOS shares the Linux dl_iterate_phdr code and implements sceKernelGetModuleInfoFromAddr (port: lines 377-383).
    • Take theirs for all 3 hunks, then:
      • Delete the fork's Mach-O block; with the port's code it can never be compiled.
      • Add <mutex> and <unordered_map> to the macOS includes; the port only gets them through other headers.
      • Accept the port's change to GuestMemory.cpp that skips the guest-module flexible-memory check on macOS (it auto-merged).
    • Converted titles are still counted, with exactly the Linux rule (GuestImages.cpp:40-55). Only plain test libraries stop being counted.
    • Alternative: keep the fork's Mach-O counting for macOS and revert that GuestMemory.cpp skip.
  10. Udp.cpp (2 hunks) — take ours for both.
    • Hunk 1 is the same poll call; the fork adds a cast.
    • Hunk 2 is how a closed connection is detected. The fork (677b8a3, 3a1fd44) asks kqueue for end-of-file on stream sockets only (Udp.cpp:426). The port peeks with recv on any socket (port: line 424).
    • The port's check marks a zero-length UDP packet as a hang-up, and misses a peer shutdown while unread data remains. That differs from Linux (Udp.cpp:428-430).
  11. Exception.cpp (4 hunks)
    • Both sides implement sceKernelRaiseException on macOS. The fork's e949e0f (fork-only) already did: lines 313-370, 416-byte register copy, stack segment read with mov %ss (lines 336-337).
    • The port's 356e20f copies the full 512-byte FXSAVE image, checks the Darwin layout at compile time, and sets the stack segment to 0 (port: line 340) without documenting it.
    • Take ours for hunk 1 (explicit <sys/ucontext.h>) and theirs for hunks 2-4.
    • Then record the 0 stack segment in TechnicalDebt (the trial does), or keep the fork's mov %ss line.
  12. GuestKernelStackProtect.cpp
    • The fork fails the test on an unexpected error; the port treats any failure as "not mapped".
    • Take ours.
  13. GuestRaiseException.cpp (2 hunks)
    • Fork 677b8a3/d76f0d6f vs port 356e20f, which renames the signal constant to GuestSigUsr1.
    • Take theirs for both. The rest of the file already auto-merged to GuestSigUsr1.
  14. GuestUdp.cpp
    • Fork 236bfb1 uses a separate connected socket and no macOS #ifdef.
    • Port b5b12157 connects the sender and adds a second socket plus an EISCONN check on macOS.
    • Take the fork's whole file (git checkout --ours); the auto-merged lines mix both designs.
  15. TechnicalDebt.md
    • The fork's entry says module info is not implemented on macOS (line 179); the port's describes the macOS limits.
    • Take theirs. The trial also documents the 0 stack segment and that named shared memory throws on macOS.

Merged without conflict but needs a fix

  • GuestAmmPlacement.cpp now has two skips: the fork's at line 18 and the port's macOS block. Drop the port's block; it can never run.
  • GuestAmpr.cpp: the port's change (port: line 1151) disables the AMM tests on macOS. The fork's 319348d makes AMM work there without a guest arena (Apr.cpp:291, kept by the merge) and runs those tests (lines 1151-1154). Revert to the fork's version.
  • LogMacros.cpp: the port's macOS block lands inside the non-Apple branch, so it is dead code; the fork already handles macOS at line 40. Revert to the fork's version.
  • SharedMemory.cpp and GuestShmOpen.cpp: the port (de3ef5d) makes named shm_open/shm_unlink throw on macOS. Accept this.
    • The fork's macOS path builds a 52-character host name (SharedMemory.cpp:146), longer than the 31 characters macOS allows per the port's commit. So the game would silently get "name too long".
    • The fork's test never checks a successful named open outside Windows (GuestShmOpen.cpp:63).
  • docs/user/MACOS.md:95 still says sceKernelGetModuleInfoFromAddr is not implemented on macOS. The trial updates it.
  • Not new in this merge, but still against the no-comments rule: PeerShutdownMacOs.cpp:10-12 and AtomicSharedPtr.hpp:9.

Checking the trial merge

  • trial-merge.diff changes 26 files (+345/−129) against main plus upstream, with no conflict markers left.
  • g++ -fsyntax-only passed on the 20 changed translation units, using build-full's flags read from its build.ninja (nothing was built there). That only covers the non-Apple code paths.

macOS features in mugurc's branch that the fork lacks

  1. sceKernelGetModuleInfoFromAddr on macOS (1f02b19). de3ef5d adds image-load counters so upstream's unwind-table cache (28320ac) can work on macOS.
    • Matters: yes. Today the fork throws here (ModuleInfo.cpp:387-391; MACOS.md:95).
    • A title's own libc.prx calls it; TechnicalDebt.md:179 names two such titles.
    • Per the port's commit, a title's unwinder asks it for unwind data at its first C++ throw. That title died at its first exception and ran 230 s once the call worked.
    • Crash handlers and unwinders that call it hit the same throw on the fork.
    • The fork's separate macOS sceKernelGetModuleInfoForUnwind (Module.cpp:162-200) already works, so titles that only use that call are fine.
    • Still missing after the merge:
      • tls_index, init_proc_addr and fini_proc_addr read as 0.
      • A module loaded through the loader gets its own id, not its load handle.
      • sceKernelGetModuleList and sceKernelGetModuleInfo still throw on macOS.
  2. kqueue/kevent on macOS (79850ed).
    • Matters: narrowly. On the fork these are upstream's stubs, which throw (Equeue.cpp:318-326).
    • The port passes calls to the host only for file-watch events (EVFILT_VNODE). Every other filter and every socket still throws (port: Kqueue.cpp:36-45).
    • TechnicalDebt.md:59 lists three titles that import these calls; one watches its content folders.
    • It does not help networking code. Read/write filters and sockets still throw.
    • The console's own event-queue API (sceKernelCreateEqueue/sceKernelWaitEqueue) is separate and unaffected.
  3. sceKernelRaiseException on macOS (356e20f): not a gap. The fork already has it (e949e0f), though the fork's TechnicalDebt.md:437 still says "on Linux". The port's version copies the floating-point state more completely.
  4. Named shared memory throws on macOS (de3ef5d): a correctness fix that follows the "unsupported paths throw" rule, not a new capability.
  5. New tests: guest_kqueue, a relinker module-info fixture, and guest_raise_exception no longer skipped on macOS.

The recommended resolution keeps the fork-only features:

  • the multisample switches
  • the packaging tools, convert-ps5.sh and unfself
  • CI and the sync workflow
  • AMM without a guest arena
  • kqueue-based closed-connection detection
  • the stricter AtomicSharedPtr

Upstream past 8fc53cb

  • It merges cleanly into the fork.
  • The little platform-specific code in it looks portable:
    • a select change in Socket.cpp under #ifndef _WIN32
    • sysconf-based system queries in SystemConfiguration.cpp
    • reallocf in libc
  • I did not build it for macOS.
  • The local, unpushed macos-graphics branch conflicts with upstream in docs/dev/TechnicalDebt.md. Both edited the v_rcp … v_sin and v_cos entry (upstream fix(shader): take v_sin_f32 and v_cos_f32 from an exact series where the driver's result is more than 4 ulp off boykopovar/AnyPS5#3770). That will show up when the branch reaches main: take upstream's line and keep the local additions.
  • That branch read as 6a58c820 when I fetched it, after showing 7ca36a8a earlier, so it is still changing.

Could not determine

  • Whether the resolved tree builds and passes tests on macOS.
  • mugurc's CI status for de3ef5d.
  • Whether the port's ModuleInfo.cpp compiles on macOS without the explicit <mutex>/<unordered_map> includes.
  • What mov %ss returns under Rosetta 2.
  • How many titles beyond those named in the repo call these functions.
  • Why the fork's Linux build failed on 9d11f29.

All under /tmp/claude-0/-home-user-AnyPS5-macos/5fe1494a-4d35-554a-a635-e6ebd6cf2b56/scratchpad/sync-preview/:

  • clone — scratch clone; branches trial/main-up (0230e3e7, main + upstream) and trial/sync-full (cf9aec4d, + port, resolved)
  • wt — worktree for trial/sync-full
  • trial-merge.diff — the resolution against main + upstream
  • tools/resolve.py — per-hunk conflict resolver
  • tools/syncheck.py — Linux syntax checker

Generated by Claude Code

Copy link
Copy Markdown
Owner Author

Handover 5/5: flaky guest_socket_read_write on macOS (EPIPE vs ECONNRESET)

Handover note: this report was written in a cloud session, read-only, against main at 9d11f29. It was not built or run on a Mac. Paths under /tmp/claude-0/... or scratchpad/ refer to that cloud machine and are not available here. Verify every claim against the code before acting on it.

The flake is a race in the test itself, not an emulator bug, and the fix belongs in the test. The patch makes the test wait until the RST has been fully handled before the write that must fail. On every kernel, that write then returns errno 32 (EPIPE) deterministically.

I could not run macOS here, so the macOS result comes from reading the XNU source, not from a run. On Linux the new sequence passed every time: 2100 of 2100 probe runs, including 1800 under CPU load.

Files:

  • /tmp/claude-0/-home-user-AnyPS5-macos/5fe1494a-4d35-554a-a635-e6ebd6cf2b56/scratchpad/socket-flake/plan.md
  • /tmp/claude-0/-home-user-AnyPS5-macos/5fe1494a-4d35-554a-a635-e6ebd6cf2b56/scratchpad/socket-flake/fix.patch
  • Kernel sources I cited: /tmp/claude-0/-home-user-AnyPS5-macos/5fe1494a-4d35-554a-a635-e6ebd6cf2b56/scratchpad/socket-flake/src/{xnu,xnu15,fbsd11,fbsd11s,linux}
  • Linux probe: /tmp/claude-0/-home-user-AnyPS5-macos/5fe1494a-4d35-554a-a635-e6ebd6cf2b56/scratchpad/socket-flake/probe/probe.cpp

Why the errno depends on timing on macOS

  • The client closed, so the server is in CLOSE_WAIT. The first server write reaches the closed peer, which answers with a RST (XNU tcp_input.c:4755).
  • On loopback, XNU handles that RST on a separate kernel thread (if_loop.c:329, dlil.c:2275-2283).
  • When the RST arrives, XNU does three things in order:
    1. sets so_error = ECONNRESET (tcp_input.c:4539-4541);
    2. marks the connection dead (tcp_subr.c:2034, in_pcb.c:2038);
    3. only then marks the socket as unable to send, SS_CANTSENDMORE (tcp_subr.c:2040, uipc_socket2.c:281).
  • Each write checks "unable to send" first and returns EPIPE (uipc_socket.c:1904-1918), and checks so_error only after that (:1919-1923).
  • But the write then releases the socket lock while it copies the data (uipc_socket.c:2197 to 2391). If the RST lands inside that gap, the send step finds the connection dead and returns ECONNRESET (tcp_usrreq.c:1166-1185). XNU's own comment there says "we lost a race … XXX EPIPE?".
  • Alone, the gap is almost never hit, which matches 6/6 passes. Under ctest --parallel 3 (macos.yml:74), preemption makes it hit occasionally. That gives the 54.
  • The same code is in macOS 15's kernel (xnu-11215.81.4: tcp_usrreq.c:1185, uipc_socket.c:2032).

What FreeBSD 11 (the PS5 base) returns

FreeBSD 11 has the same structure and the same race:

  • It checks "unable to send" first and returns EPIPE (uipc_socket.c:1259-1263), then so_error (:1264-1269).
  • It drops the lock to copy the data (:1316, :1332), with an explicit XXX comment that the earlier check "could be out of date" (:1348-1357).
  • The send step returns ECONNRESET if the connection was dropped meanwhile (tcp_usrreq.c:874-886; stable/11 :924-934).
  • A RST in CLOSE_WAIT sets so_error = ECONNRESET, then disconnects (tcp_input.c:2176-2182, tcp_subr.c:1558-1563, uipc_socket.c:3485).
  • Loopback is also handled asynchronously (if_loop.c:358).

So FreeBSD 11 returns:

  • RST fully handled before the write: EPIPE.
  • RST lands during the copy: ECONNRESET.
  • Very narrow multi-CPU window between setting so_error and disconnecting: ECONNRESET.

A PS5 could therefore also return 54 for this exact loop. Linux always returns EPIPE here, because a RST in CLOSE_WAIT sets EPIPE (tcp_input.c:4356-4357; tcp.c:1129-1131, :1325; stream.c:188-189). That is why the old test only flaked on macOS.

Fixing the implementation instead would be less faithful

  • write, _write, sceKernelWrite and sceKernelWritev all reach send_nid_postfix (Stdio.cpp:697/704, Open.cpp:265-268, Stdio.cpp:1067-1071, Udp.cpp:975-977, 608-616).
  • That function passes the host errno through GuestErrorFromHost: EPIPE becomes 32 and ECONNRESET becomes 54 (SocketError.hpp:60, :83).
  • Rewriting ECONNRESET to EPIPE would hide a value FreeBSD 11 itself returns in the same race. It would also change genuine ECONNRESET results.
  • The test cannot read SO_ERROR, because the guest getsockopt doesn't support it and returns error 42 (Udp.cpp:126-134, :493-494).

The test change

  1. Write once after the peer closes and require success. No RST can exist before this data reaches the peer.
  2. Poll with POLLOUT (0x4) every 1 ms, for up to 2 s, until POLLHUP (0x10) is set.
  3. Require the next write to return -1 with errno 32.

Why POLLHUP on a POLLOUT poll is the right signal:

  • XNU: it appears only once "unable to send" is set (uipc_socket.c:6743-6748; sys_generic.c:1762-1766, 1861-1862, 1881-1884). The next write then returns EPIPE (:1904-1918). Polling for POLLIN would not work: XNU already reports POLLHUP for it in CLOSE_WAIT (uipc_socket.c:6586-6591), which is why test line 148 accepts In | Hup.
  • FreeBSD 11: it appears only when both "can't receive" and "can't send" are set (uipc_socket.c:3040-3045). The next write then returns EPIPE (:1259-1262).
  • Linux: it appears at TCP_CLOSE (tcp.c:546-547), and the pending error is EPIPE.

The patch adds no comments and needs no TechnicalDebt.md entry. The helper and its includes sit inside #ifndef _WIN32, like the block they serve.

Checks:

  • git apply --check against main-ro succeeds, and main-ro is still clean.
  • g++ -std=c++20 -fsyntax-only -Wall -Wextra -I…/core/libs on the patched file reports nothing.
  • The Linux probe uses the same syscall sequence on raw sockets. It never saw POLLHUP before the first write.

What I could not determine

  • PS5 kernel: Sony's FreeBSD-11-based source isn't available. I used FreeBSD releng/11.0 and stable/11 and assumed Sony left these paths unchanged.
  • CI runner: its macOS version is unknown. I checked the code in xnu-12377.121.6 and xnu-11215.81.4.
  • CI log: I didn't have the failing log. I assumed the failure was line 153 with errno 54, as the task says. I did not measure how often the race hits.
  • macOS loopback path: I did not trace XNU's loopback input hop by hop.

Other things I noticed (not in the patch)

  • Linux hosts diverge from FreeBSD for a RST on an open connection: a write there returns ECONNRESET on Linux (tcp_input.c:4361-4362) but EPIPE on FreeBSD once the RST is handled. This test doesn't cover that case.
  • SIGPIPE: guest sends don't pass MSG_NOSIGNAL (Udp.cpp:53, :614), so the host raises SIGPIPE and the test ignores it on the host. FreeBSD would signal the guest unless SO_NOSIGPIPE is set (sys_socket.c:147-149). I didn't determine what the PS5 actually delivers.
  • Comments that break the no-comment rule: Udp.cpp:455, Udp.cpp:679, PeerShutdownMacOs.cpp:10-12.

fix.patch

--- a/core/libs/tests/GuestSocketReadWrite.cpp
+++ b/core/libs/tests/GuestSocketReadWrite.cpp
@@ -6,7 +6,9 @@
 #include <cstdlib>
 #include <cstring>
 #ifndef _WIN32
+#include <chrono>
 #include <csignal>
+#include <thread>
 #endif
 
 struct PollDescriptor {
@@ -58,6 +60,7 @@
 #define Require(value) Check((value), __LINE__)
 
 constexpr short In = 0x1;
+constexpr short Out = 0x4;
 constexpr short Hup = 0x10;
 constexpr int KernelAgain = static_cast<int>(0x80020023u);
 constexpr int KernelBadDescriptor = static_cast<int>(0x80020009u);
@@ -68,6 +71,19 @@
     return poll_nid_postfix(&waited, 1, 2000) == 1 && (waited.revents & accepted) != 0;
 }
 
+#ifndef _WIN32
+static bool SendSideClosed(int descriptor) {
+    const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(2);
+    for (;;) {
+        PollDescriptor waited{descriptor, Out, 0};
+        if (poll_nid_postfix(&waited, 1, 0) < 0) return false;
+        if ((waited.revents & Hup) != 0) return true;
+        if (std::chrono::steady_clock::now() >= deadline) return false;
+        std::this_thread::sleep_for(std::chrono::milliseconds(1));
+    }
+}
+#endif
+
 int main() {
 #ifndef _WIN32
     std::signal(SIGPIPE, SIG_IGN);
@@ -148,9 +164,10 @@
     Require(Readable(server, In | Hup) && read_nid_postfix(server, received, sizeof(received)) == 0);
     Require(sceKernelRead(server, received, sizeof(received)) == 0);
 #ifndef _WIN32
-    std::int64_t written = 0;
-    for (int i = 0; i < 100 && written >= 0; ++i) written = write_nid_postfix(server, request, sizeof(request));
-    Require(written == -1 && *__error_nid_postfix() == 32);
+    Require(write_nid_postfix(server, request, sizeof(request)) == sizeof(request));
+    Require(SendSideClosed(server));
+    *__error_nid_postfix() = 0;
+    Require(write_nid_postfix(server, request, sizeof(request)) == -1 && *__error_nid_postfix() == 32);
 #endif
     Require(close_nid_postfix(server) == 0);
     *__error_nid_postfix() = 0;

Generated by Claude Code

Copy link
Copy Markdown
Owner Author

Handover 1/5: subgroup operations in vertex shaders on MoltenVK (blocks PvZ and Hades II)

Handover note: this design was written in a cloud session, read-only, against main at 9d11f29. Nothing in it was built or run on a Mac. Paths under /tmp/claude-0/... or scratchpad/ refer to that cloud machine and are not available here; MVK/, SC/ and MSL/ are local clones of MoltenVK, SPIRV-Cross and the Metal Shading Language specification there. Verify every claim against the code before acting on it.

Design: subgroup operations in vertex shaders on MoltenVK

Source: main-ro at 9d11f29. I read every line cited here myself unless it is marked (report, not re-read).

Path prefixes:

  • R/ = core/shader/recompiler/
  • D/ = core/libs/prx/libSceAgcDriver/
  • MVK/ = scratchpad/bary-moltenvk/moltenvk/MoltenVK/MoltenVK/
  • SC/ = scratchpad/bary-moltenvk/spirv-cross/
  • MSL/ = scratchpad/mslspec/

0. Summary

Cause. MoltenVK never lists VERTEX or TESSELLATION_EVALUATION in subgroupSupportedStages (MVK/GPUObjects/MVKDevice.mm:1484-1489). Nothing configures this, and it cannot be fixed on the host side:

  • MSL allows SIMD-group functions only in kernel and fragment functions (MSL/msl.txt:10140-10143).
  • SPIRV-Cross throws on SubgroupLocalInvocationId in an ordinary vertex function (SC/spirv_msl.cpp:18762-18779).

The recompiler does not know which stages support subgroups: SpirvTarget has no stage field (R/Recompiler.hpp:214-232). It emits the module anyway, and the AGC validator rejects it after compilation (D/Graphics/src/ShaderValidation.cpp:199). That error does not give the program address or say which construct is responsible.

Ranked plan.

  1. Diagnostics and plumbing, shipped in the same build.

    • The device's subgroup stage mask goes into SpirvTarget and from there into every cache key and the .req format.
    • The recompiler itself rejects a stage that has no subgroup support. Its message names each construct that is still left, its guest address, and how to opt in. Because it is thrown inside PrepareShader, the error carries a replayable request.
  2. Exact lane-local lowering, on by default. It applies to Vertex, Local and TessellationEvaluation programs when the target lacks subgroups in that stage. It rewrites:

    • the own-lane bit of a lane mask;
    • lane-index tests whose result is the same for every lane;
    • v_readfirstlane/v_readlane of wave-uniform values;
    • wave-mask branches whose condition is constant, or whose region is proven to be EXEC-guarded.

    It is exact with respect to the existing vertex wave model (docs/dev/TechnicalDebt.md:157), so it adds no technical debt.

  3. Opt-in APS5_ONE_LANE_WAVES=all|<hex addresses>. Each invocation runs as a guest wave of one lane: s3 = 0x101, lane 0. This needs a TechnicalDebt entry. Reading a lane that was never launched still throws.

  4. Not now: running the vertex stage as a compute pre-pass. It would be exact but take weeks.

    Rejected:

    • making MoltenVK claim VERTEX support;
    • routing these draws through tessellation kernels;
    • SPIRV-Cross emulate_subgroups.

Tests. They run on Linux with lavapipe and simulate MoltenVK in two ways:

  • recompiler unit tests set request.target.subgroupStages;
  • execution tests run under the new driver knob APS5_SUBGROUP_STAGES=0x32.

Sample locations. VK_EXT_sample_locations on MoltenVK has the same precision as the AMD registers: a 16×16 grid over [0, 15/16]. The plan is in §10. Its error-message part goes into the same build.

What to ask the user. §9: one run of the new build with APS5_DUMP_SHADERS=1. Send the error text with its RecompileRequest: block, the shader_*.req files, and the Selected GPU line.

1. Facts the plan depends on (verified)

# Fact Where
F1 The validator throws for any subgroup capability in a stage missing from supportedStages, then for missing operations. Capabilities are checked before built-ins. D/Graphics/src/ShaderValidation.cpp:186-200 (throw at 199, operations at 200). Built-in check :95-98, reached from :467/:473. Instruction loop ends at :381.
F2 Capability 61 is declared first whenever laneCount==2 or any requirement is set. Arithmetic (63) is declared only by the half-wave reduction. R/SpirvBackend/src/SpirvMemory/SpirvModuleSetup.cpp:126-134. R/SpirvBackend/src/SpirvAlu/SpirvAluEmitterMath.cpp:554.
F3 What sets the requirements: append/consume, Ballot, ReadFirstLane, ReadLane, DPP, WriteLane, permlane, swizzle/permute/bpermute, LaneId. Every wave-mask terminator sets ballot, even with a constant condition. R/SpirvBackend/src/SpirvAnalysis.cpp:367-409 (ops), :431-435 (wave-mask terminators), :452-454 (IsWaveMaskBranch).
F4 A wave-mask branch always emits a ballot-based any. The plain per-lane path exists. R/SpirvBackend/src/SpirvFlowEmitter.cpp:133-155, :157-164.
F5 EXEC and VCC are a per-lane bool plus ballot words. threadBit needs LaneId. Saveexec writes words and then threadBit. Wave32 VCC writes go through a word. R/Translation/src/TranslationContext/ExecMask.cpp:8-33, :44-56, :81-123. R/Translation/src/ControlFlowInstructions.cpp:28-71. R/Translation/src/TranslationContext/OperandAccess.cpp:548-555.
F6 Vertex entry: EXEC = true and ExecLo = Ballot(true). s3 = lanes | lanes<<8, where lanes is 32 for wave64 on a 32-lane target and the wave size otherwise. R/Translation/src/InstructionTranslator.cpp:184-204, :366-370.
F7 A lane-bit rewrite exists only for Local, TCS and TES; Lower returns early for Vertex. A Ballot left in a TCS throws. R/Optimization/src/TessellationLowering.cpp:64-95, :354-358, :371, :615-619.
F8 Reusable pieces: a threadBit pattern matcher, and an implication engine with phi coinduction and assumption rollback. R/Optimization/src/MaskedSelectEliminator.cpp:248-265, :358-470.
F9 A wave-uniformity analysis (UniformSource, LaneSource, WaveUniformValues) exists but is used only when laneCount==2. R/SpirvBackend/src/SpirvAnalysis.cpp:12-61, :456-486. R/SpirvBackend/src/SpirvEmitter.cpp:248-249.
F10 The target carries only the subgroup size. The device queries the full properties, and the validator gets them through Context. R/Recompiler.hpp:214-232. D/Execution/src/VulkanDevice.cpp:1017-1029, :2911-2930, :2985. D/Graphics/src/Draw.cpp:755.
F11 Keys: the whole target is appended to the in-memory source and prepared keys and to the disk key. Every "APS5_*" literal in recompiler sources enters the disk switch key. Recompiler source hashes version the disk cache. R/CacheKey.hpp:85-93, :226-243. R/Recompiler.cpp:327-329, :1102-1103, :1117-1121. R/ShaderDiskCache.cpp:680-706, :899-917, :958. R/ShaderCacheVersion.cmake.
F12 Pipeline keys use variant ids. D/Graphics/src/Pipeline.cpp:642-656
F13 Request serialization is at version 16, and the target is only partly serialized. R/ControlFlow/src/RequestSerializer.cpp:592-641, :733-756, :761-786
F14 An error thrown in PrepareShader gets RecompileRequest:\n<base64> appended, and APS5_DUMP_SHADERS writes shader_<addr>.req. A validator error gets neither. R/Recompiler.cpp:1030-1036, :1097-1109. D/Execution/src/Driver/Shaders/ShaderRegistry.cpp:31-39, :467-487. D/Execution/src/Driver/Shaders/ShaderDiagnostics.cpp:52-64.
F15 Emission failures are memoised per (address, layout). R/Recompiler.cpp:804-806, :823-828
F16 The guard of a side effect: the last argument for shared and buffer accesses, the EXEC argument for exports, and (value, old, exec) for DPP updates. R/Optimization/src/TessellationLowering.cpp:399. R/Translation/src/AttributeInstructions.cpp:148. R/Translation/src/TranslationContext/OperandAccess.cpp:537.
F17 In the Vertex stage, s_barrier is a no-op or throws, and Sendmsg and Waitcnt emit nothing. R/SpirvBackend/src/SpirvFlowEmitter.cpp:841-850, :859-885
F18 Block PCs are byte offsets. The IR dump prints them but not terminators. R/RdnaDecoder/src/RdnaInstructionDecoder.cpp:54. R/Translation/src/InstructionTranslator.cpp:460-469. R/IntermediateRepresentation/src/IrProgram.cpp:315-344.
F19 Non-passthrough PRIMGEN vertex programs with DS instructions or s_barrier take the mesh path, which MoltenVK does not have. D/Execution/src/Driver/Shaders/ShaderRegistry.cpp:140-170. D/Graphics/src/State.cpp:563-567.
F20 MoltenVK reports stages FRAGMENT|COMPUTE (plus TESSELLATION_CONTROL), with all operation bits on Apple GPUs. It enables subgroup emulation only without simdPermute. MVK/GPUObjects/MVKDevice.mm:1484-1509. MVK/GPUObjects/MVKPipeline.mm:2118-2123.
F21 SIMD-group functions are not allowed in vertex functions. SPIRV-Cross throws for subgroup built-ins in a plain vertex function; tessellation vertex kernels are the exception. MSL/msl.txt:10140-10143. SC/spirv_msl.cpp:18762-18779. MVK/GPUObjects/MVKPipeline.mm:1514-1515.
F22 The narrow-host code throws for a v_readlane outside the host subgroup unless it proves the value is 0. This corrects Report A's "returns 0". R/SpirvBackend/src/SpirvAlu/SpirvAluEmitterMath.cpp:199-202, :963-976
F23 Tests that pin today's behaviour. D/tests/Graphics.cpp:4499-4528 (substring match, :89-98). D/tests/execution/ExecHostLanes.cpp:166-176. D/tests/execution/NggVertexWaveReduction.cpp:128-138. D/tests/ShaderMemory.cpp:1365-1458.

Further notes on the reports:

  • Dispatch.cpp:279 cuts compute errors at the first newline. I did not verify whether the draw path's final log line keeps the appended RecompileRequest: block. §9 therefore also asks for the .req files.
  • The replay tool prints only the first line of an error (D/tools/ShaderReplay.cpp:150-152). Every new message is therefore a single line.

2. Model and what "exact" means

The existing vertex model (docs/dev/TechnicalDebt.md:157, R/Translation/src/InstructionTranslator.cpp:184-204 and :366-370):

  • A guest wave holds lanes lanes, and a lane index lies in [0, lanes).
  • EXEC is all ones at entry.
  • The host decides which vertices share a wave.

Exact means: for every host invocation, the lowered program produces the same outputs and memory effects as the guest program produces for that lane, in every wave the model admits.

The host-subgroup mapping used today is one such admitted wave. So an exact lowering cannot change results on a device that does have vertex subgroups. The lavapipe tests check exactly this property.

Scope. The new pass runs only when two conditions hold:

  • target.subgroupStages lacks the program's stage bit;
  • the stage is Vertex, Local or TessellationEvaluation, whose invocations are independent vertices or domain points.

Other stages keep today's behaviour: the validator throws, now with the better message.

3. Ranked plan

Rank 1: diagnostics and plumbing (first PR, same build as the fix)

1a. Stage mask in the target.

  • R/Recompiler.hpp:214-232, SpirvTarget:
    • Add std::uint32_t subgroupStages = 0xffffffffu;. It holds VkShaderStageFlagBits values. The default keeps every existing test, every aggregate initialiser (D/Execution/src/VulkanDevice.cpp:2913) and every old .req at today's behaviour.
    • Add constexpr std::uint32_t SubgroupStageBit(ShaderStage), with the same mapping as VulkanStage (D/Graphics/include/Shaders.hpp:42-50): Vertex and Local → 0x1, TCS → 0x2, TES → 0x4, Geometry → 0x8, Fragment → 0x10, Compute → 0x20, Mesh → 0x80.
    • Add bool StageHasSubgroups(const SpirvTarget&, ShaderStage).
  • D/Execution/src/VulkanDevice.cpp:2911-2930 buildTarget: set target.subgroupStages = state->subgroup.supportedStages;. ComputeTarget (:2888-2892) copies it, and so does ShaderDeviceProfile (D/Execution/src/ShaderDeviceProfile.cpp:21, :73).
  • Keys:
    • R/CacheKey.hpp:226-243: add append(key, value.subgroupStages). This reaches the source and prepared keys (R/Recompiler.cpp:327-329, :1117-1121) and the disk key (R/ShaderDiskCache.cpp:899-917).
    • ContextHash (R/CacheKey.hpp:39-60) leaves the target out by design ("the device itself"), so no change there.
    • Pipeline keys need nothing (F12).
    • Old disk entries die anyway, because SourceVersion changes (R/ShaderDiskCache.cpp:958).
  • R/ControlFlow/src/RequestSerializer.cpp:
    • Write version 17 (:737) and accept versions up to 17 (:765).
    • Write request.target.subgroupStages after float64DenormPreserve (:755), and read it when the version is at least 17 (after :785).
  • D/tools/ShaderReplay.cpp: add --subgroup-stages=<hex> to override the target, next to --maintenance8 (:117, :172-175). A request dumped anywhere can then be replayed as MoltenVK.
  • R/SpirvBackend/include/SpirvBackend/SpirvEmitter.hpp:14-24: add bool stageSubgroups = true;, set in compileVariant (R/Recompiler.cpp:403-412).

1b. Test knob and log line (driver).

  • D/Execution/src/VulkanDevice.cpp, right after vkGetPhysicalDeviceProperties2 (:1017-1019): APS5_SUBGROUP_STAGES=<hex> does supportedStages &= mask.
    • It can only remove stages. A value that is not hex throws.
    • It edits state->subgroup, so the recompiler target (:2913) and the validator (:2985 → D/Graphics/src/Draw.cpp:755) see the same mask.
    • It lives outside recompiler sources, so it is not in the switch key. It acts through subgroupStages, which is keyed.
    • MoltenVK's mask is FRAGMENT|COMPUTE|TESSELLATION_CONTROL = 0x32.
  • Log line at :1029: Selected GPU name=… subgroup=%u stages=0x%x operations=0x%x, plus (APS5_SUBGROUP_STAGES) when the mask was applied.

1c. The recompiler rejects with a list of constructs.

  • Add std::vector<SubgroupUse> DescribeSubgroupUses(const IrProgram&) to R/SpirvBackend/src/SpirvAnalysis.cpp.
    • It uses the same opcode switch and terminator loop as AnalyzeProgramRequirements (:367-435).
    • It records, per use: opcode, block, startPc and endPc (byte offsets, F18).
  • In compileVariant (R/Recompiler.cpp:387-), after Rank 2's pass (or immediately, if Rank 2 has not landed yet): if !StageHasSubgroups(target, stage) and uses remain, throw message M1 (§5).
    • The throw happens inside PrepareShader, so the request is appended (F14), APS5_DUMP_SHADERS dumps the .req, and the failure is memoised (F15).
  • Backstops:
    • In SpirvEmitter::Emit (R/SpirvBackend/src/SpirvEmitter.cpp:236-249): FailProgram if !target.stageSubgroups and a subgroup requirement is set or laneCount==2.
    • In EmitHalfWaveReduction (R/SpirvBackend/src/SpirvAlu/SpirvAluEmitterMath.cpp:528-557): fail before EmitCapability(Arithmetic) at :554 in the same case.

1d. Validator backstop message. This is Report C's C1; I checked the code it relies on.

  • CompiledShader gains std::uint64_t guestAddress = 0; (D/Graphics/include/Shaders.hpp:36-40).
    • It is set at D/Execution/src/Driver/Draw/Draw.cpp:226 from program.binary.codeAddress.
    • Three-field initialisers still compile (ShaderValidation.cpp:605-610).
  • Inspect (ShaderValidation.cpp:186-200) records the subgroup capabilities, counts OpGroupNonUniform* (opcodes 333-366), and throws M3 (§5) after the loop (after :381).
  • The operations check stays where it is when the stage is supported.
  • The message keeps the substrings is unsupported for shader stage and device lacks operations.
  • For recompiled shaders, M1 should make this message unreachable.

1e. IR dump.

  • ProgramToString (R/IntermediateRepresentation/src/IrProgram.cpp:326-344) also prints each block's terminator: kind, condition kind, true/false/merge blocks, and whether the branch is wave-mask or lane-local.
  • compileVariant gets a dump point lanes after the new pass, behind the same APS5_DUMP_IR switch. That switch is neutral for cache keys (R/ShaderDiskCache.cpp:680-689).

Rank 2: exact lane-local lowering (second PR, on by default)

New pass. LaneLocalLowering lives in R/Optimization/include/Optimization/LaneLocalLowering.hpp and R/Optimization/src/LaneLocalLowering.cpp. The source must be added to the explicit list in R/CMakeLists.txt (around :101). The cache-version glob picks it up on its own.

Helpers moved, not copied:

  • The threadBit matcher (MaskedSelectEliminator.cpp:248-265) and BallotSource/HostLaneWord/SavedLaneBit (TessellationLowering.cpp:64-95) move to Optimization/LaneMask.hpp.
  • UniformSource/LaneSource/WaveUniformValues/IsWaveMaskBranch (SpirvAnalysis.cpp:12-61, :452-486) move to Optimization/WaveUniformity.hpp.

Call site. compileVariant (R/Recompiler.cpp), after ApplyStaticInterface and DCE (:392-395) and before ShaderInfoCollector (:397-398).

  • It must run after ApplyStaticInterface because E3 removes ReadFirstLane, which resource tracking matches when it selects descriptors (R/Optimization/src/ResourceTracker.cpp:350, :522-524, :813, :905).
  • Inputs: the wave size, lanes (the formula at InstructionTranslator.cpp:368), and the stage.

The rules run in this order, with constant folding and DCE after each.

E1. Own-lane bit of a mask. Every threadBit shape is replaced by LaneBit(word). The shape is INotEqual(And(Shr(word, And(LaneId,31)),1),0), where word is either W or Select(ULessThan(LaneId,32), lo, hi). LaneBit is defined case by case:

Input Result
CompositeExtract(Ballot(p), h), where h is the half that holds the lane p. With lanes ≤ 32 only h = 0 occurs. With 64 lanes, lo and hi must come from the same Ballot.
A constant A constant bool, if bits [0, min(lanes,32)) of the relevant half are all equal. Otherwise the word is not lane-local.
BitwiseAnd, Or, Xor, Not The matching logical op on the LaneBits
Phi A new bool phi, created with program.CreateValue(IrOpcode::Phi, …) + AddPhiOperand as R/Optimization/src/SsaBuilder/SsaPass.cpp:50-59 does. Memoised; cycles allowed.
Select(u, a, b), with u wave-uniform Select(u, LaneBit a, LaneBit b)
Anything else Left alone

Why it is exact: bit L of a bitwise combination of words is the same combination of their bit L, and bit L of Ballot(p) is p_L.

It generalises SavedLaneBit and covers:

  • a VOPC compare into VCC followed by v_cndmask;
  • carry and borrow chains;
  • s_*_saveexec and the s_or/s_andn2 EXEC restore;
  • s_mov exec with -1 or 0;
  • hostExecWord;
  • the entry ExecLo.

E2. Lane-index folding. Some values have only LaneId and immediates as leaves, built with And, Or, Xor, Not, Shl, Shr, Add, Sub, BitCount, Select, compares and logical ops, at a bounded depth. Such a value is evaluated for every L in [0, lanes). If every result is the same, the value is replaced by that constant. This is exact by construction.

It covers:

  • v_mbcnt(-1) < count with the count taken from s3 (the NGG passthrough prologue);
  • LaneId < 32 for wave64 on a 32-lane target.

E3. Uniform lane reads. ReadFirstLane(v, active) and ReadLane(v, n) become v when v is in WaveUniformValues.

Why it is exact:

  • A value that is uniform under this analysis is equal in every lane, inactive lanes included. Select under a lane-varying EXEC counts as varying (SpirvAnalysis.cpp:456-486).
  • Before E4 changes anything, every IR branch is wave-uniform: scalar, goto, or a wave-any.

E3b is a candidate, to add only if a dump shows it is needed. It would treat a vector load as uniform when its address and resource are uniform and the program writes no memory.

E4. Wave-mask branches (the terminators of F3):

  • (i) If the condition is constant after E1 and E2, mark the branch lane-local. When at least the current lane runs, any(c) = c.

  • (ii) Otherwise, for a selection construct only: it has a valid mergeBlock, is not a loopHeader, and is not a loop's back edge or exit. Let e be the per-lane predicate for entering the arm that holds code. Pick G:

    • Route A: G = e.
    • Route B, a uniform vote such as v_cmp of uniform operands followed by s_cbranch_vccz: c = LogicalAnd(U, G), with U wave-uniform.

    Each arm R (from the arm entry up to the merge block) must satisfy:

    • Guarded side effects. Every side-effecting instruction has a guard g with Implies(g, G).
      • Memory writes and atomics use their last argument as the guard (F16), and exports use their EXEC argument.
      • Barrier, Sendmsg, Waitcnt, TtraceData, InstPrefetch and Reference* have no effect in Vertex (F17). They need re-checking for Local and TES.
      • Any other side effect fails the check.
    • Merge phis. For every phi at the merge, the value coming from R must satisfy GuardedIdentity(v, base, G). base is the bypass value, or for two arms a common base that dominates the branch. GuardedIdentity holds when one of these is true:
      • v == base;
      • v = Select(g, x, y) with Implies(g, G) and GuardedIdentity(y);
      • v = DppUpdateU32(new, old, exec) with Implies(exec, G) and GuardedIdentity(old);
      • v is a phi inside R and all its inputs hold (coinductively);
      • v and base are both bools, and both imply G;
      • v = LogicalOr(base, x) with Implies(x, G);
      • v = LogicalAnd(base, LogicalNot(x)) with Implies(x, G).
    • Implies. It uses the engine of F8, extended with Select (both arms imply) and constant false.

    Why it is exact:

    • Lanes with e = 1 take the same path as in the guest.
    • Lanes with e = 0 skip R. In the guest they would have run R with every effect masked off. The two checks above prove that R then leaves every merged value unchanged.
    • Inner branches are processed first (post-order), so an inner branch that was already converted is just more guarded code.

How it is represented.

  • BlockInfo gains bool laneLocalBranch = false; (R/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/ControlFlowInfo.hpp:13-20).
  • IsWaveMaskBranch takes the BlockInfo and returns false when the flag is set. Its two callers are SpirvAnalysis.cpp:432 and SpirvFlowEmitter.cpp:159.
  • EmitBranchCondition then uses ctx.Def(info.condition) (SpirvFlowEmitter.cpp:162-164).
  • The CFG does not change, so the SPIR-V structure stays valid.

Not exact in v1 (these are reported):

  • wave-mask branches that control a loop, such as a waterfall loop;
  • two-armed branches without a common base;
  • any branch that fails one of the checks.

After E1–E4 and DCE, call DescribeSubgroupUses. If anything remains, either throw M1 (the default) or apply Rank 3 (opt-in).

Rank 3: opt-in APS5_ONE_LANE_WAVES (third PR)

The variable.

  • It is read next to APS5_SINGLE_LANE (R/Recompiler.cpp:83-94) and parsed the same way: all, or comma-separated hex code addresses. Any other value throws.
  • It applies only to in-scope stages that lack subgroup support.
  • It is an "APS5_*" literal in recompiler sources, so it enters the disk switch key automatically (R/ShaderDiskCache.cpp:691-706).

Changes.

  • HostSubgroupSize (R/Recompiler.cpp:85-94) returns 1 for the selected programs. That value flows into:
    • the source and prepared keys (:329, :1120);
    • the disk key (R/ShaderDiskCache.cpp:910);
    • RecompileResult::hostSubgroupSize (:427);
    • the input info (R/Translation/src/ShaderInputInfoBuilder.cpp:163).
  • R/Translation/src/InstructionTranslator.cpp:368: lanes = hostSubgroupSize == 1 ? 1 : <current formula>, which makes s3 = 0x101.
  • LaneLocalLowering runs a one-lane mode after E1–E4:
IR op One-lane value
LaneId 0
Ballot(p) (p?1:0, 0, 0, 0)
ReadFirstLane(v, a) v: lane 0 is the first active lane, or lane 0 when none is active
ReadLane(v, n) v if n folds to 0; otherwise throw (that lane was never launched)
WriteLane(v, n, old) n==0 ? v : old
DppMoveU32 / DppUpdateU32 The source lane t = f(ctrl, 0) is known at compile time. If t == 0 and valid, the lane's own value. If t is invalid, or inactive without fetch-inactive, the rules of SpirvAluEmitterMath.cpp:141-182 and :901-919 apply (0, or no write). Fetch-inactive from t ≠ 0 throws.
Permlane16U32 Same rules, with the lane-0 select nibble (:986-1023)
SwizzleU32, PermuteU32, BpermuteU32 Own value if the source lane folds to 0; otherwise throw
DataAppend / DataConsume One atomic per invocation
Remaining wave-mask branch Per-lane (any over one lane = c)
  • R/Optimization/src/ConstantFolder.cpp: fold FindILsb32 and FindUMsb32 of constants (neither is in the case list), so s_ff1 of a one-lane ballot folds to 0.
  • Once per program, print to stderr: [recompile] <stage> program 0x… runs as one-lane waves (APS5_ONE_LANE_WAVES): <constructs>.

Rank 4 and rejected alternatives

  • Vertex stage as a compute pre-pass. Dispatch over the draw's vertices, write the outputs to a buffer, then draw with a pass-through vertex shader. Compute has subgroups. It would be exact with respect to the model and would cover reductions too, but it is weeks of work: indices, instancing, restart, rect lists, tessellation and libraries. Keep it in reserve for the case where Ranks 2 and 3 leave important programs unsupported.
  • Rejected: MoltenVK reporting VERTEX. That is invalid usage, and plain vertex functions would still fail in SPIRV-Cross and MSL (F21).
  • Rejected: running the draw as a tessellation pipeline so that SPIRV-Cross's vertex_for_tessellation kernels may use SIMD functions (F21). The Vulkan stage mask still forbids it, it costs a tessellation pass, and only list topologies would map.
  • Rejected: emulate_subgroups. It supports Elect only, MoltenVK leaves it off on M-series GPUs (F20), and the AGC validator would reject the module first.

4. Construct classification (stages without subgroup support)

Construct (guest → IR) Default APS5_ONE_LANE_WAVES
VOPC → VCC/SGPR → v_cndmask/v_addc (Ballot + threadBit) exact (E1) exact (E1)
s_*_saveexec, EXEC restore, s_mov exec, -1/0, entry EXEC exact (E1) exact (E1)
v_mbcnt(-1) compared with the s3 counts, LaneId < 32 exact (E2) in model
Other uses of LaneId (v_mbcnt(exec), *_addtid, image_sample_cd permute index) throw in model (0)
v_readfirstlane/v_readlane of a uniform value exact (E3) exact
v_readfirstlane of a varying value (waterfall loop) throw in model
v_readlane of a varying value from a lane ≠ 0 throw throw
v_writelane (not removed by ReadLaneEliminator) throw in model
Ballot used as a value (s_bcnt1, s_ff1, SCC of a mask, mask stored or moved to a VGPR) throw in model (0 or 1)
s_cbranch_exec*/vcc* with a constant condition exact (E4 i) exact
Same, selection region proven EXEC-guarded exact (E4 ii) in model
Same, loops or unproven regions throw in model (per lane)
DPP/permlane from own lane or an invalid lane throw in model
DPP/permlane fetch-inactive from lane ≠ 0; swizzle/permute/bpermute from lane ≠ 0 throw throw
Half-wave reductions and prefix scans throw in model if the scan folds to lane 0; otherwise throw
ds_append/ds_consume throw in model

"In model" means exact for a one-vertex wave, under the assumption written in §7.

5. Messages (single line each)

M1: recompiler, default mode (R/Recompiler.cpp compileVariant). recompileReporting adds the ShaderRecompiler::Recompile: prefix and the request block.

vertex program 0x<code> (wave64, s3 counts 32) needs subgroup operations, which the device does not support in vertex shaders (subgroup stages 0x32); exact lowering left: a ballot read as a value at 0x<code+startPc>-0x<code+endPc>; the lane index at 0x…-0x…; a wave-mask branch at 0x<code+endPc> whose region leaves a scalar value that the skipped path does not have; APS5_ONE_LANE_WAVES=0x<code> runs this program as one-lane waves (TechnicalDebt: one-lane waves)
  • The stage word is vertex, local (tessellation LS) or tessellation evaluation.
  • Item texts, one per kind:
    • a ballot read as a value
    • the lane index
    • v_readfirstlane/v_readlane of a lane-varying value
    • v_writelane
    • DPP (ctrl 0x…)
    • v_permlane16/x16
    • ds_swizzle/ds_permute/ds_bpermute
    • ds_append/ds_consume
    • a wave-mask branch at … that controls a loop | whose region has an effect not masked by EXEC (<opcode>) | whose region leaves a scalar value that the skipped path does not have | whose condition differs between active lanes

M2: recompiler, opt-in mode.

vertex program 0x<code> runs as one-lane waves (APS5_ONE_LANE_WAVES), but <construct> at 0x…-0x… reads lane <n>, which a one-lane wave does not launch

M3: validator backstop (ShaderValidation.cpp).

AGC graphics: subgroup capability 61 (GroupNonUniform) is unsupported for shader stage 1 (vertex) of program 0x<addr|generated> (path vertex, VGT_SHADER_STAGES_EN=0x<v>, wave64, host subgroup 32): the module needs ballot, shuffle, subgroup local invocation ID (capabilities 61 64 65; <n> OpGroupNonUniform* instructions[, declared but unused]); device subgroup stages 0x32, operations 0x<ops>

M4: device log (VulkanDevice.cpp:1029).

Selected GPU name=… vendor=… device=… subgroup=32 stages=0x32 operations=0x<ops>[ (APS5_SUBGROUP_STAGES)]

6. Tests (Linux, lavapipe; each under 30 s)

T1. D/tests/ShaderMemory.cpp: new verifyStagesWithoutSubgroups(). No GPU is needed; call it from main (:3089-3140).

  • The requests copy verifyNarrowVertexWave (:1365-1388) and add request.target.subgroupStages = 0x32.
  • Programs come as raw words, as in that test.
  • Cases:
    1. Wave32: v_cmp→VCC→v_cndmask, a v_add_co/v_add_co_ci chain, s_and_saveexec + s_cbranch_execz over masked VGPR writes and an export, s_or exec. Expect: no OpCapability 61/63/64/65, no OpGroupNonUniform*, no BuiltIn SubgroupLocalInvocationId.
    2. Case 1 again without the mask: the module still contains subgroup ops. This pins that nothing changes on capable devices.
    3. Wave64 on subgroupSize = 32 with an NGG prologue (s_bfe s3, v_mbcnt, compare against the count, exp prim): exact.
    4. A uniform v_readfirstlane of v_mov v0, s[user]: exact.
    5. Must throw M1 with the right item:
      • s_bcnt1_i32_b32 s0, exec_lo fed into an export → a ballot read as a value;
      • an execz region that sets s5, with s5 read after the join → leaves a scalar value;
      • a waterfall loop → controls a loop;
      • DPP row_shr:1 → DPP.
    6. A request round-trip through RequestSerializer keeps subgroupStages.
    7. Two PrepareShader calls with masks 0x32 and ~0 do not share a source. The pattern is the same as :1430-1450.
  • Add an opt-in mode, agc_shader_memory_tests --one-lane-waves, registered next to D/CMakeLists.txt:1029-1040 with ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_ONE_LANE_WAVES=all". It checks:
    • case 5's ballot, waterfall and DPP-invalid-lane programs compile without subgroup ops;
    • hostSubgroupSize == 1;
    • s3 folds to 0x101;
    • fetch-inactive DPP from lane 1 throws M2.

T2. D/tests/Graphics.cpp.

  • :4499-4528: add guestAddress and a Local-stage case. Assert the new M3 parts (of program 0x, needs ballot).
  • :1758-1769: the sample-location message is compared by equality (:1769), so update it for S0.

T3. New execution test D/tests/execution/VertexLaneLocal.cpp. It is auto-registered by the glob at D/CMakeLists.txt:964-981.

  • Draw 189 vertices, once with a wave32 and once with a wave64 vertex program, containing the constructs of T1 case 1/3/4.
  • Each vertex writes its results to a buffer at its vertex index, in the style of ExecHostLanes (D/tests/execution/ExecHostLanes.cpp:62-121). Check them against CPU-computed values.
  • Register a second test, agc_driver_vertex_lane_local_no_vertex_subgroups, with ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_SUBGROUP_STAGES=0x32" and the same expectations. Identical results in both runs is the exactness evidence.

T4. ExecHostLanes.cpp:166-176.

  • When SubgroupStages() lacks VERTEX:
    • without APS5_ONE_LANE_WAVES, expect M1 containing controls a loop;
    • with it, run the draw and the existing Check("vertex", Vertices).
  • Its checks use the vertex index, not the lane, and they allow 1 to Keys passes (:148-162, pass count at :155), so they should hold in the one-lane model.
  • The subgroup-size skip (:170-171) must not apply when the stage has no subgroups.
  • Register …_no_vertex_subgroups (mask 0x32) and …_one_lane_waves (mask plus APS5_ONE_LANE_WAVES=all).

T5. D/tests/ShaderDiskCache.cpp. Disk keys differ when only subgroupStages differs.

7. Docs

  • docs/dev/TechnicalDebt.md.
    • New entry near :157-159: "One-lane waves (recompiler)". With APS5_ONE_LANE_WAVES, a stage the device runs without subgroup operations (MoltenVK: vertex and tessellation evaluation) runs each invocation as a wave of one lane: s3 holds one vertex and one primitive, and the lane index is 0. Ballots, first-lane reads, v_writelane, wave-mask branches, DPP and permlane take their one-lane values. A read of a lane the wave does not launch throws. The result equals the console's only if a vertex's outputs do not depend on the other vertices of its wave or on its vertex count. Not measured on hardware.
    • Add to :157: the exact lowering folds lane-index tests against these counts.
  • docs/user/USAGE.md, after :150-155: a new subsection, "Devices without subgroup operations in vertex shaders". It describes M1, APS5_ONE_LANE_WAVES and its values, and says any other value stops the title.
  • docs/user/MACOS.md.
    • :80: add vertex subgroup operations to the list of things the first titles stopped on.
    • Limitations (:91-99): MoltenVK has no subgroup operations in vertex and tessellation-evaluation shaders. The recompiler lowers what it can exactly; the rest stops with a message naming APS5_ONE_LANE_WAVES.
  • docs/dev/ARCHITECTURE.md:88-90: add one sentence on the lane-local lowering and the test knob APS5_SUBGROUP_STAGES.

8. Effort (engineer-days)

Step Days
Rank 1: plumbing, knob, serializer v17, replay flag, M1 scan, M3, IR dump terminators 2
Rank 2: E1–E3 and moving the helpers 2.5
Rank 2: E4 (guard and identity proofs) 3
Rank 3: one-lane mode 2
Tests T1–T5 3
Docs 0.5
Total ≈13
  • The minimum that probably unblocks a typical vertex program is Rank 1 + E1/E2/E4(i) + tests, about 6 days.
  • E4(ii) and Rank 3 are needed only if M1 lists those items.
  • Split into one PR per topic: diagnostics; exact lowering; opt-in; sample locations.

9. What to ask the user

Now, with the current build (optional, cheap): this gives the sample pattern.

  • Run open --env APS5_MSAA_SINGLE_SAMPLE=1 --env APS5_TRACE_MSAA=1 Title.app.
  • Send the first distinct [msaa] state … lines. They contain 2f8=, 2fe=, 302=, 306=, 30a= (D/Graphics/src/State.cpp:1304); for up to 4 samples that is the whole pattern.

With the new build (Ranks 1 and 2):

  1. Empty the log first: : > ~/Library/Logs/AnyPS5/<title id>.log, because the launcher appends (tools/package_macos_app.py:46).

  2. Run open --env APS5_MSAA_SINGLE_SAMPLE=1 --env APS5_DUMP_SHADERS=1 Title.app.

  3. Send:

    • a. The Selected GPU … stages=0x… operations=0x… line.
    • b. If it stops, the whole error: every line from ShaderRecompiler::Recompile: (or AGC graphics:) through the end of the RecompileRequest: base64 block. Say so if the log shows only one line.
    • c. Every shader_*.req in ~/Library/Application Support/AnyPS5/<title id>/ (D/Execution/src/Driver/Shaders/ShaderDiagnostics.cpp:52-64).
    • d. If it gets further, the next stopping error, plus a screenshot of a scene with characters and terrain.

    We then replay on Linux with agc_shader_replay --subgroup-stages=0x32 --spv shader_<addr>.req, and APS5_DUMP_IR=<addr> for the IR.

  4. Only if M1 names APS5_ONE_LANE_WAVES:

    • Run again with --env APS5_ONE_LANE_WAVES=0x<address from M1>, or all.
    • Send the [recompile] … runs as one-lane waves lines, the next error, and screenshots. Note any geometry that is misplaced or missing.

With the sample-locations build: run without APS5_MSAA_SINGLE_SAMPLE, using --env APS5_TRACE_MSAA=1. Send the error, which now contains the registers, and the [msaa] lines.

Also: the title id and contentVersion, and the package's COMMIT file.

10. Nonstandard sample locations: use VK_EXT_sample_locations

Why it fits:

  • MoltenVK exposes the extension when the device has programmable sample positions (MVK/Layers/MVKExtensions.def:175, MVK/GPUObjects/MVKDevice.mm:3564-3566).
  • Its range and precision are [0, 15/16] in 1/16 steps on a {1,1} pixel grid (MVKDevice.mm:1333-1342, MVKDevice.h:93-97).
  • It reads VkPipelineSampleLocationsStateCreateInfoEXT (MVK/GPUObjects/MVKPipeline.mm:1027-1049).
  • It applies the locations when a Metal render pass begins (MVK/Commands/MVKCommandEncoderState.mm:984-994, MVK/Commands/MVKCommandBuffer.mm:834-839). A change in the middle of a pass restarts the Metal pass (:854-859).

Register format. AGC decodes per-sample signed 4-bit x (low nibble) and y (high nibble), in 1/16 pixel from the pixel centre (D/Graphics/src/State.cpp:362-368). The Vulkan location is ((nx+8)/16, (ny+8)/16).

  • This is exact for all 16 values and lands in [0, 15/16].
  • I checked the conversion against the standard 4x table (State.cpp:346-348) and the test word 0x622ae6ae (D/tests/Graphics.cpp:1759). For example, (-2,-6) maps to (0.375, 0.125), which is Vulkan's standard sample 0.

Steps:

  • S0 (same build). decodeSamples (State.cpp:350-372) throws with:

    • the sample count and PA_SC_AA_CONFIG;
    • the location words of the four pixels (0x2fe-0x30d);
    • the decoded pairs and the standard pairs;
    • the existing APS5_MSAA_SINGLE_SAMPLE hint.

    The trace at :1304 adds the second word of each pixel (0x2ff, 0x303, 0x307, 0x30b) for 8x. Update the equality test at D/tests/Graphics.cpp:1769.

  • S1, device (D/Execution/src/VulkanDevice.cpp, after the conservative-rasterization block at :1173-1179).

    • If the extension is present, query VkPhysicalDeviceSampleLocationsPropertiesEXT.
    • Accept it only if sampleLocationSubPixelBits >= 4 and the coordinate range covers [0, 15/16].
    • Record sampleLocationSampleCounts, and the grid size per count from vkGetPhysicalDeviceMultisamplePropertiesEXT.
    • Enable the extension and put the result in Graphics::Context (D/Graphics/include/Context.hpp, next to subgroup at :111).
  • S2, state.

    • DecodeState has no Context (D/Graphics/include/State.hpp:125). So decodeSamples records the four pixels' locations and two flags (custom, perPixel) in State (D/Graphics/include/State.hpp:82-121, samples at :121), instead of throwing.
    • Keep throwing for things the registers make invalid.
  • S3, pipeline (D/Graphics/src/Pipeline.cpp).

    • Require next to :92/:111: the extension is present, the count is in sampleLocationSampleCounts, and, if the pixels differ, a 2×2 grid is available. Otherwise throw a message that names the registers and the single-sample hint.
    • Chain VkPipelineSampleLocationsStateCreateInfoEXT on samples (:368-369): enable = true, per pixel = samples, grid {1,1} or {2,2}, locations converted in Vulkan's grid order.
    • Append the 16–32 location bytes to the pipeline key (:689) and to the library keys fragmentShader/fragmentOutput (:189-190).
    • Start with static locations. Switch to VK_DYNAMIC_STATE_SAMPLE_LOCATIONS_EXT + vkCmdSetSampleLocationsEXT only if the trace shows the pattern changing per frame (jitter).
  • S4, depth correctness on non-MoltenVK drivers.

    • Create multisampled depth images with VK_IMAGE_CREATE_SAMPLE_LOCATIONS_COMPATIBLE_DEPTH_BIT_EXT.
    • Chain VkSampleLocationsInfoEXT on depth layout transitions and render-pass begin.
    • MoltenVK ignores both (report B: no references in MVK). Without S4, custom locations combined with a multisampled depth target must throw on such drivers.
  • S5, tests and docs.

    • Unit tests on DecodeState: a custom uniform pattern is recorded; differing pixels set perPixel.
    • Pipeline Require tests with a fake Context.
    • An execution test that skips when the extension is absent. I did not determine whether lavapipe exposes it.
    • Add a TechnicalDebt entry for the register-to-Vulkan conversion (from AMD's register format, not measured on hardware), and update USAGE.md "Multisampled render targets".
  • Effort: S0 0.25 day, S1–S3 2 days, S4 1 day, S5 1 day.

Why not: I found no reason against it on MoltenVK. The limits are:

  • different patterns in the four quad pixels cannot be expressed on MoltenVK's {1,1} grid, so they throw;
  • each pattern change between draws restarts the Metal pass.

11. Could not determine

  • Which constructs the title's vertex program contains, and its vertex wave size (bit 22 of VGT_SHADER_STAGES_EN, D/Graphics/src/State.cpp:569). So I cannot say whether E1, E2 and E4(i) alone suffice.
  • Whether the draw-path failure that reaches the log keeps lines after the first. Compute errors are cut (D/Execution/src/Driver/Dispatch/Dispatch.cpp:279).
  • Which argument guards each side-effecting IR opcode. I verified only shared and buffer accesses (last argument), exports (EXEC) and DPP updates. Image, address, append/consume and scalar-store ops must be checked when E4 is implemented; until then, an unknown guard fails the proof.
  • Whether Barrier/Sendmsg are no-ops in Local and TES. The no-op branch checks IrShaderStage::Vertex only (SpirvFlowEmitter.cpp:843).
  • The title's sample pattern, and whether it changes per frame.
  • Whether lavapipe exposes VK_EXT_sample_locations, and RADV's maxSampleLocationGridSize.
  • Whether Apple's Metal compiler rejects SIMD calls in a [[vertex]] function. The plan avoids emitting them, so this does not matter.
  • The PipelineLibrary.cpp lines in Report B (:18-32, :100, :175-179) and its Resources.cpp:~236 (report, not re-read).

File written: /tmp/claude-0/-home-user-AnyPS5-macos/5fe1494a-4d35-554a-a635-e6ebd6cf2b56/scratchpad/vertex-subgroups-design.md


Generated by Claude Code

Copy link
Copy Markdown
Owner Author

Handover: start here

This is the handover from the cloud session to a session on the owner's Mac (M5 Pro). The five comments above hold the designs and analyses; this one says where things stand and what to do next.

Where things stand

  • On main:

    • the upstream merge, from #4;
    • the macOS tools: tools/convert-ps5.sh, tools/unfself.py, and tools/package_macos_app.py, which clones a title with cp -c and clears its quarantine;
    • the opt-in single-sample MSAA fallback APS5_MSAA_SINGLE_SAMPLE=1.
  • This PR, once merged, adds:

    • barycentrics without a geometry stage, for the patterns that can be served exactly;
    • viewport depth outside [0, 1] for draws that cannot observe depth.

    Neither has run on a Mac yet.

  • Titles. All are the owner's own decrypted dumps; do not help with anything else.

    Title ID Last result on macOS
    DOOM homebrew PPSA99666 In game. Converted from fake-signed SELFs with unfself.py, using --exclude-sce-module libc.prx.
    Plants vs. Zombies: Replanted (Unity) PPSA29802 Without APS5_MSAA_SINGLE_SAMPLE=1: "nonstandard sample locations are unsupported". With it: gets through texture loading, then "subgroup capability 61 is unsupported for shader stage 1".
    Hades II (FMOD) PPSA36082 Loads its scripts and package manifests, then the same "subgroup capability 61 … stage 1". Expected next: storage-image multisampling (handover 2).
    Balatro (LÖVE) none "Barycentric geometry SPIR-V: geometry shaders are unavailable". This PR should get it further, or name the shader.
    Peppa Pig (Unity) PPSA03706 "viewport depth outside [0, 1] requires VK_EXT_depth_range_unrestricted". This PR should get it further, or print the depth registers.
    Crash 4 (UE4) PPSA02433 Out of memory after taking all 13824 MiB of direct memory, before the merge. Not retried yet; see handover 3.
  • On the owner's Mac:

    • Game folders are in ~/Downloads. Some are nested; use the folder that holds eboot.bin or eboot.elf and sce_sys.
    • The prebuilt package is in ~/Desktop/AnyPS5/anyps5-macos-x86_64. Converted apps are written there.
    • Logs are in ~/Library/Logs/AnyPS5/<title id>.log.
    • A title runs in ~/Library/Application Support/AnyPS5/<title id>.

Next steps, in order

  1. Vertex-stage subgroups (handover 1). These block PvZ and Hades II. Do phases 1 and 2 of the design:

    • diagnostics, with the device's subgroup stages in the recompiler target and keys;
    • the exact lane-local lowering.

    Then run both titles. If they still stop, the new error names the remaining constructs; the design's §9 says what to capture (APS5_DUMP_SHADERS=1).

  2. Balatro and Peppa: rerun with this PR's build and follow what the new messages say.

  3. PvZ sample locations (handover 1, §10): use VK_EXT_sample_locations so PvZ runs without APS5_MSAA_SINGLE_SAMPLE=1.

  4. Hades II storage-image multisampling (handover 2): P0, P1 and P2 of that design.

  5. Crash 4: run it and read the log first. Handover 3 expects the 448 MiB flexible-memory budget (libkernel Export.cpp) to refuse a ~5.3 GiB flexible map.

  6. Housekeeping:

    • the next scheduled sync conflicts with mugurc's macos-port (handover 4);
    • guest_socket_read_write is flaky on macOS, and handover 5 has a patch.

Building and running from source on the Mac

  • Follow docs/user/MACOS.md. In short:

    cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release
    cmake --build build --parallel
    cmake --build build --target libs --parallel
  • To use convert-ps5.sh with a source build, assemble a package folder the way .github/workflows/macos.yml's Package step does:

    • relinker;
    • libs/*.prx;
    • vulkan/lib/libvulkan.1.dylib, libMoltenVK.dylib and share/vulkan/icd.d/MoltenVK_icd.json, all from the LunarG SDK;
    • package_macos_app.py, unfself.py and convert-ps5.sh.

    Run bash convert-ps5.sh <title folder> <AppName> from that folder. To pass runtime variables, start the title as APS5_…=1 <AppName>.app/Contents/MacOS/launch.

  • Run GPU tests one at a time with a timeout, and skip the flip and display tests. A wedged GPU can stop WindowServer.

  • Repository rules, enforced by tools/check_conventions.py:

    • no code comments except technical-debt markers;
    • unsupported paths throw;
    • approximations are opt-in and documented in docs/dev/TechnicalDebt.md;
    • no title names or IDs in code;
    • Conventional Commits;
    • every test executable registered.

Generated by Claude Code

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants