Skip to content

perf(shader): span single-wave wave64 compute by default after a uniformity check - #7922

Merged
oneandonlydean merged 6 commits into
boykopovar:mainfrom
ThatsLeo:feat/shader-spanned-uniformity
Nov 2, 2026
Merged

oneandonlydean merged 6 commits into
boykopovar:mainfrom
ThatsLeo:feat/shader-spanned-uniformity

Conversation

@ThatsLeo

@ThatsLeo ThatsLeo commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

What

#5405 runs a single-wave wave64 compute program at one guest lane per invocation, across two full 32-lane host subgroups. It is off unless APS5_SPANNED_WAVE is set, because its cross-lane exchanges use workgroup barriers, and the emitter could not tell whether every invocation reaches them: its debt entry lists a manual spirv-dis scan as the only check. This PR adds that check and turns the layout on by default.

  • SpannedBarrierInDivergentFlow (SpirvSpannedUniformity.cpp) runs on every spanned module after emission. It marks the values that can differ between the invocations of a wave, iterating until nothing changes:

    • lane and subgroup IDs (LocalInvocationId/Index, GlobalInvocationId, SubgroupId, SubgroupLocalInvocationId, the subgroup masks);
    • atomic and subgroup-operation results, and function parameters;
    • loads of private or function variables stored in per-invocation control flow;
    • loads at a uniform address of memory the program writes, unless it is workgroup memory that a barrier fences on every path since the last write. Storage buffers, uniform buffers and device addresses all reach guest memory, so a write through any of them counts for all three;
    • image reads, when the program writes an image;
    • phis inside, or at the merge of, a construct such a value decides;
    • anything computed from these.

    A selection is divergent when its condition is marked. A loop is divergent when its header condition is marked, or when it can be left from per-invocation control flow. The construct's blocks are read off the dominator tree: the header's subtree minus the merge's. A construct is also divergent when a per-invocation branch without a merge instruction leaves it or continues its loop. When a divergent construct returns or kills, everything reachable from its merge is divergent; when it branches past its merge, as a continue does, the merge's subtree is.

  • If an OpControlBarrier, or a call that reaches one, sits in a divergent construct, Emit throws SpannedWaveUnsupported. Recompile already catches that and emits the program at two lanes per invocation, so a rejected program runs as on main. The check runs before SpirvEmitInfo::fullSubgroups is set, so the fallback is not created with REQUIRE_FULL_SUBGROUPS.

  • VulkanDevice turns spanning on wherever it was available under the switch (computeFullSubgroups with 32-lane compute subgroups). APS5_NO_SPANNED_WAVE turns it off; APS5_SPANNED_WAVE is gone.

  • The analysis runs until nothing changes, so it cannot stop early and throw. It is skipped for a module with no OpControlBarrier, and each function's flow graph is built once.

  • Opcode, Result and VisitIdOperands move unchanged from SpirvSpecialization.cpp to SpirvInstructionOperands.hpp, templated on the instruction container, so both passes share the operand table. SpirvSpecialization.cpp keeps main's arena-backed Instruction.

  • Guarded SRT reads. A spanned wave does not stop an invocation after a fault (bdaStopsInvocations is false), so each later guarded read of a poisoned pointer wrote its record over the first. agc_driver_guarded_null_pointer then reported the second dword of an s_load_dwordx2 (address=0x4). Where invocations do not stop, the record is now written with a compare-exchange against 0, as record_bda_fault already does, so the first fault is kept. Programs whose invocations stop keep the atomic store.

  • The debt entry states what the check proves and what it does not: writes by other dispatches or queues, and the unexplained one-barrier ballot loss. spanned_uniformity_tests links libc on MinGW, as spirv_validator_exit_tests does.

Tested

Intel Arc (Meteor Lake), Mesa 26.2.4 ANV, Fedora 44, Linux 7.2.10, GCC 16.2.1, Release.

  • spanned_uniformity (new) builds twenty-one modules by hand:

    • rejected: a barrier under a lane comparison; a barrier in a loop a lane value leaves; a call reaching a barrier under a lane comparison; a barrier after a per-lane return; a barrier after a per-lane continue, with or without a selection merge; a barrier under a buffer word read after a store through a device address; a barrier under a phi joining a per-lane selection; a barrier under a variable stored on one side of a per-lane selection; a barrier under an atomic result; a barrier under a workgroup word read at a lane index; a barrier under a workgroup word read after a store with no barrier between, or with a store on one path past the barrier;
    • kept: the same barriers under a constant comparison, after a uniform return or a uniform unmerged continue, under a buffer word the program never writes, in a uniform loop after a per-lane selection, under a workgroup word read at a uniform index, and under one read after a store and a barrier.

    With LocalInvocationIndex removed from the per-invocation built-ins, the lane-dependent cases fail. Without the fence, early-exit, guest-memory and unmerged-continue rules, the cases they cover fail.

  • Stray's compute requests: all 1,751 (PPSA02101) replayed through agc_shader_replay with a 32-lane target and spanning on, using a local switch that is not part of this PR. 1,117 programs span, the same with the guest-memory and unmerged-continue rules. The fence rule sends 13 programs back to two lanes per invocation that spanned without it (1,130). Stray's heaviest programs, 0x2011300000 and 0x200e390000, still span. A Python prototype of the first analysis agreed with it.

  • ctest on main 3bb15be09 + this PR:

  • Stray, frames 20 to 50 of the boot (APS5_TRACE_FRAMES=20:30, 3840x2160).

GPU busy per present (ms) frame p50 (ms)
main + #7811 308.9 / 313.0 / 288.3 (mean 303.4) 451.2 / 464.2 / 432.6 (mean 449.3)
this PR + #7811 180.7 / 165.1 / 173.5 (mean 173.1) 334.9 / 324.6 / 335.0 (mean 331.5)

trace_digest.py, first capture of each:

main: frames 20:30 from present 20: 30 presents, frame p50 451.2 / p90 472.1 / p99 586.3 / max 586.3 ms, GPU busy 308.9 ms per present
PR:   frames 20:30 from present 20: 30 presents, frame p50 334.9 / p90 347.4 / p99 418.7 / max 418.7 ms, GPU busy 180.7 ms per present

aps5-summary.jsonl lines, main + #7811:

{"commit":"4b4d52f7d953","dirty":false,"env":{"APS5_PLAYGO_UNLISTED_CHUNKS":"absent","APS5_TRACE_FRAMES":"20:30"},"gpu":"Intel(R) Arc(tm) Graphics (MTL)","driver":"Intel open-source Mesa driver Mesa 26.2.4","os":"Linux 7.2.10-200.fc44.x86_64","resolution":"3840x2160","window":{"spec":"frames 20:30","first_present":20,"ms":13716.468},"presents":30,"frame_ms":{"p50":451.183,"p90":472.083,"p99":586.282,"max":586.282},"gpu_busy_ms_per_present":308.934,"worker_busy_pct":{"queue worker 0x0":96.582,"queue worker 0x20":97.047},"top_phases_ms_per_frame":{"Driver.Packet":882.201,"Driver.Packet.memory_wait":418.127,"Driver.Packet.device_lock":208.359,"Driver.Packet.prepare_memory":138.870,"Graphics.Draw":127.060,"Graphics.Draw.draw_and_resource_release":126.577,"Recorder.Submit":114.858,"Driver.Packet.dispatch":68.164},"trace_dropped":false,"trace":"aps5-trace-4b4d52f7d953-938192.json.gz"}
{"commit":"4b4d52f7d953","dirty":false,"env":{"APS5_PLAYGO_UNLISTED_CHUNKS":"absent","APS5_TRACE_FRAMES":"20:30"},"gpu":"Intel(R) Arc(tm) Graphics (MTL)","driver":"Intel open-source Mesa driver Mesa 26.2.4","os":"Linux 7.2.10-200.fc44.x86_64","resolution":"3840x2160","window":{"spec":"frames 20:30","first_present":20,"ms":13995.080},"presents":30,"frame_ms":{"p50":464.151,"p90":479.730,"p99":509.222,"max":509.222},"gpu_busy_ms_per_present":312.990,"worker_busy_pct":{"queue worker 0x0":96.781,"queue worker 0x20":96.913},"top_phases_ms_per_frame":{"Driver.Packet":900.975,"Driver.Packet.memory_wait":428.313,"Driver.Packet.device_lock":205.633,"Driver.Packet.prepare_memory":148.125,"Graphics.Draw":128.606,"Graphics.Draw.draw_and_resource_release":128.151,"Recorder.Submit":107.255,"Driver.Packet.dispatch":72.186},"trace_dropped":false,"trace":"aps5-trace-4b4d52f7d953-940261.json.gz"}
{"commit":"4b4d52f7d953","dirty":false,"env":{"APS5_PLAYGO_UNLISTED_CHUNKS":"absent","APS5_TRACE_FRAMES":"20:30"},"gpu":"Intel(R) Arc(tm) Graphics (MTL)","driver":"Intel open-source Mesa driver Mesa 26.2.4","os":"Linux 7.2.10-200.fc44.x86_64","resolution":"3840x2160","window":{"spec":"frames 20:30","first_present":20,"ms":13088.121},"presents":30,"frame_ms":{"p50":432.628,"p90":450.240,"p99":530.799,"max":530.799},"gpu_busy_ms_per_present":288.316,"worker_busy_pct":{"queue worker 0x0":96.056,"queue worker 0x20":96.773},"top_phases_ms_per_frame":{"Driver.Packet":837.222,"Driver.Packet.memory_wait":395.185,"Driver.Packet.device_lock":213.902,"Graphics.Draw":129.895,"Graphics.Draw.draw_and_resource_release":129.422,"Recorder.Submit":114.352,"Driver.Packet.prepare_memory":110.092,"Driver.Packet.dispatch":71.040},"trace_dropped":false,"trace":"aps5-trace-4b4d52f7d953-942091.json.gz"}

This PR + #7811:

{"commit":"128b8c1f83c0","dirty":false,"env":{"APS5_PLAYGO_UNLISTED_CHUNKS":"absent","APS5_TRACE_FRAMES":"20:30"},"gpu":"Intel(R) Arc(tm) Graphics (MTL)","driver":"Intel open-source Mesa driver Mesa 26.2.4","os":"Linux 7.2.10-200.fc44.x86_64","resolution":"3840x2160","window":{"spec":"frames 20:30","first_present":20,"ms":10177.000},"presents":30,"frame_ms":{"p50":334.856,"p90":347.438,"p99":418.694,"max":418.694},"gpu_busy_ms_per_present":180.675,"worker_busy_pct":{"queue worker 0x0":95.362,"queue worker 0x20":96.360},"top_phases_ms_per_frame":{"Driver.Packet":646.122,"Driver.Packet.memory_wait":298.561,"Driver.Packet.device_lock":193.196,"Graphics.Draw":116.729,"Graphics.Draw.draw_and_resource_release":116.290,"Recorder.Submit":108.061,"Driver.Packet.dispatch":69.570,"Driver.Dispatch":64.534},"trace_dropped":false,"trace":"aps5-trace-128b8c1f83c0-939198.json.gz"}
{"commit":"128b8c1f83c0","dirty":false,"env":{"APS5_PLAYGO_UNLISTED_CHUNKS":"absent","APS5_TRACE_FRAMES":"20:30"},"gpu":"Intel(R) Arc(tm) Graphics (MTL)","driver":"Intel open-source Mesa driver Mesa 26.2.4","os":"Linux 7.2.10-200.fc44.x86_64","resolution":"3840x2160","window":{"spec":"frames 20:30","first_present":20,"ms":9748.101},"presents":30,"frame_ms":{"p50":324.600,"p90":332.281,"p99":340.520,"max":340.520},"gpu_busy_ms_per_present":165.056,"worker_busy_pct":{"queue worker 0x0":95.368,"queue worker 0x20":97.098},"top_phases_ms_per_frame":{"Driver.Packet":622.706,"Driver.Packet.memory_wait":285.025,"Driver.Packet.device_lock":182.915,"Graphics.Draw":113.762,"Graphics.Draw.draw_and_resource_release":113.340,"Recorder.Submit":97.834,"Driver.Packet.dispatch":72.730,"Driver.Dispatch":68.024},"trace_dropped":false,"trace":"aps5-trace-128b8c1f83c0-941263.json.gz"}
{"commit":"128b8c1f83c0","dirty":false,"env":{"APS5_PLAYGO_UNLISTED_CHUNKS":"absent","APS5_TRACE_FRAMES":"20:30"},"gpu":"Intel(R) Arc(tm) Graphics (MTL)","driver":"Intel open-source Mesa driver Mesa 26.2.4","os":"Linux 7.2.10-200.fc44.x86_64","resolution":"3840x2160","window":{"spec":"frames 20:30","first_present":20,"ms":10014.061},"presents":30,"frame_ms":{"p50":334.968,"p90":340.775,"p99":354.031,"max":354.031},"gpu_busy_ms_per_present":173.489,"worker_busy_pct":{"queue worker 0x0":95.324,"queue worker 0x20":96.938},"top_phases_ms_per_frame":{"Driver.Packet":639.070,"Driver.Packet.memory_wait":298.617,"Driver.Packet.device_lock":189.827,"Graphics.Draw":115.684,"Graphics.Draw.draw_and_resource_release":115.257,"Recorder.Submit":104.396,"Driver.Packet.dispatch":72.309,"Driver.Dispatch":68.740},"trace_dropped":false,"trace":"aps5-trace-128b8c1f83c0-943100.json.gz"}

Traces, digests and summaries: ThatsLeo:evidence/spanned-default.

The fence and early-exit rules on Stray. Same scene and machine, main 559f35d68 + this PR (without, then with, the second commit) + #8004 + #7811. One warm run each, then four interleaved rounds. After a battery drain this laptop idled at 56 °C, so every capture started below 58 °C, not 55.

GPU busy per present (ms) frame p50 (ms)
without the rules 111.5 / 113.9 / 117.5 / 116.3 (mean 114.8) 276.6 / 271.6 / 285.3 / 280.8 (mean 278.6)
with the rules 115.0 / 114.6 / 114.0 / 112.7 (mean 114.1) 268.9 / 279.8 / 272.2 / 278.3 (mean 274.8)

The difference is inside the spread.

without: frames 20:30 from present 20: 30 presents, frame p50 276.6 / p90 287.9 / p99 294.7 / max 294.7 ms, GPU busy 111.5 ms per present
with:    frames 20:30 from present 20: 30 presents, frame p50 268.9 / p90 282.2 / p99 285.1 / max 285.1 ms, GPU busy 115.0 ms per present
aps5-summary.jsonl lines
{"commit":"9667780a1567","dirty":false,"env":{"APS5_PLAYGO_UNLISTED_CHUNKS":"absent","APS5_TRACE_FRAMES":"20:30"},"gpu":"Intel(R) Arc(tm) Graphics (MTL)","driver":"Intel open-source Mesa driver Mesa 26.2.4","os":"Linux 7.2.10-200.fc44.x86_64","cpu":"Intel(R) Core(TM) Ultra 7 155H","cpu_threads":22,"memory_mib":15333,"title_id":"PPSA02101","title":"Stray","content_version":"01.002.000","resolution":"3840x2160","window":{"spec":"frames 20:30","first_present":20,"ms":8273.368},"presents":30,"frame_ms":{"p50":276.642,"p90":287.880,"p99":294.712,"max":294.712},"gpu_busy_ms_per_present":111.544,"worker_busy_pct":{"queue worker 0x0":97.191,"queue worker 0x20":97.311},"top_phases_ms_per_frame":{"Driver.Packet":532.809,"Driver.Packet.memory_wait":229.082,"Driver.Packet.device_lock":165.884,"Graphics.Draw":114.639,"Graphics.Draw.draw_and_resource_release":114.308,"Driver.Packet.dispatch":85.599,"Driver.Dispatch":59.489,"Recorder.Submit":48.015},"trace_dropped":false,"trace":"aps5-trace-9667780a1567-108138.json.gz"}
{"commit":"9667780a1567","dirty":false,"env":{"APS5_PLAYGO_UNLISTED_CHUNKS":"absent","APS5_TRACE_FRAMES":"20:30"},"gpu":"Intel(R) Arc(tm) Graphics (MTL)","driver":"Intel open-source Mesa driver Mesa 26.2.4","os":"Linux 7.2.10-200.fc44.x86_64","cpu":"Intel(R) Core(TM) Ultra 7 155H","cpu_threads":22,"memory_mib":15333,"title_id":"PPSA02101","title":"Stray","content_version":"01.002.000","resolution":"3840x2160","window":{"spec":"frames 20:30","first_present":20,"ms":8223.104},"presents":30,"frame_ms":{"p50":271.596,"p90":287.082,"p99":292.329,"max":292.329},"gpu_busy_ms_per_present":113.868,"worker_busy_pct":{"queue worker 0x0":97.306,"queue worker 0x20":96.759},"top_phases_ms_per_frame":{"Driver.Packet":529.169,"Driver.Packet.memory_wait":216.791,"Driver.Packet.device_lock":164.966,"Graphics.Draw":115.568,"Graphics.Draw.draw_and_resource_release":115.240,"Driver.Packet.dispatch":94.578,"Driver.Dispatch":63.130,"Vulkan.Dispatch":47.380},"trace_dropped":false,"trace":"aps5-trace-9667780a1567-113059.json.gz"}
{"commit":"9667780a1567","dirty":false,"env":{"APS5_PLAYGO_UNLISTED_CHUNKS":"absent","APS5_TRACE_FRAMES":"20:30"},"gpu":"Intel(R) Arc(tm) Graphics (MTL)","driver":"Intel open-source Mesa driver Mesa 26.2.4","os":"Linux 7.2.10-200.fc44.x86_64","cpu":"Intel(R) Core(TM) Ultra 7 155H","cpu_threads":22,"memory_mib":15333,"title_id":"PPSA02101","title":"Stray","content_version":"01.002.000","resolution":"3840x2160","window":{"spec":"frames 20:30","first_present":20,"ms":8561.265},"presents":30,"frame_ms":{"p50":285.252,"p90":299.190,"p99":305.800,"max":305.800},"gpu_busy_ms_per_present":117.525,"worker_busy_pct":{"queue worker 0x0":97.291,"queue worker 0x20":97.585},"top_phases_ms_per_frame":{"Driver.Packet":552.832,"Driver.Packet.memory_wait":224.121,"Driver.Packet.device_lock":164.165,"Graphics.Draw":115.802,"Graphics.Draw.draw_and_resource_release":115.458,"Driver.Packet.dispatch":109.259,"Driver.Dispatch":72.453,"Vulkan.Dispatch":47.232},"trace_dropped":false,"trace":"aps5-trace-9667780a1567-116244.json.gz"}
{"commit":"9667780a1567","dirty":false,"env":{"APS5_PLAYGO_UNLISTED_CHUNKS":"absent","APS5_TRACE_FRAMES":"20:30"},"gpu":"Intel(R) Arc(tm) Graphics (MTL)","driver":"Intel open-source Mesa driver Mesa 26.2.4","os":"Linux 7.2.10-200.fc44.x86_64","cpu":"Intel(R) Core(TM) Ultra 7 155H","cpu_threads":22,"memory_mib":15333,"title_id":"PPSA02101","title":"Stray","content_version":"01.002.000","resolution":"3840x2160","window":{"spec":"frames 20:30","first_present":20,"ms":8493.756},"presents":30,"frame_ms":{"p50":280.819,"p90":298.458,"p99":301.837,"max":301.837},"gpu_busy_ms_per_present":116.292,"worker_busy_pct":{"queue worker 0x0":97.613,"queue worker 0x20":97.336},"top_phases_ms_per_frame":{"Driver.Packet":549.554,"Driver.Packet.memory_wait":230.652,"Driver.Packet.device_lock":163.134,"Graphics.Draw":115.009,"Graphics.Draw.draw_and_resource_release":114.660,"Driver.Packet.dispatch":100.944,"Driver.Dispatch":72.601,"Recorder.Submit":49.593},"trace_dropped":false,"trace":"aps5-trace-9667780a1567-119633.json.gz"}
{"commit":"219315aabfb1","dirty":false,"env":{"APS5_PLAYGO_UNLISTED_CHUNKS":"absent","APS5_TRACE_FRAMES":"20:30"},"gpu":"Intel(R) Arc(tm) Graphics (MTL)","driver":"Intel open-source Mesa driver Mesa 26.2.4","os":"Linux 7.2.10-200.fc44.x86_64","cpu":"Intel(R) Core(TM) Ultra 7 155H","cpu_threads":22,"memory_mib":15333,"title_id":"PPSA02101","title":"Stray","content_version":"01.002.000","resolution":"3840x2160","window":{"spec":"frames 20:30","first_present":20,"ms":8094.501},"presents":30,"frame_ms":{"p50":268.921,"p90":282.204,"p99":285.051,"max":285.051},"gpu_busy_ms_per_present":115.018,"worker_busy_pct":{"queue worker 0x0":97.361,"queue worker 0x20":96.984},"top_phases_ms_per_frame":{"Driver.Packet":522.612,"Driver.Packet.memory_wait":216.751,"Driver.Packet.device_lock":163.550,"Graphics.Draw":115.508,"Graphics.Draw.draw_and_resource_release":115.189,"Driver.Packet.dispatch":89.641,"Driver.Dispatch":54.537,"Recorder.Submit":47.263},"trace_dropped":false,"trace":"aps5-trace-219315aabfb1-110545.json.gz"}
{"commit":"219315aabfb1","dirty":false,"env":{"APS5_PLAYGO_UNLISTED_CHUNKS":"absent","APS5_TRACE_FRAMES":"20:30"},"gpu":"Intel(R) Arc(tm) Graphics (MTL)","driver":"Intel open-source Mesa driver Mesa 26.2.4","os":"Linux 7.2.10-200.fc44.x86_64","cpu":"Intel(R) Core(TM) Ultra 7 155H","cpu_threads":22,"memory_mib":15333,"title_id":"PPSA02101","title":"Stray","content_version":"01.002.000","resolution":"3840x2160","window":{"spec":"frames 20:30","first_present":20,"ms":8388.481},"presents":30,"frame_ms":{"p50":279.752,"p90":289.914,"p99":307.567,"max":307.567},"gpu_busy_ms_per_present":114.558,"worker_busy_pct":{"queue worker 0x0":97.228,"queue worker 0x20":97.175},"top_phases_ms_per_frame":{"Driver.Packet":541.081,"Driver.Packet.memory_wait":229.579,"Driver.Packet.device_lock":164.570,"Graphics.Draw":115.558,"Graphics.Draw.draw_and_resource_release":115.217,"Driver.Packet.dispatch":97.113,"Driver.Dispatch":67.063,"Recorder.Submit":47.239},"trace_dropped":false,"trace":"aps5-trace-219315aabfb1-114700.json.gz"}
{"commit":"219315aabfb1","dirty":false,"env":{"APS5_PLAYGO_UNLISTED_CHUNKS":"absent","APS5_TRACE_FRAMES":"20:30"},"gpu":"Intel(R) Arc(tm) Graphics (MTL)","driver":"Intel open-source Mesa driver Mesa 26.2.4","os":"Linux 7.2.10-200.fc44.x86_64","cpu":"Intel(R) Core(TM) Ultra 7 155H","cpu_threads":22,"memory_mib":15333,"title_id":"PPSA02101","title":"Stray","content_version":"01.002.000","resolution":"3840x2160","window":{"spec":"frames 20:30","first_present":20,"ms":8163.070},"presents":30,"frame_ms":{"p50":272.213,"p90":284.784,"p99":291.836,"max":291.836},"gpu_busy_ms_per_present":114.038,"worker_busy_pct":{"queue worker 0x0":97.290,"queue worker 0x20":96.736},"top_phases_ms_per_frame":{"Driver.Packet":524.954,"Driver.Packet.memory_wait":218.094,"Driver.Packet.device_lock":160.249,"Graphics.Draw":114.762,"Graphics.Draw.draw_and_resource_release":114.432,"Driver.Packet.dispatch":88.844,"Driver.Dispatch":56.043,"Recorder.Submit":46.681},"trace_dropped":false,"trace":"aps5-trace-219315aabfb1-117978.json.gz"}
{"commit":"219315aabfb1","dirty":false,"env":{"APS5_PLAYGO_UNLISTED_CHUNKS":"absent","APS5_TRACE_FRAMES":"20:30"},"gpu":"Intel(R) Arc(tm) Graphics (MTL)","driver":"Intel open-source Mesa driver Mesa 26.2.4","os":"Linux 7.2.10-200.fc44.x86_64","cpu":"Intel(R) Core(TM) Ultra 7 155H","cpu_threads":22,"memory_mib":15333,"title_id":"PPSA02101","title":"Stray","content_version":"01.002.000","resolution":"3840x2160","window":{"spec":"frames 20:30","first_present":20,"ms":8315.173},"presents":30,"frame_ms":{"p50":278.251,"p90":288.303,"p99":290.344,"max":290.344},"gpu_busy_ms_per_present":112.656,"worker_busy_pct":{"queue worker 0x0":97.424,"queue worker 0x20":97.292},"top_phases_ms_per_frame":{"Driver.Packet":532.199,"Driver.Packet.memory_wait":217.928,"Driver.Packet.device_lock":162.971,"Graphics.Draw":116.778,"Graphics.Draw.draw_and_resource_release":116.362,"Driver.Packet.dispatch":101.673,"Driver.Dispatch":67.305,"Recorder.Submit":48.184},"trace_dropped":false,"trace":"aps5-trace-219315aabfb1-120956.json.gz"}

Traces, digests and summaries: ThatsLeo:evidence/spanned-fence.

Runs by others, on earlier heads:

Not tested:

  • A title with wave64 compute on AMD; the AMD runs above are the GPU tests only.
  • Other titles than Stray on the Arc.

Checklist

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

@github-actions github-actions Bot added perf Performance change perf numbers missing perf pull request without a before and after summary line labels Oct 19, 2026
@github-actions

Copy link
Copy Markdown

This pull request is labeled perf, so it needs the summary line of a capture on main and one with the change, from the same title, scene and machine, as the Performance report form asks. Please paste both aps5-summary.jsonl lines, attach the two traces and add the output of tools/trace_digest.py.

@github-actions

github-actions Bot commented Oct 19, 2026 •

Copy link
Copy Markdown

Other open pull requests touch the same code. Merging one will break the other, or both implement the same thing. If this one builds on them, list them in Depends on.

Pull request Conflicting files (lines on main) Same exports Same new files
PR 6416 core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvMemoryInstructions.cpp L1571
PR 12764 core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp L336

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

Pull request Shared files not compared
PR 1395 core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp
PR 1896 docs/dev/ENVIRONMENT.md
PR 2434 core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp
PR 4040 core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp
PR 4472 core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp
docs/dev/ENVIRONMENT.md
PR 5021 core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp
core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp
core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvMemoryInstructions.cpp
docs/dev/debt/shader.md
PR 5371 docs/dev/debt/shader.md
PR 5925 core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp
core/shader/recompiler/CMakeLists.txt
PR 6186 docs/dev/ENVIRONMENT.md
PR 6188 core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp
PR 6235 docs/dev/debt/shader.md
PR 6280 docs/dev/debt/shader.md
PR 6412 docs/dev/debt/shader.md
PR 6488 core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp
docs/dev/debt/shader.md
PR 6501 docs/dev/ENVIRONMENT.md
PR 6751 core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp
PR 6924 docs/dev/ENVIRONMENT.md
docs/dev/debt/shader.md
PR 7085 docs/dev/debt/shader.md
PR 7223 docs/dev/debt/shader.md
PR 7275 core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp
PR 7369 core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp
PR 7392 core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp
docs/dev/debt/shader.md
PR 7410 docs/dev/debt/shader.md
PR 7449 core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp
docs/dev/ENVIRONMENT.md
PR 7457 docs/dev/ENVIRONMENT.md
PR 7464 core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp
PR 7514 docs/dev/ENVIRONMENT.md
PR 7604 docs/dev/ENVIRONMENT.md
PR 7642 core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp
core/shader/recompiler/CMakeLists.txt
core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp
core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvMemoryInstructions.cpp
docs/dev/ENVIRONMENT.md
PR 7684 docs/dev/debt/shader.md
PR 8212 core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp
PR 8246 docs/dev/ENVIRONMENT.md
PR 8484 docs/dev/ENVIRONMENT.md
PR 9012 docs/dev/ENVIRONMENT.md
PR 9020 docs/dev/debt/shader.md
PR 9248 docs/dev/ENVIRONMENT.md
PR 9289 core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp
docs/dev/ENVIRONMENT.md
PR 9335 docs/dev/debt/shader.md
PR 9345 docs/dev/ENVIRONMENT.md
PR 9356 core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp
core/shader/recompiler/CMakeLists.txt
core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp
docs/dev/ENVIRONMENT.md
PR 9387 core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp
core/shader/recompiler/CMakeLists.txt
core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp
docs/dev/ENVIRONMENT.md
docs/dev/debt/shader.md
PR 9489 core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp
PR 9508 core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp
core/shader/recompiler/CMakeLists.txt
core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp
core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvMemoryInstructions.cpp
docs/dev/ENVIRONMENT.md
PR 9712 docs/dev/ENVIRONMENT.md
PR 9748 docs/dev/debt/shader.md
PR 9852 docs/dev/ENVIRONMENT.md
PR 9875 core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp
docs/dev/ENVIRONMENT.md
PR 9891 core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp
PR 9898 core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp
docs/dev/ENVIRONMENT.md
PR 10000 docs/dev/debt/shader.md
PR 10043 core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp
docs/dev/ENVIRONMENT.md
PR 10069 core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp
docs/dev/ENVIRONMENT.md
PR 10193 core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp
core/shader/recompiler/CMakeLists.txt
core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp
core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvMemoryInstructions.cpp
docs/dev/ENVIRONMENT.md
PR 10233 docs/dev/debt/shader.md
PR 10442 core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp
docs/dev/ENVIRONMENT.md
PR 10489 docs/dev/debt/shader.md
PR 10556 docs/dev/debt/shader.md
PR 10757 docs/dev/ENVIRONMENT.md
PR 10846 core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp
core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp
core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvMemoryInstructions.cpp
docs/dev/ENVIRONMENT.md
docs/dev/debt/shader.md
PR 10867 core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp
core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp
docs/dev/debt/shader.md
PR 10894 docs/dev/ENVIRONMENT.md
PR 11351 core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp
core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp
docs/dev/ENVIRONMENT.md
PR 11483 core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp
core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp
docs/dev/debt/shader.md
PR 12120 core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp
docs/dev/ENVIRONMENT.md
PR 12323 docs/dev/ENVIRONMENT.md
PR 12324 core/shader/recompiler/CMakeLists.txt
docs/dev/ENVIRONMENT.md
PR 12544 docs/dev/ENVIRONMENT.md
PR 12548 core/shader/recompiler/CMakeLists.txt
docs/dev/debt/shader.md
PR 12568 core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp
docs/dev/ENVIRONMENT.md
PR 12746 docs/dev/ENVIRONMENT.md
PR 12790 docs/dev/debt/shader.md
PR 12828 core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp
core/shader/recompiler/CMakeLists.txt
PR 12840 core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp
docs/dev/ENVIRONMENT.md
PR 12863 docs/dev/ENVIRONMENT.md
PR 12921 docs/dev/ENVIRONMENT.md
PR 12944 core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp
core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp
core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvMemoryInstructions.cpp
docs/dev/debt/shader.md
PR 12970 docs/dev/ENVIRONMENT.md
PR 13148 core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp
PR 13707 docs/dev/ENVIRONMENT.md
PR 13793 docs/dev/ENVIRONMENT.md
PR 13809 docs/dev/ENVIRONMENT.md
PR 13858 docs/dev/ENVIRONMENT.md
PR 13863 core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp
docs/dev/ENVIRONMENT.md
PR 13920 core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp
docs/dev/ENVIRONMENT.md
PR 13928 core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp
core/shader/recompiler/CMakeLists.txt
core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp
core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvMemoryInstructions.cpp
docs/dev/ENVIRONMENT.md
PR 13929 core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp
core/shader/recompiler/CMakeLists.txt
core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp
core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvMemoryInstructions.cpp
docs/dev/ENVIRONMENT.md
PR 14212 docs/dev/debt/shader.md
PR 14262 docs/dev/ENVIRONMENT.md
PR 14264 docs/dev/ENVIRONMENT.md
PR 14299 docs/dev/ENVIRONMENT.md
PR 14344 core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp
docs/dev/ENVIRONMENT.md
PR 14692 docs/dev/debt/shader.md
PR 14853 docs/dev/debt/shader.md
PR 14871 core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp
docs/dev/debt/shader.md
PR 14943 core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp
docs/dev/ENVIRONMENT.md

@github-actions github-actions Bot added needs rebase Conflicts with main, rebase needed build shader core/shader docs agc libSceAgc* and removed perf numbers missing perf pull request without a before and after summary line labels Oct 19, 2026
@ThatsLeo
ThatsLeo force-pushed the feat/shader-spanned-uniformity branch from 7ae9e88 to 2e78528 Compare October 19, 2026 17:11
@github-actions github-actions Bot removed the needs rebase Conflicts with main, rebase needed label Oct 19, 2026
@ThatsLeo
ThatsLeo force-pushed the feat/shader-spanned-uniformity branch from 2e78528 to 753bb56 Compare October 19, 2026 17:30

@CnRJay CnRJay left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The Stray numbers are strong (GPU busy per present 303.4 to 173.1 ms, frame p50 449.3 to 331.5 ms, three interleaved rounds, spread small next to the gain), and the fallback to two lanes per invocation when the check rejects is the right shape. Turning this on by default for every device with 32-lane compute subgroups is where I don't agree yet.

  • Everything measured is one Intel Arc (Meteor Lake) on ANV. "Wherever it was available under the switch" means NVIDIA and RDNA wave32 parts get a different compute layout for 1,130 of Stray's 1,751 programs without a run on either. Barrier-in-divergent-flow on a vendor that implements OpControlBarrier differently is a hang or VK_ERROR_DEVICE_LOST, not a wrong picture. Please post spanned_uniformity plus the Stray (or any wave64-compute title) pair on an NVIDIA card and a Radeon, or keep the default off for vendors that haven't been run.
  • The description says the check treats a load from workgroup, storage or uniform memory at a uniform address as uniform, "not proven for memory another invocation writes without a barrier in between", and that a one-barrier ballot loss is unexplained. That is a known hole in the analysis that decides whether the program can hang, and it is being made the default path. Either close it (treat such a load as divergent unless a barrier dominates it, and see what fraction of the 1,130 still spans), or state the programs it affects and keep the switch default-off until the ballot loss is explained.
  • The replay of 1,751 requests ran with a local switch that isn't in the PR, and found 0 rejections. A check that never rejects on its real corpus only shows the false-positive rate; the rejected cases are the hand-built eleven modules. It would help to have at least one real program from the corpus where the barrier sits under a divergent construct, to show the check reaches it on real SPIR-V.
  • APS5_SPANNED_WAVE is removed and APS5_NO_SPANNED_WAVE added. Is the spanning decision part of the shader disk cache key and the pipeline journal key? A cache written under the old switch must not serve a two-lane module to a spanned layout (or the other way round) after this default flips.
  • 858 added lines moving Opcode, Result and VisitIdOperands between files alongside the new pass. Splitting the move out of the behavior change would make the pass reviewable.

@github-actions github-actions Bot added the needs rebase Conflicts with main, rebase needed label Oct 19, 2026
@oneandonlydean oneandonlydean self-assigned this Oct 20, 2026
@blawesom

Copy link
Copy Markdown
Contributor

This PR looks strictly contained in #8004: its single commit 753bb56e3 ("span single-wave wave64 compute by default after a uniformity check") is exactly the first commit of #8004's branch, which carries one more on top (2276a44aa, "let spanned waves run at any host subgroup size where it can be narrower than 32"). Both are from the same series opened ~3 hours apart.

If the intent was one review thread, closing this in favour of #8004 would keep a single place for the maintainers to look — #8004 also has a verified rebase handoff onto current main (including main's WordArena infrastructure kept, the VisitIdOperands alias restored, and main's five InsertMeshBarycentricFlag sites preserved across your version-bump rewrites).

@hamb3r

hamb3r commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Tested enabling spannedWaves (state->spannedWaves = state->computeFullSubgroups) on Windows 10 / NVIDIA GeForce RTX 3080 (driver 595.71, hostSubgroupSize = 32) with Demon's Souls (PPSA01341 01.007.000), which dispatches dozens of heavy single-wave wave64 compute shaders (workgroupSize <= 64, >213,000 compute dispatches across boot, intro, and title screen):

  • No VK_ERROR_DEVICE_LOST or hangs on NVIDIA across cold-cache and warm-cache runs.
  • Avoiding the laneCount = 2 unroll on single-wave wave64 compute shaders (0x1ee14f3c0, 0x1eeb34840, etc.) cuts the specialized SPIR-V word count and vkCreateComputePipelines compile time in nvgpucomp64.dll nearly in half.

Also reviewed SpirvSpannedUniformity.cpp and noticed four technical points worth addressing when rebasing onto main:

  1. Early exits (OpReturn / break / continue) inside a divergent OpSelectionMerge (Construct, L215–227):
    Construct(flow, header, merge) stops at if (node == merge) continue;. If a branch inside a per-lane OpSelectionMerge exits early via OpReturn (or jumps to an enclosing loop's merge/continue block instead of merge), only a subset of lanes reaches merge. Any OpControlBarrier placed in merge (or dominated by merge after an early return) executes under a divergent active lane mask, but inDivergentFlow will currently be false for merge.
  2. Analysis::Run() throws std::runtime_error instead of falling back (L148):
    If the 64-round cap is hit on a deep loop-carried OpStore/OpLoad chain, Run() throws std::runtime_error("spanned wave uniformity did not settle") instead of returning a rejection reason for SpannedWaveUnsupported, which aborts shader compilation rather than falling back to unspanned wave64 (laneCount = 2).
  3. Fast-path when a module has no OpControlBarrier:
    In SpannedBarrierInDivergentFlow(words) / Analysis::Run(), if the module contains no OpControlBarrier instructions (barriers.empty()), Parse(words) and Run() still allocate a std::vector<std::uint32_t> per instruction and run the fixed-point dataflow loop. Scanning words for spv::OpControlBarrier before Parse(words) (and checking if (barriers.empty()) return std::nullopt;) avoids ~100k heap allocations on large 500k–850k word compute shaders that have no workgroup barriers.
  4. BuildFlow(function) inside Visit(function) (L238):
    BuildFlow(function) rebuilds the CFG postorder and dominator tree on every iteration of the round loop in Run(), even though the CFG is static. Precomputing Flow once per function avoids repeating dominator intersection on large shaders.

@ThatsLeo
ThatsLeo force-pushed the feat/shader-spanned-uniformity branch from 753bb56 to 4d84eb2 Compare October 20, 2026 23:44
@ThatsLeo

Copy link
Copy Markdown
Contributor Author

Rebased onto main 559f35d68, with two more commits. The description is updated.

@CnRJay, on your two points:

  • The analysis gap is closed rather than documented. A load at a uniform address is now uniform only from memory the program never writes, or from workgroup memory that a barrier fences on every path since the last write. Image reads count as per-invocation when the program writes an image. Of Stray's 1,130 spanning programs, 1,117 still span, and the heaviest ones are among them. The 13 others fall back to two lanes per invocation. Four interleaved Stray rounds with and without the rule are inside each other's spread (GPU 114.1 against 114.8 ms per present, frame p50 274.8 against 278.6 ms).

  • Other vendors. I first restricted the default to Mesa's Intel driver. Then the runs here and on perf(shader): let spanned waves run at any host subgroup size where it can be narrower than 32 #8004 came in:

    • @hamb3r: Demon's Souls on NVIDIA, with no device loss or hang;
    • @wachi35676: the GPU tests on NVIDIA and a Radeon, with no new failures;
    • @CPritch: GTA V on NVIDIA, frame p50 −6%.

    So I left it on wherever 32-lane full subgroups exist, with APS5_NO_SPANNED_WAVE as the switch. If you'd still rather gate AMD until someone runs a title there, it's a one-line change.

The one-barrier ballot loss from #5405 is still unexplained, and the debt entry says so.

@hamb3r, thanks for the run and the review:

  1. Early exits. You were right. A divergent construct that returns or kills now makes everything reachable from its merge divergent, and one that branches past its merge, as a continue does, makes the merge's subtree divergent. The tests cover a per-lane return and a per-lane continue (both rejected) and a uniform return (kept). The return case passed the old check.
  2. The analysis no longer has a round cap. The marked sets only grow, so it always settles.
  3. A module with no OpControlBarrier is skipped before it is parsed.
  4. Each function's flow graph is built once per module.

The rebase also showed that main's new agc_driver_guarded_null_pointer failed with spanning on. A spanned wave doesn't stop an invocation after a fault, so the second dword of a poisoned s_load_dwordx2 overwrote the first record. Where invocations don't stop, the record is now written only while the guard word is 0, as record_bda_fault already does.

@blawesom, thanks. I'd keep #7922 open because @CnRJay's review and the assignment are here. #8004 lists it under Depends on, and reviewing #8004 covers both.

AI-assisted: yes

@oneandonlydean

Copy link
Copy Markdown
Collaborator

@ThatsLeo Thanks for closing the analysis gap. I read SpirvSpannedUniformity.cpp against the emitter at 4d84eb2 and ran the analysis standalone with your test builder. Your seventeen cases pass, and mutants that drop LocalInvocationIndex, the fence reset or the early-exit rule each fail them. One gap needs a fix before this can be on by default, and two smaller points:

  1. Guest memory written through one storage class and read through another. Written and Racy only ask whether the load's own class is written. But guest memory is reached through both StorageBuffer descriptors and BDA PhysicalStorageBuffer pointers (SpirvRuntimeBuffer.cpp emits both forms for the same buffer atomic). So a program that stores only through a BDA pointer and loads at a uniform address through a buffer descriptor gets that load counted as uniform. Inside one spanned wave, the two host subgroups can then read different values, which is the hazard the rule exists for. A minimal module (uniform StorageBuffer load, OpIEqual, barrier inside the selection, plus one OpStore through an OpConvertUToPtr PSB pointer) is kept today. With the store going to the StorageBuffer instead, it's rejected. Could you treat the guest-memory classes as one class in Written, add that case as a rejected test, and post the new span count for PPSA02101?
  2. A per-lane continue without a selection merge. The loop rule only looks at branches to the loop's merge block, and selections are only found through OpSelectionMerge. So OpBranchConditional %lane %continue %rest in a non-header block (valid structured SPIR-V; SpirvFlowEmitter emits no merge when the terminator has none) leaves a barrier in %rest unflagged. If the emitter can never produce that with a per-invocation condition, a sentence saying why is enough. Otherwise, treating a non-uniform conditional branch to the continue target like a per-lane break would close it.
  3. The registration re-emit in Recompile runs after the SpannedWaveUnsupported catch and still spans. The check then runs on a different module, and a rejection there fails the compile instead of falling back. Wrapping it the same way, or re-emitting with spanning off, avoids that.

The rest looks right to me: the fallback doesn't set REQUIRE_FULL_SUBGROUPS, the operand table move is mechanical, and the first-fault compare-exchange is sound because the host zeroes the guard word.

@github-actions github-actions Bot removed the needs rebase Conflicts with main, rebase needed label Oct 21, 2026
@ThatsLeo
ThatsLeo force-pushed the feat/shader-spanned-uniformity branch from 4d84eb2 to 8d4f486 Compare October 21, 2026 00:13
@ThatsLeo

Copy link
Copy Markdown
Contributor Author

@oneandonlydean Thanks, all three are addressed. Both PRs are rebased onto main eda7477ac.

  1. Guest memory as one class. Uniform, StorageBuffer and PhysicalStorageBuffer now count as one class for both writes and loads. Your case is a rejected test: a uniform StorageBuffer load, a barrier under it, and one store through an OpConvertUToPtr pointer. Next to it, a kept test reads the same buffer with no store anywhere. PPSA02101 still has 1,117 spanned programs, including 0x2011300000 and 0x200e390000. The check only accepts or rejects modules, so the spanned modules are byte-identical to the previous push and the Stray A/B in the description still applies.
  2. Unmerged per-lane continue. The emitter can produce one: SpirvFlowEmitter emits OpBranchConditional with no merge whenever the IR terminator has none. A construct is now divergent when a block inside it ends in a per-invocation OpBranchConditional or OpSwitch without a merge instruction and targets the construct's merge or, for a loop, its continue target. The per-lane version of your example is rejected and the uniform one is kept. Before this commit the per-lane one was kept.
  3. The registration re-emit can't span. registration is only true for vertex and fragment stages (Recompiler.cpp:584), and SpirvEmitter.cpp sets spannedWave only for compute. The second emit therefore never carries a spanned module, so the check never runs there.

Tests on the new heads:

  • Arc: 1742 of 1748 pass. The six failures also fail on main.
  • lavapipe: 1746 of 1748 pass. Only the two application_heap tests fail.
  • Validation layer: the 54 focused tests, including agc_driver_guarded_null_pointer, show no VUID- error.

AI-assisted: yes

@thuanquang

Copy link
Copy Markdown
Contributor

A discrete RDNA 2 run with spanning on by default: RX 6700 XT (gfx1031), AMD's Windows driver 32.0.21045.5002, Windows 11 26200, MinGW GCC 15.2.0, Release. It compares main a07e985c8 with main merged with this head, 8d4f48671 (the merge is clean).

Not run: the Khronos validation layer, other AMD drivers, and titles.

@oneandonlydean

Copy link
Copy Markdown
Collaborator

@ThatsLeo a discrete RDNA 2 data point from @thuanquang: with spanning on by default on AMD's Windows driver, the device log confirms spanning is active, and main and this PR both pass 868 of 870 on the agc/shader/subgroup set, missing the same two known tests. Thanks @thuanquang.

@github-actions github-actions Bot added the needs rebase Conflicts with main, rebase needed label Oct 21, 2026
@ThatsLeo
ThatsLeo force-pushed the feat/shader-spanned-uniformity branch from 8d4f486 to 5cce035 Compare October 22, 2026 09:20
@wachi35676

Copy link
Copy Markdown
Contributor

Data from three homebrew titles whose own GPU fence waits give up (RADV's radv/ps5: the GPU has not reached submission N in 10 s, or the FSR4 Showcase's 4.5 s wait, then -4) while AnyPS5 builds a very large wave64 compute pipeline at the first dispatch. Spanning halves those programs. Windows 11, Ryzen 5 9600X, RTX 5070 Ti (driver 621.01), WinLibs GCC 15.2.0, Release, main aeff26b. Most runs use main's APS5_SPANNED_WAVE=1; one block uses this PR (head 4844a28) merged on aeff26b.

vkQuake (PPSA99010), shareware pak0, ray-traced setup at map load. SPIR-V size and NVIDIA pipeline build time of the first dispatches:

program main main + APS5_SPANNED_WAVE=1 this PR
0x20c37f400 400,503 words, 49.1 s 212,875 words, 19.2 s 400,503 words (not spanned)
0x20c382000 346,892 words, never finished before the title quit 192,767 words, 87.3 s 192,767 words (spanned)
0x20c384200 — 210,463 words, 19.2 s 399,365 words (not spanned), 45.1 s
0x20c388900 — 212,875 words, 19.8 s 400,503 words (not spanned), 39.5 s
  • On main, the pipeline journal lets each run build one more pipeline. That stopped at 0x20c382000: seven runs in a row added nothing and never got past submission 17, because the title quits about 25 s after the first timeout.
  • With APS5_SPANNED_WAVE=1, ten warm runs got it through. Runs 10 to 12 (3 of 3) had no timeout and played the attract-mode demo (You receive 25 health; the frame dumps show the level with the status bar).
  • With this PR, the three programs above stay at two lanes per invocation, about 400k words each. I take that to mean the new check finds a barrier in divergent flow in them. The others span as with the switch. Starting from the journal the switch had warmed, the third run with this PR reached the demo.
  • I couldn't get a clean cold run with this PR. NVIDIA's own pipeline cache already held every module from the earlier runs (a run with AnyPS5's shader cache moved aside still built them in about 50 ms). So I can't say how many runs this PR needs from cold.
  • Shader requests, CFG and SPIR-V of 0x20c37f400 are available if they help.

PS5 FSR4 Showcase (PPSA99011), the guided tour, no input. Its FSR4 pass uses about 30 compute programs of 117k–750k words, and the title gives each fence 4.5 s (FSR4_SHOWCASE_ERROR fence=-4 stage=fsr4 after_ms=4536).

  • main: each warm run gets one or two pipelines further. Chapter 9 of 12 came after about 38 runs, and it still failed there.
  • main + APS5_SPANNED_WAVE=1: the largest new pipelines are 536,648 words or less and take 16.1 s or less to build, against up to 750,129 words and 47.9 s without spanning. For example, 0x275620000 is 741,640 words (26.7 s) without spanning and 530,513 words (13.5 s) with it. Chapter 9 came after 8 runs. Run 11 played the whole tour, chapters 0 to 11, and started it again within 200 s, with no fence error.
  • With this PR, three runs starting from the caches the runs above left: most of the large programs are not spanned and keep main's sizes, for example 0x275480000 (404,461 words), 0x275560000 (530,441), 0x275580000 (531,614) and 0x275600000 (482,666). A few span, such as 0x2755a0000 (223,479 words, against 323,214 on main). The runs still hit the 4.5 s fence, in chapters 0, 2 and 7. NVIDIA's cache already held most of these pipelines, so the wait there was not driver compile time; I didn't find where it goes.

PS5LM Plus (PPSA99581), llama-server with SmolLM2-360M-Instruct q8_0 (Apache-2.0).

  • main: on a cold cache the first use of kernel 0x217124d00 (650,954 words, 11.3 s to build) trips the app's 10 s fence wait: ggml_vulkan: device lost on Vulkan0 / decode() failed: vk::Device::waitForFences: ErrorDeviceLost. Every new prompt shape does the same.
  • main + APS5_SPANNED_WAVE=1: 337,505 words, 4.1 s. Three different prompts in one cold server run all completed, and none lost the device. The 11-token prompt's text was garbage, but that is the flash-attention bug fix(shader): share wave64 VGPRs past the private ones between the two halves #7410 fixes, not spanning: it gives the same text without spanning and on the AMD iGPU.
  • With this PR, the PS5LM kernels do span: 0x217124d00 is 337,505 words, as with the switch. The same three prompts completed with no device lost, in one run whose pipelines NVIDIA's cache already held.

AI-assisted: yes (Claude Code); results above were run on this machine.

@ThatsLeo

Copy link
Copy Markdown
Contributor Author

@Michael-KD Works for me. Whichever lands second rebases and keeps both entries.

@ThatsLeo

Copy link
Copy Markdown
Contributor Author

@wachi35676 Thanks, this is very useful. The 0x20c37f400 programs spanning correctly under APS5_SPANNED_WAVE=1 while the check refuses them suggests one of its rules is too conservative for them. Could you attach the shader requests (the .req files) for 0x20c37f400 and 0x20c384200, plus one of the large FSR4 programs it refused, such as 0x275560000? I'll find which rule rejects them and loosen it in a follow-up PR, so this one doesn't have to wait.

AI-assisted: yes

@CnRJay CnRJay left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@oneandonlydean I don't have a setup that runs these titles, so I can't rerun 4844a28 on a GPU and won't post a result I haven't measured. My cross-vendor point was that every number came from one Intel/ANV machine; since then NVIDIA (@hamb3r, RTX 3080, Demon's Souls) and AMD (@thuanquang, RX 6700 XT, spanning confirmed active) runs have come in with no device loss, hang or corruption, which answers it. What the current head still needs from the people who have the hardware is a run of the same scene with and without APS5_NO_SPANNED_WAVE=1 on each vendor, with the GPU and driver, so the default has a paired result on NVIDIA and AMD and not only a clean boot.

@github-actions github-actions Bot added the needs rebase Conflicts with main, rebase needed label Oct 27, 2026
@thuanquang

thuanquang commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

@oneandonlydean the rerun on 4844a289c2, as asked: RX 6700 XT (gfx1031), AMD driver 32.0.21045.16010, Windows 11 26200, WinLibs GCC 15.2.0 r7, Release. The device log reports subgroup=64.

  • ctest -R "^(agc|shader)_": 997 of 1000 pass with the default setting and 997 of 1000 with APS5_NO_SPANNED_WAVE=1. In both runs the 3 failures are agc_driver_sample_order, agc_driver_sample_order_grid_reference and agc_driver_sample_order_recipe_depth_locations, the sample-order tests that fail on main on this GPU too.
  • Title: Metal Gear Solid Master Collection Vol. 1 (PPSA14363, own dump), a fixed demo route through the launcher, 330 s per run, once with each setting.
    • Both runs reached the time limit with no stop.
    • Neither log has a device loss, a fence timeout or a hang.
    • The route starts from a stored save past the launcher's Terms of Use, enters Metal Gear Solid and reaches its title screen. Frame dumps taken about every 7.5 s look the same in both runs.
    • Both runs shared the GPU with other work, so presents (430-600 per 10 s) are not a speed comparison.

AI-assisted: yes (Claude Code); results above were run on this machine.

@wachi35676

Copy link
Copy Markdown
Contributor

@ThatsLeo here are the requests and what refuses each program. Build: main 21787ea merged with this head 4844a28 (the merge is clean apart from docs/dev/debt/shader.md). Windows 11, RTX 5070 Ti (driver 621.01), WinLibs GCC 15.2.0, Release.

vkQuake (PPSA99010) requests: shader_20c37f400.req and shader_20c384200.req were dumped with APS5_DUMP_SHADERS=1 by that build, with spanning on by default (about 30 KB each). I haven't uploaded them anywhere yet. Since the trace below already names the refusing rule, tell me if you still want them and how you'd like them shared.

To find the rule, I added local logging to SpannedBarrierInDivergentFlow that follows the refusing barrier back to its first per-invocation value. Both programs are refused through the racy-load rule, and every refusing barrier comes from that one load: 33 barriers in 0x20c37f400 and 31 in 0x20c384200.

  • The root is s_load_dwordx2 s[12:13], s[2:3] at pc 0x0c, in block 0. It loads from the constant table that the user-data pointer s[2:3] points to, which reaches SPIR-V as an OpLoad of StorageBuffer class. The programs also store to guest memory through global stores. Since guest memory is now one class, Racy() counts the load as per-invocation.
  • In 0x20c37f400:
    • s12 goes through s_cmp_eq_i32 s12, 0 (0x40) and s_cmp_lg_i32 s15, 0 (0x64) to s_cbranch_scc0 at 0x74, which ends block 0.
    • That makes the selection header of block 0 per-invocation, and every barrier after it counts as divergent.
  • In 0x20c384200:
    • s12 goes through s_cmp_eq_i32 s12, 1 (0x2c), s_cmp_lg_i32 s14, 0 (0x54) and s_cmp_lg_i32 s17, 0 (0xeb4) to s_cbranch_scc0 at 0xeb8.
    • That makes the selection header at block pc 0xeb4 per-invocation.
  • No other rule is involved. When I turn the racy-load rule off for StorageBuffer-class loads, both programs pass the check and span:
    • 0x20c37f400 goes from 305,342 to 165,321 words;
    • 0x20c384200 goes from 304,501 to 163,040 words.
  • The load is an SMEM read at an SGPR address, so it is wave-uniform on the console. Spanned, the two subgroups read the same word. They could differ only if this dispatch wrote that word between the two reads, and nothing observed suggests that.
  • With main's APS5_SPANNED_WAVE=1, both programs spanned, and vkQuake played the attract-mode demo in 3 of 3 warm runs with no device loss. That is a whole-title result, not a per-program output comparison.
  • One possible loosening: count a uniform-address scalar (ReadConst) load as uniform, or keep read-only guest ranges out of the written class.

PS5 FSR4 Showcase (PPSA99011): I'm reporting the cause here instead of attaching the shaders, because the licence of the FSR4 code is unclear. The check doesn't refuse any of them, and my earlier comment was wrong about this.

  • 0x275560000, 0x275480000, 0x275580000 and 0x275600000 are wave32 programs with 64 threads. Spanning only applies to single-wave wave64 compute, so they keep the same size on main, on main with APS5_SPANNED_WAVE=1, and with this PR (0x275560000 is 530,441 words in all three).
  • I replayed the 48 requests from one FSR4 run with spanning on: 39 are wave32 and 9 are wave64, and none falls back.
  • The wave64 programs span the same way with the switch and with this PR. For example, 0x275620000 goes from 741,640 to 530,513 words in both.
  • So the FSR4 fence timeouts I saw with this PR don't come from the uniformity check.

AI-assisted: yes (Claude Code); results above were run on this machine.

@atk3001

atk3001 commented Oct 31, 2026

Copy link
Copy Markdown

GTA V (PPSA04263, content 01.010.002) on this head, as asked in #7922 (comment). Build: 4844a28 as pushed (not merged with main), Windows 10 22H2, RTX 5080 (driver 616.64), WinLibs GCC 15.2.0, Release, 3840x2160. One run each from the boot into the prologue, about 60 s in the prologue without input.

Stability. Neither run lost the device, hung or crashed: no FATAL, no VK_ERROR_DEVICE_LOST. Both runs show the rendering errors the title already has on main. In this short test the default run showed no new corruption next to APS5_NO_SPANNED_WAVE=1. That is from watching the screen; no frames were compared.

For comparison, main 474030e with the old APS5_SPANNED_WAVE=1 crashed after about 42 s of loading, before the prologue: 0xc0000005 on [RAGE] Main Thread, a read of 0x6056306b7 at app.exe+0x2aa2540, with no [spanned-wave] fallback in that run. That was one run; the same build without the switch has not crashed in eight runs. On this head the check sends 33 programs back to two lanes per invocation (67 [spanned-wave] lines, all "an OpControlBarrier ... sits in control flow a per-invocation value decides"), so the crash may come from one of them.

The prologue's heaviest program is refused. With APS5_PROFILE_GPU=1 on main, compute program 0x25b254a00 (wave64, 8x8x1 threads, 2,540 code words, one dispatch per present) takes about 160 ms of GPU time per present, about 65 % of the prologue's GPU time. On this head it falls back:

[spanned-wave] 0x25b254a00 falls back to two lanes per invocation: an OpControlBarrier in block %202 of function %151 sits in control flow a per-invocation value decides

It is built at 228,900 SPIR-V words in both runs. On main 474030e, agc_shader_replay gives 196,610 words for its request at two lanes per invocation and 123,015 with spanning forced on, using a local switch that is not upstream. For the two-lane pipeline, NVIDIA reports 255 registers and a Local Memory Size of 68,719,478,224 (APS5_PIPELINE_STATS=1 agc_compute_pipeline_replay --inspect). That is 1,488 bytes plus bit 36, so it probably spills. I haven't checked whether that barrier is really reached per invocation, or whether the rule is too conservative here, as in the vkQuake case above. I'm not attaching the request because it holds the game's shader code, but I can rerun it on a changed check.

Performance. No claim. The prologue stays at about 3 FPS in both runs. Both still stalled for seconds on pipeline builds, so only a few 10 s intervals are clean: GPU busy per present was 167 and 210 ms with spanning, and 244, 259, 272 and 244 ms with APS5_NO_SPANNED_WAVE=1. With 0x25b254a00 falling back, I wouldn't expect a large difference in this scene.

AI-assisted: yes (Claude Code); the runs above were made on this machine.

# Conflicts:
#	docs/dev/ENVIRONMENT.md
#	docs/dev/debt/shader.md
@github-actions github-actions Bot removed the needs rebase Conflicts with main, rebase needed label Nov 1, 2026
Celegans12 added a commit to Celegans12/AnyPS5-Ghost-of-Yotei that referenced this pull request Nov 1, 2026
…ater writes

Keep faulted wave participants voting instead of returning, while masking
their later writes, atomics and exports. This also preserves the healthy
partner of a two-lane invocation. Retain existing eligibility exclusions.

Latch the first guarded SRT fault so later words cannot replace it.
Strengthen host assertions; retain the runtime address and PC oracle.

Based on ThatsLeo/AnyPS5@b9362d8
core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvMemoryInstructions.cpp
(author: ThatsLeo). Adapt the actual-stopping predicate for masked lanes.
No spanned-wave policy from boykopovar#7922 is included.

AI-assisted: yes
@TechLevelZero

Copy link
Copy Markdown
Contributor

✅ NVIDIA GPU test: passed

PR head a684589 merged onto main e6f5730 · tested 2026-11-01 14:48 UTC · 25 min

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

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

@VicRaster

Copy link
Copy Markdown
Contributor

Additional qualification of head a68458936e3130ed62bcda3b4db46666cab72a79: the guarded path preserves the supplied replay images on a stationary five-frame GTA V bank-interior capture, but the dominant compute program falls back, so this does not establish a workload speedup.

Tested as an adaptation onto archived integrated source 214c012afcd5c156ddf65a45ae04ede695d6f72c, without our scalar/range-cache experiments: Windows build 26300, Ryzen 9 3900X, RTX 3080 Ti 12 GB, NVIDIA 610.88, GCC 15.2 Release, SPIRV-Tools OFF. This is not current-main qualification.

Nine focused tests passed with Vulkan required, shader cache disabled and validation enabled: spanned uniformity, shader memory, guarded null pointers, LDS mask waterfall, wave32 subgroup, BDA device, BDA span reads (including draw-pipeline mode), and scalar wide loads. No VUID or missing layer was observed.

The full replay qualification had exact matches for all three supplied final buffers, 45 submissions, 13,268.2 MiB restored, and zero failed/stale registrations, unfinished submissions, skipped mappings, pacing timeouts or synthesised waits. Existing warnings remained: one packet wait timeout, one prebuild warning and eight pending-image CPU-change warnings. This checks replay outputs, not native-perfect game rendering or every temporal frame.

The convergence check rejects the dominant program because an OpControlBarrier is under flow decided by a per-invocation value. Sixteen other distinct programs also fell back. The dominant translation retains the existing two-lanes-per-invocation layout. The raw unsafe spanning override was not enabled.

The two warm qualification passes had GPU batch-envelope unions of 513.07/518.47 ms per frame and dominant dispatches of 202.35/199.51 ms. This was a qualification/cache-population run, not a matched performance comparison; these numbers prove neither regression nor gain. The useful result is that the safety fallback is exercised in this workload, and simply enabling the guarded proposal does not remove its dominant bottleneck.

AI-assisted investigation, locally checked. No game code, captured/translated shaders, images, memory or private logs are attached.

@VicRaster

Copy link
Copy Markdown
Contributor

Follow-up to our earlier fallback qualification: sharing an experimental source-only patch and a null performance result, so others can build on the analysis without spending time repeating the same register-pressure experiment.

Scope/provenance. This is a separate laptop continuation of the same five-frame recorded workload: i7-13700HX, RTX 4070 Laptop 8 GiB, NVIDIA 592.82, 32 GiB RAM, Windows, WinLibs GCC 15.2 Release. It targets head a68458936e3130ed62bcda3b4db46666cab72a79 as adapted onto archived integrated source 214c012afcd5c156ddf65a45ae04ede695d6f72c, not current upstream main. The patch below is relative to that adapted PR baseline; it is not a guaranteed clean application to today's main. The laptop investigator performed the builds/tests/runs; this follow-up reviewed their final report and source patch but has not rerun this candidate on the original RTX 3080 Ti workstation.

What made the rejected programs eligible

Two obstacles were identified in the convergence analysis:

  1. Loads at uniform addresses through the driver's NonWritable tables were treated as potentially racy because the module writes other memory in the same storage class. The refinement tracks variable roots and writes, retaining rejection for writes through the variable or unknown pointer roots. Its safety depends on those driver tables being immutable during the dispatch and not aliasing guest device-address memory; this needs reviewer scrutiny, not a blanket assumption that NonWritable alone proves global immutability.
  2. A scalar memory read duplicated across two host subgroups need not give both subgroups the same value. The candidate shares supported scalar-load results from lane zero through workgroup memory with two barriers. The convergence check remains active: divergent placements still fall back. This does not disable the racy-load rule or force unsafe spanning.

All 17 previously rejected programs in this capture became eligible. For the dominant dispatch, reported register count changed 255 → 128, binary size 518,656 → 381,056 bytes, and SPIR-V 198,869 → 142,216 words. These are compile statistics, not occupancy or executed-instruction measurements.

Result: no demonstrated speedup

Both timing arms used the identical candidate binary, with APS5_NO_SPANNED_WAVE=1 for the two-lane arm. Three alternating profile pairs; each run repeated three passes, and warm values average passes 1 and 2. The cache was warmed before comparisons.

Dominant dispatch Two lanes Spanned Paired reduction; illustrative 95% t interval
All three pairs, including one unequal-restore run 174.5 ms 193.1 ms -18.6 ms; -93 to +56 ms
Two strictly restore-matched pairs 164.8 ms 196.5 ms -31.7 ms; -284 to +220 ms

Negative reduction means spanned was slower. Query misses were zero for the dominant dispatch. Other detail ranges hit the existing cap. Neither table establishes a gain or a reliable regression; the intervals are wide. Reducing registers did not demonstrate a performance benefit here, but this does not rule out an occupancy limitation: the alternative layout also adds substantial workgroup synchronisation, which could offset a benefit. The underlying instruction/stall bottleneck remains unmeasured.

The laptop was under severe memory pressure (other applications held about 3.4 GiB VRAM), with heavy eviction/re-upload activity and competing CPU activity. Whole-frame GPU and replay wall times therefore do not isolate the shader change; even per-dispatch results need replication under cleaner conditions. Two runs across the profile/wall series performed a real, non-synthesised wait release with an extra 204.6 MiB restore. They were retained and marked excluded; inclusive and strictly matched statistics were both reported. This is replay evidence, not a live-game FPS claim, and the 33.3 ms target was not met.

Correctness evidence and remaining gaps

  • Eight synthetic convergence-analysis cases were added; all 21 analysis cases pass. Two acceptance cases fail on the earlier analysis and pass with the refinement; conservative cases cover writes/atomics, pointer parameters and lane-indexed reads.
  • Thirteen focused tests passed on both the adapted PR baseline and candidate with Vulkan required, shader cache disabled and validation enabled; logs reported no VUID, validation error or missing requested layer. This is not a current-main comparison.
  • Measured repeat-three replays retained 45 submissions, zero failed/stale registrations, skipped mappings, unfinished submissions, pacing timeouts or synthesised waits. All three final buffers matched this laptop's unchanged control byte for byte. Existing warning classes remained.
  • The laptop's unchanged outputs differ from the supplied RTX 3080 Ti images by 8.8–10.4% of pixels, so local-control equality proves regression consistency, not cross-GPU or console fidelity. Single-pass pipeline-statistics runs also produced different images in both arms; they support compile statistics only and are not correctness runs.
  • Missing: a dedicated GPU test where a scalar memory load decides a wave-mask branch in spanned mode; cross-GPU/current-main qualification; paired live testing; stronger evidence for table lifetime/aliasing assumptions. Conventions reported no errors and one pre-existing debt-entry length warning; whitespace checks passed on the laptop.

Please treat this as an experimental enabling patch for review, not a recommended performance optimisation or a general correctness proof. No captured memory, game code, guest disassembly, translated shader binaries, images or private logs are included. The tests below construct synthetic SPIR-V; the diagnostic addition is code only, with no dump output attached.

AI-assisted: yes (Codex/Claude Code across the investigations), with local report/patch review and the test/measurement limits above.

Source-only experimental patch (AnyPS5 implementation, synthetic tests and documentation)
diff --git a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp
index c130ffc7..d55f0bb9 100644
--- a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp
+++ b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp
@@ -103,6 +103,7 @@ struct SpirvEmitterState {
     bool splitSubgroup = false;
     bool spannedWave = false;
     std::uint32_t spannedExchangeVariable = 0;
+    std::uint32_t spannedBroadcastVariable = 0;
     bool narrowSubgroupClock = false;
     bool float64DenormPreserve = false;
     bool depthRangeRemap = false;
diff --git a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvSubgroup.hpp b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvSubgroup.hpp
index ad10afcb..5ef9207f 100644
--- a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvSubgroup.hpp
+++ b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvSubgroup.hpp
@@ -12,6 +12,7 @@ void EmitHostSubgroupBallot(SpirvEmitterState& state, std::uint32_t result, std:
 void EmitSubgroupBallotFindLsb(SpirvEmitterState& state, std::uint32_t result, std::uint32_t ballot);
 void EmitSubgroupShuffle(SpirvEmitterState& state, std::uint32_t type, std::uint32_t result, std::uint32_t value, std::uint32_t lane);
 void EmitSubgroupShuffleInHalf(SpirvEmitterState& state, std::uint32_t type, std::uint32_t result, std::uint32_t value, std::uint32_t lane);
+std::uint32_t EmitSpannedUniformLoad(SpirvEmitterState& state, std::uint32_t type, std::uint32_t value);
 void EmitSubgroupElect(SpirvEmitterState& state, std::uint32_t result);
 std::uint32_t EmitSubgroupLocalInvocationId(SpirvEmitterState& state);
 std::uint32_t EmitHostSubgroupLane(SpirvEmitterState& state, std::uint32_t lane);
diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp
index c878d293..e7f90d26 100644
--- a/core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp
+++ b/core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp
@@ -331,7 +331,24 @@ std::vector<std::uint32_t> SpirvEmitter::Emit(const IrProgram& program, const Sh
     state.module.EmitEntryPoint(ExecutionModelForStage(state.program.Resources().stage), state.mainFunc, "main", state.interfaceVariables);
     auto words = state.module.Finalize();
     if (state.spannedWave) {
-        if (auto reason = SpannedBarrierInDivergentFlow(words)) throw SpannedWaveUnsupported(*reason);
+        if (auto reason = SpannedBarrierInDivergentFlow(words)) {
+            if (const char* dump = std::getenv("APS5_DUMP_REJECTED_SPANNED"); dump != nullptr && *dump != '\0') {
+                std::uint64_t hash = 0xcbf29ce484222325ull;
+                for (const auto word : words) {
+                    hash ^= word;
+                    hash *= 0x100000001b3ull;
+                }
+                char name[64];
+                std::snprintf(name, sizeof(name), "/rejected-%016llx.spv", static_cast<unsigned long long>(hash));
+                const std::string path = std::string(dump) + name;
+                if (std::FILE* file = std::fopen(path.c_str(), "wb")) {
+                    std::fwrite(words.data(), sizeof(std::uint32_t), words.size(), file);
+                    std::fclose(file);
+                    *reason += " (module written to " + path + ")";
+                }
+            }
+            throw SpannedWaveUnsupported(*reason);
+        }
     }
     if (info != nullptr) {
         info->fullSubgroups = state.spannedWave;
diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvMemoryInstructions.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvMemoryInstructions.cpp
index 16e6a6f8..593db382 100644
--- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvMemoryInstructions.cpp
+++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvMemoryInstructions.cpp
@@ -293,21 +293,23 @@ std::uint32_t LoadBda(SpirvValueEmitContext& ctx, const IrValue& inst, const Mem
             const auto zero = ConstantU32(state, 0u);
             const auto none = state.module.AllocateId();
             state.module.AddFunction(spv::OpCompositeConstruct, vector, none, zero, zero, zero, zero);
-            const auto all = EmitValueOrDefaultIfCondition(state, ActiveArgument(ctx, inst), vector, none, [&]() {
+            auto all = EmitValueOrDefaultIfCondition(state, ActiveArgument(ctx, inst), vector, none, [&]() {
                 const auto values = ReadBdaDwords(ctx, inst, mem, 4u, used);
                 const auto read = state.module.AllocateId();
                 state.module.AddFunction(spv::OpCompositeConstruct, vector, read, values[0], values[1], values[2], values[3]);
                 return read;
             });
+            if (mem.kind == ResourceKind::ScalarAddress) all = EmitSpannedUniformLoad(state, vector, all);
             for (const auto& member : members) state.bdaGroupedLoads[member.first] = {all, member.second};
             const auto value = state.module.AllocateId();
             state.module.AddFunction(spv::OpCompositeExtract, TypeU32(state), value, all, 0u);
             return value;
         }
     }
-    return EmitValueOrZeroIfCondition(ctx.state, ActiveArgument(ctx, inst), [&]() {
+    const auto value = EmitValueOrZeroIfCondition(ctx.state, ActiveArgument(ctx, inst), [&]() {
         return ReadBda(ctx, inst, mem, bits);
     });
+    return mem.kind == ResourceKind::ScalarAddress && bits == 32u ? EmitSpannedUniformLoad(state, TypeU32(state), value) : value;
 }
 
 void StoreWordInBounds(SpirvValueEmitContext& ctx, const MemoryResourceAccess& resource, std::uint32_t index, std::uint32_t data) {
@@ -1592,7 +1594,7 @@ void EmitReadConstBuffer(SpirvValueEmitContext& ctx, const IrValue& inst) {
     const auto& mem = ctx.Memory(inst);
     if (mem.planningOnly) return;
     if (mem.kind != ResourceKind::ScalarBuffer) ctx.Fail(inst, "must read a scalar buffer resource");
-    ctx.Define(inst, EmitRuntimeScalarBufferLoad(ctx, inst));
+    ctx.Define(inst, EmitSpannedUniformLoad(ctx.state, TypeId(ctx.state, inst.Type()), EmitRuntimeScalarBufferLoad(ctx, inst)));
 }
 
 void EmitGetSrtResource(SpirvValueEmitContext& context) {
diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvSubgroup.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvSubgroup.cpp
index 81449d6a..d386e2f5 100644
--- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvSubgroup.cpp
+++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvSubgroup.cpp
@@ -146,6 +146,50 @@ namespace ShaderRecompiler
         state.module.AddFunction(spv::OpGroupNonUniformShuffle, type, result, ConstantU32(state, spv::ScopeSubgroup), value, EmitBinaryU32(state, spv::OpBitwiseAnd, lane, ConstantU32(state, 31u)));
     }
 
+    std::uint32_t EmitSpannedUniformLoad(SpirvEmitterState& state, std::uint32_t type, std::uint32_t value) {
+        if (!state.spannedWave) return value;
+        std::uint32_t components = type == TypeU32(state) ? 1u : 0u;
+        for (std::uint32_t count = 2u; components == 0u && count <= 4u; ++count) {
+            if (type == TypeU32Vector(state, count)) components = count;
+        }
+        if (components == 0u) throw SpannedWaveUnsupported("a spanned wave shares only 32-bit scalar loads of up to four dwords");
+        if (state.spannedBroadcastVariable == 0u) {
+            state.spannedBroadcastVariable = state.module.DefineGlobalVariable(TypeU32ArrayPointer(state, spv::StorageClassWorkgroup, 256u), spv::StorageClassWorkgroup);
+            state.module.AddName(state.spannedBroadcastVariable, "wave_broadcast");
+        }
+        const auto slot = [&](std::uint32_t index) {
+            const auto pointer = state.module.AllocateId();
+            state.module.AddFunction(spv::OpAccessChain, TypeU32ElementPointer(state, spv::StorageClassWorkgroup), pointer, state.spannedBroadcastVariable, index);
+            return pointer;
+        };
+        const auto lane = SpannedLane(state);
+        std::array<std::uint32_t, 4> words{};
+        for (std::uint32_t component = 0; component < components; ++component) {
+            if (components == 1u) {
+                words[component] = value;
+                continue;
+            }
+            words[component] = state.module.AllocateId();
+            state.module.AddFunction(spv::OpCompositeExtract, TypeU32(state), words[component], value, component);
+        }
+        SpannedBarrier(state);
+        for (std::uint32_t component = 0; component < components; ++component) {
+            state.module.AddFunction(spv::OpStore, slot(EmitAddU32(state, lane, ConstantU32(state, component * 64u))), words[component]);
+        }
+        SpannedBarrier(state);
+        std::array<std::uint32_t, 4> shared{};
+        for (std::uint32_t component = 0; component < components; ++component) {
+            shared[component] = state.module.AllocateId();
+            state.module.AddFunction(spv::OpLoad, TypeU32(state), shared[component], slot(ConstantU32(state, component * 64u)));
+        }
+        if (components == 1u) return shared[0];
+        const auto result = state.module.AllocateId();
+        if (components == 2u) state.module.AddFunction(spv::OpCompositeConstruct, type, result, shared[0], shared[1]);
+        else if (components == 3u) state.module.AddFunction(spv::OpCompositeConstruct, type, result, shared[0], shared[1], shared[2]);
+        else state.module.AddFunction(spv::OpCompositeConstruct, type, result, shared[0], shared[1], shared[2], shared[3]);
+        return result;
+    }
+
     void EmitSubgroupElect(SpirvEmitterState& state, std::uint32_t result) {
         if (HostSubgroupSingleLane(state)) {
             state.module.AddFunction(spv::OpCopyObject, TypeBool(state), result, ConstantBool(state, true));
diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvSpannedUniformity.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvSpannedUniformity.cpp
index 1b7a231b..f3d1f75b 100644
--- a/core/shader/recompiler/SpirvBackend/src/SpirvSpannedUniformity.cpp
+++ b/core/shader/recompiler/SpirvBackend/src/SpirvSpannedUniformity.cpp
@@ -30,6 +30,9 @@ struct Module {
     std::unordered_map<std::uint32_t, std::uint32_t> storageClasses;
     std::unordered_map<std::uint32_t, std::uint32_t> pointerClasses;
     std::unordered_map<std::uint32_t, std::uint32_t> constants;
+    std::unordered_set<std::uint32_t> nonWritable;
+    std::unordered_set<std::uint32_t> deviceAddressPointers;
+    std::unordered_map<std::uint32_t, std::uint32_t> chains;
     std::vector<Function> functions;
 };
 
@@ -46,6 +49,17 @@ Module Parse(std::span<const std::uint32_t> words) {
         switch (Opcode(instruction)) {
         case spv::OpDecorate:
             if (instruction.size() >= 4u && instruction[2] == spv::DecorationBuiltIn) module.builtins[instruction[1]] = instruction[3];
+            if (instruction.size() >= 3u && instruction[2] == spv::DecorationNonWritable) module.nonWritable.insert(instruction[1]);
+            break;
+        case spv::OpConvertUToPtr:
+            if (instruction.size() >= 3u) module.deviceAddressPointers.insert(instruction[2]);
+            if (block != nullptr) block->body.push_back(std::move(instruction));
+            break;
+        case spv::OpAccessChain:
+        case spv::OpInBoundsAccessChain:
+        case spv::OpPtrAccessChain:
+            if (instruction.size() >= 4u) module.chains[instruction[2]] = instruction[3];
+            if (block != nullptr) block->body.push_back(std::move(instruction));
             break;
         case spv::OpTypePointer:
             if (instruction.size() >= 4u) module.pointerClasses[instruction[1]] = instruction[2];
@@ -165,7 +179,12 @@ public:
             for (const auto& block : function.blocks) {
                 for (const auto& instruction : block.body) {
                     const auto pointer = WrittenPointer(instruction);
-                    if (pointer != 0u) written.insert(ClassOf(pointer));
+                    if (pointer != 0u) {
+                        written.insert(ClassOf(pointer));
+                        const auto variable = BaseVariable(pointer, module.chains);
+                        if (module.storageClasses.contains(variable)) writtenVariables.insert(variable);
+                        else if (!module.deviceAddressPointers.contains(variable)) writtenThroughUnknownRoot = true;
+                    }
                     if (Opcode(instruction) == spv::OpImageWrite) written.insert(spv::StorageClassImage);
                 }
             }
@@ -241,7 +260,8 @@ private:
         return fenced && storageClass != spv::StorageClassWorkgroup && storageClass != UnknownClass;
     }
 
-    bool Racy(std::uint32_t pointer, bool fenced) const {
+    bool Racy(std::uint32_t pointer, std::uint32_t variable, bool fenced) const {
+        if (module.nonWritable.contains(variable) && module.storageClasses.contains(variable) && !writtenVariables.contains(variable) && !writtenThroughUnknownRoot) return false;
         const auto storageClass = ClassOf(pointer);
         if (storageClass != UnknownClass && (PrivateStorage(storageClass) || storageClass == spv::StorageClassInput)) return false;
         if (!Written(storageClass)) return false;
@@ -494,11 +514,11 @@ private:
                     const auto builtin = module.builtins.find(variable);
                     const auto storage = module.storageClasses.find(variable);
                     varying = NonUniform(instruction[3]) || (builtin != module.builtins.end() && VaryingBuiltin(builtin->second)) || storedNonUniform.contains(variable) ||
-                        (storage != module.storageClasses.end() && storage->second == spv::StorageClassInput && builtin == module.builtins.end()) || Racy(instruction[3], fencedBefore);
+                        (storage != module.storageClasses.end() && storage->second == spv::StorageClassInput && builtin == module.builtins.end()) || Racy(instruction[3], variable, fencedBefore);
                     break;
                 }
                 case spv::OpAtomicLoad:
-                    varying = NonUniform(instruction.at(3)) || Racy(instruction[3], fencedBefore);
+                    varying = NonUniform(instruction.at(3)) || Racy(instruction[3], BaseVariable(instruction[3], chains), fencedBefore);
                     break;
                 case spv::OpPhi:
                     varying = inDivergentFlow || divergentMerges.contains(label);
@@ -525,6 +545,8 @@ private:
     const Module& module;
     std::unordered_map<std::uint32_t, std::uint32_t> types;
     std::unordered_set<std::uint32_t> written;
+    std::unordered_set<std::uint32_t> writtenVariables;
+    bool writtenThroughUnknownRoot = false;
     std::unordered_set<std::uint32_t> barriers;
     std::unordered_set<std::uint32_t> nonUniform;
     std::unordered_set<std::uint32_t> storedNonUniform;
diff --git a/core/shader/recompiler/tests/SpannedUniformityTests.cpp b/core/shader/recompiler/tests/SpannedUniformityTests.cpp
index 7e191571..349ebe9f 100644
--- a/core/shader/recompiler/tests/SpannedUniformityTests.cpp
+++ b/core/shader/recompiler/tests/SpannedUniformityTests.cpp
@@ -29,6 +29,8 @@ enum Id : std::uint32_t {
     StoragePointer,
     Storage,
     PhysicalPointer,
+    ReadOnlyStorage,
+    PointerFunctionType,
     First = 100u,
 };
 
@@ -41,6 +43,7 @@ public:
         emit(spv::OpEntryPoint, {spv::ExecutionModelGLCompute, Main, 0x6e69616du, 0u, Index});
         emit(spv::OpExecutionMode, {Main, spv::ExecutionModeLocalSize, 64u, 1u, 1u});
         emit(spv::OpDecorate, {Index, spv::DecorationBuiltIn, spv::BuiltInLocalInvocationIndex});
+        emit(spv::OpDecorate, {ReadOnlyStorage, spv::DecorationNonWritable});
         emit(spv::OpTypeVoid, {Void});
         emit(spv::OpTypeBool, {Bool});
         emit(spv::OpTypeInt, {Uint, 32u, 0u});
@@ -58,6 +61,8 @@ public:
         emit(spv::OpTypePointer, {FunctionPointer, spv::StorageClassFunction, Uint});
         emit(spv::OpTypePointer, {StoragePointer, spv::StorageClassStorageBuffer, Uint});
         emit(spv::OpVariable, {StoragePointer, Storage, spv::StorageClassStorageBuffer});
+        emit(spv::OpVariable, {StoragePointer, ReadOnlyStorage, spv::StorageClassStorageBuffer});
+        emit(spv::OpTypeFunction, {PointerFunctionType, Void, StoragePointer});
         emit(spv::OpTypePointer, {PhysicalPointer, spv::StorageClassPhysicalStorageBuffer, Uint});
     }
 
@@ -224,6 +229,28 @@ Module joined(const std::function<void(Module&)>& condition) {
     return module;
 }
 
+Module storeThroughParameter(std::uint32_t argument) {
+    Module module;
+    module.emit(spv::OpFunction, {Void, Helper, spv::FunctionControlMaskNone, PointerFunctionType});
+    module.emit(spv::OpFunctionParameter, {StoragePointer, First + 30u});
+    module.emit(spv::OpLabel, {First + 31u});
+    module.emit(spv::OpStore, {First + 30u, Three});
+    module.end();
+    module.function(Main);
+    module.emit(spv::OpLabel, {First});
+    module.emit(spv::OpFunctionCall, {Void, First + 32u, Helper, argument});
+    module.emit(spv::OpLoad, {Uint, First + 6u, ReadOnlyStorage});
+    module.emit(spv::OpIEqual, {Bool, First + 8u, First + 6u, Two});
+    module.emit(spv::OpSelectionMerge, {First + 9u, spv::SelectionControlMaskNone});
+    module.emit(spv::OpBranchConditional, {First + 8u, First + 7u, First + 9u});
+    module.emit(spv::OpLabel, {First + 7u});
+    module.barrier();
+    module.emit(spv::OpBranch, {First + 9u});
+    module.emit(spv::OpLabel, {First + 9u});
+    module.end();
+    return module;
+}
+
 void laneSplit(Module& module, std::uint32_t merge) {
     module.emit(spv::OpULessThan, {Bool, First + 2u, First + 1u, Three});
     module.emit(spv::OpSelectionMerge, {merge, spv::SelectionControlMaskNone});
@@ -310,5 +337,39 @@ int main() {
         module.emit(spv::OpLoad, {Uint, First + 6u, First + 5u});
         module.emit(spv::OpIEqual, {Bool, First + 8u, First + 6u, Two});
     }), true);
+    expect("a barrier under a non-writable buffer word read at a uniform index after a store through a device address", joined([](Module& module) {
+        module.emit(spv::OpConvertUToPtr, {PhysicalPointer, First + 10u, Two});
+        module.emit(spv::OpStore, {First + 10u, Three});
+        module.emit(spv::OpLoad, {Uint, First + 6u, ReadOnlyStorage});
+        module.emit(spv::OpIEqual, {Bool, First + 8u, First + 6u, Two});
+    }), false);
+    expect("a barrier under a non-writable buffer word read at a uniform index after a store through another buffer", joined([](Module& module) {
+        module.emit(spv::OpStore, {Storage, Three});
+        module.emit(spv::OpLoad, {Uint, First + 6u, ReadOnlyStorage});
+        module.emit(spv::OpIEqual, {Bool, First + 8u, First + 6u, Two});
+    }), false);
+    expect("a barrier under a non-writable buffer word read at a uniform index after a store through that buffer", joined([](Module& module) {
+        module.emit(spv::OpStore, {ReadOnlyStorage, Three});
+        module.emit(spv::OpLoad, {Uint, First + 6u, ReadOnlyStorage});
+        module.emit(spv::OpIEqual, {Bool, First + 8u, First + 6u, Two});
+    }), true);
+    expect("a barrier under a non-writable buffer word read at a uniform index after an atomic through that buffer", joined([](Module& module) {
+        module.emit(spv::OpAtomicIAdd, {Uint, First + 5u, ReadOnlyStorage, Two, Semantics, Three});
+        module.emit(spv::OpLoad, {Uint, First + 6u, ReadOnlyStorage});
+        module.emit(spv::OpIEqual, {Bool, First + 8u, First + 6u, Two});
+    }), true);
+    expect("a barrier under a non-writable buffer word read at a lane index", joined([](Module& module) {
+        module.emit(spv::OpAccessChain, {StoragePointer, First + 5u, ReadOnlyStorage, First + 1u});
+        module.emit(spv::OpLoad, {Uint, First + 6u, First + 5u});
+        module.emit(spv::OpIEqual, {Bool, First + 8u, First + 6u, Two});
+    }), true);
+    expect("a barrier under a non-writable buffer word read after a store through a pointer parameter bound to that buffer", storeThroughParameter(ReadOnlyStorage), true);
+    expect("a barrier under a non-writable buffer word read after a store through a pointer parameter bound to another buffer", storeThroughParameter(Storage), true);
+    expect("a barrier under a writable buffer word read at a uniform index after a store through a device address stays rejected", joined([](Module& module) {
+        module.emit(spv::OpConvertUToPtr, {PhysicalPointer, First + 10u, Two});
+        module.emit(spv::OpStore, {First + 10u, Three});
+        module.emit(spv::OpLoad, {Uint, First + 6u, Storage});
+        module.emit(spv::OpIEqual, {Bool, First + 8u, First + 6u, Two});
+    }), true);
     return failed ? EXIT_FAILURE : EXIT_SUCCESS;
 }
diff --git a/docs/dev/ENVIRONMENT.md b/docs/dev/ENVIRONMENT.md
index 1320d3cb..6b7a7b7f 100644
--- a/docs/dev/ENVIRONMENT.md
+++ b/docs/dev/ENVIRONMENT.md
@@ -155,6 +155,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti
 | `APS5_DUMP_FRAMES_EVERY` | integer | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | 1 | dumps every n-th presented frame |
 | `APS5_DUMP_QUEUE` | integer | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketExecution.cpp` |  | dumps the first submissions of the queue with this hex id |
 | `APS5_DUMP_REJECTED` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/CommandValidation.cpp` |  | writes a rejected submission to rejected_submission_<n>.bin |
+| `APS5_DUMP_REJECTED_SPANNED` | string | `core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp` |  | directory in which a spanned single-wave64 compute module that the convergence check sends back to two lanes per invocation is written as `rejected-<hash>.spv`, named in the `[spanned-wave]` fallback line |
 | `APS5_DUMP_SCALE` | integer | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | 4 | keeps every n-th pixel in each direction of a dumped frame (1 to 16384; any other value fails) |
 | `APS5_DUMP_SHADERS` | string | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp` |  | writes each prepared shader's request to shader_<address>.req; a comma-separated list of hex program addresses (for example `807b90a100,0x807b925400`) writes only those programs' requests, and any other value (such as `1`) writes every request |
 | `APS5_DUMP_STORAGE` | string | `core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp` |  | selects storage textures to dump by hex address or WxHxL[:format] extent as storage_<address>_<n>.raw |
diff --git a/docs/dev/debt/shader.md b/docs/dev/debt/shader.md
index 9faf3a95..9f0a2eb0 100644
--- a/docs/dev/debt/shader.md
+++ b/docs/dev/debt/shader.md
@@ -210,7 +210,7 @@
 - [Flag structurization](../../../core/shader/recompiler/ControlFlow/src/Structurizer.cpp) (shader recompiler) - a graph that every structurizer attempt refuses, irreducible and non-terminating graphs included, is rebuilt with one reach flag per block and one again flag per loop (`structurizeWithFlags`): each block keeps one copy and runs behind a guard on its flag, and each strongly connected component becomes a loop whose single latch repeats it while a back edge set its flag. The output has about 8 times the input's blocks and one route variable per block, and ends in an empty Return that never runs. Only blocks that start the top-level order unconditionally run unguarded, so resource planning also sees the static paths that skip a guarded block and can plan extra descriptor candidates for them. The attempts still run first. Shared merge splitting refuses an attempt once the graph has grown past 16 times its block count at the start of splitting (at least 64 blocks); succeeding attempts grew at most 10.6 times on random graphs of up to 128 blocks, and an attempt that would succeed only beyond the budget leaves the graph to a later attempt or to this construction. Splitting that adds one block per round stays within that budget until its 4 rounds per block run out, so the attempts can still take more than 10 s (9 of 2,000 random graphs of up to 128 blocks, 63 s at most). `APS5_FORCE_STRUCTURIZER_FALLBACK=1` builds every graph this way, for tests
 - [Shared loop latches](../../../core/shader/recompiler/ControlFlow/src/Structurizer.cpp) (shader recompiler) - a loop whose single latch holds instructions and is reached by one edge gets an empty continue block, so its continue construct is that one block. A latch that several `continue` paths share keeps its instructions in the continue construct, since isolating it would clone them into each path. When such a latch emits more than one SPIR-V block, as a memory or image access does, SPIRV-Cross (MoltenVK) folds the construct into a `for` increment and drops the header's `OpPhi` updates, so the loop never advances on Metal. No title is known to reach this case.
 - [Scalar buffer descriptors](../../../core/shader/recompiler/Optimization/src/ResourceMaterializer.cpp) - the PS5's gfx1013 is not measured, nor is a V# with a null base. Scalar loads use only the base address, stride and record count: the fourth word is normalized to zero for resources accessed exclusively by scalar loads, and a [V# read at run time](../../../core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp) does not fault on its type for a scalar load. Measured on RDNA2 (gfx1036, AMD Windows driver 32.0.21030.31) with `s_buffer_load_dword` and `_dwordx4` through the [hardware oracle](../HW_ORACLE.md): every `OOB_SELECT`, `TYPE`, `FORMAT` 0, `ADD_TID_ENABLE`, `INDEX_STRIDE`, a zero and an all-ones fourth word read as 0x31016fac does; the range is `NUM_RECORDS` bytes with stride 0, else `STRIDE` × `NUM_RECORDS`, whatever `SWIZZLE_ENABLE`; a dword not wholly in range reads 0. Vector and mixed accesses retain descriptor validation.
-- [Spanned wave64 compute](../../../core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvSubgroup.cpp) (shader recompiler) - a spanned wave exchanges ballots, shuffles and reductions between its two host subgroups through workgroup barriers, which hang the device when not every invocation reaches them. [SpannedBarrierInDivergentFlow](../../../core/shader/recompiler/SpirvBackend/src/SpirvSpannedUniformity.cpp) sends a program back to two lanes per invocation when a barrier sits in control flow that a per-invocation value decides. It counts a load at a uniform address as uniform only from memory the program never writes, or from workgroup memory a barrier fences on every path since the last write; writes by other dispatches or queues are not considered. An earlier one-barrier ballot also lost the device for a reason that is not understood. `APS5_NO_SPANNED_WAVE` turns spanning off.
+- [Spanned wave64 compute](../../../core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvSubgroup.cpp) (shader recompiler) - a spanned wave exchanges ballots, shuffles and reductions between its two host subgroups through workgroup barriers, which hang the device when not every invocation reaches them. [SpannedBarrierInDivergentFlow](../../../core/shader/recompiler/SpirvBackend/src/SpirvSpannedUniformity.cpp) sends a program back to two lanes per invocation when a barrier sits in control flow that a per-invocation value decides. It counts a load at a uniform address as uniform only from memory the program never writes, or from workgroup memory a barrier fences on every path since the last write; writes by other dispatches or queues are not considered. A load through a `NonWritable` storage buffer variable (BDA page table, flattened SRT, image table map: filled by the driver before the dispatch, never stored to by the module) counts as uniform at a uniform address although the module stores elsewhere or through device addresses, which reach only guest memory; a store through that variable, or through a pointer whose root is neither a variable nor a device address, withdraws this. A spanned wave shares every scalar memory load (`s_load`, `s_buffer_load`) from lane 0 through workgroup memory behind two barriers, so both host subgroups see the one value a wave would; a scalar load inside per-invocation control flow still sends the program back to two lanes. Neither the broadcast nor the `NonWritable` rule is measured on hardware beyond the focused tests and one title's replay. An earlier one-barrier ballot also lost the device for a reason that is not understood. `APS5_NO_SPANNED_WAVE` turns spanning off.
 - [Guest memory load guards](../../../core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvMemoryInstructions.cpp) (shader recompiler) - a guest load whose lane is inactive or whose address is out of bounds is still performed and its result replaced by 0 with `OpSelect`, instead of a selection per guard, when the load can be pointed at a location nothing writes: scratch reads its own element 0; storage buffers (direct buffers, GDS) read element 0xfffffffe, which `robustBufferAccess2` turns into a zero load with no memory access, so the extra read cannot race with a write the guarded program would not have raced with ([Vulkan memory model](https://docs.vulkan.org/spec/latest/appendices/memorymodel.html#data-race)). Without `robustBufferAccess2` ([VulkanDevice.cpp](../../../core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp) enables it when the device has it) those loads keep their selections; LDS loads, stores, atomics, formatted and physical-address (BDA) accesses always do. LDS keeps the branch because NVIDIA's compiler predicates a branched LDS load at no cost, while the select form costs about 2.5 instructions per dword and splits a `ds_read_b128` into four loads (RTX 4060 measurements by @karanvora2599 in #4048); Intel's static counts favour the select only for wide reads, and run time was not measured on either. The aligned high word of a misaligned-capable buffer read re-reads the low word's own element. A selection guard costs four blocks per lane half and the host compiler's time grows with the block count: PPSA11142's merged PSP vertex program (3176 ISA words, wave64) emitted 16,983 blocks and 1,710 conditional branches, 5,907 and 868 with the selects. `agc_guarded_memory_loads` traces the emitted loads in both device modes. When the device also reports `robustStorageBufferAccessSizeAlignment` 1, a direct buffer load leaves out the comparison with the descriptor's `OpArrayLength` (which reads the descriptor) and the device returns the zero past the descriptor range: the host rounds a guest buffer's or a draw snapshot's descriptor range of 4 bytes or more down to whole dwords, which no direct access reaches past, and the misaligned-base high word keeps its comparison with the length. The guest bound and the guards of stores, atomics, GDS, LDS and BDA are unchanged. The flag is part of the shader cache key and `APS5_NO_EXACT_ROBUST_LOADS` (any value) keeps the comparison. Hardware treatment of a 32-bit load that straddles the end of a 1 to 3 byte range is not measured.
 - [Merged hull programs](../../../core/shader/recompiler/Optimization/src/TessellationLowering.cpp) (registered binary type 3) run whole in the hull stage, one invocation per output control point. On the console hull lane i keeps local lane i's registers, which with fewer input than output control points stop matching the patch's control points from i = inputs on; here invocation i holds control point min(i, inputs - 1) of its own patch. A wave-mask branch (`s_cbranch_exec[n]z`, `s_cbranch_vcc[n]z`) tests the invocation's own lane, so it can skip a block, scalar instructions included, that the console runs for the wave; `v_readfirstlane_b32` returns the invocation's own value, not the first active lane's, and another lane's register throws. The register layout (`s3`, `v0`-`v5`, as for the separate halves) is not measured on hardware. s[0:1] hold the hull user-data address (SH 0x102/0x103) when a draw sets it and zero otherwise, so a program reading it unset faults at the null address.
 - [SPIR-V instruction length and deferred phi validation](../../../core/shader/recompiler/SpirvBackend/src/SpirvModule.cpp) (shader recompiler) - SPIR-V instruction word count boundaries and deferred phi patch tokens validate bounds against logical layout rules; console GPU driver responses to oversized instructions or unlinked phi tokens remain unmeasured. Instruction emission enforces the 65,535 word limit (16-bit word count field), and deferred phi patching verifies token registration.

Patch file SHA-256: 31B5364C57CA7C9DA36F9212DECE53E6A5588148FD162D60B867213E9368E7FA

@oneandonlydean
oneandonlydean merged commit 18bb046 into boykopovar:main Nov 2, 2026
14 checks passed
adriadam10 added a commit to adriadam10/AnyPS5 that referenced this pull request Nov 2, 2026
boykopovar#7922 made single-wave wave64 compute span two subgroups by default; main's push build 41428291528 (18bb046) timed out agc_driver_image_table_vouched_lookups at 60 s on lavapipe. Not reproduced locally (submodule fetch fails here); the test pins the previous lowering.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Celegans12 added a commit to Celegans12/AnyPS5-Ghost-of-Yotei that referenced this pull request Nov 13, 2026
…ater writes

Keep faulted wave participants voting instead of returning, while masking
their later writes, atomics and exports. This also preserves the healthy
partner of a two-lane invocation. Retain existing eligibility exclusions.
On the hardware-spanning wave path, keep the lanes active for subgroup
operations and guard byte loads when a lane fault is recorded without
returning from the invocation.

Latch the first guarded SRT fault so later words cannot replace it.
Strengthen host assertions; retain the runtime address and PC oracle.

Based on ThatsLeo/AnyPS5@b9362d8
core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvMemoryInstructions.cpp
(author: ThatsLeo). Adapt the actual-stopping predicate for masked lanes.
No spanned-wave policy from boykopovar#7922 is included.

AI-assisted: yes
Celegans12 added a commit to Celegans12/AnyPS5-Ghost-of-Yotei that referenced this pull request Nov 14, 2026
…ater writes

Keep faulted wave participants voting instead of returning, while masking
their later writes, atomics and exports. This also preserves the healthy
partner of a two-lane invocation. Retain existing eligibility exclusions.
On the hardware-spanning wave path, keep the lanes active for subgroup
operations and guard byte loads when a lane fault is recorded without
returning from the invocation.

Latch the first guarded SRT fault so later words cannot replace it.
Strengthen host assertions; retain the runtime address and PC oracle.

Based on ThatsLeo/AnyPS5@b9362d8
core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvMemoryInstructions.cpp
(author: ThatsLeo). Adapt the actual-stopping predicate for masked lanes.
No spanned-wave policy from boykopovar#7922 is included.

AI-assisted: yes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agc libSceAgc* build docs perf Performance change shader core/shader

Projects

None yet

Development

Successfully merging this pull request may close these issues.