Repository navigation
feat: draw on MoltenVK without barycentrics or unrestricted depth range where exact - #5
Conversation
…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
Handover 2/5: storage-image multisampling on MoltenVK (Hades II's next expected stop)
Design written to Multisampled storage-image access without
|
| 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 byImageSampleIndex(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
0asSampleeven 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::AddImagerecordsimage.dimension = memory.imageDimension(Optimization/src/ResourceTracker.cpp:1143-1171). RuntimeImageModescopies it into every mode (ResourceMaterializer.cpp:625-676). It adds a plainDim2DMsaamode for an MSAA array at:667-671.BindingAllocatorputs 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, andMAX_MIP == LAST_LEVEL(:106-121). That means fragments == samples (no EQAA) unless the descriptor is R128. descriptorDimensionreturnsDim2DMsaafor 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.guestSamplesfrom CB_COLOR_ATTRIB and keepssamples = 1(State.cpp:931-939). It does the same for depth (:256-257). The fields are atGraphics/include/State.hpp:66,79. - A target with
samples == 1takes the resident path:CachedStorageSurface(context, SurfaceForTarget(color))(Graphics/src/Draw.cpp:1904-1937);SurfaceForTargetbuilds a 2D, one-level surface atcolor.address(Draw.cpp:65-89).
- So the target's texels live in the same
StorageTexturethat 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 matchesdocs/dev/TechnicalDebt.md:413, "A multisampled texture read (image types 14 and 15 ...) still throws".
Upstream real multisampling.
MultisampleTargetcreates a host multisampled image with usageCOLOR_ATTACHMENT | TRANSFER_DSTonly (Graphics/src/MultisampleTarget.cpp:46-102, usage at:53). It has one layer (:63) and stays inGENERAL(: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") callRequireNoMultisampleTarget(MultisampleTarget.cpp:321-330). docs/dev/ARCHITECTURE.md:97describes the same.
1.7 After the capability: the remaining blockers (all devices)
DescriptorBindingBuilder::Prepareruns at materialization (core/shader/recompiler/Recompiler.cpp:637). It setsphysical.imageShape = ImageShapeForResource(...)for every active heap (Optimization/src/DescriptorBindingBuilder.cpp:390-394). For a multisampled shape that call throwsmultisampled 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
activetest (: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-280checks 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
ImageMSArraytoshaderStorageImageMultisample(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 bytools/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:=1enables 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:1disables, anything else throws. - Set
enabled.shaderStorageImageMultisample = available && !knob. - Push both
StorageImageMultisampleandImageMSArrayonly when the feature is enabled. - Store the result in
statefor later phases. P3 needs it, and so does validation.
- Parse
SpirvDescriptors.cpp:136: emitImageMSArrayonly whensampled == 2. For that case:133has already required the feature.ShaderValidation.cpp:236-238and the signature at:550: acceptStorageImageMultisample/ImageMSArrayonly when the device enabled the feature. That needs one moreboolparameter, passed from the caller ofValidateShaders.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.mmhas no explicit check;MVKPixelFormats.mm:619-623would 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::NativetoImageResource(IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/Resources.hpp:60-100).enum class MultisampleAccess { Native, SingleSample, Refused }.- Serialize it in
ShaderDiskCache.cpp, next tofoldTexelOffsetsOnly(:505-506write,:612-613read).
- Setting it.
ResourceMaterializer::ApplyStaticInterface(ResourceMaterializer.cpp:831-889) gets the target facts the same way it getsnativeSampleOffsetstoday.compileVariantcomputes them fromrequest.target(Recompiler.cpp:387-392). In the per-image loop (:857-878), for a direct image with an MSAA dimension,resourceClass == Storage, and noStorageImageMultisamplein the target, setRefused. - Modes.
RuntimeImageModes(:625): aRefusedimage returns exactly one mode:Uintif atomic, otherwiseFloat; one mip; no conversions. - Layout.
BindingAllocator.cpp:122-127: skipRefusedmodes, so there is no heap and noImageTypecall. - Emission.
EmitImage/emitMode(SpirvImageEmitter.cpp:1625-1660) for aRefusedmode:ImageWriteemits nothing;- atomics define a zero of the result type, the same zero
EmitValueOrZeroIfConditionyields 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), ifmodes.front().multisampleAccess == Refused, throw. The message names the T# words and the missing feature, plusState.cpp:145'sSingleSampleHintonce 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
:404and:590.
- This also covers the validation calls at
- 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 whenversion >= 17.VulkanDevice::buildTarget(VulkanDevice.cpp:2911-2918) sets it fromGraphics::SingleSampleMultisampling()(State.cpp:1267-1270).compileVariantpasses it toApplyStaticInterface.
Static interface (ResourceMaterializer.cpp:857-878). When the flag is set, every direct image with an MSAA dimension becomes SingleSample:
Dim2DMsaabecomesDim2D, andDim2DMsaaArraybecomesDim2DArray. The address layout stays the instruction's own, becauseaccess.mem.imageDimensionis 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 scanApplyStaticInterfacealready uses for texel offsets (:835-853):GetRdnaImageAddressComponentLayout(flags, AddressDimension.coordinateComponents)andHasImmediate()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 aSingleSamplebase, type 14 decodes toDim2D, and type 15 toDim2DArrayorDim2D(bywantArray).- Any other T# type for a
SingleSampleimage 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 takesmin(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 LODLodU32, which is 0 because MSAA ops have no mip (:239-247). No change. Every sample reads the one texel.EmitWriteOp(:998-1010): forSingleSample, the condition becomesexec && sample == 0. The sample is read with the existing address code, whichImageSampleIndex(:991-996) should key onAddressDimension(access), the instruction, rather thanaccess.image.dimension. UseBinary(..., OpLogicalAnd, ...)as:969does.EmitAtomicOp(:1012-...):SingleSampleatomics only exist with a constant sample 0, soOpImageTexelPointeron the 2D image with Sample 0 is already what:1044emits 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. Whatimage_get_resinforeturns inwfor an MSAA resource on the hardware is not determined.
Driver.
DecodeTextureResource(GuestTextureResource.cpp:38-47,:52-200): types 14 and 15 are accepted only whenSingleSampleMultisampling(). They decode ask2D/k2DArraywith:mipCount = allocatedMipCount = 1;baseLevel = lastLevel = 0(LAST_LEVELandMAX_MIPencode log2 fragments and log2 samples here, not mips);baseLevel == 0andLAST_LEVEL == MAX_MIPrequired.
ITERATE_256(word6 bit 10) keeps throwing (:113).- Without the fallback, 14 and 15 keep throwing, with
SingleSampleHintadded. - Nothing else changes in the driver. The one-sample
k2Dsurface at the target's address has the sameSurfaceKeyasSurfaceForTarget(Draw.cpp:65-89,ShaderResources.cpp:793-797), so the storage or sampled access shares the render target's residentStorageTexture. Two conditions must hold, and the end-to-end test checks them:- the T#'s
SW_MODEmust resolve (GuestTextureResource.cpp:130-139) to the sameTextureTileModeasColorTextureTileMode(color.tileMode); - the T# must carry no DCC address. Otherwise
MetadataMovedevicts it (ShaderResources.cpp:860-863).
- the T#'s
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 sampleloop.
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_BITto the target image atMultisampleTarget.cpp:53, after checkingsampledImageColorSampleCounts. - Add
DescriptorImageShape::Image2DMultisample(Recompiler.hpp:324-331). Map it inImageShapeForResource(DescriptorBindingBuilder.cpp:79-99) and inMatchesGuestDimension(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 aMultisampleTarget(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 ... Samplebecomes MSLtexture2d_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 atspirv_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)andimageStore(planes, (xy, s)), both through uint views of equal texel size. This is bit-exact.vkCmdCopyImagecannot 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;sampleRateShadingis true on MoltenVK,MVKDevice.mm:2801) and writestexelFetch(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.
MultisampleTargetgets 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 isPlanes. 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.
- storage binding: copy in if needed, then
- 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_testswithENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_NO_STORAGE_IMAGE_MULTISAMPLE=1", next to the loop atcore/libs/prx/libSceAgcDriver/CMakeLists.txt:1182-1215. It checks that:device.ComputeTarget(32).supportedCapabilitieshas neitherStorageImageMultisamplenorImageMSArray;- an invalid knob value throws when the device is created.
- In
tests/execution/PreparedShaders.cpp, a sampled 2D MSAA-arrayimage_loadcompiles with noOpCapability ImageMSArray. Scan the words as the test at:252-275does. tests/ShaderDeviceProfile.cpp:100: anImageMSArraywithout the feature is refused.
P1
PreparedShaders.cpp:276-279changes. With the capability removed, all five variants (:243-250) prepare. The module has noStorageImageMultisample, noImageMSArray, noOpImageWriteand noOpImageTexelPointer, and the atomics yield 0.tests/ShaderMemory.cpp, next toverifyMultisampledImageCapture(:3034), for a storageimage_storewithDIM=6:RuntimeImageModeof a null T# returns 0 andDescriptorBindingBuilder::Preparecreates no binding;- with the type-14 descriptor of
:3044it throws the new message.
- New
tests/execution/MultisampleStorage.cpp, modeled onMultisampleTraceCapture.cpp:27-125(register a compute shader, submit a DCB). Run it underAPS5_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 (
ExpectFailureas at:127-136).
ShaderDiskCacheround trip of the new field, using the pattern attests/ShaderDiskCache.cpp:827-876.
P2
- Recompiler-level, no environment needed: with
target.singleSampleMultisampledImages = trueand the capability removed:- the five variants compile to non-MS
OpTypeImage; OpImageWritesits behindOpIEqual(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
Refusedand throws atPreparewith a type-14 T#.
- the five variants compile to non-MS
RequestSerializerversion 17 round trip, plus the legacy-trailer test atShaderMemory.cpp:1728. TheCacheKeymust differ when the flag differs.- In
tests/Graphics.cpp,singleSampleMultisampleTests(:1817; CTestagc_driver_graphics_single_sample_msaa,CMakeLists.txt:1123-1124):DecodeTextureResourceof a type-14 T# givesk2D, 1 mip,lastLevel 0. An EQAA T# throws. Without the variable, the message carries the hint. - End to end,
tests/execution/MultisampleStorage.cpp single-sampleunderAPS5_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:- Draw a 4x color target filled with A, using
DrawCommands()fromMultisampleTraceCapture.cpp:84-125withCB_COLOR_ATTRIBNUM_SAMPLES = 2and PA_SC_AA_CONFIG 4x. - Dispatch threads
(x, y, s)that storeB_sthroughimage_store DIM=6to a type-14 T# at the target's address. - Dispatch
image_loadof sample 2 into a buffer. - Expect the buffer and the guest bytes at the target (one-sample layout) to hold
B_0. - Expect one
StorageTexturefor both, for example throughStorageImageCached/ the storage counters. - A second case: atomics with a constant sample 0 add exactly once per pixel.
- Draw a 4x color target filled with A, using
P3
- On lavapipe with the feature, a render with per-sample distinct values (sample-mask export), then
image_loadof 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; resinfowis 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): withAPS5_MSAA_SINGLE_SAMPLE=1, multisampled textures are read and written as the one-sample image.docs/user/MACOS.md:80-90: MoltenVK has noshaderStorageImageMultisample, so titles that write multisampled images needAPS5_MSAA_SINGLE_SAMPLE=1.docs/dev/ARCHITECTURE.md:97: P2, and later P3.docs/dev/BUILD.md, tests section:APS5_NO_STORAGE_IMAGE_MULTISAMPLE=1stands 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
- The build they ran: the
COMMITfile of the package (.github/workflows/macos.yml:131-151), orgit rev-parse HEAD. - Whether the title stopped, and if so where. Send the last ~200 lines of
~/Library/Logs/AnyPS5/<title id>.logand everycould not be prepared after registrationline (all addresses). - One run started with
open --env APS5_DUMP_SHADERS=1 Title.app, plus--env APS5_MSAA_SINGLE_SAMPLE=1if they used it before. Then send theshader_*.reqfiles from~/Library/Application Support/AnyPS5/<title id>/, at leastshader_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 showDIM, opcode and sample operands.
- Whether
APS5_MSAA_SINGLE_SAMPLE=1was set, and whether the title has an anti-aliasing setting that changes anything. - 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.reqdumps. - 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_resinforeturns inwfor 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_MODEof a fallback target always maps to the target'sTextureTileMode, so that theSurfaceKeymatches. 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
Handover 3/5: Crash 4 out-of-memory, analysis of the macOS memory path
The harness refused to let me write Out of memory after grabbing all direct memory on macOS: analysis of the current code (
|
Handover 4/5: preview of the next scheduled sync (mugurc macos-port and upstream)
Sync preview: mugurc/macos-port and upstream main into the forkI could not write Short version:
How to read the citations:
Refs as fetched (2026-10-12)
What the next scheduled sync will do
Conflicts and recommended resolution
Merged without conflict but needs a fix
Checking the trial merge
macOS features in mugurc's branch that the fork lacks
The recommended resolution keeps the fork-only features:
Upstream past 8fc53cb
Could not determine
All under
Generated by Claude Code |
Handover 5/5: flaky guest_socket_read_write on macOS (EPIPE vs ECONNRESET)
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:
Why the errno depends on timing on macOS
What FreeBSD 11 (the PS5 base) returnsFreeBSD 11 has the same structure and the same race:
So FreeBSD 11 returns:
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
The test change
Why
The patch adds no comments and needs no TechnicalDebt.md entry. The helper and its includes sit inside Checks:
What I could not determine
Other things I noticed (not in the patch)
fix.patchGenerated by Claude Code |
Handover 1/5: subgroup operations in vertex shaders on MoltenVK (blocks PvZ and Hades II)
Design: subgroup operations in vertex shaders on MoltenVKSource: Path prefixes:
0. SummaryCause. MoltenVK never lists VERTEX or TESSELLATION_EVALUATION in
The recompiler does not know which stages support subgroups: Ranked plan.
Tests. They run on Linux with lavapipe and simulate MoltenVK in two ways:
Sample locations. What to ask the user. §9: one run of the new build with 1. Facts the plan depends on (verified)
Further notes on the reports:
2. Model and what "exact" meansThe existing vertex model (
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:
Other stages keep today's behaviour: the validator throws, now with the better message. 3. Ranked planRank 1: diagnostics and plumbing (first PR, same build as the fix)1a. Stage mask in the target.
1b. Test knob and log line (driver).
1c. The recompiler rejects with a list of constructs.
1d. Validator backstop message. This is Report C's C1; I checked the code it relies on.
1e. IR dump.
Rank 2: exact lane-local lowering (second PR, on by default)New pass. Helpers moved, not copied:
Call site.
The rules run in this order, with constant folding and DCE after each. E1. Own-lane bit of a mask. Every
Why it is exact: bit L of a bitwise combination of words is the same combination of their bit L, and bit L of It generalises
E2. Lane-index folding. Some values have only It covers:
E3. Uniform lane reads. Why it is exact:
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):
How it is represented.
Not exact in v1 (these are reported):
After E1–E4 and DCE, call Rank 3: opt-in
|
| 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: foldFindILsb32andFindUMsb32of constants (neither is in the case list), sos_ff1of 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_tessellationkernels 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)ortessellation evaluation. - Item texts, one per kind:
a ballot read as a valuethe lane indexv_readfirstlane/v_readlane of a lane-varying valuev_writelaneDPP (ctrl 0x…)v_permlane16/x16ds_swizzle/ds_permute/ds_bpermuteds_append/ds_consumea 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 addrequest.target.subgroupStages = 0x32. - Programs come as raw words, as in that test.
- Cases:
- Wave32:
v_cmp→VCC→v_cndmask, av_add_co/v_add_co_cichain,s_and_saveexec+s_cbranch_execzover masked VGPR writes and an export,s_or exec. Expect: noOpCapability61/63/64/65, noOpGroupNonUniform*, noBuiltIn SubgroupLocalInvocationId. - Case 1 again without the mask: the module still contains subgroup ops. This pins that nothing changes on capable devices.
- Wave64 on
subgroupSize = 32with an NGG prologue (s_bfe s3,v_mbcnt, compare against the count,exp prim): exact. - A uniform
v_readfirstlaneofv_mov v0, s[user]: exact. - Must throw M1 with the right item:
s_bcnt1_i32_b32 s0, exec_lofed into an export →a ballot read as a value;- an execz region that sets
s5, withs5read after the join →leaves a scalar value; - a waterfall loop →
controls a loop; - DPP
row_shr:1→DPP.
- A request round-trip through
RequestSerializerkeepssubgroupStages. - Two
PrepareShadercalls with masks 0x32 and ~0 do not share a source. The pattern is the same as:1430-1450.
- Wave32:
- Add an opt-in mode,
agc_shader_memory_tests --one-lane-waves, registered next toD/CMakeLists.txt:1029-1040withENVIRONMENT "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;s3folds to0x101;- fetch-inactive DPP from lane 1 throws M2.
T2. D/tests/Graphics.cpp.
:4499-4528: addguestAddressand 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, withENVIRONMENT "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 containingcontrols a loop; - with it, run the draw and the existing
Check("vertex", Vertices).
- without
- Its checks use the vertex index, not the lane, and they allow 1 to
Keyspasses (: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(mask0x32) and…_one_lane_waves(mask plusAPS5_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)". WithAPS5_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:s3holds 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.
- New entry near
docs/user/USAGE.md, after:150-155: a new subsection, "Devices without subgroup operations in vertex shaders". It describes M1,APS5_ONE_LANE_WAVESand 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 namingAPS5_ONE_LANE_WAVES.
docs/dev/ARCHITECTURE.md:88-90: add one sentence on the lane-local lowering and the test knobAPS5_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 contain2f8=,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):
-
Empty the log first:
: > ~/Library/Logs/AnyPS5/<title id>.log, because the launcher appends (tools/package_macos_app.py:46). -
Run
open --env APS5_MSAA_SINGLE_SAMPLE=1 --env APS5_DUMP_SHADERS=1 Title.app. -
Send:
- a. The
Selected GPU … stages=0x… operations=0x…line. - b. If it stops, the whole error: every line from
ShaderRecompiler::Recompile:(orAGC graphics:) through the end of theRecompileRequest:base64 block. Say so if the log shows only one line. - c. Every
shader_*.reqin~/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, andAPS5_DUMP_IR=<addr>for the IR. - a. The
-
Only if M1 names
APS5_ONE_LANE_WAVES:- Run again with
--env APS5_ONE_LANE_WAVES=0x<address from M1>, orall. - Send the
[recompile] … runs as one-lane waveslines, the next error, and screenshots. Note any geometry that is misplaced or missing.
- Run again with
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 word0x622ae6ae(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_SAMPLEhint.
The trace at
:1304adds the second word of each pixel (0x2ff, 0x303, 0x307, 0x30b) for 8x. Update the equality test atD/tests/Graphics.cpp:1769. - the sample count and
-
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 >= 4and the coordinate range covers [0, 15/16]. - Record
sampleLocationSampleCounts, and the grid size per count fromvkGetPhysicalDeviceMultisamplePropertiesEXT. - Enable the extension and put the result in
Graphics::Context(D/Graphics/include/Context.hpp, next tosubgroupat:111).
- If the extension is present, query
-
S2, state.
DecodeStatehas noContext(D/Graphics/include/State.hpp:125). SodecodeSamplesrecords the four pixels' locations and two flags (custom,perPixel) inState(D/Graphics/include/State.hpp:82-121,samplesat:121), instead of throwing.- Keep throwing for things the registers make invalid.
-
S3, pipeline (
D/Graphics/src/Pipeline.cpp).Requirenext to:92/:111: the extension is present, the count is insampleLocationSampleCounts, 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
VkPipelineSampleLocationsStateCreateInfoEXTonsamples(: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 keysfragmentShader/fragmentOutput(:189-190). - Start with static locations. Switch to
VK_DYNAMIC_STATE_SAMPLE_LOCATIONS_EXT+vkCmdSetSampleLocationsEXTonly 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
VkSampleLocationsInfoEXTon 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.
- Create multisampled depth images with
-
S5, tests and docs.
- Unit tests on
DecodeState: a custom uniform pattern is recorded; differing pixels setperPixel. PipelineRequiretests with a fakeContext.- An execution test that skips when the extension is absent. I did not determine whether lavapipe exposes it.
- Add a
TechnicalDebtentry for the register-to-Vulkan conversion (from AMD's register format, not measured on hardware), and update USAGE.md "Multisampled render targets".
- Unit tests on
-
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/Sendmsgare no-ops in Local and TES. The no-op branch checksIrShaderStage::Vertexonly (SpirvFlowEmitter.cpp:843). - The title's sample pattern, and whether it changes per frame.
- Whether lavapipe exposes
VK_EXT_sample_locations, and RADV'smaxSampleLocationGridSize. - Whether Apple's Metal compiler rejects SIMD calls in a
[[vertex]]function. The plan avoids emitting them, so this does not matter. - The
PipelineLibrary.cpplines in Report B (:18-32,:100,:175-179) and itsResources.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
Handover: start hereThis 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
Next steps, in order
Building and running from source on the Mac
Generated by Claude Code |
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:v_interp_mov_f32is declared Flat, so it reads the provoking vertex. In first-vertex mode that is the same vertex the emulation read.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)):ResolveHostDepthdecides the host viewport depth and depth bounds for each draw.Without the extension, depth bounds are mapped exactly. Bounds on a device without the
depthBoundsfeature throw, and so do depth clears outside [0, 1].APS5_NO_DEPTH_RANGE_UNRESTRICTED=1reproduces the macOS behaviour on other devices. The remap that would draw observed out-of-range depth exactly is not part of this PR.Tested
main, all 426agc, shader and recompiler tests pass or skip exceptagc_driver_prepared_shaders_registered_workgroup_sync, which fails the same way onmainwith llvmpipe.agc_driver_rect_list_barycentric_emulation;ResolveHostDepthtable;agc_driver_host_depth_rangein four modes: plain, restricted, restricted withAPS5_NO_GPL=1(the macOS path), and restricted withAPS5_VERIFY_DRAW_RECIPE=1.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_syncfails as onmain.check_conventions.pyandcheck_test_registration.pypass.Checklist
main; no other open PR implements the same functionsNotImplemented_nid_no_patch); silent stubs are listed in TechnicalDebt.mdfiles or images added to the repository (attach them to this PR)🤖 Generated with Claude Code
https://claude.ai/code/session_01HSL58TWgY3qJuxYjEgaYDE
Generated by Claude Code