From 96c3b49a315cdbab557e194818adb2b7809c67a0 Mon Sep 17 00:00:00 2001 From: legacy-code-archaeologist <359844974+legacy-code-archaeologist@users.noreply.github.com> Date: Fri, 27 Nov 2026 16:55:48 +0100 Subject: [PATCH] shader: lower v_mad_u64_u32 and v_mad_i64_i32 in the direct C++ compute path The direct compute frontend refused the 64-bit multiply-adds. They now follow gfx2hlsl.py's mad64: D = S0 * S1 + S2 modulo 2^64 with zero- or sign-extended 32-bit factors and a VGPR- or SGPR-pair S2. The unsigned form writes the carry-out of the 64-bit add to its VOP3B SDST through the lane-mask path of the carry adds, and carry_destination names that SDST for the symbolic state. The signed form is lowered only with the null SDST, and inline float factors are refused, as in gfx2hlsl.py. tests/native_mad64_check.py dispatches products just below 2^64 so that exactly the odd lanes carry, checks the module, three refusals and three mutated references. Refs #3000. AI-assisted. Co-Authored-By: Claude Opus 5.5 # Conflicts: # src/gfx1013_direct_compute.inl --- docs/experiments/native-direct-mad64.md | 43 ++++++++ src/gfx1013_compute_native.cpp | 2 + src/gfx1013_direct_compute.inl | 32 ++++++ tests/cmake/native_mad64.cmake | 13 +++ tests/native_mad64_check.py | 133 ++++++++++++++++++++++++ 5 files changed, 223 insertions(+) create mode 100644 docs/experiments/native-direct-mad64.md create mode 100644 tests/cmake/native_mad64.cmake create mode 100644 tests/native_mad64_check.py diff --git a/docs/experiments/native-direct-mad64.md b/docs/experiments/native-direct-mad64.md new file mode 100644 index 0000000000..a6ae631c69 --- /dev/null +++ b/docs/experiments/native-direct-mad64.md @@ -0,0 +1,43 @@ +# v_mad_u64_u32 and v_mad_i64_i32 in the direct C++ compute path (#3000) + +The direct compute frontend now lowers the two 64-bit multiply-adds. Before, it refused them with +`direct DXIL lowering for `. The contract is `gfx2hlsl.py` `mad64`: D = S0 * S1 + S2 modulo 2^64, with +32-bit factors and a 64-bit S2. The factors are zero-extended for `v_mad_u64_u32` and sign-extended for +`v_mad_i64_i32`. + +- `v_mad_u64_u32` writes the carry-out of the 64-bit add (sum < S2, unsigned) to its VOP3B SDST, which is VCC or + an SGPR. This uses the lane-mask path of the other carry instructions (`write_ballot`). `carry_destination` in + `src/gfx1013_compute_native.cpp` names its SDST so that the symbolic state forgets the old SGPR value. +- `v_mad_i64_i32` is lowered only with the null SDST. As in `gfx2hlsl.py`, the signed carry-out is not + established. Any other SDST is refused with `v_mad_i64_i32 carry-out destination`. +- S2 must be a VGPR pair or an aligned SGPR pair. Inline and literal 64-bit addends are refused, a narrower + contract than `gfx2hlsl.py`'s `i64_words`. +- In VOP3B, the ABS field holds SDST, so only NEG, clamp and the output modifier are refused among the modifiers. + SDWA, DPP, pixel stages and graphics inputs are refused as for the carry adds. An inline float factor is refused, + as in `gfx2hlsl.py`. +- The unsigned form with the null SDST is refused by the symbolic transfer (`unsupported carry mask destination`), + also as in `gfx2hlsl.py`, which takes only VCC or an SGPR there. + +## Fixture + +`tests/native_mad64_check.py controls|hardware` (`ctest --preset dev --no-tests=error -R '^native_mad64_' -V`). +The words were assembled with LLVM 15.0.7 (`clang -cc1as -triple amdgcn -target-cpu gfx1013 -filetype asm +-show-encoding`). + +- The dispatch has two groups of 32 lanes. With n = lane + 32 * group: + - S0 = mul_u32_u24(n, 0x0f0f0f) ^ 0xffff0000 + - S1 = mul_u32_u24(n, 0x123457) ^ 0xfff00000 + - S2 = {((n & 1) << 31) | 0x10, mul_u32_u24(n, 0x777777) ^ 0x89abcdef} + + The products lie just below 2^64, so the unsigned sum carries exactly for the odd lanes (mask 0xaaaaaaaa). Each + lane stores the unsigned and signed results and the carry mask copied from s30. +- The controls: + - check the module for two `mul i64`, a sign extension and the unsigned carry compare; + - refuse `v_mad_i64_i32` with an SGPR carry-out, `v_mad_u64_u32` with the null SDST, and an inline float factor; + - check that both groups have mixed carries; + - check that three mutated references each differ from the expected words: high word dropped, signed factors + zero-extended, and no carry. + +Measured on 27.11.2026, `cpp-migration` `e0d83759` plus this change, Windows 10.0.26100.9711. The controls passed. +The readback reported a skip (77) on the NVIDIA Quadro M1000M (driver 32.0.15.7371, debug layer unavailable): it +needs shader model 6.6 with wave32. The readback is not measured. diff --git a/src/gfx1013_compute_native.cpp b/src/gfx1013_compute_native.cpp index d7cf61bb4c..4a2f8949c7 100644 --- a/src/gfx1013_compute_native.cpp +++ b/src/gfx1013_compute_native.cpp @@ -418,6 +418,8 @@ static std::optional carry_destination(const Inst &i) { if (i.name == "v_add_co_u32" || i.name == "v_sub_co_u32" || i.name == "v_subrev_co_u32" || i.name == "v_add_co_ci_u32" || i.name == "v_sub_co_ci_u32" || i.name == "v_subrev_co_ci_u32") return i.wide ? (i.a >> 8) & 127 : 106; + if (i.name == "v_mad_u64_u32") // VOP3B: the carry-out of the 64-bit add (#3000) + return (i.a >> 8) & 127; return {}; } struct Symbol { diff --git a/src/gfx1013_direct_compute.inl b/src/gfx1013_direct_compute.inl index 7375533562..d76fce0c9c 100644 --- a/src/gfx1013_direct_compute.inl +++ b/src/gfx1013_direct_compute.inl @@ -1655,6 +1655,38 @@ struct DirectCompute { vector_write(i.dst, ir.binary("or", lo, ir.binary("shl", hi, "16"))); return; } + if (n == "v_mad_u64_u32" || n == "v_mad_i64_i32") { + // D = S0 * S1 + S2 modulo 2^64 with 32-bit factors and a 64-bit S2 (#3000, gfx2hlsl.py mad64). The + // unsigned form writes the carry-out of the 64-bit add as a lane mask; the signed carry-out is not + // established, so the signed form is lowered only with the discarding null SDST. In VOP3B the ABS field + // holds SDST, so only NEG, clamp and the output modifier are refused here. + const bool sign = n == "v_mad_i64_i32"; + const unsigned sdst = (i.a >> 8) & 127, addend = i.src[2]; + if (pixel_stage || graphics_input || i.subword || i.dpp_control || i.neg || i.clamp || i.scale) + refuse(i.pc, "unsupported " + string(n) + " stage or operand modifiers"); + if (sign ? sdst != 125 : (sdst > 105 && sdst != 106)) + refuse(i.pc, string(n) + " carry-out destination"); + const bool vgpr_pair = addend >= 256 && addend < 511, sgpr_pair = addend <= 104 && !(addend & 1); + if (!(vgpr_pair || sgpr_pair) || i.dst >= 511) + refuse(i.pc, string(n) + " addend or destination operand"); + for (unsigned j = 0; j < 2; ++j) // gfx2hlsl.py refuses an inline float as a factor + if (i.src[j] >= 240 && i.src[j] <= 248) + refuse(i.pc, string(n) + " with an inline float factor"); + const char *extend = sign ? "sext" : "zext"; + auto wide = [&](const char *how, const string &x) { return ir.value(string(how) + " i32 " + x + " to i64"); }; + auto c = ir.value("or i64 " + ir.value("shl i64 " + wide("zext", operand32(i, addend + 1)) + ", 32") + ", " + + wide("zext", operand32(i, addend))); + auto product = ir.value("mul i64 " + wide(extend, operand32(i, i.src[0])) + ", " + + wide(extend, operand32(i, i.src[1]))); + auto sum = ir.value("add i64 " + product + ", " + c); + auto carry = ir.value("icmp ult i64 " + sum + ", " + c); + ir.features |= 1048576; + vector_write(i.dst, ir.value("trunc i64 " + sum + " to i32")); + vector_write(i.dst + 1, ir.value("trunc i64 " + ir.value("lshr i64 " + sum + ", 32") + " to i32")); + if (!sign) + write_ballot(sdst, carry); + return; + } if (auto dst = carry_destination(i)) { if (pixel_stage || (graphics_input && ir.loop_dependencies) || i.subword || i.dpp_control || i.clamp || i.neg || i.scale) refuse(i.pc, "unsupported carry instruction stage or operand modifiers"); diff --git a/tests/cmake/native_mad64.cmake b/tests/cmake/native_mad64.cmake new file mode 100644 index 0000000000..328844cea9 --- /dev/null +++ b/tests/cmake/native_mad64.cmake @@ -0,0 +1,13 @@ +# Direct C++ compute: v_mad_u64_u32 and v_mad_i64_i32 (#3000). The controls compile and check the +# reference's mutants; the readback needs shader model 6.6 with wave32 and otherwise reports a skip (77). +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_mad64_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_mad64_check.py" controls + "$" "${DXC_BIN_DIR}") + set_tests_properties(native_mad64_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_mad64_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_mad64_check.py" hardware + "$" "${DXC_BIN_DIR}") + set_tests_properties(native_mad64_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/native_mad64_check.py b/tests/native_mad64_check.py new file mode 100644 index 0000000000..72dab0db6f --- /dev/null +++ b/tests/native_mad64_check.py @@ -0,0 +1,133 @@ +"""v_mad_u64_u32 and v_mad_i64_i32 in the direct compute path (#3000). + + native_mad64_check.py controls + native_mad64_check.py hardware + +D = S0 * S1 + S2 modulo 2^64, with 32-bit factors (zero- or sign-extended) and a 64-bit S2 (gfx2hlsl.py mad64). The +unsigned form writes the carry-out of the 64-bit add to its SDST as a lane mask; the signed form is lowered only with +the null SDST, as in gfx2hlsl.py. All words were assembled with LLVM 15.0.7 (clang -cc1as, gfx1013). + +The dispatch has two groups of 32 lanes. With n = lane + 32 * group, S0 = mul_u32_u24(n, 0x0f0f0f) ^ 0xffff0000, +S1 = mul_u32_u24(n, 0x123457) ^ 0xfff00000 and S2 = {((n & 1) << 31) | 0x10, mul_u32_u24(n, 0x777777) ^ 0x89abcdef}, +so the products lie just below 2^64 and the unsigned sum carries exactly for the odd lanes. Each lane stores the unsigned and signed results and +the carry mask in s30 (v_mov_b32 v12, s30), which must equal the ballot of its group. References that drop the +high word, zero-extend the signed factors or report no carry must each differ. +""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_dpp_quad_check import request + +# See the docstring; the program ends with buffer_store_dword v4, v5, v10, v11, v12 at v8 + 0..16 and s_endpgm. +HEX = ('040394be 800395be 0a0808f4200000fa 058a078f 0585088f 85001034 0710104a 0800124a ff1202160f0f0f00 ' + 'ff02023a0000ffff ff12041657341200 ff04043a0000f0ff ff120c1677777700 ff0c0c3aefcdab89 81120e36 9f0e0e34 900e0e38 ' + '041e76d501051a04 0a7d77d501051a04 1e02187e 7fc08cbf 001070e008040880 041070e008050880 081070e0080a0880 ' + '0c1070e0080b0880 101070e0080c0880 000081bf') +SIGNED_WITH_SDST = '0a1e77d501051a04' # v_mad_i64_i32 v[10:11], s30, v1, v2, v[6:7]: refused +SENTINEL = 0x69696969 +GUARD_WORDS = 8 +OUTPUT_WORDS = 2064 +M32, M64 = 0xFFFFFFFF, (1 << 64) - 1 + + +def words(text): + out = [] + for h in text.split(): + out += [int.from_bytes(bytes.fromhex(h[i:i + 8]), 'little') for i in range(0, len(h), 8)] + return out + + +def mul24(x, y): + return ((x & 0xFFFFFF) * (y & 0xFFFFFF)) & M32 + + +def s32(x): + return x - (1 << 32) if x & 0x80000000 else x + + +def operands(n): + a, b = mul24(n, 0x0F0F0F) ^ 0xFFFF0000, mul24(n, 0x123457) ^ 0xFFF00000 + c = ((((n & 1) << 31) | 0x10) << 32) | (mul24(n, 0x777777) ^ 0x89ABCDEF) + return a, b, c + + +def reference(drop_high=False, zero_extend_signed=False, no_carry=False): + expected = [SENTINEL] * OUTPUT_WORDS + for group in range(2): + mask = 0 + rows = [] + for lane in range(32): + a, b, c = operands(lane + 32 * group) + total = a * b + c + mask |= (0 if no_carry else int(total > M64)) << lane + signed = ((a * b if zero_extend_signed else s32(a) * s32(b)) + c) & M64 + unsigned = total & M64 + rows.append([unsigned & M32, 0 if drop_high else unsigned >> 32, signed & M32, signed >> 32]) + for lane, row in enumerate(rows): + base = GUARD_WORDS + (group * 32 + lane) * 8 + expected[base:base + 5] = row + [mask] + return expected + + +def compile_program(cli, sdk, work, root, code): + marker = request(work, root, code) + return marker, subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, + marker.with_suffix('.cso')], capture_output=True, text=True) + + +def controls(cli, sdk, work, root): + marker, result = compile_program(cli, sdk, work, root, words(HEX)) + assert result.returncode == 0 and marker.with_suffix('.cso').is_file(), (result.stdout, result.stderr) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', marker.with_suffix('.cso')], capture_output=True, + text=True, check=True).stdout + assert dump.count('mul i64') == 2 and 'sext i32' in dump and 'icmp ult i64' in dump, dump + signed_sdst = HEX.replace('0a7d77d501051a04', SIGNED_WITH_SDST) + _, result = compile_program(cli, sdk, work, root, words(signed_sdst)) + assert result.returncode and 'v_mad_i64_i32 carry-out destination' in result.stderr, (result.stdout, result.stderr) + # The unsigned form with the null SDST is refused by the symbolic transfer, as gfx2hlsl.py refuses it, and an + # inline float factor is refused like in gfx2hlsl.py. + for code, message in ((HEX.replace('041e76d501051a04', '047d76d501051a04'), 'unsupported carry mask destination'), + (HEX.replace('041e76d501051a04', '041e76d5f2041a04'), 'with an inline float factor')): + _, result = compile_program(cli, sdk, work, root, words(code)) + assert result.returncode and message in result.stderr, (message, result.stdout, result.stderr) + expected = reference() + masks = {expected[GUARD_WORDS + g * 32 * 8 + 4] for g in range(2)} + assert all(0 < m < M32 for m in masks), [hex(m) for m in masks] # some lanes carry, some do not + for label, mutation in (('high word dropped', {'drop_high': True}), + ('signed factors zero-extended', {'zero_extend_signed': True}), + ('no carry', {'no_carry': True})): + assert reference(**mutation) != expected, label + print('compiled with two 64-bit multiplies and an unsigned carry compare; the signed form with an SGPR ' + 'carry-out, the unsigned form with null and an inline float factor refused; both groups have mixed carries; the three mutated references differ') + return 0 + + +def hardware(replay, sdk, work, root): + marker = request(work, root, words(HEX)) + output = work / 'out.bin' + result = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if result.returncode == 77: + return 77 + result.check_returncode() + actual = list(struct.unpack(f'<{OUTPUT_WORDS}I', output.read_bytes())) + diff = [(i, hex(x), hex(y)) for i, (x, y) in enumerate(zip(actual, reference())) if x != y] + assert not diff, diff[:10] + print('v_mad_u64_u32 and v_mad_i64_i32: results, carry masks, guards and sentinels matched') + return 0 + + +def main(mode, tool, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return {'controls': controls, 'hardware': hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:]))