From e3e132b14446805dde968785324446bc0e641625 Mon Sep 17 00:00:00 2001 From: henriazz10 <100179000+henriazz10@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:31:27 -0300 Subject: [PATCH] shader: add per-lane v_cmp_* and v_cndmask_b32 in compute_store_aot Refs #721 Written with Gemini 4 Hydrogen (Antigravity CLI), reviewed by Claude. --- CMakeLists.txt | 5 + docs/experiments.md | 10 + tests/compute_alu_cmp_ne_check.py | 3 +- tests/compute_lane_mask_check.py | 12 +- tests/compute_store_check.py | 384 ++++++++++++++++++++++++++++++ tools/compute_store_aot.py | 140 +++++++++-- 6 files changed, 522 insertions(+), 32 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index df192b9fc..b119b8538 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -6977,6 +6977,11 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter}) set_tests_properties(compute_store_aot_bfe_${adapter} PROPERTIES TIMEOUT 45 ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/compute_store_aot_bfe_${adapter}.txt") + add_test(NAME compute_store_aot_vcmp_select_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/compute_store_check.py" draw-vcmp-select "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(compute_store_aot_vcmp_select_${adapter} PROPERTIES TIMEOUT 45 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/compute_store_aot_vcmp_select_${adapter}.txt") add_test(NAME compute_store_aot_mubuf_reduction_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/compute_store_check.py" draw-mubuf-reduction "${DXC_EXECUTABLE}" "$" ${adapter}) diff --git a/docs/experiments.md b/docs/experiments.md index ac23ae63d..f87b9bea7 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -5477,6 +5477,16 @@ The `DOT_U` fixture in `tests/compute_store_check.py` (`draw-dot-u`, `compute_st ctest --preset dev --no-tests=error -R '^compute_store_aot_dot_u_(warp|hardware)$' -V ``` +#### Per-lane compare and select + +`v_cmp_{f,lt,eq,le,gt,ne,ge,t}_{u32,i32}` (`_e32` into `vcc_lo` and `_e64` into `vcc_lo` or `s0..s105`), `v_cmp_{f,lt,eq,le,gt,lg,ge,o,u,nge,nlg,ngt,nle,neq,nlt,tru}_f32` (`_e32` into `vcc_lo` and `_e64` into `vcc_lo` or `s0..s105`), `v_cndmask_b32_e32 vD, S0, vS1, vcc_lo`, and `v_cndmask_b32_e64 vD, S0, S1, (vcc_lo|sN)` track per-lane compare results as `("cond", hlsl_bool_expression)` in `vcc_cond` or `scalar[n]` and lower selects to `(cond ? S1 : S0)`. Because only the same lane reads its condition bit, the lowering is independent of wave size. Integer `u32` compares compare `uint` words, `i32` compares cast via `asint(...)`, and `f32` compares cast via `asfloat(...)` with explicit `isnan(...)` checks for all ordered and unordered IEEE NaN predicates. Existing lane guards (`s_and_saveexec_b32` on uniform `v_cmp`), constant-mask `v_cndmask_b32_e64`, and `vcc_carry`/`vcc_borrow` keep their behavior, and any write to `vcc_lo` invalidates the other VCC-derived states. `f32` source modifiers, `clamp`, SDWA/DPP spellings, scalar ALU or branch readers of a condition SGPR, `s_and_saveexec_b32` on a condition built from loaded or ALU data, `_ci` carry-in from a condition, and stale conditions after another VCC write are refused. + +The `VCMP_SELECT` suite in `tests/compute_store_check.py` (`draw-vcmp-select`, `compute_store_aot_vcmp_select_${adapter}`) runs 12 64-thread `gfx1013` dispatches (`buffer_store_dwordx4`, 256 output words plus 64 `SENTINEL` words each) covering all 32 predicates across equal values, `0x7fffffff` vs `0x80000000`, `0` vs `0xffffffff`, denormal raw words (`0x00000001` vs `0x80000001`), `±0`, `NaN` on either or both sides, `±inf`, and memory-loaded/`tid` inputs, comparing all 3,840 words against an independent Python model. Reference controls (`lt`/`gt` swapped at word 1, signed for unsigned at word 1, ordered for unordered at word 5, select operands swapped at word 0, sentinel modified at word 256) and recompiled-HLSL mutations (`<` for `<=`, `asint` dropped, `isnan` replaced by `isinf` on an unordered predicate) must all fail. + +```powershell +ctest --preset dev --no-tests=error -R '^compute_store_aot_vcmp_select_(warp|hardware)$' -V +``` + ### Two- and three-dimensional thread groups The PSV0 group size can be any `numthreads(x,y,z)` within the `cs_6_0` limits diff --git a/tests/compute_alu_cmp_ne_check.py b/tests/compute_alu_cmp_ne_check.py index c7c3efbe0..a322186c8 100644 --- a/tests/compute_alu_cmp_ne_check.py +++ b/tests/compute_alu_cmp_ne_check.py @@ -26,7 +26,8 @@ def controls(): for compare, diagnostic in ( ("v_cmp_ne_i32_e32 vcc_lo, v0, s3", "Unsupported compute instruction"), ("v_cmp_ne_i32_e32 vcc_hi, s3, v0", "Unsupported compute instruction"), - ("v_cmp_ne_i32_e64 s20, s3, v0", "Unsupported compute instruction"), + # v_cmp_ne_i32_e64 s20, ... sets s20 to a per-lane cond without writing vcc_lo, so s_and_saveexec_b32 refuses it. + ("v_cmp_ne_i32_e64 s20, s3, v0", "Unverified or repeated lane guard"), ("v_cmp_ne_i32_e64 vcc_lo, -v0, s3", "Unsupported compute instruction"), ("v_cmpx_ne_i32_e32 vcc_lo, s3, v0", "Unsupported compute instruction"), ("v_cmp_ne_i32_e32 vcc_lo, s20, v0", "Unverified lane guard compare"), diff --git a/tests/compute_lane_mask_check.py b/tests/compute_lane_mask_check.py index 2afde39fa..3a08942f5 100644 --- a/tests/compute_lane_mask_check.py +++ b/tests/compute_lane_mask_check.py @@ -123,13 +123,13 @@ def mask(*changes, width=32, lines=LANE_MASK, **binding): (lane_mask, (("0x600d, s8", "0x600d, s4"),), {}), (lane_mask, (("s_bitreplicate_b64_b32 s[8:9], 0x3f3f3f3f", "s_mov_b32 s8, 0x3f3f3f3f\ns_add_u32 s8, s8, s14"), ("s_mov_b32 s14, 0xbeef", ""), ("s_mov_b32 s1, 0", "s_mov_b32 s1, 0\ns_mov_b32 s14, 0xbeef")), {}), - # Mask uses the profile does not lower: a wave64 pair, vcc_lo or exec_lo as the mask, the e32 form, an exec - # write from the mask, and a saveexec from it instead of a compare. + # Mask uses the profile does not lower: a wave64 pair, exec_lo as the mask, an exec write from the mask, + # and a saveexec from it instead of a compare; vcc_lo without a prior v_cmp_* cond is an unverified lane mask. (unsupported + "v_cndmask_b32_e64 v1, v0, 0x600d, s[8:9]", (("0x600d, s8", "0x600d, s[8:9]"),), {}), - (unsupported + "v_cndmask_b32_e64 v1, v0, 0x600d, vcc_lo", (("0x600d, s8", "0x600d, vcc_lo"),), {}), + (lane_mask, (("0x600d, s8", "0x600d, vcc_lo"),), {}), (unsupported + "v_cndmask_b32_e64 v1, v0, 0x600d, exec_lo", (("0x600d, s8", "0x600d, exec_lo"),), {}), - (unsupported + "v_cndmask_b32_e32", (("v_cndmask_b32_e64 v2, s14, v0, s10", - "v_cndmask_b32_e32 v2, s14, v0, vcc_lo"),), {}), + (lane_mask, (("v_cndmask_b32_e64 v2, s14, v0, s10", + "v_cndmask_b32_e32 v2, s14, v0, vcc_lo"),), {}), (unsupported + "s_mov_b32 exec_lo, s8", (("s_mov_b32 s14, 0xbeef", "s_mov_b32 s14, 0xbeef\n" "s_mov_b32 exec_lo, s8"),), {}), (unsupported + "s_and_saveexec_b32 s20, s8", (("s_mov_b32 s14, 0xbeef", "s_mov_b32 s14, 0xbeef\n" @@ -141,7 +141,7 @@ def mask(*changes, width=32, lines=LANE_MASK, **binding): # Select sources that are not known words, and a destination past v255. ("Unverified ALU operand", (("v2, s14, v0, s10", "v2, s20, v0, s10"),), {}), ("Unverified ALU operand", (("v2, s14, v0, s10", "v2, s14, v7, s10"),), {}), - ("Unverified ALU operand", (("v1, v0, 0x600d, s8", "v256, v0, 0x600d, s8"),), {}), + ("Invalid vector destination", (("v1, v0, 0x600d, s8", "v256, v0, 0x600d, s8"),), {}), # A select result is data only: not a store address. ("Unsupported store address", (("v[1:4], v0, s[4:7]", "v[1:4], v1, s[4:7]"),), {}), # Groups whose lanes depend on the unknown wave size, or on more than local X. diff --git a/tests/compute_store_check.py b/tests/compute_store_check.py index de8efa5d3..d3279408d 100644 --- a/tests/compute_store_check.py +++ b/tests/compute_store_check.py @@ -378,6 +378,7 @@ def controls(): ff1_exec_controls() ff1_scalar_controls() writelane_controls() + vcmp_select_controls() def grid_controls(): @@ -2549,6 +2550,387 @@ def bfe_draw(directory, compiler, renderer, backend): return 0 +VCMP_SELECT_BINDING = dict(table_reg=8, descriptor_offset=0, source_descriptor=16, group_reg=10, stride=16) +VCMP_SELECT_INT_GROUPS = (("f", "lt", "eq", "le"), ("gt", "ne", "ge", "t")) +VCMP_SELECT_F32_GROUPS = ( + ("f", "lt", "eq", "le"), + ("gt", "lg", "ge", "o"), + ("u", "nge", "nlg", "ngt"), + ("nle", "neq", "nlt", "tru"), +) + + +def vcmp_select_program(typ, preds, *, float_set="a"): + """Build a 64-thread gfx1013 program testing 4 predicates of `typ` with e32/e64 compares and selects.""" + lines = [ + "s_mov_b32 s9, 0", + "s_load_dwordx8 s[12:19], s[8:9], null", + "v_lshl_add_u32 v3, s10, 6, v0", + "v_lshlrev_b32_e32 v1, 2, v3", + "s_waitcnt lgkmcnt(0)", + "buffer_load_dword v1, v1, s[16:19], 0 offen", + "s_mov_b32 s16, 0x10101010", + "s_mov_b32 s17, 0x40404040", + "v_add_nc_u32_e32 v17, 0x20202020, v3", + "v_add_nc_u32_e32 v18, 0x30303030, v3", + "s_waitcnt vmcnt(0)", + ] + if typ in ("u32", "i32"): + lines += [ + "v_mov_b32_e32 v4, v1", + "v_xor_b32_e32 v5, 0x80000000, v3", + "v_mov_b32_e32 v6, 0x7fffffff", + "v_mov_b32_e32 v7, 0x80000000", + "v_mov_b32_e32 v8, 0xffffffff", + "v_mov_b32_e32 v9, 0x80000001", + "v_cmp_eq_u32_e32 vcc_lo, 3, v3", + "v_cndmask_b32_e32 v4, v4, v6, vcc_lo", + "v_cndmask_b32_e32 v5, v5, v6, vcc_lo", + "v_cmp_eq_u32_e32 vcc_lo, 2, v3", + "v_mov_b32_e32 v14, 1", + "v_cndmask_b32_e32 v4, v4, v14, vcc_lo", + "v_cndmask_b32_e32 v5, v5, v9, vcc_lo", + "v_cmp_eq_u32_e32 vcc_lo, 1, v3", + "v_mov_b32_e32 v14, 0", + "v_cndmask_b32_e32 v4, v4, v14, vcc_lo", + "v_cndmask_b32_e32 v5, v5, v8, vcc_lo", + "v_cmp_eq_u32_e32 vcc_lo, 0, v3", + "v_cndmask_b32_e32 v4, v4, v6, vcc_lo", + "v_cndmask_b32_e32 v5, v5, v7, vcc_lo", + ] + elif float_set == "a": + lines += [ + "v_and_b32_e32 v4, 0x3fffff, v1", + "v_or_b32_e32 v4, 0x3fc00000, v4", + "v_mov_b32_e32 v5, 0x3fe00000", + "v_mov_b32_e32 v6, 0x3fc00000", + "v_mov_b32_e32 v7, 0x7fc00000", + "v_mov_b32_e32 v8, 0x80000000", + "v_cmp_eq_u32_e32 vcc_lo, 2, v3", + "v_cndmask_b32_e32 v4, v4, v6, vcc_lo", + "v_cndmask_b32_e32 v5, v5, v7, vcc_lo", + "v_cmp_eq_u32_e32 vcc_lo, 1, v3", + "v_cndmask_b32_e32 v4, v4, v7, vcc_lo", + "v_cndmask_b32_e32 v5, v5, v6, vcc_lo", + "v_cmp_eq_u32_e32 vcc_lo, 0, v3", + "v_mov_b32_e32 v14, 0", + "v_cndmask_b32_e32 v4, v4, v14, vcc_lo", + "v_cndmask_b32_e32 v5, v5, v8, vcc_lo", + ] + else: + lines += [ + "v_and_b32_e32 v4, 0x3fffff, v1", + "v_or_b32_e32 v4, 0x3fc00000, v4", + "v_mov_b32_e32 v5, 0x3fe00000", + "v_mov_b32_e32 v6, 0x3fc00000", + "v_mov_b32_e32 v7, 0x7fc00000", + "v_mov_b32_e32 v8, 0x7fc00001", + "v_mov_b32_e32 v9, 0x7f800000", + "v_mov_b32_e32 v14, 0xff800000", + "v_mov_b32_e32 v15, 0xbf400000", + "v_cmp_eq_u32_e32 vcc_lo, 3, v3", + "v_cndmask_b32_e32 v4, v4, v6, vcc_lo", + "v_cndmask_b32_e32 v5, v5, v6, vcc_lo", + "v_cmp_eq_u32_e32 vcc_lo, 2, v3", + "v_cndmask_b32_e32 v4, v4, v14, vcc_lo", + "v_cndmask_b32_e32 v5, v5, v15, vcc_lo", + "v_cmp_eq_u32_e32 vcc_lo, 1, v3", + "v_cndmask_b32_e32 v4, v4, v9, vcc_lo", + "v_cndmask_b32_e32 v5, v5, v14, vcc_lo", + "v_cmp_eq_u32_e32 vcc_lo, 0, v3", + "v_cndmask_b32_e32 v4, v4, v7, vcc_lo", + "v_cndmask_b32_e32 v5, v5, v8, vcc_lo", + ] + p0, p1, p2, p3 = preds + lines += [ + f"v_cmp_{p0}_{typ}_e32 vcc_lo, v4, v5", + "v_cndmask_b32_e32 v10, s16, v17, vcc_lo", + f"v_cmp_{p1}_{typ}_e64 s4, v4, v5", + "v_cndmask_b32_e64 v11, v18, s17, s4", + f"v_cmp_{p2}_{typ}_e64 vcc_lo, v4, v5", + "v_cndmask_b32_e64 v12, s16, v17, vcc_lo", + f"v_cmp_{p3}_{typ}_e32 vcc_lo, v4, v5", + "v_cndmask_b32_e32 v13, v18, v17, vcc_lo", + "buffer_store_dwordx4 v[10:13], v3, s[12:15], 0 idxen", + "s_endpgm", + ] + return lines + + +VCMP_SELECT_CASES = ( + [("u32", preds, "a") for preds in VCMP_SELECT_INT_GROUPS] + + [("i32", preds, "a") for preds in VCMP_SELECT_INT_GROUPS] + + [("f32", preds, fset) for fset in ("a", "b") for preds in VCMP_SELECT_F32_GROUPS] +) +VCMP_SELECT = vcmp_select_program("u32", ("f", "lt", "eq", "le")) + + +def _py_vcmp_pred(typ, pred, a, b): + a &= 0xffffffff + b &= 0xffffffff + if typ == "u32": + return { + "f": False, "lt": a < b, "eq": a == b, "le": a <= b, + "gt": a > b, "ne": a != b, "ge": a >= b, "t": True, + }[pred] + if typ == "i32": + sa = a - 0x100000000 if a & 0x80000000 else a + sb = b - 0x100000000 if b & 0x80000000 else b + return { + "f": False, "lt": sa < sb, "eq": sa == sb, "le": sa <= sb, + "gt": sa > sb, "ne": sa != sb, "ge": sa >= sb, "t": True, + }[pred] + fa = struct.unpack(" fb), + "lg": (not unord) and (fa != fb), + "ge": (not unord) and (fa >= fb), + "o": not unord, + "u": unord, + "nge": unord or (fa < fb), + "nlg": unord or (fa == fb), + "ngt": unord or (fa <= fb), + "nle": unord or (fa > fb), + "neq": unord or (fa != fb), + "nlt": unord or (fa >= fb), + "tru": True, + }[pred] + + +def vcmp_select_words(typ, preds, *, float_set="a", pred_fn=_py_vcmp_pred, swap_select=False): + """Independent Python model for 64 threads of vcmp_select_program.""" + words = [SENTINEL] * 320 + for flat in range(64): + inp = (0x8b02a7f1 + flat * 0x413b1) & 0xffffffff + if typ in ("u32", "i32"): + pairs = { + 0: (0x7fffffff, 0x80000000), + 1: (0x00000000, 0xffffffff), + 2: (0x00000001, 0x80000001), + 3: (0x7fffffff, 0x7fffffff), + } + a, b = pairs.get(flat, (inp, flat ^ 0x80000000)) + elif float_set == "a": + pairs = { + 0: (0x00000000, 0x80000000), + 1: (0x7fc00000, 0x3fc00000), + 2: (0x3fc00000, 0x7fc00000), + } + a, b = pairs.get(flat, ((inp & 0x3fffff) | 0x3fc00000, 0x3fe00000)) + else: + pairs = { + 0: (0x7fc00000, 0x7fc00001), + 1: (0x7f800000, 0xff800000), + 2: (0xff800000, 0xbf400000), + 3: (0x3fc00000, 0x3fc00000), + } + a, b = pairs.get(flat, ((inp & 0x3fffff) | 0x3fc00000, 0x3fe00000)) + s16 = 0x10101010 + s17 = 0x40404040 + v17 = (0x20202020 + flat) & 0xffffffff + v18 = (0x30303030 + flat) & 0xffffffff + slots = ((s16, v17), (v18, s17), (s16, v17), (v18, v17)) + for idx, (pred, (src0, src1)) in enumerate(zip(preds, slots)): + cond = pred_fn(typ, pred, a, b) + if swap_select: + cond = not cond + words[flat * 4 + idx] = src1 if cond else src0 + return words + + +def vcmp_select_controls(): + """Per-lane v_cmp_* and v_cndmask_b32_e32/e64: exact HLSL and one refusal per assumption.""" + base_int = [ + "s_mov_b32 s9, 0", + "s_load_dwordx8 s[12:19], s[8:9], null", + "v_lshl_add_u32 v3, s10, 6, v0", + "v_lshlrev_b32_e32 v1, 2, v3", + "s_waitcnt lgkmcnt(0)", + "buffer_load_dword v1, v1, s[16:19], 0 offen", + "s_mov_b32 s16, 0x10101010", + "v_add_nc_u32_e32 v17, 0x20202020, v3", + "s_waitcnt vmcnt(0)", + "v_cmp_lt_u32_e32 vcc_lo, v1, v3", + "v_cndmask_b32_e32 v10, s16, v17, vcc_lo", + "buffer_store_dword v10, v3, s[12:15], 0 idxen", + "s_endpgm", + ] + int_binding = dict(table_reg=8, descriptor_offset=0, source_descriptor=16, group_reg=10, stride=4) + lines = aot.lower(base_int, 64, **int_binding).splitlines() + assert lines[4] == ( + " outputData.Store(tid.x * 4u + 0u, ((inputData.Load((tid.x << 2u) + 0u) < tid.x) " + "? (0x20202020u + tid.x) : 0x10101010u));" + ), lines + i32_e64 = variant( + base_int, + ("v_cmp_lt_u32_e32 vcc_lo, v1, v3", "v_cmp_ge_i32_e64 s4, v1, v3"), + ("v_cndmask_b32_e32 v10, s16, v17, vcc_lo", "v_cndmask_b32_e64 v10, s16, v17, s4"), + ) + assert "((asint(inputData.Load((tid.x << 2u) + 0u)) >= asint(tid.x)) ?" in "\n".join( + aot.lower(i32_e64, 64, **int_binding).splitlines() + ) + f32_unord = variant( + base_int, + ("v_cmp_lt_u32_e32 vcc_lo, v1, v3", "v_cmp_nge_f32_e32 vcc_lo, v1, v3"), + ) + assert ("((isnan(asfloat(inputData.Load((tid.x << 2u) + 0u))) || isnan(asfloat(tid.x)) " + "|| (asfloat(inputData.Load((tid.x << 2u) + 0u)) < asfloat(tid.x))) ?") in aot.lower( + f32_unord, 64, **int_binding + ) + f32_ord_lg = variant( + base_int, + ("v_cmp_lt_u32_e32 vcc_lo, v1, v3", "v_cmp_lg_f32_e64 s4, 1.0, v1"), + ("v_cndmask_b32_e32 v10, s16, v17, vcc_lo", "v_cndmask_b32_e64 v10, s16, v17, s4"), + ) + assert ("((!isnan(asfloat(0x3f800000u)) && !isnan(asfloat(inputData.Load((tid.x << 2u) + 0u))) " + "&& (asfloat(0x3f800000u) != asfloat(inputData.Load((tid.x << 2u) + 0u)))) ?") in aot.lower( + f32_ord_lg, 64, **int_binding + ) + assert "(false ?" in aot.lower( + variant(base_int, ("v_cmp_lt_u32_e32 vcc_lo, v1, v3", "v_cmp_f_f32_e32 vcc_lo, v1, v3")), + 64, **int_binding, + ) + assert "(true ?" in aot.lower( + variant(base_int, ("v_cmp_lt_u32_e32 vcc_lo, v1, v3", "v_cmp_tru_f32_e64 s4, v1, v3"), + ("v_cndmask_b32_e32 v10, s16, v17, vcc_lo", "v_cndmask_b32_e64 v10, s16, v17, s4")), + 64, **int_binding, + ) + # 1. f32 source modifiers refused. + for mod in ("v_cmp_lt_f32_e64 s4, -v1, v3", "v_cmp_lt_f32_e64 s4, |v1|, v3"): + rejects("Unsupported compute instruction", aot.lower, + variant(base_int, ("v_cmp_lt_u32_e32 vcc_lo, v1, v3", mod)), 64, **int_binding) + # 2. clamp, SDWA, and DPP spellings refused. + for bad in ( + "v_cmp_lt_u32_e64 s4, v1, v3 clamp", + "v_cmp_lt_u32_sdwa vcc_lo, v1, v3 src0_sel:DWORD src1_sel:DWORD", + "v_cndmask_b32_sdwa v10, s16, v17, vcc_lo dst_sel:DWORD", + "v_cndmask_b32_dpp v10, v1, v17, vcc_lo quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf", + ): + rejects("Unsupported compute instruction", aot.lower, + variant(base_int, ("v_cmp_lt_u32_e32 vcc_lo, v1, v3", bad)), 64, **int_binding) + # 3. Cond SGPR read by scalar ALU or used as a branch condition. + rejects("Unverified scalar ALU operand", aot.lower, + variant(i32_e64, ("v_cndmask_b32_e64 v10, s16, v17, s4", + "s_add_u32 s5, s4, 1\nv_mov_b32_e32 v10, s5")), + 64, **int_binding) + rejects("Unsupported compute instruction", aot.lower, + variant(i32_e64, ("v_cndmask_b32_e64 v10, s16, v17, s4", "s_cbranch_scc0 .L0")), + 64, **int_binding) + # 4. s_and_saveexec on a cond built from loaded or ALU data. + rejects("Unverified lane guard compare", aot.lower, + variant(base_int, ("v_cndmask_b32_e32 v10, s16, v17, vcc_lo", + "s_and_saveexec_b32 s2, vcc_lo\nv_mov_b32_e32 v10, v3\n" + "s_or_b32 exec_lo, exec_lo, s2")), + 64, **int_binding) + rejects("Unverified lane guard compare", aot.lower, + variant(base_int, ("v_cmp_lt_u32_e32 vcc_lo, v1, v3", + "v_add_nc_u32_e32 v4, 1, v3\nv_cmp_lt_u32_e32 vcc_lo, v4, v3\n" + "s_and_saveexec_b32 s2, vcc_lo\nv_mov_b32_e32 v10, v3\n" + "s_or_b32 exec_lo, exec_lo, s2")), + 64, **int_binding) + # 5. _ci carry-in from a cond (vcc_lo or SGPR). + rejects("Unverified carry-in operand", aot.lower, + variant(base_int, ("v_cndmask_b32_e32 v10, s16, v17, vcc_lo", + "v_add_co_ci_u32_e32 v10, vcc_lo, 1, v3, vcc_lo")), + 64, **(int_binding | dict(wave_size=32))) + rejects("Unverified carry-in operand", aot.lower, + variant(i32_e64, ("v_cndmask_b32_e64 v10, s16, v17, s4", + "v_add_co_ci_u32_e64 v10, s5, 1, v3, s4")), + 64, **(int_binding | dict(wave_size=32))) + # 6. Stale cond after another VCC write. + rejects("Unverified lane mask", aot.lower, + variant(base_int, ("v_cmp_lt_u32_e32 vcc_lo, v1, v3", + "v_cmp_lt_u32_e32 vcc_lo, v1, v3\nv_add_co_u32 v11, vcc_lo, 1, v3")), + 64, **(int_binding | dict(wave_size=32))) + + +def vcmp_select_binary(directory, assembler, objcopy, library): + """All assembled VCMP_SELECT programs decode to their text and lower identically.""" + for typ, preds, float_set in VCMP_SELECT_CASES: + lines = vcmp_select_program(typ, preds, float_set=float_set) + decoded = aot.labelled(disassemble(assemble(directory, assembler, objcopy, lines), library, offsets=True)) + assert [line for line in decoded if line.startswith(("v_cmp_", "v_cndmask_"))] == [ + line for line in lines if line.startswith(("v_cmp_", "v_cndmask_"))], decoded + assert aot.lower(decoded, 64, **VCMP_SELECT_BINDING) == aot.lower(lines, 64, **VCMP_SELECT_BINDING) + + +def vcmp_select_draw(directory, compiler, renderer, backend): + opcodes = set() + case_sources = {} + for idx, (typ, preds, float_set) in enumerate(VCMP_SELECT_CASES): + lines = vcmp_select_program(typ, preds, float_set=float_set) + opcodes.update(line.split()[0] for line in lines if line.strip()) + src = directory / f"vcmp_{idx}.hlsl" + cso = directory / f"vcmp_{idx}.cso" + case = directory / f"vcmp_{idx}.case" + source = aot.lower(lines, 64, **VCMP_SELECT_BINDING) + case_sources[(typ, preds, float_set)] = (source, cso, case) + src.write_text(source, encoding="ascii") + subprocess.run([compiler, "-T", "cs_6_0", "-E", "main", "-Fo", cso, src], check=True) + expected = vcmp_select_words(typ, preds, float_set=float_set) + case.write_bytes(struct.pack("<321I", 1, *expected)) + result = subprocess.run([renderer, backend, "--compute-store-case", cso, case]) + if result.returncode: + return result.returncode + # Reference controls, each failing at a stated word. + u32_key = ("u32", ("f", "lt", "eq", "le"), "a") + u32_expected = vcmp_select_words("u32", ("f", "lt", "eq", "le")) + u32_cso, u32_case = case_sources[u32_key][1:] + off = list(u32_expected) + off[256] ^= 1 + f32_key = ("f32", ("u", "nge", "nlg", "ngt"), "a") + f32_expected = vcmp_select_words("f32", ("u", "nge", "nlg", "ngt"), float_set="a") + f32_cso, f32_case = case_sources[f32_key][1:] + swap_pred = lambda t, p, a, b: _py_vcmp_pred(t, {"lt": "gt", "gt": "lt"}.get(p, p), a, b) + signed_for_unsigned = lambda t, p, a, b: _py_vcmp_pred("i32" if t == "u32" else t, p, a, b) + ord_for_unord = lambda t, p, a, b: _py_vcmp_pred(t, {"nge": "lt"}.get(p, p), a, b) + for label, expected, cso, case, reference, word in ( + ("lt and gt swapped", u32_expected, u32_cso, u32_case, + vcmp_select_words("u32", ("f", "lt", "eq", "le"), pred_fn=swap_pred), 1), + ("signed used for unsigned", u32_expected, u32_cso, u32_case, + vcmp_select_words("u32", ("f", "lt", "eq", "le"), pred_fn=signed_for_unsigned), 1), + ("ordered used for unordered", f32_expected, f32_cso, f32_case, + vcmp_select_words("f32", ("u", "nge", "nlg", "ngt"), float_set="a", pred_fn=ord_for_unord), 5), + ("select operands swapped", u32_expected, u32_cso, u32_case, + vcmp_select_words("u32", ("f", "lt", "eq", "le"), swap_select=True), 0), + ("sentinel past group", u32_expected, u32_cso, u32_case, off, 256)): + assert next(i for i, (a, b) in enumerate(zip(expected, reference)) if a != b) == word, label + case.write_bytes(struct.pack("<321I", 1, *reference)) + bad = subprocess.run([renderer, backend, "--compute-store-case", cso, case], capture_output=True, text=True) + if bad.returncode != 1 or f"word={word} expected=" not in bad.stderr: + raise AssertionError(f"vcmp_select: reference '{label}' escaped detection\n{bad.stderr}") + u32_case.write_bytes(struct.pack("<321I", 1, *u32_expected)) + f32_case.write_bytes(struct.pack("<321I", 1, *f32_expected)) + # Recompiled-HLSL mutations that must mismatch on the device. + i32_key = ("i32", ("f", "lt", "eq", "le"), "a") + i32_source, _, i32_case = case_sources[i32_key] + i32_case.write_bytes(struct.pack("<321I", 1, *vcmp_select_words("i32", ("f", "lt", "eq", "le")))) + u32_source = case_sources[u32_key][0] + f32_source = case_sources[f32_key][0] + for label, mutated, case in ( + ("< for <=", u32_source.replace(" <= ", " < "), u32_case), + ("asint dropped", i32_source.replace("asint(", "("), i32_case), + ("isnan dropped from unordered", f32_source.replace("isnan(", "isinf("), f32_case)): + assert mutated not in (u32_source, i32_source, f32_source), label + msrc, mcso = directory / "mutated.hlsl", directory / "mutated.cso" + msrc.write_text(mutated, encoding="ascii") + subprocess.run([compiler, "-T", "cs_6_0", "-E", "main", "-Fo", mcso, msrc], check=True) + bad = subprocess.run([renderer, backend, "--compute-store-case", mcso, case], capture_output=True, text=True) + if bad.returncode != 1 or "Compute readback differs" not in bad.stderr: + raise AssertionError(f"vcmp_select: mutation '{label}' escaped detection\n{bad.stderr}") + if record := os.environ.get("FORM_COVERAGE_RECORD"): + path = Path(record) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("".join(f"{op}\n" for op in sorted(opcodes)), encoding="utf-8") + return 0 + + def scalar_alu_controls(): """Scalar ALU on known words: exact output, then one rejection per operand or opcode outside the subset.""" def scalar(*changes): @@ -5556,6 +5938,7 @@ def binary(directory, assembler, objcopy, library): ff1_exec_binary(directory, assembler, objcopy, library) ff1_scalar_binary(directory, assembler, objcopy, library) writelane_binary(directory, assembler, objcopy, library) + vcmp_select_binary(directory, assembler, objcopy, library) mubuf_subword_store_controls() gfx1030_binary(directory, assembler, objcopy, library, mubuf_subword_store_cases(), "buffer_store_") ds_controls() @@ -8881,6 +9264,7 @@ def descriptor_store_draw(directory, compiler, renderer, backend): "draw-ff1-exec": ff1_exec_draw, "draw-ff1-scalar": ff1_scalar_draw, "draw-writelane": writelane_draw, + "draw-vcmp-select": vcmp_select_draw, "draw-mtbuf-store": mtbuf_store_draw, "draw-mubuf-subword-store": mubuf_subword_store_draw, "draw-guard-read": lambda d, *a: draw(d, *a, cases=GUARD_CASES + READ_CASES + ALU_CASES + SCALAR_CASES), diff --git a/tools/compute_store_aot.py b/tools/compute_store_aot.py index 29e344ec7..d21389afd 100644 --- a/tools/compute_store_aot.py +++ b/tools/compute_store_aot.py @@ -14,6 +14,34 @@ AXES = "xyz" # Integer compares a lane guard may use. Inequality is the same for signed and unsigned words. GUARD_COMPARES = {"gt": ">", "lt": "<", "ge": ">=", "le": "<=", "ne": "!="} +INT_COMPARE_PREDICATES = { + "f": lambda a, b: "false", + "lt": lambda a, b: f"({a} < {b})", + "eq": lambda a, b: f"({a} == {b})", + "le": lambda a, b: f"({a} <= {b})", + "gt": lambda a, b: f"({a} > {b})", + "ne": lambda a, b: f"({a} != {b})", + "ge": lambda a, b: f"({a} >= {b})", + "t": lambda a, b: "true", +} +FLOAT_COMPARE_PREDICATES = { + "f": lambda a, b: "false", + "lt": lambda a, b: f"(!isnan({a}) && !isnan({b}) && ({a} < {b}))", + "eq": lambda a, b: f"(!isnan({a}) && !isnan({b}) && ({a} == {b}))", + "le": lambda a, b: f"(!isnan({a}) && !isnan({b}) && ({a} <= {b}))", + "gt": lambda a, b: f"(!isnan({a}) && !isnan({b}) && ({a} > {b}))", + "lg": lambda a, b: f"(!isnan({a}) && !isnan({b}) && ({a} != {b}))", + "ge": lambda a, b: f"(!isnan({a}) && !isnan({b}) && ({a} >= {b}))", + "o": lambda a, b: f"(!isnan({a}) && !isnan({b}))", + "u": lambda a, b: f"(isnan({a}) || isnan({b}))", + "nge": lambda a, b: f"(isnan({a}) || isnan({b}) || ({a} < {b}))", + "nlg": lambda a, b: f"(isnan({a}) || isnan({b}) || ({a} == {b}))", + "ngt": lambda a, b: f"(isnan({a}) || isnan({b}) || ({a} <= {b}))", + "nle": lambda a, b: f"(isnan({a}) || isnan({b}) || ({a} > {b}))", + "neq": lambda a, b: f"(isnan({a}) || isnan({b}) || ({a} != {b}))", + "nlt": lambda a, b: f"(isnan({a}) || isnan({b}) || ({a} >= {b}))", + "tru": lambda a, b: "true", +} # The data ALU subset: the unsigned 32-bit operations the LLVM 15 code generator emits for the # read-compute-write fixture, on known words only. v_and_b32, v_or_b32, v_xor_b32 and v_lshrrev_b32 (src1 >> src0[4:0]) # reuse the pixel profile's integer templates, as does v_mul_lo_u32. v_lshlrev_b32 and v_ashrrev_i32 shift src1 @@ -782,6 +810,7 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N # where the guarded stores end. The guarded stores become an HLSL if. vcc = guard = None vcc_carry = None + vcc_cond = None guard_span = None if not instructions or instructions[-1] != "s_endpgm": raise ValueError("Missing final program exit") @@ -829,23 +858,70 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N elif image_output and stores and line == "s_waitcnt_vscnt null, 0x0": # The single image write becomes visible when the dispatch completes. continue - elif ((m := re.fullmatch(rf"v_cmp_(gt|lt|ge|le)_u32_e32 vcc_lo, {ALU_SOURCE}, (v\d+)", line)) - or (m := re.fullmatch(rf"v_cmp_(ne)_i32_e32 vcc_lo, {ALU_SOURCE}, (v\d+)", line)) - or (m := re.fullmatch(rf"v_cmp_(ne)_i32_e64 vcc_lo, {ALU_SOURCE}, {ALU_SOURCE}", line))): - op, src0, src1 = m.groups() + elif ((m := re.fullmatch(rf"v_cmp_(f|lt|eq|le|gt|ne|ge|t)_(u32|i32)_(e32) (vcc_lo), {ALU_SOURCE}, (v\d+)", line)) + or (m := re.fullmatch(rf"v_cmp_(f|lt|eq|le|gt|ne|ge|t)_(u32|i32)_(e64) (vcc_lo|s\d+), {ALU_SOURCE}, {ALU_SOURCE}", line))): + # RDNA2 ISA: VOPC sets SDST[lane] = pred(S0, S1) for each active lane. + pred, typ, enc, sdst, src0, src1 = m.groups() operands = (src0, src1) + if sdst != "vcc_lo": + sdst_reg = int(sdst[1:]) + if sdst_reg > 105 or sdst_reg in pending: + raise ValueError("Unverified compare destination") words = [alu_word(token, scalar, vector, pending) for token in operands] - # A word read or computed in the program is not a verified guard operand. - if (any(token.startswith("v") and int(token[1:]) > 255 for token in operands) - or any(word is None or isinstance(word, tuple) and word[0] in ("source", "alu") for word in words)): + if any(token.startswith("v") and int(token[1:]) > 255 for token in operands) or None in words: + raise ValueError("Unverified lane guard compare") + a, b = map(hlsl_word, words) + if typ == "i32": + a, b = f"asint({a})", f"asint({b})" + cond_expr = INT_COMPARE_PREDICATES[pred](a, b) + if len(cond_expr) > ALU_EXPRESSION_LIMIT: + raise ValueError("ALU expression too large") + guard_ok = ( + sdst == "vcc_lo" + and ((typ == "u32" and enc == "e32" and pred in ("gt", "lt", "ge", "le")) + or (typ == "i32" and pred == "ne")) + and not any(isinstance(word, tuple) and word[0] in ("source", "alu") for word in words) + ) + if guard is not None and not guard_ok: raise ValueError("Unverified lane guard compare") - vcc = (op, *words) - vcc_carry = None + if sdst == "vcc_lo": + vcc = (pred, *words) if guard_ok else ("invalid",) + vcc_cond = ("cond", cond_expr) + vcc_carry = None + else: + scalar[sdst_reg] = ("cond", cond_expr) + elif ((m := re.fullmatch(rf"v_cmp_(f|lt|eq|le|gt|lg|ge|o|u|nge|nlg|ngt|nle|neq|nlt|tru)_f32_(e32) (vcc_lo), {FLOAT_SOURCE}, (v\d+)", line)) + or (m := re.fullmatch(rf"v_cmp_(f|lt|eq|le|gt|lg|ge|o|u|nge|nlg|ngt|nle|neq|nlt|tru)_f32_(e64) (vcc_lo|s\d+), {FLOAT_SOURCE}, {FLOAT_SOURCE}", line))): + # RDNA2 ISA: VOPC f32 compare sets SDST[lane] = pred(S0, S1) with IEEE unordered NaN rules. + pred, enc, sdst, src0, src1 = m.groups() + operands = (src0, src1) + if guard is not None: + raise ValueError("Unverified lane guard compare") + if sdst != "vcc_lo": + sdst_reg = int(sdst[1:]) + if sdst_reg > 105 or sdst_reg in pending: + raise ValueError("Unverified compare destination") + words = [FLOAT_INLINE.get(token) if "." in token else alu_word(token, scalar, vector, pending) + for token in operands] + if any(token.startswith("v") and int(token[1:]) > 255 for token in operands) or None in words: + raise ValueError("Unverified float operand") + fa, fb = (f"asfloat({hlsl_word(w)})" for w in words) + cond_expr = FLOAT_COMPARE_PREDICATES[pred](fa, fb) + if len(cond_expr) > ALU_EXPRESSION_LIMIT: + raise ValueError("ALU expression too large") + if sdst == "vcc_lo": + vcc = ("invalid",) + vcc_cond = ("cond", cond_expr) + vcc_carry = None + else: + scalar[sdst_reg] = ("cond", cond_expr) elif m := re.fullmatch(r"s_and_saveexec_b32 s(\d+), vcc_lo", line): saved = int(m[1]) + if vcc == ("invalid",) and guard_span is None and saved <= 105 and saved not in pending: + raise ValueError("Unverified lane guard compare") if guard_span is not None or vcc is None or saved > 105 or saved in pending: raise ValueError("Unverified or repeated lane guard") - guard = dict(label=None, at_label=False, holders=None, vcc_carry=vcc_carry, + guard = dict(label=None, at_label=False, holders=None, vcc_carry=vcc_carry, vcc_cond=vcc_cond, scalar=dict(scalar), vector=dict(vector), pending=set(pending), loading=dict(loading)) scalar[saved] = ("exec",) guard_span = [len(stores), None, vcc] @@ -878,6 +954,8 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N pending |= guard["pending"] if vcc_carry != guard["vcc_carry"]: vcc_carry = None + if vcc_cond != guard["vcc_cond"]: + vcc_cond = None guard = None guard_span[1] = len(stores) elif line in ("s_mov_b32 m0, 0", "s_mov_b32 m0, 0x0"): @@ -996,22 +1074,32 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N raise ValueError("Unverified lane mask source") pair = sum(((int(src, 0) >> (bit // 2)) & 1) << bit for bit in range(64)) scalar[dst], scalar[high] = pair & 0xffffffff, pair >> 32 - elif m := re.fullmatch(rf"v_cndmask_b32_e64 v(\d+), {ALU_SOURCE}, {ALU_SOURCE}, s(\d+)", line): - # D = mask[lane] ? src1 : src0, with the wave32 mask in one SGPR that holds a statically known word. - # In a one-dimensional group of at most 32 threads the group is one wave at either wave size and the - # lane is local X. Past lane 31 the same encoding reads the high mask word in wave64, which the - # translator cannot tell from the code, so larger and multi-dimensional groups are refused. - dst, reg = int(m[1]), int(m[4]) - if dims[1:] != (1, 1) or dims[0] > 32: - raise ValueError("Lane mask select requires a one-dimensional group of at most 32 threads") - mask = scalar.get(reg) if reg <= 105 and reg not in pending else None - if not isinstance(mask, int): - raise ValueError("Unverified lane mask") - words = [alu_word(token, scalar, vector, pending) for token in (m[2], m[3])] - if dst > 255 or None in words: + elif ((m := re.fullmatch(rf"v_cndmask_b32_e32 v(\d+), {ALU_SOURCE}, (v\d+), (vcc_lo)", line)) + or (m := re.fullmatch(rf"v_cndmask_b32_e64 v(\d+), {ALU_SOURCE}, {ALU_SOURCE}, (vcc_lo|s\d+)", line))): + # D = mask[lane] ? src1 : src0, either from a per-lane ("cond", ...) or from a statically known + # wave32 constant mask in an SGPR. For a constant mask, a one-dimensional group of at most 32 + # threads is one wave at either wave size and the lane is local X; past lane 31 the same encoding + # reads the high mask word in wave64, which the translator cannot tell from the code. + dst, src0, src1, mask_tok = int(m[1]), m[2], m[3], m[4] + if dst > 255: + raise ValueError("Invalid vector destination") + words = [alu_word(token, scalar, vector, pending) for token in (src0, src1)] + if None in words: raise ValueError("Unverified ALU operand") - expression = (f"(((0x{mask:08x}u >> (tid.x % {dims[0]}u)) & 1u) != 0u ? {hlsl_word(words[1])}" - f" : {hlsl_word(words[0])})") + if mask_tok == "vcc_lo": + mask = vcc_cond + else: + reg = int(mask_tok[1:]) + mask = scalar.get(reg) if reg <= 105 and reg not in pending else None + if isinstance(mask, tuple) and mask[0] == "cond": + expression = f"({mask[1]} ? {hlsl_word(words[1])} : {hlsl_word(words[0])})" + elif isinstance(mask, int): + if dims[1:] != (1, 1) or dims[0] > 32: + raise ValueError("Lane mask select requires a one-dimensional group of at most 32 threads") + expression = (f"(((0x{mask:08x}u >> (tid.x % {dims[0]}u)) & 1u) != 0u ? {hlsl_word(words[1])}" + f" : {hlsl_word(words[0])})") + else: + raise ValueError("Unverified lane mask") if len(expression) > ALU_EXPRESSION_LIMIT: raise ValueError("ALU expression too large") vector[dst] = ("alu", expression) @@ -1862,6 +1950,7 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N vector[dst] = ("alu", expression) if sdst == "vcc_lo": vcc = None + vcc_cond = None vcc_carry = ("borrow", borrow_expression) else: scalar[sdst_reg] = ("borrow", borrow_expression) @@ -1905,6 +1994,7 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N vector[dst] = ("alu", expression) if sdst == "vcc_lo": vcc = None + vcc_cond = None vcc_carry = ("carry", carry_expression) else: scalar[sdst_reg] = ("carry", carry_expression)