diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index eec590bdfc..71eb719051 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -102,6 +102,7 @@ jobs: (["tests/startup_compute_gather_l_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_compute_buffer_atomics_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_compute_store_d16_x_check.py", "binary", "llvm-mc-15"], {}), + (["tests/startup_compute_store_format_xyzw_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_image_gather_c_lz_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_image_sample_c_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_image_3d_check.py", "binary", "llvm-mc-15"], {}), @@ -228,6 +229,7 @@ jobs: tests/startup_compute_gather_l_check.py \ tests/startup_compute_buffer_atomics_check.py \ tests/startup_compute_store_d16_x_check.py \ + tests/startup_compute_store_format_xyzw_check.py \ tests/startup_image_gather_c_lz_check.py \ tests/startup_image_sample_c_check.py \ tests/startup_image_3d_check.py \ diff --git a/AGENTS.md b/AGENTS.md index f17a5c5dc8..89516ec2ac 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -170,6 +170,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_compute_check.py ./out/pe-env/bin/python -B tests/startup_compute_image_store_check.py ./out/pe-env/bin/python -B tests/startup_compute_image_store_d16_check.py +./out/pe-env/bin/python -B tests/startup_compute_store_format_xyzw_check.py ./out/pe-env/bin/python -B tests/startup_compute_translate_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_swap_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_fma_mix_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index e86361468b..e8a0cb01ff 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3706,6 +3706,22 @@ if(EXISTS "${INTAKE_PYTHON}") PASS_REGULAR_EXPRESSION "control ${control}: rejected at word=[0-9]+ ") endforeach() endforeach() + # gfx2hlsl compute buffer_store_format_xyzw: 4-channel formats, bounds/OOB, channel-count no-op and EXEC guard (Refs #2274). + add_test(NAME startup_compute_store_format_xyzw_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_compute_store_format_xyzw_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_compute_store_format_xyzw_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_compute_store_format_xyzw_check.py" dispatch "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_compute_store_format_xyzw_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + foreach(control IN ITEMS x-drop-store x-swap-xy x-drop-index-oob unorm8-trunc unorm10-w-scale f16-drop-odd mismatch-writes r-drop-soffset e-drop-exec) + add_test(NAME startup_compute_store_format_xyzw_${control}_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_compute_store_format_xyzw_check.py" control ${control} "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_compute_store_format_xyzw_${control}_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77 + PASS_REGULAR_EXPRESSION "control ${control}: rejected at word=[0-9]+ ") + endforeach() + endforeach() # gfx2hlsl compute stage: entry registers, numthreads and the offen buffer store, dispatched on a plain device (#1412). add_test(NAME startup_gfx2hlsl_compute_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_compute_check.py") diff --git a/docs/experiments.md b/docs/experiments.md index f98cf844a4..76f1e4c96e 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -14866,6 +14866,22 @@ python -B tests/startup_compute_store_d16_x_check.py binary llvm-mc-15 Not covered here: `llvm-mc-15` assembly step on Linux CI (`binary`), `OOB_SELECT=3` with nonzero stride, multi-channel `buffer_store_format_d16_{xy,xyz,xyzw}`, `buffer_store_format_d16_hi_x`, and live runtime slot-67 dispatch binding of `uav_descword3`/`uav_stride`/`uav_numrecords`. +### Startup compute formatted four-component buffer stores + +[The startup translator](../tools/startup/gfx2hlsl.py) (`op_buffer_store_format_xyzw`, refs `#2274`) lowers compute MUBUF `buffer_store_format_xyzw` (`0x07`) in the `idxen` form with a non-negative inline `soffset` and an optional `offset:`. The descriptor rules, entry constants (`uav_descword3`, `uav_stride`, `uav_numrecords`), RDNA 2 `OOB_SELECT` 0/3 bounds and the `if (exec & 1)` guard are those of `buffer_store_format_d16_x` above; the bounds lines of the two helpers are checked to be identical, and the same host-view guard (`GetDimensions`) drops an element that would pass the bound UAV. FORMAT is read at dispatch. Only the 4-channel formats of [`compute_store_aot.py`](../tools/compute_store_aot.py) write, with its conversions: `BUF_FMT_32_32_32_32_UINT`/`FLOAT` (75/77, `Store4`), `BUF_FMT_16_16_16_16_FLOAT` (71, binary32 to binary16 round to nearest even through `pack16_rne`), `BUF_FMT_8_8_8_8_UNORM` (56) and `BUF_FMT_2_10_10_10_UNORM` (50, x in bits 9:0), UNORM by the Direct3D half-away-from-zero rule with NaN to 0, in the unified and legacy `DFMT`/`NFMT` encodings, with identity `DST_SEL` `0xfac`. As in that tool, a format of another channel count writes nothing: what the format unit does with the extra components is not established here. All writes are whole aligned dwords, so no read-modify-write is needed. `offen`, `idxen offen`, `off`, a register `soffset`, `glc`/`slc`/`dlc`/`tfe`/`lds` and the descriptor cases refused for `d16_x` are refused by name; outside compute the opcode keeps the unknown-op refusal. + +[The `buffer_store_format_xyzw` check](../tests/startup_compute_store_format_xyzw_check.py) runs a CPU reference of the conversions (every binary16 value round-trips, every UNORM code of 2, 8 and 10 bits reads back, named ties and overflows), checks that the format set equals the 4-channel subset of `compute_store_aot.py`, the word 3 validator over every FORMAT field in both encodings, the exact emitted helper, calls and manifests (including separate entry constants for a second UAV), 32 translator refusals, and translator mutations (handler removed, legacy table changed, EXEC guard dropped) that turn it red. It dispatches three source-built `gfx1013` programs in 19 cases: `X` (six writing format cases and nine descriptors that must write nothing: 1- and 2-channel formats, `OOB_SELECT` 1/2, swapped `DST_SEL`, stride/OOB mismatches, `SWIZZLE_ENABLE`, element larger than the stride), `R` (`soffset` 4 and `offset:12` under raw and structured bounds) and `E` (`s_and_saveexec_b32` lane guard). On WARP (`Microsoft Basic Render Driver` `1414:008c`, driver `10.0.26100.10068`) with the D3D12 debug layer, through an `offscreen_check` built from an earlier tree and its root-descriptor `--compute-store-case` mode, all 19 cases matched all `320` words (`mismatches=0`, `debug_errors=0 debug_warnings=0`), and all nine shader mutants were rejected (`x-drop-store`, `x-swap-xy`, `x-drop-index-oob`, `unorm8-trunc`, `unorm10-w-scale`, `f16-drop-odd`, `mismatch-writes`, `r-drop-soffset`, `e-drop-exec`). The check now dispatches through `--compute-store-sized-case`, as the `d16_x` check does, because `GetDimensions` has no defined size on a root descriptor; that runner mode needs the per-case root constants of the `d16_x` change and was not run here. + +```powershell +. .\tools\dev.ps1 +cmake --preset release +cmake --build --preset release --target offscreen_check +ctest --preset release --no-tests=error -j 1 -R "^startup_compute_store_format_xyzw" -V +python -B tests/startup_compute_store_format_xyzw_check.py binary llvm-mc-15 +``` + +Not covered here: hardware adapters, the `llvm-mc-15` `binary` step, formats with fewer than four channels (they write nothing), `OOB_SELECT` 1, a dispatch against a host view shorter than the guest range (the guard is checked only as emitted text), and runtime binding of the three entry constants. + ### First active lane at compute entry The startup compute translator accepts `s_ff1_i32_b32 sN, exec_lo` in the diff --git a/tests/startup_compute_store_format_xyzw_check.py b/tests/startup_compute_store_format_xyzw_check.py new file mode 100644 index 0000000000..5886077dfd --- /dev/null +++ b/tests/startup_compute_store_format_xyzw_check.py @@ -0,0 +1,528 @@ +#!/usr/bin/env python3 +"""Verify compute buffer_store_format_xyzw lowering in tools/startup/gfx2hlsl.py (Refs #2274). + + (no arguments) pure-Python unit, format, bounds and refusal checks + binary reassemble fixture sources and verify machine words + dispatch translate, compile DXC cs_6_0, dispatch and verify readback + control dispatch a mutated translation that must mismatch + +The fixtures are source-built gfx1013 compute programs. Each lane reads four words from t0 and stores them with +`buffer_store_format_xyzw ... idxen`, the only address form the lowering models: +- Program X: `v[4:7], v0, s[16:19], 0 idxen` (16 lanes). Dispatched for the five 4-channel formats (32_32_32_32 FLOAT + and UINT, 8_8_8_8_UNORM, 2_10_10_10_UNORM, 16_16_16_16_FLOAT; unified and legacy encodings) with structured + OOB_SELECT 0 bounds, plus descriptors that must write nothing: 1- and 2-channel formats (channel count mismatch), + OOB_SELECT 1/2, non-identity DST_SEL, stride 0 or nonzero against the OOB mode, DW1 swizzle bits and a stride + smaller than the element. +- Program R: inline soffset 4 and `offset:12`, under raw OOB_SELECT 3 (stride 0; every lane writes the same element + with the same data) and structured OOB_SELECT 0 (soffset added to the base, not checked against the stride). +- Program E: `s_and_saveexec_b32` narrows EXEC to lanes 0..5 before the store, so the store is lane guarded. +""" + +import math +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parent +sys.path.insert(0, str(ROOT / 'tools')) +sys.path.insert(0, str(ROOT / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) + +import gfx2hlsl as G # noqa: E402 +import compute_store_aot as A # noqa: E402 +from startup_gfx2hlsl_compute_check import SENTINEL, USER7, WORDS, patch, refused, root_blob # noqa: E402 +from startup_compute_store_d16_x_check import PREAMBLE_X8, encode_mubuf # noqa: E402 + +MUBUF_STORE_FORMAT_XYZW = 0x07 +STORE_X = '00201ce000040480' # buffer_store_format_xyzw v[4:7], v0, s[16:19], 0 idxen + +SOURCE_X = PREAMBLE_X8 + """\ +v_lshlrev_b32 v4, 4, v0 +buffer_load_dwordx4 v[4:7], v4, s[12:15], 0 offen +s_waitcnt vmcnt(0) +buffer_store_format_xyzw v[4:7], v0, s[16:19], 0 idxen +s_endpgm +""" +LOAD_X = '06038abe' '80038bbe' '05030cf4000000fa' '7fc08cbf' '84000834' '001038e004040380' '703f8cbf' +WORDS_X = bytes.fromhex(LOAD_X + STORE_X + '000081bf') + +SOURCE_R = SOURCE_X.replace('0 idxen\n', '4 idxen offset:12\n') +WORDS_R = bytes.fromhex(LOAD_X + '0c201ce000040484' '000081bf') + +SOURCE_E = SOURCE_X.replace('buffer_store', 'v_cmp_gt_u32 vcc_lo, 6, v0\ns_and_saveexec_b32 s0, vcc_lo\nbuffer_store') +WORDS_E = bytes.fromhex(LOAD_X + '8600887d' '6a3c80be' + STORE_X + '000081bf') + +# A second UAV through s[20:23] (table offset 0x20): its d16_x store and the xyzw store get separate entry constants. +SOURCE_D = SOURCE_X.replace('s_waitcnt lgkmcnt', 's_load_dwordx4 s[20:23], s[10:11], 0x20\ns_waitcnt lgkmcnt', 1).replace( + 'buffer_store', 'buffer_store_format_d16_x v4, v0, s[20:23], 0 idxen\nbuffer_store') +WORDS_D = bytes.fromhex('06038abe' '80038bbe' '05030cf4000000fa' '050508f4200000fa' '7fc08cbf' '84000834' + '001038e004040380' '703f8cbf' '002010e200040580' + STORE_X + '000081bf') + +VERIFIED_SNIPPETS = { + 'buffer_store_format_xyzw v[4:7], v0, s[16:19], 0 idxen': STORE_X, + 'buffer_store_format_xyzw v[4:7], v0, s[16:19], 4 idxen offset:12': '0c201ce000040484', + 'buffer_store_format_xyzw v[4:7], v0, s[16:19], 0 offen': '00101ce000040480', + 'buffer_store_format_xyzw v[4:7], v[0:1], s[16:19], 0 idxen offen': '00301ce000040480', + 'buffer_store_format_xyzw v[4:7], off, s[16:19], 0': '00001ce000040480', + 'buffer_store_format_xyzw v[4:7], v0, s[16:19], s4 idxen': '00201ce000040404', + 'buffer_store_format_xyzw v[4:7], v0, s[16:19], 0 idxen glc': '00601ce000040480', + 'buffer_store_format_xyzw v[4:7], v0, s[16:19], 0 idxen slc': '00201ce000044480', + 'buffer_store_format_xyzw v[4:7], v0, s[16:19], 0 idxen dlc': '00a01ce000040480', + 'buffer_store_format_xyzw v[4:7], v0, s[16:19], 0 idxen tfe': '00201ce000048480', +} + +PROGRAMS = { + 'X': (SOURCE_X, WORDS_X, USER7, (16, 1, 1), (1, 1, 1)), + 'R': (SOURCE_R, WORDS_R, USER7, (16, 1, 1), (1, 1, 1)), + 'E': (SOURCE_E, WORDS_E, USER7, (16, 1, 1), (1, 1, 1)), + 'D': (SOURCE_D, WORDS_D, USER7, (16, 1, 1), (1, 1, 1)), +} + +EXPECTED_HELPER = """\ +uint store_unorm(uint bits, float scale) { + float x = asfloat(bits); + if (isnan(x)) return 0u; + precise float saturated = saturate(x); + precise float scaled = saturated * scale; + return (uint)floor(scaled + 0.5f); +} +void store_format_xyzw(RWByteAddressBuffer buf, uint word3, uint stride, uint num_records, uint idx, uint voff, \ +uint soff, uint imm_off, uint4 v) { + if ((word3 & 0xcef80000u) != 0u || (word3 & 0xfffu) != 0xfacu) return; + uint oob_sel = (word3 >> 28u) & 3u; + if ((oob_sel != 0u && oob_sel != 3u) || stride > 0x3fffu) return; + uint field = (word3 >> 12u) & 127u; + uint fmt = 0u; + if (((word3 >> 24u) & 1u) != 0u) { + fmt = field; + } else { + if (field == 72u) fmt = 50u; + else if (field == 80u) fmt = 56u; + else if (field == 103u) fmt = 71u; + else if (field == 116u) fmt = 75u; + else if (field == 119u) fmt = 77u; + } + uint elem_bytes = (fmt == 75u || fmt == 77u) ? 16u : fmt == 71u ? 8u : (fmt == 50u || fmt == 56u) ? 4u : 0u; + if (elem_bytes == 0u) return; +BOUNDS if ((addr & 3u) != 0u) return; + uint uav_bytes = 0u; + buf.GetDimensions(uav_bytes); + if (uav_bytes < elem_bytes || addr > uav_bytes - elem_bytes) return; + if (elem_bytes == 16u) { + buf.Store4(addr, v); + } else if (fmt == 71u) { + buf.Store2(addr, uint2(pack16_rne(asfloat(v.x)) | (pack16_rne(asfloat(v.y)) << 16u), \ +pack16_rne(asfloat(v.z)) | (pack16_rne(asfloat(v.w)) << 16u))); + } else if (fmt == 56u) { + buf.Store(addr, store_unorm(v.x, 255.0f) | (store_unorm(v.y, 255.0f) << 8u) \ +| (store_unorm(v.z, 255.0f) << 16u) | (store_unorm(v.w, 255.0f) << 24u)); + } else { + buf.Store(addr, store_unorm(v.x, 1023.0f) | (store_unorm(v.y, 1023.0f) << 10u) \ +| (store_unorm(v.z, 1023.0f) << 20u) | (store_unorm(v.w, 3.0f) << 30u)); + } +} +""" +# Bounds and OOB_SELECT lines shared with buffer_store_format_d16_x: taken from its helper so the two cannot drift. +BOUNDS_FIRST, BOUNDS_LAST = ' if (voff > 0xffffffffu - imm_off) return;\n', ' addr = elem_addr + soff;\n }\n' + + +def desc_word3(code, *, legacy=False, oob_select=0, dst_sel=0xfac): + if legacy: + field, level = next(k for k, v in G.STORE_FORMAT_XYZW_LEGACY_FORMATS.items() if v == code), 0 + else: + field, level = code, 1 + return ((oob_select & 3) << 28) | (level << 24) | ((field & 0x7f) << 12) | (dst_sel & 0xfff) + + +# --- CPU reference of the format conversions --------------------------------------------------------------------- + +def f32(bits): + return struct.unpack('> 16) & 0x8000 + x = f32(bits) + if math.isnan(x): + return sign | 0x7e00 + try: + return struct.unpack(' binary32 -> f16_rne (NaN becomes the quiet NaN of its sign). + for h in range(0x10000): + x = struct.unpack(' hlsl.index('void store_format_xyzw('): + problems.append('pack16_rne not defined before the helper') + expected_manifest = ('x2w-manifest 2\nstage cs\ngroup 16 1 1\nud 5\n' + 'udsrc 0 rootconst 0 0\nudsrc 1 rootconst 0 1\n' + 'udsrc 2 uav_descword3 0\nudsrc 3 uav_stride 0\nudsrc 4 uav_numrecords 0\n' + 'srv 0 buf table 1 0\nuav 0 table 1 16\n') + if pipe.manifest() != expected_manifest: + problems.append('manifest X') + for prog, line in (('X', '\n store_format_xyzw(u0, ud2, ud3, ud4, v0, 0u, 0u, 0u, uint4(v4, v5, v6, v7));\n'), + ('R', '\n store_format_xyzw(u0, ud2, ud3, ud4, v0, 0u, 4u, 12u, uint4(v4, v5, v6, v7));\n'), + ('E', '\n if (exec & 1) store_format_xyzw(u0, ud2, ud3, ud4, v0, 0u, 0u, 0u, ' + 'uint4(v4, v5, v6, v7));\n')): + if line not in translate(prog).hlsl_cs(): + problems.append('call %s' % prog) + two = translate('D') + if ('udsrc 2 uav_descword3 0\nudsrc 3 uav_stride 0\nudsrc 4 uav_numrecords 0\n' + 'udsrc 5 uav_descword3 1\nudsrc 6 uav_stride 1\nudsrc 7 uav_numrecords 1\n') not in two.manifest() or \ + '\n store_format_xyzw(u1, ud5, ud6, ud7, v0, 0u, 0u, 0u, uint4(v4, v5, v6, v7));\n' not in d16: + problems.append('second UAV entry constants') + return problems + + +def check_controls(): + check_reference() + + # 1. Decoder round trip of every recorded encoding. + for line, hex_words in VERIFIED_SNIPPETS.items(): + (_, size, op, asm), = G.decode(bytes.fromhex(hex_words)) + assert (size, op, asm) == (8, 'buffer_store_format_xyzw', line), (line, size, op, asm) + for line, fields in ((STORE_X, dict(idxen=True)), ('0c201ce000040484', dict(idxen=True, offset=12))): + soffset = 0x84 if fields.get('offset') else 0x80 + assert encode_mubuf(MUBUF_STORE_FORMAT_XYZW, 4, 0, 16, soffset, **fields).hex() == line + + # 2. The format set is the 4-channel subset of compute_store_aot's reviewed tables, in both encodings. + four = {code for code, (_, channels) in A.DESCRIPTOR_STORE_FORMATS.items() if channels == 4} + assert set(G.STORE_FORMAT_XYZW_FORMATS) == four, (sorted(G.STORE_FORMAT_XYZW_FORMATS), sorted(four)) + assert G.STORE_FORMAT_XYZW_LEGACY_FORMATS == {f: c for f, c in A.LEGACY_DESCRIPTOR_FORMATS.items() if c in four} + + # 3. Word 3 validator: exhaustive over the FORMAT field in both encodings and both OOB modes. + for level in (0, 1): + for field in range(128): + code = field if level else G.STORE_FORMAT_XYZW_LEGACY_FORMATS.get(field) + for oob in (0, 3): + w3 = (oob << 28) | (level << 24) | (field << 12) | 0xfac + if code in G.STORE_FORMAT_XYZW_FORMATS: + assert G.validate_store_format_xyzw_word3(w3) == (code, *G.STORE_FORMAT_XYZW_FORMATS[code]) + else: + refused('is not a handled 4-channel format', lambda w=w3: G.validate_store_format_xyzw_word3(w)) + for bad, fragment in ((desc_word3(77, dst_sel=0xfa5), 'non-identity DST_SEL 0xfa5'), + (desc_word3(77, dst_sel=0xfa4), 'non-identity DST_SEL'), + (desc_word3(77, oob_select=1), 'OOB_SELECT 1'), (desc_word3(77, oob_select=2), 'OOB_SELECT 2'), + (desc_word3(77) | (1 << 23), 'flags'), (desc_word3(77) | (1 << 21), 'flags'), + (desc_word3(77) | (1 << 30), 'flags'), (desc_word3(77) | (1 << 25), 'flags'), + (-1, 'invalid descriptor word 3'), (True, 'invalid descriptor word 3'), + (1 << 32, 'invalid descriptor word 3')): + refused(fragment, lambda w=bad: G.validate_store_format_xyzw_word3(w)) + + # 4. Exact emitted text, entry constants, helper only when used. + problems = emitted_text_problems() + assert not problems, problems + plain = G.ComputePipeline(bytes.fromhex('000081bf'), root_blob(), USER7, (1, 1, 1)).hlsl_cs() + assert 'store_format_xyzw' not in plain and 'store_unorm' not in plain + + # 5. Refusals naming the unmodelled shape (negative controls). + for hex_word, fragment in ( + (VERIFIED_SNIPPETS['buffer_store_format_xyzw v[4:7], v0, s[16:19], 0 offen'], 'offen address form'), + (VERIFIED_SNIPPETS['buffer_store_format_xyzw v[4:7], v[0:1], s[16:19], 0 idxen offen'], 'offen address form'), + (VERIFIED_SNIPPETS['buffer_store_format_xyzw v[4:7], off, s[16:19], 0'], 'without idxen'), + (VERIFIED_SNIPPETS['buffer_store_format_xyzw v[4:7], v0, s[16:19], s4 idxen'], + 'soffset s4 (only a non-negative inline constant is modelled)'), + (VERIFIED_SNIPPETS['buffer_store_format_xyzw v[4:7], v0, s[16:19], 0 idxen glc'], 'modifier glc'), + (VERIFIED_SNIPPETS['buffer_store_format_xyzw v[4:7], v0, s[16:19], 0 idxen slc'], 'modifier slc'), + (VERIFIED_SNIPPETS['buffer_store_format_xyzw v[4:7], v0, s[16:19], 0 idxen dlc'], 'modifier dlc'), + (VERIFIED_SNIPPETS['buffer_store_format_xyzw v[4:7], v0, s[16:19], 0 idxen tfe'], 'modifier tfe'), + (encode_mubuf(MUBUF_STORE_FORMAT_XYZW, 4, 0, 16, 0x80, idxen=True, lds=True).hex(), 'illegal MUBUF encoding'), + (encode_mubuf(MUBUF_STORE_FORMAT_XYZW, 4, 0, 16, 0x80, idxen=True, w0_rsvd=True).hex(), 'illegal MUBUF'), + (encode_mubuf(MUBUF_STORE_FORMAT_XYZW, 4, 0, 16, 0x80, idxen=True, w1_rsvd=True).hex(), 'illegal MUBUF'), + (encode_mubuf(MUBUF_STORE_FORMAT_XYZW, 4, 0, 12, 0x80, idxen=True).hex(), 'used for a load and a store'), + ): + refused(fragment, lambda hw=hex_word: translate('X', code=patch(WORDS_X, STORE_X, hw)).hlsl_cs()) + for inserted, fragment in (('800392be', 'modified descriptor'), # s_mov_b32 s18, 0 + ('11ff1187ffff00c0', 'modified descriptor'), # s_and_b32 s17, s17, 0xc000ffff + ('10841080', 'modified descriptor'), # s_add_u32 s16, s16, 4 + ('000082bf', 'local table load')): # s_branch +0, no local reload + refused(fragment, lambda i=inserted: translate('X', code=patch(WORDS_X, STORE_X, i + STORE_X)).hlsl_cs()) + for kind in ('ps', 'vs'): # outside compute: the unknown-op refusal, the bare mnemonic + stage = G.Stage.__new__(G.Stage) + stage.kind = kind + try: + stage.op_buffer_store_format_xyzw(['v[4:7]', 'v0', 's[16:19]', '0'], ['idxen']) + except G.Unsupported as reason: + assert str(reason) == 'buffer_store_format_xyzw', str(reason) + else: + raise AssertionError('%s stage accepted buffer_store_format_xyzw' % kind) + cs = translate('X').cs + cs.raw_code = b'' # synthetic operand lists below + for ops, mods, fragment in ( + (['v[4:7]', 'v0', 's[16:19]'], ['idxen'], 'with 3 operands, expected 4'), + (['v[4:7]', 'v0', 's[16:19]', '0'], ['idxen', 'idxen'], 'modifier idxen'), + (['v[4:7]', 'v0', 's[16:19]', '0'], ['idxen', 'offset:4', 'offset:8'], 'modifier offset:8'), + (['v[4:7]', 'v0', 's[16:19]', '0'], ['idxen', 'offset:4096'], 'modifier offset:4096'), + (['v[4:7]', 'v0', 's[16:19]', '0'], ['idxen', 'lds'], 'modifier lds'), + (['v[4:6]', 'v0', 's[16:19]', '0'], ['idxen'], 'data v[4:6]'), + (['v[253:256]', 'v0', 's[16:19]', '0'], ['idxen'], 'data v[253:256]'), + (['s[4:7]', 'v0', 's[16:19]', '0'], ['idxen'], 'data s[4:7]'), + (['v[4:7]', 'v[0:1]', 's[16:19]', '0'], ['idxen'], 'vaddr v[0:1] for idxen'), + (['v[4:7]', 's0', 's[16:19]', '0'], ['idxen'], 'vaddr s0 for idxen'), + (['v[4:7]', 'v0', 's[16:19]', '-1'], ['idxen'], 'soffset -1'), + (['v[4:7]', 'v0', 's[16:19]', 'v1'], ['idxen'], 'soffset v1'), + (['v[4:7]', 'v0', 's[16:17]', '0'], ['idxen'], 'descriptor s[16:17]'), + (['v[4:7]', 'v0', 's[104:107]', '0'], ['idxen'], 'descriptor s[104:107]'), + ): + refused(fragment, lambda o=ops, m=mods: cs.op_buffer_store_format_xyzw(o, m)) + + # 6. Translator mutations turn the checks red. + saved = G.Stage.op_buffer_store_format_xyzw + try: + delattr(G.Stage, 'op_buffer_store_format_xyzw') + refused('buffer_store_format_xyzw', lambda: translate('X').hlsl_cs()) + finally: + G.Stage.op_buffer_store_format_xyzw = saved + legacy = dict(G.STORE_FORMAT_XYZW_LEGACY_FORMATS) + for mutation in ({**legacy, (14 << 3) | 4: 77}, {k: v for k, v in legacy.items() if v != 50}): + G.STORE_FORMAT_XYZW_LEGACY_FORMATS = mutation + try: + assert 'helper text' in emitted_text_problems(), mutation + finally: + G.STORE_FORMAT_XYZW_LEGACY_FORMATS = legacy + saved_emit = G.Stage.emit + try: # dropping the EXEC guard + G.Stage.emit = lambda self, line: saved_emit(self, line.replace('if (exec & 1) store_format_xyzw', 'store_format_xyzw')) + assert 'call E' in emitted_text_problems() + finally: + G.Stage.emit = saved_emit + + # 7. Dispatch inputs are self-consistent: writing cases change words, no-op cases keep every sentinel. + for name in DISPATCH_CASES: + _, _, _, expected = case_inputs(name) + writes = X_VARIANTS[name][4] if name in X_VARIANTS else name != 'R-raw-oob' + assert (expected != [SENTINEL] * WORDS) == writes, name + + print('buffer_store_format_xyzw reference, format, bounds, provenance, refusal and mutation checks pass') + + +def check_binary(llvm_mc): + from startup_flat_param_check import assemble + for name, (source, words, *_rest) in PROGRAMS.items(): + built = assemble(llvm_mc, source) + assert built == words, '%s: assembled %s, recorded %s' % (name, built.hex(), words.hex()) + for line, hex_words in VERIFIED_SNIPPETS.items(): + built = assemble(llvm_mc, line + '\n').hex() + assert built == hex_words, '%s: assembled %s, recorded %s' % (line, built, hex_words) + print('buffer_store_format_xyzw fixture words match llvm-mc (%d programs, %d snippets)' + % (len(PROGRAMS), len(VERIFIED_SNIPPETS))) + + +CONTROLS = { + 'x-drop-store': ('X-f32', ' store_format_xyzw(u0, ud2, ud3, ud4, v0, 0u, 0u, 0u, uint4(v4, v5, v6, v7));\n', ''), + 'x-swap-xy': ('X-f32', 'buf.Store4(addr, v);', 'buf.Store4(addr, v.yxzw);'), + 'x-drop-index-oob': ('X-f32', + 'if (idx >= num_records || elem_bytes > stride || rec_off > stride - elem_bytes) return;', + 'if (elem_bytes > stride || rec_off > stride - elem_bytes) return;'), + 'unorm8-trunc': ('X-unorm8', 'return (uint)floor(scaled + 0.5f);', 'return (uint)floor(scaled);'), + 'unorm10-w-scale': ('X-unorm10-legacy', '(store_unorm(v.w, 3.0f) << 30u)', '(store_unorm(v.w, 1.0f) << 30u)'), + 'f16-drop-odd': ('X-f16', 'pack16_rne(asfloat(v.x)) |', '(pack16_rne(asfloat(v.x)) & 0xfffeu) |'), + 'mismatch-writes': ('X-1ch', '(fmt == 50u || fmt == 56u) ? 4u : 0u', '(fmt == 50u || fmt == 56u || fmt == 22u) ? 4u : 0u'), + 'r-drop-soffset': ('R-struct', 'v0, 0u, 4u, 12u, uint4', 'v0, 0u, 0u, 12u, uint4'), + 'e-drop-exec': ('E', 'if (exec & 1) store_format_xyzw(', 'store_format_xyzw('), +} + + +def run_case(name, dxc, runner, adapter, directory, control=None): + prog, source, constants, expected = case_inputs(name) + hlsl = translate(prog).hlsl_cs() + if control: + _, old, new = CONTROLS[control] + assert hlsl.count(old) == 1, (control, old) + hlsl = hlsl.replace(old, new) + src, cso, case = (directory / ('%s.%s' % (name, ext)) for ext in ('hlsl', 'cso', 'case')) + src.write_text(hlsl, encoding='ascii', newline='\n') + subprocess.run([dxc, '-Gis', '-T', 'cs_6_0', '-E', 'main', '-Fo', str(cso), str(src)], check=True) + groups = PROGRAMS[prog][4] + case.write_bytes(struct.pack('> 28) & 3 + if oob_select not in (0, 3): + raise Unsupported('%s unsupported OOB_SELECT %d' % (name, oob_select)) + field = (word3 >> DESC_FORMAT_SHIFT) & DESC_FORMAT_MASK + code = field if ((word3 >> 24) & 1) else STORE_FORMAT_XYZW_LEGACY_FORMATS.get(field) + info = STORE_FORMAT_XYZW_FORMATS.get(code) + if info is None: + raise Unsupported('%s descriptor FORMAT %d is not a handled 4-channel format' % (name, field)) + return code, info[0], info[1] + def starts_with_fetch_call(code): return len(code) >= 4 and struct.unpack_from(' 0xfff: + raise Unsupported('%s modifier %s' % (name, m)) + else: + raise Unsupported('%s modifier %s' % (name, m)) + if not idxen: + raise Unsupported('%s without idxen (only the idxen address form is modelled)' % name) + src = reg_range(ops[0]) + if not src or src[0] != 'v' or src[2] - src[1] != 3 or src[2] > 255: + raise Unsupported('%s data %s' % (name, ops[0])) + vaddr = reg_range(ops[1]) + if not vaddr or vaddr[0] != 'v' or vaddr[1] != vaddr[2] or vaddr[1] > 255: + raise Unsupported('%s vaddr %s for idxen' % (name, ops[1])) + if not re.fullmatch(r'0x[0-9a-f]+|\d+', ops[3]): + raise Unsupported('%s soffset %s (only a non-negative inline constant is modelled)' % (name, ops[3])) + rsrc = reg_range(ops[2]) + if not rsrc or rsrc[0] != 's' or rsrc[2] - rsrc[1] != 3 or rsrc[2] > 105: + raise Unsupported('%s descriptor %s' % (name, ops[2])) + key = self.store_descriptor(ops[2], 4, name, stride0_ok=False) + first = self.sym.get(rsrc[1]) + if getattr(self, 'past_entry', False) and not self.formatted_descriptor_from_block(rsrc, first): + raise Unsupported('%s requires descriptor words proven in the entry block or a local table load' % name) + idx = self.u(ops[1]) + data = 'uint4(%s)' % ', '.join(self.u('v%d' % n) for n in range(src[1], src[2] + 1)) + uav = self.pipe.uav(key, 'raw') + uav_index = self.pipe.uavs[key]['index'] + word3 = 'ud%d' % self.pipe.ud(('uav_descword3', uav_index)) + stride = 'ud%d' % self.pipe.ud(('uav_stride', uav_index)) + num_records = 'ud%d' % self.pipe.ud(('uav_numrecords', uav_index)) + self.pipe.uses_store_format_xyzw = self.pipe.uses_pack16_rne = True + call = 'store_format_xyzw(%s, %s, %s, %s, %s, 0u, %du, %du, %s);' % ( + uav, word3, stride, num_records, idx, int(ops[3], 0), imm_offset or 0, data) + self.emit(call if self.exec_known else 'if (exec & 1) ' + call) + def op_tbuffer_load_format_x(self, ops, mods): self.tbuffer(ops, mods, 1) @@ -6574,6 +6674,7 @@ class Pipeline: uses_gather_2d_lod = False uses_store_d16_x = False uses_sad = () + uses_store_format_xyzw = False srv_formats = () uavs = None # key -> dict(index, kind): images a pixel stage stores to (u registers); None until the first store @@ -6604,6 +6705,7 @@ def __init__(self, vs_code, ps_code, root_blob, sampler_heap=None, rtv_formats=( self.uses_gather_2d_lod = False self.uses_store_d16_x = False self.uses_sad = set() + self.uses_store_format_xyzw = False self.resources = {} # key -> dict(index, kind) self.samplers = {} # key -> index self.uds = [] # entry-constant sources @@ -6955,6 +7057,65 @@ def common(self): out.append( 'uint sad_u32(uint a, uint b, uint c) {' ' return (a > b ? a - b : b - a) + c; }') + if self.uses_store_format_xyzw: + legacy = [' %sif (field == %du) fmt = %du;' % ('' if i == 0 else 'else ', field, code) + for i, (field, code) in enumerate(sorted(STORE_FORMAT_XYZW_LEGACY_FORMATS.items()))] + out.extend(( + 'uint store_unorm(uint bits, float scale) {', + ' float x = asfloat(bits);', + ' if (isnan(x)) return 0u;', + ' precise float saturated = saturate(x);', + ' precise float scaled = saturated * scale;', + ' return (uint)floor(scaled + 0.5f);', + '}', + 'void store_format_xyzw(RWByteAddressBuffer buf, uint word3, uint stride, uint num_records, ' + 'uint idx, uint voff, uint soff, uint imm_off, uint4 v) {', + ' if ((word3 & 0xcef80000u) != 0u || (word3 & 0xfffu) != 0xfacu) return;', + ' uint oob_sel = (word3 >> 28u) & 3u;', + ' if ((oob_sel != 0u && oob_sel != 3u) || stride > 0x3fffu) return;', + ' uint field = (word3 >> 12u) & 127u;', + ' uint fmt = 0u;', + ' if (((word3 >> 24u) & 1u) != 0u) {', + ' fmt = field;', + ' } else {', + *legacy, + ' }', + ' uint elem_bytes = (fmt == 75u || fmt == 77u) ? 16u : fmt == 71u ? 8u : (fmt == 50u || fmt == 56u) ? 4u : 0u;', + ' if (elem_bytes == 0u) return;', + ' if (voff > 0xffffffffu - imm_off) return;', + ' uint rec_off = voff + imm_off;', + ' uint addr = 0u;', + ' if (oob_sel == 3u) {', + ' if (stride != 0u) return;', + ' if (soff > 0xffffffffu - rec_off) return;', + ' addr = soff + rec_off;', + ' if (elem_bytes > num_records || addr > num_records - elem_bytes) return;', + ' } else {', + ' if (stride == 0u) return;', + ' if (idx >= num_records || elem_bytes > stride || rec_off > stride - elem_bytes) return;', + ' if (idx > (0xffffffffu - rec_off) / stride) return;', + ' uint elem_addr = idx * stride + rec_off;', + ' if (soff > 0xffffffffu - elem_addr) return;', + ' addr = elem_addr + soff;', + ' }', + ' if ((addr & 3u) != 0u) return;', + ' uint uav_bytes = 0u;', + ' buf.GetDimensions(uav_bytes);', + ' if (uav_bytes < elem_bytes || addr > uav_bytes - elem_bytes) return;', + ' if (elem_bytes == 16u) {', + ' buf.Store4(addr, v);', + ' } else if (fmt == 71u) {', + ' buf.Store2(addr, uint2(pack16_rne(asfloat(v.x)) | (pack16_rne(asfloat(v.y)) << 16u), ' + 'pack16_rne(asfloat(v.z)) | (pack16_rne(asfloat(v.w)) << 16u)));', + ' } else if (fmt == 56u) {', + ' buf.Store(addr, store_unorm(v.x, 255.0f) | (store_unorm(v.y, 255.0f) << 8u) ' + '| (store_unorm(v.z, 255.0f) << 16u) | (store_unorm(v.w, 255.0f) << 24u));', + ' } else {', + ' buf.Store(addr, store_unorm(v.x, 1023.0f) | (store_unorm(v.y, 1023.0f) << 10u) ' + '| (store_unorm(v.z, 1023.0f) << 20u) | (store_unorm(v.w, 3.0f) << 30u));', + ' }', + '}', + )) return out def interface(self, for_pixel):