Skip to content

rdna2spirv: intra-block %vgpr/%sgpr value forwarding - #4518

Open
SweatierKey wants to merge 2 commits into
ItsNotRexed:mainfrom
SweatierKey:feat/reg-load-forwarding
Open

SweatierKey wants to merge 2 commits into
ItsNotRexed:mainfrom
SweatierKey:feat/reg-load-forwarding

Conversation

@SweatierKey

Copy link
Copy Markdown
Contributor

Claim: #4421 (comment).

What changes

  • Intra-block %vgpr/%sgpr value forwarding (Gen._reg_val, default-on in translate()):
    • load_reg(kind, r) returns the cached SSA value for (kind, r) when already loaded or stored earlier in the current basic block (eliminating both the OpAccessChain and OpLoad).
    • store_reg, dst, and v_writelane_b32 continue emitting OpStore to %vgpr/%sgpr (so cross-block readers and dynamic s_movrels/v_movrels reads always see exact memory) and update _reg_val[(kind, r)] to the stored SSA value; dst and v_writelane_b32 also reuse _reg_val for old.
    • Dynamic VGPR writes (v_swaprel_b32, v_movreld_b32, v_movrelsd_b32, v_movrelsd_2_b32) invalidate all "vgpr" entries in _reg_val.
    • _reg_val clears on every OpLabel, x_split, and block boundary in translate().
  • Backwards compatibility: direct Gen() unit-test callers default to cache_regs=False, keeping inline loads inside g.body.
  • Test updates: updates 5 structural IR-tracing helpers (tests/test_translate.py, tests/test_image_load_typed.py, tests/test_rcp_iflag_mods.py, tests/semantic/test_buffer_oob_select.py, tests/semantic/test_buffer_swizzle.py) to also recognize forwarded VGPR/SGPR values (OpStore %vgpr[r] <val> and constant-folded OpBitFieldUExtract), and adds tests/semantic/test_reg_load_forwarding.py.
  • Completely independent of rdna2spirv: hoist constant-index %vgpr/%sgpr OpAccessChain to %entry (SHADER-789) #4440 (SHADER-789), rdna2spirv: cache per-block %active loads and fast-path no-EXEC dst() writes #4473 (SHADER-796), spirv_opt: sound dominator-tree SPIR-V optimizer (#884) #2298 (--opt), rdna2spirv: f32 constants are module-scope OpConstants, not a bitcast at each use (-2.4% SPIR-V) #4391 (Gen.fconst), and tof/tou round-trip folding (and synergizes with tof/tou by exposing cross-instruction bitcast chains).

Measured impact (spirv-as + spirv-val --target-env vulkan1.2)

Benchmark Before (03b09a08) After Delta
Divergent loop (2.5k RDNA2 insns, 40 s_cbranch_execz blocks) 35,738 lines / 631,184 B .spv / ~7,800 reg loads 23,865 lines / 421,728 B .spv / 925 uint loads −33.2% lines, −33.2% .spv bytes, spirv-val 34→24 ms
Straight-line ALU (1k v_fma_f32) 16,264 lines / 296,540 B .spv / ~4,000 reg loads 9,280 lines / 172,828 B .spv / 48 uint loads −42.9% lines, −41.7% .spv bytes, spirv-val 14→8 ms
234 real GPU-harness .asm fixtures (runtime/test/shaders/*.asm) 362,312 lines (234/234 valid) 340,890 lines (234/234 valid) −21,422 lines (−5.9% incl. headers/prologues)

Verification (Linux CPU, Python 3.13.5, LLVM 18.1.8, SPIRV-Tools, no game files)

  • tests/semantic/test_reg_load_forwarding.py: 6/6 OK (32-lane divergent run_wave with s_and_saveexec_b32/v_writelane_b32/self-aliasing, divergent loops, v_movreld_b32 + v_swaprel_b32 invalidation, v_movrels_b32/s_movrels_b32 coexistence, --wave64-emulate validation, direct Gen() default).
  • tests/test_translate.py: 343/343 passed (1 skipped, 0 failed) + 234/234 GPU .asm fixtures validated with spirv-val --target-env vulkan1.2 (1 pre-existing LLVM 18 operand error on ps_sdwa_f16_const, identical to 03b09a08).
  • Full tests/semantic suite (7,456 tests): zero new failures vs 03b09a08; tests/test_semantic_translator_use.py: 3/3 OK; all 74 non-pytest translator/SPIR-V tests/test_*.py: 74/74 passed.
  • git diff --check clean.

AI-assisted.

@Kam471 Kam471 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.

Ran this at c31262e3 on Windows 11: tests/semantic/test_reg_load_forwarding.py -> 6 tests, OK; compileall and git diff --check clean.

The translator forwards %vgpr/%sgpr values within a block (updating the tests that depended on the old repeated loads), and the new forwarding cases plus the affected suites pass. No blocking issue.

@tylerstraub

Copy link
Copy Markdown
Contributor

Replying to @SweatierKey.

Register forwarding preserved the full GPU readback in two cases on Linux, RTX 5090 (driver 595.99.02, subgroup 32), at c31262e37f7bdbc803b10ec35fbf7551cd2cfcfe. I compared the submitted translator with a control built from the same head with only Gen(stage, cache_regs=False) changed in translate(). All four modules passed spirv-val.

Fixture What the readback checks SPIR-V bytes, forwarding off → on
cs_movrelsd_2, native wave32 The relative writes put 33 in v4 and 1717 in v25, while v15 retained 1515. 19,732 → 19,444
cs_w64x_writelane, wave64 emulation Upper-half writes and cross-half reads returned the expected words, including 2748 in lane 32 and zero in the two untouched neighbors of lane 40. 26,144 → 25,740

For each fixture the eight expected words matched, and the entire output buffer was byte-identical with forwarding on and off.

AI-assisted.

@CuteBooty

Copy link
Copy Markdown

I ran cs_w32_lane_wrap on an RTX 3070 (driver 617.14, subgroup size 32), comparing base 03b09a08 with head c31262e3. The native wave32 lane-wrap fixture returned all four expected words on both revisions. The GPU readback was 25 16 777 777 in both runs.

In the head disassembly, both lane shuffles immediately following v_writelane_b32 consume the same selected value written to v10. Across this fixture, indexed vector-register loads fell from 25 to 11, scalar-register loads from 21 to 19, and the SPIR-V binary from 13,008 to 12,452 bytes. Both modules passed spirv-val, and the validated binaries matched the ones dispatched.

The fixture and official runner were byte-identical across revisions. Both runs used the same vk_compute_test build (a4fb7f3a), Windows 11, CPython 3.14.10, LLVM 23.1.5, and SPIRV-Tools 2026.4. Codex-assisted, synthetic shader only.

@theswiss24

Copy link
Copy Markdown

Tested c31262e3 (contains main 03b09a08) on NVIDIA GeForce RTX 2060 SUPER (Turing), driver 580.178.04, Ubuntu 24.04.5, llvm-mc 20.1.2, with test programs built from main 03b09a08 (this PR changes no C++): pass.

  • LEONIDA_W64_EMULATE=1 python3 -I scripts/run_gpu_tests.py --build <main build>: 195/210 passed, 15 skipped, 0 failed, the same result on every test as main.
  • For SHADER-774, the effect on the corpus's largest compute module (~89k RDNA2 instructions), from my own copy. Sizes only; each translates and passes spirv-val:
tree native --wave64-emulate
main 03b09a08 29,384 KB 29,841 KB
#4473 aa813789 28,456 KB (−3.2%) 28,949 KB (−3.0%)
this PR c31262e3 26,686 KB (−9.2%) 27,143 KB (−9.0%)

This PR and #4473 don't merge cleanly with each other (conflict in tools/rdna2spirv.py), so I couldn't measure the two together. No game data beyond counts.

Tested and written by Claude (Claude Code), posting from @theswiss24's account.

@whattheflop whattheflop 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.

AI-assisted independent Windows CPU check at c31262e3, base 03b09a08, with a disposable integration of #4473 aa813789 and #4510 7ea906d5. uv CPython 3.12.13, synthetic shaders only.

  • Five defined probes were bit-exact across main, the PR and the combined tree. The diamond/backedge case matched all 32 lanes, and a masked-lane case exercised all four dynamic VGPR writers while preserving lane 7. All 15 modules passed spirv-val --target-env vulkan1.2.
  • The same float chain assembled to 12,836 bytes on main, 9,660 on this PR and 7,420 combined. The combined tree removed 38 cross-instruction bitcast round trips attributable to forwarding. Disabling forwarding in the combined tree removed that opportunity and raised size to 10,692 bytes with identical outputs.
  • #4510 applied cleanly. #4473 required reconciling ten hunks in tools/rdna2spirv.py: constructor signature and fields, emit, x_split, translate setup and five reset sites. Keeping both caches' initialization and resets passed the six forwarding, six EXEC-cache and two bitcast tests.
  • The combined v_mad_i16 and D16 SINT-store probes both exercised signed inputs to tou() and neither reached a signed inversion through tof().

@ligmaSec ligmaSec left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

I tested c31262e3 against its parent 03b09a08 on Linux with Mesa 26.1.6 RADV (GFX1201 via Mesa's DRM shim). These measurements cover cold pipeline creation and use synthetic RDNA2 only. I used the same native vk_pipeline_check executable for every run, a fresh process per sample, one worker, and MESA_SHADER_CACHE_DISABLE=true.

Synthetic compute workload Translator SPIR-V bytes Pipeline creation, median (range)
1,024 chained v_fma_f32 Main 305,040 31 ms (30–40 ms)
1,024 chained v_fma_f32 #4518 177,992 24 ms (19–42 ms)
128 dynamic buffer_load_format_x loads Main 521,036 7.05 s (6.98–7.77 s)
128 dynamic buffer_load_format_x loads #4518 514,344 7.45 s (7.06–7.98 s)
128 dynamic buffer_load_format_x loads Single-component decoder prototype 491,336 0.41 s (0.40–0.46 s)
128 dynamic buffer_load_format_x loads #4518 plus prototype 484,644 0.44 s (0.39–0.45 s)

Five samples per FMA variant and three per typed-load variant. Each module passed spirv-val and created its pipeline successfully. Register forwarding reduced the FMA binary by 41.7%. The small, overlapping timing ranges make the FMA result inconclusive for compile time. On this typed-load fixture, the decoder change accounts for the large speedup. It applies cleanly on top of #4518 and keeps the compile time in the same range.

On #4518 alone the six forwarding tests and 156 buffer semantic tests pass with SPIRV-Tools required. With the decoder patch applied, the six forwarding tests and 157 buffer tests pass. The decoder differential also matches all 5,120 reference words bit-for-bit on that combined tree.

AI-assisted. No game files or physical GPU required for this check.

Larger synthetic cases

  • 512 dynamic single-result typed loads. Main and #4518 both hit a 100-second timeout. The decoder prototype compiled in 3.40 s and the combined tree compiled in 4.27 s. One run per build with an 8 GiB address-space limit, otherwise the same compiler and cache settings. All four modules passed spirv-val.
  • 2,048 integer multiply/add pairs under a partial EXEC mask. The observable value depends on a push-constant multiplier and the lane ID. #4518 reduces the binary from 744,744 to 384,296 bytes. Cold RADV pipeline creation went from a median 119 ms (119–138 ms) to 98 ms (93–101 ms), three samples per build. For synthetic chains of 128, 512 and 2,048 pairs, all 64 output words per dispatch matched a CPU reference on llvmpipe with both builds, including the 35 inactive lanes that retained their original values.

@chpeu

chpeu commented Nov 23, 2026

Copy link
Copy Markdown

Tested c31262e3 (main is an ancestor, no rebase needed) on Linux, no game files. The GPU suite is clean, but
the pytest translator suite fails 17 more cases than on main here
— measured minutes apart on the same box.

What is fine:

  • GPU: LEONIDA_W64_EMULATE=1 python -I scripts/run_gpu_tests.py --build runtime/build/linux --llvm-mc /usr/lib/llvm-20/bin/llvm-mc
    → 195/210 passed, 15 skipped, 0 failed on the RTX 3080 (driver 615.71.09), same as main; without the
    variable 164/210, 46 skipped on both.
  • Semantic folder: python -m unittest discover -s tests/semantic → 7462 tests, 8 failures, 2 errors on your
    branch vs 7456, 8 failures, 2 errors on main — same failing names (the test_loop_ballot_barrier wave64-emulate
    set, two test_cmp_class_f64.test_rejected_forms, two test_mutations anchors already handled in tests/semantic: re-anchor the v_mul_legacy_f32 mutation after the flush change #3883,
    test_anchors_match_crlf_translator_copies, and test_fma_khr where this box's Ubuntu spirv-as does not know
    FMAKHR). Your +6 tests are in the count.
  • python -m compileall -q make_game.py tools tests: clean.

What breaks: the 28 pytest-marked files as CI's translator-tests job runs them:

All 17 new failures are in one file, tests/test_cube_sample.py. Control run on this machine, that file alone:
main → 18 passed; your branch → 17 failed, 1 passed. The failure shape is the test's little SPIR-V
evaluator meeting a value it does not model, e.g.

tests/test_cube_sample.py::test_2d_array_coordinates_are_unchanged
>   assert sample_coords(spv, {4: 0.625, 5: 0.25, 6: 9.0}) == [0.625, 0.25, 9.0]
E   AssertionError: unexpected OpSelect in the coordinate

so the forwarding now leaves an OpSelect (and, in another case, a forwarded temporary %t3 where the evaluator
expects an OpLoad from %vgpr[...]) in the cube / 2D-array coordinate chain. Whether that means the generated
code changed in a way you did not intend for sampling coordinates, or only that the test evaluator has to learn the
new forwarded shape, is yours to judge — what I can state is that the suite is red on this head and green on main
for the same 18 cases.

Also fine on their own: tests/semantic/test_reg_load_forwarding.py 6 tests OK, tests/test_image_load_typed.py
21 OK, tests/test_rcp_iflag_mods.py 5 OK, and the semantic files test_buffer_oob_select.py 36 OK /
test_buffer_swizzle.py 9 OK.

RTX 5080 not run (186 MiB free, another job holds it). Machine: Linux Mint 22 (Ubuntu 24.04 base), llvm-mc 20.1.2,
SPIRV-Tools 2025.1~rc1, GCC 13.3, Python 3.12.3 with pytest 9.2.0 and numpy 2.5.5, built with
cmake -S runtime -B runtime/build/linux -DLEONIDA_VULKAN_HEADERS_FETCH=ON. AI-assisted testing, output read
through by hand.

@Atomic258

Copy link
Copy Markdown

Tested c31262e37f on Linux, Python 3.10, CPU only, synthetic fixtures, no game files: pass.

  • python -m unittest discover -s tests/semantic -p test_reg_load_forwarding.py → 6/6; test_buffer_oob_select.py → 36/36; test_buffer_swizzle.py → 9/9.
  • pytest: tests/test_translate.py, tests/test_rcp_iflag_mods.py, tests/test_image_load_typed.py → 24 passed, 587 skipped (platform/optional-dependency skips), 63 subtests passed.
  • Negative control on main's tools/rdna2spirv.py: test_reg_load_forwarding 1 failure, so the forwarding cases discriminate.
  • git diff --check and check_no_game_data.py clean.

AI-assisted (Devin).

@bobcatchris

Copy link
Copy Markdown
Contributor

Apple M2 no-regression check at head c31262e (macOS 26.4, MoltenVK 1.4.2 direct, subgroup 4..32, llvm-mc 23.1.6, clean full build exit 0).

python -I scripts/run_gpu_tests.py --build runtime/build/linux: 213 shaders translated, 213 pass spirv-val; 127/210 passed, 76 skipped, 7 failed — identical to upstream/main aa2988c on this M2, with the same seven known MoltenVK expected failures. No new failure or skip from the value-forwarding change. Head fetched read-only, no rebase/edit/push. Synthetic shaders and counts only; no game files.

AI-assisted.

@SweatierKey

Copy link
Copy Markdown
Contributor Author

Thanks @chpeu for catching the tests/test_cube_sample.py failure! Pushed fix in c5e6dafd:

  • Because intra-block forwarding now passes the dst() active-lane guarded OpSelect %uint <active> <val> <old> directly into the coordinate chain instead of re-loading from %vgpr, sample_coords() in tests/test_cube_sample.py now evaluates OpSelect whose condition is OpLoad %bool %active (or %true) to its active-lane operand a[2], while still rejecting any unexpected OpSelect in the coordinate math itself.
  • Verified: tests/test_cube_sample.py 18/18 passed (0 failed), plus test_reg_load_forwarding.py (6/6), test_buffer_oob_select.py (36/36), test_buffer_swizzle.py (9/9), test_image_load_typed.py (21/21), test_rcp_iflag_mods.py (5/5), and the remaining pytest translator suites clean (0 regressions vs 03b09a08).

@mrbean56

Copy link
Copy Markdown

Independent check of the current head c5e6dafd on AMD Radeon RX 7800 XT (RADV NAVI32, Mesa 25.0.7, Debian 13, Vulkan 1.4.309), LLVM 19 llvm-mc: no regression found, CPU or GPU.

  • pytest tests/semantic -q: 10 failed, 7,459 passed, 1 skipped, 1 xfailed, 55,600 subtests. The 10 are the base's known set: the same five files at 03b09a08 give the same 11 failed / 64 passed / 80 subtests (the 11th lives outside tests/semantic), and the failing IDs and subTest names are identical on both trees (test_fma_khr 1, test_cmp_class_f64 2, test_loop_ballot_barrier 5, test_mutations 2, test_u16_high_half 1). So the 17 extra test_cube_sample failures @chpeu caught are indeed fixed by c5e6dafd.
  • Full GPU suite on the same board, PR head vs pristine main: both 194/210 passed, 15 skipped, 1 failed, and the one failure is the same documented RADV/NIR bug in both (cs_signed_zero_nan out[5] = 0, docs/testing.md GPU test results (one comment per GPU and driver) #166/Translator: declare SignedZeroInfNanPreserve so drivers keep NaN, inf and -0 (SHADER-99) #664 — present on Mesa 25.0.7 too). Nothing in the forwarding change moves a GPU result, including cs_w32_lane_wrap, cs_store, the buffer/typed suites and the texture/sampler/bindless tests.
  • Commands: python3 -I scripts/run_gpu_tests.py --llvm-mc /usr/lib/llvm-19/bin/llvm-mc --build <ninja Release> --work <dir> with the six harness binaries built; pytest tests/semantic -q for the CPU side.

AI-assisted.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.