diff options
| author | Vonsek <45567075+Vonsek@users.noreply.github.com> | 2026-11-22 00:21:00 +0100 |
|---|---|---|
| committer | Vonsek <45567075+Vonsek@users.noreply.github.com> | 2026-11-22 00:21:00 +0100 |
| commit | fc7a3d9ca74d2fa0e79a2af74e4ae52ff2931d9a (patch) | |
| tree | e4d3d324b61cdc64de1111d0b8406b9d4493b748 /tools | |
| parent | 8bd0087d2d0e45fc18fa78fb40b70ecfc6648854 (diff) | |
FUZZ-4: scalar ALU differential fuzzer; s_ff0_i32_b32 on a constant
tools/salu_diff.py runs seeded SOP1/SOP2/SOPC/SOPK programs through its
own reference and through the translator plus spirv_mini_interp, and
compares three SGPRs and SCC. It found that s_ff0_i32_b32 read a 32-bit
constant source as a lane mask; constants are now values, as for
s_bcnt*_b32. GPU-checked with ps_salu_ff.asm.
AI-assisted (Claude Code).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'tools')
| -rw-r--r-- | tools/rdna2spirv.py | 3 | ||||
| -rw-r--r-- | tools/salu_diff.py | 509 |
2 files changed, 512 insertions, 0 deletions
diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index f4df058a5..e50338147 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py | |||
| @@ -2201,6 +2201,9 @@ class Gen: | |||
| 2201 | half = self.mask_half(a[1]) | 2201 | half = self.mask_half(a[1]) |
| 2202 | if half is not None: | 2202 | if half is not None: |
| 2203 | lo, hi = (hi if half == "hi" else lo), self.cu(0) | 2203 | lo, hi = (hi if half == "hi" else lo), self.cu(0) |
| 2204 | elif a[1]["k"] == "imm" and op.endswith("b32"): | ||
| 2205 | # A 32-bit constant is a value, as for s_bcnt*_b32: mask_src would turn it into this lane's bit. | ||
| 2206 | lo, hi = self.src_u(a[1]), self.cu(0) | ||
| 2204 | elif a[1]["k"] != "sgpr" or a[1].get("n") != 2: | 2207 | elif a[1]["k"] != "sgpr" or a[1].get("n") != 2: |
| 2205 | lo, hi = self.mask_src(a[1]), self.cu(0) | 2208 | lo, hi = self.mask_src(a[1]), self.cu(0) |
| 2206 | else: | 2209 | else: |
diff --git a/tools/salu_diff.py b/tools/salu_diff.py new file mode 100644 index 000000000..3195be829 --- /dev/null +++ b/tools/salu_diff.py | |||
| @@ -0,0 +1,509 @@ | |||
| 1 | r"""Differential fuzzing of the scalar ALU and SCC (FUZZ-4 in #156). Standard library only. | ||
| 2 | |||
| 3 | Generates seeded straight-line programs of SOP1/SOP2/SOPC/SOPK instructions, runs them through | ||
| 4 | |||
| 5 | * the reference below, written from the RDNA2 ISA guide's pseudocode for each opcode, and | ||
| 6 | * tools/rdna2spirv.py, executing the SPIR-V with tests/semantic/spirv_mini_interp.py, | ||
| 7 | |||
| 8 | and compares four exported words bit for bit: three SGPRs and SCC (through s_cselect_b32). | ||
| 9 | The reference is separate from tools/cpu_ref.py on purpose: it models only the scalar unit, keeps | ||
| 10 | SCC explicit for every opcode, and does not share code with the translator. | ||
| 11 | |||
| 12 | Usage: | ||
| 13 | python -I tools/salu_diff.py [--programs N] [--seed S] [--max-ops N] [--ops s_min_i32,s_cselect_b32] | ||
| 14 | python -I tools/salu_diff.py --list-ops | ||
| 15 | python -I tools/salu_diff.py --self-test | ||
| 16 | |||
| 17 | Exit 0 when every program matches, 1 on a mismatch (the shortest failing program is printed after | ||
| 18 | removing instructions that do not matter), 2 on a harness error. Skips are counted with their reasons. | ||
| 19 | |||
| 20 | By default the opcodes in LANE_MASK_OPS are left out: the translator models those 64-bit values (and | ||
| 21 | s_wqm_b32) as per-lane wave masks, so a 64-bit integer reference disagrees with them by design (--ops | ||
| 22 | names them explicitly). Known divergences: s_min/max_i32 SCC on a tie until SHADER-40 (#332) lands, and | ||
| 23 | s_bfe_i32 with offset + width > 32, where the reference follows the ISA pseudocode literally and the | ||
| 24 | translator sign-extends from bit 31; which one hardware does is an open question in #156. | ||
| 25 | """ | ||
| 26 | import argparse | ||
| 27 | import gc | ||
| 28 | import os | ||
| 29 | import random | ||
| 30 | import struct | ||
| 31 | import sys | ||
| 32 | import tempfile | ||
| 33 | import warnings | ||
| 34 | |||
| 35 | HERE = os.path.dirname(os.path.abspath(__file__)) | ||
| 36 | sys.dont_write_bytecode = True | ||
| 37 | if HERE not in sys.path: | ||
| 38 | sys.path.insert(0, HERE) | ||
| 39 | SEM_DIR = os.path.join(os.path.dirname(HERE), "tests", "semantic") | ||
| 40 | if SEM_DIR not in sys.path: | ||
| 41 | sys.path.insert(0, SEM_DIR) | ||
| 42 | |||
| 43 | M32 = 0xFFFFFFFF | ||
| 44 | M64 = (1 << 64) - 1 | ||
| 45 | STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4) | ||
| 46 | |||
| 47 | # Data SGPRs. 64-bit operands use the even-aligned pairs inside this range. | ||
| 48 | REGS = tuple(range(4, 20)) | ||
| 49 | PAIRS = tuple(range(4, 20, 2)) | ||
| 50 | OUT_SCC = 30 # s_cselect_b32 s30, 1, 0 observes SCC at the end | ||
| 51 | INLINE64 = False # inline constants in 64-bit positions (--inline64); the translator reads those as lane masks | ||
| 52 | |||
| 53 | LANE_MASK_OPS = ("s_and_b64", "s_or_b64", "s_xor_b64", "s_andn2_b64", "s_orn2_b64", "s_not_b64", "s_wqm_b64", | ||
| 54 | "s_wqm_b32", "s_cselect_b64", "s_bfm_b64") | ||
| 55 | |||
| 56 | INTERESTING = (0, 1, 2, 3, 31, 32, 33, 63, 64, 0x7FFFFFFF, 0x80000000, 0x80000001, 0xFFFFFFFF, 0xFFFFFFFE, | ||
| 57 | 0x0000FFFF, 0xFFFF0000, 0x00008000, 0xFFFF8000, 0x12345678, 0xDEADBEEF, 0x55555555, 0xAAAAAAAA) | ||
| 58 | |||
| 59 | |||
| 60 | def s32(x): | ||
| 61 | x &= M32 | ||
| 62 | return x - (1 << 32) if x & 0x80000000 else x | ||
| 63 | |||
| 64 | |||
| 65 | def s64(x): | ||
| 66 | x &= M64 | ||
| 67 | return x - (1 << 64) if x >> 63 else x | ||
| 68 | |||
| 69 | |||
| 70 | def sext16(x): | ||
| 71 | x &= 0xFFFF | ||
| 72 | return x - 0x10000 if x & 0x8000 else x | ||
| 73 | |||
| 74 | |||
| 75 | def is_nan(w): | ||
| 76 | return (w & 0x7F800000) == 0x7F800000 and (w & 0x7FFFFF) != 0 | ||
| 77 | |||
| 78 | |||
| 79 | def popcount(x): | ||
| 80 | return bin(x).count("1") | ||
| 81 | |||
| 82 | |||
| 83 | def first_set(x, width): | ||
| 84 | """Index of the lowest set bit, or -1 (0xFFFFFFFF).""" | ||
| 85 | for i in range(width): | ||
| 86 | if (x >> i) & 1: | ||
| 87 | return i | ||
| 88 | return M32 | ||
| 89 | |||
| 90 | |||
| 91 | def wqm(x, width): | ||
| 92 | out = 0 | ||
| 93 | for q in range(0, width, 4): | ||
| 94 | if (x >> q) & 0xF: | ||
| 95 | out |= 0xF << q | ||
| 96 | return out | ||
| 97 | |||
| 98 | |||
| 99 | def bfe(src, ctl, signed): | ||
| 100 | off, width = ctl & 31, (ctl >> 16) & 0x7F | ||
| 101 | if width == 0: | ||
| 102 | return 0 | ||
| 103 | field = (src >> off) & ((1 << width) - 1) | ||
| 104 | if signed and (field >> (width - 1)) & 1: | ||
| 105 | field -= 1 << width | ||
| 106 | return field & M32 | ||
| 107 | |||
| 108 | |||
| 109 | # ---- the reference: one entry per opcode --------------------------------------------------------- | ||
| 110 | # form: "sop2" d, a, b (32-bit); "sop2_64" d, a, b (64-bit pairs); "sop2_64s" d64, a64, b32 (shift amount); | ||
| 111 | # "sop2_bfm64" d64, a32, b32; "sop1" d, a; "sop1_64" d64, a64; "sop1_64to32" d32, a64; "sopc" a, b; | ||
| 112 | # "sopc_64" a64, b64; "sopk" d, simm16 (d is read too); "movk"; "cmpk" a, simm16. | ||
| 113 | # fn(a, b, scc[, d]) -> (result, new_scc or None). None leaves SCC as it was. | ||
| 114 | |||
| 115 | def _sop2(): | ||
| 116 | ops = {} | ||
| 117 | |||
| 118 | def add(name, fn): | ||
| 119 | ops[name] = ("sop2", fn) | ||
| 120 | |||
| 121 | add("s_add_u32", lambda a, b, c: ((a + b) & M32, (a + b) >> 32)) | ||
| 122 | add("s_sub_u32", lambda a, b, c: ((a - b) & M32, int(b > a))) | ||
| 123 | add("s_addc_u32", lambda a, b, c: ((a + b + c) & M32, (a + b + c) >> 32)) | ||
| 124 | add("s_subb_u32", lambda a, b, c: ((a - b - c) & M32, int(b + c > a))) | ||
| 125 | add("s_add_i32", lambda a, b, c: ((a + b) & M32, int(not -2**31 <= s32(a) + s32(b) < 2**31))) | ||
| 126 | add("s_sub_i32", lambda a, b, c: ((a - b) & M32, int(not -2**31 <= s32(a) - s32(b) < 2**31))) | ||
| 127 | add("s_min_i32", lambda a, b, c: (a if s32(a) < s32(b) else b, int(s32(a) < s32(b)))) | ||
| 128 | add("s_min_u32", lambda a, b, c: (a if a < b else b, int(a < b))) | ||
| 129 | add("s_max_i32", lambda a, b, c: (a if s32(a) > s32(b) else b, int(s32(a) > s32(b)))) | ||
| 130 | add("s_max_u32", lambda a, b, c: (a if a > b else b, int(a > b))) | ||
| 131 | add("s_cselect_b32", lambda a, b, c: (a if c else b, None)) | ||
| 132 | for name, f in (("and", lambda a, b: a & b), ("or", lambda a, b: a | b), ("xor", lambda a, b: a ^ b), | ||
| 133 | ("andn2", lambda a, b: a & ~b), ("orn2", lambda a, b: a | ~b), ("nand", lambda a, b: ~(a & b)), | ||
| 134 | ("nor", lambda a, b: ~(a | b)), ("xnor", lambda a, b: ~(a ^ b))): | ||
| 135 | add(f"s_{name}_b32", lambda a, b, c, f=f: (f(a, b) & M32, int(f(a, b) & M32 != 0))) | ||
| 136 | add("s_lshl_b32", lambda a, b, c: ((a << (b & 31)) & M32, int((a << (b & 31)) & M32 != 0))) | ||
| 137 | add("s_lshr_b32", lambda a, b, c: (a >> (b & 31), int(a >> (b & 31) != 0))) | ||
| 138 | add("s_ashr_i32", lambda a, b, c: ((s32(a) >> (b & 31)) & M32, int((s32(a) >> (b & 31)) & M32 != 0))) | ||
| 139 | add("s_bfm_b32", lambda a, b, c: ((((1 << (a & 31)) - 1) << (b & 31)) & M32, None)) | ||
| 140 | add("s_mul_i32", lambda a, b, c: ((s32(a) * s32(b)) & M32, None)) | ||
| 141 | add("s_mul_hi_u32", lambda a, b, c: ((a * b) >> 32, None)) | ||
| 142 | add("s_bfe_u32", lambda a, b, c: (bfe(a, b, False), int(bfe(a, b, False) != 0))) | ||
| 143 | add("s_bfe_i32", lambda a, b, c: (bfe(a, b, True), int(bfe(a, b, True) != 0))) | ||
| 144 | return ops | ||
| 145 | |||
| 146 | |||
| 147 | def _sop2_64(): | ||
| 148 | ops = {} | ||
| 149 | for name, f in (("and", lambda a, b: a & b), ("or", lambda a, b: a | b), ("xor", lambda a, b: a ^ b), | ||
| 150 | ("andn2", lambda a, b: a & ~b), ("orn2", lambda a, b: a | ~b)): | ||
| 151 | ops[f"s_{name}_b64"] = ("sop2_64", lambda a, b, c, f=f: (f(a, b) & M64, int(f(a, b) & M64 != 0))) | ||
| 152 | ops["s_cselect_b64"] = ("sop2_64", lambda a, b, c: (a if c else b, None)) | ||
| 153 | ops["s_lshl_b64"] = ("sop2_64s", lambda a, b, c: ((a << (b & 63)) & M64, int((a << (b & 63)) & M64 != 0))) | ||
| 154 | ops["s_lshr_b64"] = ("sop2_64s", lambda a, b, c: (a >> (b & 63), int(a >> (b & 63) != 0))) | ||
| 155 | ops["s_ashr_i64"] = ("sop2_64s", lambda a, b, c: ((s64(a) >> (b & 63)) & M64, int((s64(a) >> (b & 63)) & M64 != 0))) | ||
| 156 | ops["s_bfm_b64"] = ("sop2_bfm64", lambda a, b, c: ((((1 << (a & 63)) - 1) << (b & 63)) & M64, None)) | ||
| 157 | return ops | ||
| 158 | |||
| 159 | |||
| 160 | def _sop1(): | ||
| 161 | ops = { | ||
| 162 | "s_mov_b32": ("sop1", lambda a, b, c: (a, None)), | ||
| 163 | "s_not_b32": ("sop1", lambda a, b, c: (~a & M32, int(~a & M32 != 0))), | ||
| 164 | "s_brev_b32": ("sop1", lambda a, b, c: (int(f"{a:032b}"[::-1], 2), None)), | ||
| 165 | "s_bcnt0_i32_b32": ("sop1", lambda a, b, c: (32 - popcount(a), int(32 - popcount(a) != 0))), | ||
| 166 | "s_bcnt1_i32_b32": ("sop1", lambda a, b, c: (popcount(a), int(popcount(a) != 0))), | ||
| 167 | "s_ff0_i32_b32": ("sop1", lambda a, b, c: (first_set(~a & M32, 32), None)), | ||
| 168 | "s_ff1_i32_b32": ("sop1", lambda a, b, c: (first_set(a, 32), None)), | ||
| 169 | "s_flbit_i32_b32": ("sop1", lambda a, b, c: (32 - a.bit_length() if a else M32, None)), | ||
| 170 | "s_abs_i32": ("sop1", lambda a, b, c: (abs(s32(a)) & M32, int(abs(s32(a)) & M32 != 0))), | ||
| 171 | "s_wqm_b32": ("sop1", lambda a, b, c: (wqm(a, 32), int(wqm(a, 32) != 0))), | ||
| 172 | # D is read: bit S0[4:0] of the destination is cleared or set. | ||
| 173 | "s_bitset0_b32": ("sop1_rmw", lambda a, b, c, d: (d & ~(1 << (a & 31)) & M32, None)), | ||
| 174 | "s_bitset1_b32": ("sop1_rmw", lambda a, b, c, d: (d | (1 << (a & 31)), None)), | ||
| 175 | "s_mov_b64": ("sop1_64", lambda a, b, c: (a, None)), | ||
| 176 | "s_not_b64": ("sop1_64", lambda a, b, c: (~a & M64, int(~a & M64 != 0))), | ||
| 177 | "s_wqm_b64": ("sop1_64", lambda a, b, c: (wqm(a, 64), int(wqm(a, 64) != 0))), | ||
| 178 | "s_bcnt0_i32_b64": ("sop1_64to32", lambda a, b, c: (64 - popcount(a), int(64 - popcount(a) != 0))), | ||
| 179 | "s_bcnt1_i32_b64": ("sop1_64to32", lambda a, b, c: (popcount(a), int(popcount(a) != 0))), | ||
| 180 | "s_ff0_i32_b64": ("sop1_64to32", lambda a, b, c: (first_set(~a & M64, 64), None)), | ||
| 181 | "s_ff1_i32_b64": ("sop1_64to32", lambda a, b, c: (first_set(a, 64), None)), | ||
| 182 | } | ||
| 183 | return ops | ||
| 184 | |||
| 185 | |||
| 186 | def _sopc(): | ||
| 187 | ops = {} | ||
| 188 | for cmp, f in (("eq", lambda x, y: x == y), ("lg", lambda x, y: x != y), ("gt", lambda x, y: x > y), | ||
| 189 | ("ge", lambda x, y: x >= y), ("lt", lambda x, y: x < y), ("le", lambda x, y: x <= y)): | ||
| 190 | ops[f"s_cmp_{cmp}_i32"] = ("sopc", lambda a, b, c, f=f: (None, int(f(s32(a), s32(b))))) | ||
| 191 | ops[f"s_cmp_{cmp}_u32"] = ("sopc", lambda a, b, c, f=f: (None, int(f(a, b)))) | ||
| 192 | # SOPK compares: SIMM16 sign-extended for i32, zero-extended for u32. | ||
| 193 | ops[f"s_cmpk_{cmp}_i32"] = ("cmpk", lambda a, k, c, f=f: (None, int(f(s32(a), sext16(k))))) | ||
| 194 | ops[f"s_cmpk_{cmp}_u32"] = ("cmpk", lambda a, k, c, f=f: (None, int(f(a, k & 0xFFFF)))) | ||
| 195 | ops["s_bitcmp0_b32"] = ("sopc", lambda a, b, c: (None, int(not (a >> (b & 31)) & 1))) | ||
| 196 | ops["s_bitcmp1_b32"] = ("sopc", lambda a, b, c: (None, int((a >> (b & 31)) & 1))) | ||
| 197 | ops["s_cmp_eq_u64"] = ("sopc_64", lambda a, b, c: (None, int(a == b))) | ||
| 198 | ops["s_cmp_lg_u64"] = ("sopc_64", lambda a, b, c: (None, int(a != b))) | ||
| 199 | ops["s_movk_i32"] = ("movk", lambda a, k, c: (sext16(k) & M32, None)) | ||
| 200 | ops["s_addk_i32"] = ("sopk", lambda d, k, c: ((d + sext16(k)) & M32, | ||
| 201 | int(not -2**31 <= s32(d) + sext16(k) < 2**31))) | ||
| 202 | ops["s_mulk_i32"] = ("sopk", lambda d, k, c: ((s32(d) * sext16(k)) & M32, None)) | ||
| 203 | return ops | ||
| 204 | |||
| 205 | |||
| 206 | OPS = {**_sop2(), **_sop2_64(), **_sop1(), **_sopc()} | ||
| 207 | |||
| 208 | |||
| 209 | # ---- program generation --------------------------------------------------------------------------- | ||
| 210 | |||
| 211 | def _value(rng): | ||
| 212 | return rng.choice(INTERESTING) if rng.random() < 0.6 else rng.getrandbits(32) | ||
| 213 | |||
| 214 | |||
| 215 | def _src32(rng): | ||
| 216 | """An SGPR most of the time, sometimes an inline constant or a literal.""" | ||
| 217 | r = rng.random() | ||
| 218 | if r < 0.75: | ||
| 219 | return f"s{rng.choice(REGS)}" | ||
| 220 | if r < 0.9: | ||
| 221 | return str(rng.randrange(-16, 65)) | ||
| 222 | return f"0x{_value(rng):x}" | ||
| 223 | |||
| 224 | |||
| 225 | def _pair(r): | ||
| 226 | return f"s[{r}:{r + 1}]" | ||
| 227 | |||
| 228 | |||
| 229 | def _src64(rng): | ||
| 230 | if rng.random() < 0.85 or not INLINE64: | ||
| 231 | return _pair(rng.choice(PAIRS)) | ||
| 232 | return str(rng.randrange(-16, 65)) # an inline constant, sign-extended to 64 bits | ||
| 233 | |||
| 234 | |||
| 235 | def _bfe_ctl(rng): | ||
| 236 | off = rng.randrange(0, 32) | ||
| 237 | width = rng.randrange(0, 33 - off) # offset + width <= 32: the documented range | ||
| 238 | return f"0x{(width << 16) | off:x}" | ||
| 239 | |||
| 240 | |||
| 241 | def emit(rng, name): | ||
| 242 | form = OPS[name][0] | ||
| 243 | d, p = rng.choice(REGS), rng.choice(PAIRS) | ||
| 244 | if form == "sop2": | ||
| 245 | b = _bfe_ctl(rng) if name.startswith("s_bfe") and rng.random() < 0.7 else _src32(rng) | ||
| 246 | return f"{name} s{d}, {_src32(rng)}, {b}" | ||
| 247 | if form == "sop2_64": | ||
| 248 | return f"{name} {_pair(p)}, {_src64(rng)}, {_src64(rng)}" | ||
| 249 | if form == "sop2_64s": | ||
| 250 | return f"{name} {_pair(p)}, {_src64(rng)}, {_src32(rng)}" | ||
| 251 | if form == "sop2_bfm64": | ||
| 252 | return f"{name} {_pair(p)}, {_src32(rng)}, {_src32(rng)}" | ||
| 253 | if form in ("sop1", "sop1_rmw"): | ||
| 254 | return f"{name} s{d}, {_src32(rng)}" | ||
| 255 | if form == "sop1_64": | ||
| 256 | return f"{name} {_pair(p)}, {_src64(rng)}" | ||
| 257 | if form == "sop1_64to32": | ||
| 258 | return f"{name} s{d}, {_src64(rng)}" | ||
| 259 | if form == "sopc": | ||
| 260 | return f"{name} {_src32(rng)}, {_src32(rng)}" | ||
| 261 | if form == "sopc_64": | ||
| 262 | return f"{name} {_src64(rng)}, {_src64(rng)}" | ||
| 263 | k = rng.choice((0, 1, 0x7FFF, 0x8000, 0xFFFF, 0xFFFE, rng.getrandbits(16))) | ||
| 264 | if form == "cmpk": | ||
| 265 | return f"{name} s{d}, 0x{k:x}" | ||
| 266 | return f"{name} s{d}, 0x{k:x}" # movk, sopk | ||
| 267 | |||
| 268 | |||
| 269 | def generate(rng, n_ops, ops): | ||
| 270 | lines = [f"s_mov_b32 s{r}, 0x{_value(rng):x}" for r in REGS] | ||
| 271 | lines.append(f"s_cmp_eq_u32 s{rng.choice(REGS)}, s{rng.choice(REGS)}") # a known SCC to start with | ||
| 272 | for _ in range(n_ops): | ||
| 273 | lines.append(emit(rng, rng.choice(ops))) | ||
| 274 | lines += observe(rng.sample(REGS, 3)) | ||
| 275 | return lines | ||
| 276 | |||
| 277 | |||
| 278 | def observe(regs): | ||
| 279 | return [f"s_cselect_b32 s{OUT_SCC}, 1, 0", | ||
| 280 | f"v_mov_b32 v8, s{regs[0]}", f"v_mov_b32 v9, s{regs[1]}", f"v_mov_b32 v10, s{regs[2]}", | ||
| 281 | f"v_mov_b32 v11, s{OUT_SCC}"] | ||
| 282 | |||
| 283 | |||
| 284 | # ---- the reference interpreter ------------------------------------------------------------------- | ||
| 285 | |||
| 286 | class RefError(Exception): | ||
| 287 | pass | ||
| 288 | |||
| 289 | |||
| 290 | def _parse_src(tok, sgpr, width): | ||
| 291 | tok = tok.strip() | ||
| 292 | if tok.startswith("s["): | ||
| 293 | lo = int(tok[2:tok.index(":")]) | ||
| 294 | if width == 32: | ||
| 295 | raise RefError(f"pair {tok} in a 32-bit position") | ||
| 296 | return sgpr.get(lo, 0) | sgpr.get(lo + 1, 0) << 32 | ||
| 297 | if tok.startswith("s"): | ||
| 298 | if width == 64: | ||
| 299 | raise RefError(f"{tok} in a 64-bit position") | ||
| 300 | return sgpr.get(int(tok[1:]), 0) | ||
| 301 | v = int(tok, 0) | ||
| 302 | if width == 64: | ||
| 303 | # inline constants are sign-extended; a 32-bit literal is zero-extended (not generated here) | ||
| 304 | return v & M64 if -16 <= v <= 64 else v & M32 | ||
| 305 | return v & M32 | ||
| 306 | |||
| 307 | |||
| 308 | def _write(sgpr, tok, value, width): | ||
| 309 | tok = tok.strip() | ||
| 310 | if width == 64: | ||
| 311 | lo = int(tok[2:tok.index(":")]) | ||
| 312 | sgpr[lo], sgpr[lo + 1] = value & M32, (value >> 32) & M32 | ||
| 313 | else: | ||
| 314 | sgpr[int(tok[1:])] = value & M32 | ||
| 315 | |||
| 316 | |||
| 317 | def reference(lines): | ||
| 318 | """Run the scalar program; returns the four exported words.""" | ||
| 319 | sgpr, scc, vgpr = {}, 0, {} | ||
| 320 | for line in lines: | ||
| 321 | op, _, rest = line.partition(" ") | ||
| 322 | args = [a.strip() for a in rest.split(", ")] if rest else [] | ||
| 323 | if op == "v_mov_b32": | ||
| 324 | vgpr[int(args[0][1:])] = _parse_src(args[1], sgpr, 32) | ||
| 325 | continue | ||
| 326 | if op not in OPS: | ||
| 327 | raise RefError(f"{op} is not modelled") | ||
| 328 | form, fn = OPS[op] | ||
| 329 | if form == "sop2": | ||
| 330 | r, c = fn(_parse_src(args[1], sgpr, 32), _parse_src(args[2], sgpr, 32), scc) | ||
| 331 | _write(sgpr, args[0], r, 32) | ||
| 332 | elif form == "sop2_64": | ||
| 333 | r, c = fn(_parse_src(args[1], sgpr, 64), _parse_src(args[2], sgpr, 64), scc) | ||
| 334 | _write(sgpr, args[0], r, 64) | ||
| 335 | elif form == "sop2_64s": | ||
| 336 | r, c = fn(_parse_src(args[1], sgpr, 64), _parse_src(args[2], sgpr, 32), scc) | ||
| 337 | _write(sgpr, args[0], r, 64) | ||
| 338 | elif form == "sop2_bfm64": | ||
| 339 | r, c = fn(_parse_src(args[1], sgpr, 32), _parse_src(args[2], sgpr, 32), scc) | ||
| 340 | _write(sgpr, args[0], r, 64) | ||
| 341 | elif form == "sop1": | ||
| 342 | r, c = fn(_parse_src(args[1], sgpr, 32), None, scc) | ||
| 343 | _write(sgpr, args[0], r, 32) | ||
| 344 | elif form == "sop1_rmw": | ||
| 345 | r, c = fn(_parse_src(args[1], sgpr, 32), None, scc, _parse_src(args[0], sgpr, 32)) | ||
| 346 | _write(sgpr, args[0], r, 32) | ||
| 347 | elif form == "sop1_64": | ||
| 348 | r, c = fn(_parse_src(args[1], sgpr, 64), None, scc) | ||
| 349 | _write(sgpr, args[0], r, 64) | ||
| 350 | elif form == "sop1_64to32": | ||
| 351 | r, c = fn(_parse_src(args[1], sgpr, 64), None, scc) | ||
| 352 | _write(sgpr, args[0], r, 32) | ||
| 353 | elif form == "sopc": | ||
| 354 | _, c = fn(_parse_src(args[0], sgpr, 32), _parse_src(args[1], sgpr, 32), scc) | ||
| 355 | elif form == "sopc_64": | ||
| 356 | _, c = fn(_parse_src(args[0], sgpr, 64), _parse_src(args[1], sgpr, 64), scc) | ||
| 357 | elif form == "cmpk": | ||
| 358 | _, c = fn(_parse_src(args[0], sgpr, 32), int(args[1], 0), scc) | ||
| 359 | elif form == "movk": | ||
| 360 | r, c = fn(None, int(args[1], 0), scc) | ||
| 361 | _write(sgpr, args[0], r, 32) | ||
| 362 | elif form == "sopk": | ||
| 363 | r, c = fn(_parse_src(args[0], sgpr, 32), int(args[1], 0), scc) | ||
| 364 | _write(sgpr, args[0], r, 32) | ||
| 365 | else: | ||
| 366 | raise RefError(f"form {form}") | ||
| 367 | if c is not None: | ||
| 368 | scc = int(c) | ||
| 369 | return [vgpr.get(r, 0) for r in (8, 9, 10, 11)] | ||
| 370 | |||
| 371 | |||
| 372 | # ---- the translator side ------------------------------------------------------------------------- | ||
| 373 | |||
| 374 | def translated(lines, name="ps_salu"): | ||
| 375 | """Translate and execute; returns the four exported words, or raises Skip.""" | ||
| 376 | import rdna2spirv | ||
| 377 | from spirv_mini_interp import run_fragment | ||
| 378 | with tempfile.TemporaryDirectory(prefix="salu-diff-") as tmp: | ||
| 379 | dis = os.path.join(tmp, "disasm") | ||
| 380 | os.mkdir(dis) | ||
| 381 | path = os.path.join(dis, name + ".s") | ||
| 382 | with open(path, "w", encoding="utf-8") as f: | ||
| 383 | f.write(f"; {name} salu_diff case\n") | ||
| 384 | for line in lines: | ||
| 385 | f.write("\t" + line + "\n") | ||
| 386 | f.write("\texp mrt0 v8, v9, v10, v11 done vm\n\ts_endpgm\n") | ||
| 387 | with open(os.path.join(tmp, name + ".dxbc"), "wb") as f: | ||
| 388 | f.write(STUB_DXBC) | ||
| 389 | try: | ||
| 390 | with warnings.catch_warnings(): | ||
| 391 | warnings.simplefilter("ignore", ResourceWarning) | ||
| 392 | spvasm = rdna2spirv.translate(path) | ||
| 393 | gc.collect() | ||
| 394 | except rdna2spirv.Unsupported as e: | ||
| 395 | raise Skip(f"translator unsupported: {e}") from None | ||
| 396 | try: | ||
| 397 | out = run_fragment(spvasm) | ||
| 398 | except Exception as e: # noqa: BLE001 - an interpreter gap is a counted skip, never a pass | ||
| 399 | raise Skip(f"mini_interp: {type(e).__name__}: {str(e)[:80]}") from None | ||
| 400 | return [w & M32 for w in out["%out_mrt0"]] | ||
| 401 | |||
| 402 | |||
| 403 | class Skip(Exception): | ||
| 404 | pass | ||
| 405 | |||
| 406 | |||
| 407 | def check(lines): | ||
| 408 | """None on a match, else a description. Raises Skip / RefError.""" | ||
| 409 | want = reference(lines) | ||
| 410 | got = translated(lines) | ||
| 411 | # A signalling-NaN pattern comes back quiet: the exported words pass through Python floats in the interpreter. | ||
| 412 | bad = [k for k in range(4) if want[k] != got[k] and not (is_nan(want[k]) and is_nan(got[k]))] | ||
| 413 | if not bad: | ||
| 414 | return None | ||
| 415 | i = bad[0] | ||
| 416 | what = "SCC" if i == 3 else lines[-4 + i].split(", ")[1] | ||
| 417 | return f"word {i} ({what}): reference 0x{want[i]:08x}, translated 0x{got[i]:08x}" | ||
| 418 | |||
| 419 | |||
| 420 | def shrink(lines): | ||
| 421 | """Drop instructions (not seeds or the observation) while the program still mismatches.""" | ||
| 422 | n_seed = len(REGS) | ||
| 423 | body = lines[n_seed:-5] | ||
| 424 | changed = True | ||
| 425 | while changed: | ||
| 426 | changed = False | ||
| 427 | for i in range(len(body)): | ||
| 428 | trial = lines[:n_seed] + body[:i] + body[i + 1:] + lines[-5:] | ||
| 429 | try: | ||
| 430 | if check(trial): | ||
| 431 | body = body[:i] + body[i + 1:] | ||
| 432 | changed = True | ||
| 433 | break | ||
| 434 | except (Skip, RefError): | ||
| 435 | continue | ||
| 436 | return lines[:n_seed] + body + lines[-5:] | ||
| 437 | |||
| 438 | |||
| 439 | def run_suite(programs, seed, max_ops, ops): | ||
| 440 | counts = {"pass": 0, "mismatch": 0, "skip": {}} | ||
| 441 | failures = [] | ||
| 442 | rng = random.Random(seed) | ||
| 443 | for i in range(programs): | ||
| 444 | lines = generate(rng, rng.randrange(1, max_ops + 1), ops) | ||
| 445 | try: | ||
| 446 | problem = check(lines) | ||
| 447 | except Skip as e: | ||
| 448 | counts["skip"][str(e)] = counts["skip"].get(str(e), 0) + 1 | ||
| 449 | continue | ||
| 450 | if problem is None: | ||
| 451 | counts["pass"] += 1 | ||
| 452 | continue | ||
| 453 | counts["mismatch"] += 1 | ||
| 454 | failures.append((i, problem, lines)) | ||
| 455 | return counts, failures | ||
| 456 | |||
| 457 | |||
| 458 | def self_test(): | ||
| 459 | ok = check(["s_mov_b32 s4, 5", "s_mov_b32 s5, 7", "s_add_u32 s6, s4, s5", "s_cmp_eq_u32 s4, s4"] | ||
| 460 | + observe([4, 5, 6])) is None | ||
| 461 | caught = reference(["s_mov_b32 s4, 0xffffffff", "s_add_u32 s5, s4, 1"] + observe([4, 5, 6]))[3] == 1 | ||
| 462 | try: | ||
| 463 | translated(["s_rfe_b64 s[4:5]"] + observe([4, 5, 6])) | ||
| 464 | skipped = False | ||
| 465 | except Skip: | ||
| 466 | skipped = True | ||
| 467 | print(f"self-test: match {ok}, carry modelled {caught}, unsupported op skipped {skipped}") | ||
| 468 | return ok and caught and skipped | ||
| 469 | |||
| 470 | |||
| 471 | def main(argv=None): | ||
| 472 | ap = argparse.ArgumentParser(description="Scalar ALU / SCC differential fuzzing (FUZZ-4).") | ||
| 473 | ap.add_argument("--programs", type=int, default=300) | ||
| 474 | ap.add_argument("--seed", type=int, default=1) | ||
| 475 | ap.add_argument("--max-ops", type=int, default=6) | ||
| 476 | ap.add_argument("--ops", default="", help="comma-separated opcodes (default: all)") | ||
| 477 | ap.add_argument("--list-ops", action="store_true") | ||
| 478 | ap.add_argument("--self-test", action="store_true") | ||
| 479 | ap.add_argument("--all-failures", action="store_true", help="print every failing program, not just the first") | ||
| 480 | ap.add_argument("--inline64", action="store_true", | ||
| 481 | help="also use inline constants as 64-bit sources (the translator reads them as lane masks)") | ||
| 482 | a = ap.parse_args(argv) | ||
| 483 | global INLINE64 | ||
| 484 | INLINE64 = a.inline64 | ||
| 485 | if a.list_ops: | ||
| 486 | for name in sorted(OPS): | ||
| 487 | print(f"{name:20} {OPS[name][0]}") | ||
| 488 | return 0 | ||
| 489 | if a.self_test: | ||
| 490 | return 0 if self_test() else 1 | ||
| 491 | ops = sorted(a.ops.split(",")) if a.ops else sorted(o for o in OPS if o not in LANE_MASK_OPS) | ||
| 492 | unknown = [o for o in ops if o not in OPS] | ||
| 493 | if unknown: | ||
| 494 | print("unknown ops: " + ", ".join(unknown)) | ||
| 495 | return 2 | ||
| 496 | counts, failures = run_suite(a.programs, a.seed, a.max_ops, ops) | ||
| 497 | skips = sum(counts["skip"].values()) | ||
| 498 | print(f"{a.programs} programs (seed {a.seed}): {counts['pass']} pass, {counts['mismatch']} mismatch, {skips} skipped") | ||
| 499 | for reason, n in sorted(counts["skip"].items(), key=lambda kv: -kv[1]): | ||
| 500 | print(f" skip x{n}: {reason}") | ||
| 501 | for i, problem, lines in failures[: None if a.all_failures else 1]: | ||
| 502 | small = shrink(lines) | ||
| 503 | print(f"MISMATCH program {i}: {check(small) or problem}") | ||
| 504 | print("\n".join("\t" + line for line in small)) | ||
| 505 | return 1 if failures else 0 | ||
| 506 | |||
| 507 | |||
| 508 | if __name__ == "__main__": | ||
| 509 | sys.exit(main()) | ||