diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 763c15bff..d0a62fdf7 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -312,7 +312,8 @@ jobs: tests/startup_build_rev_check.py \ tests/startup_gfx2hlsl_bit_alu_check.py \ tests/startup_gfx2hlsl_int_alu_check.py \ - tests/startup_gfx2hlsl_interp_f16_check.py tests/startup_gfx2hlsl_interp_p2_hi_check.py \ + tests/startup_gfx2hlsl_interp_f16_check.py \ + tests/startup_gfx2hlsl_interp_p2_hi_check.py \ tests/startup_gfx2hlsl_sgpr_spill_check.py \ tests/startup_gfx2hlsl_spill_branches_check.py \ tests/startup_gfx2hlsl_mad_check.py \ @@ -329,6 +330,7 @@ jobs: tests/startup_gfx2hlsl_s_quadmask_check.py \ tests/startup_gfx2hlsl_fma_mix_check.py \ tests/startup_gfx2hlsl_shift64_check.py \ + tests/startup_gfx2hlsl_cmp_class_f16_sdwa_check.py \ tests/startup_gfx2hlsl_mul_hi_i32_check.py \ tests/startup_gfx2hlsl_mul_mad_i24_check.py \ tests/startup_gfx2hlsl_vopc_sdwa_check.py \ diff --git a/AGENTS.md b/AGENTS.md index f16119659..da2f754f4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -256,6 +256,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_spill_branches_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_shift64_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_vopc_sdwa_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_cmp_class_f16_sdwa_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_cmp16_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_f32_lg_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_f32_nan_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 51b074e68..aa2a0ffdd 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3432,6 +3432,9 @@ if(EXISTS "${INTAKE_PYTHON}") # The binary16 class comparison (#1855). add_test(NAME startup_gfx2hlsl_cmp_class_f16 COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_cmp_class_f16_check.py") + # The SDWA forms of the binary16 class comparison and their negative controls; the draws are registered below. + add_test(NAME startup_gfx2hlsl_cmp_class_f16_sdwa COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_cmp_class_f16_sdwa_check.py") # The 16-bit vector ALU: add, sub, mul, min, max, fma forms and the i16/u16 conversions (#1723). add_test(NAME startup_gfx2hlsl_f16_alu COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_f16_alu_check.py") @@ -3973,6 +3976,10 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_vopc_sdwa_check.py" draw "${DXC_EXECUTABLE}" "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_gfx2hlsl_vopc_sdwa_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + add_test(NAME startup_gfx2hlsl_cmp_class_f16_sdwa_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_cmp_class_f16_sdwa_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_cmp_class_f16_sdwa_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) add_test(NAME startup_gfx2hlsl_dpp_quad_broadcast_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_dpp_quad_broadcast_check.py" draw "${DXC_EXECUTABLE}" "$" ${adapter} $<$:${STARTUP_FXC}>) diff --git a/tests/startup_gfx2hlsl_cmp_class_f16_sdwa_check.py b/tests/startup_gfx2hlsl_cmp_class_f16_sdwa_check.py new file mode 100644 index 000000000..a800179f3 --- /dev/null +++ b/tests/startup_gfx2hlsl_cmp_class_f16_sdwa_check.py @@ -0,0 +1,448 @@ +"""The SDWA forms of `v_cmp_class_f16` / `v_cmpx_class_f16` in tools/startup/gfx2hlsl.py. + + (no arguments) translation controls and value checks, pure Python + draw [fxc] + compile source-built pixel programs with FXC ps_5_1 when given and with DXC + ps_6_0, draw 16 x 16 pixels and compare every pixel with a CPU reference + +The plain e32/e64 register and encoded-literal path (including the census form `0x7c01`) is covered by +startup_gfx2hlsl_cmp_class_f16_check.py. This file covers what that one does not: + + * SDWA: `src0_sel` DWORD and WORD_0 are lowered to the shared class16() helper on the register word (which reads + bits [15:0] only); `src1_sel` selects and sign-extends the integer mask as for the binary32 class compare. WORD_1, + each byte, sext() on src0, the abs/neg spellings, a missing select, a float mask and a bad destination are refused. + Words are built with the VOP_SDWA9Be layout tools/disasm_rdna2.py reads, and two of them are compared with the + bytes clang -cc1as (LLVM 15, gfx1013) emits for the same text. + * Value level: the emitted predicate is evaluated over boundary patterns of every class with garbage in the upper + half and against an independent reference written from the binary16 layout (struct 'e'). Three mutated helpers + (upper half read, sNaN and qNaN swapped, +0 and -0 swapped) must disagree with that reference. + * Draw: a register holding 0x7c01 in its low half (sNaN, class bit 0x1), a register with the same low half and a + qNaN (0x7e00, class bit 0x2) in the upper half, the encoded literal 0x7c01, the e32 spelling and both SDWA + selects all give the same class: the 16 x 16 pixels keep or discard by the class bit against a per-pixel mask, + and every variant must match one reference image. Two controls must fail it: classifying the upper half instead + of the low one (the independent high-half control) and swapping the sNaN/qNaN return values. A third reads the + whole mask dword instead of the BYTE_1 select. + +Encoded NEG and inline float constants are not lowered through the SDWA path and stay refused on the plain path +(tests/startup_gfx2hlsl_cmp_class_f16_check.py). +""" +import math +import re +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import Expr # noqa: E402 +from startup_gfx2hlsl_vopc_sdwa_check import ( # noqa: E402 + CLEAR, EXPORT_WORDS, HEIGHT, MASK, MUL_WORDS, MULTIPLIER, PACKED, WIDTH, draw, field, source, vopc_sdwa, + words_file) +from startup_image_3d_check import FULLSCREEN_VS, VS_WORDS, compile_hlsl, root_blob # noqa: E402 + +failures = [] + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH'}") + if not condition: + failures.append(label) + if detail: + print(' ' + detail) + + +CMP_CLASS_F16, CMPX_CLASS_F16 = 0x8F, 0x9F # VOPC e32 opcodes +SGPR_DST = 6 +V1, V2 = 0x101, 0x102 + + +class Probe(G.Stage): + """A Stage with no pipeline: enough state for decoded instructions to be translated.""" + + def __init__(self, exec_known=True): + self.lines, self.sym = [], {} + self.used_s, self.used_v, self.uniform_v = set(), set(), set() + self.masks = set() + self.exec_known = exec_known + + +def translate(code, exec_known=True): + decoded = G.decode(code) + assert len(decoded) == 1 and decoded[0][1] == 8, decoded + stage = Probe(exec_known) + stage.one(decoded[0][2], decoded[0][3]) + return decoded[0][3], stage + + +def refusal_of(name, asm): + try: + stage = Probe() + stage.one(name, asm) + except G.Unsupported as error: + return str(error) + return None + + +# ---- the independent reference and the helper under test ------------------------------------------------------- +def ref_class16(word): + """The class bit of S0[15:0] from the binary16 layout read through struct 'e'; the upper half is ignored.""" + low = word & 0xFFFF + value = struct.unpack(' 0) + _asm, stage = translate(vopc_sdwa(CMP_CLASS_F16, source('v', 2), source('v', 1), None, 'WORD_0', 'DWORD')) + for name in HELPER_MUTATIONS: + bad = [(hex(word), hex(upper)) for word, _bit in BOUNDARIES for upper in UPPERS + if predicate(stage, (upper << 16) | word, ref_class16(word), helper=mutated(name)) != 1] + check('control %s fails the emitted predicate on a boundary pattern' % name, bool(bad)) + + +# ---- the draw ------------------------------------------------------------------------------------------------- +LOW = 0x7C01 # a signaling NaN: class bit 0x1 +UPPER_QNAN = 0x7E00 # a quiet NaN in the upper half: class bit 0x2, what a translation reading bits [31:16] sees + + +def v_mov_literal(vdst, literal): + return struct.pack('> 16u)'), + 'sNaN and qNaN swapped': ('(h & 0x0200u) != 0u ? 0x2u : 0x1u', '(h & 0x0200u) != 0u ? 0x1u : 0x2u'), +} + + +def pixel_words(name): + return MUL_WORDS + VARIANTS[name][1] + EXPORT_WORDS + + +def pixel_hlsl(name, control=None): + text = G.Pipeline(VS_WORDS, pixel_words(name), root_blob(), ps_hw_inputs=PACKED).hlsl_ps() + if control: + old, new = CONTROLS[control] + if old == 'class16(v2)' and name.startswith('encoded literal'): + old, new = 'class16(0x00007c01u)', 'class16(0x00007c01u >> 16u)' + assert text.count(old) == 1, (name, control, old) + text = text.replace(old, new) + return text + + +def image(select, class_bit): + words = [] + for y in range(HEIGHT): + for x in range(WIDTH): + position = x | (y << 16) + mask = (position * MULTIPLIER) & MASK + if select: + mask = field(mask, select, False) + words += [position if mask & class_bit else CLEAR] * 4 + return words + + +def check_fixture(): + for name, (text, _words, select) in VARIANTS.items(): + decoded = [asm for _o, _s, _n, asm in G.decode(pixel_words(name))] + wanted = (PS_HEAD + text + '\nexp mrt0 v0, v0, v0, v0 done vm\ns_endpgm').splitlines() + wanted = [line.replace('v_mov_b32_e32', 'v_mov_b32_e32') for line in wanted] + check('%s: fixture decodes to its source' % name, decoded == wanted, '%s\n%s' % (decoded, wanted)) + hlsl = pixel_hlsl(name) + check('%s: lowered through class16 behind exec' % name, + 'class16(' in hlsl and 'if (!(exec & 1)) discard;' in hlsl, hlsl) + reference = image(select, 0x1) + kept = sum(reference[i] != CLEAR for i in range(0, len(reference), 4)) + check('%s: reference keeps %d of %d pixels' % (name, kept, WIDTH * HEIGHT), 0 < kept < WIDTH * HEIGHT) + # The controls must be distinguishable by the image, or the draw could not tell them apart. + check('classifying the upper half (class bit 0x2) changes the image', image(None, 0x1) != image(None, 0x2)) + check('swapping sNaN and qNaN changes the image', image(None, 0x1) != image(None, 0x2)) + check('ignoring the BYTE_1 select changes the image', image('BYTE_1', 0x1) != image(None, 0x1)) + for name in VARIANTS: + for control in CONTROLS: + pixel_hlsl(name, control) # every control applies to exactly one place in every variant + + +def check_draw(dxc, renderer, adapter, fxc=None): + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + plain = words_file(directory, 'plain', image(None, 0x1)) + selected = words_file(directory, 'selected', image('BYTE_1', 0x1)) + upper = words_file(directory, 'upper', image(None, 0x2)) + for kind, compiler, vs_profile, ps_profile in compilers: + vs = compile_hlsl(compiler, kind, FULLSCREEN_VS, 'vs_%s' % kind, vs_profile, directory) + for index, (name, (_text, _words, select)) in enumerate(VARIANTS.items()): + ps = compile_hlsl(compiler, kind, pixel_hlsl(name), 'ps_%d_%s' % (index, kind), ps_profile, directory) + run = draw(renderer, adapter, vs, ps, selected if select else plain) + check('%s %s: %s matches all %d pixels' % (kind, adapter, name, WIDTH * HEIGHT), + run.returncode == 0 and 'all %d pixels matched' % (WIDTH * HEIGHT) in run.stdout, + run.stdout + run.stderr) + for control in CONTROLS: + name = 'register, upper qNaN, WORD_0 / DWORD' + bad = compile_hlsl(compiler, kind, pixel_hlsl(name, control), 'ps_bad_%s_%s' % (control[:5], kind), + ps_profile, directory) + run = draw(renderer, adapter, vs, bad, plain) + check('%s %s: control %s fails the draw' % (kind, adapter, control), + run.returncode != 0 and 'pixel mismatch' in run.stderr, run.stdout + run.stderr) + # A translation that classified the upper half draws the image of the upper class bit. + bad = compile_hlsl(compiler, kind, pixel_hlsl('register, upper qNaN, WORD_0 / DWORD', + 'upper half classified'), 'ps_up_%s' % kind, ps_profile, + directory) + run = draw(renderer, adapter, vs, bad, upper) + check('%s %s: upper-half control matches the upper-class image' % (kind, adapter), + run.returncode == 0, run.stdout + run.stderr) + # The select control: the same program with the mask read as a whole dword draws the plain image. + name = 'register, upper qNaN, WORD_0 / BYTE_1' + text = pixel_hlsl(name) + assert text.count('((v1 >> 8u) & 0xffu)') == 1, text + bad = compile_hlsl(compiler, kind, text.replace('((v1 >> 8u) & 0xffu)', 'v1'), 'ps_sel_%s' % kind, + ps_profile, directory) + run = draw(renderer, adapter, vs, bad, selected) + check('%s %s: mask select control fails the draw' % (kind, adapter), + run.returncode != 0 and 'pixel mismatch' in run.stderr, run.stdout + run.stderr) + run = draw(renderer, adapter, vs, bad, plain) + check('%s %s: mask select control matches the whole-dword image' % (kind, adapter), + run.returncode == 0, run.stdout + run.stderr) + + +def main(): + if len(sys.argv) == 1: + controls() + check_fixture() + elif sys.argv[1] == 'draw': + check_fixture() + check_draw(*sys.argv[2:]) + else: + raise SystemExit(__doc__) + if failures: + print('FAIL') + for text in failures: + print(' ' + text) + sys.exit(1) + print('PASS') + + +if __name__ == '__main__': + main() diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index c4fdb7d95..fc6fb48a7 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -7233,8 +7233,6 @@ def compare(self, base, ops, mods=()): f16 = name.endswith('_f16') writes_exec = name in ('v_cmpx_class_f32', 'v_cmpx_class_f16') sdwa = name != base - if f16 and sdwa: - raise Unsupported('SDWA form of %s' % name) if sdwa: self.check_compare_sdwa_destination(base, writes_exec, ops) if len(ops) == 3: @@ -7244,7 +7242,20 @@ def compare(self, base, ops, mods=()): dst, (value, mask) = 'exec', ops else: raise Unsupported('%s with %d operands' % (base, len(ops))) - if sdwa: + if sdwa and f16: + # SDWA half class: classes bits [15:0] of a plain register. src0_sel DWORD and WORD_0 both + # leave those bits where class16 reads them; WORD_1, a byte, sext() and the abs/neg spellings + # (which print |v|, -v, abs(), neg()) would classify other bits, so they are refused. + selections = [m for m in mods if m.startswith('src0_sel:')] + if selections not in (['src0_sel:DWORD'], ['src0_sel:WORD_0']): + raise Unsupported('SDWA form of %s with %s' % (name, ' '.join(selections) or 'no src0_sel')) + if not reg_range(value): + raise Unsupported('%s with source %s' % (base, value)) + if mask in FLOATS: + raise Unsupported('%s mask %s: expected an integer class mask' % (base, mask)) + _word, mask = self.compare_sdwa_sources(base, 'u32', [value, mask], mods) + value = self.u(value) + elif sdwa: value, mask = self.compare_sdwa_sources(base, 'u32', [value, mask], mods, float_src0=True) elif f16: # abs() and - apply to bit 15 of the half, before the class test.