From 3a3cd735479c98afcdae432ebcbded52d4290c34 Mon Sep 17 00:00:00 2001 From: triggered02 <153171514+triggered02@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:36:04 +0530 Subject: [PATCH 1/2] startup/gfx2hlsl: lower v_sad_u8, v_sad_u16, and v_sad_u32 --- CMakeLists.txt | 9 + docs/experiments.md | 14 + tests/startup_gfx2hlsl_sad_check.py | 530 ++++++++++++++++++++++++++++ tools/startup/gfx2hlsl.py | 32 ++ 4 files changed, 585 insertions(+) create mode 100644 tests/startup_gfx2hlsl_sad_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 4f6fa27221..8c3bb98952 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3455,6 +3455,15 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_gfx2hlsl_mul_hi_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endforeach() + # gfx2hlsl v_sad_u8, v_sad_u16 and v_sad_u32: on-demand helpers, CPU grid evaluation, refusal and mutation controls, then desktop draw (FXC 5_1 and DXC 6_0). + add_test(NAME startup_gfx2hlsl_sad_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_sad_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_sad_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_sad_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_sad_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() add_test(NAME startup_xg_bc_tiling COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_xg_bc_tiling_check.py" "$") set_tests_properties(startup_xg_bc_tiling PROPERTIES TIMEOUT 30 ENVIRONMENT "X2W_D3D12_PERMISSIVE=1") diff --git a/docs/experiments.md b/docs/experiments.md index ff03adb934..fdacf289af 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -14888,3 +14888,17 @@ check and requires the old exception to come back: The checks are `tests/startup_gfx2hlsl_handler_arity_check.py`, `…_image_arity_check.py`, `…_operand_count_check.py` and `…_scalar_arity_check.py`. They run on Linux and Windows without D3D12 or game data, because a refusal is observable at the `Stage` entry point. +## Startup translator: v_sad_u8, v_sad_u16 and v_sad_u32 + +[`tools/startup/gfx2hlsl.py`](../tools/startup/gfx2hlsl.py) now lowers the gfx1013 VOP3A unsigned sum-of-absolute-differences instructions `v_sad_u8` (`0x15a`), `v_sad_u16` (`0x15c`) and `v_sad_u32` (`0x15d`) in `VEC_U` to three on-demand preamble helpers emitted in `Pipeline.common()` only when referenced by a stage (`sad_u8`, `sad_u16`, `sad_u32`): + +- `sad_u8(uint a, uint b, uint c)` sums `uint(abs(int((a >> shift) & 0xffu) - int((b >> shift) & 0xffu)))` over shifts `0, 8, 16, 24`, plus `c` with 32-bit unsigned wraparound. +- `sad_u16(uint a, uint b, uint c)` computes `uint(abs(int(a & 0xffffu) - int(b & 0xffffu))) + uint(abs(int(a >> 16) - int(b >> 16))) + c` with 32-bit unsigned wraparound. +- `sad_u32(uint a, uint b, uint c)` computes `(a > b ? a - b : b - a) + c` using unsigned comparison rather than signed `int` subtraction. +- Output modifiers (`clamp`, `omod`), `op_sel`, source `abs`/`neg` bits (checked in both `check_encoding` and `Stage.u`), and wrong operand counts remain refused with `Unsupported`. + +[`tests/startup_gfx2hlsl_sad_check.py`](../tests/startup_gfx2hlsl_sad_check.py) decodes synthetic gfx1013 VOP3A bytes via `G.decode()` only (no game data), verifies on-demand helper emission across `Pipeline` and `ComputePipeline`, evaluates the emitted HLSL across 600 edge/grid triples for `v_sad_u8`, 600 for `v_sad_u16` and 605 for `v_sad_u32` (covering `0xffffffff`, `0x80000000`, `0x7fffffff`, byte/halfword boundary carries and `S2` wraparound), checks all modifier/arity/unlowered refusals, and runs mutated-HLSL negative controls (dropped high byte, dropped high halfword, signed `int` subtraction). In `draw` mode on Microsoft WARP (`10.0.26100.9818`, DXC `ps_6_0` and FXC `10.0.26100` `ps_5_1`), all 18 good draws (9 per compiler) matched the Python reference and all 6 mutated draws (3 per compiler) produced the exact mutated readback words. The `_hardware` test was not run in this session. + +```powershell +ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_sad_(controls|warp|hardware)$' -V +``` diff --git a/tests/startup_gfx2hlsl_sad_check.py b/tests/startup_gfx2hlsl_sad_check.py new file mode 100644 index 0000000000..5862db56dd --- /dev/null +++ b/tests/startup_gfx2hlsl_sad_check.py @@ -0,0 +1,530 @@ +"""Unsigned sum-of-absolute-differences (v_sad_u8, v_sad_u16, v_sad_u32) in tools/startup/gfx2hlsl.py. + + (no arguments) translation, on-demand helper, value-evaluation, refusal and mutation + controls, pure Python + draw [fxc] + compile the translated pair with FXC ps_5_1 when given and with DXC ps_6_0, + draw one pixel per four input triples and compare the four result words + +The pixel fixture decodes synthetic gfx1013 VOP3A bytes via G.decode() ONLY (no game data). It reads three flat +parameters (v0..v3, v4..v7, v8..v11), computes v_sad_u* across all four lanes into v12..v15, and exports v12..v15 +to mrt0. The vertex stage supplies the input words through flat parameters so the pixel stage cannot fold them. +""" +import re +import struct +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_flat_param_check import compile_hlsl, draw, root_blob # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import ( # noqa: E402 + MASK, + POST_WORDS, + PRE_WORDS, + Probe, + check, + refused, + signed, + vs_words, + words_text, +) + +OPCODES = { + 'v_sad_u8': 0x15a, + 'v_sad_u16': 0x15c, + 'v_sad_u32': 0x15d, +} + + +def vop3a(op, vdst, src0, src1, src2, *, abs_bits=0, op_sel=0, clamp=0, omod=0, neg=0, lit=None): + """Encode one synthetic gfx1013 VOP3A 64-bit (or 96-bit with literal) instruction word.""" + w0 = 0xd4000000 | (op << 16) | (clamp << 15) | (op_sel << 11) | (abs_bits << 8) | vdst + w1 = (neg << 29) | (omod << 27) | (src2 << 18) | (src1 << 9) | src0 + out = struct.pack('<2I', w0, w1) + if lit is not None: + out += struct.pack('> shift) & 0xff) - ((b >> shift) & 0xff)) for shift in (0, 8, 16, 24)) + c) & MASK + + +def ref_sad_u16(a, b, c): + a, b, c = a & MASK, b & MASK, c & MASK + return (abs((a & 0xffff) - (b & 0xffff)) + abs(((a >> 16) & 0xffff) - ((b >> 16) & 0xffff)) + c) & MASK + + +def ref_sad_u32(a, b, c): + a, b, c = a & MASK, b & MASK, c & MASK + return (abs(a - b) + c) & MASK + + +REF = { + 'v_sad_u8': ref_sad_u8, + 'v_sad_u16': ref_sad_u16, + 'v_sad_u32': ref_sad_u32, +} + + +def mut_sad_u8(a, b, c): + """Mutated reference: drops the top byte (shift 24).""" + a, b, c = a & MASK, b & MASK, c & MASK + return (sum(abs(((a >> shift) & 0xff) - ((b >> shift) & 0xff)) for shift in (0, 8, 16)) + c) & MASK + + +def mut_sad_u16(a, b, c): + """Mutated reference: drops the top halfword (bits 31:16).""" + a, b, c = a & MASK, b & MASK, c & MASK + return (abs((a & 0xffff) - (b & 0xffff)) + c) & MASK + + +def mut_sad_u32(a, b, c): + """Mutated reference: uses signed 32-bit subtraction inside abs(int(a) - int(b)).""" + a, b, c = a & MASK, b & MASK, c & MASK + return (abs(signed(a) - signed(b)) + c) & MASK + + +MUTATION_REF = { + 'v_sad_u8': mut_sad_u8, + 'v_sad_u16': mut_sad_u16, + 'v_sad_u32': mut_sad_u32, +} + +# Grids with > 500 edge triples per instruction. +U8_WORDS = ( + 0x00000000, 0x01020304, 0x04030201, 0x7f80ff00, 0x807f00ff, + 0x00010000, 0x0000ffff, 0x7fffffff, 0x80000000, 0xffffffff, +) +U8_ADDENDS = (0, 1, 0x7fffffff, 0x80000000, 0xfffffc04, 0xffffffff) +U16_WORDS = ( + 0x00000000, 0x0000ffff, 0xffff0000, 0x0001ffff, 0xffff0001, + 0x7fff8000, 0x80007fff, 0x7fffffff, 0x80000000, 0xffffffff, +) +U16_ADDENDS = (0, 1, 0x7fffffff, 0x80000000, 0xfffe0002, 0xffffffff) +U32_WORDS = ( + 0x00000000, 0x00000001, 0x00000002, 0x12345678, 0x7ffffffe, 0x7fffffff, + 0x80000000, 0x80000001, 0xdeadbeef, 0xfffffffe, 0xffffffff, +) +U32_ADDENDS = (0, 1, 0x7fffffff, 0x80000000, 0xffffffff) + +GRID = { + 'v_sad_u8': [(a, b, c) for a in U8_WORDS for b in U8_WORDS for c in U8_ADDENDS], + 'v_sad_u16': [(a, b, c) for a in U16_WORDS for b in U16_WORDS for c in U16_ADDENDS], + 'v_sad_u32': [(a, b, c) for a in U32_WORDS for b in U32_WORDS for c in U32_ADDENDS], +} + +# 12 input triples (3 draws of 4 lanes) per instruction. +# The first 4 triples in each list separate the mutation from the reference on every single lane. +DRAW = { + 'v_sad_u8': [ + (0xff000000, 0x00000000, 0), + (0x00123456, 0xff123456, 10), + (0x807f0102, 0x7f800304, 0xfffffc04), + (0x10203040, 0xf0203040, 0xffffffff), + (0x00010000, 0x0000ffff, 0), + (0x01020304, 0x04030201, 1), + (0xffffffff, 0x00000000, 0xfffffc04), + (0x80000000, 0x7fffffff, 0x80000000), + (0x7fffffff, 0x80000000, 0x7fffffff), + (0xdeadbeef, 0xcafebabe, 0x12345678), + (0x00ff00ff, 0xff00ff00, 0), + (0xffffffff, 0xffffffff, 0xffffffff), + ], + 'v_sad_u16': [ + (0xffff0000, 0x00000000, 0), + (0x00001234, 0xffff1234, 10), + (0x80007fff, 0x7fff8000, 0xfffe0002), + (0x1000ffff, 0x2000ffff, 0xffffffff), + (0x00010000, 0x0000ffff, 0), + (0x0001ffff, 0xffff0001, 1), + (0xffffffff, 0x00000000, 0xfffe0002), + (0x80000000, 0x7fffffff, 0x80000000), + (0x7fffffff, 0x80000000, 0x7fffffff), + (0xdeadbeef, 0xcafebabe, 0x12345678), + (0x00000000, 0x00000000, 0), + (0xffffffff, 0xffffffff, 0xffffffff), + ], + 'v_sad_u32': [ + (0xffffffff, 0x00000000, 0), + (0x00000000, 0xffffffff, 0), + (0x80000001, 0x00000000, 5), + (0xfffffffe, 0x00000001, 2), + (0x7fffffff, 0x80000000, 0), + (0x80000000, 0x7fffffff, 0xffffffff), + (0x80000000, 0x00000000, 0x80000000), + (0x00000000, 0x80000000, 0x80000000), + (0xffffffff, 0x00000000, 1), + (0xdeadbeef, 0xcafebabe, 0x12345678), + (0x00000000, 0x00000000, 0xffffffff), + (0xffffffff, 0xffffffff, 0xffffffff), + ], +} + + +# ---- 32-bit HLSL expression evaluator (supports uint/int, abs(), and sad_u* helpers) ------------------------- +TOKEN = re.compile(r'\s*(0x[0-9a-fA-F]+u?|\d+u?|[A-Za-z_]\w*|<<|>>|<=|>=|==|!=|\|\||[-+*&|^~!<>?:(),])') +LEVELS = [['||'], ['|'], ['^'], ['&'], ['==', '!='], ['<', '>', '<=', '>='], ['<<', '>>'], ['+', '-'], ['*']] + + +class HlslExpr: + def __init__(self, text, helpers=None): + self.tokens = TOKEN.findall(text) + assert ''.join(self.tokens) == re.sub(r'\s+', '', text), text + self.pos = 0 + self.helpers = helpers or {} + self.tree = self.ternary() + assert self.pos == len(self.tokens), text + + def peek(self): + return self.tokens[self.pos] if self.pos < len(self.tokens) else None + + def take(self): + self.pos += 1 + return self.tokens[self.pos - 1] + + def ternary(self): + cond = self.binary(0) + if self.peek() != '?': + return cond + self.take() + yes = self.ternary() + assert self.take() == ':' + return ('?', cond, yes, self.ternary()) + + def binary(self, level): + if level == len(LEVELS): + return self.unary() + node = self.binary(level + 1) + while self.peek() in LEVELS[level]: + op = self.take() + node = (op, node, self.binary(level + 1)) + return node + + def unary(self): + token = self.take() + if token in ('~', '-', '!'): + return ('u' + token, self.unary()) + if token == '(': + node = self.ternary() + assert self.take() == ')' + return node + if token[0].isdigit(): + return ('num', int(token.rstrip('u'), 0), not token.endswith('u')) + if self.peek() != '(': + return ('var', token) + self.take() + args = [self.ternary()] + while self.peek() == ',': + self.take() + args.append(self.ternary()) + assert self.take() == ')' + return ('call', token, args) + + def run(self, env, node=None): + node = node or self.tree + kind = node[0] + if kind == 'num': + return node[1] & MASK, node[2] + if kind == 'var': + return env[node[1]] & MASK, False + if kind == '?': + return self.run(env, node[2] if self.run(env, node[1])[0] else node[3]) + if kind == 'call': + return self.call(node[1], [self.run(env, a) for a in node[2]]) + if kind[0] == 'u' and len(node) == 2: + v, s = self.run(env, node[1]) + return {'u~': ~v, 'u-': -v, 'u!': int(v == 0)}[kind] & MASK, s + (a, sa), (b, sb) = self.run(env, node[1]), self.run(env, node[2]) + both = sa and sb + if kind in ('<<', '>>'): + count = b & 31 + return ((a << count) & MASK if kind == '<<' else (signed(a) >> count if sa else a >> count) & MASK), sa + if kind in ('==', '!=', '<', '>', '<=', '>='): + x, y = (signed(a), signed(b)) if both else (a, b) + return int({'==': x == y, '!=': x != y, '<': x < y, '>': x > y, '<=': x <= y, '>=': x >= y}[kind]), True + if kind == '||': + return int(bool(a or b)), True + return {'|': a | b, '^': a ^ b, '&': a & b, '+': a + b, '-': a - b, '*': a * b}[kind] & MASK, both + + def call(self, name, args): + if name in self.helpers: + assert len(args) == 3 and all(not s for _, s in args), (name, args) + return self.helpers[name](*(v for v, _ in args)), False + (v, s), = args + if name in ('asint', 'int'): + return v, True + if name in ('asuint', 'uint'): + return v, False + if name == 'abs': + if s: + val = abs(signed(v)) + assert val <= 0x7fffffff, 'signed abs overflow on %#x' % v + return val & MASK, True + return v, False + raise AssertionError('unexpected call %s' % name) + + +def mutate_hlsl(op, text): + if op == 'v_sad_u8': + pattern = r'\+\s*uint\(abs\(int\(\(a >> 24\) & 0xffu\) - int\(\(b >> 24\) & 0xffu\)\)\)' + mutated = re.sub(pattern, '+ 0u', text) + elif op == 'v_sad_u16': + pattern = r'\+\s*uint\(abs\(int\(a >> 16\) - int\(b >> 16\)\)\)' + mutated = re.sub(pattern, '+ 0u', text) + elif op == 'v_sad_u32': + pattern = r'\(a > b \? a - b : b - a\)' + mutated = re.sub(pattern, 'uint(abs(int(a) - int(b)))', text) + else: + raise AssertionError(op) + assert mutated != text, op + return mutated + + +def translate(op, mutate=False): + pipe = G.Pipeline(vs_words([(0, 0, 0)] * 4), ps_words(op), root_blob()) + text = pipe.hlsl_ps() + if mutate: + text = mutate_hlsl(op, text) + return pipe, text + + +def extract_sad_helpers(hlsl_text): + """Parse emitted sad_u8 / sad_u16 / sad_u32 helper definitions into 32-bit evaluators.""" + helpers = {} + for helper_name in ('sad_u8', 'sad_u16', 'sad_u32'): + m = re.search(r'^uint %s\(uint a, uint b, uint c\) \{ return (.*); \}$' % helper_name, hlsl_text, re.M) + if m: + expr = HlslExpr(m.group(1)) + helpers[helper_name] = lambda a, b, c, e=expr: e.run({'a': a, 'b': b, 'c': c})[0] + return helpers + + +def lane_evaluators(hlsl_text): + helpers = extract_sad_helpers(hlsl_text) + found = re.findall(r'^\s*v(1[2-5]) = (.*);$', hlsl_text, re.M) + assert [r for r, _ in found] == ['12', '13', '14', '15'], found + return helpers, [HlslExpr(rhs, helpers) for _, rhs in found] + + +def eval_lanes(exprs, chunk): + return [expr.run({'v%d' % lane: a, 'v%d' % (4 + lane): b, 'v%d' % (8 + lane): c})[0] + for lane, (expr, (a, b, c)) in enumerate(zip(exprs, chunk))] + + +def decode_single_sad(word_bytes): + """Decode synthetic VOP3A bytes via G.decode() and lower through a Stage.""" + ins = G.decode(word_bytes) + assert len(ins) == 1, ins + _, _, name, asm = ins[0] + stage = Probe() + stage.one(name, asm) + return stage.lines + + +def controls(): + # 1. On-demand preamble helpers: none emitted without SAD, only the used helper emitted when used. + base_ps = PRE_WORDS + POST_WORDS + base_pipe = G.Pipeline(vs_words([(0, 0, 0)] * 4), base_ps, root_blob()) + base_hlsl_ps = base_pipe.hlsl_ps() + base_hlsl_vs = base_pipe.hlsl_vs() + check('on-demand: baseline pipeline without v_sad_* emits no sad_u* helpers', + all(h not in base_hlsl_ps and h not in base_hlsl_vs for h in ('sad_u8(', 'sad_u16(', 'sad_u32('))) + + for op in OPCODES: + pipe, text = translate(op) + expected_helper = op[2:] # sad_u8 / sad_u16 / sad_u32 + other_helpers = [other[2:] for other in OPCODES if other != op] + helpers, exprs = lane_evaluators(text) + check('%s: on-demand emits only %s helper in PS/VS' % (op, expected_helper), + list(helpers) == [expected_helper] + and all(f'{h}(' not in text and f'{h}(' not in pipe.hlsl_vs() for h in other_helpers)) + + # Verify lane calls in emitted HLSL. + found = re.findall(r'^\s*v(1[2-5]) = %s\(v(\d+), v(\d+), v(\d+)\);$' % expected_helper, text, re.M) + check('%s: four lane calls emitted' % op, + found == [('12', '0', '4', '8'), ('13', '1', '5', '9'), + ('14', '2', '6', '10'), ('15', '3', '7', '11')]) + + # Value-level evaluation of emitted HLSL over 500+ edge/grid triples. + grid = GRID[op] + assert len(grid) >= 500, (op, len(grid)) + ref_fn = REF[op] + mismatch = next(( + (i % 4, triple, + exprs[i % 4].run({'v%d' % (i % 4): triple[0], 'v%d' % (4 + i % 4): triple[1], + 'v%d' % (8 + i % 4): triple[2]})[0], + ref_fn(*triple)) + for i, triple in enumerate(grid) + if exprs[i % 4].run({'v%d' % (i % 4): triple[0], 'v%d' % (4 + i % 4): triple[1], + 'v%d' % (8 + i % 4): triple[2]})[0] != ref_fn(*triple) + ), None) + check('%s: emitted HLSL matches reference on %d edge/grid triples' % (op, len(grid)), + mismatch is None) + + # Mutated HLSL evaluation: must match MUTATION_REF on all non-overflowing grid triples and differ on DRAW[op][:4]. + mutated_text = translate(op, mutate=True)[1] + _, mut_exprs = lane_evaluators(mutated_text) + mut_fn = MUTATION_REF[op] + eval_grid = ( + [t for t in grid if -0x7fffffff <= signed(t[0]) - signed(t[1]) <= 0x7fffffff] + if op == 'v_sad_u32' else grid + ) + mut_mismatch = next(( + (i % 4, triple) + for i, triple in enumerate(eval_grid) + if mut_exprs[i % 4].run({'v%d' % (i % 4): triple[0], 'v%d' % (4 + i % 4): triple[1], + 'v%d' % (8 + i % 4): triple[2]})[0] != mut_fn(*triple) + ), None) + first = DRAW[op][:4] + ref_first = [ref_fn(*t) for t in first] + mut_first = [mut_fn(*t) for t in first] + check('%s: mutated HLSL matches MUTATION_REF on %d triples and differs on draw set 0 (%s != %s)' + % (op, len(eval_grid), words_text(mut_first), words_text(ref_first)), + mut_mismatch is None and eval_lanes(mut_exprs, first) == mut_first + and all(m != r for m, r in zip(mut_first, ref_first))) + + # 2. ComputePipeline on-demand helper check + SGPR / inline constant / literal / exec-masked encodings. + cs_words = vop3a(OPCODES['v_sad_u8'], 1, 4, 129, 255, lit=0x12345678) + struct.pack(' dict(index, kind): images a pixel stage stores to (u registers); None until the first store @@ -5544,6 +5558,7 @@ def __init__(self, vs_code, ps_code, root_blob, sampler_heap=None, rtv_formats=( self.uses_sampler_heap = False self.uses_pack16_rne = False self.uses_gather_2d_lod = False + self.uses_sad = set() self.resources = {} # key -> dict(index, kind) self.samplers = {} # key -> index self.uds = [] # entry-constant sources @@ -5764,6 +5779,22 @@ def common(self): ' return result;', '}', )) + if 'v_sad_u8' in self.uses_sad: + out.append( + 'uint sad_u8(uint a, uint b, uint c) {' + ' return uint(abs(int(a & 0xffu) - int(b & 0xffu)))' + ' + uint(abs(int((a >> 8) & 0xffu) - int((b >> 8) & 0xffu)))' + ' + uint(abs(int((a >> 16) & 0xffu) - int((b >> 16) & 0xffu)))' + ' + uint(abs(int((a >> 24) & 0xffu) - int((b >> 24) & 0xffu))) + c; }') + if 'v_sad_u16' in self.uses_sad: + out.append( + 'uint sad_u16(uint a, uint b, uint c) {' + ' return uint(abs(int(a & 0xffffu) - int(b & 0xffffu)))' + ' + uint(abs(int(a >> 16) - int(b >> 16))) + c; }') + if 'v_sad_u32' in self.uses_sad: + out.append( + 'uint sad_u32(uint a, uint b, uint c) {' + ' return (a > b ? a - b : b - a) + c; }') return out def interface(self, for_pixel): @@ -5892,6 +5923,7 @@ def __init__(self, cs_code, root_blob, rsrc2, group, sampler_heap=None, refusals self.sampler_heap = os.environ.get('X2W_SAMPLER_HEAP') == '1' if sampler_heap is None else sampler_heap self.uses_sampler_heap = False self.uses_gather_2d_lod = False + self.uses_sad = set() self.resources, self.uavs, self.samplers, self.uds = {}, {}, {}, [] self.notes, self.modified, self.other_modified = set(), set(), set() # other: anything but a stride clear self.lod_unvalidated = set() From a991d931b43144cff243c98256c6324011930f53 Mon Sep 17 00:00:00 2001 From: triggered02 <153171514+triggered02@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:24:12 +0530 Subject: [PATCH 2/2] tests: pin the v_sad_u* ABS and NEG encoding refusals per source The v_sad_u8/u16/u32 check listed the ABS (VOP3A w0[10:8]) and NEG (w1[31:29]) rows but aggregated them into one boolean, so a mask narrowed to a single bit (w0[8] or w1[29]) still made G.Pipeline() raise: the printed |v1| or -1 was caught later by Stage.one(), not by the encoding guard. Mutation of either mask survived. Read the refusal back from G.decode()'s refusals list, one row per source and modifier, for VGPR and inline-integer sources alike, and assert the exact 'v_sad_* with neg/abs' reason, so narrowing either mask fails. Register tests/startup_gfx2hlsl_sad_check.py in the windows.yml pure-Python job and the AGENTS.md pure-Python list. Refs #2450 AI-assisted. --- .github/workflows/windows.yml | 1 + AGENTS.md | 1 + docs/experiments.md | 4 ++-- tests/startup_gfx2hlsl_sad_check.py | 28 +++++++++++++++++++++------- 4 files changed, 25 insertions(+), 9 deletions(-) diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 5fb709690b..ffce297832 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -275,6 +275,7 @@ jobs: tests/startup_gfx2hlsl_root_check.py \ tests/startup_gfx2hlsl_sopk_signext_check.py \ tests/startup_gfx2hlsl_mul_hi_check.py \ + tests/startup_gfx2hlsl_sad_check.py \ tests/startup_gfx2hlsl_scalar_brev_fold_check.py \ tests/startup_inline_sampler_check.py \ tests/startup_buffer_address_check.py \ diff --git a/AGENTS.md b/AGENTS.md index 2af9edb75c..c9f5762366 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -240,6 +240,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_handler_arity_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_getpc_refusal_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_image_arity_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_sad_check.py ``` `tests/pixel_aot_check.py binary` additionally needs LLVM with gfx1013 support diff --git a/docs/experiments.md b/docs/experiments.md index fdacf289af..9182131993 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -14895,9 +14895,9 @@ data, because a refusal is observable at the `Stage` entry point. - `sad_u8(uint a, uint b, uint c)` sums `uint(abs(int((a >> shift) & 0xffu) - int((b >> shift) & 0xffu)))` over shifts `0, 8, 16, 24`, plus `c` with 32-bit unsigned wraparound. - `sad_u16(uint a, uint b, uint c)` computes `uint(abs(int(a & 0xffffu) - int(b & 0xffffu))) + uint(abs(int(a >> 16) - int(b >> 16))) + c` with 32-bit unsigned wraparound. - `sad_u32(uint a, uint b, uint c)` computes `(a > b ? a - b : b - a) + c` using unsigned comparison rather than signed `int` subtraction. -- Output modifiers (`clamp`, `omod`), `op_sel`, source `abs`/`neg` bits (checked in both `check_encoding` and `Stage.u`), and wrong operand counts remain refused with `Unsupported`. +- Output modifiers (`clamp`, `omod`), `op_sel`, the per-source `abs` bits (VOP3A `w0[10:8]`) and `neg` bits (`w1[31:29]`), and wrong operand counts remain refused: `check_encoding` refuses the `abs`/`neg` bits in the raw word so `neg` on an inline integer cannot print as `-N` and be read as a negative constant, and `Stage.u` refuses the printed `|vN|` and `-vN` forms, the modifier tokens and a wrong operand count. -[`tests/startup_gfx2hlsl_sad_check.py`](../tests/startup_gfx2hlsl_sad_check.py) decodes synthetic gfx1013 VOP3A bytes via `G.decode()` only (no game data), verifies on-demand helper emission across `Pipeline` and `ComputePipeline`, evaluates the emitted HLSL across 600 edge/grid triples for `v_sad_u8`, 600 for `v_sad_u16` and 605 for `v_sad_u32` (covering `0xffffffff`, `0x80000000`, `0x7fffffff`, byte/halfword boundary carries and `S2` wraparound), checks all modifier/arity/unlowered refusals, and runs mutated-HLSL negative controls (dropped high byte, dropped high halfword, signed `int` subtraction). In `draw` mode on Microsoft WARP (`10.0.26100.9818`, DXC `ps_6_0` and FXC `10.0.26100` `ps_5_1`), all 18 good draws (9 per compiler) matched the Python reference and all 6 mutated draws (3 per compiler) produced the exact mutated readback words. The `_hardware` test was not run in this session. +[`tests/startup_gfx2hlsl_sad_check.py`](../tests/startup_gfx2hlsl_sad_check.py) decodes synthetic gfx1013 VOP3A bytes via `G.decode()` only (no game data), verifies on-demand helper emission across `Pipeline` and `ComputePipeline`, evaluates the emitted HLSL across 600 edge/grid triples for `v_sad_u8`, 600 for `v_sad_u16` and 605 for `v_sad_u32` (covering `0xffffffff`, `0x80000000`, `0x7fffffff`, byte/halfword boundary carries and `S2` wraparound), checks all modifier/arity/unlowered refusals, and runs mutated-HLSL negative controls (dropped high byte, dropped high halfword, signed `int` subtraction). The encoding guard is pinned per source slot: one row each for `abs` on sources 0, 1 and 2, one for `neg` on each of them, and the same six again with the modifier on an inline `1` (36 rows), and each row reads the refusal back from `G.decode()`'s refusals list and asserts the exact `v_sad_* with neg/abs` reason. That matters because a narrowed mask still ends up refused, just later and by a different guard: with `w0 & 0x700` narrowed to `w0 & 0x100` the `abs` word decodes to `|v1|` and `Stage.u` refuses it, so the pipeline-level control alone passes; the reason check fails, as does the `w1 & 0xe0000000` → `w1 & 0x20000000` narrowing (which silently accepts `neg` on an inline `1` as `-1`). In `draw` mode on Microsoft WARP (`10.0.26100.9818`, DXC `ps_6_0` and FXC `10.0.26100` `ps_5_1`), all 18 good draws (9 per compiler) matched the Python reference and all 6 mutated draws (3 per compiler) produced the exact mutated readback words; the same 18 good and 6 mutated draws also pass on the NVIDIA GeForce GTX 1660 SUPER (driver 32.0.16.1074, Windows build 26200), where the debug layer is not installed and so the `_debug1` variants skip with exit 77. ```powershell ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_sad_(controls|warp|hardware)$' -V diff --git a/tests/startup_gfx2hlsl_sad_check.py b/tests/startup_gfx2hlsl_sad_check.py index 5862db56dd..f89588c73c 100644 --- a/tests/startup_gfx2hlsl_sad_check.py +++ b/tests/startup_gfx2hlsl_sad_check.py @@ -423,17 +423,27 @@ def controls(): # 3. Refusal controls (binary VOP3A decoded via G.decode() + Stage.one assembly/arity/unlowered). for op, code in OPCODES.items(): - # clamp, omod, op_sel, abs, neg (both on VGPR and on inline integer 1) in synthetic VOP3A bytes. - bad_encodings = [ + # clamp, omod and op_sel are refused through the printed modifier text; ABS (VOP3A w0[10:8]) and NEG + # (w1[31:29]) are refused by check_encoding() itself, one bit per source. Every source is listed for + # both modifiers and for both VGPR and inline-integer sources, and the refusal is read back from + # decode() instead of only from G.Pipeline(): with a narrowed mask the instruction is still refused + # later, by Stage.one() on the printed |v1| or -1 text, so a Pipeline() raise alone cannot show + # which guard fired. + modifiers = [ ('clamp', vop3a(code, 12, 256, 260, 264, clamp=1)), ('omod=mul:2', vop3a(code, 12, 256, 260, 264, omod=1)), ('omod=mul:4', vop3a(code, 12, 256, 260, 264, omod=2)), ('omod=div:2', vop3a(code, 12, 256, 260, 264, omod=3)), ('op_sel=[1,0,0]', vop3a(code, 12, 256, 260, 264, op_sel=1)), ('op_sel=[0,0,0,1]', vop3a(code, 12, 256, 260, 264, op_sel=8)), - ('abs src0', vop3a(code, 12, 256, 260, 264, abs_bits=1)), - ('abs src1', vop3a(code, 12, 256, 260, 264, abs_bits=2)), - ('abs src2', vop3a(code, 12, 256, 260, 264, abs_bits=4)), + ] + abs_neg = [ + ('abs src0 VGPR', vop3a(code, 12, 256, 260, 264, abs_bits=1)), + ('abs src1 VGPR', vop3a(code, 12, 256, 260, 264, abs_bits=2)), + ('abs src2 VGPR', vop3a(code, 12, 256, 260, 264, abs_bits=4)), + ('abs src0 inline 1', vop3a(code, 12, 129, 260, 264, abs_bits=1)), + ('abs src1 inline 1', vop3a(code, 12, 256, 129, 264, abs_bits=2)), + ('abs src2 inline 1', vop3a(code, 12, 256, 260, 129, abs_bits=4)), ('neg src0 VGPR', vop3a(code, 12, 256, 260, 264, neg=1)), ('neg src1 VGPR', vop3a(code, 12, 256, 260, 264, neg=2)), ('neg src2 VGPR', vop3a(code, 12, 256, 260, 264, neg=4)), @@ -441,14 +451,18 @@ def controls(): ('neg src1 inline 1', vop3a(code, 12, 256, 129, 264, neg=2)), ('neg src2 inline 1', vop3a(code, 12, 256, 260, 129, neg=4)), ] - for label, bad_word in bad_encodings: + for label, bad_word in modifiers + abs_neg: try: G.Pipeline(vs_words([(0, 0, 0)] * 4), PRE_WORDS + bad_word + POST_WORDS, root_blob()) except G.Unsupported: pass else: raise AssertionError('%s: accepted binary VOP3A with %s' % (op, label)) - check('%s: binary VOP3A refuses clamp, omod, op_sel, abs, and neg (VGPR & inline)' % op, True) + for label, bad_word in abs_neg: + reasons = [] + G.decode(bad_word, reasons) + check('%s: encoding guard refuses %s' % (op, label), + [reason for reason, where in reasons] == ['%s with neg/abs' % op]) # Direct Stage.one refusals: modifiers, abs/neg, arity. check('%s: Stage refuses modifiers, abs/neg, and wrong operand counts' % op, all(refused(asm) for asm in (