graphics: draw per-vertex pixel shaders through the VS-store path on MoltenVK #1441

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

@⁠wuboo on GitHub · 2026-10-12 06:54 UTC · original
wuboo:pr/pv-vsstore-wiring → main · +3088 −18 · 22 files · 12 commits · closed without merging

Depends on #1440 (the emitter and perVertexVsStore.h); the first three commits of this branch are #1440, review only the last two.
The path only matters where the game gets as far as drawing on MoltenVK, i.e. together with the PRs that
let the renderer start on Apple GPUs without the optional device features (for example #1314, and #633 /
#1083 for the rest of the start-up); on its own it changes nothing on devices that run PerVertexKHR.

What this is

#1440 can emit a vertex/pixel shader pair that passes the per-vertex attributes through a storage
buffer. This PR makes the renderer use it, on devices that cannot run PerVertexKHR.

  • When it is on. PvVsStoreEnabledFor(fragmentShaderBarycentric, moltenvk, KYTY_PV_VSSTORE):
    by default when the device does not run fragmentShaderBarycentric and the driver is MoltenVK
    (VkPhysicalDeviceDriverProperties::driverID). KYTY_PV_VSSTORE=0 turns it off, =1 forces it on
    (A/B runs, the GPU harness on another driver). On macOS the extension is never requested today, so
    the first term is false there; if #959 lands, the call in vulkanWindow.cpp passes its
    fragment_shader_barycentric_enabled instead (a one-line change).
  • Compile time. For every compiled vertex shader and every pixel shader with per-vertex Parameter
    inputs the VS-store variant is emitted next to the normal one (same push_data_start_dword, so the
    descriptor layout is unchanged), validated with spirv-val, and remembered by shader id. A variant
    that fails validation is logged and its draws keep the existing path. This doubles the emission cost
    of vertex shaders when the path is on.
  • Draw time (RenderExecutor::TryPvVsStoreDraw, decided before any resource of the draw is
    prepared): DecidePvVsStore (#1440, CPU-tested) takes the interface verdict of the pair, the draw
    plan from ScanPvVsStoreVertexRange (min/max of index + vertex_offset), whether the index buffer
    can be bound as a storage descriptor, whether its last word fits in the buffer the cache hands out,
    and whether a cap region is free. If everything holds the draw is recorded with the VS-store pair's
    pipeline (distinct pipeline-cache identity), set 1 = {cap slab, index buffer} and the 8-dword push
    block after the native push data.
  • Cap slabs. 64 MiB buffers, at most 8, one region per draw, a slab is reused only after the tick
    it was last used in has finished on the GPU. Touch is called when the draw is recorded, because
    resource preparation can flush the scheduler between Place and the draw.
  • Counters. Per reason a draw stays on the existing path (topology, vertex range, instanced size,
    ring, location 31, interface, index tail), plus used draws, instanced draws, records and scanned
    indices. They are logged on the first candidate draw and every 8192nd.

The index buffer copy of 8-bit indices (already widened to 16 bit on the host) is padded to a whole
word, because the pixel shader reads the buffer as uint32.

Fallback

A draw that cannot take the path is drawn exactly as before this PR. There is no replacement path
(no capture/replay prototype in main), so on a device without PerVertexKHR such a draw still has
the problems it has today; the counters say how many there are. In particular triangle strips and
fans, non-indexed draws and primitive restart are not covered.

Tests

  • CPU (per_vertex_vsstore): capability switch and its parser, the vertex-range scan (both index
    sizes, unaligned source, negative and positive vertex_offset, dropped corners, 32-bit overflow),
    nine more mutants (see #1440 for how mutants are made); each fails its test.
  • The renderer wiring itself (TryPvVsStoreDraw, BindPvVsStore, slab buffers, pipeline layout with
    the second set) is not covered by CPU tests: it needs a Vulkan device. The GPU harness from #1440
    (7/7 cases and --stress) covers the shader pair and the descriptor/push layout, not the renderer.
  • In game. The same code ran on MoltenVK in a game on a local stack that carries other work as well
    (a bench branch, not this branch): on the level scene the path gave +21 % to +34 % frames per second
    over the same stack with KYTY_PV_VSSTORE=0 (where those draws went through a local capture/replay prototype path that main does not have), with identical frames at the same guest flips. This rebased branch has not been run in a game by
    itself, so treat the numbers as indicative of the mechanism, not as a measurement of this exact tree.
  • Full ctest as on main (GPU-dependent tests skip without a Vulkan loader).

Limits and honest caveats

  • Relies on the vertex stage of a render pass being finished before its fragment stage reads the cap
    buffer (tile-based GPUs behind MoltenVK); that is why the default is MoltenVK only. See #1440.
  • Cost: one record of stride * 16 bytes per vertex per instance per draw, kept until the GPU
    finishes the command buffer; draws that do not fit a 64 MiB slab stay on the existing path. The
    index scan reads every index of every candidate draw once, on the CPU (no memo in this PR); it was
    not measured.
  • Pipelines and shader modules of the VS-store pairs are created lazily and live until exit.
  • Overlaps: #959 (barycentric optional), #643 (vertex-pixel interpolation), #685 (descriptor sets for
    MoltenVK pipelines, touches the same pipeline-layout code). Textual conflicts with several others
    in renderDraw.cpp / vulkanWindow.cpp.
**@⁠wuboo** on GitHub · 2026-10-12 06:54 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1441) `wuboo:pr/pv-vsstore-wiring` → `main` · +3088 −18 · 22 files · 12 commits · closed without merging Depends on #1440 (the emitter and `perVertexVsStore.h`); the first three commits of this branch are #1440, review only the last two. The path only matters where the game gets as far as drawing on MoltenVK, i.e. together with the PRs that let the renderer start on Apple GPUs without the optional device features (for example #1314, and #633 / #1083 for the rest of the start-up); on its own it changes nothing on devices that run `PerVertexKHR`. ## What this is #1440 can emit a vertex/pixel shader pair that passes the per-vertex attributes through a storage buffer. This PR makes the renderer use it, on devices that cannot run `PerVertexKHR`. - **When it is on.** `PvVsStoreEnabledFor(fragmentShaderBarycentric, moltenvk, KYTY_PV_VSSTORE)`: by default when the device does not run `fragmentShaderBarycentric` and the driver is MoltenVK (`VkPhysicalDeviceDriverProperties::driverID`). `KYTY_PV_VSSTORE=0` turns it off, `=1` forces it on (A/B runs, the GPU harness on another driver). On macOS the extension is never requested today, so the first term is `false` there; if #959 lands, the call in `vulkanWindow.cpp` passes its `fragment_shader_barycentric_enabled` instead (a one-line change). - **Compile time.** For every compiled vertex shader and every pixel shader with per-vertex `Parameter` inputs the VS-store variant is emitted next to the normal one (same `push_data_start_dword`, so the descriptor layout is unchanged), validated with `spirv-val`, and remembered by shader id. A variant that fails validation is logged and its draws keep the existing path. This doubles the emission cost of vertex shaders when the path is on. - **Draw time** (`RenderExecutor::TryPvVsStoreDraw`, decided before any resource of the draw is prepared): `DecidePvVsStore` (#1440, CPU-tested) takes the interface verdict of the pair, the draw plan from `ScanPvVsStoreVertexRange` (min/max of `index + vertex_offset`), whether the index buffer can be bound as a storage descriptor, whether its last word fits in the buffer the cache hands out, and whether a cap region is free. If everything holds the draw is recorded with the VS-store pair's pipeline (distinct pipeline-cache identity), set 1 = {cap slab, index buffer} and the 8-dword push block after the native push data. - **Cap slabs.** 64 MiB buffers, at most 8, one region per draw, a slab is reused only after the tick it was last used in has finished on the GPU. `Touch` is called when the draw is recorded, because resource preparation can flush the scheduler between `Place` and the draw. - **Counters.** Per reason a draw stays on the existing path (topology, vertex range, instanced size, ring, location 31, interface, index tail), plus used draws, instanced draws, records and scanned indices. They are logged on the first candidate draw and every 8192nd. The index buffer copy of 8-bit indices (already widened to 16 bit on the host) is padded to a whole word, because the pixel shader reads the buffer as `uint32`. ## Fallback A draw that cannot take the path is drawn exactly as before this PR. There is no replacement path (no capture/replay prototype in main), so on a device without `PerVertexKHR` such a draw still has the problems it has today; the counters say how many there are. In particular triangle strips and fans, non-indexed draws and primitive restart are not covered. ## Tests - CPU (`per_vertex_vsstore`): capability switch and its parser, the vertex-range scan (both index sizes, unaligned source, negative and positive `vertex_offset`, dropped corners, 32-bit overflow), nine more mutants (see #1440 for how mutants are made); each fails its test. - The renderer wiring itself (`TryPvVsStoreDraw`, `BindPvVsStore`, slab buffers, pipeline layout with the second set) is not covered by CPU tests: it needs a Vulkan device. The GPU harness from #1440 (7/7 cases and `--stress`) covers the shader pair and the descriptor/push layout, not the renderer. - **In game.** The same code ran on MoltenVK in a game on a local stack that carries other work as well (a bench branch, not this branch): on the level scene the path gave +21 % to +34 % frames per second over the same stack with `KYTY_PV_VSSTORE=0` (where those draws went through a local capture/replay prototype path that `main` does not have), with identical frames at the same guest flips. This rebased branch has not been run in a game by itself, so treat the numbers as indicative of the mechanism, not as a measurement of this exact tree. - Full `ctest` as on `main` (GPU-dependent tests skip without a Vulkan loader). ## Limits and honest caveats - Relies on the vertex stage of a render pass being finished before its fragment stage reads the cap buffer (tile-based GPUs behind MoltenVK); that is why the default is MoltenVK only. See #1440. - Cost: one record of `stride * 16` bytes per vertex per instance per draw, kept until the GPU finishes the command buffer; draws that do not fit a 64 MiB slab stay on the existing path. The index scan reads every index of every candidate draw once, on the CPU (no memo in this PR); it was not measured. - Pipelines and shader modules of the VS-store pairs are created lazily and live until exit. - Overlaps: #959 (barycentric optional), #643 (vertex-pixel interpolation), #685 (descriptor sets for MoltenVK pipelines, touches the same pipeline-layout code). Textual conflicts with several others in `renderDraw.cpp` / `vulkanWindow.cpp`.
The vertex shader of a pair writes its Parameter outputs to a storage buffer
(cap[record * stride + slot], bits unchanged); the pixel shader reads the three
corners of its primitive back through gl_PrimitiveID and the draw's index buffer
instead of using PerVertexKHR inputs. EmitProgram takes an optional PvStoreInfo;
without it the output is unchanged.

perVertexVsStore.h holds the arithmetic both sides must agree on (record
numbering, draw plan, pass ring, slab bookkeeping, index-descriptor math,
fallback classification) with CPU tests. Mutants are generated at configure time
from copies of the sources (tests/PerVertexVsStoreMutants.cmake), so the
production sources carry no mutant switches.
Draws the real emitter output with the renderer's set/push layout and compares
every probed pixel bit for bit with the CPU per-vertex model; reads the cap
buffer back to check what gl_VertexIndex / gl_InstanceIndex contain. Cases: 16-
and 32-bit indices, vertex_offset of both signs, first_instance, two instances,
an index buffer bound at an offset that is not a multiple of
minStorageBufferOffsetAlignment, 16-bit indices ending inside a word; --stress
adds draws of 2M+ triangles with 2..4 instances. --dump prints the SPIR-V and
needs no GPU. Opt-in (MoltenVK through SDL_VULKAN_LIBRARY), not part of ctest.
Two harness mutants (corners 0/2 swapped, unrounded index range) must fail it.
Location 31 carries the instance index from the VS to the PS, so a pair that
uses it cannot take the VS-store path, but the emitter used to abort the
process on it before ClassifyPvVsStoreInterface could reject the pair. The
location is now recorded and the interface check decides. Test: a VS exporting
parameter 31 emits and reports location 31; mutant: the old abort.
PlanPvVsStore multiplied records by the record stride in 64 bits only. A zero
stride made the product 0 whatever the draw size, and a record count near 2^60
wrapped the product around 2^64, so both passed as Use although the record base is
a uint32_t. The plan now bounds the record count itself and treats a zero stride
as nothing to store.

Tests: per_vertex_vsstore with mutants stride_zero_ok and records_wrap_ok.
Create the command pool with the reset flag, because the loop re-records one
command buffer for every case. Add the memory dependencies the harness lacked: a
subpass dependency from the colour attachment writes (and the final layout
transition) to the copy, and a barrier from the copy and the vertex shader stores
to the host reads. MoltenVK accepted the old harness; other drivers or the
validation layers need these.
The VS-store pixel shader reads PrimitiveId and declared the Geometry capability
for it. The device enables tessellationShader but never geometryShader (MoltenVK
has none), so a module declaring Geometry uses a feature that is not enabled.
PrimitiveId in a fragment shader is also valid with Tessellation.

Tests: shader_cfg checks the capability; the capability_geometry mutant
(shader_cfg_pv_vsstore_mutant_capability_geometry) brings Geometry back.
The VS-store pixel shader declares the Tessellation capability for PrimitiveId, so the
harness has to enable that feature (as the renderer does) instead of geometryShader.
PvVsStoreEnabledFor: the path is used when the device does not run PerVertexKHR
(fragmentShaderBarycentric not enabled) and the driver is MoltenVK;
KYTY_PV_VSSTORE=0 turns it off, =1 forces it on. ScanPvVsStoreVertexRange
derives the vertex numbers (index + vertex_offset) a draw reads, reports
negative ones as dropped and refuses numbers the 32-bit shader math cannot hold.
CPU tests, with nine more generated mutants.
On a device that cannot run PerVertexKHR the VS and the per-vertex pixel shader
of a pair are emitted again as VS-store variants at compile time, paired into
pipeline programs on first use, and drawn with set 1 (cap slab + index buffer)
and a push block after the native push data. Cap regions come from 64 MiB slabs
that are reused only after the GPU has finished the tick they were last used in;
the index descriptor is aligned, rounded to a whole word and clamped to the
buffer. Draws that cannot take the path (not a triangle list, not indexed,
primitive restart, location 31, a PS input the VS does not write, unknown or
dropped vertex range, no ring room, index tail that does not fit) keep the
existing path and are counted per reason. The path is on for MoltenVK without
fragmentShaderBarycentric; KYTY_PV_VSSTORE=0/1 overrides.
GetPvVsStorePrograms creates two shader modules for every accepted pair and
PvVsStoreSetLayout one descriptor set layout, all kept in process-wide statics that
nothing destroyed. At vkDestroyDevice the validation layer reports them as
leaked objects, which the debug messenger turns into an exit, and the statics
kept handles of a device that was gone. ShutdownPvVsStore destroys them and clears
the maps; the window context calls it after the device is idle and the render
context (pipelines and pipeline layouts) is gone, before the device is destroyed.
TryPvVsStoreDraw validated the result of an early ObtainBuffer, but
BindPvVsStore uses the binding PrepareIndexBuffer returns after
PrepareGraphicsBindings and AcquireVertexBuffers; the buffer cache can
merge or move the range in between, so the offset and the buffer size
may differ. The decision now runs right after PrepareIndexBuffer, on
the actual offset and buffer size (PvVsStoreIndexBindingFits), still
before the pipeline is chosen and the draw is recorded.

Test: PvVsStoreIndexBindingFits cases in per_vertex_vsstore; mutant
binding_fits_no_tail.
RememberPvVsStoreShader called EmitProgram with four arguments, but the
fourth parameter is maintenance8_enabled and pv_store is the sixth: the
pointer converted to bool, no VS-store info reached the emitter, and the
stored VS and PS were the plain modules (no pv_cap, no pv_indices). Pass
maintenance8 and the debug flag explicitly.

Test: TestPvVsStoreRemember in shader_cfg (the stored VS has a nonzero
location mask and pv_cap, the stored PS has pv_indices and no PerVertexKHR);
mutant shader_cfg_pv_vsstore_mutant_args4 (the four-argument call).
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:56:50 +00:00
github-bot closed this pull request 2026-11-26 09:56:50 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-12 07:03 UTC · original · edited 2026-10-17 11:32 UTC

Review in Change Stack →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

The change adds a per-vertex VS-store path for eligible indexed triangle draws. It adds planning and allocation helpers, emits vertex and pixel SPIR-V variants that store and load per-vertex data, and integrates the variants into renderer pipeline and draw execution. Draws that do not qualify continue through the existing path. CPU, shader-emission, GPU, and mutation tests cover the helpers and rendering path.

Suggested reviewers: theantipopau

Priority: ➖ Normal

Change: Feature

Merge Risk: 🟠 High · up to 29655

Eligible VS-store draws can fail on the intended MoltenVK path or render incorrect per-vertex inputs; some supported devices can also halt when creating the pipeline. These issues affect the feature’s core rendering path and should be fixed before merge.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 27.78% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 126 functions across 18 files. (1 skipped… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Description check Passed The description clearly explains the VS-store renderer integration, enablement rules, fallback behavior, tests, performance context, and known limitations.
Title check Passed The title clearly and concisely identifies the main change: routing per-vertex pixel shaders through the VS-store path on MoltenVK.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Docstring Coverage

Explanation

Docstring coverage is 27.78% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 126 functions across 18 files. (1 skipped: 1 unsupported.)

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-12 07:03 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1441#issuecomment-6119406574) · edited 2026-10-17 11:32 UTC <!-- This is an auto-generated comment: summarize by coderabbit.ai --> <!-- review_stack_entry_start --> <a href="https://app.coderabbit.ai/change-stack/KytyPS5/KytyPS5/pull/1441?scope=ghh_OusAJGA4HG8ljoOV0wJvVx8NmnZIjc2DdjmxOu0xZWA&amp;cs_source=review_comment"><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui-dark.svg?v=3"><source media="(prefers-color-scheme: light)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg?v=3"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg?v=3" alt="Review in Change Stack →" height="32"></picture></a> <!-- review_stack_entry_end --> <!-- This is an auto-generated comment: review paused by coderabbit.ai --> > [!NOTE] > ## Reviews paused > > It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the `reviews.auto_review.auto_pause_after_reviewed_commits` setting. > > - Last reviewed commit: 29655ac0ed289087d92537ffd25ba3f22a8cb396 > - Latest commit, not reviewed: 052cb072b5cbb2e28e43a0cda71954ec5dd2d414 > > Use the following commands to manage reviews: > - `@coderabbitai resume` to resume automatic reviews. > - `@coderabbitai review` to trigger a single review. > > Use the checkboxes below for quick actions: > - [ ] <!-- {"checkboxId":"7f6cc2e2-2e4e-497a-8c31-c9e4573e93d1"} --> ▶️ Resume reviews > - [ ] <!-- {"checkboxId":"e9bb8d72-00e8-4f67-9cb2-caf3b22574fe"} --> 🔍 Trigger review <!-- end of auto-generated comment: review paused by coderabbit.ai --> <!-- walkthrough_start --> <details> <summary><strong>📝 Walkthrough</strong></summary> <dl> <dd> The change adds a per-vertex VS-store path for eligible indexed triangle draws. It adds planning and allocation helpers, emits vertex and pixel SPIR-V variants that store and load per-vertex data, and integrates the variants into renderer pipeline and draw execution. Draws that do not qualify continue through the existing path. CPU, shader-emission, GPU, and mutation tests cover the helpers and rendering path. **Suggested reviewers:** `theantipopau` </dd> </dl> </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ➖ Normal <!-- change_assessment_commit:"29655ac0ed289087d92537ffd25ba3f22a8cb396" --> **Change:** Feature <!-- change_assessment_end --> <details> <summary><strong>Merge Risk:</strong> <strong>🟠 High</strong> · up to <code>29655</code></summary> <dl> <dd> <!-- final_review_risk_start --> <!-- final_review_risk_label **Merge Risk:** **🟠 High** · up to `29655` --> <!-- final_review_risk_coverage:{"sourceCommitId":"29655ac0ed289087d92537ffd25ba3f22a8cb396","coveredCommitId":"29655ac0ed289087d92537ffd25ba3f22a8cb396","kind":"reviewed"} --> Eligible VS-store draws can fail on the intended MoltenVK path or render incorrect per-vertex inputs; some supported devices can also halt when creating the pipeline. These issues affect the feature’s core rendering path and should be fixed before merge. <!-- final_review_risk_end --> </dd> </dl> </details> <!-- pre_merge_checks_walkthrough_start --> <details> <summary><strong>Pre-merge checks: <sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-passed-14-v2.svg" width="14" height="14" align="middle" alt="Passed" title="Passed"></picture></sup> 4 · <sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-failed-14-v2.svg" width="14" height="14" align="middle" alt="Failed" title="Failed"></picture></sup> 1</strong></summary> <dl> <dd> <strong><sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-failed-14-v2.svg" width="14" height="14" align="middle" alt="Failed" title="Failed"></picture></sup> Failed checks: 1 warning</strong> | Check name | Status | Explanation | Resolution | | :---------------- | :----------------------------------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------- | | Docstring Coverage | ![Warning](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-warning.svg) | Docstring coverage is 27.78% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 126 functions across 18 files. (1 skipped… | Write docstrings for the functions missing them to satisfy the coverage threshold. | <details> <summary><strong><sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-passed-14-v2.svg" width="14" height="14" align="middle" alt="Passed" title="Passed"></picture></sup> Passed checks: 4 passed</strong></summary> <dl> <dd> | Check name | Status | Explanation | | :------------------------ | :--------------------------------------------------------------------------------------------: | :---------------------------------------------------------------------------------------------------------------------------------------------------------- | | Description check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The description clearly explains the VS-store renderer integration, enablement rules, fallback behavior, tests, performance context, and known limitations. | | Title check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The title clearly and concisely identifies the main change: routing per-vertex pixel shaders through the VS-store path on MoltenVK. | | Linked Issues check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | Check skipped because no linked issues were found for this pull request. | | Out of Scope Changes check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | Check skipped because no linked issues were found for this pull request. | </dd> </dl> </details> <details> <summary><strong>Full details: Docstring Coverage</strong></summary> <dl> <dd> **Explanation** Docstring coverage is 27.78% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 126 functions across 18 files. (1 skipped: 1 unsupported.) **Resolution** Write docstrings for the functions missing them to satisfy the coverage threshold. </dd> </dl> </details> </dd> </dl> </details> <!-- pre_merge_checks_walkthrough_end --> <!-- autopilot:start --> - [ ] <!-- {"checkboxId":"2708ad07-9f24-4260-9c11-7dc76a49f2e3"} --> <strong title="Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts">Autofix</strong> · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts <!-- autopilot:end --> <!-- tips_start --> Thanks for using [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=KytyPS5/KytyPS5&utm_content=1441)! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. <details> <summary><strong>❤️ Share</strong></summary> <dl> <dd> - [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai) - [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai) - [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai) - [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code) </dd> </dl> </details> <sub>Comment `@coderabbitai help` to get the list of available commands.</sub> <!-- tips_end -->
@ -0,0 +179,4 @@
// Distinct pipeline-cache identity from the PerVertexKHR variants of the same programs.
value.graphics.vertex[0].id |= 1ull << 61;
value.graphics.pixel.id |= 1ull << 61;
value.graphics.pv_store_layout = PvVsStoreSetLayout(graphics);
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-12 07:03 UTC · original · edited 2026-10-12 10:16 UTC

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Destroy the VS-store shader modules and the set layout.

GetPvVsStorePrograms creates two shader modules with CompileSPV for each accepted pair. It stores them in the static s_pairs. PvVsStoreSetLayout creates the static s_set_layout. No code destroys any of these objects:

  • ProgramCache::~ProgramCache destroys only the native permutation modules.
  • PipelineCache::~PipelineCache destroys only the per-pipeline layouts.

At vkDestroyDevice, the validation layer reports the remaining objects as validation errors. VulkanDebugMessengerCallback calls EXIT on these errors, so a run with validation enabled aborts at shutdown. The static maps also keep handles from the old device after the device is gone.

Add a teardown function, for example ShutdownPvVsStore(vk::Device). It must destroy every s_pairs module and s_set_layout, then clear s_pairs and s_shaders. Call it from the pipeline cache destructor or before device.destroy.

✅ Confirmed as addressed by @⁠wuboo

**@⁠coderabbitai[bot]** on GitHub · 2026-10-12 07:03 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1441#discussion_r4245412074) · edited 2026-10-12 10:16 UTC **🩺 Stability & Availability** | **🟡 Minor** | **⚡ Quick win** **Destroy the VS-store shader modules and the set layout.** `GetPvVsStorePrograms` creates two shader modules with `CompileSPV` for each accepted pair. It stores them in the static `s_pairs`. `PvVsStoreSetLayout` creates the static `s_set_layout`. No code destroys any of these objects: - `ProgramCache::~ProgramCache` destroys only the native permutation modules. - `PipelineCache::~PipelineCache` destroys only the per-pipeline layouts. At `vkDestroyDevice`, the validation layer reports the remaining objects as validation errors. `VulkanDebugMessengerCallback` calls `EXIT` on these errors, so a run with validation enabled aborts at shutdown. The static maps also keep handles from the old device after the device is gone. Add a teardown function, for example `ShutdownPvVsStore(vk::Device)`. It must destroy every `s_pairs` module and `s_set_layout`, then clear `s_pairs` and `s_shaders`. Call it from the pipeline cache destructor or before `device.destroy`. <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:645b060a1ba9c8a286ec44ce --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Confirmed as addressed by @⁠wuboo <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-12 07:03 UTC · original · edited 2026-10-12 10:18 UTC
On src/graphics/shader/recompiler/backend/spirv/spirvEmitterPvStore.cpp line 157 (outdated):

@@ -0,0 +1,217 @@
+#include "graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h"
+
+// VS-store: the guest VS stores its PerVertex parameters to cap[record * stride +
+// slot]; the guest PS reads the three corners of its primitive back. The record arithmetic mirrors
+// graphics/host_gpu/renderer/perVertexVsStore.h (PvVsStoreVertexRecord / PvVsStoreCornerRecord).
+
+namespace Libs::Graphics::ShaderRecompiler::Spirv::Emitter {
+
+namespace {
+
+bool IsVertex(const EmitterState& state) {
+	return state.pv_store->role == PvStoreInfo::Role::Vertex;
+}
+
+uint32_t U(EmitterState& state, spv::Op op, uint32_t lhs, uint32_t rhs) {
+	return Binary(state, op, TypeU32(state), lhs, rhs);
+}
+
+uint32_t C(EmitterState& state, uint32_t value) {
+	return ConstantU32(state, value);
+}
+
+uint32_t Push(EmitterState& state, uint32_t dword) {
+	const auto pointer = state.builder.AllocateId();
+	state.builder.AddFunction(spv::OpAccessChain, TypePushConstantElementPointer(state), pointer,
+	                          state.push_constant_variable, C(state, 1), C(state, dword));
+	const auto value = state.builder.AllocateId();
+	state.builder.AddFunction(spv::OpLoad, TypeU32(state), value, pointer);
+	return value;
+}
+
+uint32_t LoadSigned(EmitterState& state, uint32_t variable) {
+	const auto value = state.builder.AllocateId();
+	const auto bits  = state.builder.AllocateId();
+	state.builder.AddFunction(spv::OpLoad, TypeI32(state), value, variable);
+	state.builder.AddFunction(spv::OpBitcast, TypeU32(state), bits, value);
+	return bits;
+}
+
+// base + (instance - first_instance) * span + (vertex - first)
+uint32_t Record(EmitterState& state, uint32_t instance, uint32_t vertex) {
+	const auto relative_instance =
+	    U(state, spv::OpISub, instance, Push(state, kPvPushFirstInstance));
+	const auto instance_part   = U(state, spv::OpIMul, relative_instance, Push(state, kPvPushSpan));
+	const auto relative_vertex = U(state, spv::OpISub, vertex, Push(state, kPvPushFirst));
+	return U(state, spv::OpIAdd, U(state, spv::OpIAdd, Push(state, kPvPushBase), instance_part),
+	         relative_vertex);
+}
+
+uint32_t CapComponentPointer(EmitterState& state, uint32_t record, uint32_t slot,
+                             uint32_t component) {
+	// stride 0 = the stride comes with the draw (the two variants are emitted independently).
+	constexpr uint32_t kStrideDword = kPvPushStride;
+	const auto         stride       = state.pv_store->record_stride_vec4 != 0
+	                                      ? C(state, state.pv_store->record_stride_vec4)
+	                                      : Push(state, kStrideDword);
+	const auto         element =
+	    U(state, spv::OpIAdd, U(state, spv::OpIMul, record, stride), C(state, slot));
+	const auto pointer = state.builder.AllocateId();
+	if (component == UINT32_MAX) {
+		state.builder.AddFunction(
+		    spv::OpAccessChain,
+		    TypePointer(state, spv::StorageClassStorageBuffer, TypeU32Vector(state, 4)), pointer,
+		    state.pv_cap_buffer, C(state, 0), element);
+	} else {
+		state.builder.AddFunction(
+		    spv::OpAccessChain, TypePointer(state, spv::StorageClassStorageBuffer, TypeU32(state)),
+		    pointer, state.pv_cap_buffer, C(state, 0), element, C(state, component));
+	}
+	return pointer;
+}
+
+uint32_t SlotOf(const EmitterState& state, uint32_t host_location) {
+	if (state.pv_store->record_stride_vec4 == 0) {
+		// Dynamic stride: slot == host location. Location 31 carries the instance index: a stage
+		// that uses it is still emitted (the location is recorded) and ClassifyPvVsStoreInterface
+		// rejects the pair.
+		EXIT_IF(host_location > kPvVsStoreInstanceLocation);
+		if (state.pv_store->location_mask != nullptr)
+			*state.pv_store->location_mask |= 1u << host_location;
+		return host_location;
+	}
+	const auto slot = state.pv_store->parameter_slots.find(host_location);
+	EXIT_IF(slot == state.pv_store->parameter_slots.end() ||
+	        slot->second >= state.pv_store->record_stride_vec4);
+	return slot->second;
+}
+
+// Index value of element `element` (16- or 32-bit buffer, chosen by the push flag).
+uint32_t FetchIndex(EmitterState& state, uint32_t element) {
+	const auto index32 =
+	    Binary(state, spv::OpINotEqual, TypeBool(state), Push(state, kPvPushIndex32), C(state, 0));
+	const auto word   = Select(state, TypeU32(state), index32, element,
+	                           U(state, spv::OpShiftRightLogical, element, C(state, 1)));
+	const auto length = state.builder.AllocateId();
+	state.builder.AddFunction(spv::OpArrayLength, TypeU32(state), length, state.pv_index_buffer, 0);
+	const auto clamped = EmitGlsl<GLSLstd450UMin, IR::Type::U32>(
+	    state, word, U(state, spv::OpISub, length, C(state, 1)));
+	const auto pointer = state.builder.AllocateId();
+	state.builder.AddFunction(spv::OpAccessChain,
+	                          TypePointer(state, spv::StorageClassStorageBuffer, TypeU32(state)),
+	                          pointer, state.pv_index_buffer, C(state, 0), clamped);
+	const auto raw = state.builder.AllocateId();
+	state.builder.AddFunction(spv::OpLoad, TypeU32(state), raw, pointer);
+	const auto half_shift = U(state, spv::OpShiftLeftLogical,
+	                          U(state, spv::OpBitwiseAnd, element, C(state, 1)), C(state, 4));
+	const auto shifted    = U(state, spv::OpShiftRightLogical, raw,
+	                          Select(state, TypeU32(state), index32, C(state, 0), half_shift));
+	return U(state, spv::OpBitwiseAnd, shifted,
+	         Select(state, TypeU32(state), index32, C(state, 0xffffffffu), C(state, 0xffffu)));
+}
+
+} // namespace
+
+void DefinePvStore(EmitterState& state) {
+	const bool vertex = IsVertex(state);
+	const auto uvec4  = TypeU32Vector(state, 4);
+	const auto array  = state.builder.DecoratedType(
+	    spv::OpTypeRuntimeArray, {{spv::OpDecorate, {spv::DecorationArrayStride, 16}}}, uvec4);
+	const auto block =
+	    state.builder.DecoratedType(spv::OpTypeStruct,
+	                                {{spv::OpMemberDecorate, {0, spv::DecorationOffset, 0}},
+	                                 {spv::OpDecorate, {spv::DecorationBlock}}},
+	                                array);
+	state.pv_cap_buffer = state.builder.DefineGlobalVariable(
+	    TypePointer(state, spv::StorageClassStorageBuffer, block), spv::StorageClassStorageBuffer);
+	state.builder.AddName(state.pv_cap_buffer, "pv_cap");
+	state.builder.AddAnnotation(spv::OpDecorate, state.pv_cap_buffer, spv::DecorationDescriptorSet,
+	                            1);
+	state.builder.AddAnnotation(spv::OpDecorate, state.pv_cap_buffer, spv::DecorationBinding, 0);
+	if (!vertex)
+		state.builder.AddAnnotation(spv::OpDecorate, state.pv_cap_buffer,
+		                            spv::DecorationNonWritable);
+	if (state.pv_store->coherent) {
+		state.builder.AddAnnotation(spv::OpDecorate, state.pv_cap_buffer, spv::DecorationCoherent);
+	}
+	if (!vertex) {
+		const auto words = state.builder.DecoratedType(
+		    spv::OpTypeRuntimeArray, {{spv::OpDecorate, {spv::DecorationArrayStride, 4}}},
+		    TypeU32(state));
+		const auto index_block =
+		    state.builder.DecoratedType(spv::OpTypeStruct,
+		                                {{spv::OpMemberDecorate, {0, spv::DecorationOffset, 0}},
+		                                 {spv::OpDecorate, {spv::DecorationBlock}}},
+		                                words);
+		state.pv_index_buffer = state.builder.DefineGlobalVariable(
+		    TypePointer(state, spv::StorageClassStorageBuffer, index_block),
+		    spv::StorageClassStorageBuffer);
+		state.builder.AddName(state.pv_index_buffer, "pv_indices");
+		state.builder.AddAnnotation(spv::OpDecorate, state.pv_index_buffer,
+		                            spv::DecorationDescriptorSet, 1);
+		state.builder.AddAnnotation(spv::OpDecorate, state.pv_index_buffer, spv::DecorationBinding,
+		                            1);
+		state.builder.AddAnnotation(spv::OpDecorate, state.pv_index_buffer,
+		                            spv::DecorationNonWritable);
+		// PrimitiveId in a fragment shader needs the Geometry capability.
+		state.builder.RequireCapability(spv::CapabilityGeometry);

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

set -u
printf '%s\n' '--- diff stat and relevant diff ---'
git diff --stat dad900c61d6c7ff8aefc9e666ca7c3de4bbf4176 d305947c013b60e410a52a05b54feb3b405b3aa0 -- \
  src/graphics/shader/recompiler/backend/spirv/spirvEmitterPvStore.cpp \
  src/graphics/shader/recompiler/backend/spirv/spirvEmitterModule.cpp \
  src/graphics \
  | sed -n '1,160p'
git diff --unified=35 dad900c61d6c7ff8aefc9e666ca7c3de4bbf4176 d305947c013b60e410a52a05b54feb3b405b3aa0 -- \
  src/graphics/shader/recompiler/backend/spirv/spirvEmitterPvStore.cpp \
  src/graphics/shader/recompiler/backend/spirv/spirvEmitterModule.cpp \
  | sed -n '1,1000p'

printf '%s\n' '--- relevant symbols ---'
rg -n -F --glob '*.{cpp,h,hpp}' -- \
  'CapabilityGeometry' src/graphics src | sed -n '1,120p'
rg -n -F --glob '*.{cpp,h,hpp}' -- \
  'CapabilityTessellation' src/graphics src | sed -n '1,120p'
rg -n -F --glob '*.{cpp,h,hpp}' -- \
  'fragmentShaderBarycentric' src/graphics src | sed -n '1,240p'
rg -n -F --glob '*.{cpp,h,hpp}' -- \
  'VK_KHR_fragment_shader_barycentric' src/graphics src | sed -n '1,160p'
rg -n -F --glob '*.{cpp,h,hpp}' -- \
  'VulkanCreateDevice' src | sed -n '1,80p'
rg -n -F --glob '*.{cpp,h,hpp}' -- \
  'VulkanDebugMessengerCallback' src | sed -n '1,80p'

Repository: KytyPS5/KytyPS5

Length of output: 33444


🏁 Script executed:

set -u
printf '%s\n' '--- Vulkan device feature and validation blocks ---'
sed -n '220,285p' src/graphics/presentation/window/vulkanWindow.cpp
sed -n '390,475p' src/graphics/presentation/window/vulkanWindow.cpp
sed -n '575,635p' src/graphics/presentation/window/vulkanWindow.cpp
sed -n '750,790p' src/graphics/presentation/window/vulkanWindow.cpp

printf '%s\n' '--- SPIR-V capability and extension emission ---'
rg -n -F --glob '*.cpp' --glob '*.h' --glob '*.hpp' -- \
  'CapabilityFragmentBarycentricKHR' src/graphics/shader/recompiler src/graphics
rg -n -F --glob '*.cpp' --glob '*.h' --glob '*.hpp' -- \
  'SPV_KHR_fragment_shader_barycentric' src/graphics/shader/recompiler src/graphics
rg -n -F --glob '*.cpp' --glob '*.h' --glob '*.hpp' -- \
  'BuiltInBaryCoordKHR' src/graphics/shader/recompiler src/graphics
rg -n -F --glob '*.cpp' --glob '*.h' --glob '*.hpp' -- \
  'InitializePvStore' src/graphics/shader/recompiler
rg -n -F --glob '*.cpp' --glob '*.h' --glob '*.hpp' -- \
  'pv_store' src/graphics/shader/recompiler/backend/spirv | sed -n '1,240p'

printf '%s\n' '--- relevant emitter module tail ---'
sed -n '690,830p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterModule.cpp
printf '%s\n' '--- relevant emitter program/flow wiring ---'
sed -n '1,220p' src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.cpp
sed -n '1,260p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterFlow.cpp

Repository: KytyPS5/KytyPS5

Length of output: 42151


🏁 Script executed:

set -u
printf '%s\n' '--- exact barycentric capability condition ---'
sed -n '790,830p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterModule.cpp
printf '%s\n' '--- exact VS-store emitter setup and initialization call ---'
sed -n '190,245p' src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.cpp
sed -n '700,755p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp
printf '%s\n' '--- input metadata declarations and barycentric construction references ---'
rg -n -F --glob '*.{cpp,h,hpp}' -- \
  'BaryCoordSmooth' src/graphics/shader/recompiler src/graphics | sed -n '1,180p'
rg -n -F --glob '*.{cpp,h,hpp}' -- \
  'per_vertex' src/graphics/shader/recompiler | sed -n '1,220p'

Repository: KytyPS5/KytyPS5

Length of output: 16555


🌐 Web query:

official Vulkan specification PrimitiveId fragment shader Geometry capability tessellation capability VK_KHR_fragment_shader_barycentric feature

💡 Result:

**Short answer:** `PrimitiveId` and `VK_KHR_fragment_shader_barycentric` are separate Vulkan features.

- A fragment shader reading `PrimitiveId` must declare the SPIR-V `Geometry` **or** `Tessellation` capability (mesh-shader capabilities also qualify in newer specs). This is a SPIR-V requirement; it **doesn’t by itself mean** your graphics pipeline must contain a geometry or tessellation shader. The fragment-stage value is the geometry/mesh shader’s written ID if that stage is present, otherwise the value that would have reached geometry shading. If a geometry shader *is* present, it must write `PrimitiveId` on every path when the fragment shader reads it. ([docs.vulkan.org](https://docs.vulkan.org/refpages/latest/refpages/source/PrimitiveId.html?utm_source=openai))
- `VK_KHR_fragment_shader_barycentric` provides barycentric coordinates and per-vertex fragment inputs—not `PrimitiveId`. Its `fragmentShaderBarycentric` feature must be queried and enabled to use those capabilities. ([docs.vulkan.org](https://docs.vulkan.org/refpages/latest/refpages/source/VK_KHR_fragment_shader_barycentric.html?utm_source=openai))

So, using barycentrics does **not** satisfy the `PrimitiveId` capability requirement; using `PrimitiveId` does **not** require the barycentric extension. These references are to the current Vulkan specification; exact SPIR-V capability details can vary with the spec version. ([docs.vulkan.org](https://docs.vulkan.org/refpages/latest/refpages/source/PrimitiveId.html?utm_source=openai))

Citations:

- 1: https://docs.vulkan.org/refpages/latest/refpages/source/PrimitiveId.html?utm_source=openai
- 2: https://docs.vulkan.org/refpages/latest/refpages/source/VK_KHR_fragment_shader_barycentric.html?utm_source=openai
- 3: https://docs.vulkan.org/refpages/latest/refpages/source/PrimitiveId.html?utm_source=openai

🏁 Script executed:

set -u
printf '%s\n' '--- precise evidence ranges ---'
nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterPvStore.cpp | sed -n '145,165p'
nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterModule.cpp | sed -n '495,545p'
nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterModule.cpp | sed -n '805,825p'
nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterFlow.cpp | sed -n '160,210p'
nl -ba src/graphics/presentation/window/vulkanWindow.cpp | sed -n '600,625p'
nl -ba src/graphics/presentation/window/vulkanWindow.cpp | sed -n '250,272p'
nl -ba src/graphics/shader/recompiler/ir/passes/ShaderInfoCollection.cpp | sed -n '105,128p'

Repository: KytyPS5/KytyPS5

Length of output: 12178


Use only capabilities enabled by the device.

The VS-store fragment shader declares CapabilityGeometry for PrimitiveId, but the device enables tessellationShader, not geometryShader. Vulkan permits PrimitiveId with the Tessellation capability. Use that capability instead.

Suggested fix for the PrimitiveId capability
--- "a/src/graphics/shader/recompiler/backend/spirv/spirvEmitterPvStore.cpp"
+++ "b/src/graphics/shader/recompiler/backend/spirv/spirvEmitterPvStore.cpp"
@@ -153,8 +153,8 @@
 		                            1);
 		state.builder.AddAnnotation(spv::OpDecorate, state.pv_index_buffer,
 		                            spv::DecorationNonWritable);
-		// PrimitiveId in a fragment shader needs the Geometry capability.
-		state.builder.RequireCapability(spv::CapabilityGeometry);
+		// PrimitiveId in a fragment shader is valid with the enabled tessellation capability.
+		state.builder.RequireCapability(spv::CapabilityTessellation);
 	}
 	// The instance index travels VS -> PS as a flat varying (the PS has no instance builtin).
 	state.pv_instance_variable = DefineInterfaceVariable(

The VS-store path also still requires fragment barycentrics. DefineInputs keeps per-vertex Parameter entries in state.inputs, and DefineModule uses those entries to require CapabilityFragmentBarycentricKHR and SPV_KHR_fragment_shader_barycentric. Non-flat per-vertex interpolation then reads BaryCoordSmooth or BaryCoordNoPerspective.

On Apple, VulkanCreateDevice does not chain or enable fragmentShaderBarycentric. Therefore, either enable VK_KHR_fragment_shader_barycentric and its feature when MoltenVK reports support, or remove this dependency before using VS-store on devices that do not report it. Otherwise, the emitted shader requires an unavailable feature.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

		// PrimitiveId in a fragment shader is valid with the enabled tessellation capability.
		state.builder.RequireCapability(spv::CapabilityTessellation);
**@⁠coderabbitai[bot]** on GitHub · 2026-10-12 07:03 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1441#discussion_r4245412084) · edited 2026-10-12 10:18 UTC On `src/graphics/shader/recompiler/backend/spirv/spirvEmitterPvStore.cpp` line 157 (outdated): ```diff @@ -0,0 +1,217 @@ +#include "graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h" + +// VS-store: the guest VS stores its PerVertex parameters to cap[record * stride + +// slot]; the guest PS reads the three corners of its primitive back. The record arithmetic mirrors +// graphics/host_gpu/renderer/perVertexVsStore.h (PvVsStoreVertexRecord / PvVsStoreCornerRecord). + +namespace Libs::Graphics::ShaderRecompiler::Spirv::Emitter { + +namespace { + +bool IsVertex(const EmitterState& state) { + return state.pv_store->role == PvStoreInfo::Role::Vertex; +} + +uint32_t U(EmitterState& state, spv::Op op, uint32_t lhs, uint32_t rhs) { + return Binary(state, op, TypeU32(state), lhs, rhs); +} + +uint32_t C(EmitterState& state, uint32_t value) { + return ConstantU32(state, value); +} + +uint32_t Push(EmitterState& state, uint32_t dword) { + const auto pointer = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpAccessChain, TypePushConstantElementPointer(state), pointer, + state.push_constant_variable, C(state, 1), C(state, dword)); + const auto value = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpLoad, TypeU32(state), value, pointer); + return value; +} + +uint32_t LoadSigned(EmitterState& state, uint32_t variable) { + const auto value = state.builder.AllocateId(); + const auto bits = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpLoad, TypeI32(state), value, variable); + state.builder.AddFunction(spv::OpBitcast, TypeU32(state), bits, value); + return bits; +} + +// base + (instance - first_instance) * span + (vertex - first) +uint32_t Record(EmitterState& state, uint32_t instance, uint32_t vertex) { + const auto relative_instance = + U(state, spv::OpISub, instance, Push(state, kPvPushFirstInstance)); + const auto instance_part = U(state, spv::OpIMul, relative_instance, Push(state, kPvPushSpan)); + const auto relative_vertex = U(state, spv::OpISub, vertex, Push(state, kPvPushFirst)); + return U(state, spv::OpIAdd, U(state, spv::OpIAdd, Push(state, kPvPushBase), instance_part), + relative_vertex); +} + +uint32_t CapComponentPointer(EmitterState& state, uint32_t record, uint32_t slot, + uint32_t component) { + // stride 0 = the stride comes with the draw (the two variants are emitted independently). + constexpr uint32_t kStrideDword = kPvPushStride; + const auto stride = state.pv_store->record_stride_vec4 != 0 + ? C(state, state.pv_store->record_stride_vec4) + : Push(state, kStrideDword); + const auto element = + U(state, spv::OpIAdd, U(state, spv::OpIMul, record, stride), C(state, slot)); + const auto pointer = state.builder.AllocateId(); + if (component == UINT32_MAX) { + state.builder.AddFunction( + spv::OpAccessChain, + TypePointer(state, spv::StorageClassStorageBuffer, TypeU32Vector(state, 4)), pointer, + state.pv_cap_buffer, C(state, 0), element); + } else { + state.builder.AddFunction( + spv::OpAccessChain, TypePointer(state, spv::StorageClassStorageBuffer, TypeU32(state)), + pointer, state.pv_cap_buffer, C(state, 0), element, C(state, component)); + } + return pointer; +} + +uint32_t SlotOf(const EmitterState& state, uint32_t host_location) { + if (state.pv_store->record_stride_vec4 == 0) { + // Dynamic stride: slot == host location. Location 31 carries the instance index: a stage + // that uses it is still emitted (the location is recorded) and ClassifyPvVsStoreInterface + // rejects the pair. + EXIT_IF(host_location > kPvVsStoreInstanceLocation); + if (state.pv_store->location_mask != nullptr) + *state.pv_store->location_mask |= 1u << host_location; + return host_location; + } + const auto slot = state.pv_store->parameter_slots.find(host_location); + EXIT_IF(slot == state.pv_store->parameter_slots.end() || + slot->second >= state.pv_store->record_stride_vec4); + return slot->second; +} + +// Index value of element `element` (16- or 32-bit buffer, chosen by the push flag). +uint32_t FetchIndex(EmitterState& state, uint32_t element) { + const auto index32 = + Binary(state, spv::OpINotEqual, TypeBool(state), Push(state, kPvPushIndex32), C(state, 0)); + const auto word = Select(state, TypeU32(state), index32, element, + U(state, spv::OpShiftRightLogical, element, C(state, 1))); + const auto length = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpArrayLength, TypeU32(state), length, state.pv_index_buffer, 0); + const auto clamped = EmitGlsl<GLSLstd450UMin, IR::Type::U32>( + state, word, U(state, spv::OpISub, length, C(state, 1))); + const auto pointer = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpAccessChain, + TypePointer(state, spv::StorageClassStorageBuffer, TypeU32(state)), + pointer, state.pv_index_buffer, C(state, 0), clamped); + const auto raw = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpLoad, TypeU32(state), raw, pointer); + const auto half_shift = U(state, spv::OpShiftLeftLogical, + U(state, spv::OpBitwiseAnd, element, C(state, 1)), C(state, 4)); + const auto shifted = U(state, spv::OpShiftRightLogical, raw, + Select(state, TypeU32(state), index32, C(state, 0), half_shift)); + return U(state, spv::OpBitwiseAnd, shifted, + Select(state, TypeU32(state), index32, C(state, 0xffffffffu), C(state, 0xffffu))); +} + +} // namespace + +void DefinePvStore(EmitterState& state) { + const bool vertex = IsVertex(state); + const auto uvec4 = TypeU32Vector(state, 4); + const auto array = state.builder.DecoratedType( + spv::OpTypeRuntimeArray, {{spv::OpDecorate, {spv::DecorationArrayStride, 16}}}, uvec4); + const auto block = + state.builder.DecoratedType(spv::OpTypeStruct, + {{spv::OpMemberDecorate, {0, spv::DecorationOffset, 0}}, + {spv::OpDecorate, {spv::DecorationBlock}}}, + array); + state.pv_cap_buffer = state.builder.DefineGlobalVariable( + TypePointer(state, spv::StorageClassStorageBuffer, block), spv::StorageClassStorageBuffer); + state.builder.AddName(state.pv_cap_buffer, "pv_cap"); + state.builder.AddAnnotation(spv::OpDecorate, state.pv_cap_buffer, spv::DecorationDescriptorSet, + 1); + state.builder.AddAnnotation(spv::OpDecorate, state.pv_cap_buffer, spv::DecorationBinding, 0); + if (!vertex) + state.builder.AddAnnotation(spv::OpDecorate, state.pv_cap_buffer, + spv::DecorationNonWritable); + if (state.pv_store->coherent) { + state.builder.AddAnnotation(spv::OpDecorate, state.pv_cap_buffer, spv::DecorationCoherent); + } + if (!vertex) { + const auto words = state.builder.DecoratedType( + spv::OpTypeRuntimeArray, {{spv::OpDecorate, {spv::DecorationArrayStride, 4}}}, + TypeU32(state)); + const auto index_block = + state.builder.DecoratedType(spv::OpTypeStruct, + {{spv::OpMemberDecorate, {0, spv::DecorationOffset, 0}}, + {spv::OpDecorate, {spv::DecorationBlock}}}, + words); + state.pv_index_buffer = state.builder.DefineGlobalVariable( + TypePointer(state, spv::StorageClassStorageBuffer, index_block), + spv::StorageClassStorageBuffer); + state.builder.AddName(state.pv_index_buffer, "pv_indices"); + state.builder.AddAnnotation(spv::OpDecorate, state.pv_index_buffer, + spv::DecorationDescriptorSet, 1); + state.builder.AddAnnotation(spv::OpDecorate, state.pv_index_buffer, spv::DecorationBinding, + 1); + state.builder.AddAnnotation(spv::OpDecorate, state.pv_index_buffer, + spv::DecorationNonWritable); + // PrimitiveId in a fragment shader needs the Geometry capability. + state.builder.RequireCapability(spv::CapabilityGeometry); ``` **🩺 Stability & Availability** | **🟠 Major** | **⚡ Quick win** <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash set -u printf '%s\n' '--- diff stat and relevant diff ---' git diff --stat dad900c61d6c7ff8aefc9e666ca7c3de4bbf4176 d305947c013b60e410a52a05b54feb3b405b3aa0 -- \ src/graphics/shader/recompiler/backend/spirv/spirvEmitterPvStore.cpp \ src/graphics/shader/recompiler/backend/spirv/spirvEmitterModule.cpp \ src/graphics \ | sed -n '1,160p' git diff --unified=35 dad900c61d6c7ff8aefc9e666ca7c3de4bbf4176 d305947c013b60e410a52a05b54feb3b405b3aa0 -- \ src/graphics/shader/recompiler/backend/spirv/spirvEmitterPvStore.cpp \ src/graphics/shader/recompiler/backend/spirv/spirvEmitterModule.cpp \ | sed -n '1,1000p' printf '%s\n' '--- relevant symbols ---' rg -n -F --glob '*.{cpp,h,hpp}' -- \ 'CapabilityGeometry' src/graphics src | sed -n '1,120p' rg -n -F --glob '*.{cpp,h,hpp}' -- \ 'CapabilityTessellation' src/graphics src | sed -n '1,120p' rg -n -F --glob '*.{cpp,h,hpp}' -- \ 'fragmentShaderBarycentric' src/graphics src | sed -n '1,240p' rg -n -F --glob '*.{cpp,h,hpp}' -- \ 'VK_KHR_fragment_shader_barycentric' src/graphics src | sed -n '1,160p' rg -n -F --glob '*.{cpp,h,hpp}' -- \ 'VulkanCreateDevice' src | sed -n '1,80p' rg -n -F --glob '*.{cpp,h,hpp}' -- \ 'VulkanDebugMessengerCallback' src | sed -n '1,80p' ``` Repository: KytyPS5/KytyPS5 Length of output: 33444 --- 🏁 Script executed: ```bash set -u printf '%s\n' '--- Vulkan device feature and validation blocks ---' sed -n '220,285p' src/graphics/presentation/window/vulkanWindow.cpp sed -n '390,475p' src/graphics/presentation/window/vulkanWindow.cpp sed -n '575,635p' src/graphics/presentation/window/vulkanWindow.cpp sed -n '750,790p' src/graphics/presentation/window/vulkanWindow.cpp printf '%s\n' '--- SPIR-V capability and extension emission ---' rg -n -F --glob '*.cpp' --glob '*.h' --glob '*.hpp' -- \ 'CapabilityFragmentBarycentricKHR' src/graphics/shader/recompiler src/graphics rg -n -F --glob '*.cpp' --glob '*.h' --glob '*.hpp' -- \ 'SPV_KHR_fragment_shader_barycentric' src/graphics/shader/recompiler src/graphics rg -n -F --glob '*.cpp' --glob '*.h' --glob '*.hpp' -- \ 'BuiltInBaryCoordKHR' src/graphics/shader/recompiler src/graphics rg -n -F --glob '*.cpp' --glob '*.h' --glob '*.hpp' -- \ 'InitializePvStore' src/graphics/shader/recompiler rg -n -F --glob '*.cpp' --glob '*.h' --glob '*.hpp' -- \ 'pv_store' src/graphics/shader/recompiler/backend/spirv | sed -n '1,240p' printf '%s\n' '--- relevant emitter module tail ---' sed -n '690,830p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterModule.cpp printf '%s\n' '--- relevant emitter program/flow wiring ---' sed -n '1,220p' src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.cpp sed -n '1,260p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterFlow.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 42151 --- 🏁 Script executed: ```bash set -u printf '%s\n' '--- exact barycentric capability condition ---' sed -n '790,830p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterModule.cpp printf '%s\n' '--- exact VS-store emitter setup and initialization call ---' sed -n '190,245p' src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.cpp sed -n '700,755p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp printf '%s\n' '--- input metadata declarations and barycentric construction references ---' rg -n -F --glob '*.{cpp,h,hpp}' -- \ 'BaryCoordSmooth' src/graphics/shader/recompiler src/graphics | sed -n '1,180p' rg -n -F --glob '*.{cpp,h,hpp}' -- \ 'per_vertex' src/graphics/shader/recompiler | sed -n '1,220p' ``` Repository: KytyPS5/KytyPS5 Length of output: 16555 --- 🌐 Web query: `official Vulkan specification PrimitiveId fragment shader Geometry capability tessellation capability VK_KHR_fragment_shader_barycentric feature` 💡 Result: ``` **Short answer:** `PrimitiveId` and `VK_KHR_fragment_shader_barycentric` are separate Vulkan features. - A fragment shader reading `PrimitiveId` must declare the SPIR-V `Geometry` **or** `Tessellation` capability (mesh-shader capabilities also qualify in newer specs). This is a SPIR-V requirement; it **doesn’t by itself mean** your graphics pipeline must contain a geometry or tessellation shader. The fragment-stage value is the geometry/mesh shader’s written ID if that stage is present, otherwise the value that would have reached geometry shading. If a geometry shader *is* present, it must write `PrimitiveId` on every path when the fragment shader reads it. ([docs.vulkan.org](https://docs.vulkan.org/refpages/latest/refpages/source/PrimitiveId.html?utm_source=openai)) - `VK_KHR_fragment_shader_barycentric` provides barycentric coordinates and per-vertex fragment inputs—not `PrimitiveId`. Its `fragmentShaderBarycentric` feature must be queried and enabled to use those capabilities. ([docs.vulkan.org](https://docs.vulkan.org/refpages/latest/refpages/source/VK_KHR_fragment_shader_barycentric.html?utm_source=openai)) So, using barycentrics does **not** satisfy the `PrimitiveId` capability requirement; using `PrimitiveId` does **not** require the barycentric extension. These references are to the current Vulkan specification; exact SPIR-V capability details can vary with the spec version. ([docs.vulkan.org](https://docs.vulkan.org/refpages/latest/refpages/source/PrimitiveId.html?utm_source=openai)) Citations: - 1: https://docs.vulkan.org/refpages/latest/refpages/source/PrimitiveId.html?utm_source=openai - 2: https://docs.vulkan.org/refpages/latest/refpages/source/VK_KHR_fragment_shader_barycentric.html?utm_source=openai - 3: https://docs.vulkan.org/refpages/latest/refpages/source/PrimitiveId.html?utm_source=openai ``` --- 🏁 Script executed: ```bash set -u printf '%s\n' '--- precise evidence ranges ---' nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterPvStore.cpp | sed -n '145,165p' nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterModule.cpp | sed -n '495,545p' nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterModule.cpp | sed -n '805,825p' nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterFlow.cpp | sed -n '160,210p' nl -ba src/graphics/presentation/window/vulkanWindow.cpp | sed -n '600,625p' nl -ba src/graphics/presentation/window/vulkanWindow.cpp | sed -n '250,272p' nl -ba src/graphics/shader/recompiler/ir/passes/ShaderInfoCollection.cpp | sed -n '105,128p' ``` Repository: KytyPS5/KytyPS5 Length of output: 12178 --- </details> **Use only capabilities enabled by the device.** The VS-store fragment shader declares `CapabilityGeometry` for `PrimitiveId`, but the device enables `tessellationShader`, not `geometryShader`. Vulkan permits `PrimitiveId` with the `Tessellation` capability. Use that capability instead. <details> <summary>Suggested fix for the PrimitiveId capability</summary> ```diff --- "a/src/graphics/shader/recompiler/backend/spirv/spirvEmitterPvStore.cpp" +++ "b/src/graphics/shader/recompiler/backend/spirv/spirvEmitterPvStore.cpp" @@ -153,8 +153,8 @@ 1); state.builder.AddAnnotation(spv::OpDecorate, state.pv_index_buffer, spv::DecorationNonWritable); - // PrimitiveId in a fragment shader needs the Geometry capability. - state.builder.RequireCapability(spv::CapabilityGeometry); + // PrimitiveId in a fragment shader is valid with the enabled tessellation capability. + state.builder.RequireCapability(spv::CapabilityTessellation); } // The instance index travels VS -> PS as a flat varying (the PS has no instance builtin). state.pv_instance_variable = DefineInterfaceVariable( ``` </details> The VS-store path also still requires fragment barycentrics. `DefineInputs` keeps per-vertex `Parameter` entries in `state.inputs`, and `DefineModule` uses those entries to require `CapabilityFragmentBarycentricKHR` and `SPV_KHR_fragment_shader_barycentric`. Non-flat per-vertex interpolation then reads `BaryCoordSmooth` or `BaryCoordNoPerspective`. On Apple, `VulkanCreateDevice` does not chain or enable `fragmentShaderBarycentric`. Therefore, either enable `VK_KHR_fragment_shader_barycentric` and its feature when MoltenVK reports support, or remove this dependency before using VS-store on devices that do not report it. Otherwise, the emitted shader requires an unavailable feature. <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion // PrimitiveId in a fragment shader is valid with the enabled tessellation capability. state.builder.RequireCapability(spv::CapabilityTessellation); ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:fb92f634f5d75ab27e7d5901 --> <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-12 07:03 UTC · original · reviewed

Actionable comments posted: 2

🧹 Nitpick comments (1)
tests/PerVertexVsStoreGpuTests.cpp (1)

551-553: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Increase the descriptor pool size, or free the descriptor sets, before stress cases are added.

The loop allocates one descriptor set for each case and never frees it. The pool allows 32 sets. The current run has at most 9 cases, so it does not fail now. If someone adds more than 32 cases, vkAllocateDescriptorSets fails. The fix is one line: reset the pool or size it from cases.size().


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: e3aa901a-43e9-49f1-927d-d65e10686088
📥 Commits

Reviewing files that changed from the base of the PR and between dad900c61d and d305947c013b60e410a52a05b54feb3b405b3aa0.

📒 Files selected for processing (22)
  • CMakeLists.txt
  • src/graphics/host_gpu/renderer/perVertexVsStore.h
  • src/graphics/host_gpu/renderer/perVertexVsStoreRuntime.cpp
  • src/graphics/host_gpu/renderer/perVertexVsStoreRuntime.h
  • src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp
  • src/graphics/host_gpu/renderer/pipeline/pipelineCache.h
  • src/graphics/host_gpu/renderer/pipeline/shaders.cpp
  • src/graphics/host_gpu/renderer/render.h
  • src/graphics/host_gpu/renderer/renderDraw.cpp
  • src/graphics/presentation/window/vulkanWindow.cpp
  • src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.cpp
  • src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.h
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterFlow.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterModule.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterPvStore.cpp
  • tests/PerVertexVsStoreGpu.cmake
  • tests/PerVertexVsStoreGpuTests.cpp
  • tests/PerVertexVsStoreMutants.cmake
  • tests/PerVertexVsStoreTests.cpp
  • tests/shaderCfgTests.cpp

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 5 remain after this review.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-12 07:03 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1441#pullrequestreview-5487409585) · **reviewed** **Actionable comments posted: 2** <details> <summary>🧹 Nitpick comments (1)</summary><blockquote> <details> <summary>tests/PerVertexVsStoreGpuTests.cpp (1)</summary><blockquote> `551-553`: **📐 Maintainability & Code Quality** | **🔵 Trivial** | **💤 Low value** **Increase the descriptor pool size, or free the descriptor sets, before stress cases are added.** The loop allocates one descriptor set for each case and never frees it. The pool allows 32 sets. The current run has at most 9 cases, so it does not fail now. If someone adds more than 32 cases, `vkAllocateDescriptorSets` fails. The fix is one line: reset the pool or size it from `cases.size()`. <!-- cr-comment:v1:9c714e7036673c18f54199a5 --> </blockquote></details> </blockquote></details> --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> - **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `e3aa901a-43e9-49f1-927d-d65e10686088` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between dad900c61d6c7ff8aefc9e666ca7c3de4bbf4176 and d305947c013b60e410a52a05b54feb3b405b3aa0. </details> <details> <summary>📒 Files selected for processing (22)</summary> * `CMakeLists.txt` * `src/graphics/host_gpu/renderer/perVertexVsStore.h` * `src/graphics/host_gpu/renderer/perVertexVsStoreRuntime.cpp` * `src/graphics/host_gpu/renderer/perVertexVsStoreRuntime.h` * `src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp` * `src/graphics/host_gpu/renderer/pipeline/pipelineCache.h` * `src/graphics/host_gpu/renderer/pipeline/shaders.cpp` * `src/graphics/host_gpu/renderer/render.h` * `src/graphics/host_gpu/renderer/renderDraw.cpp` * `src/graphics/presentation/window/vulkanWindow.cpp` * `src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.cpp` * `src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.h` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterFlow.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterModule.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterPvStore.cpp` * `tests/PerVertexVsStoreGpu.cmake` * `tests/PerVertexVsStoreGpuTests.cpp` * `tests/PerVertexVsStoreMutants.cmake` * `tests/PerVertexVsStoreTests.cpp` * `tests/shaderCfgTests.cpp` </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 5 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=8e4d2a91-b464-46f5-9ae5-4193a3165a8e attempt=ff9a911d-c843-417c-805b-db1c969e1c05 batch=1/1 -->
@ -0,0 +179,4 @@
// Distinct pipeline-cache identity from the PerVertexKHR variants of the same programs.
value.graphics.vertex[0].id |= 1ull << 61;
value.graphics.pixel.id |= 1ull << 61;
value.graphics.pv_store_layout = PvVsStoreSetLayout(graphics);
Author
Owner

@⁠wuboo on GitHub · 2026-10-12 10:09 UTC · original

Valid, fixed in 82f328b7. New ShutdownPvVsStore(vk::Device) destroys the two modules of every accepted pair and the set layout, clears s_pairs/s_shaders; WindowContext::~WindowContext calls it after waitIdle and after the render context (pipelines, pipeline layouts) is gone, right before the device is destroyed. Builds and the full ctest is unchanged; no CPU test is possible because the objects are Vulkan handles, and I did not run it under the validation layer.

**@⁠wuboo** on GitHub · 2026-10-12 10:09 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1441#discussion_r4246833536) Valid, fixed in 82f328b7. New `ShutdownPvVsStore(vk::Device)` destroys the two modules of every accepted pair and the set layout, clears `s_pairs`/`s_shaders`; `WindowContext::~WindowContext` calls it after `waitIdle` and after the render context (pipelines, pipeline layouts) is gone, right before the device is destroyed. Builds and the full ctest is unchanged; no CPU test is possible because the objects are Vulkan handles, and I did not run it under the validation layer.
Author
Owner

@⁠wuboo on GitHub · 2026-10-12 10:09 UTC · original
On src/graphics/shader/recompiler/backend/spirv/spirvEmitterPvStore.cpp line 157 (outdated):

@@ -0,0 +1,217 @@
+#include "graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h"
+
+// VS-store: the guest VS stores its PerVertex parameters to cap[record * stride +
+// slot]; the guest PS reads the three corners of its primitive back. The record arithmetic mirrors
+// graphics/host_gpu/renderer/perVertexVsStore.h (PvVsStoreVertexRecord / PvVsStoreCornerRecord).
+
+namespace Libs::Graphics::ShaderRecompiler::Spirv::Emitter {
+
+namespace {
+
+bool IsVertex(const EmitterState& state) {
+	return state.pv_store->role == PvStoreInfo::Role::Vertex;
+}
+
+uint32_t U(EmitterState& state, spv::Op op, uint32_t lhs, uint32_t rhs) {
+	return Binary(state, op, TypeU32(state), lhs, rhs);
+}
+
+uint32_t C(EmitterState& state, uint32_t value) {
+	return ConstantU32(state, value);
+}
+
+uint32_t Push(EmitterState& state, uint32_t dword) {
+	const auto pointer = state.builder.AllocateId();
+	state.builder.AddFunction(spv::OpAccessChain, TypePushConstantElementPointer(state), pointer,
+	                          state.push_constant_variable, C(state, 1), C(state, dword));
+	const auto value = state.builder.AllocateId();
+	state.builder.AddFunction(spv::OpLoad, TypeU32(state), value, pointer);
+	return value;
+}
+
+uint32_t LoadSigned(EmitterState& state, uint32_t variable) {
+	const auto value = state.builder.AllocateId();
+	const auto bits  = state.builder.AllocateId();
+	state.builder.AddFunction(spv::OpLoad, TypeI32(state), value, variable);
+	state.builder.AddFunction(spv::OpBitcast, TypeU32(state), bits, value);
+	return bits;
+}
+
+// base + (instance - first_instance) * span + (vertex - first)
+uint32_t Record(EmitterState& state, uint32_t instance, uint32_t vertex) {
+	const auto relative_instance =
+	    U(state, spv::OpISub, instance, Push(state, kPvPushFirstInstance));
+	const auto instance_part   = U(state, spv::OpIMul, relative_instance, Push(state, kPvPushSpan));
+	const auto relative_vertex = U(state, spv::OpISub, vertex, Push(state, kPvPushFirst));
+	return U(state, spv::OpIAdd, U(state, spv::OpIAdd, Push(state, kPvPushBase), instance_part),
+	         relative_vertex);
+}
+
+uint32_t CapComponentPointer(EmitterState& state, uint32_t record, uint32_t slot,
+                             uint32_t component) {
+	// stride 0 = the stride comes with the draw (the two variants are emitted independently).
+	constexpr uint32_t kStrideDword = kPvPushStride;
+	const auto         stride       = state.pv_store->record_stride_vec4 != 0
+	                                      ? C(state, state.pv_store->record_stride_vec4)
+	                                      : Push(state, kStrideDword);
+	const auto         element =
+	    U(state, spv::OpIAdd, U(state, spv::OpIMul, record, stride), C(state, slot));
+	const auto pointer = state.builder.AllocateId();
+	if (component == UINT32_MAX) {
+		state.builder.AddFunction(
+		    spv::OpAccessChain,
+		    TypePointer(state, spv::StorageClassStorageBuffer, TypeU32Vector(state, 4)), pointer,
+		    state.pv_cap_buffer, C(state, 0), element);
+	} else {
+		state.builder.AddFunction(
+		    spv::OpAccessChain, TypePointer(state, spv::StorageClassStorageBuffer, TypeU32(state)),
+		    pointer, state.pv_cap_buffer, C(state, 0), element, C(state, component));
+	}
+	return pointer;
+}
+
+uint32_t SlotOf(const EmitterState& state, uint32_t host_location) {
+	if (state.pv_store->record_stride_vec4 == 0) {
+		// Dynamic stride: slot == host location. Location 31 carries the instance index: a stage
+		// that uses it is still emitted (the location is recorded) and ClassifyPvVsStoreInterface
+		// rejects the pair.
+		EXIT_IF(host_location > kPvVsStoreInstanceLocation);
+		if (state.pv_store->location_mask != nullptr)
+			*state.pv_store->location_mask |= 1u << host_location;
+		return host_location;
+	}
+	const auto slot = state.pv_store->parameter_slots.find(host_location);
+	EXIT_IF(slot == state.pv_store->parameter_slots.end() ||
+	        slot->second >= state.pv_store->record_stride_vec4);
+	return slot->second;
+}
+
+// Index value of element `element` (16- or 32-bit buffer, chosen by the push flag).
+uint32_t FetchIndex(EmitterState& state, uint32_t element) {
+	const auto index32 =
+	    Binary(state, spv::OpINotEqual, TypeBool(state), Push(state, kPvPushIndex32), C(state, 0));
+	const auto word   = Select(state, TypeU32(state), index32, element,
+	                           U(state, spv::OpShiftRightLogical, element, C(state, 1)));
+	const auto length = state.builder.AllocateId();
+	state.builder.AddFunction(spv::OpArrayLength, TypeU32(state), length, state.pv_index_buffer, 0);
+	const auto clamped = EmitGlsl<GLSLstd450UMin, IR::Type::U32>(
+	    state, word, U(state, spv::OpISub, length, C(state, 1)));
+	const auto pointer = state.builder.AllocateId();
+	state.builder.AddFunction(spv::OpAccessChain,
+	                          TypePointer(state, spv::StorageClassStorageBuffer, TypeU32(state)),
+	                          pointer, state.pv_index_buffer, C(state, 0), clamped);
+	const auto raw = state.builder.AllocateId();
+	state.builder.AddFunction(spv::OpLoad, TypeU32(state), raw, pointer);
+	const auto half_shift = U(state, spv::OpShiftLeftLogical,
+	                          U(state, spv::OpBitwiseAnd, element, C(state, 1)), C(state, 4));
+	const auto shifted    = U(state, spv::OpShiftRightLogical, raw,
+	                          Select(state, TypeU32(state), index32, C(state, 0), half_shift));
+	return U(state, spv::OpBitwiseAnd, shifted,
+	         Select(state, TypeU32(state), index32, C(state, 0xffffffffu), C(state, 0xffffu)));
+}
+
+} // namespace
+
+void DefinePvStore(EmitterState& state) {
+	const bool vertex = IsVertex(state);
+	const auto uvec4  = TypeU32Vector(state, 4);
+	const auto array  = state.builder.DecoratedType(
+	    spv::OpTypeRuntimeArray, {{spv::OpDecorate, {spv::DecorationArrayStride, 16}}}, uvec4);
+	const auto block =
+	    state.builder.DecoratedType(spv::OpTypeStruct,
+	                                {{spv::OpMemberDecorate, {0, spv::DecorationOffset, 0}},
+	                                 {spv::OpDecorate, {spv::DecorationBlock}}},
+	                                array);
+	state.pv_cap_buffer = state.builder.DefineGlobalVariable(
+	    TypePointer(state, spv::StorageClassStorageBuffer, block), spv::StorageClassStorageBuffer);
+	state.builder.AddName(state.pv_cap_buffer, "pv_cap");
+	state.builder.AddAnnotation(spv::OpDecorate, state.pv_cap_buffer, spv::DecorationDescriptorSet,
+	                            1);
+	state.builder.AddAnnotation(spv::OpDecorate, state.pv_cap_buffer, spv::DecorationBinding, 0);
+	if (!vertex)
+		state.builder.AddAnnotation(spv::OpDecorate, state.pv_cap_buffer,
+		                            spv::DecorationNonWritable);
+	if (state.pv_store->coherent) {
+		state.builder.AddAnnotation(spv::OpDecorate, state.pv_cap_buffer, spv::DecorationCoherent);
+	}
+	if (!vertex) {
+		const auto words = state.builder.DecoratedType(
+		    spv::OpTypeRuntimeArray, {{spv::OpDecorate, {spv::DecorationArrayStride, 4}}},
+		    TypeU32(state));
+		const auto index_block =
+		    state.builder.DecoratedType(spv::OpTypeStruct,
+		                                {{spv::OpMemberDecorate, {0, spv::DecorationOffset, 0}},
+		                                 {spv::OpDecorate, {spv::DecorationBlock}}},
+		                                words);
+		state.pv_index_buffer = state.builder.DefineGlobalVariable(
+		    TypePointer(state, spv::StorageClassStorageBuffer, index_block),
+		    spv::StorageClassStorageBuffer);
+		state.builder.AddName(state.pv_index_buffer, "pv_indices");
+		state.builder.AddAnnotation(spv::OpDecorate, state.pv_index_buffer,
+		                            spv::DecorationDescriptorSet, 1);
+		state.builder.AddAnnotation(spv::OpDecorate, state.pv_index_buffer, spv::DecorationBinding,
+		                            1);
+		state.builder.AddAnnotation(spv::OpDecorate, state.pv_index_buffer,
+		                            spv::DecorationNonWritable);
+		// PrimitiveId in a fragment shader needs the Geometry capability.
+		state.builder.RequireCapability(spv::CapabilityGeometry);

Two parts.n1. Capability: valid. The device enables tessellationShader but not geometryShader, so the VS-store PS now declares Tessellation for PrimitiveId. Fixed in 98aac3b9 (the emitter belongs to #1440, so it is in that branch and reaches this PR by the rebase). Test: shader_cfg checks Capability Tessellation and the absence of Capability Geometry; mutant shader_cfg_pv_vsstore_mutant_capability_geometry fails it.n2. Barycentric feature: the observation is right (the PS still reads BaryCoordKHR, and on macOS fragmentShaderBarycentric is never requested; the VS-store path is meant for exactly that device), but I left it unchanged here. It is not specific to this path: every guest PS with custom interpolation (VINTRP) already gets FragmentBarycentricKHR/BaryCoordKHR from the emitter, which does not condition it on the platform (see the existing shader_cfg checks for custom VINTRP). Requesting the feature on Apple would change device creation for the whole renderer and needs its own GPU/validation run, so it is better as a separate change. I have not run the validation layer on this path.

**@⁠wuboo** on GitHub · 2026-10-12 10:09 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1441#discussion_r4246833759) On `src/graphics/shader/recompiler/backend/spirv/spirvEmitterPvStore.cpp` line 157 (outdated): ```diff @@ -0,0 +1,217 @@ +#include "graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h" + +// VS-store: the guest VS stores its PerVertex parameters to cap[record * stride + +// slot]; the guest PS reads the three corners of its primitive back. The record arithmetic mirrors +// graphics/host_gpu/renderer/perVertexVsStore.h (PvVsStoreVertexRecord / PvVsStoreCornerRecord). + +namespace Libs::Graphics::ShaderRecompiler::Spirv::Emitter { + +namespace { + +bool IsVertex(const EmitterState& state) { + return state.pv_store->role == PvStoreInfo::Role::Vertex; +} + +uint32_t U(EmitterState& state, spv::Op op, uint32_t lhs, uint32_t rhs) { + return Binary(state, op, TypeU32(state), lhs, rhs); +} + +uint32_t C(EmitterState& state, uint32_t value) { + return ConstantU32(state, value); +} + +uint32_t Push(EmitterState& state, uint32_t dword) { + const auto pointer = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpAccessChain, TypePushConstantElementPointer(state), pointer, + state.push_constant_variable, C(state, 1), C(state, dword)); + const auto value = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpLoad, TypeU32(state), value, pointer); + return value; +} + +uint32_t LoadSigned(EmitterState& state, uint32_t variable) { + const auto value = state.builder.AllocateId(); + const auto bits = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpLoad, TypeI32(state), value, variable); + state.builder.AddFunction(spv::OpBitcast, TypeU32(state), bits, value); + return bits; +} + +// base + (instance - first_instance) * span + (vertex - first) +uint32_t Record(EmitterState& state, uint32_t instance, uint32_t vertex) { + const auto relative_instance = + U(state, spv::OpISub, instance, Push(state, kPvPushFirstInstance)); + const auto instance_part = U(state, spv::OpIMul, relative_instance, Push(state, kPvPushSpan)); + const auto relative_vertex = U(state, spv::OpISub, vertex, Push(state, kPvPushFirst)); + return U(state, spv::OpIAdd, U(state, spv::OpIAdd, Push(state, kPvPushBase), instance_part), + relative_vertex); +} + +uint32_t CapComponentPointer(EmitterState& state, uint32_t record, uint32_t slot, + uint32_t component) { + // stride 0 = the stride comes with the draw (the two variants are emitted independently). + constexpr uint32_t kStrideDword = kPvPushStride; + const auto stride = state.pv_store->record_stride_vec4 != 0 + ? C(state, state.pv_store->record_stride_vec4) + : Push(state, kStrideDword); + const auto element = + U(state, spv::OpIAdd, U(state, spv::OpIMul, record, stride), C(state, slot)); + const auto pointer = state.builder.AllocateId(); + if (component == UINT32_MAX) { + state.builder.AddFunction( + spv::OpAccessChain, + TypePointer(state, spv::StorageClassStorageBuffer, TypeU32Vector(state, 4)), pointer, + state.pv_cap_buffer, C(state, 0), element); + } else { + state.builder.AddFunction( + spv::OpAccessChain, TypePointer(state, spv::StorageClassStorageBuffer, TypeU32(state)), + pointer, state.pv_cap_buffer, C(state, 0), element, C(state, component)); + } + return pointer; +} + +uint32_t SlotOf(const EmitterState& state, uint32_t host_location) { + if (state.pv_store->record_stride_vec4 == 0) { + // Dynamic stride: slot == host location. Location 31 carries the instance index: a stage + // that uses it is still emitted (the location is recorded) and ClassifyPvVsStoreInterface + // rejects the pair. + EXIT_IF(host_location > kPvVsStoreInstanceLocation); + if (state.pv_store->location_mask != nullptr) + *state.pv_store->location_mask |= 1u << host_location; + return host_location; + } + const auto slot = state.pv_store->parameter_slots.find(host_location); + EXIT_IF(slot == state.pv_store->parameter_slots.end() || + slot->second >= state.pv_store->record_stride_vec4); + return slot->second; +} + +// Index value of element `element` (16- or 32-bit buffer, chosen by the push flag). +uint32_t FetchIndex(EmitterState& state, uint32_t element) { + const auto index32 = + Binary(state, spv::OpINotEqual, TypeBool(state), Push(state, kPvPushIndex32), C(state, 0)); + const auto word = Select(state, TypeU32(state), index32, element, + U(state, spv::OpShiftRightLogical, element, C(state, 1))); + const auto length = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpArrayLength, TypeU32(state), length, state.pv_index_buffer, 0); + const auto clamped = EmitGlsl<GLSLstd450UMin, IR::Type::U32>( + state, word, U(state, spv::OpISub, length, C(state, 1))); + const auto pointer = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpAccessChain, + TypePointer(state, spv::StorageClassStorageBuffer, TypeU32(state)), + pointer, state.pv_index_buffer, C(state, 0), clamped); + const auto raw = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpLoad, TypeU32(state), raw, pointer); + const auto half_shift = U(state, spv::OpShiftLeftLogical, + U(state, spv::OpBitwiseAnd, element, C(state, 1)), C(state, 4)); + const auto shifted = U(state, spv::OpShiftRightLogical, raw, + Select(state, TypeU32(state), index32, C(state, 0), half_shift)); + return U(state, spv::OpBitwiseAnd, shifted, + Select(state, TypeU32(state), index32, C(state, 0xffffffffu), C(state, 0xffffu))); +} + +} // namespace + +void DefinePvStore(EmitterState& state) { + const bool vertex = IsVertex(state); + const auto uvec4 = TypeU32Vector(state, 4); + const auto array = state.builder.DecoratedType( + spv::OpTypeRuntimeArray, {{spv::OpDecorate, {spv::DecorationArrayStride, 16}}}, uvec4); + const auto block = + state.builder.DecoratedType(spv::OpTypeStruct, + {{spv::OpMemberDecorate, {0, spv::DecorationOffset, 0}}, + {spv::OpDecorate, {spv::DecorationBlock}}}, + array); + state.pv_cap_buffer = state.builder.DefineGlobalVariable( + TypePointer(state, spv::StorageClassStorageBuffer, block), spv::StorageClassStorageBuffer); + state.builder.AddName(state.pv_cap_buffer, "pv_cap"); + state.builder.AddAnnotation(spv::OpDecorate, state.pv_cap_buffer, spv::DecorationDescriptorSet, + 1); + state.builder.AddAnnotation(spv::OpDecorate, state.pv_cap_buffer, spv::DecorationBinding, 0); + if (!vertex) + state.builder.AddAnnotation(spv::OpDecorate, state.pv_cap_buffer, + spv::DecorationNonWritable); + if (state.pv_store->coherent) { + state.builder.AddAnnotation(spv::OpDecorate, state.pv_cap_buffer, spv::DecorationCoherent); + } + if (!vertex) { + const auto words = state.builder.DecoratedType( + spv::OpTypeRuntimeArray, {{spv::OpDecorate, {spv::DecorationArrayStride, 4}}}, + TypeU32(state)); + const auto index_block = + state.builder.DecoratedType(spv::OpTypeStruct, + {{spv::OpMemberDecorate, {0, spv::DecorationOffset, 0}}, + {spv::OpDecorate, {spv::DecorationBlock}}}, + words); + state.pv_index_buffer = state.builder.DefineGlobalVariable( + TypePointer(state, spv::StorageClassStorageBuffer, index_block), + spv::StorageClassStorageBuffer); + state.builder.AddName(state.pv_index_buffer, "pv_indices"); + state.builder.AddAnnotation(spv::OpDecorate, state.pv_index_buffer, + spv::DecorationDescriptorSet, 1); + state.builder.AddAnnotation(spv::OpDecorate, state.pv_index_buffer, spv::DecorationBinding, + 1); + state.builder.AddAnnotation(spv::OpDecorate, state.pv_index_buffer, + spv::DecorationNonWritable); + // PrimitiveId in a fragment shader needs the Geometry capability. + state.builder.RequireCapability(spv::CapabilityGeometry); ``` Two parts.n1. Capability: valid. The device enables `tessellationShader` but not `geometryShader`, so the VS-store PS now declares `Tessellation` for `PrimitiveId`. Fixed in 98aac3b9 (the emitter belongs to #1440, so it is in that branch and reaches this PR by the rebase). Test: `shader_cfg` checks `Capability Tessellation` and the absence of `Capability Geometry`; mutant `shader_cfg_pv_vsstore_mutant_capability_geometry` fails it.n2. Barycentric feature: the observation is right (the PS still reads `BaryCoordKHR`, and on macOS `fragmentShaderBarycentric` is never requested; the VS-store path is meant for exactly that device), but I left it unchanged here. It is not specific to this path: every guest PS with custom interpolation (VINTRP) already gets `FragmentBarycentricKHR`/`BaryCoordKHR` from the emitter, which does not condition it on the platform (see the existing `shader_cfg` checks for custom VINTRP). Requesting the feature on Apple would change device creation for the whole renderer and needs its own GPU/validation run, so it is better as a separate change. I have not run the validation layer on this path.
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-12 10:15 UTC · original · edited 2026-10-12 15:21 UTC
On tests/PerVertexVsStoreGpuTests.cpp line 382 (outdated):

@@ -0,0 +1,751 @@
+// GPU harness for KYTY_PV_VSSTORE (graphics/host_gpu/renderer/perVertexVsStore.h). The real SPIR-V
+// emitter produces the VS-store VS and PS from an IR vertex shader and an ISA pixel shader, and the
+// pair is drawn on the host GPU (MoltenVK) with the exact descriptor/push layout of the renderer:
+//   set 0 = empty, set 1 = {cap SSBO (VS|FS), guest index SSBO (FS)}, push = native data + 8 dwords.
+// Checks (bit for bit, no tolerance):
+//   1. image: every probed pixel equals the PerVertexKHR semantics computed on the CPU from the vertex
+//      data, the index buffer and the draw parameters (corner 0/1/2 read through P0/P10/P20),
+//   2. cap: the records the VS wrote hold {gl_VertexIndex, gl_InstanceIndex} of the cases, which
+//      settles whether gl_VertexIndex includes vertex_offset and gl_InstanceIndex first_instance.
+// Cases: 16-bit and 32-bit indices, vertex_offset > 0 and < 0, first_instance != 0, 2 instances, an index
+// buffer bound at an offset that is not a multiple of minStorageBufferOffsetAlignment.
+// Run: per_vertex_vsstore_gpu_tests [--dump] [--stress]  (--stress: 2M triangles x 2..4 instances, parameter-buffer overflow)
+//   --dump needs no GPU: it prints the emitted SPIR-V.
+// The result is compared with the CPU model of the per-vertex semantics. The mutants built from
+// tests/PerVertexVsStoreMutants.cmake (corner 0/2 swapped, index range not rounded) must fail it.
+
+#include "common/emulatorConfig.h"
+#include "common/logging/log.h"
+#include "common/subsystems.h"
+#include "common/threads.h"
+#include "graphics/host_gpu/renderer/perVertexVsStore.h"
+#include "graphics/shader/recompiler/ShaderRecompiler.h"
+#include "graphics/shader/recompiler/backend/spirv/SpirvEmitter.h"
+#include "graphics/shader/recompiler/ir/IREmitter.h"
+#include "graphics/shader/recompiler/ir/ShaderIR.h"
+#include "graphics/shader/recompiler/ir/passes/ResourceTracking.h"
+#include "graphics/shader/shader.h"
+#include "graphics/shader/shaderCompiler.h"
+
+#include <spirv-tools/libspirv.hpp>
+#include <vulkan/vulkan.h>
+
+#include <dlfcn.h>
+
+#include <algorithm>
+#include <array>
+#include <cstdint>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <span>
+#include <string>
+#include <vector>
+
+namespace Libs::Graphics {
+namespace {
+
+using namespace ShaderRecompiler;
+
+bool g_stress = false; // --stress: the >= 2M triangle cases
+
+[[noreturn]] void Fail(const char* message) {
+	std::fprintf(stderr, "per-vertex-vsstore-gpu-tests: FAILED: %s\n", message);
+	std::exit(1);
+}
+
+void Check(bool ok, const char* message) {
+	if (!ok) Fail(message);
+}
+
+void CheckVk(VkResult result, const char* what) {
+	if (result != VK_SUCCESS) {
+		std::fprintf(stderr, "per-vertex-vsstore-gpu-tests: FAILED: %s (VkResult %d)\n", what, static_cast<int>(result));
+		std::exit(1);
+	}
+}
+
+constexpr uint32_t EncodeSopp(uint32_t opcode, uint32_t simm = 0) {
+	return (0x17fu << 23u) | ((opcode & 0x7fu) << 16u) | (simm & 0xffffu);
+}
+constexpr uint32_t EncodeVintrp(uint32_t opcode, uint32_t vdst, uint32_t attr, uint32_t chan, uint32_t vsrc) {
+	return (0x32u << 26u) | ((opcode & 0x3u) << 16u) | ((vdst & 0xffu) << 18u) | ((attr & 0x3fu) << 10u) |
+	       ((chan & 0x3u) << 8u) | (vsrc & 0xffu);
+}
+constexpr uint32_t EncodeExp0(uint32_t target, uint32_t en) {
+	return (0x3eu << 26u) | ((target & 0x3fu) << 4u) | (en & 0xfu) | (1u << 11u);
+}
+constexpr uint32_t EncodeExp1(uint32_t a, uint32_t b, uint32_t c, uint32_t d) {
+	return (a & 0xffu) | ((b & 0xffu) << 8u) | ((c & 0xffu) << 16u) | ((d & 0xffu) << 24u);
+}
+
+void EnsureConfigInitialized() {
+	static bool initialized = false;
+	if (initialized) return;
+	static Common::Subsystems subsystems;
+	Common::InitializeThreads();
+	subsystems.Initialize<Config::Lifecycle>();
+	Config::ConfigOptions options;
+	options.printf_direction = Config::LogDirection::Silent;
+	Config::Load(options);
+	subsystems.Initialize<Log::Lifecycle>();
+	ShaderInit();
+	initialized = true;
+}
+
+// ---- shaders -------------------------------------------------------------------------------------
+
+struct Shaders {
+	std::vector<uint32_t> vs;
+	std::vector<uint32_t> ps;
+	uint32_t              stride_vec4 = 0;
+};
+
+// VS: position = attr0, param0 = attr1 with `+ instance` added to the bits of x (a 1 ulp difference
+// per instance shows a record of the wrong instance), param1 = {gl_VertexIndex, gl_InstanceIndex, 0, 0}.
+// PS: out = {corner0.x, corner1.y, corner2.z, corner0.w} of param0.
+Shaders BuildShaders() {
+	using IR::Value;
+	using O = IR::ValueOpcode;
+	Shaders out;
+
+	IR::Program vs;
+	vs.stage                  = ShaderType::Vertex;
+	vs.wave_size              = 64;
+	vs.srt_plan_complete      = vs.resource_tracking_complete = vs.shader_info_complete = true;
+	vs.block_storage.push_back(std::make_unique<IR::Block>());
+	vs.blocks.push_back(vs.block_storage.back().get());
+	vs.info.inputs  = {{IR::StageInputKind::VertexIndex},
+	                   {IR::StageInputKind::InstanceIndex},
+	                   {IR::StageInputKind::Parameter, 0, 4},
+	                   {IR::StageInputKind::Parameter, 1, 4}};
+	vs.info.outputs = {{IR::StageOutputKind::Position},
+	                   {IR::StageOutputKind::Parameter, 0, 0},
+	                   {IR::StageOutputKind::Parameter, 1, 1}};
+	vs.export_info  = {{.kind = IR::ExportTargetKind::Position, .en = 15},
+	                   {.kind = IR::ExportTargetKind::Parameter, .index = 0, .en = 15},
+	                   {.kind = IR::ExportTargetKind::Parameter, .index = 1, .en = 15}};
+	IR::IREmitter emit(vs.blocks.front());
+	const auto vertex   = emit.Emit(O::GetBuiltin, {Value(static_cast<uint32_t>(IR::StageInputKind::VertexIndex)), Value(0u)});
+	const auto instance = emit.Emit(O::GetBuiltin, {Value(static_cast<uint32_t>(IR::StageInputKind::InstanceIndex)), Value(0u)});
+	std::array<Value, 4> position, color;
+	for (uint32_t c = 0; c < 4; c++) position[c] = emit.Emit(O::GetAttribute, {Value(0u), Value(c)});
+	for (uint32_t c = 0; c < 4; c++) color[c] = emit.Emit(O::GetAttribute, {Value(1u), Value(c)});
+	const auto pos = emit.Emit(O::CompositeConstructU32x4, {position[0], position[1], position[2], position[3]});
+	emit.Emit(O::SetAttribute, {pos, Value(true)}, IR::ExportFlags {0});
+	const auto x      = emit.Emit(O::IAdd32, {color[0], instance});
+	const auto param0 = emit.Emit(O::CompositeConstructU32x4, {x, color[1], color[2], color[3]});
+	emit.Emit(O::SetAttribute, {param0, Value(true)}, IR::ExportFlags {1});
+	const auto param1 = emit.Emit(O::CompositeConstructU32x4, {vertex, instance, Value(0u), Value(0u)});
+	emit.Emit(O::SetAttribute, {param1, Value(true)}, IR::ExportFlags {2});
+	static const ShaderVertexInputInfo vertex_info {};
+	ShaderStageInputInfo               vs_input {.vertex = &vertex_info};
+
+	uint32_t vs_mask = 0;
+	Spirv::PvStoreInfo vs_store;
+	vs_store.role          = Spirv::PvStoreInfo::Role::Vertex;
+	vs_store.coherent      = true;
+	vs_store.location_mask = &vs_mask;
+	out.vs                 = Spirv::EmitProgram(vs, vs_input, 0, &vs_store);
+
+	// PS (the interpolation setup of TestPvVsStoreEmission): v_interp_mov_f32 with P0 / P10 / P20.
+	const uint32_t ps_code[] = {EncodeVintrp(2, 12, 0, 0, 2), EncodeVintrp(2, 13, 0, 1, 0),
+	                            EncodeVintrp(2, 14, 0, 2, 1), EncodeVintrp(2, 15, 0, 3, 2),
+	                            EncodeExp0(0x00, 0xf),        EncodeExp1(12, 13, 14, 15),
+	                            EncodeSopp(0x01)};
+	static ShaderPixelInputInfo ps_info {};
+	ps_info.input_num                 = 1;
+	ps_info.ps_system_input_base      = 2;
+	ps_info.custom_interpolation_mask = 1;
+	ps_info.ps_perspective_center_vgpr = 0;
+	for (uint32_t i = 0; i < std::size(ps_info.interpolator_settings); i++) ps_info.interpolator_settings[i] = i;
+	ps_info.interpolator_settings[0] = 0x00000420u;
+	static const std::array<uint32_t, 64> user_data = [] {
+		std::array<uint32_t, 64> data {};
+		data[3] = 3u << 28u;
+		return data;
+	}();
+	CompileOptions options;
+	options.stage            = ShaderType::Pixel;
+	options.user_data        = user_data;
+	options.input_info.pixel = &ps_info;
+	auto translated          = TranslateProgram(ps_code, options);
+	auto plan                = IR::ExtractResourcePlan(translated.program);
+	IR::ResourceSnapshot       resources;
+	IR::ResourceSpecialization specialization;
+	const IR::SrtRuntime       runtime {.user_data = options.user_data,
+	                                    .shader_base = reinterpret_cast<uint64_t>(ps_code),
+	                                    .read_specialization_memory = [](void*, uint64_t, std::span<uint32_t>) { return false; }};
+	Check(IR::MaterializeResources(plan, runtime, resources, specialization), "PS resources did not materialize");
+	auto compiled = CompileProgram(std::move(translated), options, specialization, 0);
+	uint32_t ps_mask = 0;
+	Spirv::PvStoreInfo ps_store;
+	ps_store.role          = Spirv::PvStoreInfo::Role::Pixel;
+	ps_store.coherent      = true;
+	ps_store.location_mask = &ps_mask;
+	out.ps                 = Spirv::EmitProgram(compiled.program, options.input_info, 0, &ps_store);
+
+	Check(ClassifyPvVsStoreInterface(vs_mask, ps_mask) == PvVsStoreInterfaceVerdict::Use, "VS/PS pair is not a VS-store candidate");
+	out.stride_vec4 = PvVsStoreStrideFor(vs_mask);
+	if (out.stride_vec4 != 2) std::fprintf(stderr, "VS location mask %08x, PS location mask %08x\n", vs_mask, ps_mask);
+	Check(out.stride_vec4 == 2, "expected stride 2 (locations 0 and 1)");
+	spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_2);
+	Check(tools.Validate(out.vs), "VS-store VS does not validate");
+	Check(tools.Validate(out.ps), "VS-store PS does not validate");
+	return out;
+}
+
+// ---- scene (CPU model) ---------------------------------------------------------------------------
+
+constexpr uint32_t kDim      = 32; // render target
+constexpr uint32_t kCell     = 16; // one triangle per cell: 2x2 cells
+constexpr uint32_t kVertices = 24; // 4 triangles x 3 corners, plus 12 spare vertices for offsets
+constexpr uint32_t kStrideB  = 32; // float4 position, float4 color
+
+struct Vertex {
+	float position[4];
+	float color[4];
+};
+
+std::array<Vertex, kVertices> MakeVertices() {
+	std::array<Vertex, kVertices> v {};
+	for (uint32_t i = 0; i < kVertices; ++i) {
+		const uint32_t tri = (i / 3u) % 4u;
+		const uint32_t cx  = tri % 2u, cy = tri / 2u;
+		const float    x0  = static_cast<float>(cx * kCell), y0 = static_cast<float>(cy * kCell);
+		const float    px[3] = {x0 + 2.f, x0 + 14.f, x0 + 2.f};
+		const float    py[3] = {y0 + 2.f, y0 + 2.f, y0 + 14.f};
+		const uint32_t k     = i % 3u;
+		v[i].position[0] = px[k] / (kDim / 2.f) - 1.f;
+		v[i].position[1] = py[k] / (kDim / 2.f) - 1.f;
+		v[i].position[2] = 0.5f;
+		v[i].position[3] = 1.f;
+		// distinct, normal floats: any mix-up of a vertex, a corner or a component shows
+		v[i].color[0] = 1.0f + 0.03125f * static_cast<float>(i);
+		v[i].color[1] = 2.0f + 0.0625f * static_cast<float>(i);
+		v[i].color[2] = 3.0f + 0.125f * static_cast<float>(i);
+		v[i].color[3] = 4.0f + 0.25f * static_cast<float>(i);
+	}
+	return v;
+}
+
+struct Case {
+	const char*           name;
+	bool                  index32;
+	std::vector<uint32_t> indices;       // per triangle corner, relative to vertex_offset
+	int32_t               vertex_offset;
+	uint32_t              first_instance;
+	uint32_t              instance_count;
+	uint32_t              bind_byte_offset; // where the index data starts inside the index buffer
+};
+
+uint32_t Bits(float f) {
+	uint32_t u;
+	std::memcpy(&u, &f, 4);
+	return u;
+}
+
+// Expected pixel of triangle t of the draw: {corner0.x(+inst), corner1.y, corner2.z, corner0.w}.
+std::array<uint32_t, 4> ExpectedPixel(const std::array<Vertex, kVertices>& v, const Case& c, uint32_t tri) {
+	const uint32_t last_instance = c.first_instance + c.instance_count - 1;
+	const auto     vertex = [&](uint32_t corner) { return static_cast<uint32_t>(static_cast<int32_t>(c.indices[tri * 3 + corner]) + c.vertex_offset); };
+	std::array<uint32_t, 4> out {};
+	out[0] = Bits(v[vertex(0)].color[0]) + last_instance;
+	out[1] = Bits(v[vertex(1)].color[1]);
+	out[2] = Bits(v[vertex(2)].color[2]);
+	out[3] = Bits(v[vertex(0)].color[3]);
+	return out;
+}
+
+// ---- Vulkan --------------------------------------------------------------------------------------
+
+#define VK_FUNCS(X)                                                                                                        \
+	X(vkCreateDevice) X(vkGetDeviceProcAddr) X(vkEnumeratePhysicalDevices) X(vkGetPhysicalDeviceMemoryProperties)          \
+	X(vkGetPhysicalDeviceQueueFamilyProperties) X(vkGetPhysicalDeviceFeatures) X(vkGetPhysicalDeviceProperties)
+
+#define VK_DEVICE_FUNCS(X)                                                                                                 \
+	X(vkGetDeviceQueue) X(vkCreateBuffer) X(vkGetBufferMemoryRequirements) X(vkAllocateMemory) X(vkBindBufferMemory)      \
+	X(vkMapMemory) X(vkCreateDescriptorSetLayout) X(vkCreatePipelineLayout) X(vkCreateShaderModule)                         \
+	X(vkCreateGraphicsPipelines) X(vkCreateDescriptorPool) X(vkAllocateDescriptorSets) X(vkUpdateDescriptorSets)           \
+	X(vkCreateCommandPool) X(vkAllocateCommandBuffers) X(vkBeginCommandBuffer) X(vkEndCommandBuffer)                       \
+	X(vkCmdBindPipeline) X(vkCmdBindDescriptorSets) X(vkCmdPushConstants) X(vkCmdBeginRenderPass) X(vkCmdEndRenderPass)    \
+	X(vkCmdBindVertexBuffers) X(vkCmdBindIndexBuffer) X(vkCmdDrawIndexed) X(vkCmdCopyImageToBuffer) X(vkQueueSubmit)      \
+	X(vkQueueWaitIdle) X(vkCreateRenderPass) X(vkCreateFramebuffer) X(vkCreateImage) X(vkGetImageMemoryRequirements)       \
+	X(vkBindImageMemory) X(vkCreateImageView) X(vkCmdPipelineBarrier)
+
+#define DECLARE(name) PFN_##name name##_ = nullptr;
+VK_FUNCS(DECLARE)
+VK_DEVICE_FUNCS(DECLARE)
+#undef DECLARE
+
+struct Gpu {
+	VkInstance                       instance = VK_NULL_HANDLE;
+	VkPhysicalDevice                 physical = VK_NULL_HANDLE;
+	VkDevice                         device   = VK_NULL_HANDLE;
+	VkQueue                          queue    = VK_NULL_HANDLE;
+	uint32_t                         family   = 0;
+	VkPhysicalDeviceMemoryProperties memory {};
+	VkDeviceSize                     storage_alignment = 16;
+};
+
+struct Buf {
+	VkBuffer       buffer = VK_NULL_HANDLE;
+	VkDeviceMemory memory = VK_NULL_HANDLE;
+	void*          mapped = nullptr;
+	size_t         size   = 0;
+};
+
+uint32_t MemoryType(const Gpu& gpu, uint32_t bits, VkMemoryPropertyFlags flags) {
+	for (uint32_t i = 0; i < gpu.memory.memoryTypeCount; ++i) {
+		if ((bits & (1u << i)) && (gpu.memory.memoryTypes[i].propertyFlags & flags) == flags) return i;
+	}
+	Fail("no suitable memory type");
+}
+
+Buf MakeBuffer(const Gpu& gpu, size_t size, VkBufferUsageFlags usage) {
+	Buf b;
+	b.size = size;
+	VkBufferCreateInfo info {VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
+	info.size  = size;
+	info.usage = usage;
+	CheckVk(vkCreateBuffer_(gpu.device, &info, nullptr, &b.buffer), "vkCreateBuffer");
+	VkMemoryRequirements req;
+	vkGetBufferMemoryRequirements_(gpu.device, b.buffer, &req);
+	VkMemoryAllocateInfo alloc {VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
+	alloc.allocationSize  = req.size;
+	alloc.memoryTypeIndex = MemoryType(gpu, req.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
+	CheckVk(vkAllocateMemory_(gpu.device, &alloc, nullptr, &b.memory), "vkAllocateMemory");
+	CheckVk(vkBindBufferMemory_(gpu.device, b.buffer, b.memory, 0), "vkBindBufferMemory");
+	CheckVk(vkMapMemory_(gpu.device, b.memory, 0, size, 0, &b.mapped), "vkMapMemory");
+	std::memset(b.mapped, 0xA5, size);
+	return b;
+}
+
+Gpu InitGpu() {
+	const char* driver = std::getenv("SDL_VULKAN_LIBRARY");
+	void*       lib    = dlopen(driver != nullptr ? driver : "libMoltenVK.dylib", RTLD_NOW | RTLD_LOCAL);
+	if (lib == nullptr) Fail("cannot load MoltenVK; set SDL_VULKAN_LIBRARY");
+	auto get_instance_proc = reinterpret_cast<PFN_vkGetInstanceProcAddr>(dlsym(lib, "vkGetInstanceProcAddr"));
+	if (get_instance_proc == nullptr) Fail("dlsym vkGetInstanceProcAddr");
+	auto create_instance = reinterpret_cast<PFN_vkCreateInstance>(get_instance_proc(VK_NULL_HANDLE, "vkCreateInstance"));
+	auto enumerate_extensions = reinterpret_cast<PFN_vkEnumerateInstanceExtensionProperties>(
+	    get_instance_proc(VK_NULL_HANDLE, "vkEnumerateInstanceExtensionProperties"));
+	if (enumerate_extensions == nullptr) Fail("vkEnumerateInstanceExtensionProperties");
+	uint32_t extension_count = 0;
+	CheckVk(enumerate_extensions(nullptr, &extension_count, nullptr), "vkEnumerateInstanceExtensionProperties");
+	std::vector<VkExtensionProperties> available(extension_count);
+	CheckVk(enumerate_extensions(nullptr, &extension_count, available.data()), "vkEnumerateInstanceExtensionProperties list");
+	bool has_portability = false;
+	for (const auto& e: available) {
+		if (std::strcmp(e.extensionName, VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME) == 0) has_portability = true;
+	}
+	const char* extensions[] {VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME};
+	VkApplicationInfo app {VK_STRUCTURE_TYPE_APPLICATION_INFO};
+	app.apiVersion = VK_API_VERSION_1_3;
+	VkInstanceCreateInfo info {VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO};
+	info.pApplicationInfo        = &app;
+	info.flags                   = has_portability ? VK_INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR : 0;
+	info.enabledExtensionCount   = has_portability ? 1u : 0u;
+	info.ppEnabledExtensionNames = has_portability ? extensions : nullptr;
+	Gpu gpu;
+	CheckVk(create_instance(&info, nullptr, &gpu.instance), "vkCreateInstance");
+#define LOAD_INSTANCE(name) name##_ = reinterpret_cast<PFN_##name>(get_instance_proc(gpu.instance, #name));
+	VK_FUNCS(LOAD_INSTANCE)
+#undef LOAD_INSTANCE
+	uint32_t count = 0;
+	CheckVk(vkEnumeratePhysicalDevices_(gpu.instance, &count, nullptr), "vkEnumeratePhysicalDevices");
+	Check(count > 0, "no physical device");
+	std::vector<VkPhysicalDevice> devices(count);
+	CheckVk(vkEnumeratePhysicalDevices_(gpu.instance, &count, devices.data()), "vkEnumeratePhysicalDevices list");
+	gpu.physical = devices[0];
+	vkGetPhysicalDeviceMemoryProperties_(gpu.physical, &gpu.memory);
+	VkPhysicalDeviceProperties props {};
+	vkGetPhysicalDeviceProperties_(gpu.physical, &props);
+	gpu.storage_alignment = props.limits.minStorageBufferOffsetAlignment;
+	uint32_t qcount = 0;
+	vkGetPhysicalDeviceQueueFamilyProperties_(gpu.physical, &qcount, nullptr);
+	std::vector<VkQueueFamilyProperties> queues(qcount);
+	vkGetPhysicalDeviceQueueFamilyProperties_(gpu.physical, &qcount, queues.data());
+	for (uint32_t i = 0; i < qcount; ++i) {
+		if (queues[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) {
+			gpu.family = i;
+			break;
+		}
+	}
+	VkPhysicalDeviceFeatures supported {};
+	vkGetPhysicalDeviceFeatures_(gpu.physical, &supported);
+	Check(supported.vertexPipelineStoresAndAtomics, "device lacks vertexPipelineStoresAndAtomics (the VS cannot store)");
+	VkPhysicalDeviceFeatures features {};
+	features.vertexPipelineStoresAndAtomics = VK_TRUE;
+	features.fragmentStoresAndAtomics       = supported.fragmentStoresAndAtomics;
+	features.shaderClipDistance             = supported.shaderClipDistance; // the emitted VS has a clip guard
+	features.geometryShader                 = supported.geometryShader; // PrimitiveId in the PS needs the Geometry capability

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Enable tessellationShader instead of geometryShader on the harness device.

The emitter now asks for spv::CapabilityTessellation when a pixel shader reads PrimitiveId (see DefinePvStore in spirvEmitterPvStore.cpp). The capability_geometry mutant exists to keep the pixel shader from asking for Geometry. Even so, this harness still enables geometryShader and never enables tessellationShader. The Vulkan spec does not allow a shader module to declare the Tessellation capability while tessellationShader is off. MoltenVK can accept this without an error, but validation layers will report it. It also means the harness no longer uses the same device features as the renderer, even though the file header says it uses the renderer's setup. The comment on line 382 is out of date for the same reason.

🐛 Proposed fix
-	features.geometryShader                 = supported.geometryShader; // PrimitiveId in the PS needs the Geometry capability
+	Check(supported.tessellationShader, "device lacks tessellationShader (PrimitiveId in the PS needs the Tessellation capability)");
+	features.tessellationShader             = VK_TRUE; // PrimitiveId in the PS uses the Tessellation capability
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

	features.shaderClipDistance             = supported.shaderClipDistance; // the emitted VS has a clip guard
	Check(supported.tessellationShader, "device lacks tessellationShader (PrimitiveId in the PS needs the Tessellation capability)");
	features.tessellationShader             = VK_TRUE; // PrimitiveId in the PS uses the Tessellation capability

✅ Confirmed as addressed by @⁠wuboo

**@⁠coderabbitai[bot]** on GitHub · 2026-10-12 10:15 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1441#discussion_r4246882880) · edited 2026-10-12 15:21 UTC On `tests/PerVertexVsStoreGpuTests.cpp` line 382 (outdated): ```diff @@ -0,0 +1,751 @@ +// GPU harness for KYTY_PV_VSSTORE (graphics/host_gpu/renderer/perVertexVsStore.h). The real SPIR-V +// emitter produces the VS-store VS and PS from an IR vertex shader and an ISA pixel shader, and the +// pair is drawn on the host GPU (MoltenVK) with the exact descriptor/push layout of the renderer: +// set 0 = empty, set 1 = {cap SSBO (VS|FS), guest index SSBO (FS)}, push = native data + 8 dwords. +// Checks (bit for bit, no tolerance): +// 1. image: every probed pixel equals the PerVertexKHR semantics computed on the CPU from the vertex +// data, the index buffer and the draw parameters (corner 0/1/2 read through P0/P10/P20), +// 2. cap: the records the VS wrote hold {gl_VertexIndex, gl_InstanceIndex} of the cases, which +// settles whether gl_VertexIndex includes vertex_offset and gl_InstanceIndex first_instance. +// Cases: 16-bit and 32-bit indices, vertex_offset > 0 and < 0, first_instance != 0, 2 instances, an index +// buffer bound at an offset that is not a multiple of minStorageBufferOffsetAlignment. +// Run: per_vertex_vsstore_gpu_tests [--dump] [--stress] (--stress: 2M triangles x 2..4 instances, parameter-buffer overflow) +// --dump needs no GPU: it prints the emitted SPIR-V. +// The result is compared with the CPU model of the per-vertex semantics. The mutants built from +// tests/PerVertexVsStoreMutants.cmake (corner 0/2 swapped, index range not rounded) must fail it. + +#include "common/emulatorConfig.h" +#include "common/logging/log.h" +#include "common/subsystems.h" +#include "common/threads.h" +#include "graphics/host_gpu/renderer/perVertexVsStore.h" +#include "graphics/shader/recompiler/ShaderRecompiler.h" +#include "graphics/shader/recompiler/backend/spirv/SpirvEmitter.h" +#include "graphics/shader/recompiler/ir/IREmitter.h" +#include "graphics/shader/recompiler/ir/ShaderIR.h" +#include "graphics/shader/recompiler/ir/passes/ResourceTracking.h" +#include "graphics/shader/shader.h" +#include "graphics/shader/shaderCompiler.h" + +#include <spirv-tools/libspirv.hpp> +#include <vulkan/vulkan.h> + +#include <dlfcn.h> + +#include <algorithm> +#include <array> +#include <cstdint> +#include <cstdio> +#include <cstdlib> +#include <cstring> +#include <span> +#include <string> +#include <vector> + +namespace Libs::Graphics { +namespace { + +using namespace ShaderRecompiler; + +bool g_stress = false; // --stress: the >= 2M triangle cases + +[[noreturn]] void Fail(const char* message) { + std::fprintf(stderr, "per-vertex-vsstore-gpu-tests: FAILED: %s\n", message); + std::exit(1); +} + +void Check(bool ok, const char* message) { + if (!ok) Fail(message); +} + +void CheckVk(VkResult result, const char* what) { + if (result != VK_SUCCESS) { + std::fprintf(stderr, "per-vertex-vsstore-gpu-tests: FAILED: %s (VkResult %d)\n", what, static_cast<int>(result)); + std::exit(1); + } +} + +constexpr uint32_t EncodeSopp(uint32_t opcode, uint32_t simm = 0) { + return (0x17fu << 23u) | ((opcode & 0x7fu) << 16u) | (simm & 0xffffu); +} +constexpr uint32_t EncodeVintrp(uint32_t opcode, uint32_t vdst, uint32_t attr, uint32_t chan, uint32_t vsrc) { + return (0x32u << 26u) | ((opcode & 0x3u) << 16u) | ((vdst & 0xffu) << 18u) | ((attr & 0x3fu) << 10u) | + ((chan & 0x3u) << 8u) | (vsrc & 0xffu); +} +constexpr uint32_t EncodeExp0(uint32_t target, uint32_t en) { + return (0x3eu << 26u) | ((target & 0x3fu) << 4u) | (en & 0xfu) | (1u << 11u); +} +constexpr uint32_t EncodeExp1(uint32_t a, uint32_t b, uint32_t c, uint32_t d) { + return (a & 0xffu) | ((b & 0xffu) << 8u) | ((c & 0xffu) << 16u) | ((d & 0xffu) << 24u); +} + +void EnsureConfigInitialized() { + static bool initialized = false; + if (initialized) return; + static Common::Subsystems subsystems; + Common::InitializeThreads(); + subsystems.Initialize<Config::Lifecycle>(); + Config::ConfigOptions options; + options.printf_direction = Config::LogDirection::Silent; + Config::Load(options); + subsystems.Initialize<Log::Lifecycle>(); + ShaderInit(); + initialized = true; +} + +// ---- shaders ------------------------------------------------------------------------------------- + +struct Shaders { + std::vector<uint32_t> vs; + std::vector<uint32_t> ps; + uint32_t stride_vec4 = 0; +}; + +// VS: position = attr0, param0 = attr1 with `+ instance` added to the bits of x (a 1 ulp difference +// per instance shows a record of the wrong instance), param1 = {gl_VertexIndex, gl_InstanceIndex, 0, 0}. +// PS: out = {corner0.x, corner1.y, corner2.z, corner0.w} of param0. +Shaders BuildShaders() { + using IR::Value; + using O = IR::ValueOpcode; + Shaders out; + + IR::Program vs; + vs.stage = ShaderType::Vertex; + vs.wave_size = 64; + vs.srt_plan_complete = vs.resource_tracking_complete = vs.shader_info_complete = true; + vs.block_storage.push_back(std::make_unique<IR::Block>()); + vs.blocks.push_back(vs.block_storage.back().get()); + vs.info.inputs = {{IR::StageInputKind::VertexIndex}, + {IR::StageInputKind::InstanceIndex}, + {IR::StageInputKind::Parameter, 0, 4}, + {IR::StageInputKind::Parameter, 1, 4}}; + vs.info.outputs = {{IR::StageOutputKind::Position}, + {IR::StageOutputKind::Parameter, 0, 0}, + {IR::StageOutputKind::Parameter, 1, 1}}; + vs.export_info = {{.kind = IR::ExportTargetKind::Position, .en = 15}, + {.kind = IR::ExportTargetKind::Parameter, .index = 0, .en = 15}, + {.kind = IR::ExportTargetKind::Parameter, .index = 1, .en = 15}}; + IR::IREmitter emit(vs.blocks.front()); + const auto vertex = emit.Emit(O::GetBuiltin, {Value(static_cast<uint32_t>(IR::StageInputKind::VertexIndex)), Value(0u)}); + const auto instance = emit.Emit(O::GetBuiltin, {Value(static_cast<uint32_t>(IR::StageInputKind::InstanceIndex)), Value(0u)}); + std::array<Value, 4> position, color; + for (uint32_t c = 0; c < 4; c++) position[c] = emit.Emit(O::GetAttribute, {Value(0u), Value(c)}); + for (uint32_t c = 0; c < 4; c++) color[c] = emit.Emit(O::GetAttribute, {Value(1u), Value(c)}); + const auto pos = emit.Emit(O::CompositeConstructU32x4, {position[0], position[1], position[2], position[3]}); + emit.Emit(O::SetAttribute, {pos, Value(true)}, IR::ExportFlags {0}); + const auto x = emit.Emit(O::IAdd32, {color[0], instance}); + const auto param0 = emit.Emit(O::CompositeConstructU32x4, {x, color[1], color[2], color[3]}); + emit.Emit(O::SetAttribute, {param0, Value(true)}, IR::ExportFlags {1}); + const auto param1 = emit.Emit(O::CompositeConstructU32x4, {vertex, instance, Value(0u), Value(0u)}); + emit.Emit(O::SetAttribute, {param1, Value(true)}, IR::ExportFlags {2}); + static const ShaderVertexInputInfo vertex_info {}; + ShaderStageInputInfo vs_input {.vertex = &vertex_info}; + + uint32_t vs_mask = 0; + Spirv::PvStoreInfo vs_store; + vs_store.role = Spirv::PvStoreInfo::Role::Vertex; + vs_store.coherent = true; + vs_store.location_mask = &vs_mask; + out.vs = Spirv::EmitProgram(vs, vs_input, 0, &vs_store); + + // PS (the interpolation setup of TestPvVsStoreEmission): v_interp_mov_f32 with P0 / P10 / P20. + const uint32_t ps_code[] = {EncodeVintrp(2, 12, 0, 0, 2), EncodeVintrp(2, 13, 0, 1, 0), + EncodeVintrp(2, 14, 0, 2, 1), EncodeVintrp(2, 15, 0, 3, 2), + EncodeExp0(0x00, 0xf), EncodeExp1(12, 13, 14, 15), + EncodeSopp(0x01)}; + static ShaderPixelInputInfo ps_info {}; + ps_info.input_num = 1; + ps_info.ps_system_input_base = 2; + ps_info.custom_interpolation_mask = 1; + ps_info.ps_perspective_center_vgpr = 0; + for (uint32_t i = 0; i < std::size(ps_info.interpolator_settings); i++) ps_info.interpolator_settings[i] = i; + ps_info.interpolator_settings[0] = 0x00000420u; + static const std::array<uint32_t, 64> user_data = [] { + std::array<uint32_t, 64> data {}; + data[3] = 3u << 28u; + return data; + }(); + CompileOptions options; + options.stage = ShaderType::Pixel; + options.user_data = user_data; + options.input_info.pixel = &ps_info; + auto translated = TranslateProgram(ps_code, options); + auto plan = IR::ExtractResourcePlan(translated.program); + IR::ResourceSnapshot resources; + IR::ResourceSpecialization specialization; + const IR::SrtRuntime runtime {.user_data = options.user_data, + .shader_base = reinterpret_cast<uint64_t>(ps_code), + .read_specialization_memory = [](void*, uint64_t, std::span<uint32_t>) { return false; }}; + Check(IR::MaterializeResources(plan, runtime, resources, specialization), "PS resources did not materialize"); + auto compiled = CompileProgram(std::move(translated), options, specialization, 0); + uint32_t ps_mask = 0; + Spirv::PvStoreInfo ps_store; + ps_store.role = Spirv::PvStoreInfo::Role::Pixel; + ps_store.coherent = true; + ps_store.location_mask = &ps_mask; + out.ps = Spirv::EmitProgram(compiled.program, options.input_info, 0, &ps_store); + + Check(ClassifyPvVsStoreInterface(vs_mask, ps_mask) == PvVsStoreInterfaceVerdict::Use, "VS/PS pair is not a VS-store candidate"); + out.stride_vec4 = PvVsStoreStrideFor(vs_mask); + if (out.stride_vec4 != 2) std::fprintf(stderr, "VS location mask %08x, PS location mask %08x\n", vs_mask, ps_mask); + Check(out.stride_vec4 == 2, "expected stride 2 (locations 0 and 1)"); + spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_2); + Check(tools.Validate(out.vs), "VS-store VS does not validate"); + Check(tools.Validate(out.ps), "VS-store PS does not validate"); + return out; +} + +// ---- scene (CPU model) --------------------------------------------------------------------------- + +constexpr uint32_t kDim = 32; // render target +constexpr uint32_t kCell = 16; // one triangle per cell: 2x2 cells +constexpr uint32_t kVertices = 24; // 4 triangles x 3 corners, plus 12 spare vertices for offsets +constexpr uint32_t kStrideB = 32; // float4 position, float4 color + +struct Vertex { + float position[4]; + float color[4]; +}; + +std::array<Vertex, kVertices> MakeVertices() { + std::array<Vertex, kVertices> v {}; + for (uint32_t i = 0; i < kVertices; ++i) { + const uint32_t tri = (i / 3u) % 4u; + const uint32_t cx = tri % 2u, cy = tri / 2u; + const float x0 = static_cast<float>(cx * kCell), y0 = static_cast<float>(cy * kCell); + const float px[3] = {x0 + 2.f, x0 + 14.f, x0 + 2.f}; + const float py[3] = {y0 + 2.f, y0 + 2.f, y0 + 14.f}; + const uint32_t k = i % 3u; + v[i].position[0] = px[k] / (kDim / 2.f) - 1.f; + v[i].position[1] = py[k] / (kDim / 2.f) - 1.f; + v[i].position[2] = 0.5f; + v[i].position[3] = 1.f; + // distinct, normal floats: any mix-up of a vertex, a corner or a component shows + v[i].color[0] = 1.0f + 0.03125f * static_cast<float>(i); + v[i].color[1] = 2.0f + 0.0625f * static_cast<float>(i); + v[i].color[2] = 3.0f + 0.125f * static_cast<float>(i); + v[i].color[3] = 4.0f + 0.25f * static_cast<float>(i); + } + return v; +} + +struct Case { + const char* name; + bool index32; + std::vector<uint32_t> indices; // per triangle corner, relative to vertex_offset + int32_t vertex_offset; + uint32_t first_instance; + uint32_t instance_count; + uint32_t bind_byte_offset; // where the index data starts inside the index buffer +}; + +uint32_t Bits(float f) { + uint32_t u; + std::memcpy(&u, &f, 4); + return u; +} + +// Expected pixel of triangle t of the draw: {corner0.x(+inst), corner1.y, corner2.z, corner0.w}. +std::array<uint32_t, 4> ExpectedPixel(const std::array<Vertex, kVertices>& v, const Case& c, uint32_t tri) { + const uint32_t last_instance = c.first_instance + c.instance_count - 1; + const auto vertex = [&](uint32_t corner) { return static_cast<uint32_t>(static_cast<int32_t>(c.indices[tri * 3 + corner]) + c.vertex_offset); }; + std::array<uint32_t, 4> out {}; + out[0] = Bits(v[vertex(0)].color[0]) + last_instance; + out[1] = Bits(v[vertex(1)].color[1]); + out[2] = Bits(v[vertex(2)].color[2]); + out[3] = Bits(v[vertex(0)].color[3]); + return out; +} + +// ---- Vulkan -------------------------------------------------------------------------------------- + +#define VK_FUNCS(X) \ + X(vkCreateDevice) X(vkGetDeviceProcAddr) X(vkEnumeratePhysicalDevices) X(vkGetPhysicalDeviceMemoryProperties) \ + X(vkGetPhysicalDeviceQueueFamilyProperties) X(vkGetPhysicalDeviceFeatures) X(vkGetPhysicalDeviceProperties) + +#define VK_DEVICE_FUNCS(X) \ + X(vkGetDeviceQueue) X(vkCreateBuffer) X(vkGetBufferMemoryRequirements) X(vkAllocateMemory) X(vkBindBufferMemory) \ + X(vkMapMemory) X(vkCreateDescriptorSetLayout) X(vkCreatePipelineLayout) X(vkCreateShaderModule) \ + X(vkCreateGraphicsPipelines) X(vkCreateDescriptorPool) X(vkAllocateDescriptorSets) X(vkUpdateDescriptorSets) \ + X(vkCreateCommandPool) X(vkAllocateCommandBuffers) X(vkBeginCommandBuffer) X(vkEndCommandBuffer) \ + X(vkCmdBindPipeline) X(vkCmdBindDescriptorSets) X(vkCmdPushConstants) X(vkCmdBeginRenderPass) X(vkCmdEndRenderPass) \ + X(vkCmdBindVertexBuffers) X(vkCmdBindIndexBuffer) X(vkCmdDrawIndexed) X(vkCmdCopyImageToBuffer) X(vkQueueSubmit) \ + X(vkQueueWaitIdle) X(vkCreateRenderPass) X(vkCreateFramebuffer) X(vkCreateImage) X(vkGetImageMemoryRequirements) \ + X(vkBindImageMemory) X(vkCreateImageView) X(vkCmdPipelineBarrier) + +#define DECLARE(name) PFN_##name name##_ = nullptr; +VK_FUNCS(DECLARE) +VK_DEVICE_FUNCS(DECLARE) +#undef DECLARE + +struct Gpu { + VkInstance instance = VK_NULL_HANDLE; + VkPhysicalDevice physical = VK_NULL_HANDLE; + VkDevice device = VK_NULL_HANDLE; + VkQueue queue = VK_NULL_HANDLE; + uint32_t family = 0; + VkPhysicalDeviceMemoryProperties memory {}; + VkDeviceSize storage_alignment = 16; +}; + +struct Buf { + VkBuffer buffer = VK_NULL_HANDLE; + VkDeviceMemory memory = VK_NULL_HANDLE; + void* mapped = nullptr; + size_t size = 0; +}; + +uint32_t MemoryType(const Gpu& gpu, uint32_t bits, VkMemoryPropertyFlags flags) { + for (uint32_t i = 0; i < gpu.memory.memoryTypeCount; ++i) { + if ((bits & (1u << i)) && (gpu.memory.memoryTypes[i].propertyFlags & flags) == flags) return i; + } + Fail("no suitable memory type"); +} + +Buf MakeBuffer(const Gpu& gpu, size_t size, VkBufferUsageFlags usage) { + Buf b; + b.size = size; + VkBufferCreateInfo info {VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; + info.size = size; + info.usage = usage; + CheckVk(vkCreateBuffer_(gpu.device, &info, nullptr, &b.buffer), "vkCreateBuffer"); + VkMemoryRequirements req; + vkGetBufferMemoryRequirements_(gpu.device, b.buffer, &req); + VkMemoryAllocateInfo alloc {VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; + alloc.allocationSize = req.size; + alloc.memoryTypeIndex = MemoryType(gpu, req.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); + CheckVk(vkAllocateMemory_(gpu.device, &alloc, nullptr, &b.memory), "vkAllocateMemory"); + CheckVk(vkBindBufferMemory_(gpu.device, b.buffer, b.memory, 0), "vkBindBufferMemory"); + CheckVk(vkMapMemory_(gpu.device, b.memory, 0, size, 0, &b.mapped), "vkMapMemory"); + std::memset(b.mapped, 0xA5, size); + return b; +} + +Gpu InitGpu() { + const char* driver = std::getenv("SDL_VULKAN_LIBRARY"); + void* lib = dlopen(driver != nullptr ? driver : "libMoltenVK.dylib", RTLD_NOW | RTLD_LOCAL); + if (lib == nullptr) Fail("cannot load MoltenVK; set SDL_VULKAN_LIBRARY"); + auto get_instance_proc = reinterpret_cast<PFN_vkGetInstanceProcAddr>(dlsym(lib, "vkGetInstanceProcAddr")); + if (get_instance_proc == nullptr) Fail("dlsym vkGetInstanceProcAddr"); + auto create_instance = reinterpret_cast<PFN_vkCreateInstance>(get_instance_proc(VK_NULL_HANDLE, "vkCreateInstance")); + auto enumerate_extensions = reinterpret_cast<PFN_vkEnumerateInstanceExtensionProperties>( + get_instance_proc(VK_NULL_HANDLE, "vkEnumerateInstanceExtensionProperties")); + if (enumerate_extensions == nullptr) Fail("vkEnumerateInstanceExtensionProperties"); + uint32_t extension_count = 0; + CheckVk(enumerate_extensions(nullptr, &extension_count, nullptr), "vkEnumerateInstanceExtensionProperties"); + std::vector<VkExtensionProperties> available(extension_count); + CheckVk(enumerate_extensions(nullptr, &extension_count, available.data()), "vkEnumerateInstanceExtensionProperties list"); + bool has_portability = false; + for (const auto& e: available) { + if (std::strcmp(e.extensionName, VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME) == 0) has_portability = true; + } + const char* extensions[] {VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME}; + VkApplicationInfo app {VK_STRUCTURE_TYPE_APPLICATION_INFO}; + app.apiVersion = VK_API_VERSION_1_3; + VkInstanceCreateInfo info {VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO}; + info.pApplicationInfo = &app; + info.flags = has_portability ? VK_INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR : 0; + info.enabledExtensionCount = has_portability ? 1u : 0u; + info.ppEnabledExtensionNames = has_portability ? extensions : nullptr; + Gpu gpu; + CheckVk(create_instance(&info, nullptr, &gpu.instance), "vkCreateInstance"); +#define LOAD_INSTANCE(name) name##_ = reinterpret_cast<PFN_##name>(get_instance_proc(gpu.instance, #name)); + VK_FUNCS(LOAD_INSTANCE) +#undef LOAD_INSTANCE + uint32_t count = 0; + CheckVk(vkEnumeratePhysicalDevices_(gpu.instance, &count, nullptr), "vkEnumeratePhysicalDevices"); + Check(count > 0, "no physical device"); + std::vector<VkPhysicalDevice> devices(count); + CheckVk(vkEnumeratePhysicalDevices_(gpu.instance, &count, devices.data()), "vkEnumeratePhysicalDevices list"); + gpu.physical = devices[0]; + vkGetPhysicalDeviceMemoryProperties_(gpu.physical, &gpu.memory); + VkPhysicalDeviceProperties props {}; + vkGetPhysicalDeviceProperties_(gpu.physical, &props); + gpu.storage_alignment = props.limits.minStorageBufferOffsetAlignment; + uint32_t qcount = 0; + vkGetPhysicalDeviceQueueFamilyProperties_(gpu.physical, &qcount, nullptr); + std::vector<VkQueueFamilyProperties> queues(qcount); + vkGetPhysicalDeviceQueueFamilyProperties_(gpu.physical, &qcount, queues.data()); + for (uint32_t i = 0; i < qcount; ++i) { + if (queues[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) { + gpu.family = i; + break; + } + } + VkPhysicalDeviceFeatures supported {}; + vkGetPhysicalDeviceFeatures_(gpu.physical, &supported); + Check(supported.vertexPipelineStoresAndAtomics, "device lacks vertexPipelineStoresAndAtomics (the VS cannot store)"); + VkPhysicalDeviceFeatures features {}; + features.vertexPipelineStoresAndAtomics = VK_TRUE; + features.fragmentStoresAndAtomics = supported.fragmentStoresAndAtomics; + features.shaderClipDistance = supported.shaderClipDistance; // the emitted VS has a clip guard + features.geometryShader = supported.geometryShader; // PrimitiveId in the PS needs the Geometry capability ``` **🎯 Functional Correctness** | **🟡 Minor** | **⚡ Quick win** **Enable `tessellationShader` instead of `geometryShader` on the harness device.** The emitter now asks for `spv::CapabilityTessellation` when a pixel shader reads `PrimitiveId` (see `DefinePvStore` in `spirvEmitterPvStore.cpp`). The `capability_geometry` mutant exists to keep the pixel shader from asking for Geometry. Even so, this harness still enables `geometryShader` and never enables `tessellationShader`. The Vulkan spec does not allow a shader module to declare the Tessellation capability while `tessellationShader` is off. MoltenVK can accept this without an error, but validation layers will report it. It also means the harness no longer uses the same device features as the renderer, even though the file header says it uses the renderer's setup. The comment on line 382 is out of date for the same reason. <details> <summary>🐛 Proposed fix</summary> ```diff - features.geometryShader = supported.geometryShader; // PrimitiveId in the PS needs the Geometry capability + Check(supported.tessellationShader, "device lacks tessellationShader (PrimitiveId in the PS needs the Tessellation capability)"); + features.tessellationShader = VK_TRUE; // PrimitiveId in the PS uses the Tessellation capability ``` </details> <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion features.shaderClipDistance = supported.shaderClipDistance; // the emitted VS has a clip guard Check(supported.tessellationShader, "device lacks tessellationShader (PrimitiveId in the PS needs the Tessellation capability)"); features.tessellationShader = VK_TRUE; // PrimitiveId in the PS uses the Tessellation capability ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:4c380956e459c68bf1b8e5c8 --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Confirmed as addressed by @⁠wuboo <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-12 10:15 UTC · original · reviewed

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 71bf51c1-62fe-4ff4-b286-04ca9d5ab0ab
📥 Commits

Reviewing files that changed from the base of the PR and between d305947c013b60e410a52a05b54feb3b405b3aa0 and 82f328b78974c5957965191217944b6170d24813.

📒 Files selected for processing (10)
  • CMakeLists.txt
  • src/graphics/host_gpu/renderer/perVertexVsStore.h
  • src/graphics/host_gpu/renderer/perVertexVsStoreRuntime.cpp
  • src/graphics/host_gpu/renderer/perVertexVsStoreRuntime.h
  • src/graphics/presentation/window/vulkanWindow.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterPvStore.cpp
  • tests/PerVertexVsStoreGpuTests.cpp
  • tests/PerVertexVsStoreMutants.cmake
  • tests/PerVertexVsStoreTests.cpp
  • tests/shaderCfgTests.cpp

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 5 remain after this review.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-12 10:15 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1441#pullrequestreview-5489338938) · **reviewed** **Actionable comments posted: 1** --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> - **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `71bf51c1-62fe-4ff4-b286-04ca9d5ab0ab` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between d305947c013b60e410a52a05b54feb3b405b3aa0 and 82f328b78974c5957965191217944b6170d24813. </details> <details> <summary>📒 Files selected for processing (10)</summary> * `CMakeLists.txt` * `src/graphics/host_gpu/renderer/perVertexVsStore.h` * `src/graphics/host_gpu/renderer/perVertexVsStoreRuntime.cpp` * `src/graphics/host_gpu/renderer/perVertexVsStoreRuntime.h` * `src/graphics/presentation/window/vulkanWindow.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterPvStore.cpp` * `tests/PerVertexVsStoreGpuTests.cpp` * `tests/PerVertexVsStoreMutants.cmake` * `tests/PerVertexVsStoreTests.cpp` * `tests/shaderCfgTests.cpp` </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 5 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=2ae76f13-9dc3-4f14-8fc1-8864a39e7480 attempt=481719bd-ed42-473d-a0ab-095932357849 batch=1/1 -->
@ -0,0 +179,4 @@
// Distinct pipeline-cache identity from the PerVertexKHR variants of the same programs.
value.graphics.vertex[0].id |= 1ull << 61;
value.graphics.pixel.id |= 1ull << 61;
value.graphics.pv_store_layout = PvVsStoreSetLayout(graphics);
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-12 10:16 UTC · original

@wuboo Thanks for fixing this. The teardown you describe addresses the module and descriptor-set-layout leaks and clears the cached handles. The shutdown order keeps the device alive during cleanup.

Validation-layer shutdown testing remains unverified.


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

✅ Review thread resolved.

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-12 10:16 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1441#discussion_r4246887496) `@wuboo` Thanks for fixing this. The teardown you describe addresses the module and descriptor-set-layout leaks and clears the cached handles. The shutdown order keeps the device alive during cleanup. Validation-layer shutdown testing remains unverified. --- <!-- This is an auto-generated comment: tweet message by coderabbit.ai --> If you found this review helpful, would you consider giving us a shout-out on [X](https://twitter.com/intent/tweet?related=CodeRabbitAI&text=Vulkan%20cleanup%20matters%3A%20%40coderabbitai%20caught%20leaked%20shader%20modules%20and%20set%20layouts%20that%20could%20abort%20validation-enabled%20shutdown.%20Try%20CodeRabbit%20for%20actionable%20reviews!%20%F0%9F%A9%BA%E2%9C%85&url=https%3A%2F%2Fgithub.com%2FKytyPS5%2FKytyPS5%2Fpull%2F1441%23discussion_r4245412074)? Thank you for using CodeRabbit! <!-- end of auto-generated comment: tweet message by coderabbit.ai --> ✅ Review thread resolved. _You are interacting with an AI system._ <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-12 10:18 UTC · original
On src/graphics/shader/recompiler/backend/spirv/spirvEmitterPvStore.cpp line 157 (outdated):

@@ -0,0 +1,217 @@
+#include "graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h"
+
+// VS-store: the guest VS stores its PerVertex parameters to cap[record * stride +
+// slot]; the guest PS reads the three corners of its primitive back. The record arithmetic mirrors
+// graphics/host_gpu/renderer/perVertexVsStore.h (PvVsStoreVertexRecord / PvVsStoreCornerRecord).
+
+namespace Libs::Graphics::ShaderRecompiler::Spirv::Emitter {
+
+namespace {
+
+bool IsVertex(const EmitterState& state) {
+	return state.pv_store->role == PvStoreInfo::Role::Vertex;
+}
+
+uint32_t U(EmitterState& state, spv::Op op, uint32_t lhs, uint32_t rhs) {
+	return Binary(state, op, TypeU32(state), lhs, rhs);
+}
+
+uint32_t C(EmitterState& state, uint32_t value) {
+	return ConstantU32(state, value);
+}
+
+uint32_t Push(EmitterState& state, uint32_t dword) {
+	const auto pointer = state.builder.AllocateId();
+	state.builder.AddFunction(spv::OpAccessChain, TypePushConstantElementPointer(state), pointer,
+	                          state.push_constant_variable, C(state, 1), C(state, dword));
+	const auto value = state.builder.AllocateId();
+	state.builder.AddFunction(spv::OpLoad, TypeU32(state), value, pointer);
+	return value;
+}
+
+uint32_t LoadSigned(EmitterState& state, uint32_t variable) {
+	const auto value = state.builder.AllocateId();
+	const auto bits  = state.builder.AllocateId();
+	state.builder.AddFunction(spv::OpLoad, TypeI32(state), value, variable);
+	state.builder.AddFunction(spv::OpBitcast, TypeU32(state), bits, value);
+	return bits;
+}
+
+// base + (instance - first_instance) * span + (vertex - first)
+uint32_t Record(EmitterState& state, uint32_t instance, uint32_t vertex) {
+	const auto relative_instance =
+	    U(state, spv::OpISub, instance, Push(state, kPvPushFirstInstance));
+	const auto instance_part   = U(state, spv::OpIMul, relative_instance, Push(state, kPvPushSpan));
+	const auto relative_vertex = U(state, spv::OpISub, vertex, Push(state, kPvPushFirst));
+	return U(state, spv::OpIAdd, U(state, spv::OpIAdd, Push(state, kPvPushBase), instance_part),
+	         relative_vertex);
+}
+
+uint32_t CapComponentPointer(EmitterState& state, uint32_t record, uint32_t slot,
+                             uint32_t component) {
+	// stride 0 = the stride comes with the draw (the two variants are emitted independently).
+	constexpr uint32_t kStrideDword = kPvPushStride;
+	const auto         stride       = state.pv_store->record_stride_vec4 != 0
+	                                      ? C(state, state.pv_store->record_stride_vec4)
+	                                      : Push(state, kStrideDword);
+	const auto         element =
+	    U(state, spv::OpIAdd, U(state, spv::OpIMul, record, stride), C(state, slot));
+	const auto pointer = state.builder.AllocateId();
+	if (component == UINT32_MAX) {
+		state.builder.AddFunction(
+		    spv::OpAccessChain,
+		    TypePointer(state, spv::StorageClassStorageBuffer, TypeU32Vector(state, 4)), pointer,
+		    state.pv_cap_buffer, C(state, 0), element);
+	} else {
+		state.builder.AddFunction(
+		    spv::OpAccessChain, TypePointer(state, spv::StorageClassStorageBuffer, TypeU32(state)),
+		    pointer, state.pv_cap_buffer, C(state, 0), element, C(state, component));
+	}
+	return pointer;
+}
+
+uint32_t SlotOf(const EmitterState& state, uint32_t host_location) {
+	if (state.pv_store->record_stride_vec4 == 0) {
+		// Dynamic stride: slot == host location. Location 31 carries the instance index: a stage
+		// that uses it is still emitted (the location is recorded) and ClassifyPvVsStoreInterface
+		// rejects the pair.
+		EXIT_IF(host_location > kPvVsStoreInstanceLocation);
+		if (state.pv_store->location_mask != nullptr)
+			*state.pv_store->location_mask |= 1u << host_location;
+		return host_location;
+	}
+	const auto slot = state.pv_store->parameter_slots.find(host_location);
+	EXIT_IF(slot == state.pv_store->parameter_slots.end() ||
+	        slot->second >= state.pv_store->record_stride_vec4);
+	return slot->second;
+}
+
+// Index value of element `element` (16- or 32-bit buffer, chosen by the push flag).
+uint32_t FetchIndex(EmitterState& state, uint32_t element) {
+	const auto index32 =
+	    Binary(state, spv::OpINotEqual, TypeBool(state), Push(state, kPvPushIndex32), C(state, 0));
+	const auto word   = Select(state, TypeU32(state), index32, element,
+	                           U(state, spv::OpShiftRightLogical, element, C(state, 1)));
+	const auto length = state.builder.AllocateId();
+	state.builder.AddFunction(spv::OpArrayLength, TypeU32(state), length, state.pv_index_buffer, 0);
+	const auto clamped = EmitGlsl<GLSLstd450UMin, IR::Type::U32>(
+	    state, word, U(state, spv::OpISub, length, C(state, 1)));
+	const auto pointer = state.builder.AllocateId();
+	state.builder.AddFunction(spv::OpAccessChain,
+	                          TypePointer(state, spv::StorageClassStorageBuffer, TypeU32(state)),
+	                          pointer, state.pv_index_buffer, C(state, 0), clamped);
+	const auto raw = state.builder.AllocateId();
+	state.builder.AddFunction(spv::OpLoad, TypeU32(state), raw, pointer);
+	const auto half_shift = U(state, spv::OpShiftLeftLogical,
+	                          U(state, spv::OpBitwiseAnd, element, C(state, 1)), C(state, 4));
+	const auto shifted    = U(state, spv::OpShiftRightLogical, raw,
+	                          Select(state, TypeU32(state), index32, C(state, 0), half_shift));
+	return U(state, spv::OpBitwiseAnd, shifted,
+	         Select(state, TypeU32(state), index32, C(state, 0xffffffffu), C(state, 0xffffu)));
+}
+
+} // namespace
+
+void DefinePvStore(EmitterState& state) {
+	const bool vertex = IsVertex(state);
+	const auto uvec4  = TypeU32Vector(state, 4);
+	const auto array  = state.builder.DecoratedType(
+	    spv::OpTypeRuntimeArray, {{spv::OpDecorate, {spv::DecorationArrayStride, 16}}}, uvec4);
+	const auto block =
+	    state.builder.DecoratedType(spv::OpTypeStruct,
+	                                {{spv::OpMemberDecorate, {0, spv::DecorationOffset, 0}},
+	                                 {spv::OpDecorate, {spv::DecorationBlock}}},
+	                                array);
+	state.pv_cap_buffer = state.builder.DefineGlobalVariable(
+	    TypePointer(state, spv::StorageClassStorageBuffer, block), spv::StorageClassStorageBuffer);
+	state.builder.AddName(state.pv_cap_buffer, "pv_cap");
+	state.builder.AddAnnotation(spv::OpDecorate, state.pv_cap_buffer, spv::DecorationDescriptorSet,
+	                            1);
+	state.builder.AddAnnotation(spv::OpDecorate, state.pv_cap_buffer, spv::DecorationBinding, 0);
+	if (!vertex)
+		state.builder.AddAnnotation(spv::OpDecorate, state.pv_cap_buffer,
+		                            spv::DecorationNonWritable);
+	if (state.pv_store->coherent) {
+		state.builder.AddAnnotation(spv::OpDecorate, state.pv_cap_buffer, spv::DecorationCoherent);
+	}
+	if (!vertex) {
+		const auto words = state.builder.DecoratedType(
+		    spv::OpTypeRuntimeArray, {{spv::OpDecorate, {spv::DecorationArrayStride, 4}}},
+		    TypeU32(state));
+		const auto index_block =
+		    state.builder.DecoratedType(spv::OpTypeStruct,
+		                                {{spv::OpMemberDecorate, {0, spv::DecorationOffset, 0}},
+		                                 {spv::OpDecorate, {spv::DecorationBlock}}},
+		                                words);
+		state.pv_index_buffer = state.builder.DefineGlobalVariable(
+		    TypePointer(state, spv::StorageClassStorageBuffer, index_block),
+		    spv::StorageClassStorageBuffer);
+		state.builder.AddName(state.pv_index_buffer, "pv_indices");
+		state.builder.AddAnnotation(spv::OpDecorate, state.pv_index_buffer,
+		                            spv::DecorationDescriptorSet, 1);
+		state.builder.AddAnnotation(spv::OpDecorate, state.pv_index_buffer, spv::DecorationBinding,
+		                            1);
+		state.builder.AddAnnotation(spv::OpDecorate, state.pv_index_buffer,
+		                            spv::DecorationNonWritable);
+		// PrimitiveId in a fragment shader needs the Geometry capability.
+		state.builder.RequireCapability(spv::CapabilityGeometry);

@wuboo Thanks for the clarification.

The reported Tessellation change addresses the capability concern. The regression check and capability mutant cover that change.

I agree that the barycentric dependency is shared with existing custom VINTRP shaders, rather than introduced by VS-store. A separate renderer-wide change with GPU and validation-layer testing is appropriate. The dependency remains unresolved, so this combined finding stays open.

Would you like me to open a follow-up issue for the macOS barycentric-feature dependency?


✏️ Learnings added
Learnt from: wuboo
Repo: KytyPS5/KytyPS5 PR: 1441
File: src/graphics/shader/recompiler/backend/spirv/spirvEmitterPvStore.cpp:0-0
Timestamp: 2026-10-12T10:18:27.325Z
Learning: In KytyPS5, custom VINTRP pixel shaders already receive FragmentBarycentricKHR and BaryCoordKHR from the SPIR-V emitter without platform conditioning. The VS-store path shares this dependency. macOS device creation in src/graphics/presentation/window/vulkanWindow.cpp does not request fragmentShaderBarycentric. Changes to this feature setup affect the whole renderer and require separate GPU and validation-layer testing.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-12 10:18 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1441#discussion_r4246905633) On `src/graphics/shader/recompiler/backend/spirv/spirvEmitterPvStore.cpp` line 157 (outdated): ```diff @@ -0,0 +1,217 @@ +#include "graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h" + +// VS-store: the guest VS stores its PerVertex parameters to cap[record * stride + +// slot]; the guest PS reads the three corners of its primitive back. The record arithmetic mirrors +// graphics/host_gpu/renderer/perVertexVsStore.h (PvVsStoreVertexRecord / PvVsStoreCornerRecord). + +namespace Libs::Graphics::ShaderRecompiler::Spirv::Emitter { + +namespace { + +bool IsVertex(const EmitterState& state) { + return state.pv_store->role == PvStoreInfo::Role::Vertex; +} + +uint32_t U(EmitterState& state, spv::Op op, uint32_t lhs, uint32_t rhs) { + return Binary(state, op, TypeU32(state), lhs, rhs); +} + +uint32_t C(EmitterState& state, uint32_t value) { + return ConstantU32(state, value); +} + +uint32_t Push(EmitterState& state, uint32_t dword) { + const auto pointer = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpAccessChain, TypePushConstantElementPointer(state), pointer, + state.push_constant_variable, C(state, 1), C(state, dword)); + const auto value = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpLoad, TypeU32(state), value, pointer); + return value; +} + +uint32_t LoadSigned(EmitterState& state, uint32_t variable) { + const auto value = state.builder.AllocateId(); + const auto bits = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpLoad, TypeI32(state), value, variable); + state.builder.AddFunction(spv::OpBitcast, TypeU32(state), bits, value); + return bits; +} + +// base + (instance - first_instance) * span + (vertex - first) +uint32_t Record(EmitterState& state, uint32_t instance, uint32_t vertex) { + const auto relative_instance = + U(state, spv::OpISub, instance, Push(state, kPvPushFirstInstance)); + const auto instance_part = U(state, spv::OpIMul, relative_instance, Push(state, kPvPushSpan)); + const auto relative_vertex = U(state, spv::OpISub, vertex, Push(state, kPvPushFirst)); + return U(state, spv::OpIAdd, U(state, spv::OpIAdd, Push(state, kPvPushBase), instance_part), + relative_vertex); +} + +uint32_t CapComponentPointer(EmitterState& state, uint32_t record, uint32_t slot, + uint32_t component) { + // stride 0 = the stride comes with the draw (the two variants are emitted independently). + constexpr uint32_t kStrideDword = kPvPushStride; + const auto stride = state.pv_store->record_stride_vec4 != 0 + ? C(state, state.pv_store->record_stride_vec4) + : Push(state, kStrideDword); + const auto element = + U(state, spv::OpIAdd, U(state, spv::OpIMul, record, stride), C(state, slot)); + const auto pointer = state.builder.AllocateId(); + if (component == UINT32_MAX) { + state.builder.AddFunction( + spv::OpAccessChain, + TypePointer(state, spv::StorageClassStorageBuffer, TypeU32Vector(state, 4)), pointer, + state.pv_cap_buffer, C(state, 0), element); + } else { + state.builder.AddFunction( + spv::OpAccessChain, TypePointer(state, spv::StorageClassStorageBuffer, TypeU32(state)), + pointer, state.pv_cap_buffer, C(state, 0), element, C(state, component)); + } + return pointer; +} + +uint32_t SlotOf(const EmitterState& state, uint32_t host_location) { + if (state.pv_store->record_stride_vec4 == 0) { + // Dynamic stride: slot == host location. Location 31 carries the instance index: a stage + // that uses it is still emitted (the location is recorded) and ClassifyPvVsStoreInterface + // rejects the pair. + EXIT_IF(host_location > kPvVsStoreInstanceLocation); + if (state.pv_store->location_mask != nullptr) + *state.pv_store->location_mask |= 1u << host_location; + return host_location; + } + const auto slot = state.pv_store->parameter_slots.find(host_location); + EXIT_IF(slot == state.pv_store->parameter_slots.end() || + slot->second >= state.pv_store->record_stride_vec4); + return slot->second; +} + +// Index value of element `element` (16- or 32-bit buffer, chosen by the push flag). +uint32_t FetchIndex(EmitterState& state, uint32_t element) { + const auto index32 = + Binary(state, spv::OpINotEqual, TypeBool(state), Push(state, kPvPushIndex32), C(state, 0)); + const auto word = Select(state, TypeU32(state), index32, element, + U(state, spv::OpShiftRightLogical, element, C(state, 1))); + const auto length = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpArrayLength, TypeU32(state), length, state.pv_index_buffer, 0); + const auto clamped = EmitGlsl<GLSLstd450UMin, IR::Type::U32>( + state, word, U(state, spv::OpISub, length, C(state, 1))); + const auto pointer = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpAccessChain, + TypePointer(state, spv::StorageClassStorageBuffer, TypeU32(state)), + pointer, state.pv_index_buffer, C(state, 0), clamped); + const auto raw = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpLoad, TypeU32(state), raw, pointer); + const auto half_shift = U(state, spv::OpShiftLeftLogical, + U(state, spv::OpBitwiseAnd, element, C(state, 1)), C(state, 4)); + const auto shifted = U(state, spv::OpShiftRightLogical, raw, + Select(state, TypeU32(state), index32, C(state, 0), half_shift)); + return U(state, spv::OpBitwiseAnd, shifted, + Select(state, TypeU32(state), index32, C(state, 0xffffffffu), C(state, 0xffffu))); +} + +} // namespace + +void DefinePvStore(EmitterState& state) { + const bool vertex = IsVertex(state); + const auto uvec4 = TypeU32Vector(state, 4); + const auto array = state.builder.DecoratedType( + spv::OpTypeRuntimeArray, {{spv::OpDecorate, {spv::DecorationArrayStride, 16}}}, uvec4); + const auto block = + state.builder.DecoratedType(spv::OpTypeStruct, + {{spv::OpMemberDecorate, {0, spv::DecorationOffset, 0}}, + {spv::OpDecorate, {spv::DecorationBlock}}}, + array); + state.pv_cap_buffer = state.builder.DefineGlobalVariable( + TypePointer(state, spv::StorageClassStorageBuffer, block), spv::StorageClassStorageBuffer); + state.builder.AddName(state.pv_cap_buffer, "pv_cap"); + state.builder.AddAnnotation(spv::OpDecorate, state.pv_cap_buffer, spv::DecorationDescriptorSet, + 1); + state.builder.AddAnnotation(spv::OpDecorate, state.pv_cap_buffer, spv::DecorationBinding, 0); + if (!vertex) + state.builder.AddAnnotation(spv::OpDecorate, state.pv_cap_buffer, + spv::DecorationNonWritable); + if (state.pv_store->coherent) { + state.builder.AddAnnotation(spv::OpDecorate, state.pv_cap_buffer, spv::DecorationCoherent); + } + if (!vertex) { + const auto words = state.builder.DecoratedType( + spv::OpTypeRuntimeArray, {{spv::OpDecorate, {spv::DecorationArrayStride, 4}}}, + TypeU32(state)); + const auto index_block = + state.builder.DecoratedType(spv::OpTypeStruct, + {{spv::OpMemberDecorate, {0, spv::DecorationOffset, 0}}, + {spv::OpDecorate, {spv::DecorationBlock}}}, + words); + state.pv_index_buffer = state.builder.DefineGlobalVariable( + TypePointer(state, spv::StorageClassStorageBuffer, index_block), + spv::StorageClassStorageBuffer); + state.builder.AddName(state.pv_index_buffer, "pv_indices"); + state.builder.AddAnnotation(spv::OpDecorate, state.pv_index_buffer, + spv::DecorationDescriptorSet, 1); + state.builder.AddAnnotation(spv::OpDecorate, state.pv_index_buffer, spv::DecorationBinding, + 1); + state.builder.AddAnnotation(spv::OpDecorate, state.pv_index_buffer, + spv::DecorationNonWritable); + // PrimitiveId in a fragment shader needs the Geometry capability. + state.builder.RequireCapability(spv::CapabilityGeometry); ``` `@wuboo` Thanks for the clarification. The reported `Tessellation` change addresses the capability concern. The regression check and capability mutant cover that change. I agree that the barycentric dependency is shared with existing custom VINTRP shaders, rather than introduced by VS-store. A separate renderer-wide change with GPU and validation-layer testing is appropriate. The dependency remains unresolved, so this combined finding stays open. Would you like me to open a follow-up issue for the macOS barycentric-feature dependency? --- <details> <summary>✏️ Learnings added</summary> ``` Learnt from: wuboo Repo: KytyPS5/KytyPS5 PR: 1441 File: src/graphics/shader/recompiler/backend/spirv/spirvEmitterPvStore.cpp:0-0 Timestamp: 2026-10-12T10:18:27.325Z Learning: In KytyPS5, custom VINTRP pixel shaders already receive FragmentBarycentricKHR and BaryCoordKHR from the SPIR-V emitter without platform conditioning. The VS-store path shares this dependency. macOS device creation in src/graphics/presentation/window/vulkanWindow.cpp does not request fragmentShaderBarycentric. Changes to this feature setup affect the whole renderer and require separate GPU and validation-layer testing. ``` > Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure [review instructions](https://docs.coderabbit.ai/guides/review-instructions). You can manage existing learnings in the [app](https://app.coderabbit.ai/learnings). </details> --- <!-- This is an auto-generated comment: tweet message by coderabbit.ai --> If you found this review helpful, would you consider giving us a shout-out on [X](https://twitter.com/intent/tweet?related=CodeRabbitAI&text=VS-store%20shaders%20need%20%60CapabilityTessellation%60%20for%20%60PrimitiveId%60%20when%20geometry%20is%20disabled%3B%20barycentric%20support%20remains%20a%20platform-wide%20gap.%20Try%20%40coderabbitai%20to%20catch%20nuanced%20Vulkan%20issues%20%F0%9F%90%87&url=https%3A%2F%2Fgithub.com%2FKytyPS5%2FKytyPS5%2Fpull%2F1441%23discussion_r4245412084)? Thank you for using CodeRabbit! <!-- end of auto-generated comment: tweet message by coderabbit.ai --> _You are interacting with an AI system._ <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠theantipopau on GitHub · 2026-10-12 11:09 UTC · original · approved these changes

Reviewed only the two wiring commits (8a389ff8, 82f328b7) per the PR note; #1440's emitter/harness commits are out of scope here.

Wiring correctness checks against main:

  • Gating: TryPvVsStoreDraw runs before bindings are prepared, correctly rejects mesh stages and non-per-vertex pairs, and every DecidePvVsStore fallback keeps the existing path and just counts the reason (CountPvVsStoreDraw) — no draws regress on other drivers.
  • Ordering hazard handled: Touch(region) happens at record time before BindPvVsStore, matching the stated reason (resource prep can flush the scheduler between Place and the draw); the slab's tick-based reuse rules live in the runtime.
  • Index handling: host copies are padded to a whole word and zero-filled in PrepareIndexBuffer (needed since the PS reads uint32), the guest path re-ObtainBuffers to compute tail_fits from the buffer the cache hands out, and unaligned guest addresses remain on PerVertexKHR — conservative and correct.
  • Pipeline: pushing use_pv_store ? pv_store.programs->graphics : state.programs into GetGraphicsPipeline drives the 2-set layout (PvVsStorePushRangeBytes computes the larger push range only when the variant layout exists), so per-variant pipelines get distinct identity.
  • 82f328b7's shutdown destroys modules/set layout under the same lock before device teardown and skips non-Use pairs that borrowed graphics — matches object-lifetime requirements.

One observation, non-blocking: ResolvePvVsStoreEnabled is called in VulkanCreateDevice every device creation but only reads its env/driverID inputs — fine, just noting the one-line follow-up when #959 lands is deliberate.

CI green on all platforms; the path is default-off outside MoltenVK-without-barycentric, so risk on other drivers is nil. Murphy's-honest approval: renderer wiring itself is Vulkan-device-dependent and doesn't have CPU coverage, but the tested seams (scan/decide/push-block) are CPU-consumed in the harness.

**@⁠theantipopau** on GitHub · 2026-10-12 11:09 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1441#pullrequestreview-5489888063) · **approved these changes** Reviewed only the two wiring commits (`8a389ff8`, `82f328b7`) per the PR note; #1440's emitter/harness commits are out of scope here. Wiring correctness checks against main: - Gating: `TryPvVsStoreDraw` runs before bindings are prepared, correctly rejects mesh stages and non-per-vertex pairs, and every `DecidePvVsStore` fallback keeps the existing path and just counts the reason (`CountPvVsStoreDraw`) — no draws regress on other drivers. - Ordering hazard handled: `Touch(region)` happens at record time before `BindPvVsStore`, matching the stated reason (resource prep can flush the scheduler between `Place` and the draw); the slab's tick-based reuse rules live in the runtime. - Index handling: host copies are padded to a whole word and zero-filled in `PrepareIndexBuffer` (needed since the PS reads `uint32`), the guest path re-`ObtainBuffer`s to compute `tail_fits` from the buffer the cache hands out, and unaligned guest addresses remain on PerVertexKHR — conservative and correct. - Pipeline: pushing `use_pv_store ? pv_store.programs->graphics : state.programs` into `GetGraphicsPipeline` drives the 2-set layout (`PvVsStorePushRangeBytes` computes the larger push range only when the variant layout exists), so per-variant pipelines get distinct identity. - `82f328b7`'s shutdown destroys modules/set layout under the same lock before device teardown and skips non-`Use` pairs that borrowed `graphics` — matches object-lifetime requirements. One observation, non-blocking: `ResolvePvVsStoreEnabled` is called in `VulkanCreateDevice` every device creation but only reads its env/`driverID` inputs — fine, just noting the one-line follow-up when #959 lands is deliberate. CI green on all platforms; the path is default-off outside MoltenVK-without-barycentric, so risk on other drivers is nil. Murphy's-honest approval: renderer wiring itself is Vulkan-device-dependent and doesn't have CPU coverage, but the tested seams (scan/decide/push-block) are CPU-consumed in the harness.
Author
Owner

@⁠wuboo on GitHub · 2026-10-12 13:54 UTC · original
On tests/PerVertexVsStoreGpuTests.cpp line 382 (outdated):

@@ -0,0 +1,751 @@
+// GPU harness for KYTY_PV_VSSTORE (graphics/host_gpu/renderer/perVertexVsStore.h). The real SPIR-V
+// emitter produces the VS-store VS and PS from an IR vertex shader and an ISA pixel shader, and the
+// pair is drawn on the host GPU (MoltenVK) with the exact descriptor/push layout of the renderer:
+//   set 0 = empty, set 1 = {cap SSBO (VS|FS), guest index SSBO (FS)}, push = native data + 8 dwords.
+// Checks (bit for bit, no tolerance):
+//   1. image: every probed pixel equals the PerVertexKHR semantics computed on the CPU from the vertex
+//      data, the index buffer and the draw parameters (corner 0/1/2 read through P0/P10/P20),
+//   2. cap: the records the VS wrote hold {gl_VertexIndex, gl_InstanceIndex} of the cases, which
+//      settles whether gl_VertexIndex includes vertex_offset and gl_InstanceIndex first_instance.
+// Cases: 16-bit and 32-bit indices, vertex_offset > 0 and < 0, first_instance != 0, 2 instances, an index
+// buffer bound at an offset that is not a multiple of minStorageBufferOffsetAlignment.
+// Run: per_vertex_vsstore_gpu_tests [--dump] [--stress]  (--stress: 2M triangles x 2..4 instances, parameter-buffer overflow)
+//   --dump needs no GPU: it prints the emitted SPIR-V.
+// The result is compared with the CPU model of the per-vertex semantics. The mutants built from
+// tests/PerVertexVsStoreMutants.cmake (corner 0/2 swapped, index range not rounded) must fail it.
+
+#include "common/emulatorConfig.h"
+#include "common/logging/log.h"
+#include "common/subsystems.h"
+#include "common/threads.h"
+#include "graphics/host_gpu/renderer/perVertexVsStore.h"
+#include "graphics/shader/recompiler/ShaderRecompiler.h"
+#include "graphics/shader/recompiler/backend/spirv/SpirvEmitter.h"
+#include "graphics/shader/recompiler/ir/IREmitter.h"
+#include "graphics/shader/recompiler/ir/ShaderIR.h"
+#include "graphics/shader/recompiler/ir/passes/ResourceTracking.h"
+#include "graphics/shader/shader.h"
+#include "graphics/shader/shaderCompiler.h"
+
+#include <spirv-tools/libspirv.hpp>
+#include <vulkan/vulkan.h>
+
+#include <dlfcn.h>
+
+#include <algorithm>
+#include <array>
+#include <cstdint>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <span>
+#include <string>
+#include <vector>
+
+namespace Libs::Graphics {
+namespace {
+
+using namespace ShaderRecompiler;
+
+bool g_stress = false; // --stress: the >= 2M triangle cases
+
+[[noreturn]] void Fail(const char* message) {
+	std::fprintf(stderr, "per-vertex-vsstore-gpu-tests: FAILED: %s\n", message);
+	std::exit(1);
+}
+
+void Check(bool ok, const char* message) {
+	if (!ok) Fail(message);
+}
+
+void CheckVk(VkResult result, const char* what) {
+	if (result != VK_SUCCESS) {
+		std::fprintf(stderr, "per-vertex-vsstore-gpu-tests: FAILED: %s (VkResult %d)\n", what, static_cast<int>(result));
+		std::exit(1);
+	}
+}
+
+constexpr uint32_t EncodeSopp(uint32_t opcode, uint32_t simm = 0) {
+	return (0x17fu << 23u) | ((opcode & 0x7fu) << 16u) | (simm & 0xffffu);
+}
+constexpr uint32_t EncodeVintrp(uint32_t opcode, uint32_t vdst, uint32_t attr, uint32_t chan, uint32_t vsrc) {
+	return (0x32u << 26u) | ((opcode & 0x3u) << 16u) | ((vdst & 0xffu) << 18u) | ((attr & 0x3fu) << 10u) |
+	       ((chan & 0x3u) << 8u) | (vsrc & 0xffu);
+}
+constexpr uint32_t EncodeExp0(uint32_t target, uint32_t en) {
+	return (0x3eu << 26u) | ((target & 0x3fu) << 4u) | (en & 0xfu) | (1u << 11u);
+}
+constexpr uint32_t EncodeExp1(uint32_t a, uint32_t b, uint32_t c, uint32_t d) {
+	return (a & 0xffu) | ((b & 0xffu) << 8u) | ((c & 0xffu) << 16u) | ((d & 0xffu) << 24u);
+}
+
+void EnsureConfigInitialized() {
+	static bool initialized = false;
+	if (initialized) return;
+	static Common::Subsystems subsystems;
+	Common::InitializeThreads();
+	subsystems.Initialize<Config::Lifecycle>();
+	Config::ConfigOptions options;
+	options.printf_direction = Config::LogDirection::Silent;
+	Config::Load(options);
+	subsystems.Initialize<Log::Lifecycle>();
+	ShaderInit();
+	initialized = true;
+}
+
+// ---- shaders -------------------------------------------------------------------------------------
+
+struct Shaders {
+	std::vector<uint32_t> vs;
+	std::vector<uint32_t> ps;
+	uint32_t              stride_vec4 = 0;
+};
+
+// VS: position = attr0, param0 = attr1 with `+ instance` added to the bits of x (a 1 ulp difference
+// per instance shows a record of the wrong instance), param1 = {gl_VertexIndex, gl_InstanceIndex, 0, 0}.
+// PS: out = {corner0.x, corner1.y, corner2.z, corner0.w} of param0.
+Shaders BuildShaders() {
+	using IR::Value;
+	using O = IR::ValueOpcode;
+	Shaders out;
+
+	IR::Program vs;
+	vs.stage                  = ShaderType::Vertex;
+	vs.wave_size              = 64;
+	vs.srt_plan_complete      = vs.resource_tracking_complete = vs.shader_info_complete = true;
+	vs.block_storage.push_back(std::make_unique<IR::Block>());
+	vs.blocks.push_back(vs.block_storage.back().get());
+	vs.info.inputs  = {{IR::StageInputKind::VertexIndex},
+	                   {IR::StageInputKind::InstanceIndex},
+	                   {IR::StageInputKind::Parameter, 0, 4},
+	                   {IR::StageInputKind::Parameter, 1, 4}};
+	vs.info.outputs = {{IR::StageOutputKind::Position},
+	                   {IR::StageOutputKind::Parameter, 0, 0},
+	                   {IR::StageOutputKind::Parameter, 1, 1}};
+	vs.export_info  = {{.kind = IR::ExportTargetKind::Position, .en = 15},
+	                   {.kind = IR::ExportTargetKind::Parameter, .index = 0, .en = 15},
+	                   {.kind = IR::ExportTargetKind::Parameter, .index = 1, .en = 15}};
+	IR::IREmitter emit(vs.blocks.front());
+	const auto vertex   = emit.Emit(O::GetBuiltin, {Value(static_cast<uint32_t>(IR::StageInputKind::VertexIndex)), Value(0u)});
+	const auto instance = emit.Emit(O::GetBuiltin, {Value(static_cast<uint32_t>(IR::StageInputKind::InstanceIndex)), Value(0u)});
+	std::array<Value, 4> position, color;
+	for (uint32_t c = 0; c < 4; c++) position[c] = emit.Emit(O::GetAttribute, {Value(0u), Value(c)});
+	for (uint32_t c = 0; c < 4; c++) color[c] = emit.Emit(O::GetAttribute, {Value(1u), Value(c)});
+	const auto pos = emit.Emit(O::CompositeConstructU32x4, {position[0], position[1], position[2], position[3]});
+	emit.Emit(O::SetAttribute, {pos, Value(true)}, IR::ExportFlags {0});
+	const auto x      = emit.Emit(O::IAdd32, {color[0], instance});
+	const auto param0 = emit.Emit(O::CompositeConstructU32x4, {x, color[1], color[2], color[3]});
+	emit.Emit(O::SetAttribute, {param0, Value(true)}, IR::ExportFlags {1});
+	const auto param1 = emit.Emit(O::CompositeConstructU32x4, {vertex, instance, Value(0u), Value(0u)});
+	emit.Emit(O::SetAttribute, {param1, Value(true)}, IR::ExportFlags {2});
+	static const ShaderVertexInputInfo vertex_info {};
+	ShaderStageInputInfo               vs_input {.vertex = &vertex_info};
+
+	uint32_t vs_mask = 0;
+	Spirv::PvStoreInfo vs_store;
+	vs_store.role          = Spirv::PvStoreInfo::Role::Vertex;
+	vs_store.coherent      = true;
+	vs_store.location_mask = &vs_mask;
+	out.vs                 = Spirv::EmitProgram(vs, vs_input, 0, &vs_store);
+
+	// PS (the interpolation setup of TestPvVsStoreEmission): v_interp_mov_f32 with P0 / P10 / P20.
+	const uint32_t ps_code[] = {EncodeVintrp(2, 12, 0, 0, 2), EncodeVintrp(2, 13, 0, 1, 0),
+	                            EncodeVintrp(2, 14, 0, 2, 1), EncodeVintrp(2, 15, 0, 3, 2),
+	                            EncodeExp0(0x00, 0xf),        EncodeExp1(12, 13, 14, 15),
+	                            EncodeSopp(0x01)};
+	static ShaderPixelInputInfo ps_info {};
+	ps_info.input_num                 = 1;
+	ps_info.ps_system_input_base      = 2;
+	ps_info.custom_interpolation_mask = 1;
+	ps_info.ps_perspective_center_vgpr = 0;
+	for (uint32_t i = 0; i < std::size(ps_info.interpolator_settings); i++) ps_info.interpolator_settings[i] = i;
+	ps_info.interpolator_settings[0] = 0x00000420u;
+	static const std::array<uint32_t, 64> user_data = [] {
+		std::array<uint32_t, 64> data {};
+		data[3] = 3u << 28u;
+		return data;
+	}();
+	CompileOptions options;
+	options.stage            = ShaderType::Pixel;
+	options.user_data        = user_data;
+	options.input_info.pixel = &ps_info;
+	auto translated          = TranslateProgram(ps_code, options);
+	auto plan                = IR::ExtractResourcePlan(translated.program);
+	IR::ResourceSnapshot       resources;
+	IR::ResourceSpecialization specialization;
+	const IR::SrtRuntime       runtime {.user_data = options.user_data,
+	                                    .shader_base = reinterpret_cast<uint64_t>(ps_code),
+	                                    .read_specialization_memory = [](void*, uint64_t, std::span<uint32_t>) { return false; }};
+	Check(IR::MaterializeResources(plan, runtime, resources, specialization), "PS resources did not materialize");
+	auto compiled = CompileProgram(std::move(translated), options, specialization, 0);
+	uint32_t ps_mask = 0;
+	Spirv::PvStoreInfo ps_store;
+	ps_store.role          = Spirv::PvStoreInfo::Role::Pixel;
+	ps_store.coherent      = true;
+	ps_store.location_mask = &ps_mask;
+	out.ps                 = Spirv::EmitProgram(compiled.program, options.input_info, 0, &ps_store);
+
+	Check(ClassifyPvVsStoreInterface(vs_mask, ps_mask) == PvVsStoreInterfaceVerdict::Use, "VS/PS pair is not a VS-store candidate");
+	out.stride_vec4 = PvVsStoreStrideFor(vs_mask);
+	if (out.stride_vec4 != 2) std::fprintf(stderr, "VS location mask %08x, PS location mask %08x\n", vs_mask, ps_mask);
+	Check(out.stride_vec4 == 2, "expected stride 2 (locations 0 and 1)");
+	spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_2);
+	Check(tools.Validate(out.vs), "VS-store VS does not validate");
+	Check(tools.Validate(out.ps), "VS-store PS does not validate");
+	return out;
+}
+
+// ---- scene (CPU model) ---------------------------------------------------------------------------
+
+constexpr uint32_t kDim      = 32; // render target
+constexpr uint32_t kCell     = 16; // one triangle per cell: 2x2 cells
+constexpr uint32_t kVertices = 24; // 4 triangles x 3 corners, plus 12 spare vertices for offsets
+constexpr uint32_t kStrideB  = 32; // float4 position, float4 color
+
+struct Vertex {
+	float position[4];
+	float color[4];
+};
+
+std::array<Vertex, kVertices> MakeVertices() {
+	std::array<Vertex, kVertices> v {};
+	for (uint32_t i = 0; i < kVertices; ++i) {
+		const uint32_t tri = (i / 3u) % 4u;
+		const uint32_t cx  = tri % 2u, cy = tri / 2u;
+		const float    x0  = static_cast<float>(cx * kCell), y0 = static_cast<float>(cy * kCell);
+		const float    px[3] = {x0 + 2.f, x0 + 14.f, x0 + 2.f};
+		const float    py[3] = {y0 + 2.f, y0 + 2.f, y0 + 14.f};
+		const uint32_t k     = i % 3u;
+		v[i].position[0] = px[k] / (kDim / 2.f) - 1.f;
+		v[i].position[1] = py[k] / (kDim / 2.f) - 1.f;
+		v[i].position[2] = 0.5f;
+		v[i].position[3] = 1.f;
+		// distinct, normal floats: any mix-up of a vertex, a corner or a component shows
+		v[i].color[0] = 1.0f + 0.03125f * static_cast<float>(i);
+		v[i].color[1] = 2.0f + 0.0625f * static_cast<float>(i);
+		v[i].color[2] = 3.0f + 0.125f * static_cast<float>(i);
+		v[i].color[3] = 4.0f + 0.25f * static_cast<float>(i);
+	}
+	return v;
+}
+
+struct Case {
+	const char*           name;
+	bool                  index32;
+	std::vector<uint32_t> indices;       // per triangle corner, relative to vertex_offset
+	int32_t               vertex_offset;
+	uint32_t              first_instance;
+	uint32_t              instance_count;
+	uint32_t              bind_byte_offset; // where the index data starts inside the index buffer
+};
+
+uint32_t Bits(float f) {
+	uint32_t u;
+	std::memcpy(&u, &f, 4);
+	return u;
+}
+
+// Expected pixel of triangle t of the draw: {corner0.x(+inst), corner1.y, corner2.z, corner0.w}.
+std::array<uint32_t, 4> ExpectedPixel(const std::array<Vertex, kVertices>& v, const Case& c, uint32_t tri) {
+	const uint32_t last_instance = c.first_instance + c.instance_count - 1;
+	const auto     vertex = [&](uint32_t corner) { return static_cast<uint32_t>(static_cast<int32_t>(c.indices[tri * 3 + corner]) + c.vertex_offset); };
+	std::array<uint32_t, 4> out {};
+	out[0] = Bits(v[vertex(0)].color[0]) + last_instance;
+	out[1] = Bits(v[vertex(1)].color[1]);
+	out[2] = Bits(v[vertex(2)].color[2]);
+	out[3] = Bits(v[vertex(0)].color[3]);
+	return out;
+}
+
+// ---- Vulkan --------------------------------------------------------------------------------------
+
+#define VK_FUNCS(X)                                                                                                        \
+	X(vkCreateDevice) X(vkGetDeviceProcAddr) X(vkEnumeratePhysicalDevices) X(vkGetPhysicalDeviceMemoryProperties)          \
+	X(vkGetPhysicalDeviceQueueFamilyProperties) X(vkGetPhysicalDeviceFeatures) X(vkGetPhysicalDeviceProperties)
+
+#define VK_DEVICE_FUNCS(X)                                                                                                 \
+	X(vkGetDeviceQueue) X(vkCreateBuffer) X(vkGetBufferMemoryRequirements) X(vkAllocateMemory) X(vkBindBufferMemory)      \
+	X(vkMapMemory) X(vkCreateDescriptorSetLayout) X(vkCreatePipelineLayout) X(vkCreateShaderModule)                         \
+	X(vkCreateGraphicsPipelines) X(vkCreateDescriptorPool) X(vkAllocateDescriptorSets) X(vkUpdateDescriptorSets)           \
+	X(vkCreateCommandPool) X(vkAllocateCommandBuffers) X(vkBeginCommandBuffer) X(vkEndCommandBuffer)                       \
+	X(vkCmdBindPipeline) X(vkCmdBindDescriptorSets) X(vkCmdPushConstants) X(vkCmdBeginRenderPass) X(vkCmdEndRenderPass)    \
+	X(vkCmdBindVertexBuffers) X(vkCmdBindIndexBuffer) X(vkCmdDrawIndexed) X(vkCmdCopyImageToBuffer) X(vkQueueSubmit)      \
+	X(vkQueueWaitIdle) X(vkCreateRenderPass) X(vkCreateFramebuffer) X(vkCreateImage) X(vkGetImageMemoryRequirements)       \
+	X(vkBindImageMemory) X(vkCreateImageView) X(vkCmdPipelineBarrier)
+
+#define DECLARE(name) PFN_##name name##_ = nullptr;
+VK_FUNCS(DECLARE)
+VK_DEVICE_FUNCS(DECLARE)
+#undef DECLARE
+
+struct Gpu {
+	VkInstance                       instance = VK_NULL_HANDLE;
+	VkPhysicalDevice                 physical = VK_NULL_HANDLE;
+	VkDevice                         device   = VK_NULL_HANDLE;
+	VkQueue                          queue    = VK_NULL_HANDLE;
+	uint32_t                         family   = 0;
+	VkPhysicalDeviceMemoryProperties memory {};
+	VkDeviceSize                     storage_alignment = 16;
+};
+
+struct Buf {
+	VkBuffer       buffer = VK_NULL_HANDLE;
+	VkDeviceMemory memory = VK_NULL_HANDLE;
+	void*          mapped = nullptr;
+	size_t         size   = 0;
+};
+
+uint32_t MemoryType(const Gpu& gpu, uint32_t bits, VkMemoryPropertyFlags flags) {
+	for (uint32_t i = 0; i < gpu.memory.memoryTypeCount; ++i) {
+		if ((bits & (1u << i)) && (gpu.memory.memoryTypes[i].propertyFlags & flags) == flags) return i;
+	}
+	Fail("no suitable memory type");
+}
+
+Buf MakeBuffer(const Gpu& gpu, size_t size, VkBufferUsageFlags usage) {
+	Buf b;
+	b.size = size;
+	VkBufferCreateInfo info {VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
+	info.size  = size;
+	info.usage = usage;
+	CheckVk(vkCreateBuffer_(gpu.device, &info, nullptr, &b.buffer), "vkCreateBuffer");
+	VkMemoryRequirements req;
+	vkGetBufferMemoryRequirements_(gpu.device, b.buffer, &req);
+	VkMemoryAllocateInfo alloc {VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
+	alloc.allocationSize  = req.size;
+	alloc.memoryTypeIndex = MemoryType(gpu, req.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
+	CheckVk(vkAllocateMemory_(gpu.device, &alloc, nullptr, &b.memory), "vkAllocateMemory");
+	CheckVk(vkBindBufferMemory_(gpu.device, b.buffer, b.memory, 0), "vkBindBufferMemory");
+	CheckVk(vkMapMemory_(gpu.device, b.memory, 0, size, 0, &b.mapped), "vkMapMemory");
+	std::memset(b.mapped, 0xA5, size);
+	return b;
+}
+
+Gpu InitGpu() {
+	const char* driver = std::getenv("SDL_VULKAN_LIBRARY");
+	void*       lib    = dlopen(driver != nullptr ? driver : "libMoltenVK.dylib", RTLD_NOW | RTLD_LOCAL);
+	if (lib == nullptr) Fail("cannot load MoltenVK; set SDL_VULKAN_LIBRARY");
+	auto get_instance_proc = reinterpret_cast<PFN_vkGetInstanceProcAddr>(dlsym(lib, "vkGetInstanceProcAddr"));
+	if (get_instance_proc == nullptr) Fail("dlsym vkGetInstanceProcAddr");
+	auto create_instance = reinterpret_cast<PFN_vkCreateInstance>(get_instance_proc(VK_NULL_HANDLE, "vkCreateInstance"));
+	auto enumerate_extensions = reinterpret_cast<PFN_vkEnumerateInstanceExtensionProperties>(
+	    get_instance_proc(VK_NULL_HANDLE, "vkEnumerateInstanceExtensionProperties"));
+	if (enumerate_extensions == nullptr) Fail("vkEnumerateInstanceExtensionProperties");
+	uint32_t extension_count = 0;
+	CheckVk(enumerate_extensions(nullptr, &extension_count, nullptr), "vkEnumerateInstanceExtensionProperties");
+	std::vector<VkExtensionProperties> available(extension_count);
+	CheckVk(enumerate_extensions(nullptr, &extension_count, available.data()), "vkEnumerateInstanceExtensionProperties list");
+	bool has_portability = false;
+	for (const auto& e: available) {
+		if (std::strcmp(e.extensionName, VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME) == 0) has_portability = true;
+	}
+	const char* extensions[] {VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME};
+	VkApplicationInfo app {VK_STRUCTURE_TYPE_APPLICATION_INFO};
+	app.apiVersion = VK_API_VERSION_1_3;
+	VkInstanceCreateInfo info {VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO};
+	info.pApplicationInfo        = &app;
+	info.flags                   = has_portability ? VK_INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR : 0;
+	info.enabledExtensionCount   = has_portability ? 1u : 0u;
+	info.ppEnabledExtensionNames = has_portability ? extensions : nullptr;
+	Gpu gpu;
+	CheckVk(create_instance(&info, nullptr, &gpu.instance), "vkCreateInstance");
+#define LOAD_INSTANCE(name) name##_ = reinterpret_cast<PFN_##name>(get_instance_proc(gpu.instance, #name));
+	VK_FUNCS(LOAD_INSTANCE)
+#undef LOAD_INSTANCE
+	uint32_t count = 0;
+	CheckVk(vkEnumeratePhysicalDevices_(gpu.instance, &count, nullptr), "vkEnumeratePhysicalDevices");
+	Check(count > 0, "no physical device");
+	std::vector<VkPhysicalDevice> devices(count);
+	CheckVk(vkEnumeratePhysicalDevices_(gpu.instance, &count, devices.data()), "vkEnumeratePhysicalDevices list");
+	gpu.physical = devices[0];
+	vkGetPhysicalDeviceMemoryProperties_(gpu.physical, &gpu.memory);
+	VkPhysicalDeviceProperties props {};
+	vkGetPhysicalDeviceProperties_(gpu.physical, &props);
+	gpu.storage_alignment = props.limits.minStorageBufferOffsetAlignment;
+	uint32_t qcount = 0;
+	vkGetPhysicalDeviceQueueFamilyProperties_(gpu.physical, &qcount, nullptr);
+	std::vector<VkQueueFamilyProperties> queues(qcount);
+	vkGetPhysicalDeviceQueueFamilyProperties_(gpu.physical, &qcount, queues.data());
+	for (uint32_t i = 0; i < qcount; ++i) {
+		if (queues[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) {
+			gpu.family = i;
+			break;
+		}
+	}
+	VkPhysicalDeviceFeatures supported {};
+	vkGetPhysicalDeviceFeatures_(gpu.physical, &supported);
+	Check(supported.vertexPipelineStoresAndAtomics, "device lacks vertexPipelineStoresAndAtomics (the VS cannot store)");
+	VkPhysicalDeviceFeatures features {};
+	features.vertexPipelineStoresAndAtomics = VK_TRUE;
+	features.fragmentStoresAndAtomics       = supported.fragmentStoresAndAtomics;
+	features.shaderClipDistance             = supported.shaderClipDistance; // the emitted VS has a clip guard
+	features.geometryShader                 = supported.geometryShader; // PrimitiveId in the PS needs the Geometry capability

Agreed and fixed. The harness now checks that the device supports tessellationShader and enables it (features.tessellationShader = VK_TRUE) instead of geometryShader, matching the renderer and the Tessellation capability the emitter declares for PrimitiveId; the stale comment is replaced. The change lives in #1440 (pr/d1-emitter, 8977bb43), and #1441 is rebased on top of it. It is a GPU-only harness, so there is no CPU test or mutant for this line; the harness compiles, it still has to be run on a GPU machine.

**@⁠wuboo** on GitHub · 2026-10-12 13:54 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1441#discussion_r4248805204) On `tests/PerVertexVsStoreGpuTests.cpp` line 382 (outdated): ```diff @@ -0,0 +1,751 @@ +// GPU harness for KYTY_PV_VSSTORE (graphics/host_gpu/renderer/perVertexVsStore.h). The real SPIR-V +// emitter produces the VS-store VS and PS from an IR vertex shader and an ISA pixel shader, and the +// pair is drawn on the host GPU (MoltenVK) with the exact descriptor/push layout of the renderer: +// set 0 = empty, set 1 = {cap SSBO (VS|FS), guest index SSBO (FS)}, push = native data + 8 dwords. +// Checks (bit for bit, no tolerance): +// 1. image: every probed pixel equals the PerVertexKHR semantics computed on the CPU from the vertex +// data, the index buffer and the draw parameters (corner 0/1/2 read through P0/P10/P20), +// 2. cap: the records the VS wrote hold {gl_VertexIndex, gl_InstanceIndex} of the cases, which +// settles whether gl_VertexIndex includes vertex_offset and gl_InstanceIndex first_instance. +// Cases: 16-bit and 32-bit indices, vertex_offset > 0 and < 0, first_instance != 0, 2 instances, an index +// buffer bound at an offset that is not a multiple of minStorageBufferOffsetAlignment. +// Run: per_vertex_vsstore_gpu_tests [--dump] [--stress] (--stress: 2M triangles x 2..4 instances, parameter-buffer overflow) +// --dump needs no GPU: it prints the emitted SPIR-V. +// The result is compared with the CPU model of the per-vertex semantics. The mutants built from +// tests/PerVertexVsStoreMutants.cmake (corner 0/2 swapped, index range not rounded) must fail it. + +#include "common/emulatorConfig.h" +#include "common/logging/log.h" +#include "common/subsystems.h" +#include "common/threads.h" +#include "graphics/host_gpu/renderer/perVertexVsStore.h" +#include "graphics/shader/recompiler/ShaderRecompiler.h" +#include "graphics/shader/recompiler/backend/spirv/SpirvEmitter.h" +#include "graphics/shader/recompiler/ir/IREmitter.h" +#include "graphics/shader/recompiler/ir/ShaderIR.h" +#include "graphics/shader/recompiler/ir/passes/ResourceTracking.h" +#include "graphics/shader/shader.h" +#include "graphics/shader/shaderCompiler.h" + +#include <spirv-tools/libspirv.hpp> +#include <vulkan/vulkan.h> + +#include <dlfcn.h> + +#include <algorithm> +#include <array> +#include <cstdint> +#include <cstdio> +#include <cstdlib> +#include <cstring> +#include <span> +#include <string> +#include <vector> + +namespace Libs::Graphics { +namespace { + +using namespace ShaderRecompiler; + +bool g_stress = false; // --stress: the >= 2M triangle cases + +[[noreturn]] void Fail(const char* message) { + std::fprintf(stderr, "per-vertex-vsstore-gpu-tests: FAILED: %s\n", message); + std::exit(1); +} + +void Check(bool ok, const char* message) { + if (!ok) Fail(message); +} + +void CheckVk(VkResult result, const char* what) { + if (result != VK_SUCCESS) { + std::fprintf(stderr, "per-vertex-vsstore-gpu-tests: FAILED: %s (VkResult %d)\n", what, static_cast<int>(result)); + std::exit(1); + } +} + +constexpr uint32_t EncodeSopp(uint32_t opcode, uint32_t simm = 0) { + return (0x17fu << 23u) | ((opcode & 0x7fu) << 16u) | (simm & 0xffffu); +} +constexpr uint32_t EncodeVintrp(uint32_t opcode, uint32_t vdst, uint32_t attr, uint32_t chan, uint32_t vsrc) { + return (0x32u << 26u) | ((opcode & 0x3u) << 16u) | ((vdst & 0xffu) << 18u) | ((attr & 0x3fu) << 10u) | + ((chan & 0x3u) << 8u) | (vsrc & 0xffu); +} +constexpr uint32_t EncodeExp0(uint32_t target, uint32_t en) { + return (0x3eu << 26u) | ((target & 0x3fu) << 4u) | (en & 0xfu) | (1u << 11u); +} +constexpr uint32_t EncodeExp1(uint32_t a, uint32_t b, uint32_t c, uint32_t d) { + return (a & 0xffu) | ((b & 0xffu) << 8u) | ((c & 0xffu) << 16u) | ((d & 0xffu) << 24u); +} + +void EnsureConfigInitialized() { + static bool initialized = false; + if (initialized) return; + static Common::Subsystems subsystems; + Common::InitializeThreads(); + subsystems.Initialize<Config::Lifecycle>(); + Config::ConfigOptions options; + options.printf_direction = Config::LogDirection::Silent; + Config::Load(options); + subsystems.Initialize<Log::Lifecycle>(); + ShaderInit(); + initialized = true; +} + +// ---- shaders ------------------------------------------------------------------------------------- + +struct Shaders { + std::vector<uint32_t> vs; + std::vector<uint32_t> ps; + uint32_t stride_vec4 = 0; +}; + +// VS: position = attr0, param0 = attr1 with `+ instance` added to the bits of x (a 1 ulp difference +// per instance shows a record of the wrong instance), param1 = {gl_VertexIndex, gl_InstanceIndex, 0, 0}. +// PS: out = {corner0.x, corner1.y, corner2.z, corner0.w} of param0. +Shaders BuildShaders() { + using IR::Value; + using O = IR::ValueOpcode; + Shaders out; + + IR::Program vs; + vs.stage = ShaderType::Vertex; + vs.wave_size = 64; + vs.srt_plan_complete = vs.resource_tracking_complete = vs.shader_info_complete = true; + vs.block_storage.push_back(std::make_unique<IR::Block>()); + vs.blocks.push_back(vs.block_storage.back().get()); + vs.info.inputs = {{IR::StageInputKind::VertexIndex}, + {IR::StageInputKind::InstanceIndex}, + {IR::StageInputKind::Parameter, 0, 4}, + {IR::StageInputKind::Parameter, 1, 4}}; + vs.info.outputs = {{IR::StageOutputKind::Position}, + {IR::StageOutputKind::Parameter, 0, 0}, + {IR::StageOutputKind::Parameter, 1, 1}}; + vs.export_info = {{.kind = IR::ExportTargetKind::Position, .en = 15}, + {.kind = IR::ExportTargetKind::Parameter, .index = 0, .en = 15}, + {.kind = IR::ExportTargetKind::Parameter, .index = 1, .en = 15}}; + IR::IREmitter emit(vs.blocks.front()); + const auto vertex = emit.Emit(O::GetBuiltin, {Value(static_cast<uint32_t>(IR::StageInputKind::VertexIndex)), Value(0u)}); + const auto instance = emit.Emit(O::GetBuiltin, {Value(static_cast<uint32_t>(IR::StageInputKind::InstanceIndex)), Value(0u)}); + std::array<Value, 4> position, color; + for (uint32_t c = 0; c < 4; c++) position[c] = emit.Emit(O::GetAttribute, {Value(0u), Value(c)}); + for (uint32_t c = 0; c < 4; c++) color[c] = emit.Emit(O::GetAttribute, {Value(1u), Value(c)}); + const auto pos = emit.Emit(O::CompositeConstructU32x4, {position[0], position[1], position[2], position[3]}); + emit.Emit(O::SetAttribute, {pos, Value(true)}, IR::ExportFlags {0}); + const auto x = emit.Emit(O::IAdd32, {color[0], instance}); + const auto param0 = emit.Emit(O::CompositeConstructU32x4, {x, color[1], color[2], color[3]}); + emit.Emit(O::SetAttribute, {param0, Value(true)}, IR::ExportFlags {1}); + const auto param1 = emit.Emit(O::CompositeConstructU32x4, {vertex, instance, Value(0u), Value(0u)}); + emit.Emit(O::SetAttribute, {param1, Value(true)}, IR::ExportFlags {2}); + static const ShaderVertexInputInfo vertex_info {}; + ShaderStageInputInfo vs_input {.vertex = &vertex_info}; + + uint32_t vs_mask = 0; + Spirv::PvStoreInfo vs_store; + vs_store.role = Spirv::PvStoreInfo::Role::Vertex; + vs_store.coherent = true; + vs_store.location_mask = &vs_mask; + out.vs = Spirv::EmitProgram(vs, vs_input, 0, &vs_store); + + // PS (the interpolation setup of TestPvVsStoreEmission): v_interp_mov_f32 with P0 / P10 / P20. + const uint32_t ps_code[] = {EncodeVintrp(2, 12, 0, 0, 2), EncodeVintrp(2, 13, 0, 1, 0), + EncodeVintrp(2, 14, 0, 2, 1), EncodeVintrp(2, 15, 0, 3, 2), + EncodeExp0(0x00, 0xf), EncodeExp1(12, 13, 14, 15), + EncodeSopp(0x01)}; + static ShaderPixelInputInfo ps_info {}; + ps_info.input_num = 1; + ps_info.ps_system_input_base = 2; + ps_info.custom_interpolation_mask = 1; + ps_info.ps_perspective_center_vgpr = 0; + for (uint32_t i = 0; i < std::size(ps_info.interpolator_settings); i++) ps_info.interpolator_settings[i] = i; + ps_info.interpolator_settings[0] = 0x00000420u; + static const std::array<uint32_t, 64> user_data = [] { + std::array<uint32_t, 64> data {}; + data[3] = 3u << 28u; + return data; + }(); + CompileOptions options; + options.stage = ShaderType::Pixel; + options.user_data = user_data; + options.input_info.pixel = &ps_info; + auto translated = TranslateProgram(ps_code, options); + auto plan = IR::ExtractResourcePlan(translated.program); + IR::ResourceSnapshot resources; + IR::ResourceSpecialization specialization; + const IR::SrtRuntime runtime {.user_data = options.user_data, + .shader_base = reinterpret_cast<uint64_t>(ps_code), + .read_specialization_memory = [](void*, uint64_t, std::span<uint32_t>) { return false; }}; + Check(IR::MaterializeResources(plan, runtime, resources, specialization), "PS resources did not materialize"); + auto compiled = CompileProgram(std::move(translated), options, specialization, 0); + uint32_t ps_mask = 0; + Spirv::PvStoreInfo ps_store; + ps_store.role = Spirv::PvStoreInfo::Role::Pixel; + ps_store.coherent = true; + ps_store.location_mask = &ps_mask; + out.ps = Spirv::EmitProgram(compiled.program, options.input_info, 0, &ps_store); + + Check(ClassifyPvVsStoreInterface(vs_mask, ps_mask) == PvVsStoreInterfaceVerdict::Use, "VS/PS pair is not a VS-store candidate"); + out.stride_vec4 = PvVsStoreStrideFor(vs_mask); + if (out.stride_vec4 != 2) std::fprintf(stderr, "VS location mask %08x, PS location mask %08x\n", vs_mask, ps_mask); + Check(out.stride_vec4 == 2, "expected stride 2 (locations 0 and 1)"); + spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_2); + Check(tools.Validate(out.vs), "VS-store VS does not validate"); + Check(tools.Validate(out.ps), "VS-store PS does not validate"); + return out; +} + +// ---- scene (CPU model) --------------------------------------------------------------------------- + +constexpr uint32_t kDim = 32; // render target +constexpr uint32_t kCell = 16; // one triangle per cell: 2x2 cells +constexpr uint32_t kVertices = 24; // 4 triangles x 3 corners, plus 12 spare vertices for offsets +constexpr uint32_t kStrideB = 32; // float4 position, float4 color + +struct Vertex { + float position[4]; + float color[4]; +}; + +std::array<Vertex, kVertices> MakeVertices() { + std::array<Vertex, kVertices> v {}; + for (uint32_t i = 0; i < kVertices; ++i) { + const uint32_t tri = (i / 3u) % 4u; + const uint32_t cx = tri % 2u, cy = tri / 2u; + const float x0 = static_cast<float>(cx * kCell), y0 = static_cast<float>(cy * kCell); + const float px[3] = {x0 + 2.f, x0 + 14.f, x0 + 2.f}; + const float py[3] = {y0 + 2.f, y0 + 2.f, y0 + 14.f}; + const uint32_t k = i % 3u; + v[i].position[0] = px[k] / (kDim / 2.f) - 1.f; + v[i].position[1] = py[k] / (kDim / 2.f) - 1.f; + v[i].position[2] = 0.5f; + v[i].position[3] = 1.f; + // distinct, normal floats: any mix-up of a vertex, a corner or a component shows + v[i].color[0] = 1.0f + 0.03125f * static_cast<float>(i); + v[i].color[1] = 2.0f + 0.0625f * static_cast<float>(i); + v[i].color[2] = 3.0f + 0.125f * static_cast<float>(i); + v[i].color[3] = 4.0f + 0.25f * static_cast<float>(i); + } + return v; +} + +struct Case { + const char* name; + bool index32; + std::vector<uint32_t> indices; // per triangle corner, relative to vertex_offset + int32_t vertex_offset; + uint32_t first_instance; + uint32_t instance_count; + uint32_t bind_byte_offset; // where the index data starts inside the index buffer +}; + +uint32_t Bits(float f) { + uint32_t u; + std::memcpy(&u, &f, 4); + return u; +} + +// Expected pixel of triangle t of the draw: {corner0.x(+inst), corner1.y, corner2.z, corner0.w}. +std::array<uint32_t, 4> ExpectedPixel(const std::array<Vertex, kVertices>& v, const Case& c, uint32_t tri) { + const uint32_t last_instance = c.first_instance + c.instance_count - 1; + const auto vertex = [&](uint32_t corner) { return static_cast<uint32_t>(static_cast<int32_t>(c.indices[tri * 3 + corner]) + c.vertex_offset); }; + std::array<uint32_t, 4> out {}; + out[0] = Bits(v[vertex(0)].color[0]) + last_instance; + out[1] = Bits(v[vertex(1)].color[1]); + out[2] = Bits(v[vertex(2)].color[2]); + out[3] = Bits(v[vertex(0)].color[3]); + return out; +} + +// ---- Vulkan -------------------------------------------------------------------------------------- + +#define VK_FUNCS(X) \ + X(vkCreateDevice) X(vkGetDeviceProcAddr) X(vkEnumeratePhysicalDevices) X(vkGetPhysicalDeviceMemoryProperties) \ + X(vkGetPhysicalDeviceQueueFamilyProperties) X(vkGetPhysicalDeviceFeatures) X(vkGetPhysicalDeviceProperties) + +#define VK_DEVICE_FUNCS(X) \ + X(vkGetDeviceQueue) X(vkCreateBuffer) X(vkGetBufferMemoryRequirements) X(vkAllocateMemory) X(vkBindBufferMemory) \ + X(vkMapMemory) X(vkCreateDescriptorSetLayout) X(vkCreatePipelineLayout) X(vkCreateShaderModule) \ + X(vkCreateGraphicsPipelines) X(vkCreateDescriptorPool) X(vkAllocateDescriptorSets) X(vkUpdateDescriptorSets) \ + X(vkCreateCommandPool) X(vkAllocateCommandBuffers) X(vkBeginCommandBuffer) X(vkEndCommandBuffer) \ + X(vkCmdBindPipeline) X(vkCmdBindDescriptorSets) X(vkCmdPushConstants) X(vkCmdBeginRenderPass) X(vkCmdEndRenderPass) \ + X(vkCmdBindVertexBuffers) X(vkCmdBindIndexBuffer) X(vkCmdDrawIndexed) X(vkCmdCopyImageToBuffer) X(vkQueueSubmit) \ + X(vkQueueWaitIdle) X(vkCreateRenderPass) X(vkCreateFramebuffer) X(vkCreateImage) X(vkGetImageMemoryRequirements) \ + X(vkBindImageMemory) X(vkCreateImageView) X(vkCmdPipelineBarrier) + +#define DECLARE(name) PFN_##name name##_ = nullptr; +VK_FUNCS(DECLARE) +VK_DEVICE_FUNCS(DECLARE) +#undef DECLARE + +struct Gpu { + VkInstance instance = VK_NULL_HANDLE; + VkPhysicalDevice physical = VK_NULL_HANDLE; + VkDevice device = VK_NULL_HANDLE; + VkQueue queue = VK_NULL_HANDLE; + uint32_t family = 0; + VkPhysicalDeviceMemoryProperties memory {}; + VkDeviceSize storage_alignment = 16; +}; + +struct Buf { + VkBuffer buffer = VK_NULL_HANDLE; + VkDeviceMemory memory = VK_NULL_HANDLE; + void* mapped = nullptr; + size_t size = 0; +}; + +uint32_t MemoryType(const Gpu& gpu, uint32_t bits, VkMemoryPropertyFlags flags) { + for (uint32_t i = 0; i < gpu.memory.memoryTypeCount; ++i) { + if ((bits & (1u << i)) && (gpu.memory.memoryTypes[i].propertyFlags & flags) == flags) return i; + } + Fail("no suitable memory type"); +} + +Buf MakeBuffer(const Gpu& gpu, size_t size, VkBufferUsageFlags usage) { + Buf b; + b.size = size; + VkBufferCreateInfo info {VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; + info.size = size; + info.usage = usage; + CheckVk(vkCreateBuffer_(gpu.device, &info, nullptr, &b.buffer), "vkCreateBuffer"); + VkMemoryRequirements req; + vkGetBufferMemoryRequirements_(gpu.device, b.buffer, &req); + VkMemoryAllocateInfo alloc {VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; + alloc.allocationSize = req.size; + alloc.memoryTypeIndex = MemoryType(gpu, req.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); + CheckVk(vkAllocateMemory_(gpu.device, &alloc, nullptr, &b.memory), "vkAllocateMemory"); + CheckVk(vkBindBufferMemory_(gpu.device, b.buffer, b.memory, 0), "vkBindBufferMemory"); + CheckVk(vkMapMemory_(gpu.device, b.memory, 0, size, 0, &b.mapped), "vkMapMemory"); + std::memset(b.mapped, 0xA5, size); + return b; +} + +Gpu InitGpu() { + const char* driver = std::getenv("SDL_VULKAN_LIBRARY"); + void* lib = dlopen(driver != nullptr ? driver : "libMoltenVK.dylib", RTLD_NOW | RTLD_LOCAL); + if (lib == nullptr) Fail("cannot load MoltenVK; set SDL_VULKAN_LIBRARY"); + auto get_instance_proc = reinterpret_cast<PFN_vkGetInstanceProcAddr>(dlsym(lib, "vkGetInstanceProcAddr")); + if (get_instance_proc == nullptr) Fail("dlsym vkGetInstanceProcAddr"); + auto create_instance = reinterpret_cast<PFN_vkCreateInstance>(get_instance_proc(VK_NULL_HANDLE, "vkCreateInstance")); + auto enumerate_extensions = reinterpret_cast<PFN_vkEnumerateInstanceExtensionProperties>( + get_instance_proc(VK_NULL_HANDLE, "vkEnumerateInstanceExtensionProperties")); + if (enumerate_extensions == nullptr) Fail("vkEnumerateInstanceExtensionProperties"); + uint32_t extension_count = 0; + CheckVk(enumerate_extensions(nullptr, &extension_count, nullptr), "vkEnumerateInstanceExtensionProperties"); + std::vector<VkExtensionProperties> available(extension_count); + CheckVk(enumerate_extensions(nullptr, &extension_count, available.data()), "vkEnumerateInstanceExtensionProperties list"); + bool has_portability = false; + for (const auto& e: available) { + if (std::strcmp(e.extensionName, VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME) == 0) has_portability = true; + } + const char* extensions[] {VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME}; + VkApplicationInfo app {VK_STRUCTURE_TYPE_APPLICATION_INFO}; + app.apiVersion = VK_API_VERSION_1_3; + VkInstanceCreateInfo info {VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO}; + info.pApplicationInfo = &app; + info.flags = has_portability ? VK_INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR : 0; + info.enabledExtensionCount = has_portability ? 1u : 0u; + info.ppEnabledExtensionNames = has_portability ? extensions : nullptr; + Gpu gpu; + CheckVk(create_instance(&info, nullptr, &gpu.instance), "vkCreateInstance"); +#define LOAD_INSTANCE(name) name##_ = reinterpret_cast<PFN_##name>(get_instance_proc(gpu.instance, #name)); + VK_FUNCS(LOAD_INSTANCE) +#undef LOAD_INSTANCE + uint32_t count = 0; + CheckVk(vkEnumeratePhysicalDevices_(gpu.instance, &count, nullptr), "vkEnumeratePhysicalDevices"); + Check(count > 0, "no physical device"); + std::vector<VkPhysicalDevice> devices(count); + CheckVk(vkEnumeratePhysicalDevices_(gpu.instance, &count, devices.data()), "vkEnumeratePhysicalDevices list"); + gpu.physical = devices[0]; + vkGetPhysicalDeviceMemoryProperties_(gpu.physical, &gpu.memory); + VkPhysicalDeviceProperties props {}; + vkGetPhysicalDeviceProperties_(gpu.physical, &props); + gpu.storage_alignment = props.limits.minStorageBufferOffsetAlignment; + uint32_t qcount = 0; + vkGetPhysicalDeviceQueueFamilyProperties_(gpu.physical, &qcount, nullptr); + std::vector<VkQueueFamilyProperties> queues(qcount); + vkGetPhysicalDeviceQueueFamilyProperties_(gpu.physical, &qcount, queues.data()); + for (uint32_t i = 0; i < qcount; ++i) { + if (queues[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) { + gpu.family = i; + break; + } + } + VkPhysicalDeviceFeatures supported {}; + vkGetPhysicalDeviceFeatures_(gpu.physical, &supported); + Check(supported.vertexPipelineStoresAndAtomics, "device lacks vertexPipelineStoresAndAtomics (the VS cannot store)"); + VkPhysicalDeviceFeatures features {}; + features.vertexPipelineStoresAndAtomics = VK_TRUE; + features.fragmentStoresAndAtomics = supported.fragmentStoresAndAtomics; + features.shaderClipDistance = supported.shaderClipDistance; // the emitted VS has a clip guard + features.geometryShader = supported.geometryShader; // PrimitiveId in the PS needs the Geometry capability ``` Agreed and fixed. The harness now checks that the device supports `tessellationShader` and enables it (`features.tessellationShader = VK_TRUE`) instead of `geometryShader`, matching the renderer and the `Tessellation` capability the emitter declares for `PrimitiveId`; the stale comment is replaced. The change lives in #1440 (`pr/d1-emitter`, 8977bb43), and #1441 is rebased on top of it. It is a GPU-only harness, so there is no CPU test or mutant for this line; the harness compiles, it still has to be run on a GPU machine.
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-12 13:54 UTC · original
On tests/PerVertexVsStoreGpuTests.cpp line 382 (outdated):

@@ -0,0 +1,751 @@
+// GPU harness for KYTY_PV_VSSTORE (graphics/host_gpu/renderer/perVertexVsStore.h). The real SPIR-V
+// emitter produces the VS-store VS and PS from an IR vertex shader and an ISA pixel shader, and the
+// pair is drawn on the host GPU (MoltenVK) with the exact descriptor/push layout of the renderer:
+//   set 0 = empty, set 1 = {cap SSBO (VS|FS), guest index SSBO (FS)}, push = native data + 8 dwords.
+// Checks (bit for bit, no tolerance):
+//   1. image: every probed pixel equals the PerVertexKHR semantics computed on the CPU from the vertex
+//      data, the index buffer and the draw parameters (corner 0/1/2 read through P0/P10/P20),
+//   2. cap: the records the VS wrote hold {gl_VertexIndex, gl_InstanceIndex} of the cases, which
+//      settles whether gl_VertexIndex includes vertex_offset and gl_InstanceIndex first_instance.
+// Cases: 16-bit and 32-bit indices, vertex_offset > 0 and < 0, first_instance != 0, 2 instances, an index
+// buffer bound at an offset that is not a multiple of minStorageBufferOffsetAlignment.
+// Run: per_vertex_vsstore_gpu_tests [--dump] [--stress]  (--stress: 2M triangles x 2..4 instances, parameter-buffer overflow)
+//   --dump needs no GPU: it prints the emitted SPIR-V.
+// The result is compared with the CPU model of the per-vertex semantics. The mutants built from
+// tests/PerVertexVsStoreMutants.cmake (corner 0/2 swapped, index range not rounded) must fail it.
+
+#include "common/emulatorConfig.h"
+#include "common/logging/log.h"
+#include "common/subsystems.h"
+#include "common/threads.h"
+#include "graphics/host_gpu/renderer/perVertexVsStore.h"
+#include "graphics/shader/recompiler/ShaderRecompiler.h"
+#include "graphics/shader/recompiler/backend/spirv/SpirvEmitter.h"
+#include "graphics/shader/recompiler/ir/IREmitter.h"
+#include "graphics/shader/recompiler/ir/ShaderIR.h"
+#include "graphics/shader/recompiler/ir/passes/ResourceTracking.h"
+#include "graphics/shader/shader.h"
+#include "graphics/shader/shaderCompiler.h"
+
+#include <spirv-tools/libspirv.hpp>
+#include <vulkan/vulkan.h>
+
+#include <dlfcn.h>
+
+#include <algorithm>
+#include <array>
+#include <cstdint>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <span>
+#include <string>
+#include <vector>
+
+namespace Libs::Graphics {
+namespace {
+
+using namespace ShaderRecompiler;
+
+bool g_stress = false; // --stress: the >= 2M triangle cases
+
+[[noreturn]] void Fail(const char* message) {
+	std::fprintf(stderr, "per-vertex-vsstore-gpu-tests: FAILED: %s\n", message);
+	std::exit(1);
+}
+
+void Check(bool ok, const char* message) {
+	if (!ok) Fail(message);
+}
+
+void CheckVk(VkResult result, const char* what) {
+	if (result != VK_SUCCESS) {
+		std::fprintf(stderr, "per-vertex-vsstore-gpu-tests: FAILED: %s (VkResult %d)\n", what, static_cast<int>(result));
+		std::exit(1);
+	}
+}
+
+constexpr uint32_t EncodeSopp(uint32_t opcode, uint32_t simm = 0) {
+	return (0x17fu << 23u) | ((opcode & 0x7fu) << 16u) | (simm & 0xffffu);
+}
+constexpr uint32_t EncodeVintrp(uint32_t opcode, uint32_t vdst, uint32_t attr, uint32_t chan, uint32_t vsrc) {
+	return (0x32u << 26u) | ((opcode & 0x3u) << 16u) | ((vdst & 0xffu) << 18u) | ((attr & 0x3fu) << 10u) |
+	       ((chan & 0x3u) << 8u) | (vsrc & 0xffu);
+}
+constexpr uint32_t EncodeExp0(uint32_t target, uint32_t en) {
+	return (0x3eu << 26u) | ((target & 0x3fu) << 4u) | (en & 0xfu) | (1u << 11u);
+}
+constexpr uint32_t EncodeExp1(uint32_t a, uint32_t b, uint32_t c, uint32_t d) {
+	return (a & 0xffu) | ((b & 0xffu) << 8u) | ((c & 0xffu) << 16u) | ((d & 0xffu) << 24u);
+}
+
+void EnsureConfigInitialized() {
+	static bool initialized = false;
+	if (initialized) return;
+	static Common::Subsystems subsystems;
+	Common::InitializeThreads();
+	subsystems.Initialize<Config::Lifecycle>();
+	Config::ConfigOptions options;
+	options.printf_direction = Config::LogDirection::Silent;
+	Config::Load(options);
+	subsystems.Initialize<Log::Lifecycle>();
+	ShaderInit();
+	initialized = true;
+}
+
+// ---- shaders -------------------------------------------------------------------------------------
+
+struct Shaders {
+	std::vector<uint32_t> vs;
+	std::vector<uint32_t> ps;
+	uint32_t              stride_vec4 = 0;
+};
+
+// VS: position = attr0, param0 = attr1 with `+ instance` added to the bits of x (a 1 ulp difference
+// per instance shows a record of the wrong instance), param1 = {gl_VertexIndex, gl_InstanceIndex, 0, 0}.
+// PS: out = {corner0.x, corner1.y, corner2.z, corner0.w} of param0.
+Shaders BuildShaders() {
+	using IR::Value;
+	using O = IR::ValueOpcode;
+	Shaders out;
+
+	IR::Program vs;
+	vs.stage                  = ShaderType::Vertex;
+	vs.wave_size              = 64;
+	vs.srt_plan_complete      = vs.resource_tracking_complete = vs.shader_info_complete = true;
+	vs.block_storage.push_back(std::make_unique<IR::Block>());
+	vs.blocks.push_back(vs.block_storage.back().get());
+	vs.info.inputs  = {{IR::StageInputKind::VertexIndex},
+	                   {IR::StageInputKind::InstanceIndex},
+	                   {IR::StageInputKind::Parameter, 0, 4},
+	                   {IR::StageInputKind::Parameter, 1, 4}};
+	vs.info.outputs = {{IR::StageOutputKind::Position},
+	                   {IR::StageOutputKind::Parameter, 0, 0},
+	                   {IR::StageOutputKind::Parameter, 1, 1}};
+	vs.export_info  = {{.kind = IR::ExportTargetKind::Position, .en = 15},
+	                   {.kind = IR::ExportTargetKind::Parameter, .index = 0, .en = 15},
+	                   {.kind = IR::ExportTargetKind::Parameter, .index = 1, .en = 15}};
+	IR::IREmitter emit(vs.blocks.front());
+	const auto vertex   = emit.Emit(O::GetBuiltin, {Value(static_cast<uint32_t>(IR::StageInputKind::VertexIndex)), Value(0u)});
+	const auto instance = emit.Emit(O::GetBuiltin, {Value(static_cast<uint32_t>(IR::StageInputKind::InstanceIndex)), Value(0u)});
+	std::array<Value, 4> position, color;
+	for (uint32_t c = 0; c < 4; c++) position[c] = emit.Emit(O::GetAttribute, {Value(0u), Value(c)});
+	for (uint32_t c = 0; c < 4; c++) color[c] = emit.Emit(O::GetAttribute, {Value(1u), Value(c)});
+	const auto pos = emit.Emit(O::CompositeConstructU32x4, {position[0], position[1], position[2], position[3]});
+	emit.Emit(O::SetAttribute, {pos, Value(true)}, IR::ExportFlags {0});
+	const auto x      = emit.Emit(O::IAdd32, {color[0], instance});
+	const auto param0 = emit.Emit(O::CompositeConstructU32x4, {x, color[1], color[2], color[3]});
+	emit.Emit(O::SetAttribute, {param0, Value(true)}, IR::ExportFlags {1});
+	const auto param1 = emit.Emit(O::CompositeConstructU32x4, {vertex, instance, Value(0u), Value(0u)});
+	emit.Emit(O::SetAttribute, {param1, Value(true)}, IR::ExportFlags {2});
+	static const ShaderVertexInputInfo vertex_info {};
+	ShaderStageInputInfo               vs_input {.vertex = &vertex_info};
+
+	uint32_t vs_mask = 0;
+	Spirv::PvStoreInfo vs_store;
+	vs_store.role          = Spirv::PvStoreInfo::Role::Vertex;
+	vs_store.coherent      = true;
+	vs_store.location_mask = &vs_mask;
+	out.vs                 = Spirv::EmitProgram(vs, vs_input, 0, &vs_store);
+
+	// PS (the interpolation setup of TestPvVsStoreEmission): v_interp_mov_f32 with P0 / P10 / P20.
+	const uint32_t ps_code[] = {EncodeVintrp(2, 12, 0, 0, 2), EncodeVintrp(2, 13, 0, 1, 0),
+	                            EncodeVintrp(2, 14, 0, 2, 1), EncodeVintrp(2, 15, 0, 3, 2),
+	                            EncodeExp0(0x00, 0xf),        EncodeExp1(12, 13, 14, 15),
+	                            EncodeSopp(0x01)};
+	static ShaderPixelInputInfo ps_info {};
+	ps_info.input_num                 = 1;
+	ps_info.ps_system_input_base      = 2;
+	ps_info.custom_interpolation_mask = 1;
+	ps_info.ps_perspective_center_vgpr = 0;
+	for (uint32_t i = 0; i < std::size(ps_info.interpolator_settings); i++) ps_info.interpolator_settings[i] = i;
+	ps_info.interpolator_settings[0] = 0x00000420u;
+	static const std::array<uint32_t, 64> user_data = [] {
+		std::array<uint32_t, 64> data {};
+		data[3] = 3u << 28u;
+		return data;
+	}();
+	CompileOptions options;
+	options.stage            = ShaderType::Pixel;
+	options.user_data        = user_data;
+	options.input_info.pixel = &ps_info;
+	auto translated          = TranslateProgram(ps_code, options);
+	auto plan                = IR::ExtractResourcePlan(translated.program);
+	IR::ResourceSnapshot       resources;
+	IR::ResourceSpecialization specialization;
+	const IR::SrtRuntime       runtime {.user_data = options.user_data,
+	                                    .shader_base = reinterpret_cast<uint64_t>(ps_code),
+	                                    .read_specialization_memory = [](void*, uint64_t, std::span<uint32_t>) { return false; }};
+	Check(IR::MaterializeResources(plan, runtime, resources, specialization), "PS resources did not materialize");
+	auto compiled = CompileProgram(std::move(translated), options, specialization, 0);
+	uint32_t ps_mask = 0;
+	Spirv::PvStoreInfo ps_store;
+	ps_store.role          = Spirv::PvStoreInfo::Role::Pixel;
+	ps_store.coherent      = true;
+	ps_store.location_mask = &ps_mask;
+	out.ps                 = Spirv::EmitProgram(compiled.program, options.input_info, 0, &ps_store);
+
+	Check(ClassifyPvVsStoreInterface(vs_mask, ps_mask) == PvVsStoreInterfaceVerdict::Use, "VS/PS pair is not a VS-store candidate");
+	out.stride_vec4 = PvVsStoreStrideFor(vs_mask);
+	if (out.stride_vec4 != 2) std::fprintf(stderr, "VS location mask %08x, PS location mask %08x\n", vs_mask, ps_mask);
+	Check(out.stride_vec4 == 2, "expected stride 2 (locations 0 and 1)");
+	spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_2);
+	Check(tools.Validate(out.vs), "VS-store VS does not validate");
+	Check(tools.Validate(out.ps), "VS-store PS does not validate");
+	return out;
+}
+
+// ---- scene (CPU model) ---------------------------------------------------------------------------
+
+constexpr uint32_t kDim      = 32; // render target
+constexpr uint32_t kCell     = 16; // one triangle per cell: 2x2 cells
+constexpr uint32_t kVertices = 24; // 4 triangles x 3 corners, plus 12 spare vertices for offsets
+constexpr uint32_t kStrideB  = 32; // float4 position, float4 color
+
+struct Vertex {
+	float position[4];
+	float color[4];
+};
+
+std::array<Vertex, kVertices> MakeVertices() {
+	std::array<Vertex, kVertices> v {};
+	for (uint32_t i = 0; i < kVertices; ++i) {
+		const uint32_t tri = (i / 3u) % 4u;
+		const uint32_t cx  = tri % 2u, cy = tri / 2u;
+		const float    x0  = static_cast<float>(cx * kCell), y0 = static_cast<float>(cy * kCell);
+		const float    px[3] = {x0 + 2.f, x0 + 14.f, x0 + 2.f};
+		const float    py[3] = {y0 + 2.f, y0 + 2.f, y0 + 14.f};
+		const uint32_t k     = i % 3u;
+		v[i].position[0] = px[k] / (kDim / 2.f) - 1.f;
+		v[i].position[1] = py[k] / (kDim / 2.f) - 1.f;
+		v[i].position[2] = 0.5f;
+		v[i].position[3] = 1.f;
+		// distinct, normal floats: any mix-up of a vertex, a corner or a component shows
+		v[i].color[0] = 1.0f + 0.03125f * static_cast<float>(i);
+		v[i].color[1] = 2.0f + 0.0625f * static_cast<float>(i);
+		v[i].color[2] = 3.0f + 0.125f * static_cast<float>(i);
+		v[i].color[3] = 4.0f + 0.25f * static_cast<float>(i);
+	}
+	return v;
+}
+
+struct Case {
+	const char*           name;
+	bool                  index32;
+	std::vector<uint32_t> indices;       // per triangle corner, relative to vertex_offset
+	int32_t               vertex_offset;
+	uint32_t              first_instance;
+	uint32_t              instance_count;
+	uint32_t              bind_byte_offset; // where the index data starts inside the index buffer
+};
+
+uint32_t Bits(float f) {
+	uint32_t u;
+	std::memcpy(&u, &f, 4);
+	return u;
+}
+
+// Expected pixel of triangle t of the draw: {corner0.x(+inst), corner1.y, corner2.z, corner0.w}.
+std::array<uint32_t, 4> ExpectedPixel(const std::array<Vertex, kVertices>& v, const Case& c, uint32_t tri) {
+	const uint32_t last_instance = c.first_instance + c.instance_count - 1;
+	const auto     vertex = [&](uint32_t corner) { return static_cast<uint32_t>(static_cast<int32_t>(c.indices[tri * 3 + corner]) + c.vertex_offset); };
+	std::array<uint32_t, 4> out {};
+	out[0] = Bits(v[vertex(0)].color[0]) + last_instance;
+	out[1] = Bits(v[vertex(1)].color[1]);
+	out[2] = Bits(v[vertex(2)].color[2]);
+	out[3] = Bits(v[vertex(0)].color[3]);
+	return out;
+}
+
+// ---- Vulkan --------------------------------------------------------------------------------------
+
+#define VK_FUNCS(X)                                                                                                        \
+	X(vkCreateDevice) X(vkGetDeviceProcAddr) X(vkEnumeratePhysicalDevices) X(vkGetPhysicalDeviceMemoryProperties)          \
+	X(vkGetPhysicalDeviceQueueFamilyProperties) X(vkGetPhysicalDeviceFeatures) X(vkGetPhysicalDeviceProperties)
+
+#define VK_DEVICE_FUNCS(X)                                                                                                 \
+	X(vkGetDeviceQueue) X(vkCreateBuffer) X(vkGetBufferMemoryRequirements) X(vkAllocateMemory) X(vkBindBufferMemory)      \
+	X(vkMapMemory) X(vkCreateDescriptorSetLayout) X(vkCreatePipelineLayout) X(vkCreateShaderModule)                         \
+	X(vkCreateGraphicsPipelines) X(vkCreateDescriptorPool) X(vkAllocateDescriptorSets) X(vkUpdateDescriptorSets)           \
+	X(vkCreateCommandPool) X(vkAllocateCommandBuffers) X(vkBeginCommandBuffer) X(vkEndCommandBuffer)                       \
+	X(vkCmdBindPipeline) X(vkCmdBindDescriptorSets) X(vkCmdPushConstants) X(vkCmdBeginRenderPass) X(vkCmdEndRenderPass)    \
+	X(vkCmdBindVertexBuffers) X(vkCmdBindIndexBuffer) X(vkCmdDrawIndexed) X(vkCmdCopyImageToBuffer) X(vkQueueSubmit)      \
+	X(vkQueueWaitIdle) X(vkCreateRenderPass) X(vkCreateFramebuffer) X(vkCreateImage) X(vkGetImageMemoryRequirements)       \
+	X(vkBindImageMemory) X(vkCreateImageView) X(vkCmdPipelineBarrier)
+
+#define DECLARE(name) PFN_##name name##_ = nullptr;
+VK_FUNCS(DECLARE)
+VK_DEVICE_FUNCS(DECLARE)
+#undef DECLARE
+
+struct Gpu {
+	VkInstance                       instance = VK_NULL_HANDLE;
+	VkPhysicalDevice                 physical = VK_NULL_HANDLE;
+	VkDevice                         device   = VK_NULL_HANDLE;
+	VkQueue                          queue    = VK_NULL_HANDLE;
+	uint32_t                         family   = 0;
+	VkPhysicalDeviceMemoryProperties memory {};
+	VkDeviceSize                     storage_alignment = 16;
+};
+
+struct Buf {
+	VkBuffer       buffer = VK_NULL_HANDLE;
+	VkDeviceMemory memory = VK_NULL_HANDLE;
+	void*          mapped = nullptr;
+	size_t         size   = 0;
+};
+
+uint32_t MemoryType(const Gpu& gpu, uint32_t bits, VkMemoryPropertyFlags flags) {
+	for (uint32_t i = 0; i < gpu.memory.memoryTypeCount; ++i) {
+		if ((bits & (1u << i)) && (gpu.memory.memoryTypes[i].propertyFlags & flags) == flags) return i;
+	}
+	Fail("no suitable memory type");
+}
+
+Buf MakeBuffer(const Gpu& gpu, size_t size, VkBufferUsageFlags usage) {
+	Buf b;
+	b.size = size;
+	VkBufferCreateInfo info {VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
+	info.size  = size;
+	info.usage = usage;
+	CheckVk(vkCreateBuffer_(gpu.device, &info, nullptr, &b.buffer), "vkCreateBuffer");
+	VkMemoryRequirements req;
+	vkGetBufferMemoryRequirements_(gpu.device, b.buffer, &req);
+	VkMemoryAllocateInfo alloc {VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
+	alloc.allocationSize  = req.size;
+	alloc.memoryTypeIndex = MemoryType(gpu, req.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
+	CheckVk(vkAllocateMemory_(gpu.device, &alloc, nullptr, &b.memory), "vkAllocateMemory");
+	CheckVk(vkBindBufferMemory_(gpu.device, b.buffer, b.memory, 0), "vkBindBufferMemory");
+	CheckVk(vkMapMemory_(gpu.device, b.memory, 0, size, 0, &b.mapped), "vkMapMemory");
+	std::memset(b.mapped, 0xA5, size);
+	return b;
+}
+
+Gpu InitGpu() {
+	const char* driver = std::getenv("SDL_VULKAN_LIBRARY");
+	void*       lib    = dlopen(driver != nullptr ? driver : "libMoltenVK.dylib", RTLD_NOW | RTLD_LOCAL);
+	if (lib == nullptr) Fail("cannot load MoltenVK; set SDL_VULKAN_LIBRARY");
+	auto get_instance_proc = reinterpret_cast<PFN_vkGetInstanceProcAddr>(dlsym(lib, "vkGetInstanceProcAddr"));
+	if (get_instance_proc == nullptr) Fail("dlsym vkGetInstanceProcAddr");
+	auto create_instance = reinterpret_cast<PFN_vkCreateInstance>(get_instance_proc(VK_NULL_HANDLE, "vkCreateInstance"));
+	auto enumerate_extensions = reinterpret_cast<PFN_vkEnumerateInstanceExtensionProperties>(
+	    get_instance_proc(VK_NULL_HANDLE, "vkEnumerateInstanceExtensionProperties"));
+	if (enumerate_extensions == nullptr) Fail("vkEnumerateInstanceExtensionProperties");
+	uint32_t extension_count = 0;
+	CheckVk(enumerate_extensions(nullptr, &extension_count, nullptr), "vkEnumerateInstanceExtensionProperties");
+	std::vector<VkExtensionProperties> available(extension_count);
+	CheckVk(enumerate_extensions(nullptr, &extension_count, available.data()), "vkEnumerateInstanceExtensionProperties list");
+	bool has_portability = false;
+	for (const auto& e: available) {
+		if (std::strcmp(e.extensionName, VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME) == 0) has_portability = true;
+	}
+	const char* extensions[] {VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME};
+	VkApplicationInfo app {VK_STRUCTURE_TYPE_APPLICATION_INFO};
+	app.apiVersion = VK_API_VERSION_1_3;
+	VkInstanceCreateInfo info {VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO};
+	info.pApplicationInfo        = &app;
+	info.flags                   = has_portability ? VK_INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR : 0;
+	info.enabledExtensionCount   = has_portability ? 1u : 0u;
+	info.ppEnabledExtensionNames = has_portability ? extensions : nullptr;
+	Gpu gpu;
+	CheckVk(create_instance(&info, nullptr, &gpu.instance), "vkCreateInstance");
+#define LOAD_INSTANCE(name) name##_ = reinterpret_cast<PFN_##name>(get_instance_proc(gpu.instance, #name));
+	VK_FUNCS(LOAD_INSTANCE)
+#undef LOAD_INSTANCE
+	uint32_t count = 0;
+	CheckVk(vkEnumeratePhysicalDevices_(gpu.instance, &count, nullptr), "vkEnumeratePhysicalDevices");
+	Check(count > 0, "no physical device");
+	std::vector<VkPhysicalDevice> devices(count);
+	CheckVk(vkEnumeratePhysicalDevices_(gpu.instance, &count, devices.data()), "vkEnumeratePhysicalDevices list");
+	gpu.physical = devices[0];
+	vkGetPhysicalDeviceMemoryProperties_(gpu.physical, &gpu.memory);
+	VkPhysicalDeviceProperties props {};
+	vkGetPhysicalDeviceProperties_(gpu.physical, &props);
+	gpu.storage_alignment = props.limits.minStorageBufferOffsetAlignment;
+	uint32_t qcount = 0;
+	vkGetPhysicalDeviceQueueFamilyProperties_(gpu.physical, &qcount, nullptr);
+	std::vector<VkQueueFamilyProperties> queues(qcount);
+	vkGetPhysicalDeviceQueueFamilyProperties_(gpu.physical, &qcount, queues.data());
+	for (uint32_t i = 0; i < qcount; ++i) {
+		if (queues[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) {
+			gpu.family = i;
+			break;
+		}
+	}
+	VkPhysicalDeviceFeatures supported {};
+	vkGetPhysicalDeviceFeatures_(gpu.physical, &supported);
+	Check(supported.vertexPipelineStoresAndAtomics, "device lacks vertexPipelineStoresAndAtomics (the VS cannot store)");
+	VkPhysicalDeviceFeatures features {};
+	features.vertexPipelineStoresAndAtomics = VK_TRUE;
+	features.fragmentStoresAndAtomics       = supported.fragmentStoresAndAtomics;
+	features.shaderClipDistance             = supported.shaderClipDistance; // the emitted VS has a clip guard
+	features.geometryShader                 = supported.geometryShader; // PrimitiveId in the PS needs the Geometry capability

@wuboo Thanks for confirming the fix. The support check and features.tessellationShader = VK_TRUE address this finding. GPU validation remains pending, as you noted.


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

✅ Review thread resolved.

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-12 13:54 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1441#discussion_r4248809605) On `tests/PerVertexVsStoreGpuTests.cpp` line 382 (outdated): ```diff @@ -0,0 +1,751 @@ +// GPU harness for KYTY_PV_VSSTORE (graphics/host_gpu/renderer/perVertexVsStore.h). The real SPIR-V +// emitter produces the VS-store VS and PS from an IR vertex shader and an ISA pixel shader, and the +// pair is drawn on the host GPU (MoltenVK) with the exact descriptor/push layout of the renderer: +// set 0 = empty, set 1 = {cap SSBO (VS|FS), guest index SSBO (FS)}, push = native data + 8 dwords. +// Checks (bit for bit, no tolerance): +// 1. image: every probed pixel equals the PerVertexKHR semantics computed on the CPU from the vertex +// data, the index buffer and the draw parameters (corner 0/1/2 read through P0/P10/P20), +// 2. cap: the records the VS wrote hold {gl_VertexIndex, gl_InstanceIndex} of the cases, which +// settles whether gl_VertexIndex includes vertex_offset and gl_InstanceIndex first_instance. +// Cases: 16-bit and 32-bit indices, vertex_offset > 0 and < 0, first_instance != 0, 2 instances, an index +// buffer bound at an offset that is not a multiple of minStorageBufferOffsetAlignment. +// Run: per_vertex_vsstore_gpu_tests [--dump] [--stress] (--stress: 2M triangles x 2..4 instances, parameter-buffer overflow) +// --dump needs no GPU: it prints the emitted SPIR-V. +// The result is compared with the CPU model of the per-vertex semantics. The mutants built from +// tests/PerVertexVsStoreMutants.cmake (corner 0/2 swapped, index range not rounded) must fail it. + +#include "common/emulatorConfig.h" +#include "common/logging/log.h" +#include "common/subsystems.h" +#include "common/threads.h" +#include "graphics/host_gpu/renderer/perVertexVsStore.h" +#include "graphics/shader/recompiler/ShaderRecompiler.h" +#include "graphics/shader/recompiler/backend/spirv/SpirvEmitter.h" +#include "graphics/shader/recompiler/ir/IREmitter.h" +#include "graphics/shader/recompiler/ir/ShaderIR.h" +#include "graphics/shader/recompiler/ir/passes/ResourceTracking.h" +#include "graphics/shader/shader.h" +#include "graphics/shader/shaderCompiler.h" + +#include <spirv-tools/libspirv.hpp> +#include <vulkan/vulkan.h> + +#include <dlfcn.h> + +#include <algorithm> +#include <array> +#include <cstdint> +#include <cstdio> +#include <cstdlib> +#include <cstring> +#include <span> +#include <string> +#include <vector> + +namespace Libs::Graphics { +namespace { + +using namespace ShaderRecompiler; + +bool g_stress = false; // --stress: the >= 2M triangle cases + +[[noreturn]] void Fail(const char* message) { + std::fprintf(stderr, "per-vertex-vsstore-gpu-tests: FAILED: %s\n", message); + std::exit(1); +} + +void Check(bool ok, const char* message) { + if (!ok) Fail(message); +} + +void CheckVk(VkResult result, const char* what) { + if (result != VK_SUCCESS) { + std::fprintf(stderr, "per-vertex-vsstore-gpu-tests: FAILED: %s (VkResult %d)\n", what, static_cast<int>(result)); + std::exit(1); + } +} + +constexpr uint32_t EncodeSopp(uint32_t opcode, uint32_t simm = 0) { + return (0x17fu << 23u) | ((opcode & 0x7fu) << 16u) | (simm & 0xffffu); +} +constexpr uint32_t EncodeVintrp(uint32_t opcode, uint32_t vdst, uint32_t attr, uint32_t chan, uint32_t vsrc) { + return (0x32u << 26u) | ((opcode & 0x3u) << 16u) | ((vdst & 0xffu) << 18u) | ((attr & 0x3fu) << 10u) | + ((chan & 0x3u) << 8u) | (vsrc & 0xffu); +} +constexpr uint32_t EncodeExp0(uint32_t target, uint32_t en) { + return (0x3eu << 26u) | ((target & 0x3fu) << 4u) | (en & 0xfu) | (1u << 11u); +} +constexpr uint32_t EncodeExp1(uint32_t a, uint32_t b, uint32_t c, uint32_t d) { + return (a & 0xffu) | ((b & 0xffu) << 8u) | ((c & 0xffu) << 16u) | ((d & 0xffu) << 24u); +} + +void EnsureConfigInitialized() { + static bool initialized = false; + if (initialized) return; + static Common::Subsystems subsystems; + Common::InitializeThreads(); + subsystems.Initialize<Config::Lifecycle>(); + Config::ConfigOptions options; + options.printf_direction = Config::LogDirection::Silent; + Config::Load(options); + subsystems.Initialize<Log::Lifecycle>(); + ShaderInit(); + initialized = true; +} + +// ---- shaders ------------------------------------------------------------------------------------- + +struct Shaders { + std::vector<uint32_t> vs; + std::vector<uint32_t> ps; + uint32_t stride_vec4 = 0; +}; + +// VS: position = attr0, param0 = attr1 with `+ instance` added to the bits of x (a 1 ulp difference +// per instance shows a record of the wrong instance), param1 = {gl_VertexIndex, gl_InstanceIndex, 0, 0}. +// PS: out = {corner0.x, corner1.y, corner2.z, corner0.w} of param0. +Shaders BuildShaders() { + using IR::Value; + using O = IR::ValueOpcode; + Shaders out; + + IR::Program vs; + vs.stage = ShaderType::Vertex; + vs.wave_size = 64; + vs.srt_plan_complete = vs.resource_tracking_complete = vs.shader_info_complete = true; + vs.block_storage.push_back(std::make_unique<IR::Block>()); + vs.blocks.push_back(vs.block_storage.back().get()); + vs.info.inputs = {{IR::StageInputKind::VertexIndex}, + {IR::StageInputKind::InstanceIndex}, + {IR::StageInputKind::Parameter, 0, 4}, + {IR::StageInputKind::Parameter, 1, 4}}; + vs.info.outputs = {{IR::StageOutputKind::Position}, + {IR::StageOutputKind::Parameter, 0, 0}, + {IR::StageOutputKind::Parameter, 1, 1}}; + vs.export_info = {{.kind = IR::ExportTargetKind::Position, .en = 15}, + {.kind = IR::ExportTargetKind::Parameter, .index = 0, .en = 15}, + {.kind = IR::ExportTargetKind::Parameter, .index = 1, .en = 15}}; + IR::IREmitter emit(vs.blocks.front()); + const auto vertex = emit.Emit(O::GetBuiltin, {Value(static_cast<uint32_t>(IR::StageInputKind::VertexIndex)), Value(0u)}); + const auto instance = emit.Emit(O::GetBuiltin, {Value(static_cast<uint32_t>(IR::StageInputKind::InstanceIndex)), Value(0u)}); + std::array<Value, 4> position, color; + for (uint32_t c = 0; c < 4; c++) position[c] = emit.Emit(O::GetAttribute, {Value(0u), Value(c)}); + for (uint32_t c = 0; c < 4; c++) color[c] = emit.Emit(O::GetAttribute, {Value(1u), Value(c)}); + const auto pos = emit.Emit(O::CompositeConstructU32x4, {position[0], position[1], position[2], position[3]}); + emit.Emit(O::SetAttribute, {pos, Value(true)}, IR::ExportFlags {0}); + const auto x = emit.Emit(O::IAdd32, {color[0], instance}); + const auto param0 = emit.Emit(O::CompositeConstructU32x4, {x, color[1], color[2], color[3]}); + emit.Emit(O::SetAttribute, {param0, Value(true)}, IR::ExportFlags {1}); + const auto param1 = emit.Emit(O::CompositeConstructU32x4, {vertex, instance, Value(0u), Value(0u)}); + emit.Emit(O::SetAttribute, {param1, Value(true)}, IR::ExportFlags {2}); + static const ShaderVertexInputInfo vertex_info {}; + ShaderStageInputInfo vs_input {.vertex = &vertex_info}; + + uint32_t vs_mask = 0; + Spirv::PvStoreInfo vs_store; + vs_store.role = Spirv::PvStoreInfo::Role::Vertex; + vs_store.coherent = true; + vs_store.location_mask = &vs_mask; + out.vs = Spirv::EmitProgram(vs, vs_input, 0, &vs_store); + + // PS (the interpolation setup of TestPvVsStoreEmission): v_interp_mov_f32 with P0 / P10 / P20. + const uint32_t ps_code[] = {EncodeVintrp(2, 12, 0, 0, 2), EncodeVintrp(2, 13, 0, 1, 0), + EncodeVintrp(2, 14, 0, 2, 1), EncodeVintrp(2, 15, 0, 3, 2), + EncodeExp0(0x00, 0xf), EncodeExp1(12, 13, 14, 15), + EncodeSopp(0x01)}; + static ShaderPixelInputInfo ps_info {}; + ps_info.input_num = 1; + ps_info.ps_system_input_base = 2; + ps_info.custom_interpolation_mask = 1; + ps_info.ps_perspective_center_vgpr = 0; + for (uint32_t i = 0; i < std::size(ps_info.interpolator_settings); i++) ps_info.interpolator_settings[i] = i; + ps_info.interpolator_settings[0] = 0x00000420u; + static const std::array<uint32_t, 64> user_data = [] { + std::array<uint32_t, 64> data {}; + data[3] = 3u << 28u; + return data; + }(); + CompileOptions options; + options.stage = ShaderType::Pixel; + options.user_data = user_data; + options.input_info.pixel = &ps_info; + auto translated = TranslateProgram(ps_code, options); + auto plan = IR::ExtractResourcePlan(translated.program); + IR::ResourceSnapshot resources; + IR::ResourceSpecialization specialization; + const IR::SrtRuntime runtime {.user_data = options.user_data, + .shader_base = reinterpret_cast<uint64_t>(ps_code), + .read_specialization_memory = [](void*, uint64_t, std::span<uint32_t>) { return false; }}; + Check(IR::MaterializeResources(plan, runtime, resources, specialization), "PS resources did not materialize"); + auto compiled = CompileProgram(std::move(translated), options, specialization, 0); + uint32_t ps_mask = 0; + Spirv::PvStoreInfo ps_store; + ps_store.role = Spirv::PvStoreInfo::Role::Pixel; + ps_store.coherent = true; + ps_store.location_mask = &ps_mask; + out.ps = Spirv::EmitProgram(compiled.program, options.input_info, 0, &ps_store); + + Check(ClassifyPvVsStoreInterface(vs_mask, ps_mask) == PvVsStoreInterfaceVerdict::Use, "VS/PS pair is not a VS-store candidate"); + out.stride_vec4 = PvVsStoreStrideFor(vs_mask); + if (out.stride_vec4 != 2) std::fprintf(stderr, "VS location mask %08x, PS location mask %08x\n", vs_mask, ps_mask); + Check(out.stride_vec4 == 2, "expected stride 2 (locations 0 and 1)"); + spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_2); + Check(tools.Validate(out.vs), "VS-store VS does not validate"); + Check(tools.Validate(out.ps), "VS-store PS does not validate"); + return out; +} + +// ---- scene (CPU model) --------------------------------------------------------------------------- + +constexpr uint32_t kDim = 32; // render target +constexpr uint32_t kCell = 16; // one triangle per cell: 2x2 cells +constexpr uint32_t kVertices = 24; // 4 triangles x 3 corners, plus 12 spare vertices for offsets +constexpr uint32_t kStrideB = 32; // float4 position, float4 color + +struct Vertex { + float position[4]; + float color[4]; +}; + +std::array<Vertex, kVertices> MakeVertices() { + std::array<Vertex, kVertices> v {}; + for (uint32_t i = 0; i < kVertices; ++i) { + const uint32_t tri = (i / 3u) % 4u; + const uint32_t cx = tri % 2u, cy = tri / 2u; + const float x0 = static_cast<float>(cx * kCell), y0 = static_cast<float>(cy * kCell); + const float px[3] = {x0 + 2.f, x0 + 14.f, x0 + 2.f}; + const float py[3] = {y0 + 2.f, y0 + 2.f, y0 + 14.f}; + const uint32_t k = i % 3u; + v[i].position[0] = px[k] / (kDim / 2.f) - 1.f; + v[i].position[1] = py[k] / (kDim / 2.f) - 1.f; + v[i].position[2] = 0.5f; + v[i].position[3] = 1.f; + // distinct, normal floats: any mix-up of a vertex, a corner or a component shows + v[i].color[0] = 1.0f + 0.03125f * static_cast<float>(i); + v[i].color[1] = 2.0f + 0.0625f * static_cast<float>(i); + v[i].color[2] = 3.0f + 0.125f * static_cast<float>(i); + v[i].color[3] = 4.0f + 0.25f * static_cast<float>(i); + } + return v; +} + +struct Case { + const char* name; + bool index32; + std::vector<uint32_t> indices; // per triangle corner, relative to vertex_offset + int32_t vertex_offset; + uint32_t first_instance; + uint32_t instance_count; + uint32_t bind_byte_offset; // where the index data starts inside the index buffer +}; + +uint32_t Bits(float f) { + uint32_t u; + std::memcpy(&u, &f, 4); + return u; +} + +// Expected pixel of triangle t of the draw: {corner0.x(+inst), corner1.y, corner2.z, corner0.w}. +std::array<uint32_t, 4> ExpectedPixel(const std::array<Vertex, kVertices>& v, const Case& c, uint32_t tri) { + const uint32_t last_instance = c.first_instance + c.instance_count - 1; + const auto vertex = [&](uint32_t corner) { return static_cast<uint32_t>(static_cast<int32_t>(c.indices[tri * 3 + corner]) + c.vertex_offset); }; + std::array<uint32_t, 4> out {}; + out[0] = Bits(v[vertex(0)].color[0]) + last_instance; + out[1] = Bits(v[vertex(1)].color[1]); + out[2] = Bits(v[vertex(2)].color[2]); + out[3] = Bits(v[vertex(0)].color[3]); + return out; +} + +// ---- Vulkan -------------------------------------------------------------------------------------- + +#define VK_FUNCS(X) \ + X(vkCreateDevice) X(vkGetDeviceProcAddr) X(vkEnumeratePhysicalDevices) X(vkGetPhysicalDeviceMemoryProperties) \ + X(vkGetPhysicalDeviceQueueFamilyProperties) X(vkGetPhysicalDeviceFeatures) X(vkGetPhysicalDeviceProperties) + +#define VK_DEVICE_FUNCS(X) \ + X(vkGetDeviceQueue) X(vkCreateBuffer) X(vkGetBufferMemoryRequirements) X(vkAllocateMemory) X(vkBindBufferMemory) \ + X(vkMapMemory) X(vkCreateDescriptorSetLayout) X(vkCreatePipelineLayout) X(vkCreateShaderModule) \ + X(vkCreateGraphicsPipelines) X(vkCreateDescriptorPool) X(vkAllocateDescriptorSets) X(vkUpdateDescriptorSets) \ + X(vkCreateCommandPool) X(vkAllocateCommandBuffers) X(vkBeginCommandBuffer) X(vkEndCommandBuffer) \ + X(vkCmdBindPipeline) X(vkCmdBindDescriptorSets) X(vkCmdPushConstants) X(vkCmdBeginRenderPass) X(vkCmdEndRenderPass) \ + X(vkCmdBindVertexBuffers) X(vkCmdBindIndexBuffer) X(vkCmdDrawIndexed) X(vkCmdCopyImageToBuffer) X(vkQueueSubmit) \ + X(vkQueueWaitIdle) X(vkCreateRenderPass) X(vkCreateFramebuffer) X(vkCreateImage) X(vkGetImageMemoryRequirements) \ + X(vkBindImageMemory) X(vkCreateImageView) X(vkCmdPipelineBarrier) + +#define DECLARE(name) PFN_##name name##_ = nullptr; +VK_FUNCS(DECLARE) +VK_DEVICE_FUNCS(DECLARE) +#undef DECLARE + +struct Gpu { + VkInstance instance = VK_NULL_HANDLE; + VkPhysicalDevice physical = VK_NULL_HANDLE; + VkDevice device = VK_NULL_HANDLE; + VkQueue queue = VK_NULL_HANDLE; + uint32_t family = 0; + VkPhysicalDeviceMemoryProperties memory {}; + VkDeviceSize storage_alignment = 16; +}; + +struct Buf { + VkBuffer buffer = VK_NULL_HANDLE; + VkDeviceMemory memory = VK_NULL_HANDLE; + void* mapped = nullptr; + size_t size = 0; +}; + +uint32_t MemoryType(const Gpu& gpu, uint32_t bits, VkMemoryPropertyFlags flags) { + for (uint32_t i = 0; i < gpu.memory.memoryTypeCount; ++i) { + if ((bits & (1u << i)) && (gpu.memory.memoryTypes[i].propertyFlags & flags) == flags) return i; + } + Fail("no suitable memory type"); +} + +Buf MakeBuffer(const Gpu& gpu, size_t size, VkBufferUsageFlags usage) { + Buf b; + b.size = size; + VkBufferCreateInfo info {VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; + info.size = size; + info.usage = usage; + CheckVk(vkCreateBuffer_(gpu.device, &info, nullptr, &b.buffer), "vkCreateBuffer"); + VkMemoryRequirements req; + vkGetBufferMemoryRequirements_(gpu.device, b.buffer, &req); + VkMemoryAllocateInfo alloc {VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; + alloc.allocationSize = req.size; + alloc.memoryTypeIndex = MemoryType(gpu, req.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); + CheckVk(vkAllocateMemory_(gpu.device, &alloc, nullptr, &b.memory), "vkAllocateMemory"); + CheckVk(vkBindBufferMemory_(gpu.device, b.buffer, b.memory, 0), "vkBindBufferMemory"); + CheckVk(vkMapMemory_(gpu.device, b.memory, 0, size, 0, &b.mapped), "vkMapMemory"); + std::memset(b.mapped, 0xA5, size); + return b; +} + +Gpu InitGpu() { + const char* driver = std::getenv("SDL_VULKAN_LIBRARY"); + void* lib = dlopen(driver != nullptr ? driver : "libMoltenVK.dylib", RTLD_NOW | RTLD_LOCAL); + if (lib == nullptr) Fail("cannot load MoltenVK; set SDL_VULKAN_LIBRARY"); + auto get_instance_proc = reinterpret_cast<PFN_vkGetInstanceProcAddr>(dlsym(lib, "vkGetInstanceProcAddr")); + if (get_instance_proc == nullptr) Fail("dlsym vkGetInstanceProcAddr"); + auto create_instance = reinterpret_cast<PFN_vkCreateInstance>(get_instance_proc(VK_NULL_HANDLE, "vkCreateInstance")); + auto enumerate_extensions = reinterpret_cast<PFN_vkEnumerateInstanceExtensionProperties>( + get_instance_proc(VK_NULL_HANDLE, "vkEnumerateInstanceExtensionProperties")); + if (enumerate_extensions == nullptr) Fail("vkEnumerateInstanceExtensionProperties"); + uint32_t extension_count = 0; + CheckVk(enumerate_extensions(nullptr, &extension_count, nullptr), "vkEnumerateInstanceExtensionProperties"); + std::vector<VkExtensionProperties> available(extension_count); + CheckVk(enumerate_extensions(nullptr, &extension_count, available.data()), "vkEnumerateInstanceExtensionProperties list"); + bool has_portability = false; + for (const auto& e: available) { + if (std::strcmp(e.extensionName, VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME) == 0) has_portability = true; + } + const char* extensions[] {VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME}; + VkApplicationInfo app {VK_STRUCTURE_TYPE_APPLICATION_INFO}; + app.apiVersion = VK_API_VERSION_1_3; + VkInstanceCreateInfo info {VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO}; + info.pApplicationInfo = &app; + info.flags = has_portability ? VK_INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR : 0; + info.enabledExtensionCount = has_portability ? 1u : 0u; + info.ppEnabledExtensionNames = has_portability ? extensions : nullptr; + Gpu gpu; + CheckVk(create_instance(&info, nullptr, &gpu.instance), "vkCreateInstance"); +#define LOAD_INSTANCE(name) name##_ = reinterpret_cast<PFN_##name>(get_instance_proc(gpu.instance, #name)); + VK_FUNCS(LOAD_INSTANCE) +#undef LOAD_INSTANCE + uint32_t count = 0; + CheckVk(vkEnumeratePhysicalDevices_(gpu.instance, &count, nullptr), "vkEnumeratePhysicalDevices"); + Check(count > 0, "no physical device"); + std::vector<VkPhysicalDevice> devices(count); + CheckVk(vkEnumeratePhysicalDevices_(gpu.instance, &count, devices.data()), "vkEnumeratePhysicalDevices list"); + gpu.physical = devices[0]; + vkGetPhysicalDeviceMemoryProperties_(gpu.physical, &gpu.memory); + VkPhysicalDeviceProperties props {}; + vkGetPhysicalDeviceProperties_(gpu.physical, &props); + gpu.storage_alignment = props.limits.minStorageBufferOffsetAlignment; + uint32_t qcount = 0; + vkGetPhysicalDeviceQueueFamilyProperties_(gpu.physical, &qcount, nullptr); + std::vector<VkQueueFamilyProperties> queues(qcount); + vkGetPhysicalDeviceQueueFamilyProperties_(gpu.physical, &qcount, queues.data()); + for (uint32_t i = 0; i < qcount; ++i) { + if (queues[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) { + gpu.family = i; + break; + } + } + VkPhysicalDeviceFeatures supported {}; + vkGetPhysicalDeviceFeatures_(gpu.physical, &supported); + Check(supported.vertexPipelineStoresAndAtomics, "device lacks vertexPipelineStoresAndAtomics (the VS cannot store)"); + VkPhysicalDeviceFeatures features {}; + features.vertexPipelineStoresAndAtomics = VK_TRUE; + features.fragmentStoresAndAtomics = supported.fragmentStoresAndAtomics; + features.shaderClipDistance = supported.shaderClipDistance; // the emitted VS has a clip guard + features.geometryShader = supported.geometryShader; // PrimitiveId in the PS needs the Geometry capability ``` `@wuboo` Thanks for confirming the fix. The support check and `features.tessellationShader = VK_TRUE` address this finding. GPU validation remains pending, as you noted. --- <!-- This is an auto-generated comment: tweet message by coderabbit.ai --> If you found this review helpful, would you consider giving us a shout-out on [X](https://twitter.com/intent/tweet?related=CodeRabbitAI&text=Enable%20%60tessellationShader%60%E2%80%94not%20%60geometryShader%60%E2%80%94for%20%60PrimitiveId%60%E2%80%99s%20SPIR-V%20capability.%20This%20aligns%20the%20harness%20with%20the%20renderer%20and%20avoids%20validation%20errors.%20Try%20%40coderabbitai%20%F0%9F%90%87%E2%9C%85&url=https%3A%2F%2Fgithub.com%2FKytyPS5%2FKytyPS5%2Fpull%2F1441%23discussion_r4246882880)? Thank you for using CodeRabbit! <!-- end of auto-generated comment: tweet message by coderabbit.ai --> ✅ Review thread resolved. _You are interacting with an AI system._ <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠wuboo on GitHub · 2026-10-12 15:21 UTC · original
On tests/PerVertexVsStoreGpuTests.cpp line 382 (outdated):

@@ -0,0 +1,751 @@
+// GPU harness for KYTY_PV_VSSTORE (graphics/host_gpu/renderer/perVertexVsStore.h). The real SPIR-V
+// emitter produces the VS-store VS and PS from an IR vertex shader and an ISA pixel shader, and the
+// pair is drawn on the host GPU (MoltenVK) with the exact descriptor/push layout of the renderer:
+//   set 0 = empty, set 1 = {cap SSBO (VS|FS), guest index SSBO (FS)}, push = native data + 8 dwords.
+// Checks (bit for bit, no tolerance):
+//   1. image: every probed pixel equals the PerVertexKHR semantics computed on the CPU from the vertex
+//      data, the index buffer and the draw parameters (corner 0/1/2 read through P0/P10/P20),
+//   2. cap: the records the VS wrote hold {gl_VertexIndex, gl_InstanceIndex} of the cases, which
+//      settles whether gl_VertexIndex includes vertex_offset and gl_InstanceIndex first_instance.
+// Cases: 16-bit and 32-bit indices, vertex_offset > 0 and < 0, first_instance != 0, 2 instances, an index
+// buffer bound at an offset that is not a multiple of minStorageBufferOffsetAlignment.
+// Run: per_vertex_vsstore_gpu_tests [--dump] [--stress]  (--stress: 2M triangles x 2..4 instances, parameter-buffer overflow)
+//   --dump needs no GPU: it prints the emitted SPIR-V.
+// The result is compared with the CPU model of the per-vertex semantics. The mutants built from
+// tests/PerVertexVsStoreMutants.cmake (corner 0/2 swapped, index range not rounded) must fail it.
+
+#include "common/emulatorConfig.h"
+#include "common/logging/log.h"
+#include "common/subsystems.h"
+#include "common/threads.h"
+#include "graphics/host_gpu/renderer/perVertexVsStore.h"
+#include "graphics/shader/recompiler/ShaderRecompiler.h"
+#include "graphics/shader/recompiler/backend/spirv/SpirvEmitter.h"
+#include "graphics/shader/recompiler/ir/IREmitter.h"
+#include "graphics/shader/recompiler/ir/ShaderIR.h"
+#include "graphics/shader/recompiler/ir/passes/ResourceTracking.h"
+#include "graphics/shader/shader.h"
+#include "graphics/shader/shaderCompiler.h"
+
+#include <spirv-tools/libspirv.hpp>
+#include <vulkan/vulkan.h>
+
+#include <dlfcn.h>
+
+#include <algorithm>
+#include <array>
+#include <cstdint>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <span>
+#include <string>
+#include <vector>
+
+namespace Libs::Graphics {
+namespace {
+
+using namespace ShaderRecompiler;
+
+bool g_stress = false; // --stress: the >= 2M triangle cases
+
+[[noreturn]] void Fail(const char* message) {
+	std::fprintf(stderr, "per-vertex-vsstore-gpu-tests: FAILED: %s\n", message);
+	std::exit(1);
+}
+
+void Check(bool ok, const char* message) {
+	if (!ok) Fail(message);
+}
+
+void CheckVk(VkResult result, const char* what) {
+	if (result != VK_SUCCESS) {
+		std::fprintf(stderr, "per-vertex-vsstore-gpu-tests: FAILED: %s (VkResult %d)\n", what, static_cast<int>(result));
+		std::exit(1);
+	}
+}
+
+constexpr uint32_t EncodeSopp(uint32_t opcode, uint32_t simm = 0) {
+	return (0x17fu << 23u) | ((opcode & 0x7fu) << 16u) | (simm & 0xffffu);
+}
+constexpr uint32_t EncodeVintrp(uint32_t opcode, uint32_t vdst, uint32_t attr, uint32_t chan, uint32_t vsrc) {
+	return (0x32u << 26u) | ((opcode & 0x3u) << 16u) | ((vdst & 0xffu) << 18u) | ((attr & 0x3fu) << 10u) |
+	       ((chan & 0x3u) << 8u) | (vsrc & 0xffu);
+}
+constexpr uint32_t EncodeExp0(uint32_t target, uint32_t en) {
+	return (0x3eu << 26u) | ((target & 0x3fu) << 4u) | (en & 0xfu) | (1u << 11u);
+}
+constexpr uint32_t EncodeExp1(uint32_t a, uint32_t b, uint32_t c, uint32_t d) {
+	return (a & 0xffu) | ((b & 0xffu) << 8u) | ((c & 0xffu) << 16u) | ((d & 0xffu) << 24u);
+}
+
+void EnsureConfigInitialized() {
+	static bool initialized = false;
+	if (initialized) return;
+	static Common::Subsystems subsystems;
+	Common::InitializeThreads();
+	subsystems.Initialize<Config::Lifecycle>();
+	Config::ConfigOptions options;
+	options.printf_direction = Config::LogDirection::Silent;
+	Config::Load(options);
+	subsystems.Initialize<Log::Lifecycle>();
+	ShaderInit();
+	initialized = true;
+}
+
+// ---- shaders -------------------------------------------------------------------------------------
+
+struct Shaders {
+	std::vector<uint32_t> vs;
+	std::vector<uint32_t> ps;
+	uint32_t              stride_vec4 = 0;
+};
+
+// VS: position = attr0, param0 = attr1 with `+ instance` added to the bits of x (a 1 ulp difference
+// per instance shows a record of the wrong instance), param1 = {gl_VertexIndex, gl_InstanceIndex, 0, 0}.
+// PS: out = {corner0.x, corner1.y, corner2.z, corner0.w} of param0.
+Shaders BuildShaders() {
+	using IR::Value;
+	using O = IR::ValueOpcode;
+	Shaders out;
+
+	IR::Program vs;
+	vs.stage                  = ShaderType::Vertex;
+	vs.wave_size              = 64;
+	vs.srt_plan_complete      = vs.resource_tracking_complete = vs.shader_info_complete = true;
+	vs.block_storage.push_back(std::make_unique<IR::Block>());
+	vs.blocks.push_back(vs.block_storage.back().get());
+	vs.info.inputs  = {{IR::StageInputKind::VertexIndex},
+	                   {IR::StageInputKind::InstanceIndex},
+	                   {IR::StageInputKind::Parameter, 0, 4},
+	                   {IR::StageInputKind::Parameter, 1, 4}};
+	vs.info.outputs = {{IR::StageOutputKind::Position},
+	                   {IR::StageOutputKind::Parameter, 0, 0},
+	                   {IR::StageOutputKind::Parameter, 1, 1}};
+	vs.export_info  = {{.kind = IR::ExportTargetKind::Position, .en = 15},
+	                   {.kind = IR::ExportTargetKind::Parameter, .index = 0, .en = 15},
+	                   {.kind = IR::ExportTargetKind::Parameter, .index = 1, .en = 15}};
+	IR::IREmitter emit(vs.blocks.front());
+	const auto vertex   = emit.Emit(O::GetBuiltin, {Value(static_cast<uint32_t>(IR::StageInputKind::VertexIndex)), Value(0u)});
+	const auto instance = emit.Emit(O::GetBuiltin, {Value(static_cast<uint32_t>(IR::StageInputKind::InstanceIndex)), Value(0u)});
+	std::array<Value, 4> position, color;
+	for (uint32_t c = 0; c < 4; c++) position[c] = emit.Emit(O::GetAttribute, {Value(0u), Value(c)});
+	for (uint32_t c = 0; c < 4; c++) color[c] = emit.Emit(O::GetAttribute, {Value(1u), Value(c)});
+	const auto pos = emit.Emit(O::CompositeConstructU32x4, {position[0], position[1], position[2], position[3]});
+	emit.Emit(O::SetAttribute, {pos, Value(true)}, IR::ExportFlags {0});
+	const auto x      = emit.Emit(O::IAdd32, {color[0], instance});
+	const auto param0 = emit.Emit(O::CompositeConstructU32x4, {x, color[1], color[2], color[3]});
+	emit.Emit(O::SetAttribute, {param0, Value(true)}, IR::ExportFlags {1});
+	const auto param1 = emit.Emit(O::CompositeConstructU32x4, {vertex, instance, Value(0u), Value(0u)});
+	emit.Emit(O::SetAttribute, {param1, Value(true)}, IR::ExportFlags {2});
+	static const ShaderVertexInputInfo vertex_info {};
+	ShaderStageInputInfo               vs_input {.vertex = &vertex_info};
+
+	uint32_t vs_mask = 0;
+	Spirv::PvStoreInfo vs_store;
+	vs_store.role          = Spirv::PvStoreInfo::Role::Vertex;
+	vs_store.coherent      = true;
+	vs_store.location_mask = &vs_mask;
+	out.vs                 = Spirv::EmitProgram(vs, vs_input, 0, &vs_store);
+
+	// PS (the interpolation setup of TestPvVsStoreEmission): v_interp_mov_f32 with P0 / P10 / P20.
+	const uint32_t ps_code[] = {EncodeVintrp(2, 12, 0, 0, 2), EncodeVintrp(2, 13, 0, 1, 0),
+	                            EncodeVintrp(2, 14, 0, 2, 1), EncodeVintrp(2, 15, 0, 3, 2),
+	                            EncodeExp0(0x00, 0xf),        EncodeExp1(12, 13, 14, 15),
+	                            EncodeSopp(0x01)};
+	static ShaderPixelInputInfo ps_info {};
+	ps_info.input_num                 = 1;
+	ps_info.ps_system_input_base      = 2;
+	ps_info.custom_interpolation_mask = 1;
+	ps_info.ps_perspective_center_vgpr = 0;
+	for (uint32_t i = 0; i < std::size(ps_info.interpolator_settings); i++) ps_info.interpolator_settings[i] = i;
+	ps_info.interpolator_settings[0] = 0x00000420u;
+	static const std::array<uint32_t, 64> user_data = [] {
+		std::array<uint32_t, 64> data {};
+		data[3] = 3u << 28u;
+		return data;
+	}();
+	CompileOptions options;
+	options.stage            = ShaderType::Pixel;
+	options.user_data        = user_data;
+	options.input_info.pixel = &ps_info;
+	auto translated          = TranslateProgram(ps_code, options);
+	auto plan                = IR::ExtractResourcePlan(translated.program);
+	IR::ResourceSnapshot       resources;
+	IR::ResourceSpecialization specialization;
+	const IR::SrtRuntime       runtime {.user_data = options.user_data,
+	                                    .shader_base = reinterpret_cast<uint64_t>(ps_code),
+	                                    .read_specialization_memory = [](void*, uint64_t, std::span<uint32_t>) { return false; }};
+	Check(IR::MaterializeResources(plan, runtime, resources, specialization), "PS resources did not materialize");
+	auto compiled = CompileProgram(std::move(translated), options, specialization, 0);
+	uint32_t ps_mask = 0;
+	Spirv::PvStoreInfo ps_store;
+	ps_store.role          = Spirv::PvStoreInfo::Role::Pixel;
+	ps_store.coherent      = true;
+	ps_store.location_mask = &ps_mask;
+	out.ps                 = Spirv::EmitProgram(compiled.program, options.input_info, 0, &ps_store);
+
+	Check(ClassifyPvVsStoreInterface(vs_mask, ps_mask) == PvVsStoreInterfaceVerdict::Use, "VS/PS pair is not a VS-store candidate");
+	out.stride_vec4 = PvVsStoreStrideFor(vs_mask);
+	if (out.stride_vec4 != 2) std::fprintf(stderr, "VS location mask %08x, PS location mask %08x\n", vs_mask, ps_mask);
+	Check(out.stride_vec4 == 2, "expected stride 2 (locations 0 and 1)");
+	spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_2);
+	Check(tools.Validate(out.vs), "VS-store VS does not validate");
+	Check(tools.Validate(out.ps), "VS-store PS does not validate");
+	return out;
+}
+
+// ---- scene (CPU model) ---------------------------------------------------------------------------
+
+constexpr uint32_t kDim      = 32; // render target
+constexpr uint32_t kCell     = 16; // one triangle per cell: 2x2 cells
+constexpr uint32_t kVertices = 24; // 4 triangles x 3 corners, plus 12 spare vertices for offsets
+constexpr uint32_t kStrideB  = 32; // float4 position, float4 color
+
+struct Vertex {
+	float position[4];
+	float color[4];
+};
+
+std::array<Vertex, kVertices> MakeVertices() {
+	std::array<Vertex, kVertices> v {};
+	for (uint32_t i = 0; i < kVertices; ++i) {
+		const uint32_t tri = (i / 3u) % 4u;
+		const uint32_t cx  = tri % 2u, cy = tri / 2u;
+		const float    x0  = static_cast<float>(cx * kCell), y0 = static_cast<float>(cy * kCell);
+		const float    px[3] = {x0 + 2.f, x0 + 14.f, x0 + 2.f};
+		const float    py[3] = {y0 + 2.f, y0 + 2.f, y0 + 14.f};
+		const uint32_t k     = i % 3u;
+		v[i].position[0] = px[k] / (kDim / 2.f) - 1.f;
+		v[i].position[1] = py[k] / (kDim / 2.f) - 1.f;
+		v[i].position[2] = 0.5f;
+		v[i].position[3] = 1.f;
+		// distinct, normal floats: any mix-up of a vertex, a corner or a component shows
+		v[i].color[0] = 1.0f + 0.03125f * static_cast<float>(i);
+		v[i].color[1] = 2.0f + 0.0625f * static_cast<float>(i);
+		v[i].color[2] = 3.0f + 0.125f * static_cast<float>(i);
+		v[i].color[3] = 4.0f + 0.25f * static_cast<float>(i);
+	}
+	return v;
+}
+
+struct Case {
+	const char*           name;
+	bool                  index32;
+	std::vector<uint32_t> indices;       // per triangle corner, relative to vertex_offset
+	int32_t               vertex_offset;
+	uint32_t              first_instance;
+	uint32_t              instance_count;
+	uint32_t              bind_byte_offset; // where the index data starts inside the index buffer
+};
+
+uint32_t Bits(float f) {
+	uint32_t u;
+	std::memcpy(&u, &f, 4);
+	return u;
+}
+
+// Expected pixel of triangle t of the draw: {corner0.x(+inst), corner1.y, corner2.z, corner0.w}.
+std::array<uint32_t, 4> ExpectedPixel(const std::array<Vertex, kVertices>& v, const Case& c, uint32_t tri) {
+	const uint32_t last_instance = c.first_instance + c.instance_count - 1;
+	const auto     vertex = [&](uint32_t corner) { return static_cast<uint32_t>(static_cast<int32_t>(c.indices[tri * 3 + corner]) + c.vertex_offset); };
+	std::array<uint32_t, 4> out {};
+	out[0] = Bits(v[vertex(0)].color[0]) + last_instance;
+	out[1] = Bits(v[vertex(1)].color[1]);
+	out[2] = Bits(v[vertex(2)].color[2]);
+	out[3] = Bits(v[vertex(0)].color[3]);
+	return out;
+}
+
+// ---- Vulkan --------------------------------------------------------------------------------------
+
+#define VK_FUNCS(X)                                                                                                        \
+	X(vkCreateDevice) X(vkGetDeviceProcAddr) X(vkEnumeratePhysicalDevices) X(vkGetPhysicalDeviceMemoryProperties)          \
+	X(vkGetPhysicalDeviceQueueFamilyProperties) X(vkGetPhysicalDeviceFeatures) X(vkGetPhysicalDeviceProperties)
+
+#define VK_DEVICE_FUNCS(X)                                                                                                 \
+	X(vkGetDeviceQueue) X(vkCreateBuffer) X(vkGetBufferMemoryRequirements) X(vkAllocateMemory) X(vkBindBufferMemory)      \
+	X(vkMapMemory) X(vkCreateDescriptorSetLayout) X(vkCreatePipelineLayout) X(vkCreateShaderModule)                         \
+	X(vkCreateGraphicsPipelines) X(vkCreateDescriptorPool) X(vkAllocateDescriptorSets) X(vkUpdateDescriptorSets)           \
+	X(vkCreateCommandPool) X(vkAllocateCommandBuffers) X(vkBeginCommandBuffer) X(vkEndCommandBuffer)                       \
+	X(vkCmdBindPipeline) X(vkCmdBindDescriptorSets) X(vkCmdPushConstants) X(vkCmdBeginRenderPass) X(vkCmdEndRenderPass)    \
+	X(vkCmdBindVertexBuffers) X(vkCmdBindIndexBuffer) X(vkCmdDrawIndexed) X(vkCmdCopyImageToBuffer) X(vkQueueSubmit)      \
+	X(vkQueueWaitIdle) X(vkCreateRenderPass) X(vkCreateFramebuffer) X(vkCreateImage) X(vkGetImageMemoryRequirements)       \
+	X(vkBindImageMemory) X(vkCreateImageView) X(vkCmdPipelineBarrier)
+
+#define DECLARE(name) PFN_##name name##_ = nullptr;
+VK_FUNCS(DECLARE)
+VK_DEVICE_FUNCS(DECLARE)
+#undef DECLARE
+
+struct Gpu {
+	VkInstance                       instance = VK_NULL_HANDLE;
+	VkPhysicalDevice                 physical = VK_NULL_HANDLE;
+	VkDevice                         device   = VK_NULL_HANDLE;
+	VkQueue                          queue    = VK_NULL_HANDLE;
+	uint32_t                         family   = 0;
+	VkPhysicalDeviceMemoryProperties memory {};
+	VkDeviceSize                     storage_alignment = 16;
+};
+
+struct Buf {
+	VkBuffer       buffer = VK_NULL_HANDLE;
+	VkDeviceMemory memory = VK_NULL_HANDLE;
+	void*          mapped = nullptr;
+	size_t         size   = 0;
+};
+
+uint32_t MemoryType(const Gpu& gpu, uint32_t bits, VkMemoryPropertyFlags flags) {
+	for (uint32_t i = 0; i < gpu.memory.memoryTypeCount; ++i) {
+		if ((bits & (1u << i)) && (gpu.memory.memoryTypes[i].propertyFlags & flags) == flags) return i;
+	}
+	Fail("no suitable memory type");
+}
+
+Buf MakeBuffer(const Gpu& gpu, size_t size, VkBufferUsageFlags usage) {
+	Buf b;
+	b.size = size;
+	VkBufferCreateInfo info {VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
+	info.size  = size;
+	info.usage = usage;
+	CheckVk(vkCreateBuffer_(gpu.device, &info, nullptr, &b.buffer), "vkCreateBuffer");
+	VkMemoryRequirements req;
+	vkGetBufferMemoryRequirements_(gpu.device, b.buffer, &req);
+	VkMemoryAllocateInfo alloc {VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
+	alloc.allocationSize  = req.size;
+	alloc.memoryTypeIndex = MemoryType(gpu, req.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
+	CheckVk(vkAllocateMemory_(gpu.device, &alloc, nullptr, &b.memory), "vkAllocateMemory");
+	CheckVk(vkBindBufferMemory_(gpu.device, b.buffer, b.memory, 0), "vkBindBufferMemory");
+	CheckVk(vkMapMemory_(gpu.device, b.memory, 0, size, 0, &b.mapped), "vkMapMemory");
+	std::memset(b.mapped, 0xA5, size);
+	return b;
+}
+
+Gpu InitGpu() {
+	const char* driver = std::getenv("SDL_VULKAN_LIBRARY");
+	void*       lib    = dlopen(driver != nullptr ? driver : "libMoltenVK.dylib", RTLD_NOW | RTLD_LOCAL);
+	if (lib == nullptr) Fail("cannot load MoltenVK; set SDL_VULKAN_LIBRARY");
+	auto get_instance_proc = reinterpret_cast<PFN_vkGetInstanceProcAddr>(dlsym(lib, "vkGetInstanceProcAddr"));
+	if (get_instance_proc == nullptr) Fail("dlsym vkGetInstanceProcAddr");
+	auto create_instance = reinterpret_cast<PFN_vkCreateInstance>(get_instance_proc(VK_NULL_HANDLE, "vkCreateInstance"));
+	auto enumerate_extensions = reinterpret_cast<PFN_vkEnumerateInstanceExtensionProperties>(
+	    get_instance_proc(VK_NULL_HANDLE, "vkEnumerateInstanceExtensionProperties"));
+	if (enumerate_extensions == nullptr) Fail("vkEnumerateInstanceExtensionProperties");
+	uint32_t extension_count = 0;
+	CheckVk(enumerate_extensions(nullptr, &extension_count, nullptr), "vkEnumerateInstanceExtensionProperties");
+	std::vector<VkExtensionProperties> available(extension_count);
+	CheckVk(enumerate_extensions(nullptr, &extension_count, available.data()), "vkEnumerateInstanceExtensionProperties list");
+	bool has_portability = false;
+	for (const auto& e: available) {
+		if (std::strcmp(e.extensionName, VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME) == 0) has_portability = true;
+	}
+	const char* extensions[] {VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME};
+	VkApplicationInfo app {VK_STRUCTURE_TYPE_APPLICATION_INFO};
+	app.apiVersion = VK_API_VERSION_1_3;
+	VkInstanceCreateInfo info {VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO};
+	info.pApplicationInfo        = &app;
+	info.flags                   = has_portability ? VK_INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR : 0;
+	info.enabledExtensionCount   = has_portability ? 1u : 0u;
+	info.ppEnabledExtensionNames = has_portability ? extensions : nullptr;
+	Gpu gpu;
+	CheckVk(create_instance(&info, nullptr, &gpu.instance), "vkCreateInstance");
+#define LOAD_INSTANCE(name) name##_ = reinterpret_cast<PFN_##name>(get_instance_proc(gpu.instance, #name));
+	VK_FUNCS(LOAD_INSTANCE)
+#undef LOAD_INSTANCE
+	uint32_t count = 0;
+	CheckVk(vkEnumeratePhysicalDevices_(gpu.instance, &count, nullptr), "vkEnumeratePhysicalDevices");
+	Check(count > 0, "no physical device");
+	std::vector<VkPhysicalDevice> devices(count);
+	CheckVk(vkEnumeratePhysicalDevices_(gpu.instance, &count, devices.data()), "vkEnumeratePhysicalDevices list");
+	gpu.physical = devices[0];
+	vkGetPhysicalDeviceMemoryProperties_(gpu.physical, &gpu.memory);
+	VkPhysicalDeviceProperties props {};
+	vkGetPhysicalDeviceProperties_(gpu.physical, &props);
+	gpu.storage_alignment = props.limits.minStorageBufferOffsetAlignment;
+	uint32_t qcount = 0;
+	vkGetPhysicalDeviceQueueFamilyProperties_(gpu.physical, &qcount, nullptr);
+	std::vector<VkQueueFamilyProperties> queues(qcount);
+	vkGetPhysicalDeviceQueueFamilyProperties_(gpu.physical, &qcount, queues.data());
+	for (uint32_t i = 0; i < qcount; ++i) {
+		if (queues[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) {
+			gpu.family = i;
+			break;
+		}
+	}
+	VkPhysicalDeviceFeatures supported {};
+	vkGetPhysicalDeviceFeatures_(gpu.physical, &supported);
+	Check(supported.vertexPipelineStoresAndAtomics, "device lacks vertexPipelineStoresAndAtomics (the VS cannot store)");
+	VkPhysicalDeviceFeatures features {};
+	features.vertexPipelineStoresAndAtomics = VK_TRUE;
+	features.fragmentStoresAndAtomics       = supported.fragmentStoresAndAtomics;
+	features.shaderClipDistance             = supported.shaderClipDistance; // the emitted VS has a clip guard
+	features.geometryShader                 = supported.geometryShader; // PrimitiveId in the PS needs the Geometry capability

Follow-up: with 8977bb43 the harness enables tessellationShader and has been run on MoltenVK (Apple M3 Max): all 7 cases pass, --stress passes, and both harness mutants fail as expected.

**@⁠wuboo** on GitHub · 2026-10-12 15:21 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1441#discussion_r4249658221) On `tests/PerVertexVsStoreGpuTests.cpp` line 382 (outdated): ```diff @@ -0,0 +1,751 @@ +// GPU harness for KYTY_PV_VSSTORE (graphics/host_gpu/renderer/perVertexVsStore.h). The real SPIR-V +// emitter produces the VS-store VS and PS from an IR vertex shader and an ISA pixel shader, and the +// pair is drawn on the host GPU (MoltenVK) with the exact descriptor/push layout of the renderer: +// set 0 = empty, set 1 = {cap SSBO (VS|FS), guest index SSBO (FS)}, push = native data + 8 dwords. +// Checks (bit for bit, no tolerance): +// 1. image: every probed pixel equals the PerVertexKHR semantics computed on the CPU from the vertex +// data, the index buffer and the draw parameters (corner 0/1/2 read through P0/P10/P20), +// 2. cap: the records the VS wrote hold {gl_VertexIndex, gl_InstanceIndex} of the cases, which +// settles whether gl_VertexIndex includes vertex_offset and gl_InstanceIndex first_instance. +// Cases: 16-bit and 32-bit indices, vertex_offset > 0 and < 0, first_instance != 0, 2 instances, an index +// buffer bound at an offset that is not a multiple of minStorageBufferOffsetAlignment. +// Run: per_vertex_vsstore_gpu_tests [--dump] [--stress] (--stress: 2M triangles x 2..4 instances, parameter-buffer overflow) +// --dump needs no GPU: it prints the emitted SPIR-V. +// The result is compared with the CPU model of the per-vertex semantics. The mutants built from +// tests/PerVertexVsStoreMutants.cmake (corner 0/2 swapped, index range not rounded) must fail it. + +#include "common/emulatorConfig.h" +#include "common/logging/log.h" +#include "common/subsystems.h" +#include "common/threads.h" +#include "graphics/host_gpu/renderer/perVertexVsStore.h" +#include "graphics/shader/recompiler/ShaderRecompiler.h" +#include "graphics/shader/recompiler/backend/spirv/SpirvEmitter.h" +#include "graphics/shader/recompiler/ir/IREmitter.h" +#include "graphics/shader/recompiler/ir/ShaderIR.h" +#include "graphics/shader/recompiler/ir/passes/ResourceTracking.h" +#include "graphics/shader/shader.h" +#include "graphics/shader/shaderCompiler.h" + +#include <spirv-tools/libspirv.hpp> +#include <vulkan/vulkan.h> + +#include <dlfcn.h> + +#include <algorithm> +#include <array> +#include <cstdint> +#include <cstdio> +#include <cstdlib> +#include <cstring> +#include <span> +#include <string> +#include <vector> + +namespace Libs::Graphics { +namespace { + +using namespace ShaderRecompiler; + +bool g_stress = false; // --stress: the >= 2M triangle cases + +[[noreturn]] void Fail(const char* message) { + std::fprintf(stderr, "per-vertex-vsstore-gpu-tests: FAILED: %s\n", message); + std::exit(1); +} + +void Check(bool ok, const char* message) { + if (!ok) Fail(message); +} + +void CheckVk(VkResult result, const char* what) { + if (result != VK_SUCCESS) { + std::fprintf(stderr, "per-vertex-vsstore-gpu-tests: FAILED: %s (VkResult %d)\n", what, static_cast<int>(result)); + std::exit(1); + } +} + +constexpr uint32_t EncodeSopp(uint32_t opcode, uint32_t simm = 0) { + return (0x17fu << 23u) | ((opcode & 0x7fu) << 16u) | (simm & 0xffffu); +} +constexpr uint32_t EncodeVintrp(uint32_t opcode, uint32_t vdst, uint32_t attr, uint32_t chan, uint32_t vsrc) { + return (0x32u << 26u) | ((opcode & 0x3u) << 16u) | ((vdst & 0xffu) << 18u) | ((attr & 0x3fu) << 10u) | + ((chan & 0x3u) << 8u) | (vsrc & 0xffu); +} +constexpr uint32_t EncodeExp0(uint32_t target, uint32_t en) { + return (0x3eu << 26u) | ((target & 0x3fu) << 4u) | (en & 0xfu) | (1u << 11u); +} +constexpr uint32_t EncodeExp1(uint32_t a, uint32_t b, uint32_t c, uint32_t d) { + return (a & 0xffu) | ((b & 0xffu) << 8u) | ((c & 0xffu) << 16u) | ((d & 0xffu) << 24u); +} + +void EnsureConfigInitialized() { + static bool initialized = false; + if (initialized) return; + static Common::Subsystems subsystems; + Common::InitializeThreads(); + subsystems.Initialize<Config::Lifecycle>(); + Config::ConfigOptions options; + options.printf_direction = Config::LogDirection::Silent; + Config::Load(options); + subsystems.Initialize<Log::Lifecycle>(); + ShaderInit(); + initialized = true; +} + +// ---- shaders ------------------------------------------------------------------------------------- + +struct Shaders { + std::vector<uint32_t> vs; + std::vector<uint32_t> ps; + uint32_t stride_vec4 = 0; +}; + +// VS: position = attr0, param0 = attr1 with `+ instance` added to the bits of x (a 1 ulp difference +// per instance shows a record of the wrong instance), param1 = {gl_VertexIndex, gl_InstanceIndex, 0, 0}. +// PS: out = {corner0.x, corner1.y, corner2.z, corner0.w} of param0. +Shaders BuildShaders() { + using IR::Value; + using O = IR::ValueOpcode; + Shaders out; + + IR::Program vs; + vs.stage = ShaderType::Vertex; + vs.wave_size = 64; + vs.srt_plan_complete = vs.resource_tracking_complete = vs.shader_info_complete = true; + vs.block_storage.push_back(std::make_unique<IR::Block>()); + vs.blocks.push_back(vs.block_storage.back().get()); + vs.info.inputs = {{IR::StageInputKind::VertexIndex}, + {IR::StageInputKind::InstanceIndex}, + {IR::StageInputKind::Parameter, 0, 4}, + {IR::StageInputKind::Parameter, 1, 4}}; + vs.info.outputs = {{IR::StageOutputKind::Position}, + {IR::StageOutputKind::Parameter, 0, 0}, + {IR::StageOutputKind::Parameter, 1, 1}}; + vs.export_info = {{.kind = IR::ExportTargetKind::Position, .en = 15}, + {.kind = IR::ExportTargetKind::Parameter, .index = 0, .en = 15}, + {.kind = IR::ExportTargetKind::Parameter, .index = 1, .en = 15}}; + IR::IREmitter emit(vs.blocks.front()); + const auto vertex = emit.Emit(O::GetBuiltin, {Value(static_cast<uint32_t>(IR::StageInputKind::VertexIndex)), Value(0u)}); + const auto instance = emit.Emit(O::GetBuiltin, {Value(static_cast<uint32_t>(IR::StageInputKind::InstanceIndex)), Value(0u)}); + std::array<Value, 4> position, color; + for (uint32_t c = 0; c < 4; c++) position[c] = emit.Emit(O::GetAttribute, {Value(0u), Value(c)}); + for (uint32_t c = 0; c < 4; c++) color[c] = emit.Emit(O::GetAttribute, {Value(1u), Value(c)}); + const auto pos = emit.Emit(O::CompositeConstructU32x4, {position[0], position[1], position[2], position[3]}); + emit.Emit(O::SetAttribute, {pos, Value(true)}, IR::ExportFlags {0}); + const auto x = emit.Emit(O::IAdd32, {color[0], instance}); + const auto param0 = emit.Emit(O::CompositeConstructU32x4, {x, color[1], color[2], color[3]}); + emit.Emit(O::SetAttribute, {param0, Value(true)}, IR::ExportFlags {1}); + const auto param1 = emit.Emit(O::CompositeConstructU32x4, {vertex, instance, Value(0u), Value(0u)}); + emit.Emit(O::SetAttribute, {param1, Value(true)}, IR::ExportFlags {2}); + static const ShaderVertexInputInfo vertex_info {}; + ShaderStageInputInfo vs_input {.vertex = &vertex_info}; + + uint32_t vs_mask = 0; + Spirv::PvStoreInfo vs_store; + vs_store.role = Spirv::PvStoreInfo::Role::Vertex; + vs_store.coherent = true; + vs_store.location_mask = &vs_mask; + out.vs = Spirv::EmitProgram(vs, vs_input, 0, &vs_store); + + // PS (the interpolation setup of TestPvVsStoreEmission): v_interp_mov_f32 with P0 / P10 / P20. + const uint32_t ps_code[] = {EncodeVintrp(2, 12, 0, 0, 2), EncodeVintrp(2, 13, 0, 1, 0), + EncodeVintrp(2, 14, 0, 2, 1), EncodeVintrp(2, 15, 0, 3, 2), + EncodeExp0(0x00, 0xf), EncodeExp1(12, 13, 14, 15), + EncodeSopp(0x01)}; + static ShaderPixelInputInfo ps_info {}; + ps_info.input_num = 1; + ps_info.ps_system_input_base = 2; + ps_info.custom_interpolation_mask = 1; + ps_info.ps_perspective_center_vgpr = 0; + for (uint32_t i = 0; i < std::size(ps_info.interpolator_settings); i++) ps_info.interpolator_settings[i] = i; + ps_info.interpolator_settings[0] = 0x00000420u; + static const std::array<uint32_t, 64> user_data = [] { + std::array<uint32_t, 64> data {}; + data[3] = 3u << 28u; + return data; + }(); + CompileOptions options; + options.stage = ShaderType::Pixel; + options.user_data = user_data; + options.input_info.pixel = &ps_info; + auto translated = TranslateProgram(ps_code, options); + auto plan = IR::ExtractResourcePlan(translated.program); + IR::ResourceSnapshot resources; + IR::ResourceSpecialization specialization; + const IR::SrtRuntime runtime {.user_data = options.user_data, + .shader_base = reinterpret_cast<uint64_t>(ps_code), + .read_specialization_memory = [](void*, uint64_t, std::span<uint32_t>) { return false; }}; + Check(IR::MaterializeResources(plan, runtime, resources, specialization), "PS resources did not materialize"); + auto compiled = CompileProgram(std::move(translated), options, specialization, 0); + uint32_t ps_mask = 0; + Spirv::PvStoreInfo ps_store; + ps_store.role = Spirv::PvStoreInfo::Role::Pixel; + ps_store.coherent = true; + ps_store.location_mask = &ps_mask; + out.ps = Spirv::EmitProgram(compiled.program, options.input_info, 0, &ps_store); + + Check(ClassifyPvVsStoreInterface(vs_mask, ps_mask) == PvVsStoreInterfaceVerdict::Use, "VS/PS pair is not a VS-store candidate"); + out.stride_vec4 = PvVsStoreStrideFor(vs_mask); + if (out.stride_vec4 != 2) std::fprintf(stderr, "VS location mask %08x, PS location mask %08x\n", vs_mask, ps_mask); + Check(out.stride_vec4 == 2, "expected stride 2 (locations 0 and 1)"); + spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_2); + Check(tools.Validate(out.vs), "VS-store VS does not validate"); + Check(tools.Validate(out.ps), "VS-store PS does not validate"); + return out; +} + +// ---- scene (CPU model) --------------------------------------------------------------------------- + +constexpr uint32_t kDim = 32; // render target +constexpr uint32_t kCell = 16; // one triangle per cell: 2x2 cells +constexpr uint32_t kVertices = 24; // 4 triangles x 3 corners, plus 12 spare vertices for offsets +constexpr uint32_t kStrideB = 32; // float4 position, float4 color + +struct Vertex { + float position[4]; + float color[4]; +}; + +std::array<Vertex, kVertices> MakeVertices() { + std::array<Vertex, kVertices> v {}; + for (uint32_t i = 0; i < kVertices; ++i) { + const uint32_t tri = (i / 3u) % 4u; + const uint32_t cx = tri % 2u, cy = tri / 2u; + const float x0 = static_cast<float>(cx * kCell), y0 = static_cast<float>(cy * kCell); + const float px[3] = {x0 + 2.f, x0 + 14.f, x0 + 2.f}; + const float py[3] = {y0 + 2.f, y0 + 2.f, y0 + 14.f}; + const uint32_t k = i % 3u; + v[i].position[0] = px[k] / (kDim / 2.f) - 1.f; + v[i].position[1] = py[k] / (kDim / 2.f) - 1.f; + v[i].position[2] = 0.5f; + v[i].position[3] = 1.f; + // distinct, normal floats: any mix-up of a vertex, a corner or a component shows + v[i].color[0] = 1.0f + 0.03125f * static_cast<float>(i); + v[i].color[1] = 2.0f + 0.0625f * static_cast<float>(i); + v[i].color[2] = 3.0f + 0.125f * static_cast<float>(i); + v[i].color[3] = 4.0f + 0.25f * static_cast<float>(i); + } + return v; +} + +struct Case { + const char* name; + bool index32; + std::vector<uint32_t> indices; // per triangle corner, relative to vertex_offset + int32_t vertex_offset; + uint32_t first_instance; + uint32_t instance_count; + uint32_t bind_byte_offset; // where the index data starts inside the index buffer +}; + +uint32_t Bits(float f) { + uint32_t u; + std::memcpy(&u, &f, 4); + return u; +} + +// Expected pixel of triangle t of the draw: {corner0.x(+inst), corner1.y, corner2.z, corner0.w}. +std::array<uint32_t, 4> ExpectedPixel(const std::array<Vertex, kVertices>& v, const Case& c, uint32_t tri) { + const uint32_t last_instance = c.first_instance + c.instance_count - 1; + const auto vertex = [&](uint32_t corner) { return static_cast<uint32_t>(static_cast<int32_t>(c.indices[tri * 3 + corner]) + c.vertex_offset); }; + std::array<uint32_t, 4> out {}; + out[0] = Bits(v[vertex(0)].color[0]) + last_instance; + out[1] = Bits(v[vertex(1)].color[1]); + out[2] = Bits(v[vertex(2)].color[2]); + out[3] = Bits(v[vertex(0)].color[3]); + return out; +} + +// ---- Vulkan -------------------------------------------------------------------------------------- + +#define VK_FUNCS(X) \ + X(vkCreateDevice) X(vkGetDeviceProcAddr) X(vkEnumeratePhysicalDevices) X(vkGetPhysicalDeviceMemoryProperties) \ + X(vkGetPhysicalDeviceQueueFamilyProperties) X(vkGetPhysicalDeviceFeatures) X(vkGetPhysicalDeviceProperties) + +#define VK_DEVICE_FUNCS(X) \ + X(vkGetDeviceQueue) X(vkCreateBuffer) X(vkGetBufferMemoryRequirements) X(vkAllocateMemory) X(vkBindBufferMemory) \ + X(vkMapMemory) X(vkCreateDescriptorSetLayout) X(vkCreatePipelineLayout) X(vkCreateShaderModule) \ + X(vkCreateGraphicsPipelines) X(vkCreateDescriptorPool) X(vkAllocateDescriptorSets) X(vkUpdateDescriptorSets) \ + X(vkCreateCommandPool) X(vkAllocateCommandBuffers) X(vkBeginCommandBuffer) X(vkEndCommandBuffer) \ + X(vkCmdBindPipeline) X(vkCmdBindDescriptorSets) X(vkCmdPushConstants) X(vkCmdBeginRenderPass) X(vkCmdEndRenderPass) \ + X(vkCmdBindVertexBuffers) X(vkCmdBindIndexBuffer) X(vkCmdDrawIndexed) X(vkCmdCopyImageToBuffer) X(vkQueueSubmit) \ + X(vkQueueWaitIdle) X(vkCreateRenderPass) X(vkCreateFramebuffer) X(vkCreateImage) X(vkGetImageMemoryRequirements) \ + X(vkBindImageMemory) X(vkCreateImageView) X(vkCmdPipelineBarrier) + +#define DECLARE(name) PFN_##name name##_ = nullptr; +VK_FUNCS(DECLARE) +VK_DEVICE_FUNCS(DECLARE) +#undef DECLARE + +struct Gpu { + VkInstance instance = VK_NULL_HANDLE; + VkPhysicalDevice physical = VK_NULL_HANDLE; + VkDevice device = VK_NULL_HANDLE; + VkQueue queue = VK_NULL_HANDLE; + uint32_t family = 0; + VkPhysicalDeviceMemoryProperties memory {}; + VkDeviceSize storage_alignment = 16; +}; + +struct Buf { + VkBuffer buffer = VK_NULL_HANDLE; + VkDeviceMemory memory = VK_NULL_HANDLE; + void* mapped = nullptr; + size_t size = 0; +}; + +uint32_t MemoryType(const Gpu& gpu, uint32_t bits, VkMemoryPropertyFlags flags) { + for (uint32_t i = 0; i < gpu.memory.memoryTypeCount; ++i) { + if ((bits & (1u << i)) && (gpu.memory.memoryTypes[i].propertyFlags & flags) == flags) return i; + } + Fail("no suitable memory type"); +} + +Buf MakeBuffer(const Gpu& gpu, size_t size, VkBufferUsageFlags usage) { + Buf b; + b.size = size; + VkBufferCreateInfo info {VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; + info.size = size; + info.usage = usage; + CheckVk(vkCreateBuffer_(gpu.device, &info, nullptr, &b.buffer), "vkCreateBuffer"); + VkMemoryRequirements req; + vkGetBufferMemoryRequirements_(gpu.device, b.buffer, &req); + VkMemoryAllocateInfo alloc {VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; + alloc.allocationSize = req.size; + alloc.memoryTypeIndex = MemoryType(gpu, req.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); + CheckVk(vkAllocateMemory_(gpu.device, &alloc, nullptr, &b.memory), "vkAllocateMemory"); + CheckVk(vkBindBufferMemory_(gpu.device, b.buffer, b.memory, 0), "vkBindBufferMemory"); + CheckVk(vkMapMemory_(gpu.device, b.memory, 0, size, 0, &b.mapped), "vkMapMemory"); + std::memset(b.mapped, 0xA5, size); + return b; +} + +Gpu InitGpu() { + const char* driver = std::getenv("SDL_VULKAN_LIBRARY"); + void* lib = dlopen(driver != nullptr ? driver : "libMoltenVK.dylib", RTLD_NOW | RTLD_LOCAL); + if (lib == nullptr) Fail("cannot load MoltenVK; set SDL_VULKAN_LIBRARY"); + auto get_instance_proc = reinterpret_cast<PFN_vkGetInstanceProcAddr>(dlsym(lib, "vkGetInstanceProcAddr")); + if (get_instance_proc == nullptr) Fail("dlsym vkGetInstanceProcAddr"); + auto create_instance = reinterpret_cast<PFN_vkCreateInstance>(get_instance_proc(VK_NULL_HANDLE, "vkCreateInstance")); + auto enumerate_extensions = reinterpret_cast<PFN_vkEnumerateInstanceExtensionProperties>( + get_instance_proc(VK_NULL_HANDLE, "vkEnumerateInstanceExtensionProperties")); + if (enumerate_extensions == nullptr) Fail("vkEnumerateInstanceExtensionProperties"); + uint32_t extension_count = 0; + CheckVk(enumerate_extensions(nullptr, &extension_count, nullptr), "vkEnumerateInstanceExtensionProperties"); + std::vector<VkExtensionProperties> available(extension_count); + CheckVk(enumerate_extensions(nullptr, &extension_count, available.data()), "vkEnumerateInstanceExtensionProperties list"); + bool has_portability = false; + for (const auto& e: available) { + if (std::strcmp(e.extensionName, VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME) == 0) has_portability = true; + } + const char* extensions[] {VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME}; + VkApplicationInfo app {VK_STRUCTURE_TYPE_APPLICATION_INFO}; + app.apiVersion = VK_API_VERSION_1_3; + VkInstanceCreateInfo info {VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO}; + info.pApplicationInfo = &app; + info.flags = has_portability ? VK_INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR : 0; + info.enabledExtensionCount = has_portability ? 1u : 0u; + info.ppEnabledExtensionNames = has_portability ? extensions : nullptr; + Gpu gpu; + CheckVk(create_instance(&info, nullptr, &gpu.instance), "vkCreateInstance"); +#define LOAD_INSTANCE(name) name##_ = reinterpret_cast<PFN_##name>(get_instance_proc(gpu.instance, #name)); + VK_FUNCS(LOAD_INSTANCE) +#undef LOAD_INSTANCE + uint32_t count = 0; + CheckVk(vkEnumeratePhysicalDevices_(gpu.instance, &count, nullptr), "vkEnumeratePhysicalDevices"); + Check(count > 0, "no physical device"); + std::vector<VkPhysicalDevice> devices(count); + CheckVk(vkEnumeratePhysicalDevices_(gpu.instance, &count, devices.data()), "vkEnumeratePhysicalDevices list"); + gpu.physical = devices[0]; + vkGetPhysicalDeviceMemoryProperties_(gpu.physical, &gpu.memory); + VkPhysicalDeviceProperties props {}; + vkGetPhysicalDeviceProperties_(gpu.physical, &props); + gpu.storage_alignment = props.limits.minStorageBufferOffsetAlignment; + uint32_t qcount = 0; + vkGetPhysicalDeviceQueueFamilyProperties_(gpu.physical, &qcount, nullptr); + std::vector<VkQueueFamilyProperties> queues(qcount); + vkGetPhysicalDeviceQueueFamilyProperties_(gpu.physical, &qcount, queues.data()); + for (uint32_t i = 0; i < qcount; ++i) { + if (queues[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) { + gpu.family = i; + break; + } + } + VkPhysicalDeviceFeatures supported {}; + vkGetPhysicalDeviceFeatures_(gpu.physical, &supported); + Check(supported.vertexPipelineStoresAndAtomics, "device lacks vertexPipelineStoresAndAtomics (the VS cannot store)"); + VkPhysicalDeviceFeatures features {}; + features.vertexPipelineStoresAndAtomics = VK_TRUE; + features.fragmentStoresAndAtomics = supported.fragmentStoresAndAtomics; + features.shaderClipDistance = supported.shaderClipDistance; // the emitted VS has a clip guard + features.geometryShader = supported.geometryShader; // PrimitiveId in the PS needs the Geometry capability ``` Follow-up: with 8977bb43 the harness enables `tessellationShader` and has been run on MoltenVK (Apple M3 Max): all 7 cases pass, `--stress` passes, and both harness mutants fail as expected.
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-12 15:21 UTC · original
On tests/PerVertexVsStoreGpuTests.cpp line 382 (outdated):

@@ -0,0 +1,751 @@
+// GPU harness for KYTY_PV_VSSTORE (graphics/host_gpu/renderer/perVertexVsStore.h). The real SPIR-V
+// emitter produces the VS-store VS and PS from an IR vertex shader and an ISA pixel shader, and the
+// pair is drawn on the host GPU (MoltenVK) with the exact descriptor/push layout of the renderer:
+//   set 0 = empty, set 1 = {cap SSBO (VS|FS), guest index SSBO (FS)}, push = native data + 8 dwords.
+// Checks (bit for bit, no tolerance):
+//   1. image: every probed pixel equals the PerVertexKHR semantics computed on the CPU from the vertex
+//      data, the index buffer and the draw parameters (corner 0/1/2 read through P0/P10/P20),
+//   2. cap: the records the VS wrote hold {gl_VertexIndex, gl_InstanceIndex} of the cases, which
+//      settles whether gl_VertexIndex includes vertex_offset and gl_InstanceIndex first_instance.
+// Cases: 16-bit and 32-bit indices, vertex_offset > 0 and < 0, first_instance != 0, 2 instances, an index
+// buffer bound at an offset that is not a multiple of minStorageBufferOffsetAlignment.
+// Run: per_vertex_vsstore_gpu_tests [--dump] [--stress]  (--stress: 2M triangles x 2..4 instances, parameter-buffer overflow)
+//   --dump needs no GPU: it prints the emitted SPIR-V.
+// The result is compared with the CPU model of the per-vertex semantics. The mutants built from
+// tests/PerVertexVsStoreMutants.cmake (corner 0/2 swapped, index range not rounded) must fail it.
+
+#include "common/emulatorConfig.h"
+#include "common/logging/log.h"
+#include "common/subsystems.h"
+#include "common/threads.h"
+#include "graphics/host_gpu/renderer/perVertexVsStore.h"
+#include "graphics/shader/recompiler/ShaderRecompiler.h"
+#include "graphics/shader/recompiler/backend/spirv/SpirvEmitter.h"
+#include "graphics/shader/recompiler/ir/IREmitter.h"
+#include "graphics/shader/recompiler/ir/ShaderIR.h"
+#include "graphics/shader/recompiler/ir/passes/ResourceTracking.h"
+#include "graphics/shader/shader.h"
+#include "graphics/shader/shaderCompiler.h"
+
+#include <spirv-tools/libspirv.hpp>
+#include <vulkan/vulkan.h>
+
+#include <dlfcn.h>
+
+#include <algorithm>
+#include <array>
+#include <cstdint>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <span>
+#include <string>
+#include <vector>
+
+namespace Libs::Graphics {
+namespace {
+
+using namespace ShaderRecompiler;
+
+bool g_stress = false; // --stress: the >= 2M triangle cases
+
+[[noreturn]] void Fail(const char* message) {
+	std::fprintf(stderr, "per-vertex-vsstore-gpu-tests: FAILED: %s\n", message);
+	std::exit(1);
+}
+
+void Check(bool ok, const char* message) {
+	if (!ok) Fail(message);
+}
+
+void CheckVk(VkResult result, const char* what) {
+	if (result != VK_SUCCESS) {
+		std::fprintf(stderr, "per-vertex-vsstore-gpu-tests: FAILED: %s (VkResult %d)\n", what, static_cast<int>(result));
+		std::exit(1);
+	}
+}
+
+constexpr uint32_t EncodeSopp(uint32_t opcode, uint32_t simm = 0) {
+	return (0x17fu << 23u) | ((opcode & 0x7fu) << 16u) | (simm & 0xffffu);
+}
+constexpr uint32_t EncodeVintrp(uint32_t opcode, uint32_t vdst, uint32_t attr, uint32_t chan, uint32_t vsrc) {
+	return (0x32u << 26u) | ((opcode & 0x3u) << 16u) | ((vdst & 0xffu) << 18u) | ((attr & 0x3fu) << 10u) |
+	       ((chan & 0x3u) << 8u) | (vsrc & 0xffu);
+}
+constexpr uint32_t EncodeExp0(uint32_t target, uint32_t en) {
+	return (0x3eu << 26u) | ((target & 0x3fu) << 4u) | (en & 0xfu) | (1u << 11u);
+}
+constexpr uint32_t EncodeExp1(uint32_t a, uint32_t b, uint32_t c, uint32_t d) {
+	return (a & 0xffu) | ((b & 0xffu) << 8u) | ((c & 0xffu) << 16u) | ((d & 0xffu) << 24u);
+}
+
+void EnsureConfigInitialized() {
+	static bool initialized = false;
+	if (initialized) return;
+	static Common::Subsystems subsystems;
+	Common::InitializeThreads();
+	subsystems.Initialize<Config::Lifecycle>();
+	Config::ConfigOptions options;
+	options.printf_direction = Config::LogDirection::Silent;
+	Config::Load(options);
+	subsystems.Initialize<Log::Lifecycle>();
+	ShaderInit();
+	initialized = true;
+}
+
+// ---- shaders -------------------------------------------------------------------------------------
+
+struct Shaders {
+	std::vector<uint32_t> vs;
+	std::vector<uint32_t> ps;
+	uint32_t              stride_vec4 = 0;
+};
+
+// VS: position = attr0, param0 = attr1 with `+ instance` added to the bits of x (a 1 ulp difference
+// per instance shows a record of the wrong instance), param1 = {gl_VertexIndex, gl_InstanceIndex, 0, 0}.
+// PS: out = {corner0.x, corner1.y, corner2.z, corner0.w} of param0.
+Shaders BuildShaders() {
+	using IR::Value;
+	using O = IR::ValueOpcode;
+	Shaders out;
+
+	IR::Program vs;
+	vs.stage                  = ShaderType::Vertex;
+	vs.wave_size              = 64;
+	vs.srt_plan_complete      = vs.resource_tracking_complete = vs.shader_info_complete = true;
+	vs.block_storage.push_back(std::make_unique<IR::Block>());
+	vs.blocks.push_back(vs.block_storage.back().get());
+	vs.info.inputs  = {{IR::StageInputKind::VertexIndex},
+	                   {IR::StageInputKind::InstanceIndex},
+	                   {IR::StageInputKind::Parameter, 0, 4},
+	                   {IR::StageInputKind::Parameter, 1, 4}};
+	vs.info.outputs = {{IR::StageOutputKind::Position},
+	                   {IR::StageOutputKind::Parameter, 0, 0},
+	                   {IR::StageOutputKind::Parameter, 1, 1}};
+	vs.export_info  = {{.kind = IR::ExportTargetKind::Position, .en = 15},
+	                   {.kind = IR::ExportTargetKind::Parameter, .index = 0, .en = 15},
+	                   {.kind = IR::ExportTargetKind::Parameter, .index = 1, .en = 15}};
+	IR::IREmitter emit(vs.blocks.front());
+	const auto vertex   = emit.Emit(O::GetBuiltin, {Value(static_cast<uint32_t>(IR::StageInputKind::VertexIndex)), Value(0u)});
+	const auto instance = emit.Emit(O::GetBuiltin, {Value(static_cast<uint32_t>(IR::StageInputKind::InstanceIndex)), Value(0u)});
+	std::array<Value, 4> position, color;
+	for (uint32_t c = 0; c < 4; c++) position[c] = emit.Emit(O::GetAttribute, {Value(0u), Value(c)});
+	for (uint32_t c = 0; c < 4; c++) color[c] = emit.Emit(O::GetAttribute, {Value(1u), Value(c)});
+	const auto pos = emit.Emit(O::CompositeConstructU32x4, {position[0], position[1], position[2], position[3]});
+	emit.Emit(O::SetAttribute, {pos, Value(true)}, IR::ExportFlags {0});
+	const auto x      = emit.Emit(O::IAdd32, {color[0], instance});
+	const auto param0 = emit.Emit(O::CompositeConstructU32x4, {x, color[1], color[2], color[3]});
+	emit.Emit(O::SetAttribute, {param0, Value(true)}, IR::ExportFlags {1});
+	const auto param1 = emit.Emit(O::CompositeConstructU32x4, {vertex, instance, Value(0u), Value(0u)});
+	emit.Emit(O::SetAttribute, {param1, Value(true)}, IR::ExportFlags {2});
+	static const ShaderVertexInputInfo vertex_info {};
+	ShaderStageInputInfo               vs_input {.vertex = &vertex_info};
+
+	uint32_t vs_mask = 0;
+	Spirv::PvStoreInfo vs_store;
+	vs_store.role          = Spirv::PvStoreInfo::Role::Vertex;
+	vs_store.coherent      = true;
+	vs_store.location_mask = &vs_mask;
+	out.vs                 = Spirv::EmitProgram(vs, vs_input, 0, &vs_store);
+
+	// PS (the interpolation setup of TestPvVsStoreEmission): v_interp_mov_f32 with P0 / P10 / P20.
+	const uint32_t ps_code[] = {EncodeVintrp(2, 12, 0, 0, 2), EncodeVintrp(2, 13, 0, 1, 0),
+	                            EncodeVintrp(2, 14, 0, 2, 1), EncodeVintrp(2, 15, 0, 3, 2),
+	                            EncodeExp0(0x00, 0xf),        EncodeExp1(12, 13, 14, 15),
+	                            EncodeSopp(0x01)};
+	static ShaderPixelInputInfo ps_info {};
+	ps_info.input_num                 = 1;
+	ps_info.ps_system_input_base      = 2;
+	ps_info.custom_interpolation_mask = 1;
+	ps_info.ps_perspective_center_vgpr = 0;
+	for (uint32_t i = 0; i < std::size(ps_info.interpolator_settings); i++) ps_info.interpolator_settings[i] = i;
+	ps_info.interpolator_settings[0] = 0x00000420u;
+	static const std::array<uint32_t, 64> user_data = [] {
+		std::array<uint32_t, 64> data {};
+		data[3] = 3u << 28u;
+		return data;
+	}();
+	CompileOptions options;
+	options.stage            = ShaderType::Pixel;
+	options.user_data        = user_data;
+	options.input_info.pixel = &ps_info;
+	auto translated          = TranslateProgram(ps_code, options);
+	auto plan                = IR::ExtractResourcePlan(translated.program);
+	IR::ResourceSnapshot       resources;
+	IR::ResourceSpecialization specialization;
+	const IR::SrtRuntime       runtime {.user_data = options.user_data,
+	                                    .shader_base = reinterpret_cast<uint64_t>(ps_code),
+	                                    .read_specialization_memory = [](void*, uint64_t, std::span<uint32_t>) { return false; }};
+	Check(IR::MaterializeResources(plan, runtime, resources, specialization), "PS resources did not materialize");
+	auto compiled = CompileProgram(std::move(translated), options, specialization, 0);
+	uint32_t ps_mask = 0;
+	Spirv::PvStoreInfo ps_store;
+	ps_store.role          = Spirv::PvStoreInfo::Role::Pixel;
+	ps_store.coherent      = true;
+	ps_store.location_mask = &ps_mask;
+	out.ps                 = Spirv::EmitProgram(compiled.program, options.input_info, 0, &ps_store);
+
+	Check(ClassifyPvVsStoreInterface(vs_mask, ps_mask) == PvVsStoreInterfaceVerdict::Use, "VS/PS pair is not a VS-store candidate");
+	out.stride_vec4 = PvVsStoreStrideFor(vs_mask);
+	if (out.stride_vec4 != 2) std::fprintf(stderr, "VS location mask %08x, PS location mask %08x\n", vs_mask, ps_mask);
+	Check(out.stride_vec4 == 2, "expected stride 2 (locations 0 and 1)");
+	spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_2);
+	Check(tools.Validate(out.vs), "VS-store VS does not validate");
+	Check(tools.Validate(out.ps), "VS-store PS does not validate");
+	return out;
+}
+
+// ---- scene (CPU model) ---------------------------------------------------------------------------
+
+constexpr uint32_t kDim      = 32; // render target
+constexpr uint32_t kCell     = 16; // one triangle per cell: 2x2 cells
+constexpr uint32_t kVertices = 24; // 4 triangles x 3 corners, plus 12 spare vertices for offsets
+constexpr uint32_t kStrideB  = 32; // float4 position, float4 color
+
+struct Vertex {
+	float position[4];
+	float color[4];
+};
+
+std::array<Vertex, kVertices> MakeVertices() {
+	std::array<Vertex, kVertices> v {};
+	for (uint32_t i = 0; i < kVertices; ++i) {
+		const uint32_t tri = (i / 3u) % 4u;
+		const uint32_t cx  = tri % 2u, cy = tri / 2u;
+		const float    x0  = static_cast<float>(cx * kCell), y0 = static_cast<float>(cy * kCell);
+		const float    px[3] = {x0 + 2.f, x0 + 14.f, x0 + 2.f};
+		const float    py[3] = {y0 + 2.f, y0 + 2.f, y0 + 14.f};
+		const uint32_t k     = i % 3u;
+		v[i].position[0] = px[k] / (kDim / 2.f) - 1.f;
+		v[i].position[1] = py[k] / (kDim / 2.f) - 1.f;
+		v[i].position[2] = 0.5f;
+		v[i].position[3] = 1.f;
+		// distinct, normal floats: any mix-up of a vertex, a corner or a component shows
+		v[i].color[0] = 1.0f + 0.03125f * static_cast<float>(i);
+		v[i].color[1] = 2.0f + 0.0625f * static_cast<float>(i);
+		v[i].color[2] = 3.0f + 0.125f * static_cast<float>(i);
+		v[i].color[3] = 4.0f + 0.25f * static_cast<float>(i);
+	}
+	return v;
+}
+
+struct Case {
+	const char*           name;
+	bool                  index32;
+	std::vector<uint32_t> indices;       // per triangle corner, relative to vertex_offset
+	int32_t               vertex_offset;
+	uint32_t              first_instance;
+	uint32_t              instance_count;
+	uint32_t              bind_byte_offset; // where the index data starts inside the index buffer
+};
+
+uint32_t Bits(float f) {
+	uint32_t u;
+	std::memcpy(&u, &f, 4);
+	return u;
+}
+
+// Expected pixel of triangle t of the draw: {corner0.x(+inst), corner1.y, corner2.z, corner0.w}.
+std::array<uint32_t, 4> ExpectedPixel(const std::array<Vertex, kVertices>& v, const Case& c, uint32_t tri) {
+	const uint32_t last_instance = c.first_instance + c.instance_count - 1;
+	const auto     vertex = [&](uint32_t corner) { return static_cast<uint32_t>(static_cast<int32_t>(c.indices[tri * 3 + corner]) + c.vertex_offset); };
+	std::array<uint32_t, 4> out {};
+	out[0] = Bits(v[vertex(0)].color[0]) + last_instance;
+	out[1] = Bits(v[vertex(1)].color[1]);
+	out[2] = Bits(v[vertex(2)].color[2]);
+	out[3] = Bits(v[vertex(0)].color[3]);
+	return out;
+}
+
+// ---- Vulkan --------------------------------------------------------------------------------------
+
+#define VK_FUNCS(X)                                                                                                        \
+	X(vkCreateDevice) X(vkGetDeviceProcAddr) X(vkEnumeratePhysicalDevices) X(vkGetPhysicalDeviceMemoryProperties)          \
+	X(vkGetPhysicalDeviceQueueFamilyProperties) X(vkGetPhysicalDeviceFeatures) X(vkGetPhysicalDeviceProperties)
+
+#define VK_DEVICE_FUNCS(X)                                                                                                 \
+	X(vkGetDeviceQueue) X(vkCreateBuffer) X(vkGetBufferMemoryRequirements) X(vkAllocateMemory) X(vkBindBufferMemory)      \
+	X(vkMapMemory) X(vkCreateDescriptorSetLayout) X(vkCreatePipelineLayout) X(vkCreateShaderModule)                         \
+	X(vkCreateGraphicsPipelines) X(vkCreateDescriptorPool) X(vkAllocateDescriptorSets) X(vkUpdateDescriptorSets)           \
+	X(vkCreateCommandPool) X(vkAllocateCommandBuffers) X(vkBeginCommandBuffer) X(vkEndCommandBuffer)                       \
+	X(vkCmdBindPipeline) X(vkCmdBindDescriptorSets) X(vkCmdPushConstants) X(vkCmdBeginRenderPass) X(vkCmdEndRenderPass)    \
+	X(vkCmdBindVertexBuffers) X(vkCmdBindIndexBuffer) X(vkCmdDrawIndexed) X(vkCmdCopyImageToBuffer) X(vkQueueSubmit)      \
+	X(vkQueueWaitIdle) X(vkCreateRenderPass) X(vkCreateFramebuffer) X(vkCreateImage) X(vkGetImageMemoryRequirements)       \
+	X(vkBindImageMemory) X(vkCreateImageView) X(vkCmdPipelineBarrier)
+
+#define DECLARE(name) PFN_##name name##_ = nullptr;
+VK_FUNCS(DECLARE)
+VK_DEVICE_FUNCS(DECLARE)
+#undef DECLARE
+
+struct Gpu {
+	VkInstance                       instance = VK_NULL_HANDLE;
+	VkPhysicalDevice                 physical = VK_NULL_HANDLE;
+	VkDevice                         device   = VK_NULL_HANDLE;
+	VkQueue                          queue    = VK_NULL_HANDLE;
+	uint32_t                         family   = 0;
+	VkPhysicalDeviceMemoryProperties memory {};
+	VkDeviceSize                     storage_alignment = 16;
+};
+
+struct Buf {
+	VkBuffer       buffer = VK_NULL_HANDLE;
+	VkDeviceMemory memory = VK_NULL_HANDLE;
+	void*          mapped = nullptr;
+	size_t         size   = 0;
+};
+
+uint32_t MemoryType(const Gpu& gpu, uint32_t bits, VkMemoryPropertyFlags flags) {
+	for (uint32_t i = 0; i < gpu.memory.memoryTypeCount; ++i) {
+		if ((bits & (1u << i)) && (gpu.memory.memoryTypes[i].propertyFlags & flags) == flags) return i;
+	}
+	Fail("no suitable memory type");
+}
+
+Buf MakeBuffer(const Gpu& gpu, size_t size, VkBufferUsageFlags usage) {
+	Buf b;
+	b.size = size;
+	VkBufferCreateInfo info {VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
+	info.size  = size;
+	info.usage = usage;
+	CheckVk(vkCreateBuffer_(gpu.device, &info, nullptr, &b.buffer), "vkCreateBuffer");
+	VkMemoryRequirements req;
+	vkGetBufferMemoryRequirements_(gpu.device, b.buffer, &req);
+	VkMemoryAllocateInfo alloc {VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
+	alloc.allocationSize  = req.size;
+	alloc.memoryTypeIndex = MemoryType(gpu, req.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
+	CheckVk(vkAllocateMemory_(gpu.device, &alloc, nullptr, &b.memory), "vkAllocateMemory");
+	CheckVk(vkBindBufferMemory_(gpu.device, b.buffer, b.memory, 0), "vkBindBufferMemory");
+	CheckVk(vkMapMemory_(gpu.device, b.memory, 0, size, 0, &b.mapped), "vkMapMemory");
+	std::memset(b.mapped, 0xA5, size);
+	return b;
+}
+
+Gpu InitGpu() {
+	const char* driver = std::getenv("SDL_VULKAN_LIBRARY");
+	void*       lib    = dlopen(driver != nullptr ? driver : "libMoltenVK.dylib", RTLD_NOW | RTLD_LOCAL);
+	if (lib == nullptr) Fail("cannot load MoltenVK; set SDL_VULKAN_LIBRARY");
+	auto get_instance_proc = reinterpret_cast<PFN_vkGetInstanceProcAddr>(dlsym(lib, "vkGetInstanceProcAddr"));
+	if (get_instance_proc == nullptr) Fail("dlsym vkGetInstanceProcAddr");
+	auto create_instance = reinterpret_cast<PFN_vkCreateInstance>(get_instance_proc(VK_NULL_HANDLE, "vkCreateInstance"));
+	auto enumerate_extensions = reinterpret_cast<PFN_vkEnumerateInstanceExtensionProperties>(
+	    get_instance_proc(VK_NULL_HANDLE, "vkEnumerateInstanceExtensionProperties"));
+	if (enumerate_extensions == nullptr) Fail("vkEnumerateInstanceExtensionProperties");
+	uint32_t extension_count = 0;
+	CheckVk(enumerate_extensions(nullptr, &extension_count, nullptr), "vkEnumerateInstanceExtensionProperties");
+	std::vector<VkExtensionProperties> available(extension_count);
+	CheckVk(enumerate_extensions(nullptr, &extension_count, available.data()), "vkEnumerateInstanceExtensionProperties list");
+	bool has_portability = false;
+	for (const auto& e: available) {
+		if (std::strcmp(e.extensionName, VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME) == 0) has_portability = true;
+	}
+	const char* extensions[] {VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME};
+	VkApplicationInfo app {VK_STRUCTURE_TYPE_APPLICATION_INFO};
+	app.apiVersion = VK_API_VERSION_1_3;
+	VkInstanceCreateInfo info {VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO};
+	info.pApplicationInfo        = &app;
+	info.flags                   = has_portability ? VK_INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR : 0;
+	info.enabledExtensionCount   = has_portability ? 1u : 0u;
+	info.ppEnabledExtensionNames = has_portability ? extensions : nullptr;
+	Gpu gpu;
+	CheckVk(create_instance(&info, nullptr, &gpu.instance), "vkCreateInstance");
+#define LOAD_INSTANCE(name) name##_ = reinterpret_cast<PFN_##name>(get_instance_proc(gpu.instance, #name));
+	VK_FUNCS(LOAD_INSTANCE)
+#undef LOAD_INSTANCE
+	uint32_t count = 0;
+	CheckVk(vkEnumeratePhysicalDevices_(gpu.instance, &count, nullptr), "vkEnumeratePhysicalDevices");
+	Check(count > 0, "no physical device");
+	std::vector<VkPhysicalDevice> devices(count);
+	CheckVk(vkEnumeratePhysicalDevices_(gpu.instance, &count, devices.data()), "vkEnumeratePhysicalDevices list");
+	gpu.physical = devices[0];
+	vkGetPhysicalDeviceMemoryProperties_(gpu.physical, &gpu.memory);
+	VkPhysicalDeviceProperties props {};
+	vkGetPhysicalDeviceProperties_(gpu.physical, &props);
+	gpu.storage_alignment = props.limits.minStorageBufferOffsetAlignment;
+	uint32_t qcount = 0;
+	vkGetPhysicalDeviceQueueFamilyProperties_(gpu.physical, &qcount, nullptr);
+	std::vector<VkQueueFamilyProperties> queues(qcount);
+	vkGetPhysicalDeviceQueueFamilyProperties_(gpu.physical, &qcount, queues.data());
+	for (uint32_t i = 0; i < qcount; ++i) {
+		if (queues[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) {
+			gpu.family = i;
+			break;
+		}
+	}
+	VkPhysicalDeviceFeatures supported {};
+	vkGetPhysicalDeviceFeatures_(gpu.physical, &supported);
+	Check(supported.vertexPipelineStoresAndAtomics, "device lacks vertexPipelineStoresAndAtomics (the VS cannot store)");
+	VkPhysicalDeviceFeatures features {};
+	features.vertexPipelineStoresAndAtomics = VK_TRUE;
+	features.fragmentStoresAndAtomics       = supported.fragmentStoresAndAtomics;
+	features.shaderClipDistance             = supported.shaderClipDistance; // the emitted VS has a clip guard
+	features.geometryShader                 = supported.geometryShader; // PrimitiveId in the PS needs the Geometry capability

@wuboo Thanks for confirming the GPU results. Your reported MoltenVK run covers the previously pending GPU check: all 7 cases and --stress pass, and both harness mutants fail as expected.

✅ Review thread resolved.

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-12 15:21 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1441#discussion_r4249661598) On `tests/PerVertexVsStoreGpuTests.cpp` line 382 (outdated): ```diff @@ -0,0 +1,751 @@ +// GPU harness for KYTY_PV_VSSTORE (graphics/host_gpu/renderer/perVertexVsStore.h). The real SPIR-V +// emitter produces the VS-store VS and PS from an IR vertex shader and an ISA pixel shader, and the +// pair is drawn on the host GPU (MoltenVK) with the exact descriptor/push layout of the renderer: +// set 0 = empty, set 1 = {cap SSBO (VS|FS), guest index SSBO (FS)}, push = native data + 8 dwords. +// Checks (bit for bit, no tolerance): +// 1. image: every probed pixel equals the PerVertexKHR semantics computed on the CPU from the vertex +// data, the index buffer and the draw parameters (corner 0/1/2 read through P0/P10/P20), +// 2. cap: the records the VS wrote hold {gl_VertexIndex, gl_InstanceIndex} of the cases, which +// settles whether gl_VertexIndex includes vertex_offset and gl_InstanceIndex first_instance. +// Cases: 16-bit and 32-bit indices, vertex_offset > 0 and < 0, first_instance != 0, 2 instances, an index +// buffer bound at an offset that is not a multiple of minStorageBufferOffsetAlignment. +// Run: per_vertex_vsstore_gpu_tests [--dump] [--stress] (--stress: 2M triangles x 2..4 instances, parameter-buffer overflow) +// --dump needs no GPU: it prints the emitted SPIR-V. +// The result is compared with the CPU model of the per-vertex semantics. The mutants built from +// tests/PerVertexVsStoreMutants.cmake (corner 0/2 swapped, index range not rounded) must fail it. + +#include "common/emulatorConfig.h" +#include "common/logging/log.h" +#include "common/subsystems.h" +#include "common/threads.h" +#include "graphics/host_gpu/renderer/perVertexVsStore.h" +#include "graphics/shader/recompiler/ShaderRecompiler.h" +#include "graphics/shader/recompiler/backend/spirv/SpirvEmitter.h" +#include "graphics/shader/recompiler/ir/IREmitter.h" +#include "graphics/shader/recompiler/ir/ShaderIR.h" +#include "graphics/shader/recompiler/ir/passes/ResourceTracking.h" +#include "graphics/shader/shader.h" +#include "graphics/shader/shaderCompiler.h" + +#include <spirv-tools/libspirv.hpp> +#include <vulkan/vulkan.h> + +#include <dlfcn.h> + +#include <algorithm> +#include <array> +#include <cstdint> +#include <cstdio> +#include <cstdlib> +#include <cstring> +#include <span> +#include <string> +#include <vector> + +namespace Libs::Graphics { +namespace { + +using namespace ShaderRecompiler; + +bool g_stress = false; // --stress: the >= 2M triangle cases + +[[noreturn]] void Fail(const char* message) { + std::fprintf(stderr, "per-vertex-vsstore-gpu-tests: FAILED: %s\n", message); + std::exit(1); +} + +void Check(bool ok, const char* message) { + if (!ok) Fail(message); +} + +void CheckVk(VkResult result, const char* what) { + if (result != VK_SUCCESS) { + std::fprintf(stderr, "per-vertex-vsstore-gpu-tests: FAILED: %s (VkResult %d)\n", what, static_cast<int>(result)); + std::exit(1); + } +} + +constexpr uint32_t EncodeSopp(uint32_t opcode, uint32_t simm = 0) { + return (0x17fu << 23u) | ((opcode & 0x7fu) << 16u) | (simm & 0xffffu); +} +constexpr uint32_t EncodeVintrp(uint32_t opcode, uint32_t vdst, uint32_t attr, uint32_t chan, uint32_t vsrc) { + return (0x32u << 26u) | ((opcode & 0x3u) << 16u) | ((vdst & 0xffu) << 18u) | ((attr & 0x3fu) << 10u) | + ((chan & 0x3u) << 8u) | (vsrc & 0xffu); +} +constexpr uint32_t EncodeExp0(uint32_t target, uint32_t en) { + return (0x3eu << 26u) | ((target & 0x3fu) << 4u) | (en & 0xfu) | (1u << 11u); +} +constexpr uint32_t EncodeExp1(uint32_t a, uint32_t b, uint32_t c, uint32_t d) { + return (a & 0xffu) | ((b & 0xffu) << 8u) | ((c & 0xffu) << 16u) | ((d & 0xffu) << 24u); +} + +void EnsureConfigInitialized() { + static bool initialized = false; + if (initialized) return; + static Common::Subsystems subsystems; + Common::InitializeThreads(); + subsystems.Initialize<Config::Lifecycle>(); + Config::ConfigOptions options; + options.printf_direction = Config::LogDirection::Silent; + Config::Load(options); + subsystems.Initialize<Log::Lifecycle>(); + ShaderInit(); + initialized = true; +} + +// ---- shaders ------------------------------------------------------------------------------------- + +struct Shaders { + std::vector<uint32_t> vs; + std::vector<uint32_t> ps; + uint32_t stride_vec4 = 0; +}; + +// VS: position = attr0, param0 = attr1 with `+ instance` added to the bits of x (a 1 ulp difference +// per instance shows a record of the wrong instance), param1 = {gl_VertexIndex, gl_InstanceIndex, 0, 0}. +// PS: out = {corner0.x, corner1.y, corner2.z, corner0.w} of param0. +Shaders BuildShaders() { + using IR::Value; + using O = IR::ValueOpcode; + Shaders out; + + IR::Program vs; + vs.stage = ShaderType::Vertex; + vs.wave_size = 64; + vs.srt_plan_complete = vs.resource_tracking_complete = vs.shader_info_complete = true; + vs.block_storage.push_back(std::make_unique<IR::Block>()); + vs.blocks.push_back(vs.block_storage.back().get()); + vs.info.inputs = {{IR::StageInputKind::VertexIndex}, + {IR::StageInputKind::InstanceIndex}, + {IR::StageInputKind::Parameter, 0, 4}, + {IR::StageInputKind::Parameter, 1, 4}}; + vs.info.outputs = {{IR::StageOutputKind::Position}, + {IR::StageOutputKind::Parameter, 0, 0}, + {IR::StageOutputKind::Parameter, 1, 1}}; + vs.export_info = {{.kind = IR::ExportTargetKind::Position, .en = 15}, + {.kind = IR::ExportTargetKind::Parameter, .index = 0, .en = 15}, + {.kind = IR::ExportTargetKind::Parameter, .index = 1, .en = 15}}; + IR::IREmitter emit(vs.blocks.front()); + const auto vertex = emit.Emit(O::GetBuiltin, {Value(static_cast<uint32_t>(IR::StageInputKind::VertexIndex)), Value(0u)}); + const auto instance = emit.Emit(O::GetBuiltin, {Value(static_cast<uint32_t>(IR::StageInputKind::InstanceIndex)), Value(0u)}); + std::array<Value, 4> position, color; + for (uint32_t c = 0; c < 4; c++) position[c] = emit.Emit(O::GetAttribute, {Value(0u), Value(c)}); + for (uint32_t c = 0; c < 4; c++) color[c] = emit.Emit(O::GetAttribute, {Value(1u), Value(c)}); + const auto pos = emit.Emit(O::CompositeConstructU32x4, {position[0], position[1], position[2], position[3]}); + emit.Emit(O::SetAttribute, {pos, Value(true)}, IR::ExportFlags {0}); + const auto x = emit.Emit(O::IAdd32, {color[0], instance}); + const auto param0 = emit.Emit(O::CompositeConstructU32x4, {x, color[1], color[2], color[3]}); + emit.Emit(O::SetAttribute, {param0, Value(true)}, IR::ExportFlags {1}); + const auto param1 = emit.Emit(O::CompositeConstructU32x4, {vertex, instance, Value(0u), Value(0u)}); + emit.Emit(O::SetAttribute, {param1, Value(true)}, IR::ExportFlags {2}); + static const ShaderVertexInputInfo vertex_info {}; + ShaderStageInputInfo vs_input {.vertex = &vertex_info}; + + uint32_t vs_mask = 0; + Spirv::PvStoreInfo vs_store; + vs_store.role = Spirv::PvStoreInfo::Role::Vertex; + vs_store.coherent = true; + vs_store.location_mask = &vs_mask; + out.vs = Spirv::EmitProgram(vs, vs_input, 0, &vs_store); + + // PS (the interpolation setup of TestPvVsStoreEmission): v_interp_mov_f32 with P0 / P10 / P20. + const uint32_t ps_code[] = {EncodeVintrp(2, 12, 0, 0, 2), EncodeVintrp(2, 13, 0, 1, 0), + EncodeVintrp(2, 14, 0, 2, 1), EncodeVintrp(2, 15, 0, 3, 2), + EncodeExp0(0x00, 0xf), EncodeExp1(12, 13, 14, 15), + EncodeSopp(0x01)}; + static ShaderPixelInputInfo ps_info {}; + ps_info.input_num = 1; + ps_info.ps_system_input_base = 2; + ps_info.custom_interpolation_mask = 1; + ps_info.ps_perspective_center_vgpr = 0; + for (uint32_t i = 0; i < std::size(ps_info.interpolator_settings); i++) ps_info.interpolator_settings[i] = i; + ps_info.interpolator_settings[0] = 0x00000420u; + static const std::array<uint32_t, 64> user_data = [] { + std::array<uint32_t, 64> data {}; + data[3] = 3u << 28u; + return data; + }(); + CompileOptions options; + options.stage = ShaderType::Pixel; + options.user_data = user_data; + options.input_info.pixel = &ps_info; + auto translated = TranslateProgram(ps_code, options); + auto plan = IR::ExtractResourcePlan(translated.program); + IR::ResourceSnapshot resources; + IR::ResourceSpecialization specialization; + const IR::SrtRuntime runtime {.user_data = options.user_data, + .shader_base = reinterpret_cast<uint64_t>(ps_code), + .read_specialization_memory = [](void*, uint64_t, std::span<uint32_t>) { return false; }}; + Check(IR::MaterializeResources(plan, runtime, resources, specialization), "PS resources did not materialize"); + auto compiled = CompileProgram(std::move(translated), options, specialization, 0); + uint32_t ps_mask = 0; + Spirv::PvStoreInfo ps_store; + ps_store.role = Spirv::PvStoreInfo::Role::Pixel; + ps_store.coherent = true; + ps_store.location_mask = &ps_mask; + out.ps = Spirv::EmitProgram(compiled.program, options.input_info, 0, &ps_store); + + Check(ClassifyPvVsStoreInterface(vs_mask, ps_mask) == PvVsStoreInterfaceVerdict::Use, "VS/PS pair is not a VS-store candidate"); + out.stride_vec4 = PvVsStoreStrideFor(vs_mask); + if (out.stride_vec4 != 2) std::fprintf(stderr, "VS location mask %08x, PS location mask %08x\n", vs_mask, ps_mask); + Check(out.stride_vec4 == 2, "expected stride 2 (locations 0 and 1)"); + spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_2); + Check(tools.Validate(out.vs), "VS-store VS does not validate"); + Check(tools.Validate(out.ps), "VS-store PS does not validate"); + return out; +} + +// ---- scene (CPU model) --------------------------------------------------------------------------- + +constexpr uint32_t kDim = 32; // render target +constexpr uint32_t kCell = 16; // one triangle per cell: 2x2 cells +constexpr uint32_t kVertices = 24; // 4 triangles x 3 corners, plus 12 spare vertices for offsets +constexpr uint32_t kStrideB = 32; // float4 position, float4 color + +struct Vertex { + float position[4]; + float color[4]; +}; + +std::array<Vertex, kVertices> MakeVertices() { + std::array<Vertex, kVertices> v {}; + for (uint32_t i = 0; i < kVertices; ++i) { + const uint32_t tri = (i / 3u) % 4u; + const uint32_t cx = tri % 2u, cy = tri / 2u; + const float x0 = static_cast<float>(cx * kCell), y0 = static_cast<float>(cy * kCell); + const float px[3] = {x0 + 2.f, x0 + 14.f, x0 + 2.f}; + const float py[3] = {y0 + 2.f, y0 + 2.f, y0 + 14.f}; + const uint32_t k = i % 3u; + v[i].position[0] = px[k] / (kDim / 2.f) - 1.f; + v[i].position[1] = py[k] / (kDim / 2.f) - 1.f; + v[i].position[2] = 0.5f; + v[i].position[3] = 1.f; + // distinct, normal floats: any mix-up of a vertex, a corner or a component shows + v[i].color[0] = 1.0f + 0.03125f * static_cast<float>(i); + v[i].color[1] = 2.0f + 0.0625f * static_cast<float>(i); + v[i].color[2] = 3.0f + 0.125f * static_cast<float>(i); + v[i].color[3] = 4.0f + 0.25f * static_cast<float>(i); + } + return v; +} + +struct Case { + const char* name; + bool index32; + std::vector<uint32_t> indices; // per triangle corner, relative to vertex_offset + int32_t vertex_offset; + uint32_t first_instance; + uint32_t instance_count; + uint32_t bind_byte_offset; // where the index data starts inside the index buffer +}; + +uint32_t Bits(float f) { + uint32_t u; + std::memcpy(&u, &f, 4); + return u; +} + +// Expected pixel of triangle t of the draw: {corner0.x(+inst), corner1.y, corner2.z, corner0.w}. +std::array<uint32_t, 4> ExpectedPixel(const std::array<Vertex, kVertices>& v, const Case& c, uint32_t tri) { + const uint32_t last_instance = c.first_instance + c.instance_count - 1; + const auto vertex = [&](uint32_t corner) { return static_cast<uint32_t>(static_cast<int32_t>(c.indices[tri * 3 + corner]) + c.vertex_offset); }; + std::array<uint32_t, 4> out {}; + out[0] = Bits(v[vertex(0)].color[0]) + last_instance; + out[1] = Bits(v[vertex(1)].color[1]); + out[2] = Bits(v[vertex(2)].color[2]); + out[3] = Bits(v[vertex(0)].color[3]); + return out; +} + +// ---- Vulkan -------------------------------------------------------------------------------------- + +#define VK_FUNCS(X) \ + X(vkCreateDevice) X(vkGetDeviceProcAddr) X(vkEnumeratePhysicalDevices) X(vkGetPhysicalDeviceMemoryProperties) \ + X(vkGetPhysicalDeviceQueueFamilyProperties) X(vkGetPhysicalDeviceFeatures) X(vkGetPhysicalDeviceProperties) + +#define VK_DEVICE_FUNCS(X) \ + X(vkGetDeviceQueue) X(vkCreateBuffer) X(vkGetBufferMemoryRequirements) X(vkAllocateMemory) X(vkBindBufferMemory) \ + X(vkMapMemory) X(vkCreateDescriptorSetLayout) X(vkCreatePipelineLayout) X(vkCreateShaderModule) \ + X(vkCreateGraphicsPipelines) X(vkCreateDescriptorPool) X(vkAllocateDescriptorSets) X(vkUpdateDescriptorSets) \ + X(vkCreateCommandPool) X(vkAllocateCommandBuffers) X(vkBeginCommandBuffer) X(vkEndCommandBuffer) \ + X(vkCmdBindPipeline) X(vkCmdBindDescriptorSets) X(vkCmdPushConstants) X(vkCmdBeginRenderPass) X(vkCmdEndRenderPass) \ + X(vkCmdBindVertexBuffers) X(vkCmdBindIndexBuffer) X(vkCmdDrawIndexed) X(vkCmdCopyImageToBuffer) X(vkQueueSubmit) \ + X(vkQueueWaitIdle) X(vkCreateRenderPass) X(vkCreateFramebuffer) X(vkCreateImage) X(vkGetImageMemoryRequirements) \ + X(vkBindImageMemory) X(vkCreateImageView) X(vkCmdPipelineBarrier) + +#define DECLARE(name) PFN_##name name##_ = nullptr; +VK_FUNCS(DECLARE) +VK_DEVICE_FUNCS(DECLARE) +#undef DECLARE + +struct Gpu { + VkInstance instance = VK_NULL_HANDLE; + VkPhysicalDevice physical = VK_NULL_HANDLE; + VkDevice device = VK_NULL_HANDLE; + VkQueue queue = VK_NULL_HANDLE; + uint32_t family = 0; + VkPhysicalDeviceMemoryProperties memory {}; + VkDeviceSize storage_alignment = 16; +}; + +struct Buf { + VkBuffer buffer = VK_NULL_HANDLE; + VkDeviceMemory memory = VK_NULL_HANDLE; + void* mapped = nullptr; + size_t size = 0; +}; + +uint32_t MemoryType(const Gpu& gpu, uint32_t bits, VkMemoryPropertyFlags flags) { + for (uint32_t i = 0; i < gpu.memory.memoryTypeCount; ++i) { + if ((bits & (1u << i)) && (gpu.memory.memoryTypes[i].propertyFlags & flags) == flags) return i; + } + Fail("no suitable memory type"); +} + +Buf MakeBuffer(const Gpu& gpu, size_t size, VkBufferUsageFlags usage) { + Buf b; + b.size = size; + VkBufferCreateInfo info {VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; + info.size = size; + info.usage = usage; + CheckVk(vkCreateBuffer_(gpu.device, &info, nullptr, &b.buffer), "vkCreateBuffer"); + VkMemoryRequirements req; + vkGetBufferMemoryRequirements_(gpu.device, b.buffer, &req); + VkMemoryAllocateInfo alloc {VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; + alloc.allocationSize = req.size; + alloc.memoryTypeIndex = MemoryType(gpu, req.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); + CheckVk(vkAllocateMemory_(gpu.device, &alloc, nullptr, &b.memory), "vkAllocateMemory"); + CheckVk(vkBindBufferMemory_(gpu.device, b.buffer, b.memory, 0), "vkBindBufferMemory"); + CheckVk(vkMapMemory_(gpu.device, b.memory, 0, size, 0, &b.mapped), "vkMapMemory"); + std::memset(b.mapped, 0xA5, size); + return b; +} + +Gpu InitGpu() { + const char* driver = std::getenv("SDL_VULKAN_LIBRARY"); + void* lib = dlopen(driver != nullptr ? driver : "libMoltenVK.dylib", RTLD_NOW | RTLD_LOCAL); + if (lib == nullptr) Fail("cannot load MoltenVK; set SDL_VULKAN_LIBRARY"); + auto get_instance_proc = reinterpret_cast<PFN_vkGetInstanceProcAddr>(dlsym(lib, "vkGetInstanceProcAddr")); + if (get_instance_proc == nullptr) Fail("dlsym vkGetInstanceProcAddr"); + auto create_instance = reinterpret_cast<PFN_vkCreateInstance>(get_instance_proc(VK_NULL_HANDLE, "vkCreateInstance")); + auto enumerate_extensions = reinterpret_cast<PFN_vkEnumerateInstanceExtensionProperties>( + get_instance_proc(VK_NULL_HANDLE, "vkEnumerateInstanceExtensionProperties")); + if (enumerate_extensions == nullptr) Fail("vkEnumerateInstanceExtensionProperties"); + uint32_t extension_count = 0; + CheckVk(enumerate_extensions(nullptr, &extension_count, nullptr), "vkEnumerateInstanceExtensionProperties"); + std::vector<VkExtensionProperties> available(extension_count); + CheckVk(enumerate_extensions(nullptr, &extension_count, available.data()), "vkEnumerateInstanceExtensionProperties list"); + bool has_portability = false; + for (const auto& e: available) { + if (std::strcmp(e.extensionName, VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME) == 0) has_portability = true; + } + const char* extensions[] {VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME}; + VkApplicationInfo app {VK_STRUCTURE_TYPE_APPLICATION_INFO}; + app.apiVersion = VK_API_VERSION_1_3; + VkInstanceCreateInfo info {VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO}; + info.pApplicationInfo = &app; + info.flags = has_portability ? VK_INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR : 0; + info.enabledExtensionCount = has_portability ? 1u : 0u; + info.ppEnabledExtensionNames = has_portability ? extensions : nullptr; + Gpu gpu; + CheckVk(create_instance(&info, nullptr, &gpu.instance), "vkCreateInstance"); +#define LOAD_INSTANCE(name) name##_ = reinterpret_cast<PFN_##name>(get_instance_proc(gpu.instance, #name)); + VK_FUNCS(LOAD_INSTANCE) +#undef LOAD_INSTANCE + uint32_t count = 0; + CheckVk(vkEnumeratePhysicalDevices_(gpu.instance, &count, nullptr), "vkEnumeratePhysicalDevices"); + Check(count > 0, "no physical device"); + std::vector<VkPhysicalDevice> devices(count); + CheckVk(vkEnumeratePhysicalDevices_(gpu.instance, &count, devices.data()), "vkEnumeratePhysicalDevices list"); + gpu.physical = devices[0]; + vkGetPhysicalDeviceMemoryProperties_(gpu.physical, &gpu.memory); + VkPhysicalDeviceProperties props {}; + vkGetPhysicalDeviceProperties_(gpu.physical, &props); + gpu.storage_alignment = props.limits.minStorageBufferOffsetAlignment; + uint32_t qcount = 0; + vkGetPhysicalDeviceQueueFamilyProperties_(gpu.physical, &qcount, nullptr); + std::vector<VkQueueFamilyProperties> queues(qcount); + vkGetPhysicalDeviceQueueFamilyProperties_(gpu.physical, &qcount, queues.data()); + for (uint32_t i = 0; i < qcount; ++i) { + if (queues[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) { + gpu.family = i; + break; + } + } + VkPhysicalDeviceFeatures supported {}; + vkGetPhysicalDeviceFeatures_(gpu.physical, &supported); + Check(supported.vertexPipelineStoresAndAtomics, "device lacks vertexPipelineStoresAndAtomics (the VS cannot store)"); + VkPhysicalDeviceFeatures features {}; + features.vertexPipelineStoresAndAtomics = VK_TRUE; + features.fragmentStoresAndAtomics = supported.fragmentStoresAndAtomics; + features.shaderClipDistance = supported.shaderClipDistance; // the emitted VS has a clip guard + features.geometryShader = supported.geometryShader; // PrimitiveId in the PS needs the Geometry capability ``` `@wuboo` Thanks for confirming the GPU results. Your reported MoltenVK run covers the previously pending GPU check: all 7 cases and `--stress` pass, and both harness mutants fail as expected. ✅ Review thread resolved. _You are interacting with an AI system._ <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-16 18:06 UTC · original · edited 2026-10-16 18:42 UTC
On src/graphics/host_gpu/renderer/renderDraw.cpp line 1171 (outdated):

@@ -1092,6 +1104,135 @@ bool RenderExecutor::CopyDepthToColor(CommandBuffer& buffer, const DrawCallInfo&
 	return true;
 }
 
+// ---- VS-store path (PerVertexKHR emulation, see perVertexVsStore.h) ----
+bool RenderExecutor::TryPvVsStoreDraw(const DrawCallInfo& draw, const DrawRenderState& state,
+                                      vk::PrimitiveTopology topology, bool primitive_restart_enable,
+                                      const DrawEmitInfo&          emit,
+                                      const DrawIndexBufferSource& index_source,
+                                      PvVsStoreDrawSetup&          setup) {
+	if (!state.ps_active || state.vertex_info[0].logical_stage != ShaderType::Vertex ||
+	    state.vertex_info[0].stage.program->stage == ShaderType::Mesh)
+		return false;
+	auto&       graphics = m_context.GetGraphics();
+	const auto* programs = GetPvVsStorePrograms(graphics, state.programs);
+	if (programs == nullptr) return false; // not a per-vertex pair the store knows
+	if (programs->verdict != PvVsStoreInterfaceVerdict::Use) {
+		// A PS whose per-vertex inputs are never read (NoPerVertex) is not a fallback: nothing to
+		// count.
+		if (const auto fallback = ClassifyPvVsStoreFallback(programs->verdict);
+		    fallback != PvVsStoreFallback::None)
+			CountPvVsStoreDraw(fallback);
+		return false;
+	}
+	const uint32_t element_size =
+	    index_source.host_data != nullptr ? sizeof(uint16_t) : index_source.guest_element_size;
+
+	PvVsStoreRequest request;
+	request.enabled            = true;
+	request.triangle_list      = topology == vk::PrimitiveTopology::eTriangleList;
+	request.indexed            = draw.IsIndexed();
+	request.primitive_restart  = primitive_restart_enable;
+	request.index_size         = draw.IsIndexed() ? element_size : 0;
+	request.index_count        = draw.index_count;
+	request.instance_count     = draw.instance_count;
+	request.record_stride_vec4 = programs->stride_vec4;
+	const bool scannable = request.triangle_list && request.indexed && !primitive_restart_enable &&
+	                       (element_size == 2 || element_size == 4) && index_source.size != 0 &&
+	                       index_source.size >= uint64_t {draw.index_count} * element_size;
+	if (scannable) {
+		const void* idx_bytes = index_source.host_data != nullptr
+		                            ? index_source.host_data
+		                            : reinterpret_cast<const void*>(index_source.address);
+		const auto  range =
+		    ScanPvVsStoreVertexRange(idx_bytes, element_size, draw.index_count, emit.vertex_offset);
+		PvVsStoreStatsRef().scanned_indices.fetch_add(draw.index_count, std::memory_order_relaxed);
+		request.range_known   = range.known;
+		request.range_dropped = range.dropped;
+		request.range_first   = range.first;
+		request.range_end     = range.end;
+	}
+	// A storage descriptor is bound from an aligned offset and the difference becomes first_index;
+	// the guest address decides the offset modulo the element size, so an odd one stays on
+	// PerVertexKHR.
+	const bool index_aligned = element_size == 0 || index_source.host_data != nullptr ||
+	                           index_source.address % element_size == 0;
+	// The descriptor of the index buffer must stay inside the buffer the cache hands out (its end
+	// is not ours to choose): obtain the binding now (the draw obtains the same range again) and
+	// ask whether the last word the PS reads fits. A host copy is padded to a whole word in
+	// PrepareIndexBuffer.
+	bool index_tail_fits = true;
+	if (index_aligned && scannable && index_source.host_data == nullptr) {
+		const auto [index_buffer, index_offset] =
+		    m_context.GetBufferCache().ObtainBuffer(index_source.address, index_source.size, false);
+		index_tail_fits =
+		    PvVsStoreIndexDescriptorFor(index_offset, element_size, graphics.StorageMinAlignment(),
+		                                index_source.size, index_buffer->Size())
+		        .tail_fits;
+	}

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '940,980p' src/graphics/host_gpu/renderer/renderDraw.cpp
sed -n '1135,1240p' src/graphics/host_gpu/renderer/renderDraw.cpp
sed -n '1260,1350p' src/graphics/host_gpu/renderer/renderDraw.cpp
sed -n '480,545p' src/graphics/host_gpu/renderer/cache/bufferCache.cpp

Repository: KytyPS5/KytyPS5

Length of output: 14291


🏁 Script executed:

set -o pipefail
rg -n -F --glob '*.cpp' --glob '*.h' \
  -e 'PrepareGraphicsBindings' \
  -e 'AcquireVertexBuffers' \
  -e 'SynchronizeBuffer' \
  -e 'FindBuffer' \
  -e 'm_slot_buffers' \
  -e 'm_stream_buffer' \
  src/graphics/host_gpu/renderer src/graphics/host_gpu/renderer/cache
printf '\n--- renderDraw relevant declarations and call sites ---\n'
rg -n -C 18 -F -- 'void RenderExecutor::PrepareGraphicsBindings' src/graphics/host_gpu/renderer
rg -n -C 22 -F -- 'PreparedVertexBuffers RenderExecutor::AcquireVertexBuffers' src/graphics/host_gpu/renderer
printf '\n--- buffer cache definitions ---\n'
rg -n -C 20 -F -- 'BufferCache::FindBuffer' src/graphics/host_gpu/renderer/cache/bufferCache.cpp
rg -n -C 24 -F -- 'BufferCache::SynchronizeBuffer' src/graphics/host_gpu/renderer/cache/bufferCache.cpp

Repository: KytyPS5/KytyPS5

Length of output: 22297


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- FindBuffers and PrepareGraphicsBindings ---'
sed -n '700,885p' src/graphics/host_gpu/renderer/pipeline/descriptors.cpp
printf '%s\n' '--- AcquireVertexBuffers and surrounding helpers ---'
sed -n '620,735p' src/graphics/host_gpu/renderer/renderDraw.cpp
printf '%s\n' '--- buffer creation and overlap handling ---'
sed -n '318,425p' src/graphics/host_gpu/renderer/cache/bufferCache.cpp
printf '%s\n' '--- buffer lifetime, bounds, offset, and registration ---'
sed -n '1,190p' src/graphics/host_gpu/renderer/cache/bufferCache.cpp
sed -n '1,180p' src/graphics/host_gpu/renderer/cache/bufferCache.h
printf '%s\n' '--- exact VS-store decision and bind path ---'
sed -n '1010,1185p' src/graphics/host_gpu/renderer/renderDraw.cpp
sed -n '1248,1355p' src/graphics/host_gpu/renderer/renderDraw.cpp

Repository: KytyPS5/KytyPS5

Length of output: 43352


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- exact numbered VS-store and draw-order lines ---'
nl -ba src/graphics/host_gpu/renderer/renderDraw.cpp | sed -n '1060,1185p'
nl -ba src/graphics/host_gpu/renderer/renderDraw.cpp | sed -n '1270,1338p'
printf '%s\n' '--- descriptor helper ---'
rg -n -C 30 -F -- 'PvVsStoreIndexDescriptorFor' src/graphics/host_gpu/renderer
printf '%s\n' '--- stream Map declaration and implementation ---'
rg -n -F -- 'StreamBuffer::Map' src/graphics/host_gpu
rg -n -C 18 -F -- 'class StreamBuffer' src/graphics/host_gpu
printf '%s\n' '--- changed diff for this boundary ---'
git diff d7974dc76357565e58a88887060f8300dc8a3966 990c1754919ef8aaa6acbab752be16fbb02e4e39 -- src/graphics/host_gpu/renderer/renderDraw.cpp src/graphics/host_gpu/renderer/cache/bufferCache.cpp

Repository: KytyPS5/KytyPS5

Length of output: 42238


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- StreamBuffer::Map complete body ---'
nl -ba src/graphics/host_gpu/renderer/cache/streamBuffer.cpp | sed -n '210,310p'
printf '%s\n' '--- PrepareBda and BDA synchronization ---'
rg -n -C 35 -F -- 'void RenderContext::PrepareBda' src/graphics/host_gpu
rg -n -C 35 -F -- 'SynchronizeBda' src/graphics/host_gpu
printf '%s\n' '--- memory tracker CPU/GPU modified transitions ---'
rg -n -C 12 -F -- 'MarkRegionAsCpuModified' src/graphics/host_gpu/renderer/cache
rg -n -C 12 -F -- 'UnmarkRegionAsCpuModified' src/graphics/host_gpu/renderer/cache

Repository: KytyPS5/KytyPS5

Length of output: 32373


🏁 Script executed:

set -o pipefail
rg -n -C 8 -F -- 'TryPvVsStoreDraw' src/graphics/host_gpu/renderer
nl -ba src/graphics/host_gpu/renderer/renderDraw.cpp | sed -n '940,985p'
nl -ba src/graphics/host_gpu/renderer/renderDraw.cpp | sed -n '1200,1230p'

Repository: KytyPS5/KytyPS5

Length of output: 9995


Validate the prepared index binding.

TryPvVsStoreDraw validates one ObtainBuffer result before PrepareGraphicsBindings, but PrepareIndexBuffer obtains the same range again afterward. For small CPU-modified ranges, ObtainBuffer uses StreamBuffer::Map; each Commit advances the stream offset, so the two bindings can differ. BindPvVsStore then uses the second binding. If its descriptor is invalid, EXIT_IF aborts the draw. If only the tail does not fit, the descriptor is clamped and the draw still does not fall back.

Move the VS-store decision after PrepareIndexBuffer and validate that prepared binding.

Suggested fix
 // render.h
-                                    const DrawIndexBufferSource& index_source,
+                                    const DrawIndexBufferSource& index_source,
+                                    vk::DeviceSize              index_offset,
+                                    vk::DeviceSize              index_buffer_size,
                                     PvVsStoreDrawSetup&          setup);

 // renderDraw.cpp
 bool RenderExecutor::TryPvVsStoreDraw(const DrawCallInfo& draw, const DrawRenderState& state,
                                       vk::PrimitiveTopology topology, bool primitive_restart_enable,
                                       const DrawEmitInfo&          emit,
                                       const DrawIndexBufferSource& index_source,
+                                      vk::DeviceSize               index_offset,
+                                      vk::DeviceSize               index_buffer_size,
                                       PvVsStoreDrawSetup&          setup) {
 ...
-       const auto [index_buffer, index_offset] =
-           m_context.GetBufferCache().ObtainBuffer(index_source.address, index_source.size, false);
        index_tail_fits =
-           PvVsStoreIndexDescriptorFor(index_offset, element_size, graphics.StorageMinAlignment(),
-                                       index_source.size, index_buffer->Size())
+           PvVsStoreIndexDescriptorFor(index_offset, element_size, graphics.StorageMinAlignment(),
+                                       index_source.size, index_buffer_size)
                .tail_fits;
 ...
-   PvVsStoreDrawSetup pv_store;
-   const bool use_pv_store = !mesh_active && PvVsStoreEnabled() &&
-                             TryPvVsStoreDraw(draw, state, topology, primitive_restart_enable,
-                                              emit, index_source, pv_store);
    LogDrawPhase(draw.Name(), "PrepareBindings");
 ...
    if (!mesh_active) {
        LogDrawPhase(draw.Name(), "PrepareVertexBuffers");
        vertex_bindings = AcquireVertexBuffers(buffer, state.vertex_info[0]);
        index_binding   = PrepareIndexBuffer(buffer, index_source);
    }
+   PvVsStoreDrawSetup pv_store;
+   const bool use_pv_store = !mesh_active && PvVsStoreEnabled() &&
+                             TryPvVsStoreDraw(draw, state, topology, primitive_restart_enable,
+                                              emit, index_source, index_binding.offset,
+                                              index_binding.size, pv_store);

✅ Addressed in commit 29655ac

**@⁠coderabbitai[bot]** on GitHub · 2026-10-16 18:06 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1441#discussion_r4297806051) · edited 2026-10-16 18:42 UTC On `src/graphics/host_gpu/renderer/renderDraw.cpp` line 1171 (outdated): ```diff @@ -1092,6 +1104,135 @@ bool RenderExecutor::CopyDepthToColor(CommandBuffer& buffer, const DrawCallInfo& return true; } +// ---- VS-store path (PerVertexKHR emulation, see perVertexVsStore.h) ---- +bool RenderExecutor::TryPvVsStoreDraw(const DrawCallInfo& draw, const DrawRenderState& state, + vk::PrimitiveTopology topology, bool primitive_restart_enable, + const DrawEmitInfo& emit, + const DrawIndexBufferSource& index_source, + PvVsStoreDrawSetup& setup) { + if (!state.ps_active || state.vertex_info[0].logical_stage != ShaderType::Vertex || + state.vertex_info[0].stage.program->stage == ShaderType::Mesh) + return false; + auto& graphics = m_context.GetGraphics(); + const auto* programs = GetPvVsStorePrograms(graphics, state.programs); + if (programs == nullptr) return false; // not a per-vertex pair the store knows + if (programs->verdict != PvVsStoreInterfaceVerdict::Use) { + // A PS whose per-vertex inputs are never read (NoPerVertex) is not a fallback: nothing to + // count. + if (const auto fallback = ClassifyPvVsStoreFallback(programs->verdict); + fallback != PvVsStoreFallback::None) + CountPvVsStoreDraw(fallback); + return false; + } + const uint32_t element_size = + index_source.host_data != nullptr ? sizeof(uint16_t) : index_source.guest_element_size; + + PvVsStoreRequest request; + request.enabled = true; + request.triangle_list = topology == vk::PrimitiveTopology::eTriangleList; + request.indexed = draw.IsIndexed(); + request.primitive_restart = primitive_restart_enable; + request.index_size = draw.IsIndexed() ? element_size : 0; + request.index_count = draw.index_count; + request.instance_count = draw.instance_count; + request.record_stride_vec4 = programs->stride_vec4; + const bool scannable = request.triangle_list && request.indexed && !primitive_restart_enable && + (element_size == 2 || element_size == 4) && index_source.size != 0 && + index_source.size >= uint64_t {draw.index_count} * element_size; + if (scannable) { + const void* idx_bytes = index_source.host_data != nullptr + ? index_source.host_data + : reinterpret_cast<const void*>(index_source.address); + const auto range = + ScanPvVsStoreVertexRange(idx_bytes, element_size, draw.index_count, emit.vertex_offset); + PvVsStoreStatsRef().scanned_indices.fetch_add(draw.index_count, std::memory_order_relaxed); + request.range_known = range.known; + request.range_dropped = range.dropped; + request.range_first = range.first; + request.range_end = range.end; + } + // A storage descriptor is bound from an aligned offset and the difference becomes first_index; + // the guest address decides the offset modulo the element size, so an odd one stays on + // PerVertexKHR. + const bool index_aligned = element_size == 0 || index_source.host_data != nullptr || + index_source.address % element_size == 0; + // The descriptor of the index buffer must stay inside the buffer the cache hands out (its end + // is not ours to choose): obtain the binding now (the draw obtains the same range again) and + // ask whether the last word the PS reads fits. A host copy is padded to a whole word in + // PrepareIndexBuffer. + bool index_tail_fits = true; + if (index_aligned && scannable && index_source.host_data == nullptr) { + const auto [index_buffer, index_offset] = + m_context.GetBufferCache().ObtainBuffer(index_source.address, index_source.size, false); + index_tail_fits = + PvVsStoreIndexDescriptorFor(index_offset, element_size, graphics.StorageMinAlignment(), + index_source.size, index_buffer->Size()) + .tail_fits; + } ``` **🩺 Stability & Availability** | **🟠 Major** | **⚡ Quick win** <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash sed -n '940,980p' src/graphics/host_gpu/renderer/renderDraw.cpp sed -n '1135,1240p' src/graphics/host_gpu/renderer/renderDraw.cpp sed -n '1260,1350p' src/graphics/host_gpu/renderer/renderDraw.cpp sed -n '480,545p' src/graphics/host_gpu/renderer/cache/bufferCache.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 14291 --- 🏁 Script executed: ```bash set -o pipefail rg -n -F --glob '*.cpp' --glob '*.h' \ -e 'PrepareGraphicsBindings' \ -e 'AcquireVertexBuffers' \ -e 'SynchronizeBuffer' \ -e 'FindBuffer' \ -e 'm_slot_buffers' \ -e 'm_stream_buffer' \ src/graphics/host_gpu/renderer src/graphics/host_gpu/renderer/cache printf '\n--- renderDraw relevant declarations and call sites ---\n' rg -n -C 18 -F -- 'void RenderExecutor::PrepareGraphicsBindings' src/graphics/host_gpu/renderer rg -n -C 22 -F -- 'PreparedVertexBuffers RenderExecutor::AcquireVertexBuffers' src/graphics/host_gpu/renderer printf '\n--- buffer cache definitions ---\n' rg -n -C 20 -F -- 'BufferCache::FindBuffer' src/graphics/host_gpu/renderer/cache/bufferCache.cpp rg -n -C 24 -F -- 'BufferCache::SynchronizeBuffer' src/graphics/host_gpu/renderer/cache/bufferCache.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 22297 --- 🏁 Script executed: ```bash set -o pipefail printf '%s\n' '--- FindBuffers and PrepareGraphicsBindings ---' sed -n '700,885p' src/graphics/host_gpu/renderer/pipeline/descriptors.cpp printf '%s\n' '--- AcquireVertexBuffers and surrounding helpers ---' sed -n '620,735p' src/graphics/host_gpu/renderer/renderDraw.cpp printf '%s\n' '--- buffer creation and overlap handling ---' sed -n '318,425p' src/graphics/host_gpu/renderer/cache/bufferCache.cpp printf '%s\n' '--- buffer lifetime, bounds, offset, and registration ---' sed -n '1,190p' src/graphics/host_gpu/renderer/cache/bufferCache.cpp sed -n '1,180p' src/graphics/host_gpu/renderer/cache/bufferCache.h printf '%s\n' '--- exact VS-store decision and bind path ---' sed -n '1010,1185p' src/graphics/host_gpu/renderer/renderDraw.cpp sed -n '1248,1355p' src/graphics/host_gpu/renderer/renderDraw.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 43352 --- 🏁 Script executed: ```bash set -o pipefail printf '%s\n' '--- exact numbered VS-store and draw-order lines ---' nl -ba src/graphics/host_gpu/renderer/renderDraw.cpp | sed -n '1060,1185p' nl -ba src/graphics/host_gpu/renderer/renderDraw.cpp | sed -n '1270,1338p' printf '%s\n' '--- descriptor helper ---' rg -n -C 30 -F -- 'PvVsStoreIndexDescriptorFor' src/graphics/host_gpu/renderer printf '%s\n' '--- stream Map declaration and implementation ---' rg -n -F -- 'StreamBuffer::Map' src/graphics/host_gpu rg -n -C 18 -F -- 'class StreamBuffer' src/graphics/host_gpu printf '%s\n' '--- changed diff for this boundary ---' git diff d7974dc76357565e58a88887060f8300dc8a3966 990c1754919ef8aaa6acbab752be16fbb02e4e39 -- src/graphics/host_gpu/renderer/renderDraw.cpp src/graphics/host_gpu/renderer/cache/bufferCache.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 42238 --- 🏁 Script executed: ```bash set -o pipefail printf '%s\n' '--- StreamBuffer::Map complete body ---' nl -ba src/graphics/host_gpu/renderer/cache/streamBuffer.cpp | sed -n '210,310p' printf '%s\n' '--- PrepareBda and BDA synchronization ---' rg -n -C 35 -F -- 'void RenderContext::PrepareBda' src/graphics/host_gpu rg -n -C 35 -F -- 'SynchronizeBda' src/graphics/host_gpu printf '%s\n' '--- memory tracker CPU/GPU modified transitions ---' rg -n -C 12 -F -- 'MarkRegionAsCpuModified' src/graphics/host_gpu/renderer/cache rg -n -C 12 -F -- 'UnmarkRegionAsCpuModified' src/graphics/host_gpu/renderer/cache ``` Repository: KytyPS5/KytyPS5 Length of output: 32373 --- 🏁 Script executed: ```bash set -o pipefail rg -n -C 8 -F -- 'TryPvVsStoreDraw' src/graphics/host_gpu/renderer nl -ba src/graphics/host_gpu/renderer/renderDraw.cpp | sed -n '940,985p' nl -ba src/graphics/host_gpu/renderer/renderDraw.cpp | sed -n '1200,1230p' ``` Repository: KytyPS5/KytyPS5 Length of output: 9995 --- </details> **Validate the prepared index binding.** `TryPvVsStoreDraw` validates one `ObtainBuffer` result before `PrepareGraphicsBindings`, but `PrepareIndexBuffer` obtains the same range again afterward. For small CPU-modified ranges, `ObtainBuffer` uses `StreamBuffer::Map`; each `Commit` advances the stream offset, so the two bindings can differ. `BindPvVsStore` then uses the second binding. If its descriptor is invalid, `EXIT_IF` aborts the draw. If only the tail does not fit, the descriptor is clamped and the draw still does not fall back. Move the VS-store decision after `PrepareIndexBuffer` and validate that prepared binding. <details> <summary>Suggested fix</summary> ```diff // render.h - const DrawIndexBufferSource& index_source, + const DrawIndexBufferSource& index_source, + vk::DeviceSize index_offset, + vk::DeviceSize index_buffer_size, PvVsStoreDrawSetup& setup); // renderDraw.cpp bool RenderExecutor::TryPvVsStoreDraw(const DrawCallInfo& draw, const DrawRenderState& state, vk::PrimitiveTopology topology, bool primitive_restart_enable, const DrawEmitInfo& emit, const DrawIndexBufferSource& index_source, + vk::DeviceSize index_offset, + vk::DeviceSize index_buffer_size, PvVsStoreDrawSetup& setup) { ... - const auto [index_buffer, index_offset] = - m_context.GetBufferCache().ObtainBuffer(index_source.address, index_source.size, false); index_tail_fits = - PvVsStoreIndexDescriptorFor(index_offset, element_size, graphics.StorageMinAlignment(), - index_source.size, index_buffer->Size()) + PvVsStoreIndexDescriptorFor(index_offset, element_size, graphics.StorageMinAlignment(), + index_source.size, index_buffer_size) .tail_fits; ... - PvVsStoreDrawSetup pv_store; - const bool use_pv_store = !mesh_active && PvVsStoreEnabled() && - TryPvVsStoreDraw(draw, state, topology, primitive_restart_enable, - emit, index_source, pv_store); LogDrawPhase(draw.Name(), "PrepareBindings"); ... if (!mesh_active) { LogDrawPhase(draw.Name(), "PrepareVertexBuffers"); vertex_bindings = AcquireVertexBuffers(buffer, state.vertex_info[0]); index_binding = PrepareIndexBuffer(buffer, index_source); } + PvVsStoreDrawSetup pv_store; + const bool use_pv_store = !mesh_active && PvVsStoreEnabled() && + TryPvVsStoreDraw(draw, state, topology, primitive_restart_enable, + emit, index_source, index_binding.offset, + index_binding.size, pv_store); ``` </details> <!-- fingerprinting:phantom:medusa:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:04fad1bf026bf64ee953e20b --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commit 29655ac
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-16 18:06 UTC · original · reviewed

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 63c0a4ae-fe87-4d74-afac-8ce9e18f2355
📥 Commits

Reviewing files that changed from the base of the PR and between 516a49f94c0d5d1a14a0f1d4531128e4fb3f0d4d and 990c175491.

📒 Files selected for processing: 15
  • CMakeLists.txt
  • src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp
  • src/graphics/host_gpu/renderer/pipeline/pipelineCache.h
  • src/graphics/host_gpu/renderer/pipeline/shaders.cpp
  • src/graphics/host_gpu/renderer/render.h
  • src/graphics/host_gpu/renderer/renderDraw.cpp
  • src/graphics/presentation/window/vulkanWindow.cpp
  • src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.cpp
  • src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.h
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterFlow.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterModule.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp
  • tests/PerVertexVsStoreGpuTests.cpp
  • tests/shaderCfgTests.cpp

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 4 remain after this review.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-16 18:06 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1441#pullrequestreview-5551837476) · **reviewed** **Actionable comments posted: 1** --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> - **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `63c0a4ae-fe87-4d74-afac-8ce9e18f2355` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 516a49f94c0d5d1a14a0f1d4531128e4fb3f0d4d and 990c1754919ef8aaa6acbab752be16fbb02e4e39. </details> <details> <summary>📒 Files selected for processing: 15</summary> * `CMakeLists.txt` * `src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp` * `src/graphics/host_gpu/renderer/pipeline/pipelineCache.h` * `src/graphics/host_gpu/renderer/pipeline/shaders.cpp` * `src/graphics/host_gpu/renderer/render.h` * `src/graphics/host_gpu/renderer/renderDraw.cpp` * `src/graphics/presentation/window/vulkanWindow.cpp` * `src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.cpp` * `src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.h` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterFlow.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterModule.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp` * `tests/PerVertexVsStoreGpuTests.cpp` * `tests/shaderCfgTests.cpp` </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 4 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=6bc6365d-2136-4f6b-a310-1b7e87af0aca attempt=f19468c2-760c-412b-b421-7033c8c1b38d batch=1/1 -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-16 18:51 UTC · original · reviewed

Caution

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

⚠️ Outside diff range comments (2)

🟠 Major · Split the VS-store draw before fragment reads. · spirvEmitterPvStore.cpp:183-191

src/graphics/shader/recompiler/backend/spirv/spirvEmitterPvStore.cpp:183-191
🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

Split the VS-store draw before fragment reads.

When use_pv_store is true, the renderer binds pv_store.programs->graphics and issues one draw. The vertex shader stores records, and the fragment shader loads those records during the same draw. The OpMemoryBarrier orders accesses within one vertex invocation. It does not wait for all vertex invocations before fragment loads begin. ShaderWriteBarrier runs only after EmitDrawPrimitives, so it is too late.

Fragment invocations can therefore read stale or uninitialized records and produce incorrect per-vertex inputs. Execute the stores in a producer command without a fragment consumer, insert a buffer barrier from vertex-shader writes to fragment-shader reads, and issue a consumer draw with a vertex variant that does not rewrite the cap buffer. A single draw cannot provide this dependency.

🟠 Major · Gate the VS-store path on maxPushConstantsSize. · shaders.cpp:472-499

src/graphics/host_gpu/renderer/pipeline/shaders.cpp:472-499
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Gate the VS-store path on maxPushConstantsSize.

Vulkan 1.3 permits maxPushConstantsSize values as low as 128 bytes. The VS-store layout requests 160 bytes. The device-selection path does not reject a device with a smaller limit.

When an eligible draw selects the VS-store pipeline, createPipelineLayout can reject that range. EXIT_NOT_IMPLEMENTED then halts the emulator, and the draw does not fall back to the native path.

Suggested fix
 const PvVsStorePrograms* GetPvVsStorePrograms(GraphicContext&                        graphics,
                                               const PipelineCache::GraphicsPrograms& programs) {
 	if (!PvVsStoreEnabled() || programs.VertexStageCount() != 1) return nullptr;
+	if (graphics.GetPhysicalDeviceProperties().limits.maxPushConstantsSize <
+	    PvVsStorePushRangeBytes(ShaderRecompiler::IR::NativePushConstantSize, true)) {
+		return nullptr;
+	}
 	const auto      key = std::pair {programs.vertex[0].id, programs.pixel.id};

ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 7f007654-4c63-40cc-9a68-53a095ac4375
📥 Commits

Reviewing files that changed from the base of the PR and between 990c175491 and 29655ac0ed.

📒 Files selected for processing: 5
  • src/graphics/host_gpu/renderer/perVertexVsStore.h
  • src/graphics/host_gpu/renderer/render.h
  • src/graphics/host_gpu/renderer/renderDraw.cpp
  • tests/PerVertexVsStoreMutants.cmake
  • tests/PerVertexVsStoreTests.cpp
🚧 Files skipped from review as they are similar to previous changes: 3
  • src/graphics/host_gpu/renderer/render.h
  • src/graphics/host_gpu/renderer/renderDraw.cpp
  • src/graphics/host_gpu/renderer/perVertexVsStore.h

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 3 remain after this review.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-16 18:51 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1441#pullrequestreview-5552328098) · **reviewed** > [!CAUTION] > Some comments are outside the diff and can’t be posted inline due to GitHub limitations. > > **⚠️ Outside diff range comments (2)** > > <details> > <summary><strong>🟠 Major</strong> · Split the VS-store draw before fragment reads. · <code>spirvEmitterPvStore.cpp:183-191</code></summary><blockquote> > > `src/graphics/shader/recompiler/backend/spirv/spirvEmitterPvStore.cpp:183-191` > **🎯 Functional Correctness** | **🟠 Major** | **🏗️ Heavy lift** > > **Split the VS-store draw before fragment reads.** > > When `use_pv_store` is true, the renderer binds `pv_store.programs->graphics` and issues one draw. The vertex shader stores records, and the fragment shader loads those records during the same draw. The `OpMemoryBarrier` orders accesses within one vertex invocation. It does not wait for all vertex invocations before fragment loads begin. `ShaderWriteBarrier` runs only after `EmitDrawPrimitives`, so it is too late. > > Fragment invocations can therefore read stale or uninitialized records and produce incorrect per-vertex inputs. Execute the stores in a producer command without a fragment consumer, insert a buffer barrier from vertex-shader writes to fragment-shader reads, and issue a consumer draw with a vertex variant that does not rewrite the cap buffer. A single draw cannot provide this dependency. > > <!-- cr-comment:v1:8eba031b7d525baca13e70f4 --> > > </blockquote></details> > <details> > <summary><strong>🟠 Major</strong> · Gate the VS-store path on <code>maxPushConstantsSize</code>. · <code>shaders.cpp:472-499</code></summary><blockquote> > > `src/graphics/host_gpu/renderer/pipeline/shaders.cpp:472-499` > **🩺 Stability & Availability** | **🟠 Major** | **⚡ Quick win** > > **Gate the VS-store path on `maxPushConstantsSize`.** > > Vulkan 1.3 permits `maxPushConstantsSize` values as low as 128 bytes. The VS-store layout requests 160 bytes. The device-selection path does not reject a device with a smaller limit. > > When an eligible draw selects the VS-store pipeline, `createPipelineLayout` can reject that range. `EXIT_NOT_IMPLEMENTED` then halts the emulator, and the draw does not fall back to the native path. > > <details> > <summary>Suggested fix</summary> > > ```diff > const PvVsStorePrograms* GetPvVsStorePrograms(GraphicContext& graphics, > const PipelineCache::GraphicsPrograms& programs) { > if (!PvVsStoreEnabled() || programs.VertexStageCount() != 1) return nullptr; > + if (graphics.GetPhysicalDeviceProperties().limits.maxPushConstantsSize < > + PvVsStorePushRangeBytes(ShaderRecompiler::IR::NativePushConstantSize, true)) { > + return nullptr; > + } > const auto key = std::pair {programs.vertex[0].id, programs.pixel.id}; > ``` > > </details> > > <!-- cr-comment:v1:d4591b0303518c69f5e8d7e6 --> > > </blockquote></details> --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> - **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `7f007654-4c63-40cc-9a68-53a095ac4375` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 990c1754919ef8aaa6acbab752be16fbb02e4e39 and 29655ac0ed289087d92537ffd25ba3f22a8cb396. </details> <details> <summary>📒 Files selected for processing: 5</summary> * `src/graphics/host_gpu/renderer/perVertexVsStore.h` * `src/graphics/host_gpu/renderer/render.h` * `src/graphics/host_gpu/renderer/renderDraw.cpp` * `tests/PerVertexVsStoreMutants.cmake` * `tests/PerVertexVsStoreTests.cpp` </details> <details> <summary>🚧 Files skipped from review as they are similar to previous changes: 3</summary> * src/graphics/host_gpu/renderer/render.h * src/graphics/host_gpu/renderer/renderDraw.cpp * src/graphics/host_gpu/renderer/perVertexVsStore.h </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 3 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=74ef83cd-f63e-4483-afbc-a0e0d91b9863 attempt=7555e1cd-a0b0-4fda-b5cd-aa0188d10d77 batch=1/1 -->

Pull request closed

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