From 11652e9050ec96472ec16ab23a8ebe967477bc9e Mon Sep 17 00:00:00 2001 From: triggered02 <153171514+triggered02@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:13:50 +0530 Subject: [PATCH 1/2] startup: lower v_mul_hi_u32 to a halfword-product helper Fixes #1792. The high half of an unsigned 32x32 product had no lowering, so v_mul_hi_u32 was refused, including the census form with a literal operand (v_mul_hi_u32 v1, v0, 0xaaaaaaab) - one of the remaining refused shaders in the loading-screen cache (#870). tools/pixel_aot.py already had the halfword-product helper; it is ported into the gfx2hlsl preamble because these stages have no 64-bit multiply and the low half of a*b is not the high half. Both the register and literal forms lower; v_mul_lo_u32 is unchanged. Test builds VOP3A encodings (opcode 0x16a, literal source 255 followed by its dword), decodes, then translates, and also checks the helper is present in the common preamble and uses halfword products. Fail-first: lowering to a plain multiply fails 'the literal form uses the helper'; removing the helper fails 'the helper uses halfword products, not a 64-bit multiply'. Both presets pass. --- CMakeLists.txt | 3 + docs/experiments.md | 7 ++ tests/startup_gfx2hlsl_mul_hi_check.py | 110 +++++++++++++++++++++++++ tools/startup/gfx2hlsl.py | 6 +- 4 files changed, 125 insertions(+), 1 deletion(-) create mode 100644 tests/startup_gfx2hlsl_mul_hi_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 2deade1b55..096899f336 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1702,6 +1702,9 @@ if(EXISTS "${INTAKE_PYTHON}") # lowering of the same selections. add_test(NAME startup_gfx2hlsl_sdwa COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_sdwa_check.py") + # The high half of an unsigned 32x32 product (#1781). + add_test(NAME startup_gfx2hlsl_mul_hi COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_mul_hi_check.py") # SDWA forms of the float-result conversions (#1727). add_test(NAME startup_gfx2hlsl_sdwa_cvt COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_sdwa_cvt_check.py") diff --git a/docs/experiments.md b/docs/experiments.md index 32155c94f4..66e4c4efd9 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -5777,6 +5777,13 @@ uint-result table, so every `v_cvt_f32_*_sdwa` was refused until it was pointed restored path keeps the source selection, the `dst_sel`/`dst_unused` write and the `U(...)` wrapper, and a conversion's output modifier inside an SDWA form is still refused rather than dropped. +**The high half of an unsigned product.** `v_mul_hi_u32` had no lowering, so the form refused - one of the +remaining refused shaders in the first main-game loading-screen cache (#870, issue #1792). It now lowers to +a halfword-product helper carried in the shader preamble: the helper computes the high 32 bits by carrying +the low halfword product into the two cross products, because HLSL has no 64-bit multiply in these stages +and the low half of `a * b` is not the high half. The register and literal forms both lower; `v_mul_lo_u32` +is unchanged. Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_mul_hi$' -V`. + ## Pixel color without a texture sample For an unsampled pixel program, a matched P1/P2 interpolation in the entry mask can supply attr0.x/y/z/w from a four-component TEXCOORD0. The profile binds entry v0/v1 to the barycentric pair and the observed m0 source to the interpolation base. Each completed P2 produces a distinct value, including when the destination overwrites v0. The test vertex shader varies all four channels across a full-screen triangle. CPU references check all four output words at 1,024 pixel centers; an incorrect channel at an interior pixel must fail. Run `ctest --preset dev --no-tests=error -R '^pixel_aot_attribute_'`. diff --git a/tests/startup_gfx2hlsl_mul_hi_check.py b/tests/startup_gfx2hlsl_mul_hi_check.py new file mode 100644 index 0000000000..35bb2ed761 --- /dev/null +++ b/tests/startup_gfx2hlsl_mul_hi_check.py @@ -0,0 +1,110 @@ +"""`v_mul_hi_u32` in tools/startup/gfx2hlsl.py (issue #1792). + +usage: startup_gfx2hlsl_mul_hi_check.py + +The high half of an unsigned 32x32 product had no lowering, so `v_mul_hi_u32` was refused - one of the +remaining refused shaders in the main-game loading-screen cache (#870). `tools/pixel_aot.py` already had the +halfword-product helper; this port lowers the VOP3A form to it. + +The instruction bytes are **constructed here** from the field layout the checked-in decoder reads +(`tools/disasm_rdna2.py`, VOP3A branch): prefix `0b110101`, opcode `0x16a` in `w0[25:16]`, vdst in `w0[7:0]`, +src0 in `w1[8:0]`, src1 in `w1[17:9]`, and source 255 followed by a literal dword. +""" +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 = [] + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH'}") + if not condition: + failures.append(label) + if detail: + print(' ' + detail) + + +VOP3A_MUL_HI_U32 = 0x16A +V0, V1, V2 = 0x100, 0x101, 0x102 +LITERAL_SOURCE = 255 + + +def encode_vop3a(op, vdst, srcs, literal=None): + """Encode a native VOP3A instruction; a source of 255 is followed by its literal dword.""" + w0 = (0b110101 << 26) | ((op & 0x3FF) << 16) | (vdst & 0xFF) + w1 = 0 + for i, src in enumerate(srcs): + w1 |= (src & 0x1FF) << (9 * i) + code = struct.pack('> 16' in common, common[:200]) + +# 5. A neighbouring operation is untouched: the low-half multiply still lowers to a plain product. +VOP3A_MUL_LO_U32 = 0x169 +asm, emitted = translate(encode_vop3a(VOP3A_MUL_LO_U32, 1, [V1, V2])) +check('the low multiply is unchanged', emitted == 'v1 = v1 * v2;', emitted) + +if failures: + print('FAIL') + for text in failures: + print(' ' + text) + sys.exit(1) +print('PASS') \ No newline at end of file diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index fc60a41aad..21f2ffb02c 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -1110,7 +1110,7 @@ def declarations(self): # operands are uints; the result is a uint expression VEC_U = { 'v_add_nc_u32': (2, '{0} + {1}'), 'v_sub_nc_u32': (2, '{0} - {1}'), 'v_subrev_nc_u32': (2, '{1} - {0}'), - 'v_mul_lo_u32': (2, '{0} * {1}'), 'v_and_b32': (2, '{0} & {1}'), 'v_or_b32': (2, '{0} | {1}'), 'v_xor_b32': (2, '{0} ^ {1}'), + 'v_mul_lo_u32': (2, '{0} * {1}'), 'v_mul_hi_u32': (2, 'mul_hi_u32({0}, {1})'), 'v_and_b32': (2, '{0} & {1}'), 'v_or_b32': (2, '{0} | {1}'), 'v_xor_b32': (2, '{0} ^ {1}'), 'v_not_b32': (1, '~{0}'), 'v_lshlrev_b32': (2, '{1} << ({0} & 31)'), 'v_lshrrev_b32': (2, '{1} >> ({0} & 31)'), 'v_ashrrev_i32': (2, 'uint(int({1}) >> ({0} & 31))'), 'v_min_u32': (2, 'min({0}, {1})'), 'v_max_u32': (2, 'max({0}, {1})'), 'v_min_i32': (2, 'uint(min(int({0}), int({1})))'), 'v_max_i32': (2, 'uint(max(int({0}), int({1})))'), @@ -1270,6 +1270,10 @@ def common(self): out = ['#define F(x) asfloat(x)', '#define U(x) asuint(x)', 'float mul_legacy(float a, float b) { return (a == 0.0 || b == 0.0) ? 0.0 : a * b; }', '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); }', 'uint ldu(ByteAddressBuffer b, uint a) { uint k = (a & 3) * 8, lo = b.Load(a & ~3u); if (k == 0) return lo; ' 'return (lo >> k) | (b.Load((a & ~3u) + 4) << (32 - k)); }', 'cbuffer entry : register(b0) { %s };' % ' '.join('uint ud%d;' % i for i in range(len(self.uds)))] From 6782e7248adcbd144ae5af49891a476863692341 Mon Sep 17 00:00:00 2001 From: triggered02 <153171514+triggered02@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:02:44 +0530 Subject: [PATCH 2/2] startup: check the mul_hi helper by value, not by text Review on #1793 (P2): the checks compared emitted text only, so a wrong carry passed. The test now carries a small recursive-descent evaluator for the integer HLSL the helper emits (C precedence for * + - >> << & ^ |), extracts the helper body from Pipeline.common() and runs it for 20169 input pairs: all pairs of the 13 edge values from the review plus 20000 pseudo-random pairs from a fixed LCG, compared against the exact (a*b) >> 32. Fail-first: dropping the low-product carry, or replacing the middle carry term with its low half, each fails this check while the old text checks still passed. --- tests/startup_gfx2hlsl_mul_hi_check.py | 109 +++++++++++++++++++++++++ 1 file changed, 109 insertions(+) diff --git a/tests/startup_gfx2hlsl_mul_hi_check.py b/tests/startup_gfx2hlsl_mul_hi_check.py index 35bb2ed761..e95949cd5b 100644 --- a/tests/startup_gfx2hlsl_mul_hi_check.py +++ b/tests/startup_gfx2hlsl_mul_hi_check.py @@ -11,6 +11,7 @@ src0 in `w1[8:0]`, src1 in `w1[17:9]`, and source 255 followed by a literal dword. """ import os +import re import struct import sys @@ -102,6 +103,114 @@ def translate(code): asm, emitted = translate(encode_vop3a(VOP3A_MUL_LO_U32, 1, [V1, V2])) check('the low multiply is unchanged', emitted == 'v1 = v1 * v2;', emitted) +# ---- value-level check of the emitted helper -------------------------------------------------------------- +# The reference is the exact product, so a wrong carry in the helper must fail even though the emitted text is +# unchanged. The evaluator covers the integer operators this helper uses, with C precedence. +TOKEN = re.compile(r'\s*(0x[0-9a-fA-F]+u?|\d+u?|[A-Za-z_]\w*|>>|<<|[&|^()*+-])') + + +def tokens(source): + out, position = [], 0 + while position < len(source): + match = TOKEN.match(source, position) + if not match: + raise ValueError('cannot tokenise %r' % source[position:position + 20]) + out.append(match.group(1)) + position = match.end() + return out + + +class Expr: + """A recursive-descent evaluator for the 32-bit integer HLSL the mul_hi helper emits.""" + + LEVELS = [('|',), ('^',), ('&',), ('>>', '<<'), ('+', '-'), ('*',)] + + def __init__(self, source, variables): + self.items, self.at, self.vars = tokens(source), 0, variables + + def peek(self): + return self.items[self.at] if self.at < len(self.items) else '' + + def take(self): + item = self.peek() + self.at += 1 + return item + + def value(self): + return self.binary(0) + + def binary(self, level): + if level == len(self.LEVELS): + return self.unary() + left = self.binary(level + 1) + while self.peek() in self.LEVELS[level]: + operator = self.take() + right = self.binary(level + 1) + if operator == '*': + left = (left * right) & 0xFFFFFFFF + elif operator == '+': + left = (left + right) & 0xFFFFFFFF + elif operator == '-': + left = (left - right) & 0xFFFFFFFF + elif operator == '&': + left &= right + elif operator == '^': + left ^= right + elif operator == '|': + left |= right + elif operator == '>>': + left >>= right + elif operator == '<<': + left = (left << right) & 0xFFFFFFFF + return left + + def unary(self): + item = self.take() + if item == '(': + value = self.value() + if self.take() != ')': + raise ValueError('missing )') + return value + if re.fullmatch(r'0x[0-9a-fA-F]+u?', item): + return int(item.rstrip('u'), 16) + if re.fullmatch(r'\d+u?', item): + return int(item.rstrip('u')) + return self.vars[item] + + +def evaluate_mul_hi(helper, a, b): + """Run the emitted helper body for one pair, so what is checked is the value it returns.""" + body = helper[helper.index('{') + 1:helper.rindex('}')] + variables = {'a': a, 'b': b} + for statement in (piece.strip() for piece in body.split(';')): + if not statement: + continue + if statement.startswith('uint '): + for part in statement[4:].split(','): + name, expr = (piece.strip() for piece in part.split('=', 1)) + variables[name] = Expr(expr, variables).value() & 0xFFFFFFFF + elif statement.startswith('return '): + return Expr(statement[7:], variables).value() & 0xFFFFFFFF + raise ValueError('the helper returned nothing for %#x %#x' % (a, b)) + + +_pipe = object.__new__(G.Pipeline) +_pipe.uds, _pipe.resources, _pipe.samplers, _pipe.uses_sampler_heap = [], {}, {}, False +mul_hi_text = [entry for entry in _pipe.common() if 'uint mul_hi_u32(' in entry][0] +edges = [0, 1, 2, 0xFFFF, 0x10000, 0x10001, 0x7FFFFFFF, 0x80000000, + 0x80000001, 0xFFFEFFFF, 0xFFFF0000, 0xFFFFFFFF, 0x12345678] +pairs = [(a, b) for a in edges for b in edges] +state = 0x2545F491 +for _ in range(20000): + state = (state * 1103515245 + 12345) & 0xFFFFFFFF + first = state + state = (state * 1103515245 + 12345) & 0xFFFFFFFF + pairs.append((first, state)) +mismatches = [(a, b, (a * b) >> 32, evaluate_mul_hi(mul_hi_text, a, b)) for a, b in pairs + if evaluate_mul_hi(mul_hi_text, a, b) != ((a * b) >> 32)] +check('the emitted helper agrees with the exact product on %d pairs' % len(pairs), not mismatches, + repr(mismatches[:4])) + if failures: print('FAIL') for text in failures: