From ea765a73910f4f0d1dfd1eee96fce339bc53baef Mon Sep 17 00:00:00 2001 From: mcpeacebir-lang <254700965+mcpeacebir-lang@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:16:19 +0300 Subject: [PATCH] tools: valu_literal64_probe measures how a 32-bit VALU literal is extended in a 64-bit integer operand (HW-VALU-LITERAL64-EXT) The "32-bit literal source of a signed 64-bit vector op" row of docs/design.md said its rule (sign-extend in an i64 operand, zero-extend in a u64/b64 one, Gen.valu_imm_i64) was not measured on hardware. tools/valu_literal64_probe.py runs 21 op forms (v_cmp/v_cmpx lt/gt i64/u64, v_ashrrev_i64, v_lshrrev_b64, v_lshlrev_b64, v_mad_i64_i32, v_mad_u64_u32) x the literals 0xffffff9c, 0x80000000 and 0x7fffffff through tools/hw_oracle in wave32 and wave64. On an RX 7800 XT (gfx1101) every result follows the row's rule; the row now says so and that RDNA2 is not measured. tests/test_valu_literal64_probe.py is CPU-only; its assembler check runs when LEONIDA_AMD_CLANG has llvm-mc beside it. Co-Authored-By: Claude Opus 5.5 --- docs/design.md | 2 +- tests/test_valu_literal64_probe.py | 253 +++++++++++++++++++++ tools/valu_literal64_probe.py | 338 +++++++++++++++++++++++++++++ 3 files changed, 592 insertions(+), 1 deletion(-) create mode 100644 tests/test_valu_literal64_probe.py create mode 100644 tools/valu_literal64_probe.py diff --git a/docs/design.md b/docs/design.md index 7888e24f72..f44117fcc6 100644 --- a/docs/design.md +++ b/docs/design.md @@ -394,7 +394,7 @@ How the generated SPIR-V expects the runtime to work: | Denormal flush and special results in `v_rcp_f32`, `v_rsq_f32`, `v_sqrt_f32`, `v_log_f32`, `v_exp_f32`, `v_rcp_iflag_f32` | Measured on an RX 6800 (gfx1030, not the console's gfx1013) with raw kernels in both wave sizes and all four IEEE/DX10_CLAMP combinations: all six read a denormal input as a zero of its sign and flush a denormal result, even with MODE's denormal field set to keep them. `v_rcp_f32(±0)` = ±inf, `v_rsq_f32(-0)` = -inf, `v_sqrt_f32(-0)` = -0, `v_log_f32(±0)` = -inf, `v_rcp_f32(FLT_MAX)` = +0, `v_exp_f32(-127)` = +0, `v_exp_f32(128)` = +inf, and every invalid result (`v_sqrt_f32`/`v_rsq_f32`/`v_log_f32` of a negative, …) is `0xffc00000`. Each is within 1 ulp of correctly rounded on the values tried, and `v_rcp_iflag_f32` is bit-identical to `v_rcp_f32`. **Not modelled yet:** the translator leaves all six on Vulkan's default denormal handling, and the ±0 and negative inputs above stay undefined in the emitted SPIR-V (`OpFDiv` by zero, `Sqrt`/`Log2` of a negative), as listed in the multiply-add and output modifiers row; the `clamp`/`omod` bits on `v_cvt_f32_*` and `v_rcp_iflag_f32` are modelled there. Source: [@shelbykb2's hardware words](https://github.com/ItsNotRexed/Leonida/issues/634#issuecomment-7074348963), not the ISA text. The corpus only ever writes MODE's FP_ROUND field and carries `mul:2`/`mul:4`/`div:2` on 102,365 float instructions (a compiler does not emit one that is ignored), so the inferred f32 state, IEEE off with denormals flushed, is the one to model. Corpus count (`tools/shader_profile.py`, 26,503 shaders; the shader count of each op deduplicates its `_e32`/`_e64` forms): `v_rcp_f32` 17,393 shaders / 424,863 occurrences, `v_rsq_f32` 17,221 / 269,310, `v_sqrt_f32` 14,511 / 201,422, `v_log_f32` 8,454 / 90,199, `v_exp_f32` 8,603 / 148,846, `v_rcp_iflag_f32` 7,395 / 34,852; 20,193 shaders (76.2%) use at least one, 1,169,492 occurrences (2.6% of the corpus's 44,406,870 instructions). | | f16 transcendentals (`v_exp_f16`, `v_log_f16`, `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16`, `v_sin_f16`, `v_cos_f16`) | Measured on an RX 6700 XT (gfx1031, not the console's gfx1013) with `tools/f16_trans_sweep.py`: all 65,536 inputs of each op, wave32 and wave64 (identical on every input), five MODEs (FUZZ-29). With f16 denormals kept (`denorm_mode_16_64 = 3`, the assembler default and what the translator assumes), `v_exp/log/rcp/rsq/sqrt_f16` are **correctly rounded on every input that is not a NaN** (0 ulp). `v_sin/v_cos_f16` take turns and reduce them exactly over the whole f16 range (no ±256 limit): compared with sin/cos(2πx), every result for \|x\| > 1 is bit-exact, and for \|x\| ≤ 1 only 14 (sin) and 4 (cos) of 30,722 are 1 ulp off. So the translator's rule (widen to f32, the GLSL.std.450 function, round to nearest even back to f16) matches the hardware as far as the driver's f32 function is accurate. For sin/cos that holds only once the angle is reduced in turns first (#594): with the f32 product 6.2831855 · x, 16,366 sin and 2,036 cos inputs are more than 1 ulp off, up to 9,944 ulp (sin of 64,640 turns: 0.0267 instead of 0). With `denorm_mode_16_64 = 0`, a denormal operand reads as a zero of its sign, and a denormal result is written as a zero of its sign. That differs from the f32 ops in the row above, which flush in both modes. The f16 field of FP_ROUND is ignored: round toward zero gives the same words as round to nearest on every input. IEEE changes only signalling NaNs. With IEEE off they pass through unchanged; with IEEE on they are quieted (bit 9 set). Payload and sign are kept either way, and quiet NaNs pass unchanged in every mode. Where SPIR-V leaves the result undefined, the hardware gives: log(±0) = -inf, rcp(±0) = ±inf, rsq(+0) = +inf, rsq(-0) = -inf, sqrt(-0) = -0, and `0xfe00` for log/rsq/sqrt of a negative (-inf included) and for sin/cos(±inf). `v_exp_f16`/`v_log_f16` give the same counts on gfx1036 (RDNA2, AMD Windows driver; SHADER-135). Since 2026-11-22 the translator selects those hardware words for `v_rcp_f16`, `v_rsq_f16` and `v_sqrt_f16` itself (the operand is replaced by 1.0 for the f32 `OpFDiv`/`InverseSqrt`/`Sqrt`, which SPIR-V leaves undefined at 0 or below 0) and `0xfe00` is the negative quiet NaN; checked bit for bit through the interpreter by `tests/semantic/test_valu_rcp_f16.py`, `test_valu_rsq_f16.py` and `test_valu_sqrt_f16.py` against exactly rounded references. The undefined cases of `v_exp_f16`/`v_log_f16`/`v_sin_f16`/`v_cos_f16` are still left to the driver. **Not modelled yet:** `Gen.f16_bits` quiets every NaN (the hardware keeps a signalling NaN with IEEE off), and the undefined cases above are left to the driver. | | f64 literal sources | For `v_cvt_f32_f64` and either source of `v_add_f64`, a literal dword supplies bits 63:32 and bits 31:0 are zero. For `v_cvt_f32_f64`, `v_rcp_f64`, `v_rsq_f64`, `v_sqrt_f64`, `v_frexp_mant_f64`, `v_frexp_exp_i32_f64` and either source of `v_add_f64`, a literal dword supplies bits 63:32 and bits 31:0 are zero. Inline integers are sign-extended and inline floats use their binary64 value. For example, gfx1030 `llvm-mc` encodes 1.5 as the literal word `0x3ff80000`. The synthetic `tests/semantic/fixtures/f64_literals.asm` checks both source words in the translated SPIR-V, including the distinction between the printed literal `0x1` and inline `1`. [LLVM AMDGPU operand conversions](https://releases.llvm.org/15.0.0/docs/AMDGPUOperandSyntax.html#integer-literals) In the synthetic `unary_f64_literals.asm`, LLVM gfx1030 encodes the five unary literal sources in trailing dwords. The regression checks the emitted high and low operand words for reciprocal, reciprocal square root and square root. It executes the integer-only frexp paths: for 6.0 the mantissa words are (0, 0x3fe80000) and the exponent is 3. The full fixture passes Vulkan 1.2 validation; the semantic interpreter cannot execute its Float64 instructions. The rule keys on the literal's printed width, not only its value: LLVM pads nothing, so a value that fits one literal dword prints in at most 8 hex digits, and a spelling of more than 8 is the whole binary64 constant (the full-width form `tools/f64_diff.py` writes: `0x0000000012345678` is the low word `0x12345678` and a zero high word, while `0x12345678` stays the high word). gfx1013 `llvm-mc` refuses a literal wider than 32 bits for these ops ("invalid operand"), so a listing from the game carries only the one-dword form and its words do not change. The wider form used to be refused by the four rounding ops; they now read the whole constant, which is what the differential check's generated programs needed. `tests/semantic/test_f64_literal_whole.py` checks those emitted words for `v_sqrt_f64`, `v_rsq_f64`, `v_rcp_f64`, the four rounding ops and the frexp exponent path, next to the one-dword, padded-width and inline-integer controls; `tests/test_f64_diff.py` checks that the CPU reference reads a literal the same way; `tools/f64_diff.py`'s CPU reference judged the whole-literal `v_add_f64`/`v_rsq_f64`/`v_sqrt_f64` programs as mismatches before the change. | -| 32-bit literal source of a signed 64-bit vector op (`v_cmp(x)_*_i64`, `v_ashrrev_i64` S1, `v_mad_i64_i32` S2) | A VALU literal is one dword and llvm-mc prints `-100` as `0xffffff9c` (both encode to the same bytes on gfx1030). In an i64 operand that dword is sign-extended to 64 bits (`{-1, num.i32}`), in a u64/b64 operand zero-extended (`{0, num.u32}`) ([LLVM AMDGPU operand syntax, Conversion of Integer Values](https://releases.llvm.org/15.0.0/docs/AMDGPUOperandSyntax.html#integer-literals); `Gen.valu_imm_i64`). So `v_cmp_lt_i64 vcc_lo, 5, 0xffffff9c` = 0, `v_ashrrev_i64 v[10:11], 4, 0xffffff9c` = 0xFFFFFFFF_FFFFFFF9 and `v_mad_i64_i32 v[10:11], vcc_lo, 1, 1, 0xffffff9c` = -99, the same as the decimal spelling and the explicit pair. `v_cmp_*_u64`, `v_lshlrev_b64`, `v_lshrrev_b64` and `v_mad_u64_u32` S2 still zero-extend a literal, a positive literal (`0x7fffffff`) stays positive, and the inline constants (-16..64) were already full-width. f64 literals keep their own rule (row above). The vector half of the scalar rule for `s_ashr_i64`, `s_bfe_i64` and `s_flbit_i32_i64` (#978). Confirmed by `tests/semantic/test_valu_signed_literal64.py` (CPU, the three spellings agree; 5 of its 8 tests fail on the previous translator, which zero-extended the printed literal) and by the llvm-mc gfx1030 encodings of `-100` and `0xffffff9c`. Not measured on hardware. | +| 32-bit literal source of a signed 64-bit vector op (`v_cmp(x)_*_i64`, `v_ashrrev_i64` S1, `v_mad_i64_i32` S2) | A VALU literal is one dword and llvm-mc prints `-100` as `0xffffff9c` (both encode to the same bytes on gfx1030). In an i64 operand that dword is sign-extended to 64 bits (`{-1, num.i32}`), in a u64/b64 operand zero-extended (`{0, num.u32}`) ([LLVM AMDGPU operand syntax, Conversion of Integer Values](https://releases.llvm.org/15.0.0/docs/AMDGPUOperandSyntax.html#integer-literals); `Gen.valu_imm_i64`). So `v_cmp_lt_i64 vcc_lo, 5, 0xffffff9c` = 0, `v_ashrrev_i64 v[10:11], 4, 0xffffff9c` = 0xFFFFFFFF_FFFFFFF9 and `v_mad_i64_i32 v[10:11], vcc_lo, 1, 1, 0xffffff9c` = -99, the same as the decimal spelling and the explicit pair. `v_cmp_*_u64`, `v_lshlrev_b64`, `v_lshrrev_b64` and `v_mad_u64_u32` S2 still zero-extend a literal, a positive literal (`0x7fffffff`) stays positive, and the inline constants (-16..64) were already full-width. f64 literals keep their own rule (row above). The vector half of the scalar rule for `s_ashr_i64`, `s_bfe_i64` and `s_flbit_i32_i64` (#978). Confirmed by `tests/semantic/test_valu_signed_literal64.py` (CPU, the three spellings agree; 5 of its 8 tests fail on the previous translator, which zero-extended the printed literal) and by the llvm-mc gfx1030 encodings of `-100` and `0xffffff9c`. **Measured on RDNA3**: on an AMD Radeon RX 7800 XT (gfx1101, Windows driver 32.0.32029.2010) through `tools/hw_oracle`, `tools/valu_literal64_probe.py` finds the same rule for every result in wave32 and wave64. It covers 21 op forms (`v_cmp_{lt,gt}_{i64,u64}` e32 and e64 with the literal as src0 and src1, `v_cmpx_{lt,gt}_{i64,u64}`, `v_ashrrev_i64`, `v_lshrrev_b64`, `v_lshlrev_b64`, `v_mad_i64_i32`, `v_mad_u64_u32`) × the literals `0xffffff9c`, `0x80000000` and `0x7fffffff`. Each i64 operand sign-extends and each u64/b64 operand zero-extends the same literal dword ([result](https://github.com/ubiquitarianism/leonida/issues/1608#issuecomment-7162059499)). **Not measured on RDNA2**; the same command runs it on a gfx103x card. | | `v_cvt_f32_f64` output modifiers | Convert to f32, apply `mul:2`, `mul:4`, or `div:2` if present, then apply `clamp` to [0, 1] if requested. [LLVM GFX10 assembler tests](https://github.com/llvm/llvm-project/blob/main/llvm/test/MC/AMDGPU/gfx10_asm_vop1.s#L3044-L3054) confirm the modifier encodings. `tests/test_f64_conversion.py` checks the resulting SPIR-V data flow. | | 32-bit integers to binary64 | `v_cvt_f64_i32` sign-extends the input value and `v_cvt_f64_u32` treats it as unsigned. Every 32-bit integer is exactly representable in binary64. The low word goes in the first destination VGPR. **The output scaling is gated by `MODE`, measured by @fiestorra**: on a gfx1036 iGPU (Radeon(TM) Graphics, drivers `31.0.24002.92` and `32.0.21045.29003` (the same counts on both), raw ISA through `tools/hw_oracle`, `tools/f64_omod_probe.py`, 6 inputs x 5 modifier forms x 5 MODEs, wave32 and wave64 identical) `mul:2`/`mul:4`/`div:2` scale the binary64 result only under `IEEE=0` with `denorm_mode_16_64=0`; under `denorm_mode_16_64=3`, which is what the translator assumes, and under `IEEE=1` they are ignored, while `clamp` applies in every MODE — so only `clamp` reaches `dst_f64` for these two ops, as `v_ldexp_f64` already does. For input `0x80000001`, SPIRV-Tools constant folding reproduced both words of each result in the synthetic `ps_int32_to_f64.s` fixture. [AMD RDNA 2 ISA, VOP1 conversions](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) | | `v_add_f64` output modifiers | The double sum is scaled by `mul:2`, `mul:4` or `div:2` if present, then clamped to [0, 1] if `clamp` is set, as for f32 (`clamp_mods_f64`, GLSL.std.450 `FClamp` on the double, so a NaN result and the sign of a -0 result are left to the driver, also as for f32). **Until 2026-11-22 both were ignored.** Source: LLVM AMDGPU defines it as `VOP3Inst<"v_add_f64", VOP3_Profile>` (VOP3Instructions.td), and `VOPProfile` sets `HasClamp` (f64 is a modifier type) and `HasOMod` (floating-point destination) (SIInstrInfo.td). It is the only f64 arithmetic the translator handles; `v_cvt_f32_f64` has the row above. `tests/test_f64_output_modifiers.py` checks the SPIR-V data flow; `runtime/test/shaders/ps_f64_mods.asm` is the GPU test (needs `shaderFloat64`, which `vk_harness` now enables when the fragment shader declares `Float64`), passed on an NVIDIA RTX 6000 Ada (driver 615.71.09, Linux; 4096/4096 pixels exact, and the `main` translator gives the predicted old words). | diff --git a/tests/test_valu_literal64_probe.py b/tests/test_valu_literal64_probe.py new file mode 100644 index 0000000000..9f90e869b5 --- /dev/null +++ b/tests/test_valu_literal64_probe.py @@ -0,0 +1,253 @@ +"""CPU-only unit tests for tools/valu_literal64_probe.py (HW-VALU-LITERAL64-EXT). No GPU and no game files. + +The assembler test runs AMD clang's llvm-mc when LEONIDA_AMD_CLANG points at a clang.exe with llvm-mc beside it, and +is skipped otherwise. +""" +import io +import json +import os +import shutil +import subprocess +import sys +import tempfile +import types +import unittest +from unittest import mock + +REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +TOOLS = os.path.join(REPO, "tools") +PROBE = os.path.join(TOOLS, "valu_literal64_probe.py") +if TOOLS not in sys.path: + sys.path.insert(0, TOOLS) + +import valu_literal64_probe as probe # noqa: E402 + + +class _FakeUnavailable(Exception): + pass + + +def _fake_hw_oracle(open_side_effect=None, family="gfx11"): + def fam(arch): + if family is None: + raise ValueError(arch) + return family + asm_mod = types.SimpleNamespace(family=fam, Kernel=lambda *a, **k: (a, k)) + open_oracle = mock.Mock(side_effect=open_side_effect or _FakeUnavailable("no gpu")) + runner_mod = types.SimpleNamespace(Unavailable=_FakeUnavailable, open_oracle=open_oracle) + pkg = types.SimpleNamespace(asm=asm_mod, runner=runner_mod) + return {"hw_oracle": pkg, "hw_oracle.asm": asm_mod, "hw_oracle.runner": runner_mod}, open_oracle + + +def _words(model=None): + """The words a GPU stores: each case under `model`, or under the row's rule for its operand when None.""" + out = [] + for case, lit in probe.runs(): + v = probe.expected(case, lit, model or case.rule) + out += [v & 0xFFFFFFFF, v >> 32] + return out + + +class Model(unittest.TestCase): + def test_self_test_passes(self): + with mock.patch.object(sys, "stdout", io.StringIO()): + probe.self_test() + + def test_extend(self): + self.assertEqual(probe.extend(0x80000000, "sext"), 0xFFFFFFFF80000000) + self.assertEqual(probe.extend(0x80000000, "zext"), 0x80000000) + self.assertEqual(probe.extend(0x00000001, "sext"), 1) + with self.assertRaises(ValueError): + probe.extend(1 << 32, "sext") + with self.assertRaises(ValueError): + probe.extend(1, "other") + + def test_the_row_examples(self): + # docs/design.md: v_cmp_lt_i64 vcc_lo, 5, 0xffffff9c = 0; v_ashrrev_i64 4, 0xffffff9c = 0xFFFFFFFF_FFFFFFF9; + # v_mad_i64_i32 1, 1, 0xffffff9c = -99 + named = {c.name: c for c in probe.CASES} + self.assertEqual(named["v_cmp_lt_i64_e64 v, lit"].model(5, probe.extend(0xFFFFFF9C, "sext")), 0) + self.assertEqual(probe.expected(named["v_ashrrev_i64 4, lit"], 0xFFFFFF9C, "sext"), 0xFFFFFFFFFFFFFFF9) + self.assertEqual(probe.s64(probe.expected(named["v_mad_i64_i32 1, 1, lit"], 0xFFFFFF9C, "sext")), -99) + + def test_every_case_separates_the_models_except_the_control(self): + for case in probe.CASES: + for lit in probe.LITERALS: + with self.subTest(case=case.name, lit=hex(lit)): + same = probe.expected(case, lit, "sext") == probe.expected(case, lit, "zext") + self.assertEqual(same, lit == 0x7FFFFFFF) + + def test_operand_kinds_follow_the_op_names(self): + for case in probe.CASES: + op = case.name.split()[0] + with self.subTest(case=case.name): + signed = "_i64" in op + self.assertEqual(case.kind, "i64" if signed else "u64") + self.assertEqual(case.rule, "sext" if signed else "zext") + + def test_kernel_lines_store_each_result_at_its_own_offset(self): + for wave in (32, 64): + with self.subTest(wave=wave): + lines = probe.kernel_lines(wave) + offsets = [int(ln.rsplit("offset:", 1)[1]) for ln in lines if ln.startswith("global_store_b32")] + self.assertEqual(offsets, [4 * i for i in range(2 * len(probe.runs()))]) + self.assertEqual(lines[-1], "s_endpgm") + self.assertEqual(any("exec_lo" in ln for ln in lines), wave == 32) + self.assertEqual(any("s[4:5]" in ln for ln in lines), wave == 64) + with self.assertRaises(ValueError): + probe.kernel_lines(16) + + def test_every_literal_is_in_the_kernel_once_per_case(self): + text = "\n".join(probe.kernel_lines(32)) + for lit in probe.LITERALS: + self.assertEqual(text.count(f"0x{lit:08x}"), len(probe.CASES), hex(lit)) + + +@unittest.skipUnless(os.environ.get("LEONIDA_AMD_CLANG") and shutil.which( + os.path.join(os.path.dirname(os.environ.get("LEONIDA_AMD_CLANG", "")), "llvm-mc")), + "needs LEONIDA_AMD_CLANG with llvm-mc beside it") +class LlvmMcAssembles(unittest.TestCase): + """Every kernel body assembles for gfx1030 (in GFX10 spelling) and gfx1101, in both wave sizes, and every + literal is encoded as the one dword the probe names.""" + + def test_kernel_lines_assemble(self): + from hw_oracle import asm + mc = shutil.which(os.path.join(os.path.dirname(os.environ["LEONIDA_AMD_CLANG"]), "llvm-mc")) + for cpu in ("gfx1030", "gfx1101"): + for wave in (32, 64): + lines = probe.kernel_lines(wave) + if cpu == "gfx1030": + lines = [asm.gfx10_spelling(ln) for ln in lines] + with self.subTest(cpu=cpu, wave=wave): + r = subprocess.run([mc, "-arch=amdgcn", f"-mcpu={cpu}", f"-mattr=+wavefrontsize{wave}", + "--show-encoding"], input="\n".join(lines) + "\n", capture_output=True, + text=True, check=False) + self.assertEqual(r.returncode, 0, r.stderr) + self.assertNotIn("error", r.stderr) + for lit in probe.LITERALS: + b = lit.to_bytes(4, "little") + tail = ",".join(f"0x{x:02x}" for x in b) + "]" + enc = [ln for ln in r.stdout.splitlines() if f"0x{lit:08x}" in ln.split(";")[0]] + self.assertEqual(len(enc), len(probe.CASES), hex(lit)) + self.assertTrue(all(ln.rstrip().endswith(tail) for ln in enc), hex(lit)) + + +class Judging(unittest.TestCase): + def test_words_that_follow_the_rule_pass(self): + entry = probe.judge(32, _words()) + self.assertTrue(entry["ok"]) + self.assertEqual(sum(r["control"] for r in entry["results"]), len(probe.CASES)) + self.assertIn("63/63 follow the rule", probe.describe(entry)) + + def test_one_model_for_every_operand_fails(self): + for model in probe.MODELS: + with self.subTest(model=model): + entry = probe.judge(64, _words(model)) + self.assertFalse(entry["ok"]) + wrong = [r for r in entry["results"] if not r["follows_rule"]] + kind = "u64" if model == "sext" else "i64" + self.assertTrue(wrong and all(r["operand"] == kind for r in wrong)) + self.assertIn("rule:", probe.describe(entry)) + + def test_a_word_neither_model_gives_is_reported(self): + words = _words() + words[0] ^= 2 + entry = probe.judge(32, words) + self.assertFalse(entry["ok"]) + self.assertEqual(entry["results"][0]["models"], []) + self.assertIn("neither model", probe.describe(entry)) + + def test_a_short_result_is_a_harness_error(self): + with self.assertRaises(RuntimeError): + probe.judge(32, _words()[:-1]) + + +class Cli(unittest.TestCase): + def run_main(self, argv, modules): + stdout, stderr = io.StringIO(), io.StringIO() + with mock.patch.dict(sys.modules, modules), mock.patch.object(sys, "stdout", stdout), \ + mock.patch.object(sys, "stderr", stderr): + rc = probe.main(argv) + return rc, stdout.getvalue(), stderr.getvalue() + + def test_missing_oracle_exits_77(self): + env = {k: v for k, v in os.environ.items() if not k.startswith("LEONIDA_HW_") and k != "LEONIDA_AMD_CLANG"} + env["LEONIDA_AMD_CLANG"] = os.path.join(REPO, "does_not_exist_clang") + proc = subprocess.run([sys.executable, "-I", PROBE], env=env, capture_output=True, text=True, check=False) + self.assertEqual(proc.returncode, 77, proc.stderr or proc.stdout) + + def test_self_test_flag(self): + proc = subprocess.run([sys.executable, "-I", PROBE, "--self-test"], capture_output=True, text=True, + check=False) + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertIn("self-test OK", proc.stdout) + + def test_bad_arguments_are_rejected_before_the_oracle_opens(self): + modules, open_oracle = _fake_hw_oracle() + for argv in (["--waves", ""], ["--waves", "16"], ["--waves", "32,x"], ["--json", ""], + ["--json", "bad\x00.json"]): + with self.subTest(argv=argv): + rc, _, err = self.run_main(argv, modules) + self.assertEqual(rc, 2) + self.assertIn("error:", err) + open_oracle.assert_not_called() + + def test_json_path_that_is_a_directory_is_rejected(self): + modules, open_oracle = _fake_hw_oracle() + with tempfile.TemporaryDirectory() as tmp: + rc, _, _ = self.run_main(["--json", tmp], modules) + self.assertEqual(rc, 2) + open_oracle.assert_not_called() + + def test_other_families_skip_with_77_and_close_the_oracle(self): + for family in ("gfx12", None): + oracle = types.SimpleNamespace(arch="gfx1201", close=mock.Mock()) + modules, _ = _fake_hw_oracle(open_side_effect=lambda: oracle, family=family) + with self.subTest(family=family): + rc, _, err = self.run_main([], modules) + self.assertEqual(rc, 77) + self.assertIn("SKIP", err) + oracle.close.assert_called_once() + + def test_run_writes_the_report_and_exit_code_follows_it(self): + def oracle_for(model=None): + return types.SimpleNamespace(arch="gfx1101", close=mock.Mock(), + run=lambda ks: [_words(model) for _ in ks]) + good = oracle_for() + modules, _ = _fake_hw_oracle(open_side_effect=lambda: good) + with tempfile.TemporaryDirectory() as tmp: + out = os.path.join(tmp, "sub", "report.json") + rc, stdout, _ = self.run_main(["--json", out], modules) + self.assertEqual(rc, 0, stdout) + self.assertIn("every literal is extended as the row says", stdout) + with open(out, "rb") as f: + raw = f.read() + self.assertNotIn(b"\r\n", raw) + data = json.loads(raw) + self.assertEqual((data["arch"], data["ok"], [k["wave"] for k in data["kernels"]]), + ("gfx1101", True, [32, 64])) + good.close.assert_called_once() + bad = oracle_for("zext") + modules, _ = _fake_hw_oracle(open_side_effect=lambda: bad) + rc, stdout, _ = self.run_main(["--waves", "32"], modules) + self.assertEqual(rc, 1) + self.assertIn("NOT every literal", stdout) + + def test_a_failed_kernel_is_a_harness_error(self): + oracle = types.SimpleNamespace(arch="gfx1101", close=mock.Mock(), + run=lambda kernels: ["assembler rejected: x"] * len(kernels)) + modules, _ = _fake_hw_oracle(open_side_effect=lambda: oracle) + rc, _, err = self.run_main(["--waves", "32"], modules) + self.assertEqual(rc, 2) + self.assertIn("assembler rejected", err) + oracle.close.assert_called_once() + + def test_write_json_report_error_is_one_line(self): + with tempfile.TemporaryDirectory() as tmp: + with mock.patch("builtins.open", side_effect=PermissionError(13, "denied")): + err = probe.write_json_report(os.path.join(tmp, "out.json"), {}) + self.assertIn("cannot write --json", err) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/valu_literal64_probe.py b/tools/valu_literal64_probe.py new file mode 100644 index 0000000000..796c56d147 --- /dev/null +++ b/tools/valu_literal64_probe.py @@ -0,0 +1,338 @@ +r"""Measure how the hardware extends a 32-bit VALU literal in a 64-bit integer operand (HW-VALU-LITERAL64-EXT). + +A VALU literal is one dword. In a 64-bit integer operand its high dword comes from somewhere: the translator +sign-extends it in an i64 operand and zero-extends it in a u64/b64 operand (`Gen.valu_imm_i64` in +`tools/rdna2spirv.py`); this is the "32-bit literal source of a signed 64-bit vector op" row of docs/design.md. +Measured on an RX 7800 XT (gfx1101): the hardware does the same for every op here. + +Each kernel runs one lane; there is one kernel per wave size. Every op form of CASES runs with each literal of +LITERALS and stores its 64-bit result as (lo, hi). The forms are `v_cmp_{lt,gt}_{i64,u64}` (e64 with the literal as +src0 and as src1, and e32), `v_cmpx_{lt,gt}_{i64,u64}`, `v_ashrrev_i64`, `v_lshrrev_b64`, `v_lshlrev_b64`, +`v_mad_i64_i32` and `v_mad_u64_u32`. The VGPR operand is chosen so the two models (high dword sign-extended, or +zero-extended) give different results; `0x7fffffff` is a control both models agree on. + +Usage: + python -I tools/valu_literal64_probe.py [--waves 32,64] [--json out.json] + python -I tools/valu_literal64_probe.py --self-test # model checks, no GPU + +Exit 0 when every result follows the row's rule (or --self-test passed), 1 when one does not or the report cannot be +written, 2 on a harness or CLI error, 77 when tools/hw_oracle is unavailable or the GPU is not gfx10 / gfx11. +Standard library only; nothing here reads game files. +""" +import argparse +import json +import os +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.dont_write_bytecode = True +if HERE not in sys.path: + sys.path.insert(0, HERE) + +FAMILIES = ("gfx10", "gfx11") +M64 = (1 << 64) - 1 +LITERALS = (0xFFFFFF9C, 0x80000000, 0x7FFFFFFF) +MODELS = ("sext", "zext") + + +def extend(lit, model): + """The 64-bit value of a 32-bit literal under a model.""" + if not 0 <= lit <= 0xFFFFFFFF: + raise ValueError(f"literal 0x{lit:x} is not 32 bits") + if model not in MODELS: + raise ValueError(f"unknown model {model!r}") + return lit | 0xFFFFFFFF00000000 if model == "sext" and lit & 0x80000000 else lit + + +def s64(x): + x &= M64 + return x - (1 << 64) if x >> 63 else x + + +class Case: + """One op form: `kind` is "i64" (the row says sign-extend) or "u64" (zero-extend), `vin` the 64-bit value of + v[2:3], `body(wave, lit)` the lines that leave the result in v[10:11] and `model(vin, lit64)` its value.""" + + def __init__(self, name, kind, vin, body, model): + self.name, self.kind, self.vin, self.body, self.model = name, kind, vin, body, model + + @property + def rule(self): + return "sext" if self.kind == "i64" else "zext" + + +def _rel(op): + return {"lt": lambda a, b: a < b, "gt": lambda a, b: a > b}[op.split("_")[-2]] + + +def _cmp_model(op, lit_first): + rel, signed = _rel(op), op.endswith("i64") + + def model(vin, lit): + a, b = (lit, vin) if lit_first else (vin, lit) + return int(rel(s64(a), s64(b)) if signed else rel(a, b)) + return model + + +def _sdst(wave): + return "s4" if wave == 32 else "s[4:5]" + + +def _cmp_e64(op, lit_first): + def body(wave, lit): + a, b = (f"0x{lit:08x}", "v[2:3]") if lit_first else ("v[2:3]", f"0x{lit:08x}") + return [f"{op}_e64 {_sdst(wave)}, {a}, {b}", "s_nop 7", f"v_cndmask_b32_e64 v10, 0, 1, {_sdst(wave)}", + "v_mov_b32 v11, 0"] + kind = op[-3:] + return Case(f"{op}_e64 {'lit, v' if lit_first else 'v, lit'}", kind, 0 if kind == "i64" else 1 << 32, body, + _cmp_model(op, lit_first)) + + +def _cmp_e32(op): + def body(wave, lit): + vcc = "vcc_lo" if wave == 32 else "vcc" + return [f"{op}_e32 {vcc}, 0x{lit:08x}, v[2:3]", "s_nop 7", f"v_cndmask_b32_e64 v10, 0, 1, {vcc}", + "v_mov_b32 v11, 0"] + kind = op[-3:] + return Case(f"{op}_e32 lit, v", kind, 0 if kind == "i64" else 1 << 32, body, _cmp_model(op, True)) + + +def _cmpx(op): + def body(wave, lit): + if wave == 32: + save, read, restore = "s_mov_b32 s8, exec_lo", "s_mov_b32 s6, exec_lo", "s_mov_b32 exec_lo, s8" + else: + save, read, restore = "s_mov_b64 s[8:9], exec", "s_mov_b64 s[6:7], exec", "s_mov_b64 exec, s[8:9]" + return [save, f"{op}_e64 0x{lit:08x}, v[2:3]", "s_nop 7", read, restore, "s_nop 7", "v_mov_b32 v10, s6", + "v_mov_b32 v11, 0"] + kind = op[-3:] + return Case(f"{op}_e64 lit, v", kind, 0 if kind == "i64" else 1 << 32, body, _cmp_model(op, True)) + + +def _shift(op): + def body(wave, lit): + return [f"{op} v[10:11], 4, 0x{lit:08x}"] + + def model(vin, lit): + if op == "v_ashrrev_i64": + return s64(lit) >> 4 + return lit >> 4 if op == "v_lshrrev_b64" else lit << 4 + return Case(f"{op} 4, lit", "i64" if op == "v_ashrrev_i64" else "u64", 0, body, model) + + +def _mad(op): + def body(wave, lit): + return [f"{op} v[10:11], {'s6' if wave == 32 else 's[6:7]'}, 1, 1, 0x{lit:08x}"] + + def model(vin, lit): + return 1 + (s64(lit) if op == "v_mad_i64_i32" else lit) + return Case(f"{op} 1, 1, lit", "i64" if op == "v_mad_i64_i32" else "u64", 0, body, model) + + +CASES = tuple([_cmp_e64(f"v_cmp_{r}_{t}", first) for t in ("i64", "u64") for r in ("lt", "gt") + for first in (True, False)] + + [_cmp_e32(f"v_cmp_{r}_{t}") for t in ("i64", "u64") for r in ("lt", "gt")] + + [_cmpx(f"v_cmpx_{r}_{t}") for t in ("i64", "u64") for r in ("lt", "gt")] + + [_shift(op) for op in ("v_ashrrev_i64", "v_lshrrev_b64", "v_lshlrev_b64")] + + [_mad(op) for op in ("v_mad_i64_i32", "v_mad_u64_u32")]) + + +def runs(): + """(case, literal) in store order.""" + return [(case, lit) for case in CASES for lit in LITERALS] + + +def expected(case, lit, model): + return case.model(case.vin, extend(lit, model)) & M64 + + +def kernel_lines(wave): + """The raw kernel body (GFX11 spelling; hw_oracle renames the stores for GFX10).""" + if wave not in (32, 64): + raise ValueError(f"wave size {wave} is not 32 or 64") + body = ["v_mov_b32 v20, 0"] + for k, (case, lit) in enumerate(runs()): + body += [f"v_mov_b32 v2, 0x{case.vin & 0xFFFFFFFF:08x}", f"v_mov_b32 v3, 0x{case.vin >> 32:08x}"] + body += case.body(wave, lit) + body += [f"global_store_b32 v20, v10, s[2:3] offset:{8 * k}", + f"global_store_b32 v20, v11, s[2:3] offset:{8 * k + 4}"] + body.append("s_endpgm") + return body + + +def judge(wave, got): + """The report entry of one kernel's stored words.""" + if len(got) != 2 * len(runs()): + raise RuntimeError(f"wave{wave}: {len(got)} words, expected {2 * len(runs())}") + results = [] + for k, (case, lit) in enumerate(runs()): + value = got[2 * k] | got[2 * k + 1] << 32 + models = [m for m in MODELS if expected(case, lit, m) == value] + results.append({"case": case.name, "operand": case.kind, "literal": f"0x{lit:08x}", + "got": f"0x{value:016x}", "models": models, "rule": case.rule, + "follows_rule": case.rule in models, + "control": expected(case, lit, "sext") == expected(case, lit, "zext")}) + return {"wave": wave, "results": results, "ok": all(r["follows_rule"] for r in results)} + + +def describe(entry): + res = entry["results"] + tell = [r for r in res if not r["control"]] + by = {m: sum(r["models"] == [m] for r in tell) for m in MODELS} + line = (f"wave{entry['wave']}: {sum(r['follows_rule'] for r in res)}/{len(res)} follow the rule " + f"(i64 sign-extends, u64/b64 zero-extends); {by['sext']} match only sext, {by['zext']} only zext, " + f"{sum(r['control'] for r in res)} controls") + for r in res: + if not r["follows_rule"]: + line += (f"\n {r['case']} lit={r['literal']}: got {r['got']}, matches " + f"{', '.join(r['models']) or 'neither model'} (rule: {r['rule']})") + return line + + +def probe(oracle, asm_mod, waves): + kernels = [asm_mod.Kernel(kernel_lines(w), wave=w, threads=1, words=2 * len(runs()), raw=True) for w in waves] + entries = [] + for wave, got in zip(waves, oracle.run(kernels)): + if isinstance(got, str): + raise RuntimeError(f"wave{wave}: {got}") + entries.append(judge(wave, got)) + return entries + + +# ---- self-test and CLI -------------------------------------------------------------------------------------------- + +def self_test(): + assert extend(0xFFFFFF9C, "sext") == 0xFFFFFFFFFFFFFF9C and extend(0xFFFFFF9C, "zext") == 0xFFFFFF9C + assert extend(0x7FFFFFFF, "sext") == extend(0x7FFFFFFF, "zext") == 0x7FFFFFFF + assert len(CASES) == 21 and len({c.name for c in CASES}) == 21 + assert sum(c.kind == "i64" for c in CASES) == 10 + for case in CASES: + for lit in LITERALS: + same = expected(case, lit, "sext") == expected(case, lit, "zext") + assert same == (lit == 0x7FFFFFFF), (case.name, hex(lit)) + named = {c.name: c for c in CASES} + # the words the row of docs/design.md gives + assert expected(named["v_cmp_lt_i64_e64 v, lit"], 0xFFFFFF9C, "sext") == 0 + assert expected(named["v_ashrrev_i64 4, lit"], 0xFFFFFF9C, "sext") == 0xFFFFFFFFFFFFFFF9 + assert s64(expected(named["v_mad_i64_i32 1, 1, lit"], 0xFFFFFF9C, "sext")) == -99 + assert expected(named["v_lshlrev_b64 4, lit"], 0x80000000, "zext") == 0x800000000 + for wave in (32, 64): + lines = kernel_lines(wave) + assert sum(ln.startswith("global_store_b32") for ln in lines) == 2 * len(runs()) + rule_words = [] + for case, lit in runs(): + v = expected(case, lit, case.rule) + rule_words += [v & 0xFFFFFFFF, v >> 32] + assert judge(32, rule_words)["ok"] + all_zext = [] + for case, lit in runs(): + v = expected(case, lit, "zext") + all_zext += [v & 0xFFFFFFFF, v >> 32] + assert not judge(64, all_zext)["ok"] + print("self-test OK") + + +def parse_waves(text): + out = [] + for tok in (t.strip() for t in text.split(",")): + if tok not in ("32", "64"): + raise ValueError(f"invalid wave {tok!r}; expected 32 or 64") + if int(tok) not in out: + out.append(int(tok)) + return out + + +def validate_json_path(path): + """An error string if `path` cannot be a --json output file, or None.""" + if not path or not path.strip(): + return "--json path must not be empty" + if "\x00" in path: + return "--json path contains a NUL byte" + if path.endswith(os.sep) or (os.altsep and path.endswith(os.altsep)) or os.path.isdir(path): + return f"--json path is a directory: {path}" + cur = os.path.dirname(os.path.abspath(path)) + while cur: + if os.path.isdir(cur): + break + if os.path.lexists(cur): + return f"--json parent is not a directory: {cur}" + nxt = os.path.dirname(cur) + if nxt == cur: + break + cur = nxt + return None + + +def write_json_report(path, data): + """Create missing parent directories and write `data` as LF-terminated JSON, or return an error string.""" + parent = os.path.dirname(os.path.abspath(path)) + try: + os.makedirs(parent, exist_ok=True) + with open(path, "w", encoding="utf-8", newline="\n") as f: + json.dump(data, f, indent=2) + f.write("\n") + except OSError as e: + return f"cannot write --json {path}: {e.strerror or e}" + return None + + +def main(argv=None): + ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + ap.add_argument("--waves", default="32,64", help="wave sizes to run (default: 32,64)") + ap.add_argument("--json", dest="json_out", help="write the full report to this path") + ap.add_argument("--self-test", action="store_true", help="check the models without a GPU") + args = ap.parse_args(argv) + if args.self_test: + self_test() + return 0 + try: + waves = parse_waves(args.waves) + except ValueError as exc: + print(f"error: {exc}", file=sys.stderr) + return 2 + if args.json_out is not None: + err = validate_json_path(args.json_out) + if err: + print(f"error: {err}", file=sys.stderr) + return 2 + from hw_oracle import asm, runner + try: + oracle = runner.open_oracle() + except runner.Unavailable as exc: + print(f"SKIP: {exc}", file=sys.stderr) + return 77 + try: + try: + fam = asm.family(oracle.arch) + except ValueError: + fam = None + if fam not in FAMILIES: + print(f"SKIP: {oracle.arch} is not gfx10 or gfx11", file=sys.stderr) + return 77 + try: + entries = probe(oracle, asm, waves) + except RuntimeError as exc: + print(f"error: {exc}", file=sys.stderr) + return 2 + finally: + close = getattr(oracle, "close", None) + if close: + close() + print(f"device: {oracle.arch}") + for entry in entries: + print(describe(entry)) + ok = all(e["ok"] for e in entries) + print("result: " + ("every literal is extended as the row says" if ok + else "NOT every literal is extended as the row says; see above")) + if args.json_out is not None: + err = write_json_report(args.json_out, {"arch": oracle.arch, "ok": ok, "kernels": entries}) + if err: + print(f"error: {err}", file=sys.stderr) + return 1 + return 0 if ok else 1 + + +if __name__ == "__main__": + if hasattr(sys.stdout, "reconfigure"): + sys.stdout.reconfigure(errors="replace") + raise SystemExit(main())