From 8ff3dddf38854a2b59e036c89274442f38c7925f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?As=C4=B1m=20Mirza=20=C3=87iftler?= Date: Tue, 24 Nov 2026 21:00:54 +0300 Subject: [PATCH] startup: draw the gfx2hlsl binary32 rounding operations The VEC_F table lowers v_floor_f32, v_ceil_f32, v_trunc_f32, v_fract_f32 and v_rndne_f32 to HLSL floor, ceil, trunc, frac and round, and no check ran any of them. tests/startup_gfx2hlsl_float_round_check.py draws them with the shared per-lane runner (byte-identical copy of tests/startup_gfx2hlsl_lane_alu.py) against references written from the RDNA 2 ISA: signed zero results, round half to even, and fract capped at 0x3f7fffff, on exact halves and quarters, 1000000.5, the binary32 just below 0.5, 8388607.5 and -2^-30. Each operation has a mutated lowering whose first draw must read its own words. All 20 draws match on WARP and an RX 6600 through FXC ps_5_1 and DXC ps_6_0, the 10 mutated draws read their mutated words, and frac(-2^-30) reads 0x3f7fffff on both adapters. --- .github/workflows/windows.yml | 2 + CMakeLists.txt | 10 ++ docs/experiments.md | 15 ++ tests/startup_gfx2hlsl_float_round_check.py | 81 +++++++++ tests/startup_gfx2hlsl_lane_alu.py | 172 ++++++++++++++++++++ 5 files changed, 280 insertions(+) create mode 100644 tests/startup_gfx2hlsl_float_round_check.py create mode 100644 tests/startup_gfx2hlsl_lane_alu.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 7817ba0896..5bb48adef7 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -73,6 +73,7 @@ jobs: (["tests/startup_image_sample_c_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_image_3d_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_image_load_mip_check.py", "--llvm-mc", "llvm-mc-15"], {}), + (["tests/startup_gfx2hlsl_float_round_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_image_2d_array_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_flat_param_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_bit_alu_check.py", "binary", "llvm-mc-15"], {}), @@ -170,6 +171,7 @@ jobs: tests/startup_image_3d_check.py \ tests/startup_image_load_mip_check.py \ tests/startup_gfx2hlsl_operand_count_check.py \ + tests/startup_gfx2hlsl_float_round_check.py \ tests/startup_image_2d_array_check.py \ tests/startup_host_cpu_check.py \ tests/startup_gfx2hlsl_capture_check.py \ diff --git a/CMakeLists.txt b/CMakeLists.txt index 43a812e9f7..25807d2ffa 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1643,6 +1643,16 @@ if(EXISTS "${INTAKE_PYTHON}") # gfx2hlsl refuses a binary32 or integer vector operation with a source too few or too many. add_test(NAME startup_gfx2hlsl_operand_count COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_operand_count_check.py") + # gfx2hlsl binary32 rounding (VEC_F floor, ceil, trunc, fract, rndne): translation controls, then a draw of + # the translated pairs with reference words and one mutated lowering per operation. + add_test(NAME startup_gfx2hlsl_float_round_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_float_round_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_float_round_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_float_round_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_float_round_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + endforeach() # 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 2fd6141860..3af27309df 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -10625,6 +10625,21 @@ Not covered: a D3D12 readback of a translated comparison draw. The compared resu The binary32 table (`VEC_F`) applies the same operand-count rule. Before this change, a form one source short (`v_add_f32 v1, v2`) raised `IndexError` in `Stage.one` instead of `Unsupported`. A form with one source too many (`v_med3_f32 v1, v2, v3, v4, v5`) translated with the extra source dropped. `tests/startup_gfx2hlsl_operand_count_check.py` (`startup_gfx2hlsl_operand_count`) checks every operation of both tables: one source fewer and one source more are refused, and the exact count translates. It also checks that the constant and accumulator forms (`v_fmac_f32`, `v_mac_f32`, `v_fmamk_f32`, `v_fmaak_f32`, `v_madmk_f32`, `v_madak_f32`) keep translating with their usual operands. As a control, it loads the translator with the new `VEC_F` guard removed and requires both old failures to come back. +## Startup translator: binary32 rounding + +No check ran the rounding operations of the `VEC_F` table in `tools/startup/gfx2hlsl.py` before: `v_floor_f32`, `v_ceil_f32`, `v_trunc_f32`, `v_fract_f32` and `v_rndne_f32`. They lower to HLSL `floor`, `ceil`, `trunc`, `frac` and `round`. `tests/startup_gfx2hlsl_float_round_check.py` draws them with the shared runner `tests/startup_gfx2hlsl_lane_alu.py`, one operation per lane on flat inputs, alternating the `_e32` and `_e64` spellings, and compares the four result words exactly. + +The references follow the AMD RDNA 2 ISA reference: +- A zero result keeps the sign of the source: `ceil(-0.75)`, `trunc(-0.75)` and `rndne(-2^-30)` are -0. +- `v_rndne_f32` rounds halves to even: 2.5 → 2, 3.5 → 4, -2.5 → -2, 1000000.5 → 1000000. +- `v_fract_f32` is `x - floor(x)`, capped at the largest binary32 below 1.0. With -2^-30 the exact difference rounds to 1.0, and the instruction gives `0x3f7fffff`. + +The inputs also include the binary32 just below 0.5 and 8388607.5. + +Each operation has a wrong lowering whose first draw must read its own mutated words: floor and ceil exchanged, floor for trunc, `x - trunc(x)` for frac, and trunc for round. + +On WARP 10.0.26100.9818 and on an AMD Radeon RX 6600 (driver 32.0.21045.29003), all 20 draws matched through FXC `ps_5_1` and DXC `ps_6_0`, and all 10 mutated draws read their mutated words. On both adapters, HLSL `frac` of -2^-30 read `0x3f7fffff`, so the lowering kept the cap on these two adapters without an explicit comparison. Tests: `startup_gfx2hlsl_float_round_controls`, `startup_gfx2hlsl_float_round_warp` and `startup_gfx2hlsl_float_round_hardware`. + ## Startup translator: SMEM offset operands `tools/startup/gfx2hlsl.py` accepts these offset operands for the scalar memory loads ([issue #1674](https://github.com/R0Y00/Xbox2Windows/issues/1674)): diff --git a/tests/startup_gfx2hlsl_float_round_check.py b/tests/startup_gfx2hlsl_float_round_check.py new file mode 100644 index 0000000000..b1c71d851c --- /dev/null +++ b/tests/startup_gfx2hlsl_float_round_check.py @@ -0,0 +1,81 @@ +"""Binary32 rounding operations of tools/startup/gfx2hlsl.py (its VEC_F table). + + (no arguments) translation controls, pure Python + binary reassemble the pixel bodies and compare them with the recorded words + draw [fxc] + draw one pixel per four input sets and compare the four result words + +Covers v_floor_f32, v_ceil_f32, v_trunc_f32, v_fract_f32 and v_rndne_f32, which no check ran before. The fixture and +runner are startup_gfx2hlsl_lane_alu.py: one operation per lane, alternating the e32 and e64 spellings, on flat +parameters the compilers cannot fold. The references follow the AMD RDNA 2 ISA reference: a zero result keeps the sign +of the source (ceil(-0.75) and trunc(-0.75) are -0), v_rndne_f32 rounds halves to even, and v_fract_f32 is +x - floor(x) capped at the largest binary32 below 1.0 (0x3f7fffff), so a tiny negative source does not give 1.0. +The inputs are exact halves and quarters, 1000000.5, the binary32 just below 0.5, 8388607.5 and -2^-30. +""" +import math +import struct +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from startup_gfx2hlsl_lane_alu import main, words # noqa: E402 + + +def f(value): + return struct.unpack(' reassemble the pixel bodies and compare them with the recorded words + draw [fxc] + draw one pixel per four input sets and compare the four result words + +The pixel fixture is the one of startup_gfx2hlsl_bit_alu_check.py: it reads three flat parameters (v0..v3, v4..v7, +v8..v11), applies one operation per lane with sources v(4s + lane) and exports v12..v15 to mrt0, whose words the +renderer compares exactly. The vertex stage places the inputs in the parameters, so the compilers cannot fold them. + +A family is a dict with: + ops: mnemonic -> (source count, reference over ints, VOP2 or VOP1 so the e32 and e64 spellings both exist) + draw: mnemonic -> input sets (src0, src1, src2), a multiple of four + mutations: mnemonic -> (pattern in the translated pixel text, replacement, reference of the mutated lowering) + body: mnemonic -> the recorded pixel body words (llvm-mc -mcpu=gfx1013) + refused: assembly lines that must stay refused + accepted: assembly lines that must translate (one instruction, no pipeline) +Every reference is written from the ISA description with plain integer arithmetic, not from the lowering. +""" +import re +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_flat_param_check import assemble, compile_hlsl, draw, root_blob # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import (POST_SOURCE, POST_WORDS, PRE_SOURCE, PRE_WORDS, Probe, # noqa: E402 + vs_source, vs_words, words_text) + +MASK = 0xffffffff + + +def body_source(family, op): + arity, _, alternate = family['ops'][op] + lines = [] + for lane in range(4): + sources = ', '.join('v%d' % (4 * s + lane) for s in range(arity)) + lines.append('%s%s v%d, %s\n' % (op, '_e64' if alternate and lane % 2 else '', 12 + lane, sources)) + return ''.join(lines) + + +def translate(family, op, mutate=False): + pipe = G.Pipeline(vs_words([(0, 0, 0)] * 4), PRE_WORDS + family['body'][op] + POST_WORDS, root_blob()) + text = pipe.hlsl_ps() + if mutate: + pattern, replacement, _ = family['mutations'][op] + mutated, count = re.subn(pattern, replacement, text) + assert count == 4 and mutated != text, (op, count) + text = mutated + return pipe, text + + +def refused(assembly): + try: + Probe().one(assembly.split(' ', 1)[0], assembly) + except G.Unsupported: + return True + return False + + +def check(label, ok): + print('%s: %s' % (label, 'ok' if ok else 'MISMATCH')) + if not ok: + raise AssertionError(label) + + +def expected(family, op, sets, mutated=False): + arity, reference, _ = family['ops'][op] + function = family['mutations'][op][2] if mutated else reference + return [function(*x[:arity]) & MASK for x in sets] + + +def controls(family): + for op, (arity, _, _) in family['ops'].items(): + _, text = translate(family, op) + lanes = re.findall(r'^\s*v(1[2-5]) = (.*);$', text, re.M) + check('%s: four lanes translated' % op, [lane for lane, _ in lanes] == ['12', '13', '14', '15']) + translate(family, op, True) + sets = family['draw'][op] + check('%s: %d draw sets' % (op, len(sets)), sets and len(sets) % 4 == 0) + # Each mutation reads a wrong word in the first draw, so the mutated draw cannot pass by accident. + first = sets[:4] + check('%s: mutation changes draw set 0' % op, + expected(family, op, first, True) != expected(family, op, first)) + check('accepted forms translate', not any(refused(a) for a in family['accepted'])) + check('refused forms stay refused', all(refused(a) for a in family['refused'])) + + +def check_binary(family, llvm_mc): + for op in family['ops']: + built = assemble(llvm_mc, body_source(family, op)) + if built != family['body'][op]: + raise AssertionError('%s: assembled %s, recorded %s' % (op, built.hex(), family['body'][op].hex())) + for name, source, words in (('prologue', PRE_SOURCE, PRE_WORDS), ('export', POST_SOURCE, POST_WORDS)): + if assemble(llvm_mc, source) != words: + raise AssertionError('%s fixture differs from llvm-mc' % name) + for op, sets in family['draw'].items(): + for i in range(0, len(sets), 4): + if assemble(llvm_mc, vs_source(sets[i:i + 4])) != vs_words(sets[i:i + 4]): + raise AssertionError('vertex fixture for %s %s differs from llvm-mc' % (op, sets[i:i + 4])) + print('fixture words match llvm-mc') + + +def check_draw(family, dxc, renderer, adapter, fxc=None): + controls(family) + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + draws = mutations = 0 + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + for op, sets in family['draw'].items(): + arity = family['ops'][op][0] + good = compile_hlsl(compiler, kind, translate(family, op)[1], 'ps_%s_%s' % (op, kind), ps_profile, + directory) + for index in range(0, len(sets), 4): + chunk = sets[index:index + 4] + vs = compile_hlsl(compiler, kind, G.Pipeline(vs_words(chunk), PRE_WORDS + family['body'][op] + + POST_WORDS, root_blob()).hlsl_vs(), + 'vs_%s_%d_%s' % (op, index, kind), vs_profile, directory) + want = words_text(expected(family, op, chunk)) + run = draw(renderer, adapter, vs, good, want) + if run.returncode: + raise AssertionError('%s %s inputs %s\n%s\n%s' % (kind, op, chunk, run.stdout, run.stderr)) + draws += 1 + print('%s %s %s: %s' % (kind, op, [tuple('%x' % v for v in x[:arity]) for x in chunk], want), + flush=True) + if index: + continue + # The same draw with the mutated lowering must read the mutated words, not the reference. + wrong = words_text(expected(family, op, chunk, True)) + bad = compile_hlsl(compiler, kind, translate(family, op, True)[1], 'mutated_%s_%s' % (op, kind), + ps_profile, directory) + run = draw(renderer, adapter, vs, bad, want) + if run.returncode == 0 or 'actual=%s' % wrong not in run.stderr: + raise AssertionError('%s %s mutation did not read %s\n%s\n%s' + % (kind, op, wrong, run.stdout, run.stderr)) + mutations += 1 + print('%s %s mutation: fails as expected, reads %s' % (kind, op, wrong), flush=True) + print('%s: %d draws matched, %d mutated draws read their mutated words' % (adapter, draws, mutations)) + + +def main(family, doc): + if len(sys.argv) == 1: + controls(family) + return + mode, *args = sys.argv[1:] + if mode == 'binary': + check_binary(family, *args) + elif mode == 'draw': + check_draw(family, *args) + else: + raise SystemExit(doc) + + +def words(hex_text): + return bytes.fromhex(hex_text) + + +def signed(v): + return v - (1 << 32) if v >> 31 else v + + +def body_words(family, llvm_mc): + """Development aid: print the body words llvm-mc gives for every operation of a family.""" + for op in family['ops']: + print(" '%s': words('%s')," % (op, assemble(llvm_mc, body_source(family, op)).hex()))