From 5052f5dc180a08000353fbf21b1baad3e616a195 Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 03:48:05 +0100 Subject: [PATCH] startup: lower s_mul_hi_u32 in gfx2hlsl s_mul_hi_u32 writes the high 32 bits of the unsigned 64-bit product of two scalar words and leaves SCC unchanged (pixel_aot SCALAR["mul_hi_u32"], the LLVM SOP2 definition has no SCC def). Startup HLSL has no 64-bit integer, so a mul_hi_u32 helper in the common preamble builds the high word from halfword products, the same arithmetic as pixel_aot's scalar helper. The operation needs each source's whole word, so it joins the halfword pack's guard: wave-mask sources, vcc/exec destinations, symbolic descriptors and reserved encodings are refused. An SGPR that held a compare mask may be overwritten; set_s drops its mask mark. The SOP2 check runs the emitted helper text against (a * b) >> 32 over every value form and kills six mutants. The cvt_alu ubyte2 mutation pattern is anchored to its operand so it no longer also matches the helper's shifts. Co-Authored-By: Claude Fable 5.2 --- docs/experiments.md | 13 ++ tests/startup_gfx2hlsl_cvt_alu_check.py | 2 +- .../startup_gfx2hlsl_sop2_complement_check.py | 152 +++++++++++++++++- tools/startup/gfx2hlsl.py | 16 +- 4 files changed, 176 insertions(+), 7 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index af679e6458..fb0a79bf7b 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -6470,6 +6470,19 @@ half. SCC is unchanged. The fixture covers in-place, immediate and `m0` forms. Disabling the lowering or swapping the sources fails the check. Wave masks, symbolic descriptors and reserved scalar encodings stay refused. [Refs #1996](https://github.com/R0Y00/Xbox2Windows/issues/1996) +**Scalar unsigned multiply-high.** The same check covers `s_mul_hi_u32`, the +high 32 bits of the unsigned 64-bit product of two scalar words, with SCC +unchanged. Startup HLSL has no 64-bit integer type, so a `mul_hi_u32` helper in +the common preamble builds the high word from halfword products, as the +`pixel_aot` scalar helper does. The check runs the emitted helper text on the +CPU against `(a * b) >> 32` over the SOP2 forms above, edge pairs such as all +ones squared and `0x80000000 x 2`, and seeded random pairs. The low word, the +signed high word, a helper without either carry term, an added SCC write and a +disabled lowering each fail. Wave-mask sources, a vcc or exec destination, +symbolic descriptors and reserved scalar encodings stay refused; an SGPR that +held a compare mask may be overwritten and loses its mask mark. +`s_mul_hi_i32` is still refused by name. + **Scalar bit tests.** Startup translation sets SCC for `s_bitcmp0_b32` and `s_bitcmp1_b32` by comparing the selected bit of the first word to zero or one. Only the low five bits of the index are used. EXEC, VCC and SGPRs tracked diff --git a/tests/startup_gfx2hlsl_cvt_alu_check.py b/tests/startup_gfx2hlsl_cvt_alu_check.py index d26a5daf14..f4df92f7a7 100644 --- a/tests/startup_gfx2hlsl_cvt_alu_check.py +++ b/tests/startup_gfx2hlsl_cvt_alu_check.py @@ -82,7 +82,7 @@ def to_half(word): lambda a: 0 if value(a) != value(a) or value(a) <= 0 else round(value(a))), 'v_cvt_f32_ubyte0': (r'& 255\)\)', r'& 127))', lambda a: f32(float(a & 127))), 'v_cvt_f32_ubyte1': (r'>> 8\)', r'>> 16)', lambda a: f32(float(a >> 16 & 255))), - 'v_cvt_f32_ubyte2': (r'>> 16\)', r'>> 8)', lambda a: f32(float(a >> 8 & 255))), + 'v_cvt_f32_ubyte2': (r'(v\d+) >> 16\)', r'\1 >> 8)', lambda a: f32(float(a >> 8 & 255))), 'v_cvt_f32_ubyte3': (r'U\(float\((v\d+) >> 24\)\)', r'U(float((\1 >> 16) & 255))', lambda a: f32(float(a >> 16 & 255))), 'v_cvt_f32_f16': (r'f16tof32\((v\d+)\)', r'f16tof32(\1 >> 16)', lambda a: f32(half(a >> 16))), 'v_cvt_f16_f32': (r'f32tof16\(F\((v\d+)\)\)', r'f32tof16(-F(\1))', lambda a: to_half(a ^ 0x80000000)), diff --git a/tests/startup_gfx2hlsl_sop2_complement_check.py b/tests/startup_gfx2hlsl_sop2_complement_check.py index 598837df81..659e73d101 100644 --- a/tests/startup_gfx2hlsl_sop2_complement_check.py +++ b/tests/startup_gfx2hlsl_sop2_complement_check.py @@ -1,4 +1,5 @@ -"""Scalar SOP2 complement logic (#1919) and high-halfword packing (#1996) in tools/startup/gfx2hlsl.py. +"""Scalar SOP2 complement logic (#1919), high-halfword packing (#1996) and unsigned multiply-high in +tools/startup/gfx2hlsl.py. (no arguments) translation controls, pure Python binary assemble the decoded text of every form with llvm-mc and compare with the words built here @@ -25,7 +26,14 @@ The `s_pack_hh_b32_b16` forms use the same encoder and evaluator. The reference places the high half of src0 in the low result half and the high half of src1 in the high result half, preserving SCC. Swapping the inputs must fail the value check. + +The `s_mul_hi_u32` forms use the same encoder and evaluator. The emitted mul_hi_u32 helper is taken from the +translator's common preamble and run statement by statement in 32-bit arithmetic; the reference is (a * b) >> 32 on +Python integers, SCC unchanged. The value set adds 0 x 0, 1 x 1, all ones squared, 0x80000000 x 2 and seeded random +pairs. Mutations that must each fail: the low word of the product, the signed high word, the helper without the +low-halfword carry, the helper without the final carry limb, an added SCC write and a disabled lowering. """ +import random import re import struct import sys @@ -39,7 +47,7 @@ import gfx2hlsl as G # noqa: E402 import pixel_aot as P # noqa: E402 from startup_flat_param_check import assemble # noqa: E402 -from startup_gfx2hlsl_bit_alu_check import Expr # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import Expr as BitExpr # noqa: E402 MASK = 0xffffffff OPCODE = {name: op for op, (name, _) in D.SOP2_OPS.items()} @@ -135,6 +143,43 @@ def source_value(code_, literal, env): return env['s%d' % code_] +def common_lines(): + pipe = object.__new__(G.Pipeline) + pipe.uds, pipe.resources, pipe.samplers, pipe.uses_sampler_heap = [], {}, {}, False + return pipe.common() + + +def mul_hi_helper(): + """The emitted mul_hi_u32 body as (declarations, return expression), parsed for the evaluator.""" + text = ''.join(entry for entry in common_lines() if entry.startswith('uint mul_hi_u32(')) + m = re.fullmatch(r'uint mul_hi_u32\(uint a, uint b\) \{ (.*) \}', text) + assert m, text + *statements, result = [part.strip() for part in m.group(1).split(';') if part.strip()] + assert result.startswith('return '), result + declarations = [] + for statement in statements: + assert statement.startswith('uint '), statement + for item in statement[5:].split(', '): + name, value = item.split(' = ', 1) + declarations.append((name, BitExpr(value))) + return declarations, BitExpr(result[7:]) + + +class Expr(BitExpr): + """The bit-ALU evaluator, plus the translator's own mul_hi_u32 helper text.""" + helper = None + + def call(self, name, args): + if name != 'mul_hi_u32': + return BitExpr.call(name, args) + assert not args[0][1] and not args[1][1], 'mul_hi_u32 reads uint operands' + declarations, result = Expr.helper + env = {'a': args[0][0], 'b': args[1][0]} + for local, value in declarations: + env[local] = value.run(env)[0] + return result.run(env)[0], False + + def run_lines(lines, env): env = dict(env) for line in lines: @@ -225,6 +270,106 @@ def reference(a, b): G.SCA[PACK_HH] = saved +MUL_HI = 's_mul_hi_u32' +MUL_EDGES = [(0, 0), (1, 1), (MASK, MASK), (0x80000000, 2), (2, 0x80000000), (0x10000, 0x10000), (0xffff, 0xffff), + (0x1ffff, 0x1ffff), (MASK, 1), (0x80000000, 0x80000000), (0xaaaaaaab, 0xfffffffd)] +_random = random.Random(0x1723) +MUL_PAIRS = MUL_EDGES + PAIRS + [(_random.getrandbits(32), _random.getrandbits(32)) for _ in range(512)] + + +def mul_reference(a, b): + return (a * b) >> 32 + + +def mul_mismatch(): + """first_mismatch() over the multiply value set, with the helper re-read from the preamble.""" + global PAIRS + Expr.helper = mul_hi_helper() + saved, PAIRS = PAIRS, MUL_PAIRS + try: + return first_mismatch(MUL_HI, mul_reference, updates_scc=False) + finally: + PAIRS = saved + + +def mul_controls(): + check('mul_hi matches the LLVM 15 SOP2 encoding', sop2(MUL_HI, 0, 1, 2).hex() == '0102809a') + text, scc = G.SCA.get(MUL_HI, (None, None)) + arity, aot_text, aot_scc = P.SCALAR['mul_hi_u32'] + check('mul_hi: %r SCC %r equals pixel_aot %r SCC %r' % (text, scc, aot_text, aot_scc), + arity == 2 and text == aot_text and scc is None and aot_scc is None and MUL_HI not in G.SCC_UNMODELLED) + check('mul_hi: reference gives 0xfffffffe for all ones squared and 1 for 0x80000000 x 2', + mul_reference(MASK, MASK) == 0xfffffffe and mul_reference(0x80000000, 2) == 1) + mismatch = mul_mismatch() + check('mul_hi result and untouched SCC across %d forms and %d input pairs' % (len(VALUE_FORMS), len(MUL_PAIRS)), + mismatch is None, str(mismatch)) + asm, stage = translate(sop2(MUL_HI, 3, LITERAL, 2, 0xaaaaaaab)) + check('mul_hi literal form emits the helper call', stage.lines == ['s3 = mul_hi_u32(0xaaaaaaabu, s2);'], + '%s -> %s' % (asm, stage.lines)) + + masked = [(form, attempt(code(MUL_HI, form))[1].lines) for form in MASK_FORMS + [(3, 107, 2, None)]] + check('mul_hi refuses whole-wave mask sources and destinations', + all(lines == ['refused: %s on a lane mask' % MUL_HI] for _, lines in masked), str(masked)) + _, reserved = attempt(sop2(MUL_HI, 3, 209, 2)) + check('mul_hi refuses a reserved scalar source encoding', + reserved.lines == ['refused: %s source s209' % MUL_HI], str(reserved.lines)) + for symbolic in ('mask', 'descriptor'): + stage = Probe() + if symbolic == 'mask': + stage.masks.add(1) + else: + stage.sym[1] = ('ptr', 0, 0) + try: + stage.one(MUL_HI, decode_one(sop2(MUL_HI, 3, 1, 2))[1]) + except G.Unsupported as error: + reason = 'a lane mask' if symbolic == 'mask' else 'descriptor data' + check('mul_hi refuses a symbolic %s' % symbolic, + str(error) == '%s on %s' % (MUL_HI, reason) and not stage.lines, str(error)) + else: + check('mul_hi refuses a symbolic %s' % symbolic, False, str(stage.lines)) + # An SGPR that held a compare mask is overwritten with a plain word, and is no longer a mask. + stage = Probe() + stage.masks.add(3) + stage.one(MUL_HI, decode_one(sop2(MUL_HI, 3, 1, 2))[1]) + check('mul_hi over a mask-marked destination writes the word and drops the mark', + stage.lines == ['s3 = mul_hi_u32(s1, s2);'] and 3 not in stage.masks, str((stage.lines, stage.masks))) + + # Mutations: each must read a wrong word or SCC somewhere in the value set. + saved_entry, saved_common = G.SCA[MUL_HI], G.Pipeline.common + table = { + 'the low word of the product': ('{0} * {1}', None), + 'the signed high word': ('mul_hi_u32({0}, {1}) - (({0} >> 31) != 0u ? {1} : 0u)' + ' - (({1} >> 31) != 0u ? {0} : 0u)', None), + 'an added SCC write': (saved_entry[0], '$ != 0'), + } + helper = { + 'the low-halfword carry dropped': (' + ((la * lb) >> 16)', ''), + 'the final carry limb dropped': ('(((middle & 0xffffu) + la * (b >> 16)) >> 16)', '((la * (b >> 16)) >> 16)'), + } + try: + for label, entry in table.items(): + G.SCA[MUL_HI] = entry + found = mul_mismatch() + check('mul_hi mutation with %s fails: %s' % (label, found), found is not None) + G.SCA[MUL_HI] = saved_entry + for label, (old, new) in helper.items(): + def mutated(self, old=old, new=new): + lines = saved_common(self) + assert sum(old in line for line in lines) == 1, old + return [line.replace(old, new) for line in lines] + G.Pipeline.common = mutated + found = mul_mismatch() + check('mul_hi mutation with %s fails: %s' % (label, found), found is not None) + G.Pipeline.common = saved_common + del G.SCA[MUL_HI] + disabled = mul_mismatch() + check('mul_hi negative control catches a disabled lowering', + disabled is not None and disabled[-1] == 'refused: %s' % MUL_HI, str(disabled)) + finally: + G.SCA[MUL_HI] = saved_entry + G.Pipeline.common = saved_common + + def controls(): # 1. The encoder writes what the decoder reads, checked on the LLVM 15 encodings in tests/rdna2_tools_check.py. known = [(sop2('s_nand_b32', 0, 1, 2), '0102008c'), (sop2('s_nor_b32', 0, 1, 2), '0102008d'), @@ -330,11 +475,12 @@ def controls(): check('%d SOP2 operations without a lowering are refused by name (%s)' % (len(missing), ', '.join(missing)), missing and not wrong and not set(OPS) & set(missing), str(wrong)) pack_controls() + mul_controls() def all_codes(): logic = [code(name, form) for name in list(OPS) + [s for s, _ in OPS.values()] for form in VALUE_FORMS + MASK_FORMS] - return logic + [code(PACK_HH, form) for form in VALUE_FORMS] + return logic + [code(name, form) for name in (PACK_HH, MUL_HI) for form in VALUE_FORMS] def check_binary(llvm_mc): diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 6c816ffb2e..1b54cd527e 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -821,10 +821,14 @@ def low(tok): srcs = [str(sopk_imm(srcs[0], True))] # D.i32 = signext(SIMM16) shift_add = base in SHIFT_ADD word_complement = base in ('s_nand_b32', 's_nor_b32', 's_xnor_b32') - word_pack = base == 's_pack_hh_b32_b16' + # s_mul_hi_u32 needs the whole 32-bit word of each source, like the halfword pack. + word_pack = base in ('s_pack_hh_b32_b16', 's_mul_hi_u32') if shift_add or word_complement or word_pack: - # The per-lane mask cannot supply the full word needed by these operations. - if self.is_lane_mask(dname) or any(self.is_lane_mask(t) for t in srcs): + # The per-lane mask cannot supply the full word needed by these operations. s_mul_hi_u32 into an + # SGPR that held a mask replaces it with a plain word (set_s drops the mark), so only vcc/exec count. + mask_dest = (dname in ('exec', 'exec_lo', 'exec_hi', 'vcc', 'vcc_lo', 'vcc_hi') if base == 's_mul_hi_u32' + else self.is_lane_mask(dname)) + if mask_dest or any(self.is_lane_mask(t) for t in srcs): raise Unsupported('%s on a lane mask' % base) if shift_add and dname != 'm0' and (not dst or dst[0] != 's' or dst[1] != dst[2] or dst[1] > 105): raise Unsupported('%s destination %s' % (base, dname)) @@ -2010,6 +2014,8 @@ def declarations(self): 's_min_i32': ('uint(min(int({0}), int({1})))', None), 's_max_i32': ('uint(max(int({0}), int({1})))', None), 's_bfe_u32': ('({0} >> ({1} & 31)) & ((1u << (({1} >> 16) & 127)) - 1)', '$ != 0'), 's_brev_b32': ('reversebits({0})', None), + # s_mul_hi_u32: high 32 bits of the unsigned 64-bit product; SCC unchanged. + 's_mul_hi_u32': ('mul_hi_u32({0}, {1})', None), 's_pack_hh_b32_b16': ('({0} >> 16) | ({1} & 0xffff0000u)', None), # s_bfm_b32: a mask of S0[4:0] ones shifted left by S1[4:0]; SCC unchanged. 's_bfm_b32': ('(((1u << ({0} & 31)) - 1) << ({1} & 31))', None), @@ -2184,6 +2190,10 @@ def common(self): ' return ftz32(sum);', '}', 'float med3(float a, float b, float c) { return max(min(a, b), min(max(a, b), c)); }', + # High half of an unsigned 32x32 product, by halfword products so it fits 32-bit HLSL. + 'uint mul_hi_u32(uint a, uint b) { uint la = a & 0xffffu, lb = b & 0xffffu;' + ' uint middle = (a >> 16) * lb + ((la * lb) >> 16);' + ' return (a >> 16) * (b >> 16) + (middle >> 16) + (((middle & 0xffffu) + la * (b >> 16)) >> 16); }', # The ten binary32 classes v_cmp_class_f32 tests, from the raw encoding (#1795). 'uint class32(float value) { uint bits = asuint(value), magnitude = bits & 0x7fffffffu;' ' bool negative = bits >= 0x80000000u;'