Skip to content

rdna2spirv: a bitcast back to a value's original type is the original id (-1.4% SPIR-V) - #4510

Closed
mrp1no wants to merge 5 commits into
ItsNotRexed:mainfrom
mrp1no:shader-bitcast-round-trips
Closed

mrp1no wants to merge 5 commits into
ItsNotRexed:mainfrom
mrp1no:shader-bitcast-round-trips

Conversation

@mrp1no

@mrp1no mrp1no commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

New SHADER item. Claim: #4421 (comment)

Gen.tof/Gen.tou emitted a second OpBitcast to turn a value back into the type it had just been bitcast from. It happens when a register is read as float and then flushed (flush_f32 reads the float's bits), when a float result is stored back, and so on. On a 133-shader corpus sample, bitcasts are 14% of all body lines, and 1.9% are such round trips.

Commits

  1. rdna2spirv: Gen.bitcast_from maps each tof/tou result to its source, and the reverse bitcast returns that source.

    • This is always valid SSA: wherever the result is usable, its source is too, because the result's own definition uses it.
    • The keys are only ids that tof/tou just made, never module-scope constants, so nothing crosses a function.
  2. tests/semantic/test_bitcast_round_trip.py checks two things:

    • the helpers return the source without emitting a reverse bitcast;
    • a translated module with a v_mad_f32 and a v_mul_legacy_f32 has no OpBitcast whose operand is a bitcast from the same type.

    main's translator emits five such round trips in that module, and the test fails there.

Measured on my own 1.0.2.1 corpus (shard 0/40, counts only)

main 03b09a08 this PR
translated / spirv-val 663 / 663 663 / 663
total SPIR-V 500.1 MiB 492.9 MiB (−1.4%), 624 modules smaller (median −1.0%, up to −2.6%)

Semantic suite: 7,458 tests. The only failures are the ones main already has: test_loop_ballot_barrier (5), test_cmp_class_f64 (2), and test_mutations' legacy anchor (2, fixed by #3883).

Independent of #4345, #4391, #4477 and @SweatierKey's %active reuse item. Each one removes a different redundancy, so the savings add up. AI-assisted (Claude Code).

🤖 Generated with Claude Code

mrp1no and others added 2 commits November 23, 2026 02:40
Gen.tof/Gen.tou emitted a second OpBitcast to turn a value back into the
type it was bitcast from: a register read as float and then flushed
(flush_f32 reads the float's bits), a float result stored back, and so on.
On a 133-shader corpus sample bitcasts are 14% of body lines, and 1.9%
are such round trips.

Gen.bitcast_from maps each tof/tou result to its source, and the reverse
bitcast returns the source. Always valid SSA: wherever the result is
usable its source is too, since the result's own definition uses it.
Keys are only ids tof/tou just made, never module-scope constants.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
test_bitcast_round_trip.py checks that tof/tou return the source for the
reverse bitcast without emitting one, and that a translated module with a
v_mad_f32 and a v_mul_legacy_f32 has no OpBitcast whose operand is a
bitcast from the same type. main's translator emits five such round trips
in that module.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@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 7ea906d5 on Windows 11: tests/semantic/test_bitcast_round_trip.py -> 2 tests, OK; compileall and git diff --check clean.

tof/tou now reuse the original id when a bitcast returns to the source type, and the new cases verify no round-trip bitcast is emitted; the source's definition dominates every later use, so no dominance is lost. No blocking issue.

@CaravelaLabs

Copy link
Copy Markdown
Contributor

Automated test: 7ea906d5 merged onto main 03b09a08 on AMD Radeon 8060S (RADV GFX1151, RDNA 3.5), Mesa 25.2.8, Ubuntu 24.04, runtime rebuilt from this branch in a clean sandbox. Result: pass.

  • scripts/run_gpu_tests.py: 192/209 passed, 15 skipped (plain main: 192/209 passed, 15 skipped).
  • Python tests this PR touches: 2 passed.

Same machine and setup as my earlier manual reports. AI-assisted (Claude Code).

@Atomic258

Copy link
Copy Markdown
Contributor

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

  • python -m unittest discover -s tests/semantic -p test_bitcast_round_trip.py → 2/2 pass.
  • Negative control on main: 2/2 fail (no bitcast_from round-trip), so the tests discriminate.
  • Read: tou(tof(u))/tof(tou(f)) return the original id; dominance argument holds since the bitcast's own definition uses the source. No behavior change beyond fewer OpBitcasts.
  • Full semantic suite not run here (LLVM/spirv-tools absent); translator unit path only.

AI-assisted (Devin).

@kapitche

Copy link
Copy Markdown
Contributor

Tested 7ea906d merged with main 03b09a0 on Linux (WSL2), Python 3.12.16: pass. tests/semantic/test_bitcast_round_trip.py 2 tests OK. The whole tests/semantic directory (366 files, one unittest discover -p run each) gives 362 OK; the 4 that fail (test_cmp_class_f64, test_loop_ballot_barrier, test_vcmp16_opsel, test_mutations) fail with identical counts on main (2 / 3F+2E / 1E / 2F), so they are not from this change. Negative control: tools/rdna2spirv.py restored from main with the PR test kept -> FAILED (failures=2). Not run: spirv-val over the translated output. Diff read, one observation rather than a bug: bitcast_from is not keyed by type, so tof(tou(x)) returns x as is. Two existing callers feed tou an %int value (self.tou(self.i16_half(...)) in the v_mad_i16 path and the d16 tbuffer path); there the result is used directly and never goes back through tof, so nothing breaks today, but a future tof(tou(int_id)) would hand back an %int id as a float.

@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 of 7ea906d5 against 03b09a08, plus a clean scratch merge with #4473 aa813789. uv CPython 3.12.13, Vulkan SDK 1.4.363.0, synthetic fragment shaders only.

  • All 1,006 cases that translated had bit-identical mrt0 output across the three trees, including signed zero, denormals, infinities and NaN payload inputs. All three rejected the same 18 multiply-with-clamp cases at the existing undefined FClamp check.
  • A separate 16-module sample assembled and passed spirv-val --target-env vulkan1.3 in all three trees. OpBitcast count fell from 456 to 399 in both the PR and the combined tree.
  • The existing %int inputs to tou() in signed d16 packing and v_mad_i16 feed integer consumers. I found no current route from those result IDs to tof(). A future such route would need to preserve the float destination type instead of reusing the signed source ID.

@mrbean56

Copy link
Copy Markdown

Tested 7ea906d543 on Linux (Debian 13), Python 3.13.5: pass, and the guard has teeth.

  • pytest tests/semantic/test_bitcast_round_trip.py -q: 2 passed.
  • Mutation: removing the if u in self.bitcast_from: return self.bitcast_from[u] early return from Gen.tou makes test_helpers_return_the_source fail, so the unit half pins the round trip.
  • Non-vacuous: the translated PS module contains 33 OpBitcast and zero chained ones, so back == [] is a real observation, not an empty set. mrt0_words still returns the 4 expected words.
  • The SSA argument in the docstring holds: the source dominates every use of the cast's result, so substituting it cannot create a use before definition. bitcast_from is populated on both directions, so tof(tou(u)) also returns u.

No GPU, no game data. AI-assisted.

tou remembers its argument so that tof can hand it back, which is only right when that argument is a %float.
v_mad_i16 and the signed d16 buffer store passed the %int halves from i16_half; nothing bitcast those results back
yet, but a later tof would have been given the %int as a float (@whattheflop's review). They now use int_bits, a
plain bitcast with no memo, and tof/tou say what they take. The new test checks the type of every tof/tou argument
in a module with v_mad_i16 and fails without the change; a corpus sample (133 shaders, 716,716 calls) already held it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@mrp1no

mrp1no commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

@whattheflop Thanks, good catch. Fixed in 59dd5ceb:

  • v_mad_i16 and the signed d16 buffer store now turn their %int halves into bits with a new Gen.int_bits. It is a plain bitcast with no memo, so tof can never be handed an %int.
  • tof/tou now document their argument types.
  • A new test, test_tou_takes_a_float_and_tof_a_uint, wraps both helpers while translating a module with v_mad_i16 (with and without op_sel and clamp), v_mad_u16 and v_mad_f32. It checks the defined type of every argument.
    • It fails without the change: six ('tou', 'int').
    • On my 1.0.2.1 sample (133 shaders, counts only) all 716,716 tof/tou calls already had the right type, so the output is unchanged.
  • The semantic suite shows only main's known failures, plus test_vcmp16_opsel's spirv-val step, which fails identically without this commit because my shell lacks the tool on PATH.

AI-assisted (Claude Code).

@tylerstraub

Copy link
Copy Markdown
Contributor

Replying to @mrp1no.

Confirmed the signed D16 buffer-store caller in 59dd5cebf411c6af255d5ba6de8cf1191fc60b1b. I exercised the new test’s bitcast_arguments probe with buffer_store_format_d16_x v1, off, s[4:7], 0 and a runtime descriptor. The parent translator (7ea906d5) passed an %int to tou once in 14 calls. On the fixed head all 13 calls had the declared argument type. This store listing would also work as a regression case alongside the existing arithmetic listing.

For the GPU check I set the descriptor to 32_SINT and stored from v1 = 0x4321fffd. Both translators produced Vulkan 1.2-valid modules. On Linux RTX 5090 (595.99.02), both wrote 0xfffffffd (−3), and all 63 other buffer words retained the fill value. The helper trace distinguishes the fix even though the GPU output for this store was already correct.

AI-assisted.

…nd trip

test_volume_address_operands (a16), test_explicit_mip_depth_compare (a16) and test_rcp_iflag_mods' source-modifier
chain walked an f32 through `OpBitcast %uint` and back to `OpBitcast %float`. That round trip is now the original id,
so the a16 coordinates and LOD are the UnpackHalf2x16 component itself, and a modified source feeds OpFDiv directly.
The checks now skip bitcasts (or, for the modifiers, require none) on the way to the same source. tests/ outside
tests/semantic now fails exactly as main does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@mrp1no

mrp1no commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Follow-up: I had run only tests/semantic on this branch. The rest of tests/ had three structural checks that walked an f32 through the round trip this PR removes:

  • test_image_load_typed.py::test_volume_address_operands (a16, 2 subtests)
  • test_translate.py::test_explicit_mip_depth_compare[*-a16] (2)
  • test_rcp_iflag_mods.py's source-modifier chain (6 subtests)

The output was right in each case. The a16 coordinates and LOD are now the UnpackHalf2x16 component itself, and a modified source feeds OpFDiv directly. The latest commit updates the checks to follow the value to the same source without the round trip; for the modifiers they now require that no bitcast is left.

pytest tests --ignore=tests/semantic -n 10 now gives the same 8 failures as main (test_build_llvm_mc_batch, test_meta_to_xml_paths, test_check_no_game_data, test_u16_high_half, each with an open fix). No translator change. AI-assisted (Claude Code).

@Kev-Ball

Copy link
Copy Markdown

Tested e3914247 on an NVIDIA GeForce RTX 3080 Ti (32-lane subgroups), driver 620.73.04, CachyOS Linux 7.3.5-2-cachyos. I rebuilt the Vulkan harnesses from this revision and selected the NVIDIA device explicitly.

Ran the full default-mode scripts/run_gpu_tests.py --build runtime/build/linux --require-pass suite on this head: 164/210 passed, 46 skipped, 0 failed. This checks the Vulkan output on Ampere; the run used the synthetic suite.

AI-assisted verification with synthetic inputs.

@lunarminus

Copy link
Copy Markdown

Tested e3914247 merged onto main d0835dd9 on an AMD Radeon 760M (RDNA3 iGPU, gfx1103, subgroup 32..64), RADV Mesa 26.3.1, CachyOS Linux: pass

  • Merges cleanly. The PR only touches tools/rdna2spirv.py and tests, so the runtime test programs are the d0835dd9 build.
  • python -I -m unittest discover -s tests/semantic -p test_bitcast_round_trip.py: 3/3 OK. Negative control: the same file against the d0835dd9 translator fails 3/3.
  • pytest tests/test_image_load_typed.py tests/test_rcp_iflag_mods.py tests/test_translate.py: 607 passed, 4 skipped, 70 subtests passed.
  • Full tests/semantic (with spirv-val, spirv-as and llvm-mc on PATH): 7459 tests. 7 failures and 2 errors, the same set as d0835dd9 without the PR (7456 tests): test_loop_ballot_barrier, test_cmp_class_f64, and test_mutations' v_mul_legacy_f32 anchor.
  • scripts/run_gpu_tests.py, native and LEONIDA_W64_EMULATE=1: 196/210 passed, 14 skipped in each mode. The per-test PASS/FAIL/SKIP results match d0835dd9 without the PR in both modes, with no differences and no FAIL.

AI-assisted (Claude Code).

@sperm

sperm commented Nov 23, 2026

Copy link
Copy Markdown

Tested e391424 (a re-test at the new head) on AMD Radeon RX 9070 XT (RADV GFX1201) and the Ryzen 7 9800X3D iGPU (RADV RAPHAEL_MENDOCINO, gfx1036), Mesa 26.2.6, Linux 7.3.4: pass, no regressions.

  • Full python -I scripts/run_gpu_tests.py (Linux build of this branch's runtime/, LEONIDA_VK_DEVICE per GPU): 196/210 passed, 14 skipped, 0 failed on both GPUs, with every test's result the same as at the merge base 03b09a0.
  • tests/test_image_load_typed.py: 21 OK. tests/test_rcp_iflag_mods.py: 5 OK. tests/test_translate.py: 581 passed, 4 skipped.
  • python -m unittest discover -s tests/semantic: 7459 run, 7 failures and 2 errors. That is main's known set at 03b09a0 (test_cmp_class_f64, test_mutations, test_loop_ballot_barrier). The PR adds none.
  • Note: main has moved 917 commits past that merge base, so this doesn't cover the branch merged onto current main.

No game files. AI-assisted.

It sat between self.consts and self.n, the lines ItsNotRexed#4391 also adds to, so the two PRs conflicted there whichever
merged second. No change in behaviour.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
mrp1no added a commit to mrp1no/Leonida that referenced this pull request Nov 23, 2026
It made one with Gen.__new__ and set only the attributes fconst used. The fallback for -0, subnormals, inf and NaN
calls tof, so once tof keeps state of its own (ItsNotRexed#4510's bitcast_from) that Gen lacked it and the test failed on the
merge of the two PRs. Gen("ps") has every attribute; the uses_fhalf check reads its initial False.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@mrp1no

mrp1no commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Merge-order note: #4391 and this PR added lines next to each other in Gen.__init__, so whichever merged second conflicted. bb4548f9 moves bitcast_from below self.inputs, and the two now merge cleanly. On a scratch merge of both onto main 0db7fed5, their tests pass together (test_bitcast_round_trip, test_module_float_constants, test_rcp_iflag_mods, test_translate, test_image_load_typed, test_f64_conversion). For that, #4391's fconst test now builds a whole Gen (06218d94). I also checked each of my five translator PRs (#4345, #4391, #4477, #4510, #4633) against the others and against #4473/#4518: git merge-tree is clean for every pair. AI-assisted (Claude Code).

@SweatierKey

Copy link
Copy Markdown
Contributor

Tested bb4548f9 on Linux (x86_64, Python 3.13.5, SPIRV-Tools on PATH, CPU/no-GPU): pass (code read + unit tests + spirv-val).

What I ran:

  • git diff --check main...HEAD: clean.
  • PYTHONPATH=tests/semantic python3 -m unittest -v tests/semantic/test_bitcast_round_trip.py tests/test_image_load_typed.py tests/test_rcp_iflag_mods.py (with LEONIDA_REQUIRE_SPIRV_TOOLS=1): 29/29 OK.
  • tests/test_cube_sample.py: 18/18 OK.

Code review:

  • Caching self.bitcast_from[f] = u in tof() and self.bitcast_from[u] = f in tou() while routing %int → %uint bitcasts (signed d16 packing and v_mad_i16) through the new int_bits() helper cleanly prevents a %int source ID from ever leaking back through tof() as a %float.
  • Initializing self.bitcast_from right after self.inputs in Gen.__init__ is clean and dominance-safe since any lookup key is dominated by its source.

@gertify

gertify commented Nov 23, 2026

Copy link
Copy Markdown

Tested bb4548f (the current head) on Ubuntu 24.04, Mesa 25.2.8 ANV, Intel UHD 630: tests/test_translate.py passes, 581 passed and 4 skipped. The GPU suite was not rerun on this head. AI-assisted.

@sebashord

Copy link
Copy Markdown

Tested bb4548f91e8a43d9aac75799d2294e7553029854 (the current head) on Windows 11 Pro build 26300.9974 with two GPUs: Radeon iGPU of a Ryzen 7 9800X3D (gfx1036, 0x1002:0x13c0, AMD proprietary driver 25.10.36, subgroup 32..64) and RTX 5070 Ti (driver 621.01, subgroup 32..32): pass, every GPU result is identical to the base 03b09a08. This adds the AMD Windows driver and an RTX 50 card at the current head.

GPU suite (python -I scripts\run_gpu_tests.py --build runtime\build --require-pass, one GPU at a time)

Device Base 03b09a08 This head
Radeon iGPU, 25.10.36, native wave64 195/210 passed, 15 skipped, 0 failed 195/210 passed, 15 skipped, 0 failed
RTX 5070 Ti, 621.01, native 164/210, 46 skipped, 0 failed 164/210, 46 skipped, 0 failed
RTX 5070 Ti, LEONIDA_W64_EMULATE=1 195/210, 15 skipped, 0 failed 195/210, 15 skipped, 0 failed

In each of the three configurations all 210 result lines (status and output words) are the same for base and head, and the 83 raw\*.raw files the suite leaves in its work folder are byte-identical (SHA-256).

Fuzzer on the Radeon: python -I tools\valu_fuzz.py --family f16 --seed 1 --programs 300 --wave 32 --build runtime\build gives 300/300 match, 0 mismatched, 0 skipped. I stopped at 300 because on this driver seed 1 reaches the known SHADER-777 mismatch at program 534 on this base.

CPU tests (LEONIDA_REQUIRE_SPIRV_TOOLS=1, python -I <file>, all OK): tests/semantic/test_bitcast_round_trip.py (3), tests/test_image_load_typed.py (21), tests/test_rcp_iflag_mods.py (5).

This is the head on its own base, not the scratch merge with #4391.

This PR changes no C++, so I did not rebuild: the test programs are an MSVC 14.44 build of 72cda1f2 (#1976, same base 03b09a08), whose compiled sources differ from this head only in runtime/shims/dxgi_com.cpp, runtime/test/dxgi_swapchain_test.cpp and runtime/CMakeLists.txt. Base and head rows used the same programs.

Not run: tests/test_translate.py (no pytest on this machine), and I did not measure the SPIR-V size change.

Tools: llvm-mc 23.1.6 (conda-forge), Vulkan SDK 1.4.363.0, Python 3.11.9, VK_LOADER_LAYERS_DISABLE=~implicit~.

AI-assisted. Synthetic test programs and counts only, no game files.

Created with Perplexity

@memorypressure

Copy link
Copy Markdown

Verified on the merged tree (main 3faac55): the bitcast identity is sound SSA — the source dominates wherever the result is used — and the %int memo escape via int_bits covers both i16_half sites (grep confirms no tou(i16_half(...)) remains). The new test_bitcast_round_trip passes 3/3 both directly and via discover (class correctly above unittest.main), reworked structural checks in test_image_load_typed (23), test_rcp_iflag_mods (5) and the 596 translate cases pass, and the full 6,248-test semantic suite is green except the five known main reds. The reworked assertions stayed assertive — one is strictly stronger. The -1.4% size claim was not measured here. Checks pending. AI-assisted: yes. Tested on Linux (RTX 5080 host, CPU-only run).

@mrp1no

mrp1no commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Closing: the four commits that change behaviour or tests (3e3eedf2, 7ea906d5, 59dd5ceb, e3914247) are on main as they are. The last one, bb4548f9, only moved the self.bitcast_from = {} line to avoid a textual conflict with #4391. #4391 is now rebased onto 561b65a8 with main's placement, so that commit has nothing left to do.

AI-assisted (Claude Code).

@mrp1no mrp1no closed this Nov 23, 2026
mrp1no added a commit to mrp1no/Leonida that referenced this pull request Nov 23, 2026
It made one with Gen.__new__ and set only the attributes fconst used. The fallback for -0, subnormals, inf and NaN
calls tof, so once tof keeps state of its own (ItsNotRexed#4510's bitcast_from) that Gen lacked it and the test failed on the
merge of the two PRs. Gen("ps") has every attribute; the uses_fhalf check reads its initial False.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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.