Skip to content

Recompiler: simplify direct DXIL binary16, D16, and buffer store lowering - #3650

Open
Kalmarv wants to merge 2 commits into
xcl-dev:mainfrom
Kalmarv:pr/dxil-lower-fp16-mem
Open

Kalmarv wants to merge 2 commits into
xcl-dev:mainfrom
Kalmarv:pr/dxil-lower-fp16-mem

Conversation

@Kalmarv

@Kalmarv Kalmarv commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

Compacts emitted direct-DXIL IR for binary16/float/D16 conversions, formatted buffer stores, and buffer address/bounds lowering across 4 files (+447/-242, 2 commits), without changing RDNA2 rounding, NaN, or bounds semantics.

What is in it

  • Commit 1 — Binary16, float saturation, and normalized D16 lowering (lower_wide.rs, prelude.rs, lower_mem.rs, core_tests.rs):
    • Round default f32_to_f16_rne subnormal magnitudes with a single native RNE add at 0.5 (2^-24 binary32 ulp) and round normal significands with a retained parity bit (51 → 21 SSA ops; -72,820 B across 329 validated shaders).
    • Derive directed f32_to_f16_rm rounding from f32_to_f16_rne by comparing widened unsigned magnitude bits (-13,340 B).
    • Drop redundant IsNaN checks in cvt_u32 (fcmp ule <= 0.0) and f16_rtz (ordered fcmp ogt is already false for NaN and zero halves, also dropping the zero-magnitude guard) (-51,888 B combined; builds on @ramon-victor's Recompiler: drop redundant IsNaN checks in direct DXIL cvt_u32 and f16_rtz #2289, which is currently conflicting on main).
    • Scale normalized D16 buffer loads directly into half-significand units and round with a 32-bit unsigned quotient instead of 64-bit division (-8,544 B).
  • Commit 2 — Formatted store and buffer address/bounds lowering (lower_mem.rs):
    • Pack formatted store components by the actual GFX10 dword layouts instead of scattering every component into all four words (-63,872 B), and rotate dynamic-format four-component stores through one numeric encoder loop (-146,160 B).
    • Select the descriptor-heap window once per fragmented store (-114,308 B) and emit runtime byte-count fragmented stores as a bounded word loop while keeping straight-line stores for constant counts (-77,400 B main, -72,780 B auxiliary dispatch pieces).
    • Share a single remaining byte limit across multiword buffer loads and stores (-10,640 B), check the carried scalar flat-read window validity once (-2,992 B), and reuse the 32-bit lane-stride product in buffer window calculations when IDXEN is clear (-11,248 B).
  • Measured impact:
    • Offline 329-shader DXIL validation sweep (0 validation errors): ~573 KB combined main-shader bitcode savings (~146.6 KB from Commit 1 + ~426.6 KB main / 72.8 KB auxiliary from Commit 2) across the individual before/after measurements on 329 validated shaders.
    • 60 s title smoke (RTX 5070 Ti, 4f39cd191 vs main 1c8b55147): 1267 vs 1387 frames shown (91.3%), 60 60 61 presents per 2 s, peak commit 15112 MB vs 17480 MB (-2368 MB / -13.5%), 0 device removals, 0 crashes.

Tested

  • Hardware & toolchain: NVIDIA GeForce RTX 5070 Ti (driver 610.74), AMD Ryzen 9 9950X, Windows 11 Pro 26200, rustc 1.99.0 (b940084d7 2026-09-28), DXC 1.9.2609.5 (debug + release).
  • scripts/test.ps1 (cargo build --workspace, cargo bench -p xcl --bench '*' -- --test, cargo test --workspace -- --test-threads=4): 2921 passed, 0 failed, 51 ignored across all 43 test targets (24 SKIPPED GPU tests on this adapter: 22 no wave64, 2 no heap windows).
  • New unit/disassembly/validation tests in gpu::dxil::core_tests and gpu::dxil::lower_mem::stage_guard_tests (all passing with DXC 1.9.2609.5 validation).
  • cargo build --release -p xcl: clean (39 warnings, 0 new vs main).

Regression run

Baseline (main):

xcl-smoke v1
commit: 1c8b551475e1e7bfe48f94448492a4c3544a2e0f
gpu: NVIDIA GeForce RTX 5070 Ti
title: ea3b5e4d
seconds: 60
exit: 0x0
frames shown: 1387 (PresentX 1387)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 17480 MB

PR head:

xcl-smoke v1
commit: 4f39cd191811eace5ebd31f3adb8f613b7a9cd9d
gpu: NVIDIA GeForce RTX 5070 Ti
title: ea3b5e4d
seconds: 60
exit: 0x0
frames shown: 1267 (PresentX 1267)
presents per 2 s (last 3): 60 60 61
device removals: 0
crashes: 0
peak commit: 15112 MB

Not tested

  • AMD and Intel GPUs, including native wave64 hardware paths (22 wave64 GPU tests skipped on RTX 5070 Ti).
  • Opt-in XCL_HEAP_WINDOWS=1 GPU tests (2 skipped under default scripts/test.ps1).
  • Full offline precompile timing A/B on main + this PR alone (individual 329-shader corpus byte savings were recorded during the offline validation sweep before cherry-picking).

AI use

  • Codex (GPT-6) wrote the individual binary16/float/D16 and buffer/store lowering improvements and unit tests during the offline DXIL size sweep.
  • Antigravity (Gemini 4 Neon) audited and cherry-picked the main-independent subset onto main, adapted the directed binary16 unit test for inline f32_to_f16_rne, ran cargo build --release, scripts/test.ps1, and the 60 s smoke run, and drafted this description.

Kalmarv and others added 2 commits December 1, 2026 22:30
…lowering

Compact five scalar/half conversion paths in the direct RDNA2 -> DXIL emitter
without changing RDNA2 rounding or NaN semantics:

- Default binary16 RNE (`lower_wide.rs`): round subnormal magnitudes with one
  native RNE addition at 0.5 (2^-24 binary32 ulp) and round normal significands
  with a retained parity bit (51 -> 21 SSA ops, -72,820 B across 329 validated
  shaders).
- Directed binary16 rounding (`lower_wide.rs`): derive directed results from
  the nearest binary16 value by comparing widened unsigned magnitude bits
  (-13,340 B).
- `f16_rtz` and `cvt_u32` (`prelude.rs`): drop redundant `IsNaN` checks and the
  zero-magnitude guard in `f16_rtz` via unordered `<= 0.0` / ordered `>`
  comparisons (-51,888 B combined; builds on @ramon-victor's xcl-dev#2289).
- Normalized D16 buffer loads (`lower_mem.rs`): scale the recovered magnitude
  into half-significand units and round with a 32-bit unsigned quotient instead
  of 64-bit division (-8,544 B).

Combined offline savings: ~146.6 KB across 329 validated shaders (0 validation
errors). Adds disassembly/validation unit tests in `core_tests.rs` and
`lower_mem.rs`.

Co-Authored-By: Codex (GPT-6) <noreply@openai.com>
Co-Authored-By: Antigravity (Gemini 4 Neon) <noreply@google.com>
Reduce emitted DXIL instruction count and container size for buffer accesses
and formatted stores in `crates/xcl/src/gpu/dxil/lower_mem.rs`:

- Formatted stores: pack components by the actual GFX10 dword layouts instead
  of scattering every component into four words (-63,872 B), and rotate dynamic
  format four-component stores through one numeric encoder loop (-146,160 B).
- Fragmented byte stores: select the descriptor-heap window once before
  lowering fragments (-114,308 B), and emit runtime byte-count stores as a
  bounded word loop while keeping straight-line stores for constant counts
  (-77,400 B main / -72,780 B auxiliary dispatch pieces).
- Multiword buffer loads/stores: share one remaining byte limit across dwords
  (-10,640 B).
- Scalar flat reads: check the carried window validity once instead of per
  carry arm (-2,992 B).
- Buffer address windows: reuse the 32-bit lane-stride product when IDXEN is
  clear instead of emitting a wide multiply (-11,248 B).

Combined offline savings: ~426.6 KB main (+72.8 KB auxiliary) across 329
validated shaders (0 validation errors). Adds focused unit/validation tests in
`lower_mem.rs`.

Co-Authored-By: Codex (GPT-6) <noreply@openai.com>
Co-Authored-By: Antigravity (Gemini 4 Neon) <noreply@google.com>
@github-actions github-actions Bot added area:recompiler RDNA2 decoder, HLSL/direct-DXIL recompiler, wave64/wave32 area:tests Unit, integration, e2e tests, or testtitle gpu:amd Code is specific to AMD / RDNA / wave64 GPUs (scope tag; see needs:amd-test) labels Dec 2, 2026
@Kalmarv Kalmarv closed this Dec 2, 2026
@Kalmarv Kalmarv reopened this Dec 2, 2026
@Foniass

Foniass commented Dec 2, 2026

Copy link
Copy Markdown
Collaborator

Review (head 4f39cd1, diff read, not a merge-check):

  • Two separate changes in one PR, and the second commit bundles seven. The PR changes 689 lines, against a target of about 400. Commit 1 changes the binary16 and D16 conversions. Commit 2 changes format packing, the encoder loop, the byte-store loop, the heap-window selection, the multiword bounds, the flat-read carry and the buffer-window product. These are unrelated paths, and each could be reviewed and bisected on its own. Please split it, at least along the two commits.
  • Overlaps Recompiler: outline repeated direct-DXIL helpers into internal functions #3654 and conflicts with it. The new f32_to_f16_rne (lower_wide.rs ~708) is the same instruction sequence as the xcl.f16.rne body in Recompiler: outline repeated direct-DXIL helpers into internal functions #3654 (module.rs ~845). Both PRs change fmt_encode to take the width (lower_mem.rs ~1042), but they remove its four copies in different ways: this PR runs it in a loop (encode_dynamic_components ~1136), and Recompiler: outline repeated direct-DXIL helpers into internal functions #3654 makes it an outlined xcl.fmt.encode call. Both also rework the carried-window check in scalar_flat_read (~1244). The two PRs conflict in core_tests.rs, lower_mem.rs and lower_wide.rs. One of them has to drop these parts. This PR is the smaller place to keep them.
  • Repeats open Recompiler: drop redundant IsNaN checks in direct DXIL cvt_u32 and f16_rtz #2289. The cvt_u32 / f16_rtz change in prelude.rs ~20/~62 is the change from Recompiler: drop redundant IsNaN checks in direct DXIL cvt_u32 and f16_rtz #2289, plus the removal of the zero-magnitude guard. Recompiler: drop redundant IsNaN checks in direct DXIL cvt_u32 and f16_rtz #2289 comes with a GPU value test, and this PR does not. One of the two should be closed, and the test should be kept.
  • The new tests check the shape of the output, not its values. The core_tests.rs tests and most of the lower_mem.rs tests count instructions in the disassembly (one fadd … 0.5, one createHandleFromHeap, one legacyF32ToF16). The only value test of the rewritten RNE and directed conversions is the existing 8-case GPU test (core_tests.rs ~915). It has no NaN payload, ±inf, -0, min-normal boundary, subnormal tie or +inf/-inf mode case. A GPU parity test against the unchanged HLSL f32_to_f16_rm (recomp/emit.rs ~7003) over those cases, in all four modes, would pin the behaviour down. Also, a_fragmented_store_selects_its_heap_window_once (~2934) never calls validate, and it is the only test of the new single heap-window wrapper in st_bytes (~548).
  • The smoke run shows 8.7% fewer frames, and the description does not explain it. It shows 1267 frames against 1387 on the same title. That is above the 80% gate, but the PR adds runtime loops to the default path (dynamic format stores and runtime byte counts, ~607 and ~1136). The description does not say whether the drop is noise. The run was on NVIDIA only.

Fine: By reading, the new RNE sequence matches what main computes. The subnormal rounding through the 0.5 add relies on f32 fadd rounding to nearest even, which round_tests.rs already assumes. Ties, 65520 → inf, the NaN payload and quiet bit, and the sign all match. The directed modes step from the nearest result correctly: overflow gives 0x7BFF or inf, the smallest subnormal is used when rounding away from zero, and NaN and inf are left alone. The D16 UNORM/SNORM 32-bit quotient matches main's 64-bit division for widths 1–16, including y = 0 (FirstbitHi of 0 is -1, so the shift is capped at 24) and y = dmax (the carry gives 0x3C00). The shared byte limit gives the same result for each dword as before, including when the offset wraps. pack_components is tested against every BUF_FORMATS layout, and only the format's bytes are stored. The straight-line and loop forms of the byte store keep the word and spill order and the 16-byte cap. The 32-bit lane × stride product cannot overflow. D16 store packing is unchanged.

AI review: Claude Code (Claude Opus 5.5), posted by Foniass without a human check of each point.

@Foniass

Foniass commented Dec 2, 2026 •

Copy link
Copy Markdown
Collaborator

merge-check
base: 1c8b551
head: 4f39cd1
merge: clean
build: cargo build --workspace -> ok
tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 2921 passed, 0 failed, 51 ignored; SKIPPED: 28 (20 no wave64, 2 no d3d12SDKLayers.dll, 1 no D3D12 debug layer, 1 no heap windows, 1 cannot disable the driver cache, 3 others; the same set as on main); failing: none
review: read by one reviewer at this same head; the review is at #3650 (comment) and its findings stand. Most serious: two changes in one PR; its f16 rounding and fmt_encode work is redone differently in #3654 and repeats open #2289.
performance: 60 s smoke of a retail title, main 1c8b551 vs this merge (4f39cd1): 1652 -> 1424 frames shown (86 %; last presents per 2 s: 61 60 60), peak commit 18228 -> 15835 MB, 0 device removals, 0 crashes. This run is lower than most today: the PC was in use at the time (a browser and Discord running), and main's own runs on this machine today ranged from 1370 to 1652 frames, so the difference isn't clearly from this PR.
verdict: safe to merge as code (no bug found, the suite passes, the smoke run has no crash), but it is two changes in one PR and its f16 rounding and fmt_encode work overlaps open #2289 and #3654, so only one of those should land
hardware / tool and model: RTX 5070 Ti (driver 621.14), Ryzen 7 7800X3D, Windows 11 26300 / Claude Code with Claude Opus 5.5

AI-written and posted by Foniass without a human check of each point.

@github-actions github-actions Bot added needs-2nd-check Has 1 safe merge-check; needs second independent check (#3041) needs:amd-test Needs a test report or merge-check on an AMD GPU labels Dec 2, 2026
@vasanex

vasanex commented Dec 2, 2026 •

Copy link
Copy Markdown

merge-check
base: 1c8b551
head: 4f39cd1
merge: clean (git diff --check clean)
build: cargo build --workspace -> ok
tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 2921 passed, 0 failed, 51 ignored; SKIPPED: 25 (22 no wave64, 2 no heap windows, 1 cannot disable the driver cache), the same tests as on the base (2909 passed there); failing: none. The twelve new tests ran and passed.
review: whole diff read (4 files, +447/-242). No correctness finding. Checked by reading: (1) the new f32_to_f16_rne gives the old results for zero, the tiny range (tie at 2^-25 to zero), subnormals up to the smallest normal, normals with a tie to even and a carry into the exponent, overflow to infinity from 0x477ff000 on, and the NaN payload; (2) the directed modes step the nearest result by one towards or away from zero from an unsigned compare of the magnitudes, which also turns an overflow to infinity into 0x7bff when rounding towards zero and leaves infinities and NaN alone; (3) the normalised D16 quotient: for a code y below dmax = 2^we - 1 the quotient stays inside the binade the shift picks, so exp + sig is right with sig up to 2048, y = dmax gives 0x3c00, y = 0 gives 0 through the capped shift, and adding dmax / 2 before the division rounds to nearest without a tie; (4) FULe and the bare FOGt in cvt_u32 / f16_rtz equal the old guarded forms; (5) the word loop in for_store_words stores the same words, masks and spills as the four unrolled copies, and the rotating encoder returns X, Y, Z, W after four turns; (6) pack_components relies on absent components having width 0, which the all-formats test confirms for the table. One thing a reviewer should know: the old round-to-nearest conversion was integer-only, the new one takes the subnormal significand from one host fadd at 0.5, so it depends on the host adding with round to nearest even; the existing GPU value test passes on this card, and there is no wider value test (as the review above says). The overlap with #3654 and #2289 named there stands; I did not test the combinations. The wave64 paths did not run here (wave32 card).
performance: the default path gets a loop for runtime-sized byte stores and runtime formats in place of four unrolled copies. 60 s smoke, release, same title and settings, machine otherwise idle: base 1608 frames, peak commit 19911 MB; merged tree 1698 frames, 17980 MB (90 %), presents 61 60 60, 0 device removals, 0 crashes. So the 86 % of the first check does not show here. Not measured: translation time and shader size.
verdict: safe to merge
hardware / tool and model: NVIDIA GeForce RTX 3080 10 GB (driver 621.40), AMD Ryzen 9 7950X, Windows 11 Pro 26200, rustc 1.100.0 / Claude Code with Claude Fable 5.2. Run and posted without a human check of each point.

@github-actions github-actions Bot added ready-to-merge Has 2 independent safe merge-checks on current head (#3041) and removed needs-2nd-check Has 1 safe merge-check; needs second independent check (#3041) needs:amd-test Needs a test report or merge-check on an AMD GPU labels Dec 2, 2026
@Kalmarv

Kalmarv commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @Foniass and @vasanex for the review and merge-checks! Leaving 4f39cd191 untouched while ready-to-merge is set; we will drop the overlapping f16 RNE / fmt_encode / scalar_flat_read hunks from #3654 when rebasing #3654 onto main so only one PR carries them (and note #2289's GPU value test can be kept as a follow-up or folded in if preferred).

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

Review of 4f39cd19: 1 finding(s) (1 medium), most severe first.

  1. Medium crates/xcl/src/gpu/dxil/prelude.rs:21: Not certain about this one, since it depends on how drivers treat float compares in these modules: cvt_u32 drops the explicit dx.op.isSpecialFloat IsNaN check and relies on the unordered fcmp ule being true for NaN, and f16_rtz (.... (inline)

These findings come from an AI-assisted review (Claude Code) and focus on correctness. Each is a candidate; please check it before acting on it.

let z = self.fc(0.0);
let le = self.fcmp(Pred::FOLe, f, z);
let low = self.lor(n, le);
let low = self.fcmp(Pred::FULe, f, z);

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.

Medium: Not certain about this one, since it depends on how drivers treat float compares in these modules: cvt_u32 drops the explicit dx.op.isSpecialFloat IsNaN check and relies on the unordered fcmp ule being true for NaN, and f16_rtz (prelude.rs:69) drops its isnan(f) guard and relies on the ordered fcmp ogt being false for NaN. These modules don't set DisableMathRefactoring by default. If a driver treats the compares as NaN-free, v_cvt_u32_f32 on NaN returns ftoui(NaN) (driver-defined) instead of 0, and v_cvt_pkrtz_f16_f32 or a 16-bit FLOAT store turns a NaN encoded as 0x7C01/0xFC01 into ±infinity. The HLSL path still has both isnan guards, so the two paths can disagree on NaN inputs. Keeping the explicit IsNaN checks costs a few instructions and removes the dependence.

@bmjask

bmjask commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

@Prime1997 could you take a look at this one for review and merge? My automated review notes are above, if any.

@Kalmarv

Kalmarv commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @bmjask for checking this — leaving 4f39cd191 untouched (2 safe to merge merge-checks + ready-to-merge set):

  • In direct DXIL, Op::Cmp (crates/xcl/src/gpu/dxil/module.rs ABBREV_CMP2) emits strict IEEE fcmp with no fast-math flags (nnan/fast are never emitted on fcmp).
  • Direct DXIL already relies on bare ordered/unordered fcmp predicates without DisableMathRefactoring for all 16 f32 v_cmp_* instructions (lower_valu.rs::float_compare uses Pred::FOGt, Pred::FULe, Pred::FOrd, Pred::FUno, etc.). The HLSL prelude (recomp/emit.rs) keeps explicit isnan because HLSL source has no unordered <= operator and DXC emits fast-math flags by default.
  • The same cvt_u32 (Pred::FULe) + f16_rtz (Pred::FOGt) simplification was also verified on GPU across ±0.0, ±Inf, qNaN, and sNaN in Recompiler: drop redundant IsNaN checks in direct DXIL cvt_u32 and f16_rtz #2289 (gpu_direct_cvt_u32_and_pkrtz_drop_isnan_and_match_isa); happy to bring that GPU value test over as a follow-up once this lands.

@throny throny added needs:amd-test Needs a test report or merge-check on an AMD GPU needs:title-run Runtime change: needs a merge-check with a real title run into the world (#3041) and removed ready-to-merge Has 2 independent safe merge-checks on current head (#3041) labels Dec 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:recompiler RDNA2 decoder, HLSL/direct-DXIL recompiler, wave64/wave32 area:tests Unit, integration, e2e tests, or testtitle gpu:amd Code is specific to AMD / RDNA / wave64 GPUs (scope tag; see needs:amd-test) needs:amd-test Needs a test report or merge-check on an AMD GPU needs:title-run Runtime change: needs a merge-check with a real title run into the world (#3041)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants