From 83652068628f90b5fb501ba45bf6857a6306b5dc Mon Sep 17 00:00:00 2001 From: tedin7 Date: Wed, 25 Nov 2026 01:01:28 +0100 Subject: [PATCH 1/6] startup: lower frexp, floor and round-to-plus-infinity conversions and ldexp in gfx2hlsl Part of #1723 Adds v_frexp_mant_f32, v_frexp_exp_i32_f32, v_cvt_flr_i32_f32, v_cvt_rpi_i32_f32 and v_ldexp_f32 to the pixel-stage lowering, with a pure-Python check registered in CMake. --- CMakeLists.txt | 4 + tests/startup_gfx2hlsl_frexp_cvt_check.py | 250 ++++++++++++++++++++++ tools/startup/gfx2hlsl.py | 55 +++++ 3 files changed, 309 insertions(+) create mode 100644 tests/startup_gfx2hlsl_frexp_cvt_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 09cf1ebf29..23b1929d7a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2716,6 +2716,10 @@ if(EXISTS "${INTAKE_PYTHON}") # 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") + # v_frexp_mant_f32, v_frexp_exp_i32_f32, v_cvt_flr_i32_f32, v_cvt_rpi_i32_f32 and v_ldexp_f32 (#1723). + add_test(NAME startup_gfx2hlsl_frexp_cvt COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_frexp_cvt_check.py") + set_tests_properties(startup_gfx2hlsl_frexp_cvt PROPERTIES TIMEOUT 60) # VOPC SDWA compares (#1906): every integer compare, select and sext() evaluated against an integer # reference; floating-point SDWA forms and unsupported modifiers are refused. The draws are registered below. add_test(NAME startup_gfx2hlsl_vopc_sdwa COMMAND "${INTAKE_PYTHON}" -B diff --git a/tests/startup_gfx2hlsl_frexp_cvt_check.py b/tests/startup_gfx2hlsl_frexp_cvt_check.py new file mode 100644 index 0000000000..f70c5b64c7 --- /dev/null +++ b/tests/startup_gfx2hlsl_frexp_cvt_check.py @@ -0,0 +1,250 @@ +"""v_frexp_mant_f32, v_frexp_exp_i32_f32, v_cvt_flr_i32_f32, v_cvt_rpi_i32_f32 and v_ldexp_f32 in +tools/startup/gfx2hlsl.py (FRONTIER_NEXT_BATCH_3 item 7). + +usage: startup_gfx2hlsl_frexp_cvt_check.py (pure Python, no compiler) + +Each operation is lowered by the translator, then the emitted HLSL line is run on the CPU by a small evaluator +(binary32 rounding after every float multiply). The references follow the AMD RDNA 2 ISA reference: + frexp_mant: sign and mantissa in [0.5, 1) of a normal input; zero and denormal give a signed zero; inf and NaN + pass through. + frexp_exp: the matching exponent; 0 for zero, denormal, inf and NaN. + cvt_flr / cvt_rpi: floor(x) / floor(x + 0.5), saturated to int32, NaN reads 0. + ldexp: S0 * 2^S1 with S1 a signed integer. +Not covered: denormal inputs and results of v_ldexp_f32 (the denormal mode decides them) and signaling-NaN payloads. +""" +import math +import re +import struct +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / 'tools' / 'startup')) +import gfx2hlsl as G # noqa: E402 + +MASK = 0xffffffff +TOKEN = re.compile(r'0x[0-9a-fA-F]+u?|\d+\.\d+|\d+u?|[A-Za-z_]\w*|\|\||==|!=|<=|>=|>>|<<|[-+*/&|?:(),<>!~]') +BINARY = [['||'], ['|'], ['&'], ['==', '!='], ['<', '>', '<=', '>='], ['<<', '>>'], ['+', '-'], ['*', '/']] + + +def f32(x): + try: + return struct.unpack('= 1 << 31 else x + + +FUNCS = { + 'U': bits, 'F': value, 'uint': lambda x: int(x) & MASK, 'int': to_int, 'float': float, + 'floor': lambda x: x if math.isinf(x) else float(math.floor(x)), 'max': max, 'exp2': lambda x: f32(2.0 ** x), + 'clamp': lambda x, lo, hi: min(max(x, lo), hi), 'saturate': lambda x: min(max(x, 0.0), 1.0), +} + + +def idiv(a, b): + return int(a / b) + + +def mul(a, b): + return f32(a * b) if isinstance(a, float) or isinstance(b, float) else (a * b) & MASK + + +class Parser: + """C-precedence parser for the emitted subset; produces a Python expression string.""" + + def __init__(self, text): + self.t = TOKEN.findall(text) + assert ''.join(self.t) == re.sub(r'\s+', '', text), text + self.i = 0 + self.out = self.ternary() + assert self.i == len(self.t), text + + def peek(self): + return self.t[self.i] if self.i < len(self.t) else None + + def take(self): + self.i += 1 + return self.t[self.i - 1] + + def ternary(self): + cond = self.binary(0) + if self.peek() != '?': + return cond + self.take() + yes = self.ternary() + assert self.take() == ':' + return '(%s if %s else %s)' % (yes, cond, self.ternary()) + + def binary(self, level): + if level == len(BINARY): + return self.unary() + node = self.binary(level + 1) + while self.peek() in BINARY[level]: + op = self.take() + right = self.binary(level + 1) + if op == '||': + node = '(%s or %s)' % (node, right) + elif op == '/': + node = 'idiv(%s, %s)' % (node, right) + elif op == '*': + node = 'mul(%s, %s)' % (node, right) + else: + node = '(%s %s %s)' % (node, op, right) + return node + + def unary(self): + token = self.take() + if token == '-': + return '(-%s)' % self.unary() + if token == '(': + node = self.ternary() + assert self.take() == ')' + return node + if token[0].isdigit(): + return repr(float(token)) if '.' in token else str(int(token.rstrip('u'), 0)) + if self.peek() != '(': + return token + self.take() + args = [self.ternary()] + while self.peek() == ',': + self.take() + args.append(self.ternary()) + assert self.take() == ')' + return '%s(%s)' % (token, ', '.join(args)) + + +def lowered(base, asm): + """The right-hand side of the one register write the translator emits for `asm`.""" + stage = G.Stage.__new__(G.Stage) + stage.sym, stage.used_s, stage.used_v, stage.uniform_v = {}, set(), set(), set() + stage.exec_known, stage.has_branches, stage.lines = True, False, [] + stage.one(base, asm) + assert len(stage.lines) == 1, stage.lines + match = re.fullmatch(r'v3 = (.*);', stage.lines[0]) + assert match, stage.lines + return match.group(1) + + +def run(text, **regs): + env = dict(FUNCS, idiv=idiv, mul=mul, **regs) + return eval(Parser(text).out, {'__builtins__': {}}, env) + + +# ---- references ---------------------------------------------------------------------------------------- +def ref_frexp_mant(w): + e = w >> 23 & 255 + if e == 255: + return w + if e == 0: + return w & 0x80000000 + mant, _ = math.frexp(value(w)) + return bits(mant) + + +def ref_frexp_exp(w): + e = w >> 23 & 255 + return 0 if e in (0, 255) else math.frexp(value(w))[1] & MASK + + +def saturate_int(x): + if x != x: + return 0 + return max(-2 ** 31, min(2 ** 31 - 1, math.floor(x))) & MASK if not math.isinf(x) else ( + MASK >> 1 if x > 0 else 0x80000000) + + +def ref_cvt_flr(w): + return saturate_int(value(w)) + + +def ref_cvt_rpi(w): + x = value(w) + return saturate_int(x if math.isinf(x) or x != x else math.floor(x + 0.5)) + + +def ref_ldexp(a, n): + n = n - (1 << 32) if n >= 1 << 31 else n + x = value(a) + if x != x or math.isinf(x) or x == 0.0: + return a + try: + return bits(math.ldexp(x, max(-400, min(400, n)))) + except OverflowError: + return bits(math.copysign(math.inf, x)) + + +NAN, INF = 0x7fc00000, 0x7f800000 +FLOATS = [0.0, -0.0, 1.0, -1.0, 0.5, -0.5, 0.75, 1.5, -2.5, 3.0, 0.1, -0.1, 0.4999, 0.5001, -0.5001, 1e-5, + 123456.789, -98765.4, 1.0e20, -1.0e20, 2.0 ** -126, 2.0 ** 127, 1.7014118e38, 8388608.5, 2147483520.0, + -2147483648.0, 2.0 ** 31, -2.0 ** 33, 3.4028235e38, -3.4028235e38] +WORDS = [bits(x) for x in FLOATS] + [NAN, INF, INF | 0x80000000, 0x00000001, 0x80400000, 0x007fffff] +SHIFTS = [0, 1, -1, 5, -5, 24, -24, 100, -100, 126, -126, 127, -127, 200, -200, 299, 300, 301, -300, 1000, -1000, + 2 ** 31 - 1, -2 ** 31] + +failures = [] + + +def check(label, got, want, case): + if got != want: + failures.append(label) + print('%s: MISMATCH %s got 0x%08x want 0x%08x' % (label, case, got, want)) + + +def unary(label, name, ref): + for w in WORDS: + for suffix in ('e32', 'e64'): + got = run(lowered('%s_%s' % (name, suffix), '%s_%s v3, v1' % (name, suffix)), v1=w) + check('%s_%s' % (label, suffix), got & MASK, ref(w) & MASK, hex(w)) + print('%s: %d inputs' % (label, len(WORDS))) + + +def main(): + unary('v_frexp_mant_f32', 'v_frexp_mant_f32', ref_frexp_mant) + unary('v_frexp_exp_i32_f32', 'v_frexp_exp_i32_f32', ref_frexp_exp) + unary('v_cvt_flr_i32_f32', 'v_cvt_flr_i32_f32', ref_cvt_flr) + unary('v_cvt_rpi_i32_f32', 'v_cvt_rpi_i32_f32', ref_cvt_rpi) + count = 0 + for a in [bits(x) for x in FLOATS if x != 2.0 ** -126] + [NAN, INF, INF | 0x80000000]: + for n in SHIFTS: + got = run(lowered('v_ldexp_f32', 'v_ldexp_f32 v3, v1, v2'), v1=a, v2=n & MASK) + want = ref_ldexp(a, n & MASK) + if (got & MASK) != want and not (got != got and want != want): + check('v_ldexp_f32', got & MASK, want, '%s << %d' % (hex(a), n)) + count += 1 + print('v_ldexp_f32: %d inputs' % count) + # Source and output modifiers: negation reaches the operand, mul:2 scales the result, and the operations + # that cannot carry a modifier refuse it. + check('ldexp neg', run(lowered('v_ldexp_f32', 'v_ldexp_f32 v3, -v1, v2'), v1=bits(1.5), v2=2) & MASK, + bits(-6.0), 'neg') + check('ldexp mul:2', run(lowered('v_ldexp_f32', 'v_ldexp_f32 v3, v1, v2 mul:2'), v1=bits(1.5), v2=2) & MASK, + bits(12.0), 'mul:2') + for asm in ('v_cvt_flr_i32_f32_e64 v3, v1 clamp', 'v_cvt_rpi_i32_f32_e64 v3, v1 mul:2', + 'v_frexp_exp_i32_f32_e64 v3, v1 clamp'): + try: + lowered(asm.split()[0], asm) + except G.Unsupported: + continue + failures.append(asm) + print('accepted a modifier: ' + asm) + if failures: + print('FAILED: %d' % len(failures)) + return 1 + print('gfx2hlsl frexp/cvt/ldexp check passed') + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 673c53f331..2d9b3f27d3 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -2724,6 +2724,61 @@ def op_v_mbcnt_lo_u32_b32(self, ops, mods, high=False): def op_v_mbcnt_hi_u32_b32(self, ops, mods): self.op_v_mbcnt_lo_u32_b32(ops, mods, high=True) + def float_bits(self, tok): + """uint bits of a float source, with the inline neg/abs operand modifiers applied.""" + return 'U(%s)' % self.f(tok) + + def op_v_frexp_mant_f32(self, ops, mods): + # Sign and mantissa in [0.5, 1) of a normal input; zero and denormals read as a signed zero; + # infinity and NaN pass through unchanged (RDNA 2 ISA, V_FREXP_MANT_F32). + if len(ops) != 2: + raise Unsupported('v_frexp_mant_f32 with %d operands, expected 2' % len(ops)) + b = self.float_bits(ops[1]) + e = '((%s >> 23) & 255u)' % b + expr = 'F(%s == 255u ? %s : %s == 0u ? (%s & 0x80000000u) : ((%s & 0x807fffffu) | 0x3f000000u))' % ( + e, b, e, b, b) + self.set_vf(reg_range(ops[0])[1], expr, mods) + + def op_v_frexp_exp_i32_f32(self, ops, mods): + # Exponent e with input = mantissa * 2^e and mantissa in [0.5, 1). Zero, denormal, infinity and NaN give 0. + if mods: + raise Unsupported('v_frexp_exp_i32_f32 with modifiers') + if len(ops) != 2: + raise Unsupported('v_frexp_exp_i32_f32 with %d operands, expected 2' % len(ops)) + e = '((%s >> 23) & 255u)' % self.float_bits(ops[1]) + self.set_v(reg_range(ops[0])[1], '(%s == 0u || %s == 255u) ? 0u : (%s - 126u)' % (e, e, e)) + + def float_to_int(self, base, ops, mods, rounded): + # Saturating conversion of the rounded float; NaN reads 0. v_cvt_flr rounds toward -inf, v_cvt_rpi + # rounds floor(x + 0.5). A value at or above 2^31 reads INT_MAX; one below -2^31 reads INT_MIN. + if mods: + raise Unsupported('%s with modifiers' % base) + if len(ops) != 2: + raise Unsupported('%s with %d operands, expected 2' % (base, len(ops))) + x = self.f(ops[1]) + r = 'floor(%s)' % (rounded % x) + self.set_v(reg_range(ops[0])[1], '(%s != %s) ? 0u : (%s >= 2147483648.0) ? 0x7fffffffu : uint(int(max(%s, -2147483648.0)))' % ( + x, x, r, r)) + + def op_v_cvt_flr_i32_f32(self, ops, mods): + self.float_to_int('v_cvt_flr_i32_f32', ops, mods, '%s') + + def op_v_cvt_rpi_i32_f32(self, ops, mods): + self.float_to_int('v_cvt_rpi_i32_f32', ops, mods, '%s + 0.5') + + def op_v_ldexp_f32(self, ops, mods): + # D = S0 * 2^S1 with S1 a signed integer, clamped to +-300 (the result is 0 or inf past that anyway). + # The scale is applied in three parts of at most 2^100 each, so that no factor overflows binary32 + # when the product is finite. + if len(ops) != 3: + raise Unsupported('v_ldexp_f32 with %d operands, expected 3' % len(ops)) + n = 'clamp(int(%s), -300, 300)' % self.u(ops[2]) + a = '(%s / 3)' % n + b = '((%s - %s) / 2)' % (n, a) + c = '(%s - %s - %s)' % (n, a, b) + expr = '((%s * exp2(float(%s))) * exp2(float(%s))) * exp2(float(%s))' % (self.f(ops[1]), a, b, c) + self.set_vf(reg_range(ops[0])[1], expr, mods) + def op_v_readfirstlane_b32(self, ops, mods): src, dst = reg_range(ops[1]), reg_range(ops[0]) past_entry = getattr(self, 'past_entry', True) From 8bd517ed5eb9c80012dd2bd966bb8986e0730530 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Wed, 25 Nov 2026 01:35:54 +0100 Subject: [PATCH 2/6] tests: add a D3D12 draw check for the frexp, float-to-int and ldexp lowerings in gfx2hlsl --- CMakeLists.txt | 10 + .../startup_gfx2hlsl_frexp_cvt_warp_check.py | 180 ++++++++++++++++++ 2 files changed, 190 insertions(+) create mode 100644 tests/startup_gfx2hlsl_frexp_cvt_warp_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 23b1929d7a..92a9dd755e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2990,6 +2990,16 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_gfx2hlsl_sgpr_spill_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) endforeach() + # gfx2hlsl frexp, float-to-int conversions and ldexp (#1723): translation controls, then a desktop draw of each + # operation compared with a reference computed from Python doubles, with a mutated lowering that must differ. + add_test(NAME startup_gfx2hlsl_frexp_cvt_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_frexp_cvt_warp_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_frexp_cvt_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_frexp_cvt_warp_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_frexp_cvt_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + endforeach() # gfx2hlsl v_cmpx_le_i32_sdwa on a sign-extended byte decides which of 16 x 16 pixels survive, checked # pixel by pixel (#1906); translations without the select or without sext() must fail the same draw. foreach(adapter IN ITEMS warp hardware) diff --git a/tests/startup_gfx2hlsl_frexp_cvt_warp_check.py b/tests/startup_gfx2hlsl_frexp_cvt_warp_check.py new file mode 100644 index 0000000000..64c9b69b34 --- /dev/null +++ b/tests/startup_gfx2hlsl_frexp_cvt_warp_check.py @@ -0,0 +1,180 @@ +"""D3D12 draw check for v_frexp_mant_f32, v_frexp_exp_i32_f32, v_cvt_flr_i32_f32, v_cvt_rpi_i32_f32 and +v_ldexp_f32 in tools/startup/gfx2hlsl.py (Part of #1723). + + (no arguments) translation controls, pure Python + binary reassemble the fixture bodies and compare them with the words below + draw [fxc] + compile the translated pair with FXC ps_5_1 when given and with DXC ps_6_0, + draw one pixel per input chunk and compare the four result words + +The fixture reuses the flat-parameter pixel prologue of startup_gfx2hlsl_bit_alu_check.py: twelve words arrive in +v0..v11 and v12..v15 are exported. Each operation runs on four lanes per pixel (source words v0..v3, the ldexp +exponents v4..v7). + +The expected words come from the references of startup_gfx2hlsl_frexp_cvt_check.py (math.frexp, math.floor and +math.ldexp on Python doubles), not from the lowering. Each lowering has a mutation (a changed constant) whose draw +must read other words, so a draw that cannot see the difference fails the check. Denormal inputs and results are +left out: the denormal mode decides them. +""" +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 +import startup_gfx2hlsl_frexp_cvt_check as R # 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, # noqa: E402 + vs_source, vs_words) + +MASK = 0xffffffff +UNARY = ('v_frexp_mant_f32', 'v_frexp_exp_i32_f32', 'v_cvt_flr_i32_f32', 'v_cvt_rpi_i32_f32') +OPS = UNARY + ('v_ldexp_f32',) +REFERENCE = {'v_frexp_mant_f32': R.ref_frexp_mant, 'v_frexp_exp_i32_f32': R.ref_frexp_exp, + 'v_cvt_flr_i32_f32': R.ref_cvt_flr, 'v_cvt_rpi_i32_f32': R.ref_cvt_rpi} +# mnemonic -> (text the lowering must contain, replacement that changes the result) +MUTATION = {'v_frexp_mant_f32': ('0x3f000000u', '0x3f800000u'), + 'v_frexp_exp_i32_f32': ('- 126u', '- 127u'), + 'v_cvt_flr_i32_f32': ('floor(', 'ceil('), + 'v_cvt_rpi_i32_f32': ('+ 0.5', '+ 0.25'), + 'v_ldexp_f32': ('exp2(float(', '-exp2(float(')} +BODY_SOURCE = {op: ''.join('%s v%d, v%d\n' % (op, 12 + i, i) for i in range(4)) for op in UNARY} +BODY_SOURCE['v_ldexp_f32'] = ''.join('v_ldexp_f32 v%d, v%d, v%d\n' % (12 + i, i, 4 + i) for i in range(4)) + +# Normal, finite, inf and NaN inputs; the cvt inputs include the saturating ends. +UNARY_INPUTS = [R.bits(x) for x in (1.0, -1.0, 0.5, 0.75, -2.5, 3.0, 0.1, -0.1, 0.4999, 0.5001, 123456.789, + -98765.4, 1.0e20, -1.0e20, 2.0 ** 127, 8388608.5, 2147483520.0, + -2147483648.0, 2.0 ** 31, -2.0 ** 33, 3.4028235e38, 0.0, -0.0, 2.0 ** -126)] +UNARY_INPUTS += [R.INF, R.INF | 0x80000000, R.NAN, 0x7f7fffff] +LDEXP_INPUTS = [(R.bits(a), n & MASK) for a, n in ( + (1.0, 1), (1.5, -1), (-1.5, 5), (0.1, 24), (123456.789, -20), (-3.0, 100), (1.0, 127), (1.0, -126), + (1.0, 200), (-1.0, -200), (0.0, 5), (-0.0, -5), (1.0, 2 ** 31 - 1), (1.0, -2 ** 31), (2.0, 300), (1.5, 0))] +LDEXP_INPUTS += [(R.INF, 3), (R.INF | 0x80000000, -3 & MASK), (R.NAN, 7), (R.bits(3.0), 2)] + + +def chunks(op): + """(12 parameter words, 4 expected result words) per pixel.""" + out = [] + if op == 'v_ldexp_f32': + for i in range(0, len(LDEXP_INPUTS), 4): + part = LDEXP_INPUTS[i:i + 4] + out.append(([a for a, _ in part] + [n for _, n in part] + [0] * 4, [R.ref_ldexp(a, n) for a, n in part])) + else: + for i in range(0, len(UNARY_INPUTS), 4): + part = UNARY_INPUTS[i:i + 4] + out.append((part + [0] * 8, [REFERENCE[op](w) & MASK for w in part])) + return out + + +def mutate_text(op, text): + old, new = MUTATION[op] + mutated = text.replace(old, new) + assert mutated != text, op + return mutated + + +def sets_for(words): + """The four (src0, src1, src2) tuples vs_words() turns into parameter words 0..11 in order.""" + return [(words[lane], words[4 + lane], words[8 + lane]) for lane in range(4)] + + +def ps_words(op): + return PRE_WORDS + BODY_WORDS[op] + POST_WORDS + + +BODY_WORDS = { + 'v_frexp_mant_f32': bytes.fromhex('0081187e01811a7e02811c7e03811e7e'), + 'v_frexp_exp_i32_f32': bytes.fromhex('007f187e017f1a7e027f1c7e037f1e7e'), + 'v_cvt_flr_i32_f32': bytes.fromhex('001b187e011b1a7e021b1c7e031b1e7e'), + 'v_cvt_rpi_i32_f32': bytes.fromhex('0019187e01191a7e02191c7e03191e7e'), + 'v_ldexp_f32': bytes.fromhex('0c0062d7000902000d0062d7010b02000e0062d7020d02000f0062d7030f0200'), +} + + +def translate(op, mutate=False): + pipe = G.Pipeline(vs_words([(0, 0, 0)] * 4), ps_words(op), root_blob()) + text = pipe.hlsl_ps() + return pipe, mutate_text(op, text) if mutate else text + + +def check(label, ok): + print('%s: %s' % (label, 'ok' if ok else 'MISMATCH')) + if not ok: + raise AssertionError(label) + + +def controls(): + for op in OPS: + check('%s fixture has 12 words per pixel' % op, all(len(w) == 12 and len(e) == 4 for w, e in chunks(op))) + check('%s inputs fill every lane' % op, sum(len(e) for _, e in chunks(op)) == ( + len(LDEXP_INPUTS) if op == 'v_ldexp_f32' else len(UNARY_INPUTS))) + check('%s mutation changes the translation' % op, translate(op, True)[1] != translate(op)[1]) + + +def check_binary(llvm_mc): + for op, source in BODY_SOURCE.items(): + words = assemble(llvm_mc, source) + if op in BODY_WORDS and BODY_WORDS[op] != words: + raise AssertionError('%s: assembled %s, recorded %s' % (op, words.hex(), BODY_WORDS[op].hex())) + print(" '%s': bytes.fromhex('%s')," % (op, words.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 in OPS: + for words, _ in chunks(op): + sets = sets_for(words) + if assemble(llvm_mc, vs_source(sets)) != vs_words(sets): + raise AssertionError('vertex fixture for %s differs from llvm-mc' % (sets,)) + print('fixture words match llvm-mc') + + +def words_text(values): + return ','.join('%08x' % v for v in values) + + +def check_draw(dxc, renderer, adapter, fxc=None): + controls() + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + for op in OPS: + good_ps = compile_hlsl(compiler, kind, translate(op)[1], 'ps_%s_%s' % (op, kind), ps_profile, directory) + bad_ps = compile_hlsl(compiler, kind, translate(op, True)[1], 'mutated_%s_%s' % (op, kind), + ps_profile, directory) + caught = 0 + for index, (words, expected) in enumerate(chunks(op)): + vs = compile_hlsl(compiler, kind, G.Pipeline(vs_words(sets_for(words)), ps_words(op), + root_blob()).hlsl_vs(), + 'vs_%s_%d_%s' % (op, index, kind), vs_profile, directory) + want = words_text(expected) + run = draw(renderer, adapter, vs, good_ps, want) + if run.returncode: + raise AssertionError('%s %s pixel %d expected %s\n%s\n%s' % (kind, op, index, want, run.stdout, + run.stderr)) + print('%s %s pixel %d: %s' % (kind, op, index, want), flush=True) + run = draw(renderer, adapter, vs, bad_ps, want) + caught += run.returncode != 0 + if not caught: + raise AssertionError('%s %s: no pixel told the mutated lowering from the reference' % (kind, op)) + print('%s %s mutation: %d pixels read other words' % (kind, op, caught), flush=True) + + +def main(): + if len(sys.argv) == 1: + controls() + print('gfx2hlsl frexp/cvt draw fixture: controls passed') + return + mode, *args = sys.argv[1:] + if mode == 'binary': + check_binary(*args) + elif mode == 'draw': + check_draw(*args) + else: + raise SystemExit(__doc__) + + +if __name__ == '__main__': + main() From 57156788b3e27c37f4c2cf8a8177dc0c4300c7e8 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Wed, 25 Nov 2026 01:38:39 +0100 Subject: [PATCH 3/6] fix: read NaN as zero in the float-to-int lowering with isnan, which the shader compiler keeps --- tests/startup_gfx2hlsl_frexp_cvt_check.py | 2 +- tools/startup/gfx2hlsl.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/startup_gfx2hlsl_frexp_cvt_check.py b/tests/startup_gfx2hlsl_frexp_cvt_check.py index f70c5b64c7..13a44833c4 100644 --- a/tests/startup_gfx2hlsl_frexp_cvt_check.py +++ b/tests/startup_gfx2hlsl_frexp_cvt_check.py @@ -50,7 +50,7 @@ def to_int(x): FUNCS = { 'U': bits, 'F': value, 'uint': lambda x: int(x) & MASK, 'int': to_int, 'float': float, 'floor': lambda x: x if math.isinf(x) else float(math.floor(x)), 'max': max, 'exp2': lambda x: f32(2.0 ** x), - 'clamp': lambda x, lo, hi: min(max(x, lo), hi), 'saturate': lambda x: min(max(x, 0.0), 1.0), + 'isnan': lambda x: x != x, 'clamp': lambda x, lo, hi: min(max(x, lo), hi), 'saturate': lambda x: min(max(x, 0.0), 1.0), } diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 2d9b3f27d3..6691e46f8a 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -2757,8 +2757,8 @@ def float_to_int(self, base, ops, mods, rounded): raise Unsupported('%s with %d operands, expected 2' % (base, len(ops))) x = self.f(ops[1]) r = 'floor(%s)' % (rounded % x) - self.set_v(reg_range(ops[0])[1], '(%s != %s) ? 0u : (%s >= 2147483648.0) ? 0x7fffffffu : uint(int(max(%s, -2147483648.0)))' % ( - x, x, r, r)) + self.set_v(reg_range(ops[0])[1], 'isnan(%s) ? 0u : (%s >= 2147483648.0) ? 0x7fffffffu : uint(int(max(%s, -2147483648.0)))' % ( + x, r, r)) def op_v_cvt_flr_i32_f32(self, ops, mods): self.float_to_int('v_cvt_flr_i32_f32', ops, mods, '%s') From d8c21fb293414eee34dcffd0f44b0f535347f94d Mon Sep 17 00:00:00 2001 From: tedin7 Date: Wed, 25 Nov 2026 02:02:38 +0100 Subject: [PATCH 4/6] shader: exact cvt_rpi rounding, sign-dependent NaN saturation and docs for startup frexp/cvt/ldexp (Part of #1723) v_cvt_flr/rpi now read 0x7fffffff for a positive NaN and 0x80000000 for a negative one, and v_cvt_rpi adds 1 to floor(x) from the exact fraction instead of binary32 x + 0.5. The CPU evaluator rounds binary32 add/sub, the reference table gains the 0x3effffff, 2^23+1 and NaN rows, and docs/experiments.md describes the startup lowering and its check. --- docs/experiments.md | 13 ++++++++ tests/startup_gfx2hlsl_frexp_cvt_check.py | 31 ++++++++++++++----- .../startup_gfx2hlsl_frexp_cvt_warp_check.py | 5 +-- tools/startup/gfx2hlsl.py | 22 ++++++++----- 4 files changed, 53 insertions(+), 18 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 9ba4398dae..ee43925aad 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -13534,6 +13534,19 @@ A lane that was inactive at the definition keeps an older VGPR value; the recomp ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_readfirstlane_(uniform|recompute)$' -V ``` +### Startup translator: frexp, float-to-int conversions and ldexp + +`tools/startup/gfx2hlsl.py` lowers five more operations: `v_frexp_mant_f32`, `v_frexp_exp_i32_f32`, `v_cvt_flr_i32_f32`, `v_cvt_rpi_i32_f32` and `v_ldexp_f32`. This is the startup path, separate from the `pixel_aot.py` helpers of the same names. `v_cvt_rpi_i32_f32` adds one to `floor(x)` when the exact fraction `x - floor(x)` is at least 0.5, because binary32 `x + 0.5` would round `0x3effffff` up to 1 and move `8388609.0`. A NaN reads `0x7fffffff` with its sign bit clear and `0x80000000` with it set, and values outside the int32 range saturate, matching `CVT_FLR_RPI_EXCEPTIONAL` in `tests/pixel_aot_check.py`. `v_frexp_exp_i32_f32` gives 0 for zero, denormals, infinity and NaN. Output modifiers and `clamp` on the two conversions and on `v_frexp_exp_i32_f32` are refused. + +`tests/startup_gfx2hlsl_frexp_cvt_check.py` is CPU only: it translates each operation, runs the emitted line on a small evaluator that rounds every binary32 add, subtract and multiply, and compares with an exact reference over 51 words per unary operation (including all six NaN spellings, both infinities and the saturation edges) and 736 `v_ldexp_f32` pairs. `tests/startup_gfx2hlsl_frexp_cvt_warp_check.py` draws the same operations through D3D12 and compares the read-back with that reference on WARP and on hardware. + +```bash +python3 -B tests/startup_gfx2hlsl_frexp_cvt_check.py +ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_frexp_cvt' -V +``` + +Not covered: denormal inputs and results of `v_ldexp_f32` (the denormal mode decides them), signalling-NaN payloads of `v_frexp_mant_f32`, and the console's own results. + ## Desktop audio render sink `startup_audio_output` drives a small WASAPI shared-mode render sink ([`audio_sink.h`](../src/startup_stubs/audio_sink.h)) with generated PCM blocks. It is the first slice of [issue #1145](https://github.com/R0Y00/Xbox2Windows/issues/1145). The sink takes `submit(format, frames, bytes)`, converts the block to the endpoint mix format (32-bit float or 16-bit PCM only) and records the first accepted block, the submitted format, per-block frame counts and peaks, consumed frames (submitted minus `GetCurrentPadding`), the `IAudioClock` position, the drained interval and the recovery. The fixture runs three cases in one process: no submission; eight 40 ms blocks with distinct amplitudes, one of them intentionally silent; and a producer that withholds the next block until the queue is empty, then resumes. diff --git a/tests/startup_gfx2hlsl_frexp_cvt_check.py b/tests/startup_gfx2hlsl_frexp_cvt_check.py index 13a44833c4..1abfddcd93 100644 --- a/tests/startup_gfx2hlsl_frexp_cvt_check.py +++ b/tests/startup_gfx2hlsl_frexp_cvt_check.py @@ -8,7 +8,8 @@ frexp_mant: sign and mantissa in [0.5, 1) of a normal input; zero and denormal give a signed zero; inf and NaN pass through. frexp_exp: the matching exponent; 0 for zero, denormal, inf and NaN. - cvt_flr / cvt_rpi: floor(x) / floor(x + 0.5), saturated to int32, NaN reads 0. + cvt_flr / cvt_rpi: floor(x) / floor(x + 0.5) in exact arithmetic, saturated to int32; a NaN reads 0x7fffffff + (sign clear) or 0x80000000 (sign set), as measured on RDNA 2 (CVT_FLR_RPI_EXCEPTIONAL). ldexp: S0 * 2^S1 with S1 a signed integer. Not covered: denormal inputs and results of v_ldexp_f32 (the denormal mode decides them) and signaling-NaN payloads. """ @@ -50,7 +51,7 @@ def to_int(x): FUNCS = { 'U': bits, 'F': value, 'uint': lambda x: int(x) & MASK, 'int': to_int, 'float': float, 'floor': lambda x: x if math.isinf(x) else float(math.floor(x)), 'max': max, 'exp2': lambda x: f32(2.0 ** x), - 'isnan': lambda x: x != x, 'clamp': lambda x, lo, hi: min(max(x, lo), hi), 'saturate': lambda x: min(max(x, 0.0), 1.0), + 'clamp': lambda x, lo, hi: min(max(x, lo), hi), 'saturate': lambda x: min(max(x, 0.0), 1.0), } @@ -58,6 +59,14 @@ def idiv(a, b): return int(a / b) +def add(a, b): + return f32(a + b) if isinstance(a, float) or isinstance(b, float) else (a + b) & MASK + + +def sub(a, b): + return f32(a - b) if isinstance(a, float) or isinstance(b, float) else a - b + + def mul(a, b): return f32(a * b) if isinstance(a, float) or isinstance(b, float) else (a * b) & MASK @@ -101,6 +110,10 @@ def binary(self, level): node = 'idiv(%s, %s)' % (node, right) elif op == '*': node = 'mul(%s, %s)' % (node, right) + elif op == '+': + node = 'add(%s, %s)' % (node, right) + elif op == '-': + node = 'sub(%s, %s)' % (node, right) else: node = '(%s %s %s)' % (node, op, right) return node @@ -139,7 +152,7 @@ def lowered(base, asm): def run(text, **regs): - env = dict(FUNCS, idiv=idiv, mul=mul, **regs) + env = dict(FUNCS, idiv=idiv, mul=mul, add=add, sub=sub, **regs) return eval(Parser(text).out, {'__builtins__': {}}, env) @@ -159,20 +172,20 @@ def ref_frexp_exp(w): return 0 if e in (0, 255) else math.frexp(value(w))[1] & MASK -def saturate_int(x): +def saturate_int(x, word): if x != x: - return 0 + return 0x7fffffff + (word >> 31) return max(-2 ** 31, min(2 ** 31 - 1, math.floor(x))) & MASK if not math.isinf(x) else ( MASK >> 1 if x > 0 else 0x80000000) def ref_cvt_flr(w): - return saturate_int(value(w)) + return saturate_int(value(w), w) def ref_cvt_rpi(w): x = value(w) - return saturate_int(x if math.isinf(x) or x != x else math.floor(x + 0.5)) + return saturate_int(x if math.isinf(x) or x != x else math.floor(x + 0.5), w) def ref_ldexp(a, n): @@ -190,7 +203,9 @@ def ref_ldexp(a, n): FLOATS = [0.0, -0.0, 1.0, -1.0, 0.5, -0.5, 0.75, 1.5, -2.5, 3.0, 0.1, -0.1, 0.4999, 0.5001, -0.5001, 1e-5, 123456.789, -98765.4, 1.0e20, -1.0e20, 2.0 ** -126, 2.0 ** 127, 1.7014118e38, 8388608.5, 2147483520.0, -2147483648.0, 2.0 ** 31, -2.0 ** 33, 3.4028235e38, -3.4028235e38] -WORDS = [bits(x) for x in FLOATS] + [NAN, INF, INF | 0x80000000, 0x00000001, 0x80400000, 0x007fffff] +WORDS = [bits(x) for x in FLOATS] + [NAN, INF, INF | 0x80000000, 0x00000001, 0x80400000, 0x007fffff, + 0xffc00000, 0x7f800001, 0xff800001, 0x7fffffff, 0xffffffff, + 0x3effffff, 0xbf000001, 0x4b000001, 0xcb000001, 0x4b7fffff, 0x4effffff] SHIFTS = [0, 1, -1, 5, -5, 24, -24, 100, -100, 126, -126, 127, -127, 200, -200, 299, 300, 301, -300, 1000, -1000, 2 ** 31 - 1, -2 ** 31] diff --git a/tests/startup_gfx2hlsl_frexp_cvt_warp_check.py b/tests/startup_gfx2hlsl_frexp_cvt_warp_check.py index 64c9b69b34..33edb3b2b5 100644 --- a/tests/startup_gfx2hlsl_frexp_cvt_warp_check.py +++ b/tests/startup_gfx2hlsl_frexp_cvt_warp_check.py @@ -38,7 +38,7 @@ MUTATION = {'v_frexp_mant_f32': ('0x3f000000u', '0x3f800000u'), 'v_frexp_exp_i32_f32': ('- 126u', '- 127u'), 'v_cvt_flr_i32_f32': ('floor(', 'ceil('), - 'v_cvt_rpi_i32_f32': ('+ 0.5', '+ 0.25'), + 'v_cvt_rpi_i32_f32': ('>= 0.5', '>= 0.75'), 'v_ldexp_f32': ('exp2(float(', '-exp2(float(')} BODY_SOURCE = {op: ''.join('%s v%d, v%d\n' % (op, 12 + i, i) for i in range(4)) for op in UNARY} BODY_SOURCE['v_ldexp_f32'] = ''.join('v_ldexp_f32 v%d, v%d, v%d\n' % (12 + i, i, 4 + i) for i in range(4)) @@ -47,7 +47,8 @@ UNARY_INPUTS = [R.bits(x) for x in (1.0, -1.0, 0.5, 0.75, -2.5, 3.0, 0.1, -0.1, 0.4999, 0.5001, 123456.789, -98765.4, 1.0e20, -1.0e20, 2.0 ** 127, 8388608.5, 2147483520.0, -2147483648.0, 2.0 ** 31, -2.0 ** 33, 3.4028235e38, 0.0, -0.0, 2.0 ** -126)] -UNARY_INPUTS += [R.INF, R.INF | 0x80000000, R.NAN, 0x7f7fffff] +UNARY_INPUTS += [R.INF, R.INF | 0x80000000, R.NAN, 0x7f7fffff, + 0xffc00000, 0x3effffff, 0x4b000001, 0xff800001] LDEXP_INPUTS = [(R.bits(a), n & MASK) for a, n in ( (1.0, 1), (1.5, -1), (-1.5, 5), (0.1, 24), (123456.789, -20), (-3.0, 100), (1.0, 127), (1.0, -126), (1.0, 200), (-1.0, -200), (0.0, 5), (-0.0, -5), (1.0, 2 ** 31 - 1), (1.0, -2 ** 31), (2.0, 300), (1.5, 0))] diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 6691e46f8a..f49111aa35 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -2748,23 +2748,29 @@ def op_v_frexp_exp_i32_f32(self, ops, mods): e = '((%s >> 23) & 255u)' % self.float_bits(ops[1]) self.set_v(reg_range(ops[0])[1], '(%s == 0u || %s == 255u) ? 0u : (%s - 126u)' % (e, e, e)) - def float_to_int(self, base, ops, mods, rounded): - # Saturating conversion of the rounded float; NaN reads 0. v_cvt_flr rounds toward -inf, v_cvt_rpi - # rounds floor(x + 0.5). A value at or above 2^31 reads INT_MAX; one below -2^31 reads INT_MIN. + def float_to_int(self, base, ops, mods, rpi): + # Saturating conversion. v_cvt_flr rounds toward -inf; v_cvt_rpi adds 1 to floor(x) when the exact + # fraction x - floor(x) is at least 0.5 (binary32 x + 0.5 would round 0x3effffff up and 2^23 + 1 off). + # A NaN reads 0x7fffffff with its sign bit clear and 0x80000000 with it set; a value at or above 2^31 + # reads INT_MAX and one below -2^31 reads INT_MIN (native RDNA 2 words, tests/pixel_aot_check.py). if mods: raise Unsupported('%s with modifiers' % base) if len(ops) != 2: raise Unsupported('%s with %d operands, expected 2' % (base, len(ops))) x = self.f(ops[1]) - r = 'floor(%s)' % (rounded % x) - self.set_v(reg_range(ops[0])[1], 'isnan(%s) ? 0u : (%s >= 2147483648.0) ? 0x7fffffffu : uint(int(max(%s, -2147483648.0)))' % ( - x, r, r)) + r = 'floor(%s)' % x + if rpi: + r = '(%s + (((%s) - %s) >= 0.5 ? 1.0 : 0.0))' % (r, x, r) + bits = self.float_bits(ops[1]) + self.set_v(reg_range(ops[0])[1], '((%s & 0x7fffffffu) > 0x7f800000u) ? (0x7fffffffu + (%s >> 31)) : ' + '(%s >= 2147483648.0) ? 0x7fffffffu : uint(int(clamp(%s, -2147483648.0, 2147483520.0)))' % ( + bits, bits, x, r)) def op_v_cvt_flr_i32_f32(self, ops, mods): - self.float_to_int('v_cvt_flr_i32_f32', ops, mods, '%s') + self.float_to_int('v_cvt_flr_i32_f32', ops, mods, False) def op_v_cvt_rpi_i32_f32(self, ops, mods): - self.float_to_int('v_cvt_rpi_i32_f32', ops, mods, '%s + 0.5') + self.float_to_int('v_cvt_rpi_i32_f32', ops, mods, True) def op_v_ldexp_f32(self, ops, mods): # D = S0 * 2^S1 with S1 a signed integer, clamped to +-300 (the result is 0 or inf past that anyway). From 4807377921d62919409d23cb9e47d78ac12d8464 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Wed, 25 Nov 2026 11:41:47 +0100 Subject: [PATCH 5/6] fix: keep the NaN word in the v_ldexp_f32 lowering and the signaling NaN word in the CPU check (Part of #1723) An RTX 3070 Ti read a NaN times the exp2 factors back as 0x7fffffff, not the input word the ISA returns. A NaN source is now passed through unchanged. The CPU check lost the signaling NaN word to the quiet-bit change of struct.unpack on Python 3.11 and 3.12, so values now carry their word. --- tests/startup_gfx2hlsl_frexp_cvt_check.py | 12 +++++++++++- tools/startup/gfx2hlsl.py | 6 +++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/tests/startup_gfx2hlsl_frexp_cvt_check.py b/tests/startup_gfx2hlsl_frexp_cvt_check.py index 1abfddcd93..b7084793c4 100644 --- a/tests/startup_gfx2hlsl_frexp_cvt_check.py +++ b/tests/startup_gfx2hlsl_frexp_cvt_check.py @@ -34,12 +34,22 @@ def f32(x): return math.copysign(math.inf, x) +class F32(float): + """binary32 value that keeps its source word: struct.unpack(' U() would change the word.""" + word = None + + def bits(x): + if isinstance(x, F32) and x.word is not None: + return x.word return struct.unpack(' Date: Thu, 26 Nov 2026 08:50:00 +0100 Subject: [PATCH 6/6] test: state the normal-domain profile of the frexp/cvt/ldexp oracle --- tests/startup_gfx2hlsl_frexp_cvt_check.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/tests/startup_gfx2hlsl_frexp_cvt_check.py b/tests/startup_gfx2hlsl_frexp_cvt_check.py index b7084793c4..45042d70c1 100644 --- a/tests/startup_gfx2hlsl_frexp_cvt_check.py +++ b/tests/startup_gfx2hlsl_frexp_cvt_check.py @@ -12,6 +12,13 @@ (sign clear) or 0x80000000 (sign set), as measured on RDNA 2 (CVT_FLR_RPI_EXCEPTIONAL). ldexp: S0 * 2^S1 with S1 a signed integer. Not covered: denormal inputs and results of v_ldexp_f32 (the denormal mode decides them) and signaling-NaN payloads. + +Profile this oracle states: the NORMAL domain only (normal inputs, normal results, zero, inf, NaN). The binary32 denormal +selection (MODE[5:4]) is not modelled by the startup translator: a write that selects it is accepted and changes no emitted +line, so the emitted code follows the desktop compiler's own denormal behaviour (flushing, as measured on WARP and one +desktop GPU). ref_cvt_flr and ref_ldexp compute denormal words exactly, ref_frexp_mant answers a signed zero; none of +these denormal rows is a guest guarantee, and a desktop result on them says nothing about the console. A guest profile +for denormals needs a source-built native reference that records the selected mode, the input and the output words. """ import math import re