From e4b2f516ee391f8be0b4df76997c1f03a7746f94 Mon Sep 17 00:00:00 2001 From: saii <120340942+Not-Saii@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:35:40 +0200 Subject: [PATCH 1/8] shader: lower v_fma_mix_f32 in gfx2hlsl v_fma_mix_f32 was refused by the startup translator (58 code pairs in the #1723 refusal snapshot). It now shares Stage.mix() with the two binary16-destination forms and writes the binary32 result to the whole VGPR. Source selection follows LLVM 15 SelectVOP3PMadMixModsImpl: op_sel_hi marks a binary16 source and op_sel picks its high half; abs then neg apply after widening. The shared handler now reads high halves, accepts neg/abs on binary16 registers, and refuses op_sel on a binary32 source, unknown modifiers, and inline floats or literals on binary16 sources (mixlo/mixhi used to read the binary32 bits of 1.0 as 0). Refs #1723 Co-Authored-By: Claude Opus 5.5 --- .github/workflows/windows.yml | 1 + AGENTS.md | 1 + CMakeLists.txt | 3 + docs/experiments.md | 19 +++ tests/startup_gfx2hlsl_fma_mix_check.py | 162 ++++++++++++++++++++++++ tools/startup/gfx2hlsl.py | 64 +++++++--- 6 files changed, 235 insertions(+), 15 deletions(-) create mode 100644 tests/startup_gfx2hlsl_fma_mix_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index dd99cd9adc..db29732dca 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -253,6 +253,7 @@ jobs: tests/startup_compute_lds_b64_check.py \ tests/startup_compute_translate_check.py \ tests/startup_gfx2hlsl_swap_check.py \ + tests/startup_gfx2hlsl_fma_mix_check.py \ tests/startup_gfx2hlsl_shift64_check.py \ tests/startup_gfx2hlsl_vopc_sdwa_check.py \ tests/startup_gfx2hlsl_cmp16_check.py \ diff --git a/AGENTS.md b/AGENTS.md index 75c0bc30c2..9e082267da 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -167,6 +167,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_compute_image_store_d16_check.py ./out/pe-env/bin/python -B tests/startup_compute_translate_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_swap_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_fma_mix_check.py ./out/pe-env/bin/python -B tests/startup_image_2d_array_check.py ./out/pe-env/bin/python -B tests/startup_image_sample_a16_check.py ./out/pe-env/bin/python -B tests/startup_image_load_d16_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 62c52a9e9c..1d0263ef53 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2859,6 +2859,9 @@ if(EXISTS "${INTAKE_PYTHON}") # them as an index error before it checked the count. add_test(NAME startup_gfx2hlsl_image_arity COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_image_arity_check.py") + # gfx2hlsl lowers v_fma_mix_f32 and selects binary16 source halves on all three mixed-precision FMAs. + add_test(NAME startup_gfx2hlsl_fma_mix COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_fma_mix_check.py") # VOP1/VOP2 sub-dword addressing (SDWA) in the translator (#1141), checked against the pixel AOT # lowering of the same selections. add_test(NAME startup_gfx2hlsl_sdwa COMMAND "${INTAKE_PYTHON}" -B diff --git a/docs/experiments.md b/docs/experiments.md index 64002f1210..ae4a088dc5 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -13744,6 +13744,25 @@ The binary32 table (`VEC_F`) applies the same operand-count rule. Before this ch `tests/startup_gfx2hlsl_swap_check.py` (`startup_gfx2hlsl_swap`) decodes the documented VOP1 words, evaluates the translated text of seven programs on the CPU against a plain exchange of two list entries, and checks the refusals. Two mutations (write before read, only one destination written) are loaded from the translator source and must fail the fixtures. `python -B tests/startup_gfx2hlsl_swap_check.py binary llvm-mc-15` also reassembles the source lines. This is translation only; no draw was run. +## Startup translator: v_fma_mix_f32 + +`tools/startup/gfx2hlsl.py` now lowers `v_fma_mix_f32` (VOP3P, opcode 0x20), which it used to refuse. It shares one handler with `v_fma_mixlo_f16` and `v_fma_mixhi_f16`. Each source is read as LLVM 15 selects it (`SelectVOP3PMadMixModsImpl`): `op_sel_hi` set means a binary16 source, and `op_sel` then picks its high half. abs and then neg apply after widening. The binary32 result is written to the whole VGPR, with optional `clamp`. + +The shared handler now also: + +- reads the high half of a binary16 source with `op_sel` (previously refused on all three forms); +- accepts `-` and `|...|` on binary16 register sources; +- refuses `op_sel` on a binary32 source and any modifier it does not model (previously ignored); +- refuses an inline float or literal on a binary16 source. Before, `mixlo`/`mixhi` passed the binary32 bits of an inline float such as `1.0` through `f16tof32`, which reads 0. + +`pixel_aot.py` reads the two selector fields the other way round (`op_sel` as the format, `op_sel_hi` as the half). Its WARP fixture checks against a reference that uses the same reading, so it does not catch the swap. This change leaves `pixel_aot` alone. + +`tests/startup_gfx2hlsl_fma_mix_check.py` (`startup_gfx2hlsl_fma_mix`) builds VOP3P words from the decoder layout, checks the decoded text, and pins the translation of nine forms. Two controls check that flipping `op_sel` and `op_sel_hi` changes the output, and four forms must be refused. On the translator before this change the check fails at the first form. This is translation only; FXC 10.0.26100 compiles the emitted expressions, but no draw or dispatch was run. + +```powershell +ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_fma_mix$' -V +``` + ## Non-fused multiply-add in the startup translator The gfx1013 `v_mad_f32`, `v_mac_f32`, `v_madmk_f32`, `v_madak_f32` and diff --git a/tests/startup_gfx2hlsl_fma_mix_check.py b/tests/startup_gfx2hlsl_fma_mix_check.py new file mode 100644 index 0000000000..b6c8be2e63 --- /dev/null +++ b/tests/startup_gfx2hlsl_fma_mix_check.py @@ -0,0 +1,162 @@ +"""Mixed-precision VOP3P FMA (`v_fma_mix_f32`, `v_fma_mix{lo,hi}_f16`) in tools/startup/gfx2hlsl.py. + +usage: startup_gfx2hlsl_fma_mix_check.py + +`v_fma_mix_f32` was refused outright (58 code pairs in the #1723 refusal snapshot). It now shares +`Stage.mix()` with the two binary16-destination forms. + +Source selection follows LLVM 15 (`AMDGPUDAGToDAGISel::SelectVOP3PMadMixModsImpl`, llvmorg-15.0.7): +"If the source's op_sel_hi is set, it indicates to do a conversion from fp16. If the sources's op_sel +is set, it picks the high half of the source register." `AMDGPUInstPrinter::printOpSelHi` prints +`SISrcMods::OP_SEL_1`, the bit that function sets for an fp16 source. abs, then neg, apply after +the conversion. + +The instruction bytes are **constructed here** from the VOP3P layout the checked-in decoder reads +(`tools/disasm_rdna2.py`, VOP3P branch): + w0: [31:23] = 0b110011000, [22:16] opcode, [15] clamp, [14] op_sel_hi[2], [13:11] op_sel, + [10:8] abs (neg_hi on other VOP3P), [7:0] vdst + w1: [8:0] src0, [17:9] src1, [26:18] src2, [28:27] op_sel_hi[1:0], [31:29] neg (neg_lo) +""" +import os +import struct +import sys + +here = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(here, '..', 'tools')) +sys.path.insert(0, os.path.join(here, '..', 'tools', 'startup')) +import gfx2hlsl as G # noqa: E402 + +failures = [] + +MIX_F32, MIXLO_F16, MIXHI_F16 = 0x20, 0x21, 0x22 +V = 0x100 # VGPR source base +S5 = 5 +ZERO = 128 # inline integer 0 +ONE_F = 242 # inline float 1.0 +LITERAL = 255 + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH'}") + if not condition: + failures.append(label) + if detail: + print(' ' + detail) + + +def encode(op, vdst, srcs, *, op_sel=(0, 0, 0), op_sel_hi=(0, 0, 0), abs_bits=(0, 0, 0), + neg=(0, 0, 0), clamp=0, literal=None): + w0 = (0b110011000 << 23) | (op << 16) | (clamp << 15) | (op_sel_hi[2] << 14) | (vdst & 0xff) + w1 = srcs[0] | (srcs[1] << 9) | (srcs[2] << 18) | (op_sel_hi[0] << 27) | (op_sel_hi[1] << 28) + for i in range(3): + w0 |= op_sel[i] << (11 + i) + w0 |= abs_bits[i] << (8 + i) + w1 |= neg[i] << (29 + i) + code = struct.pack('> 16) * F(v3) + F(v4));') +check('control: op_sel changes the selected half', low != high) +check('control: op_sel_hi changes the source format', plain != low) +expect('abs then neg after widening a high half, scalar source, clamp', + encode(MIX_F32, 1, (v2, S5, v4), op_sel=(0, 1, 0), op_sel_hi=(0, 1, 0), + abs_bits=(0, 1, 0), neg=(0, 1, 0), clamp=1), + 'v_fma_mix_f32 v1, v2, -|s5|, v4 op_sel:[0,1,0] op_sel_hi:[0,1,0] clamp', + 'v1 = U(saturate(F(v2) * (-abs(f16tof32(s5 >> 16))) + F(v4)));') +expect('inline 0 as a binary16 addend', + encode(MIX_F32, 1, (v2, v3, ZERO), op_sel_hi=(1, 1, 1)), + 'v_fma_mix_f32 v1, v2, v3, 0 op_sel_hi:[1,1,1]', + 'v1 = U(f16tof32(v2) * f16tof32(v3) + 0.0);') +expect('inline float on a binary32 source', + encode(MIX_F32, 1, (v2, ONE_F, v4), op_sel_hi=(1, 0, 0)), + 'v_fma_mix_f32 v1, v2, 1.0, v4 op_sel_hi:[1,0,0]', + 'v1 = U(f16tof32(v2) * 1.0 + F(v4));') + +# --- the binary16-destination forms keep their packing -------------------------------------------- +expect('mixlo writes the low half', + encode(MIXLO_F16, 1, (v2, v3, v4), op_sel_hi=(1, 1, 0)), + 'v_fma_mixlo_f16 v1, v2, v3, v4 op_sel_hi:[1,1,0]', + 'v1 = (v1 & 0xffff0000u) | f32tof16(f16tof32(v2) * f16tof32(v3) + F(v4));') +expect('mixhi writes the high half from a high-half source', + encode(MIXHI_F16, 1, (v2, v3, v4), op_sel=(0, 0, 1), op_sel_hi=(0, 0, 1)), + 'v_fma_mixhi_f16 v1, v2, v3, v4 op_sel:[0,0,1] op_sel_hi:[0,0,1]', + 'v1 = (v1 & 0xffffu) | (f32tof16(F(v2) * F(v3) + f16tof32(v4 >> 16)) << 16);') + +# --- refusals ------------------------------------------------------------------------------------- +expect_refused('op_sel without op_sel_hi (high half of a binary32 source)', + encode(MIX_F32, 1, (v2, v3, v4), op_sel=(1, 0, 0)), + 'v_fma_mix_f32 v1, v2, v3, v4 op_sel:[1,0,0]') +# The binary16 encoding of an inline float on a half source is unverified. The old mixlo/mixhi path +# read the binary32 bits of 1.0 through f16tof32, i.e. 0.0; it is now refused rather than wrong. +expect_refused('inline float on a binary16 source', + encode(MIX_F32, 1, (v2, ONE_F, v4), op_sel_hi=(0, 1, 0)), + 'v_fma_mix_f32 v1, v2, 1.0, v4 op_sel_hi:[0,1,0]') +expect_refused('inline float on a binary16 source of mixlo', + encode(MIXLO_F16, 1, (v2, ONE_F, v4), op_sel_hi=(0, 1, 0)), + 'v_fma_mixlo_f16 v1, v2, 1.0, v4 op_sel_hi:[0,1,0]') +expect_refused('literal on a binary16 source', + encode(MIX_F32, 1, (LITERAL, v3, v4), op_sel_hi=(1, 0, 0), literal=0x3c00), + 'v_fma_mix_f32 v1, 0x3c00, v3, v4 op_sel_hi:[1,0,0]') + +if failures: + print(f'FAILED: {len(failures)} check(s): {", ".join(failures)}') + sys.exit(1) +print('all fma_mix checks passed') diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 086e8c59e5..3230559270 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -4179,34 +4179,68 @@ def note_attr(self, tok, how): self.attrs.setdefault(attr, set()).add(how) return attr, component - def mix(self, ops, mods, high): - """v_fma_mix{lo,hi}_f16: fma of operands that are f32 or f16 halves; the f16 result goes to one half.""" - sel = [0, 0, 0] + def mix(self, ops, mods, dest): + """v_fma_mix_f32 / v_fma_mix{lo,hi}_f16: fma of sources that are binary32 words or binary16 halves. + + Per source (LLVM 15 SelectVOP3PMadMixModsImpl): op_sel_hi set means the source is binary16, and + op_sel set picks its high half. abs, then neg, apply after widening. dest is 'f32', 'lo' or 'hi'. + """ + half, hi, clamp = [0, 0, 0], [0, 0, 0], False for m in mods: - if m.startswith('op_sel_hi:'): - sel = [int(x) for x in m[11:-1].split(',')] - elif m.startswith('op_sel:'): - raise Unsupported('op_sel on fma_mix') - def operand(tok, is_half): - if not is_half or tok in ('-0', '0'): + if m.startswith('op_sel_hi:['): + half = [int(x) for x in m[11:-1].split(',')] + elif m.startswith('op_sel:['): + hi = [int(x) for x in m[8:-1].split(',')] + elif m == 'clamp': + clamp = True + else: + raise Unsupported('fma_mix modifier %s' % m) + + def operand(tok, is_half, is_hi): + if not is_half: + if is_hi: + raise Unsupported('op_sel on a binary32 fma_mix source %s' % tok) return self.f(tok) - return 'f16tof32(%s)' % self.u(tok, low16_only=True) - expr = '%s * %s + %s' % tuple(operand(t, s) for t, s in zip(ops[1:4], sel)) - if 'clamp' in mods: + neg = tok.startswith('-') and not re.match(r'-[\d.]', tok) + if neg: + tok = tok[1:] + absolute = tok.startswith('|') and tok.endswith('|') + if absolute: + tok = tok[1:-1] + r = reg_range(tok) + if tok == '0': + text = '0.0' + elif r and r[1] == r[2]: + # ponytail: binary16 literals and inline floats stay refused; their half encoding is unverified. + text = 'f16tof32(%s%s)' % (self.u(tok, low16_only=not is_hi), ' >> 16' if is_hi else '') + else: + raise Unsupported('binary16 fma_mix source %s' % tok) + if absolute: + text = 'abs(%s)' % text + return '(-%s)' % text if neg else text + + expr = '%s * %s + %s' % tuple(operand(*a) for a in zip(ops[1:4], half, hi)) + if clamp: expr = 'saturate(%s)' % expr d = reg_range(ops[0])[1] + if dest == 'f32': + self.set_v(d, 'U(%s)' % expr) + return self.used_v.add(d) - if high: + if dest == 'hi': self.set_v(d, '(v%d & 0xffffu) | (f32tof16(%s) << 16)' % (d, expr)) else: keep_low16 = d in self.low16_only_v self.set_v(d, '(v%d & 0xffff0000u) | f32tof16(%s)' % (d, expr), low16_only=keep_low16) + def op_v_fma_mix_f32(self, ops, mods): + self.mix(ops, mods, 'f32') + def op_v_fma_mixlo_f16(self, ops, mods): - self.mix(ops, mods, False) + self.mix(ops, mods, 'lo') def op_v_fma_mixhi_f16(self, ops, mods): - self.mix(ops, mods, True) + self.mix(ops, mods, 'hi') def i64_words(self, tok): """(low, high) uint expressions of a 64-bit integer source: a VGPR/SGPR pair or an inline int.""" From e0189164de0ce31c0224cc829a1e0e608bd34335 Mon Sep 17 00:00:00 2001 From: saii <120340942+Not-Saii@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:39:20 +0200 Subject: [PATCH 2/8] shader: keep -0 on fma_mix sources and anchor the VOP3P encoder Restore the negated inline zero on binary16 sources, read it as -0.0 on every source, and check the test encoder against two llvm-mc words. Refs #1723 Co-Authored-By: Claude Opus 5.5 --- docs/experiments.md | 7 +++---- tests/startup_gfx2hlsl_fma_mix_check.py | 16 ++++++++++++++++ tools/startup/gfx2hlsl.py | 3 +++ 3 files changed, 22 insertions(+), 4 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index ae4a088dc5..e8a28a077a 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -13753,11 +13753,10 @@ The shared handler now also: - reads the high half of a binary16 source with `op_sel` (previously refused on all three forms); - accepts `-` and `|...|` on binary16 register sources; - refuses `op_sel` on a binary32 source and any modifier it does not model (previously ignored); -- refuses an inline float or literal on a binary16 source. Before, `mixlo`/`mixhi` passed the binary32 bits of an inline float such as `1.0` through `f16tof32`, which reads 0. +- refuses an inline float or literal on a binary16 source. Before, `mixlo`/`mixhi` passed the binary32 bits of an inline float such as `1.0` through `f16tof32`, which reads 0; +- reads a negated inline zero (`-0`) as `-0.0` on any source, so a `-0` product stays `-0`. -`pixel_aot.py` reads the two selector fields the other way round (`op_sel` as the format, `op_sel_hi` as the half). Its WARP fixture checks against a reference that uses the same reading, so it does not catch the swap. This change leaves `pixel_aot` alone. - -`tests/startup_gfx2hlsl_fma_mix_check.py` (`startup_gfx2hlsl_fma_mix`) builds VOP3P words from the decoder layout, checks the decoded text, and pins the translation of nine forms. Two controls check that flipping `op_sel` and `op_sel_hi` changes the output, and four forms must be refused. On the translator before this change the check fails at the first form. This is translation only; FXC 10.0.26100 compiles the emitted expressions, but no draw or dispatch was run. +`tests/startup_gfx2hlsl_fma_mix_check.py` (`startup_gfx2hlsl_fma_mix`) builds VOP3P words from the decoder layout. It first checks that its encoder reproduces two `llvm-mc`-assembled words already pinned in `tests/rdna2_tools_check.py`. It then checks the decoded text and pins the translation of ten forms. Two controls check that flipping `op_sel` and `op_sel_hi` changes the output, and four forms must be refused. On the translator before this change the check fails at the first form. This is translation only; no draw or dispatch was run, and the refusal census was not re-measured. ```powershell ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_fma_mix$' -V diff --git a/tests/startup_gfx2hlsl_fma_mix_check.py b/tests/startup_gfx2hlsl_fma_mix_check.py index b6c8be2e63..fb3d9b25ac 100644 --- a/tests/startup_gfx2hlsl_fma_mix_check.py +++ b/tests/startup_gfx2hlsl_fma_mix_check.py @@ -101,6 +101,14 @@ def expect_refused(label, code, asm): v2, v3, v4 = V + 2, V + 3, V + 4 +# The encoder must reproduce the LLVM-assembled words pinned in tests/rdna2_tools_check.py, so it does +# not only mirror the decoder it feeds. +check('encoder matches llvm-mc: v_fma_mix_f32 v12, s44, v19, v20', + encode(MIX_F32, 12, (44, V + 19, V + 20)).hex() == '0c0020cc2c265204') +check('encoder matches llvm-mc: v_fma_mix_f32 v12, |s44|, -v19, v20 op_sel:[1,1,0] op_sel_hi:[1,0,0]', + encode(MIX_F32, 12, (44, V + 19, V + 20), op_sel=(1, 1, 0), op_sel_hi=(1, 0, 0), + abs_bits=(1, 0, 0), neg=(0, 1, 0)).hex() == '0c1920cc2c26524c') + # --- v_fma_mix_f32: binary32 result, sources selected per operand ----------------------------------- plain = expect('f32 sources', encode(MIX_F32, 1, (v2, v3, v4)), @@ -125,6 +133,10 @@ def expect_refused(label, code, asm): encode(MIX_F32, 1, (v2, v3, ZERO), op_sel_hi=(1, 1, 1)), 'v_fma_mix_f32 v1, v2, v3, 0 op_sel_hi:[1,1,1]', 'v1 = U(f16tof32(v2) * f16tof32(v3) + 0.0);') +expect('negated inline 0 addend keeps a -0 product', + encode(MIX_F32, 1, (v2, v3, ZERO), op_sel=(0, 1, 0), op_sel_hi=(0, 1, 0), neg=(0, 0, 1)), + 'v_fma_mix_f32 v1, v2, v3, -0 op_sel:[0,1,0] op_sel_hi:[0,1,0]', + 'v1 = U(F(v2) * f16tof32(v3 >> 16) + (-0.0));') expect('inline float on a binary32 source', encode(MIX_F32, 1, (v2, ONE_F, v4), op_sel_hi=(1, 0, 0)), 'v_fma_mix_f32 v1, v2, 1.0, v4 op_sel_hi:[1,0,0]', @@ -135,6 +147,10 @@ def expect_refused(label, code, asm): encode(MIXLO_F16, 1, (v2, v3, v4), op_sel_hi=(1, 1, 0)), 'v_fma_mixlo_f16 v1, v2, v3, v4 op_sel_hi:[1,1,0]', 'v1 = (v1 & 0xffff0000u) | f32tof16(f16tof32(v2) * f16tof32(v3) + F(v4));') +expect('mixlo with a negated inline 0 on a binary16 source', + encode(MIXLO_F16, 1, (v2, v3, ZERO), op_sel_hi=(1, 1, 1), neg=(0, 0, 1)), + 'v_fma_mixlo_f16 v1, v2, v3, -0 op_sel_hi:[1,1,1]', + 'v1 = (v1 & 0xffff0000u) | f32tof16(f16tof32(v2) * f16tof32(v3) + (-0.0));') expect('mixhi writes the high half from a high-half source', encode(MIXHI_F16, 1, (v2, v3, v4), op_sel=(0, 0, 1), op_sel_hi=(0, 0, 1)), 'v_fma_mixhi_f16 v1, v2, v3, v4 op_sel:[0,0,1] op_sel_hi:[0,0,1]', diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 3230559270..850181ea80 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -4197,6 +4197,9 @@ def mix(self, ops, mods, dest): raise Unsupported('fma_mix modifier %s' % m) def operand(tok, is_half, is_hi): + if tok == '-0': + # neg on inline 0 is -0.0 in either format; f() would print +0.0, which changes a -0 product. + return '(-0.0)' if not is_half: if is_hi: raise Unsupported('op_sel on a binary32 fma_mix source %s' % tok) From 560df3e9d94b41f6b8e8f5df49e93e72e88fdd30 Mon Sep 17 00:00:00 2001 From: saii <120340942+Not-Saii@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:17:18 +0200 Subject: [PATCH 3/8] shader: refuse ambiguous negated sources in gfx2hlsl fma_mix Emit neg on a negative inline float (`--0.5`) as `(-(-0.5))` instead of an HLSL decrement, and refuse binary32 sources printed as a negative integer or literal, where the decoder text loses the sign-bit flip (review on #2055). Refs #1723 Co-Authored-By: Claude Opus 5.5 --- docs/experiments.md | 6 ++++-- tests/startup_gfx2hlsl_fma_mix_check.py | 28 +++++++++++++++++++++++++ tools/startup/gfx2hlsl.py | 7 +++++++ 3 files changed, 39 insertions(+), 2 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index e8a28a077a..656ad57749 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -13754,9 +13754,11 @@ The shared handler now also: - accepts `-` and `|...|` on binary16 register sources; - refuses `op_sel` on a binary32 source and any modifier it does not model (previously ignored); - refuses an inline float or literal on a binary16 source. Before, `mixlo`/`mixhi` passed the binary32 bits of an inline float such as `1.0` through `f16tof32`, which reads 0; -- reads a negated inline zero (`-0`) as `-0.0` on any source, so a `-0` product stays `-0`. +- reads a negated inline zero (`-0`) as `-0.0` on any source, so a `-0` product stays `-0`; +- emits neg on a negative inline float (printed `--0.5`) as `(-(-0.5))`. Before, `(--0.5)` was an HLSL decrement and did not compile; +- refuses a binary32 source printed as a negative integer or literal (`-1`, `-17`, `-0x…`). The decoder prints neg on inline 1..64 or on a literal that way, and reading it as an integer loses the sign-bit flip: neg on inline 1 is `0x80000001`, not `0xffffffff`. Inline `-1` prints the same text as neg on inline 1, so it is refused too until the decoder resolves the operand from the encoding, as it does for `v_cndmask_b32_e64` (#1932). -`tests/startup_gfx2hlsl_fma_mix_check.py` (`startup_gfx2hlsl_fma_mix`) builds VOP3P words from the decoder layout. It first checks that its encoder reproduces two `llvm-mc`-assembled words already pinned in `tests/rdna2_tools_check.py`. It then checks the decoded text and pins the translation of ten forms. Two controls check that flipping `op_sel` and `op_sel_hi` changes the output, and four forms must be refused. On the translator before this change the check fails at the first form. This is translation only; no draw or dispatch was run, and the refusal census was not re-measured. +`tests/startup_gfx2hlsl_fma_mix_check.py` (`startup_gfx2hlsl_fma_mix`) builds VOP3P words from the decoder layout. It first checks that its encoder reproduces two `llvm-mc`-assembled words already pinned in `tests/rdna2_tools_check.py`. It then checks the decoded text and pins the translation of twelve forms. Two controls check that flipping `op_sel` and `op_sel_hi` changes the output, a third checks that an unnegated literal still translates, and eight forms must be refused. On the translator before this change the check fails at the first form. This is translation only; no draw or dispatch was run, and the refusal census was not re-measured. ```powershell ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_fma_mix$' -V diff --git a/tests/startup_gfx2hlsl_fma_mix_check.py b/tests/startup_gfx2hlsl_fma_mix_check.py index fb3d9b25ac..9d1f37d0bb 100644 --- a/tests/startup_gfx2hlsl_fma_mix_check.py +++ b/tests/startup_gfx2hlsl_fma_mix_check.py @@ -32,6 +32,10 @@ V = 0x100 # VGPR source base S5 = 5 ZERO = 128 # inline integer 0 +ONE = 129 # inline integer 1 +SEVENTEEN = 145 # inline integer 17 +MINUS_ONE = 193 # inline integer -1 +MINUS_HALF_F = 241 # inline float -0.5 ONE_F = 242 # inline float 1.0 LITERAL = 255 @@ -141,6 +145,15 @@ def expect_refused(label, code, asm): encode(MIX_F32, 1, (v2, ONE_F, v4), op_sel_hi=(1, 0, 0)), 'v_fma_mix_f32 v1, v2, 1.0, v4 op_sel_hi:[1,0,0]', 'v1 = U(f16tof32(v2) * 1.0 + F(v4));') +# neg on inline -0.5 prints as `--0.5`; `(--0.5)` would be an HLSL decrement (review on #2055). +expect('negated negative inline float', + encode(MIX_F32, 1, (MINUS_HALF_F, v3, v4), neg=(1, 0, 0)), + 'v_fma_mix_f32 v1, --0.5, v3, v4', + 'v1 = U((-(-0.5)) * F(v3) + F(v4));') +expect('control: an unnegated literal on a binary32 source still translates', + encode(MIX_F32, 1, (LITERAL, v3, v4), literal=0x3f800000), + 'v_fma_mix_f32 v1, 0x3f800000, v3, v4', + 'v1 = U(F(0x3f800000u) * F(v3) + F(v4));') # --- the binary16-destination forms keep their packing -------------------------------------------- expect('mixlo writes the low half', @@ -171,6 +184,21 @@ def expect_refused(label, code, asm): expect_refused('literal on a binary16 source', encode(MIX_F32, 1, (LITERAL, v3, v4), op_sel_hi=(1, 0, 0), literal=0x3c00), 'v_fma_mix_f32 v1, 0x3c00, v3, v4 op_sel_hi:[1,0,0]') +# The decoder prints neg on inline 1..64 or a literal as a negative integer. Read as an integer, the +# sign-bit flip is lost (neg on inline 1 is 0x80000001, not 0xffffffff), so these stay refused. +# Inline -1 prints the same text as neg on inline 1, so it is refused too. +expect_refused('neg on inline 1 (binary32)', + encode(MIX_F32, 1, (ONE, v3, v4), neg=(1, 0, 0)), + 'v_fma_mix_f32 v1, -1, v3, v4') +expect_refused('inline -1 (same text as neg on inline 1)', + encode(MIX_F32, 1, (MINUS_ONE, v3, v4)), + 'v_fma_mix_f32 v1, -1, v3, v4') +expect_refused('neg on inline 17 (binary32)', + encode(MIX_F32, 1, (SEVENTEEN, v3, v4), neg=(1, 0, 0)), + 'v_fma_mix_f32 v1, -17, v3, v4') +expect_refused('neg on a literal (binary32)', + encode(MIX_F32, 1, (LITERAL, v3, v4), neg=(1, 0, 0), literal=0x3f800000), + 'v_fma_mix_f32 v1, -0x3f800000, v3, v4') if failures: print(f'FAILED: {len(failures)} check(s): {", ".join(failures)}') diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 850181ea80..3749732ef4 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -4203,6 +4203,13 @@ def operand(tok, is_half, is_hi): if not is_half: if is_hi: raise Unsupported('op_sel on a binary32 fma_mix source %s' % tok) + if tok.startswith('--') and tok[1:] in FLOATS: + # neg on a negative inline float prints as `--0.5`; `(--0.5)` is an HLSL decrement. + return '(-(%s))' % self.f(tok[1:]) + if re.fullmatch(r'-(\d+|0x[0-9a-fA-F]+)', tok): + # The decoder prints neg on inline 1..64 or a literal as a negative integer, which f() + # reads without the sign-bit flip. Refuse until the decoder resolves it from the encoding. + raise Unsupported('negated integer or literal fma_mix source %s' % tok) return self.f(tok) neg = tok.startswith('-') and not re.match(r'-[\d.]', tok) if neg: From 2254b51fb3a24fada2dca3b877e7d5ba3a7f98b9 Mon Sep 17 00:00:00 2001 From: saii <120340942+Not-Saii@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:27:31 +0200 Subject: [PATCH 4/8] shader: compile the fma_mix translations and tidy review nits Check op_sel on a binary32 source before the -0 shortcut, drop a stray tool marker from a comment, and fix the docs wording about earlier op_sel handling. Add a check mode that compiles every translated line with FXC for ps_5_1 (startup_gfx2hlsl_fma_mix_fxc when FXC is found), and cases for a register with undefined upper bits after an odd-dmask D16 image_load: a low-half read is accepted, high-half and binary32 reads are refused. Refs #1723 Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 5 ++ docs/experiments.md | 10 ++-- tests/startup_gfx2hlsl_fma_mix_check.py | 67 ++++++++++++++++++++++--- tools/startup/gfx2hlsl.py | 7 +-- 4 files changed, 75 insertions(+), 14 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 1d0263ef53..1dea5bc9f0 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2941,6 +2941,11 @@ if(EXISTS "${INTAKE_PYTHON}") # gfx2hlsl run-time sampler heap indexing (#1143): translation controls, then a desktop draw with # DXC ps_6_0 and, when the Windows SDK's FXC is found, the ps_5_1 the startup tools compile with. find_program(STARTUP_FXC fxc HINTS "${DXC_BIN_DIR}") + if(STARTUP_FXC) + # The v_fma_mix* translations from startup_gfx2hlsl_fma_mix, compiled for ps_5_1. + add_test(NAME startup_gfx2hlsl_fma_mix_fxc COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_fma_mix_check.py" fxc "${STARTUP_FXC}") + endif() # gfx2hlsl conversion operations: translation controls, then a draw of the translated pairs with # reference words and one mutated lowering per operation (v_cvt_f16_f32 through DXC only). # Compute translator: integer inequality lane guards. diff --git a/docs/experiments.md b/docs/experiments.md index 656ad57749..1075712dc3 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -13752,16 +13752,20 @@ The shared handler now also: - reads the high half of a binary16 source with `op_sel` (previously refused on all three forms); - accepts `-` and `|...|` on binary16 register sources; -- refuses `op_sel` on a binary32 source and any modifier it does not model (previously ignored); +- still refuses `op_sel` on a binary32 source, including a negated inline zero (it was refused on every source before); +- refuses any other modifier it does not model (previously ignored); +- reads only bits 15:0 of a low-half binary16 source, so a register left with undefined upper bits by an odd-dmask D16 `image_load` stays usable there; a high-half read is still refused for such a register; - refuses an inline float or literal on a binary16 source. Before, `mixlo`/`mixhi` passed the binary32 bits of an inline float such as `1.0` through `f16tof32`, which reads 0; - reads a negated inline zero (`-0`) as `-0.0` on any source, so a `-0` product stays `-0`; - emits neg on a negative inline float (printed `--0.5`) as `(-(-0.5))`. Before, `(--0.5)` was an HLSL decrement and did not compile; - refuses a binary32 source printed as a negative integer or literal (`-1`, `-17`, `-0x…`). The decoder prints neg on inline 1..64 or on a literal that way, and reading it as an integer loses the sign-bit flip: neg on inline 1 is `0x80000001`, not `0xffffffff`. Inline `-1` prints the same text as neg on inline 1, so it is refused too until the decoder resolves the operand from the encoding, as it does for `v_cndmask_b32_e64` (#1932). -`tests/startup_gfx2hlsl_fma_mix_check.py` (`startup_gfx2hlsl_fma_mix`) builds VOP3P words from the decoder layout. It first checks that its encoder reproduces two `llvm-mc`-assembled words already pinned in `tests/rdna2_tools_check.py`. It then checks the decoded text and pins the translation of twelve forms. Two controls check that flipping `op_sel` and `op_sel_hi` changes the output, a third checks that an unnegated literal still translates, and eight forms must be refused. On the translator before this change the check fails at the first form. This is translation only; no draw or dispatch was run, and the refusal census was not re-measured. +`tests/startup_gfx2hlsl_fma_mix_check.py` (`startup_gfx2hlsl_fma_mix`) builds VOP3P words from the decoder layout. It first checks that its encoder reproduces two `llvm-mc`-assembled words already pinned in `tests/rdna2_tools_check.py`. It then checks the decoded text and pins the translation of thirteen forms, one of them a register with undefined upper bits read through its low half. Two controls check that flipping `op_sel` and `op_sel_hi` changes the output, a third checks that an unnegated literal still translates, and eleven forms must be refused. On the translator before this change the check fails at the first form. + +With `fxc `, the check also compiles all thirteen translated lines for ps_5_1, the profile the startup tools use. CMake registers that mode as `startup_gfx2hlsl_fma_mix_fxc` when it finds FXC. As a control, putting back the earlier `(--0.5)` text makes FXC fail with error X3025. This is translation and compilation only; no draw or dispatch was run, and the refusal census was not re-measured. ```powershell -ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_fma_mix$' -V +ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_fma_mix(_fxc)?$' -V ``` ## Non-fused multiply-add in the startup translator diff --git a/tests/startup_gfx2hlsl_fma_mix_check.py b/tests/startup_gfx2hlsl_fma_mix_check.py index 9d1f37d0bb..af8eb28d95 100644 --- a/tests/startup_gfx2hlsl_fma_mix_check.py +++ b/tests/startup_gfx2hlsl_fma_mix_check.py @@ -1,6 +1,9 @@ """Mixed-precision VOP3P FMA (`v_fma_mix_f32`, `v_fma_mix{lo,hi}_f16`) in tools/startup/gfx2hlsl.py. -usage: startup_gfx2hlsl_fma_mix_check.py +usage: startup_gfx2hlsl_fma_mix_check.py [fxc ] + +With `fxc`, every translated line is also compiled for ps_5_1 (the profile the startup tools use), +so emitted text that is not valid HLSL fails here and not only in a later draw. `v_fma_mix_f32` was refused outright (58 code pairs in the #1723 refusal snapshot). It now shares `Stage.mix()` with the two binary16-destination forms. @@ -18,8 +21,11 @@ w1: [8:0] src0, [17:9] src1, [26:18] src2, [28:27] op_sel_hi[1:0], [31:29] neg (neg_lo) """ import os +import re import struct +import subprocess import sys +import tempfile here = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.join(here, '..', 'tools')) @@ -27,6 +33,7 @@ import gfx2hlsl as G # noqa: E402 failures = [] +translated = [] # every emitted line, compiled together in fxc mode MIX_F32, MIXLO_F16, MIXHI_F16 = 0x20, 0x21, 0x22 V = 0x100 # VGPR source base @@ -68,34 +75,36 @@ def __init__(self): class Stage(G.Stage): """A Stage with no pipeline: enough state for a decoded instruction to be translated.""" - def __init__(self): + def __init__(self, low16_only_v=()): self.lines, self.sym = [], {} + self.low16_only_v = set(low16_only_v) self.used_s, self.used_v, self.uniform_v = set(), set(), set() self.exec_known = True self.exports = {} self.pipe = Pipeline() -def translate(code): +def translate(code, low16_only_v=()): decoded = G.decode(code) - stage = Stage() + stage = Stage(low16_only_v) for _offset, _size, name, asm in decoded: stage.one(name, asm) return ' | '.join(asm for _o, _s, _n, asm in decoded), ' '.join(stage.lines) -def expect(label, code, asm, hlsl): - got_asm, got = translate(code) +def expect(label, code, asm, hlsl, low16_only_v=()): + got_asm, got = translate(code, low16_only_v) + translated.append(got) check(label + ' (decode)', got_asm == asm, f'got {got_asm!r}') check(label, got == hlsl, f'got {got!r}\n want {hlsl!r}') return got -def expect_refused(label, code, asm): +def expect_refused(label, code, asm, low16_only_v=()): decoded = G.decode(code) check(label + ' (decode)', decoded[0][3] == asm, f'got {decoded[0][3]!r}') try: - _asm, got = translate(code) + _asm, got = translate(code, low16_only_v) except G.Unsupported as e: check(label + ' refused', True) return str(e) @@ -169,7 +178,22 @@ def expect_refused(label, code, asm): 'v_fma_mixhi_f16 v1, v2, v3, v4 op_sel:[0,0,1] op_sel_hi:[0,0,1]', 'v1 = (v1 & 0xffffu) | (f32tof16(F(v2) * F(v3) + f16tof32(v4 >> 16)) << 16);') +# A register whose upper 16 bits are undefined (odd-dmask D16 image_load) can feed a low-half read. +expect('low half of a register with undefined upper bits', + encode(MIX_F32, 1, (v2, v3, v4), op_sel_hi=(1, 0, 0)), + 'v_fma_mix_f32 v1, v2, v3, v4 op_sel_hi:[1,0,0]', + 'v1 = U(f16tof32(v2) * F(v3) + F(v4));', low16_only_v={2}) + # --- refusals ------------------------------------------------------------------------------------- +expect_refused('high half of a register with undefined upper bits', + encode(MIX_F32, 1, (v2, v3, v4), op_sel=(1, 0, 0), op_sel_hi=(1, 0, 0)), + 'v_fma_mix_f32 v1, v2, v3, v4 op_sel:[1,0,0] op_sel_hi:[1,0,0]', low16_only_v={2}) +expect_refused('binary32 use of a register with undefined upper bits', + encode(MIX_F32, 1, (v2, v3, v4)), + 'v_fma_mix_f32 v1, v2, v3, v4', low16_only_v={2}) +expect_refused('op_sel on a binary32 negated inline 0', + encode(MIX_F32, 1, (v2, v3, ZERO), op_sel=(0, 0, 1), neg=(0, 0, 1)), + 'v_fma_mix_f32 v1, v2, v3, -0 op_sel:[0,0,1]') expect_refused('op_sel without op_sel_hi (high half of a binary32 source)', encode(MIX_F32, 1, (v2, v3, v4), op_sel=(1, 0, 0)), 'v_fma_mix_f32 v1, v2, v3, v4 op_sel:[1,0,0]') @@ -200,6 +224,33 @@ def expect_refused(label, code, asm): encode(MIX_F32, 1, (LITERAL, v3, v4), neg=(1, 0, 0), literal=0x3f800000), 'v_fma_mix_f32 v1, -0x3f800000, v3, v4') + + +def compile_translated(fxc): + """Compile every translated line in one ps_5_1 entry point; returns FXC's exit status and output.""" + regs = sorted({int(n) for line in translated for n in re.findall(r'\bv(\d+)\b', line)}) + body = ['#define F asfloat', '#define U asuint', + 'uint main(nointerpolation uint4 p : TEXCOORD0) : SV_Target {', + ' uint s5 = p.y;'] + body += [' uint v%d = p.x + %du;' % (r, r) for r in regs] + body += [' ' + line for line in translated] + body += [' return %s;' % ' ^ '.join('v%d' % r for r in regs), '}'] + with tempfile.TemporaryDirectory() as d: + src = os.path.join(d, 'fma_mix.hlsl') + with open(src, 'w') as fh: + fh.write('\n'.join(body) + '\n') + run = subprocess.run([fxc, '/nologo', '/T', 'ps_5_1', '/E', 'main', '/Fo', os.path.join(d, 'fma_mix.cso'), src], + capture_output=True, text=True) + return run.returncode, (run.stdout + run.stderr).strip() + + +if len(sys.argv) == 3 and sys.argv[1] == 'fxc': + status, output = compile_translated(sys.argv[2]) + check(f'fxc ps_5_1 compiles all {len(translated)} translated lines', status == 0, output) +elif len(sys.argv) != 1: + print(__doc__) + sys.exit(2) + if failures: print(f'FAILED: {len(failures)} check(s): {", ".join(failures)}') sys.exit(1) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 3749732ef4..8b67e93b76 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -4197,12 +4197,12 @@ def mix(self, ops, mods, dest): raise Unsupported('fma_mix modifier %s' % m) def operand(tok, is_half, is_hi): + if not is_half and is_hi: + raise Unsupported('op_sel on a binary32 fma_mix source %s' % tok) if tok == '-0': # neg on inline 0 is -0.0 in either format; f() would print +0.0, which changes a -0 product. return '(-0.0)' if not is_half: - if is_hi: - raise Unsupported('op_sel on a binary32 fma_mix source %s' % tok) if tok.startswith('--') and tok[1:] in FLOATS: # neg on a negative inline float prints as `--0.5`; `(--0.5)` is an HLSL decrement. return '(-(%s))' % self.f(tok[1:]) @@ -4221,7 +4221,8 @@ def operand(tok, is_half, is_hi): if tok == '0': text = '0.0' elif r and r[1] == r[2]: - # ponytail: binary16 literals and inline floats stay refused; their half encoding is unverified. + # Binary16 literals and inline floats stay refused: their half encoding is unverified. + # Only a high-half read needs the upper 16 bits defined. text = 'f16tof32(%s%s)' % (self.u(tok, low16_only=not is_hi), ' >> 16' if is_hi else '') else: raise Unsupported('binary16 fma_mix source %s' % tok) From bfd4ce70776bd0f01f929dd55ecdd047f0cdf58a Mon Sep 17 00:00:00 2001 From: Royoo <3230853833@qq.com> Date: Wed, 25 Nov 2026 14:47:35 +0800 Subject: [PATCH 5/8] startup: select the binary16 half of a mixed FMA literal --- tests/startup_gfx2hlsl_fma_mix_check.py | 21 +++++++++++++++++++-- tools/startup/gfx2hlsl.py | 6 +++++- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/tests/startup_gfx2hlsl_fma_mix_check.py b/tests/startup_gfx2hlsl_fma_mix_check.py index af8eb28d95..f443d332f0 100644 --- a/tests/startup_gfx2hlsl_fma_mix_check.py +++ b/tests/startup_gfx2hlsl_fma_mix_check.py @@ -205,9 +205,10 @@ def expect_refused(label, code, asm, low16_only_v=()): expect_refused('inline float on a binary16 source of mixlo', encode(MIXLO_F16, 1, (v2, ONE_F, v4), op_sel_hi=(0, 1, 0)), 'v_fma_mixlo_f16 v1, v2, 1.0, v4 op_sel_hi:[0,1,0]') -expect_refused('literal on a binary16 source', +expect('literal on a binary16 source', encode(MIX_F32, 1, (LITERAL, v3, v4), op_sel_hi=(1, 0, 0), literal=0x3c00), - 'v_fma_mix_f32 v1, 0x3c00, v3, v4 op_sel_hi:[1,0,0]') + 'v_fma_mix_f32 v1, 0x3c00, v3, v4 op_sel_hi:[1,0,0]', + 'v1 = U(f16tof32(0x3c00u) * F(v3) + F(v4));') # The decoder prints neg on inline 1..64 or a literal as a negative integer. Read as an integer, the # sign-bit flip is lost (neg on inline 1 is 0x80000001, not 0xffffffff), so these stay refused. # Inline -1 prints the same text as neg on inline 1, so it is refused too. @@ -224,6 +225,22 @@ def expect_refused(label, code, asm, low16_only_v=()): encode(MIX_F32, 1, (LITERAL, v3, v4), neg=(1, 0, 0), literal=0x3f800000), 'v_fma_mix_f32 v1, -0x3f800000, v3, v4') +# Both halves contain normal binary16 numbers: 1.0 in the low word and 2.0 in the high word. +for high, bits in ((0, 0x3c00), (1, 0x4000)): + raw = encode(MIX_F32, 1, (LITERAL, v3, v4), literal=0x40003c00, + op_sel=(high, 0, 0), op_sel_hi=(1, 0, 0)) + suffix = (' op_sel:[1,0,0]' if high else '') + ' op_sel_hi:[1,0,0]' + expect('select literal half %d' % high, raw, + 'v_fma_mix_f32 v1, 0x40003c00, v3, v4' + suffix, + 'v1 = U(f16tof32(0x%04xu) * F(v3) + F(v4));' % bits) + +expect('inline half on a low binary16 source', + encode(MIX_F32, 1, (240, v3, v4), op_sel_hi=(1, 0, 0)), + 'v_fma_mix_f32 v1, 0.5, v3, v4 op_sel_hi:[1,0,0]', + 'v1 = U(0.5 * F(v3) + F(v4));') +expect_refused('unverified high half of inline constant', + encode(MIX_F32, 1, (240, v3, v4), op_sel=(1, 0, 0), op_sel_hi=(1, 0, 0)), + 'v_fma_mix_f32 v1, 0.5, v3, v4 op_sel:[1,0,0] op_sel_hi:[1,0,0]') def compile_translated(fxc): diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 8b67e93b76..cd2fb61754 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -4220,8 +4220,12 @@ def operand(tok, is_half, is_hi): r = reg_range(tok) if tok == '0': text = '0.0' + elif re.fullmatch(r'0x[0-9a-fA-F]{1,8}', tok): + word = (int(tok, 16) >> (16 if is_hi else 0)) & 0xffff + text = 'f16tof32(0x%04xu)' % word + elif tok == '0.5' and not is_hi: + text = '0.5' elif r and r[1] == r[2]: - # Binary16 literals and inline floats stay refused: their half encoding is unverified. # Only a high-half read needs the upper 16 bits defined. text = 'f16tof32(%s%s)' % (self.u(tok, low16_only=not is_hi), ' >> 16' if is_hi else '') else: From a6319325816aa385b8ec92b2ae4f7ef7465d3a4d Mon Sep 17 00:00:00 2001 From: saii <120340942+Not-Saii@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:38:23 +0200 Subject: [PATCH 6/8] docs: describe literal half selection and inline 0.5 in fma_mix Refs #1723 Co-Authored-By: Claude Opus 5.5 --- docs/experiments.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 1075712dc3..15837d4c6d 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -13755,14 +13755,15 @@ The shared handler now also: - still refuses `op_sel` on a binary32 source, including a negated inline zero (it was refused on every source before); - refuses any other modifier it does not model (previously ignored); - reads only bits 15:0 of a low-half binary16 source, so a register left with undefined upper bits by an odd-dmask D16 `image_load` stays usable there; a high-half read is still refused for such a register; -- refuses an inline float or literal on a binary16 source. Before, `mixlo`/`mixhi` passed the binary32 bits of an inline float such as `1.0` through `f16tof32`, which reads 0; +- reads a literal on a binary16 source through the selected half, so `0x40003c00` gives 1.0 from the low half and 2.0 from the high half; +- accepts inline `0.5` on a low-half binary16 source and refuses the high half of an inline constant and every other inline float there. Before, `mixlo`/`mixhi` passed the binary32 bits of an inline float such as `1.0` through `f16tof32`, which reads 0; - reads a negated inline zero (`-0`) as `-0.0` on any source, so a `-0` product stays `-0`; - emits neg on a negative inline float (printed `--0.5`) as `(-(-0.5))`. Before, `(--0.5)` was an HLSL decrement and did not compile; - refuses a binary32 source printed as a negative integer or literal (`-1`, `-17`, `-0x…`). The decoder prints neg on inline 1..64 or on a literal that way, and reading it as an integer loses the sign-bit flip: neg on inline 1 is `0x80000001`, not `0xffffffff`. Inline `-1` prints the same text as neg on inline 1, so it is refused too until the decoder resolves the operand from the encoding, as it does for `v_cndmask_b32_e64` (#1932). -`tests/startup_gfx2hlsl_fma_mix_check.py` (`startup_gfx2hlsl_fma_mix`) builds VOP3P words from the decoder layout. It first checks that its encoder reproduces two `llvm-mc`-assembled words already pinned in `tests/rdna2_tools_check.py`. It then checks the decoded text and pins the translation of thirteen forms, one of them a register with undefined upper bits read through its low half. Two controls check that flipping `op_sel` and `op_sel_hi` changes the output, a third checks that an unnegated literal still translates, and eleven forms must be refused. On the translator before this change the check fails at the first form. +`tests/startup_gfx2hlsl_fma_mix_check.py` (`startup_gfx2hlsl_fma_mix`) builds VOP3P words from the decoder layout. It first checks that its encoder reproduces two `llvm-mc`-assembled words already pinned in `tests/rdna2_tools_check.py`. It then checks the decoded text and pins the translation of seventeen forms. They include a register with undefined upper bits read through its low half, both halves of one literal, and inline `0.5` on a low half. Two controls check that flipping `op_sel` and `op_sel_hi` changes the output, a third checks that an unnegated literal still translates, and eleven forms must be refused. On the translator before this change the check fails at the first form. -With `fxc `, the check also compiles all thirteen translated lines for ps_5_1, the profile the startup tools use. CMake registers that mode as `startup_gfx2hlsl_fma_mix_fxc` when it finds FXC. As a control, putting back the earlier `(--0.5)` text makes FXC fail with error X3025. This is translation and compilation only; no draw or dispatch was run, and the refusal census was not re-measured. +With `fxc `, the check also compiles all seventeen translated lines for ps_5_1, the profile the startup tools use. CMake registers that mode as `startup_gfx2hlsl_fma_mix_fxc` when it finds FXC. As a control, putting back the earlier `(--0.5)` text makes FXC fail with error X3025. This is translation and compilation only; no draw or dispatch was run, and the refusal census was not re-measured. ```powershell ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_fma_mix(_fxc)?$' -V From 49a285bbfd0c169ba24ef65dd364554db78bdc1b Mon Sep 17 00:00:00 2001 From: saii <120340942+Not-Saii@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:50:11 +0200 Subject: [PATCH 7/8] tests: dispatch the gfx2hlsl fma_mix translations against a CPU reference Add a dispatch mode to startup_gfx2hlsl_fma_mix_check.py. Every translated line runs in a DXC cs_6_0 thread on WARP or a hardware adapter, and each result word is compared with a CPU reference that decodes the VOP3P word itself (LLVM 15 reading). A control drops the high-half shift and must then follow a reference with op_sel cleared. Registered as startup_gfx2hlsl_fma_mix_dispatch_warp and _hardware (review on #2055). Refs #1723 Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 9 ++ docs/experiments.md | 8 +- tests/startup_gfx2hlsl_fma_mix_check.py | 182 +++++++++++++++++++++++- 3 files changed, 195 insertions(+), 4 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 1dea5bc9f0..b15ee57f1a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3248,6 +3248,15 @@ if(EXISTS "${INTAKE_PYTHON}") set_tests_properties(startup_gfx2hlsl_mad_dispatch_${adapter} startup_gfx2hlsl_mad_preserve_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endforeach() + # gfx2hlsl v_fma_mix*: every translated form dispatched against a CPU reference that decodes the VOP3P + # word itself, plus a control that drops the high-half shift. + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_fma_mix_dispatch_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_fma_mix_check.py" dispatch "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_gfx2hlsl_fma_mix_dispatch_${adapter} + PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() # gfx2hlsl compute stage: entry registers, numthreads and the offen buffer store, dispatched on a plain device (#1412). add_test(NAME startup_gfx2hlsl_compute_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_compute_check.py") diff --git a/docs/experiments.md b/docs/experiments.md index 15837d4c6d..52c226aae3 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -13763,10 +13763,14 @@ The shared handler now also: `tests/startup_gfx2hlsl_fma_mix_check.py` (`startup_gfx2hlsl_fma_mix`) builds VOP3P words from the decoder layout. It first checks that its encoder reproduces two `llvm-mc`-assembled words already pinned in `tests/rdna2_tools_check.py`. It then checks the decoded text and pins the translation of seventeen forms. They include a register with undefined upper bits read through its low half, both halves of one literal, and inline `0.5` on a low half. Two controls check that flipping `op_sel` and `op_sel_hi` changes the output, a third checks that an unnegated literal still translates, and eleven forms must be refused. On the translator before this change the check fails at the first form. -With `fxc `, the check also compiles all seventeen translated lines for ps_5_1, the profile the startup tools use. CMake registers that mode as `startup_gfx2hlsl_fma_mix_fxc` when it finds FXC. As a control, putting back the earlier `(--0.5)` text makes FXC fail with error X3025. This is translation and compilation only; no draw or dispatch was run, and the refusal census was not re-measured. +With `fxc `, the check also compiles all seventeen translated lines for ps_5_1, the profile the startup tools use. CMake registers that mode as `startup_gfx2hlsl_fma_mix_fxc` when it finds FXC. As a control, putting back the earlier `(--0.5)` text makes FXC fail with error X3025. The refusal census was not re-measured. + +With `dispatch warp|hardware`, all seventeen translated lines run in one DXC cs_6_0 thread. CMake registers this as `startup_gfx2hlsl_fma_mix_dispatch_warp` and `_hardware`. Each case loads its register words through the raw UAV fill pattern, so the compiler cannot fold them, runs the line and stores the destination. The check compares each word with a CPU reference that decodes the VOP3P word itself, without the decoder or the translator. The reference applies the LLVM 15 reading: binary16 if `op_sel_hi`, high half if `op_sel`, abs then neg, clamp. Inputs have short mantissas, so a fused and an unfused multiply-add give the same word; this check does not separate the two. A control drops the high-half shift from the emitted lines. Its readback must then follow a reference with `op_sel` cleared, and must differ from the correct result in at least one case. It differs in 3 of 4: the `-0` case has a zero product, so the half it reads does not show. + +Measured at `741ff02c` plus the dispatch mode, `dev` preset, Windows 11 26300.9974. On WARP (Microsoft Basic Render Driver, 1414:008c) and on an NVIDIA GeForce RTX 4090 (10de:2684, driver 32.0.16.1088), 17 of 17 words matched the reference, and the control read the low half in all 4 high-half cases. Neither run reported a capability skip. The fixture does not report D3D12 debug-layer status. ```powershell -ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_fma_mix(_fxc)?$' -V +ctest --preset dev --no-tests=error -j1 -R '^startup_gfx2hlsl_fma_mix(_fxc|_dispatch_(warp|hardware))?$' -V ``` ## Non-fused multiply-add in the startup translator diff --git a/tests/startup_gfx2hlsl_fma_mix_check.py b/tests/startup_gfx2hlsl_fma_mix_check.py index f443d332f0..b2f25cc64f 100644 --- a/tests/startup_gfx2hlsl_fma_mix_check.py +++ b/tests/startup_gfx2hlsl_fma_mix_check.py @@ -1,9 +1,11 @@ """Mixed-precision VOP3P FMA (`v_fma_mix_f32`, `v_fma_mix{lo,hi}_f16`) in tools/startup/gfx2hlsl.py. -usage: startup_gfx2hlsl_fma_mix_check.py [fxc ] +usage: startup_gfx2hlsl_fma_mix_check.py [fxc | dispatch warp|hardware] With `fxc`, every translated line is also compiled for ps_5_1 (the profile the startup tools use), -so emitted text that is not valid HLSL fails here and not only in a later draw. +so emitted text that is not valid HLSL fails here and not only in a later draw. With `dispatch`, every +translated line runs in a DXC cs_6_0 shader on WARP or a hardware adapter, and each result word is +compared with a CPU reference that decodes the VOP3P word itself. Exit code 77 is a capability skip. `v_fma_mix_f32` was refused outright (58 code pairs in the #1723 refusal snapshot). It now shares `Stage.mix()` with the two binary16-destination forms. @@ -34,6 +36,7 @@ failures = [] translated = [] # every emitted line, compiled together in fxc mode +cases = [] # (label, encoding, emitted line), run in dispatch mode MIX_F32, MIXLO_F16, MIXHI_F16 = 0x20, 0x21, 0x22 V = 0x100 # VGPR source base @@ -95,6 +98,7 @@ def translate(code, low16_only_v=()): def expect(label, code, asm, hlsl, low16_only_v=()): got_asm, got = translate(code, low16_only_v) translated.append(got) + cases.append((label, code, got)) check(label + ' (decode)', got_asm == asm, f'got {got_asm!r}') check(label, got == hlsl, f'got {got!r}\n want {hlsl!r}') return got @@ -261,9 +265,183 @@ def compile_translated(fxc): return run.returncode, (run.stdout + run.stderr).strip() +# --- dispatch mode: run the translated lines on a D3D12 device and compare with a CPU reference ---- +# +# The reference decodes each VOP3P word itself (layout in the module docstring), without +# tools/disasm_rdna2.py or gfx2hlsl, and applies the LLVM 15 reading: op_sel_hi = binary16 source, +# op_sel = its high half, abs then neg after widening, clamp = saturate. Inputs have short mantissas, +# so the product and sum are exact in binary32 and binary16, and a fused and an unfused multiply-add +# give the same word. + +INLINE_F32 = {240: 0.5, 241: -0.5, 242: 1.0, 243: -1.0, 244: 2.0, 245: -2.0, 246: 4.0, 247: -4.0} +F32_INPUT = {'v2': 1.25, 'v3': -0.75, 'v4': 3.0, 's5': 0.5} # binary32 reads +F16_INPUT = {'v2': (1.5, -2.5), 'v3': (0.75, 4.0), 'v4': (-1.25, 0.5), 's5': (2.0, -3.0)} # (low, high) +V1_BEFORE = 0x13579bdf # mixlo/mixhi keep one half of the destination +# The -0 case needs a zero product: a +0 addend would give +0, the -0 addend keeps -0. +OVERRIDES = {'negated inline 0 addend keeps a -0 product': {'v2': 0x80000000}} + + +def f32_word(value): + return struct.unpack('= 12 else None + return { + 'op': (w0 >> 16) & 0x7f, 'clamp': (w0 >> 15) & 1, + 'srcs': [w1 & 0x1ff, (w1 >> 9) & 0x1ff, (w1 >> 18) & 0x1ff], + 'op_sel': [(w0 >> (11 + i)) & 1 for i in range(3)], + 'op_sel_hi': [(w1 >> 27) & 1, (w1 >> 28) & 1, (w0 >> 14) & 1], + 'abs': [(w0 >> (8 + i)) & 1 for i in range(3)], + 'neg': [(w1 >> (29 + i)) & 1 for i in range(3)], + 'literal': literal, + } + + +def is_register(src): + return src >= V or src < 106 + + +def register_name(src): + return 'v%d' % (src - V) if src >= V else 's%d' % src + + +def case_inputs(label, fields): + """Register words for one case: each source register gets a value in the format it is read as.""" + words = {'v1': V1_BEFORE} + for src, half in zip(fields['srcs'], fields['op_sel_hi']): + if is_register(src): + name = register_name(src) + if half: + low, high = F16_INPUT[name] + words[name] = f16_word(low) | (f16_word(high) << 16) + else: + words[name] = f32_word(F32_INPUT[name]) + words.update(OVERRIDES.get(label, {})) + return words + + +def source_value(src, half, high, words, literal): + if is_register(src): + word = words[register_name(src)] + elif src == 255: + word = literal + elif src == 128: + return 0.0 + elif src in INLINE_F32: + assert not high, 'the translator refuses the high half of an inline constant' + return INLINE_F32[src] + else: + raise ValueError('source %d has no reference' % src) + if half: + return struct.unpack('> (16 * high)) & 0xffff))[0] + return struct.unpack('> 16)', ')') for line in lines] + changed = [i for i, (a, b) in enumerate(zip(lines, mutated)) if a != b] + control = run_dispatch(dxc, runner, adapter, dispatch_source(rows, mutated), len(rows) * 6, directory, + 'fma_mix_control') + low_reads = [] + for i in changed: + fields = decode_mix(cases[i][1]) + fields['op_sel'] = [0, 0, 0] + low_reads.append(reference(fields, rows[i][1])) + follows = all(control[i * 6 + 5] == want for i, want in zip(changed, low_reads)) + caught = [i for i in changed if control[i * 6 + 5] != expected[i]] + check('%s: control without the high-half shift reads the low half in all %d high-half cases' + % (adapter, len(changed)), bool(changed) and follows) + check('%s: control changes %d of %d high-half results' % (adapter, len(caught), len(changed)), + len(caught) > 0) + + if len(sys.argv) == 3 and sys.argv[1] == 'fxc': status, output = compile_translated(sys.argv[2]) check(f'fxc ps_5_1 compiles all {len(translated)} translated lines', status == 0, output) +elif len(sys.argv) == 5 and sys.argv[1] == 'dispatch': + check_dispatch(*sys.argv[2:]) elif len(sys.argv) != 1: print(__doc__) sys.exit(2) From 9d64a6b5ffb050434b949aa464fc65751977653b Mon Sep 17 00:00:00 2001 From: saii <120340942+Not-Saii@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:56:09 +0200 Subject: [PATCH 8/8] shader: note the unfused multiply-add in gfx2hlsl fma_mix Review nit on #2055. Refs #1723 Co-Authored-By: Claude Opus 5.5 --- tools/startup/gfx2hlsl.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index cd2fb61754..dbf1405c07 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -4234,6 +4234,8 @@ def operand(tok, is_half, is_hi): text = 'abs(%s)' % text return '(-%s)' % text if neg else text + # v_fma_mix* is fused, but HLSL may round `a * b` before the add, so binary32 sources with long + # mantissas can differ from the hardware by 1 ULP (same as v_fma_f32 in VEC_F). expr = '%s * %s + %s' % tuple(operand(*a) for a in zip(ops[1:4], half, hi)) if clamp: expr = 'saturate(%s)' % expr