From 93da95ef844ed3be986c0ef36efc6cc75e8b52fa Mon Sep 17 00:00:00 2001 From: Vladimir <39053957+Vladimir-Human@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:56:37 -0600 Subject: [PATCH 1/6] shader: lower compute buffer_store_format_d16_x in gfx2hlsl MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refs #2274. Adds compute-stage MUBUF buffer_store_format_d16_x (opcode 0x84) lowering to tools/startup/gfx2hlsl.py: - Validates four untouched descriptor words from a fixed native table entry (refusing modified descriptors including stride clears, shared load/store descriptors, missing local table provenance after branches, non-compute stages, lane-mask soffset, illegal binary lds/reserved MUBUF bits, bad operand shapes, and unsupported modifiers glc/slc/dlc/tfe/lds). - Emits uav table plus udsrc entries uav_descword3, uav_stride (unmasked DW1 >> 16, so stride > 0x3fffu rejects DW1[31:30] CACHE_SWIZZLE/SWIZZLE_ENABLE) and uav_numrecords, under an if (exec & 1) guard when EXEC is not proven entry-full. - Supports 1-channel formats BUF_FMT_32_FLOAT (22), BUF_FMT_16_FLOAT (13), BUF_FMT_16_UNORM (7), BUF_FMT_16_SNORM (8), BUF_FMT_16_UINT (11) and BUF_FMT_16_SINT (12) in both GFX10 unified and legacy DFMT/NFMT encodings, checking DST_SEL_X == 4, zero reserved/swizzle/ADD_TID_ENABLE/TYPE flags, and RDNA 2 ISA §8.1.5 Table 35 bounds modes: OOB_SELECT 0 (structured, stride != 0, rec_off = voff + imm_off checked against stride while soffset adds to base) and OOB_SELECT 3 (raw, stride == 0, soffset + rec_off + elem_bytes <= num_records). OOB_SELECT 1/2, mismatched stride/OOB_SELECT, 32-bit overflow, misaligned addresses, unsupported formats/flags and OOB lanes are no-ops. - Uses 4-byte aligned Store for BUF_FMT_32_FLOAT and a lock-free InterlockedCompareExchange CAS loop for 2-byte aligned 16-bit formats. Adds tests/startup_compute_store_d16_x_check.py wired in CMakeLists.txt, .github/workflows/windows.yml and docs/experiments.md. AI-assisted: implementation and tests drafted and verified with an AI coding assistant. --- .github/workflows/windows.yml | 2 + CMakeLists.txt | 16 + docs/experiments.md | 18 + tests/startup_compute_store_d16_x_check.py | 647 +++++++++++++++++++++ tools/startup/gfx2hlsl.py | 224 ++++++- 5 files changed, 905 insertions(+), 2 deletions(-) create mode 100644 tests/startup_compute_store_d16_x_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index b1e699497d..af82a2cb2c 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -93,6 +93,7 @@ jobs: (["tests/startup_compute_readfirstlane_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["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_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"], {}), @@ -207,6 +208,7 @@ jobs: tests/startup_compute_image_store_d16_check.py \ tests/startup_compute_gather_l_check.py \ tests/startup_compute_buffer_atomics_check.py \ + tests/startup_compute_store_d16_x_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/CMakeLists.txt b/CMakeLists.txt index 09ad6dc25b..09686117e5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3343,6 +3343,22 @@ if(EXISTS "${INTAKE_PYTHON}") set_tests_properties(startup_gfx2hlsl_mad_dispatch_${adapter} startup_gfx2hlsl_mad_preserve_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endforeach() + # gfx2hlsl compute buffer_store_format_d16_x: multi-format, bounds/OOB, atomic CAS RMW and EXEC guard (Refs #2274). + add_test(NAME startup_compute_store_d16_x_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_compute_store_d16_x_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_compute_store_d16_x_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_compute_store_d16_x_check.py" dispatch "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_compute_store_d16_x_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + foreach(control IN ITEMS f32-drop-store f32-wrong-half f32-drop-oob unorm16-trunc p-drop-soffset p-drop-keep s-fold-soff-stride e-drop-exec) + add_test(NAME startup_compute_store_d16_x_${control}_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_compute_store_d16_x_check.py" control ${control} "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_compute_store_d16_x_${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 222b1ee7a8..12c8eacbe8 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -14015,6 +14015,24 @@ case. The three mutations mismatched 32, 8 and 16 words respectively on both ada ctest --preset dev --no-tests=error -j 1 -R '^startup_gfx2hlsl_compute_(controls|warp|hardware)$' -V ``` +### Startup compute formatted 16-bit single-channel buffer stores + +[The startup translator](../tools/startup/gfx2hlsl.py) (`op_buffer_store_format_d16_x`, refs `#2274`) lowers compute MUBUF `buffer_store_format_d16_x` (`0x84`) through four untouched words of a fixed native table descriptor (`uav table `), requesting `udsrc` entries `uav_descword3`, `uav_stride` (unmasked `DW1 >> 16`, so `stride > 0x3fffu` rejects nonzero `CACHE_SWIZZLE`/`SWIZZLE_ENABLE` bits 31:30) and `uav_numrecords` for that UAV slot. After a branch, the descriptor must come from a local table load with a proven entry root pointer; non-compute stages, modified descriptors (including stride clears), shared load/store descriptors, lane-mask `soffset`, illegal binary `lds`/reserved MUBUF bits, and unsupported modifiers (`glc`, `slc`, `dlc`, `tfe`, `lds`) are refused with `Unsupported`. + +Supported 1-channel formats (`BUF_FMT_32_FLOAT` 22, `BUF_FMT_16_FLOAT` 13, `BUF_FMT_16_UNORM` 7, `BUF_FMT_16_SNORM` 8, `BUF_FMT_16_UINT` 11, `BUF_FMT_16_SINT` 12, in both GFX10 unified and legacy `DFMT`/`NFMT` encodings) extract the low 16 bits of `vdata`, enforce `DST_SEL_X == 4`, zero reserved/swizzle/`ADD_TID_ENABLE`/`TYPE` bits, and RDNA 2 ISA §8.1.5 Table 35 bounds modes: `OOB_SELECT == 0` (`SQ_OOB_INDEX_AND_OFFSET`, requires `stride != 0`, checks `idx < num_records` and `rec_off + elem_bytes <= stride` where `rec_off = voff + imm_off`, while `soffset` adds to base address) and `OOB_SELECT == 3` (`SQ_OOB_COMPLETE` raw mode, requires `stride == 0`, checks `soffset + rec_off + elem_bytes <= num_records`). `OOB_SELECT` `1` (`INDEX_ONLY`) and `2` (`NUM_RECORDS_0` / disabled bounds), mismatched `stride`/`OOB_SELECT`, 32-bit address overflow, misaligned addresses, and OOB lanes are no-ops. Stores use 4-byte aligned `Store` for `32_FLOAT` and a lock-free `InterlockedCompareExchange` CAS loop for 2-byte aligned 16-bit formats, under an `if (exec & 1)` lane guard when `EXEC` is not proven entry-full. + +[The `buffer_store_format_d16_x` check](../tests/startup_compute_store_d16_x_check.py) covers pure-Python unit/manifest/encoding/provenance/refusal checks and dispatches five source-built `gfx1013` compute programs: `F` (all six formats + legacy encodings + 7 no-op descriptor/OOB/swizzle checks), `P` (`OOB_SELECT=3` raw bounds + `stride=0` + `offen` + SGPR `soffset` + concurrent adjacent halves), `S` (`OOB_SELECT=0` structured with `soffset=16 > stride=8`), `E` (`idxen offen` + local descriptor reload after `s_cbranch_execz` + inner `s_and_saveexec_b32` EXEC guard), and `C` (256 concurrent threads hammering the same low/high 16-bit halfwords to verify atomic CAS without bitwise-OR or torn corruption). On both WARP (`Microsoft Basic Render Driver` `1414:008c`, driver `10.0.26100.9818`) and `NVIDIA GeForce RTX 4070 SUPER` (`10de:2783`, driver `32.0.16.2114`) with the D3D12 debug layer enabled, all 16 deterministic dispatch cases matched all `320` words (`mismatches=0`, `debug_errors=0 debug_warnings=0`), Case `C` produced valid atomic halfword values with 319 untouched sentinels (`debug_errors=0 debug_warnings=0`), and all eight shader mutants rejected cleanly on both adapters (`f32-drop-store`, `f32-wrong-half`, `f32-drop-oob`, `unorm16-trunc`, `p-drop-soffset`, `p-drop-keep`, `s-fold-soff-stride`, `e-drop-exec`). + +```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_d16_x" -V +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`. + ### 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_d16_x_check.py b/tests/startup_compute_store_d16_x_check.py new file mode 100644 index 0000000000..7966c9cb94 --- /dev/null +++ b/tests/startup_compute_store_d16_x_check.py @@ -0,0 +1,647 @@ +#!/usr/bin/env python3 +"""Verify compute buffer_store_format_d16_x 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: +- Case F: 16 lanes read poisoned-high-half inputs from t0 and store via `buffer_store_format_d16_x ... idxen offset:4`. + Dispatched across all six supported formats (32_FLOAT, 16_FLOAT, 16_UNORM, 16_SNORM legacy, 16_UINT, 16_SINT legacy) + with OOB_SELECT=0, stride=8, num_records=12 (so lanes 12..15 are OOB no-ops preserving sentinel), plus no-op checks + for unsupported FORMAT, OOB_SELECT=1/2, OOB_SELECT=0 with stride=0, OOB_SELECT=3 with stride=8, and DW1 swizzle bits. +- Case P: 32 lanes concurrently write adjacent low/high 16-bit halves of the same dwords using `offen`, SGPR `soffset` + (`s4`), `offset:2`, OOB_SELECT=3, `stride=0` and `num_records=50` (raw byte bounds; lanes 23..31 are OOB no-ops). +- Case S: 16 lanes store via structured OOB_SELECT=0 with SGPR `soffset` (`s4=16 > stride=8`) and `offset:4`, proving + RDNA 2 ISA separation of `soffset` from the record offset checked against `stride`. +- Case E: 16 lanes narrow EXEC to tid.x < 10, branch with `s_cbranch_execz`, locally reload the UAV descriptor, narrow + EXEC again to tid.x < 6 via `s_and_saveexec_b32`, and store via `idxen offen` to `BUF_FMT_16_FLOAT` (OOB_SELECT=0); + inactive lanes 6..15 must preserve sentinel. +- Case C: 256 concurrent threads (4 groups x 64 lanes) repeatedly write competing values ({0x1111, 0x2222} to byte 0, + {0x4444, 0x8888} to byte 2) to the same 16-bit halfwords, verifying atomic CAS prevents bitwise-OR or torn corruption. +""" + +import math +import re +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 +from startup_gfx2hlsl_compute_check import SENTINEL, USER7, WORDS, patch, refused, root_blob # noqa: E402 + +MUBUF_STORE_FORMAT_D16_X = 0x84 + + +def encode_mubuf(op, vdata, vaddr, srsrc, soffset_enc, *, idxen=False, offen=False, offset=0, + glc=False, slc=False, dlc=False, tfe=False, lds=False, w0_rsvd=False, w1_rsvd=False): + w0 = (0xe0000000 | ((op & 0xff) << 18) | (int(w0_rsvd) << 17) | (int(lds) << 16) + | (int(dlc) << 15) | (int(glc) << 14) | (int(idxen) << 13) | (int(offen) << 12) | (offset & 0xfff)) + w1 = (((soffset_enc & 0xff) << 24) | (int(tfe) << 23) | (int(slc) << 22) | (int(w1_rsvd) << 21) + | (((srsrc // 4) & 0x1f) << 16) | ((vdata & 0xff) << 8) | (vaddr & 0xff)) + return struct.pack('> 16, num_records). +F_VARIANTS = { + 'F-f32': (desc_word3(22, oob_select=0, dst_sel=0x204), 8, 12, 'fp16', True), + 'F-f16': (desc_word3(13, oob_select=0, dst_sel=0xFAC), 8, 12, 'fp16', True), + 'F-unorm16': (desc_word3(7, oob_select=0, dst_sel=0x204), 8, 12, 'fp16', True), + 'F-snorm16': (desc_word3(8, legacy=True, oob_select=0), 8, 12, 'fp16', True), + 'F-uint16': (desc_word3(11, oob_select=0, dst_sel=0xFAC), 8, 12, 'int16', True), + 'F-sint16': (desc_word3(12, legacy=True, oob_select=0), 8, 12, 'int16', True), + # Refused / no-op descriptor configurations (must preserve all 320 sentinel words): + 'F-unsupported': (desc_word3(29, oob_select=0, dst_sel=0xFAC), 8, 12, 'fp16', False), # 16_16_FLOAT + 'F-oob1': (desc_word3(22, oob_select=1, dst_sel=0x204), 8, 12, 'fp16', False), # INDEX_ONLY + 'F-oob2': (desc_word3(22, oob_select=2, dst_sel=0x204), 8, 12, 'fp16', False), # DISABLED + 'F-oob0-stride0': (desc_word3(22, oob_select=0, dst_sel=0x204), 0, 64, 'fp16', False), # structured + stride=0 + 'F-oob3-stride8': (desc_word3(22, oob_select=3, dst_sel=0x204), 8, 64, 'fp16', False), # raw + stride!=0 + 'F-swizzle-en': (desc_word3(22, oob_select=0, dst_sel=0x204), 8 | 0x8000, 12, 'fp16', False), # DW1 bit 31 + 'F-cache-swizzle': (desc_word3(22, oob_select=0, dst_sel=0x204), 8 | 0x4000, 12, 'fp16', False), # DW1 bit 30 +} + +PROGRAMS = { + 'F': (SOURCE_F, WORDS_F, USER7, (16, 1, 1), (1, 1, 1)), + 'P': (SOURCE_P, WORDS_P, USER7, (32, 1, 1), (1, 1, 1)), + 'S': (SOURCE_S, WORDS_S, USER7, (16, 1, 1), (1, 1, 1)), + 'E': (SOURCE_E, WORDS_E, USER7, (16, 1, 1), (1, 1, 1)), + 'C': (SOURCE_C, WORDS_C, USER7, (64, 1, 1), (4, 1, 1)), +} + +DISPATCH_CASES = (*F_VARIANTS.keys(), 'P', 'S', 'E') +CONTENTION_VALID_LO = (0x1111, 0x2222) +CONTENTION_VALID_HI = (0x4444, 0x8888) + + +def f16_to_f32_bits(h): + val = struct.unpack('= 0.0 + else math.ceil(struct.unpack(' base byte offset 4; lane i writes at 4 + 2*i. + # OOB_SELECT=3 (raw), stride = 0, num_records = 50 -> lanes 0..22 write bytes 4..49, + # lanes 23..31 are OOB no-ops preserving sentinel (including high half of dword 12). + halves = tuple(((0x1000 + i * 0x0137) & 0xffff) for i in range(32)) + source = poisoned_source(halves) + word3 = desc_word3(11, oob_select=3, dst_sel=0xFAC) # BUF_FMT_16_UINT, OOB_SELECT=3 (RAW) + constants = [2, 0, word3, 0, 50] + [0] * 11 + for lane in range(32): + addr = 4 + 2 * lane + if addr + 2 <= 50: + put_half(buf, addr, halves[lane]) + return 'P', source, constants, list(struct.unpack('<%dI' % WORDS, buf)) + + if name == 'S': + # Structured OOB_SELECT=0 with soffset (s4=16) > stride (8) and imm_off=4. + # RDNA 2 ISA: rec_off=4 <= stride-4 (in-bounds), addr = 16 + idx*8 + 4 for idx < 12. + halves = tuple(0x7c00 if i == 11 else h for i, h in enumerate(FP16_VALUES)) + source = poisoned_source(halves) + word3 = desc_word3(22, oob_select=0, dst_sel=0x204) # BUF_FMT_32_FLOAT, OOB_SELECT=0 + constants = [16, 0, word3, 8, 12] + [0] * 11 + for lane in range(12): + struct.pack_into('> 16u) & 0xffffu;\n', + ), + 'f32-drop-oob': ( + 'F-f32', + ' if (idx >= num_records || elem_bytes > stride || rec_off > stride - elem_bytes) return;\n', + ' if (elem_bytes > stride || rec_off > stride - elem_bytes) return;\n', + ), + 'unorm16-trunc': ( + 'F-unorm16', + ' return (uint)floor(scaled + 0.5f);\n', + ' return (uint)floor(scaled);\n', + ), + 'p-drop-soffset': ( + 'P', + ' store_format_d16_x(u0, ud2, ud3, ud4, 0u, v1, ud0, 2u, v5);\n', + ' store_format_d16_x(u0, ud2, ud3, ud4, 0u, v1, 0u, 2u, v5);\n', + ), + 'p-drop-keep': ( + 'P', + ' uint next = (cur & keep) | ins;\n', + ' uint next = ins;\n', + ), + 's-fold-soff-stride': ( + 'S', + ' if (idx >= num_records || elem_bytes > stride || rec_off > stride - elem_bytes) return;\n', + ' if (idx >= num_records || elem_bytes > stride || (rec_off + soff) > stride - elem_bytes) return;\n', + ), + 'e-drop-exec': ( + 'E', + 'if (exec & 1) store_format_d16_x(', + 'store_format_d16_x(', + ), +} + + +def mutate(hlsl, control): + _, old, new = CONTROLS[control] + assert hlsl.count(old) == 1, (control, hlsl) + return hlsl.replace(old, new) + + +def run_case(name, dxc, runner, adapter, directory, control=None): + prog_key, source, constants, exp = case_inputs(name) + hlsl = translate(prog_key).hlsl_cs() + if control: + hlsl = mutate(hlsl, control) + src, cso, case = (directory / ('%s.%s' % (name, ext)) for ext in ('hlsl', 'cso', 'case')) + src.write_text(hlsl, encoding='ascii') + subprocess.run([dxc, '-Gis', '-T', 'cs_6_0', '-E', 'main', '-Fo', str(cso), str(src)], check=True) + groups = PROGRAMS[prog_key][4] + case.write_bytes( + struct.pack('> 16) & 0xffff + assert lo in CONTENTION_VALID_LO and hi in CONTENTION_VALID_HI, ( + 'case C: atomic CAS contention corrupted word 0: 0x%08x (lo=0x%04x hi=0x%04x)' % (actual, lo, hi)) + print('case C: atomic CAS contention ok (word0=0x%08x, 319 sentinels untouched)' % actual) + return 0 + + +if __name__ == '__main__': + if len(sys.argv) == 1: + check_controls() + elif len(sys.argv) == 3 and sys.argv[1] == 'binary': + check_binary(sys.argv[2]) + elif len(sys.argv) == 5 and sys.argv[1] == 'dispatch': + sys.exit(check_dispatch(*sys.argv[2:])) + elif len(sys.argv) == 6 and sys.argv[1] == 'control': + sys.exit(check_dispatch(*sys.argv[3:], control=sys.argv[2])) + else: + sys.exit(__doc__) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 221cedb43b..81fb06d9dc 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -167,6 +167,52 @@ def strip_header(code): # Integer formats read a DST_SEL constant 1 as the integer 1, every other format as 1.0. DESC_ONE_INTEGER = ('BUF_FMT_8_UINT', 'BUF_FMT_16_16_UINT', 'BUF_FMT_8_8_8_8_UINT') +# Supported 1-channel formats for compute buffer_store_format_d16_x (RDNA 2 MUBUF 0x84): +# V# word 3 bits 18:12 carry the 7-bit GFX10 unified FORMAT when RESOURCE_LEVEL (bit 24) is 1, +# or legacy (DFMT << 3) | NFMT when bit 24 is 0. Bits checked zero: TYPE[31:30], reserved[27:25], +# ADD_TID_ENABLE[23], INDEX_STRIDE[22:21], reserved[20:19]. DST_SEL_X[2:0] must be 4 (SQ_SEL_X); +# OOB_SELECT[29:28] must be 0 (SQ_OOB_INDEX_AND_OFFSET, structured with stride != 0) or +# 3 (SQ_OOB_COMPLETE, raw byte bounds with stride == 0). Modes 1 (INDEX_ONLY) and 2 +# (NUM_RECORDS_0 / disabled bounds check) are refused. Entry constant uav_stride carries the +# unmasked upper 16 bits of V# word 1 (DW1 >> 16), so stride > 0x3fffu rejects CACHE_SWIZZLE +# (bit 30) and SWIZZLE_ENABLE (bit 31). +STORE_D16_X_FORMATS = { + 7: ('BUF_FMT_16_UNORM', 2), + 8: ('BUF_FMT_16_SNORM', 2), + 11: ('BUF_FMT_16_UINT', 2), + 12: ('BUF_FMT_16_SINT', 2), + 13: ('BUF_FMT_16_FLOAT', 2), + 22: ('BUF_FMT_32_FLOAT', 4), +} +STORE_D16_X_LEGACY_FORMATS = { + (2 << 3) | 0: 7, # DFMT_16 + NFMT_UNORM + (2 << 3) | 1: 8, # DFMT_16 + NFMT_SNORM + (2 << 3) | 4: 11, # DFMT_16 + NFMT_UINT + (2 << 3) | 5: 12, # DFMT_16 + NFMT_SINT + (2 << 3) | 7: 13, # DFMT_16 + NFMT_FLOAT + (4 << 3) | 7: 22, # DFMT_32 + NFMT_FLOAT +} +STORE_D16_X_WORD3_ZERO_MASK = 0xcef80000 + + +def validate_store_d16_x_word3(word3): + """Validate V# word 3 for compute buffer_store_format_d16_x and return (code, name, elem_bytes).""" + if not isinstance(word3, int) or isinstance(word3, bool) or not 0 <= word3 <= 0xffffffff: + raise Unsupported('buffer_store_format_d16_x invalid descriptor word 3 %r' % (word3,)) + if word3 & STORE_D16_X_WORD3_ZERO_MASK: + raise Unsupported('buffer_store_format_d16_x unsupported descriptor word 3 flags 0x%08x' % word3) + if (word3 & 7) != 4: + raise Unsupported('buffer_store_format_d16_x non-identity DST_SEL_X %d' % (word3 & 7)) + oob_select = (word3 >> 28) & 3 + if oob_select not in (0, 3): + raise Unsupported('buffer_store_format_d16_x unsupported OOB_SELECT %d' % oob_select) + field = (word3 >> DESC_FORMAT_SHIFT) & DESC_FORMAT_MASK + code = field if ((word3 >> 24) & 1) else STORE_D16_X_LEGACY_FORMATS.get(field) + info = STORE_D16_X_FORMATS.get(code) + if info is None: + raise Unsupported('buffer_store_format_d16_x unsupported descriptor FORMAT %d' % field) + return code, info[0], info[1] + def starts_with_fetch_call(code): return len(code) >= 4 and struct.unpack_from(' binary32, 4-byte aligned Store. + - BUF_FMT_16_FLOAT (13), BUF_FMT_16_UINT (11), BUF_FMT_16_SINT (12): low 16 bits stored at a + 2-byte aligned offset via a lock-free InterlockedCompareExchange CAS loop on the enclosing dword. + - BUF_FMT_16_UNORM (7), BUF_FMT_16_SNORM (8): binary16 -> binary32 -> D3D half-away-from-zero + 16-bit UNORM/SNORM (NaN -> 0), stored via the same 2-byte atomic CAS loop. + Per RDNA 2 ISA §8.1.5 Table 35, OOB_SELECT 0 (structured, stride != 0) checks index < num_records + and (voff + imm_off) + elem_bytes <= stride while soffset adds to the base address; OOB_SELECT 3 + (raw, stride == 0) checks (soffset + voff + imm_off) + elem_bytes <= num_records. OOB_SELECT 1/2, + mismatched stride/OOB_SELECT, nonzero DW1[31:30] swizzle flags (uav_stride carries DW1 >> 16), + unsupported formats/flags, misaligned addresses and out-of-bounds lanes are no-ops. + """ + name = 'buffer_store_format_d16_x' + if self.kind != 'cs': + raise Unsupported(name) + raw = getattr(self, 'raw_code', b'') + pc = getattr(self, 'pc', None) + if raw and pc is not None and pc + 8 <= len(raw): + w0, w1 = struct.unpack_from(' 0xfff: + raise Unsupported('%s modifier %s' % (name, m)) + imm_offset = val + else: + raise Unsupported('%s modifier %s' % (name, m)) + imm_offset = 0 if imm_offset is None else imm_offset + src = reg_range(ops[0]) + if not src or src[0] != 'v' or src[1] != src[2] or src[1] > 255: + raise Unsupported('%s data %s' % (name, ops[0])) + if idxen and offen: + vaddr = reg_range(ops[1]) + if not vaddr or vaddr[0] != 'v' or vaddr[2] - vaddr[1] != 1 or vaddr[2] > 255: + raise Unsupported('%s vaddr %s for idxen offen' % (name, ops[1])) + idx_expr, voff_expr = self.u('v%d' % vaddr[1]), self.u('v%d' % vaddr[2]) + elif idxen: + 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])) + idx_expr, voff_expr = self.u(ops[1]), '0u' + elif offen: + 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 offen' % (name, ops[1])) + idx_expr, voff_expr = '0u', self.u(ops[1]) + else: + if ops[1] != 'off': + raise Unsupported('%s vaddr %s without idxen or offen' % (name, ops[1])) + idx_expr, voff_expr = '0u', '0u' + if re.fullmatch(r'0x[0-9a-f]+|\d+', ops[3]): + soff_imm = int(ops[3], 0) + if soff_imm > 0xffffffff: + raise Unsupported('%s soffset %s' % (name, ops[3])) + soff_expr = '%du' % soff_imm + else: + if self.is_lane_mask(ops[3]): + raise Unsupported('%s soffset %s is a lane mask' % (name, ops[3])) + sreg = reg_range(ops[3]) + if not sreg or sreg[0] != 's' or sreg[1] != sreg[2] or sreg[1] > 105: + raise Unsupported('%s soffset %s' % (name, ops[3])) + soff_expr = self.S(sreg[1]) + 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) + 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)) + val_expr = self.u(ops[0], low16_only=True) + self.pipe.uses_store_d16_x = True + call = 'store_format_d16_x(%s, %s, %s, %s, %s, %s, %s, %du, %s);' % ( + uav, word3, stride, num_records, idx_expr, voff_expr, soff_expr, imm_offset, val_expr) + 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) @@ -4952,6 +5093,7 @@ def read(fmt, data, offset): class Pipeline: uses_pack16_rne = False uses_gather_2d_lod = False + uses_store_d16_x = False srv_formats = () uavs = None # key -> dict(index, kind): images a pixel stage stores to (u registers); None until the first store @@ -4983,6 +5125,7 @@ def __init__(self, vs_code, ps_code, root_blob, sampler_heap=None, rtv_formats=( self.uses_sampler_heap = False self.uses_pack16_rne = False self.uses_gather_2d_lod = False + self.uses_store_d16_x = False self.resources = {} # key -> dict(index, kind) self.samplers = {} # key -> index self.uds = [] # entry-constant sources @@ -5194,6 +5337,82 @@ def common(self): ' return result;', '}', )) + if self.uses_store_d16_x: + out.extend(( + 'uint d16_to_unorm16(uint h) {', + ' float x = f16tof32(h);', + ' if (isnan(x)) return 0u;', + ' precise float saturated = saturate(x);', + ' precise float scaled = saturated * 65535.0f;', + ' return (uint)floor(scaled + 0.5f);', + '}', + 'uint d16_to_snorm16(uint h) {', + ' float x = f16tof32(h);', + ' if (isnan(x)) return 0u;', + ' precise float saturated = clamp(x, -1.0f, 1.0f);', + ' precise float scaled = saturated * 32767.0f;', + ' precise float rounded = scaled >= 0.0f ? floor(scaled + 0.5f) : ceil(scaled - 0.5f);', + ' return ((uint)(int)rounded) & 0xffffu;', + '}', + 'void store_format_d16_x(RWByteAddressBuffer buf, uint word3, uint stride, uint num_records, ' + 'uint idx, uint voff, uint soff, uint imm_off, uint val) {', + ' if ((word3 & 0xcef80000u) != 0u || (word3 & 7u) != 4u) 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 == 16u) fmt = 7u;', + ' else if (field == 17u) fmt = 8u;', + ' else if (field == 20u) fmt = 11u;', + ' else if (field == 21u) fmt = 12u;', + ' else if (field == 23u) fmt = 13u;', + ' else if (field == 39u) fmt = 22u;', + ' }', + ' uint elem_bytes = fmt == 22u ? 4u : (fmt == 7u || fmt == 8u || fmt == 11u || fmt == 12u || fmt == 13u ? 2u : 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;', + ' }', + ' uint h = val & 0xffffu;', + ' if (fmt == 22u) {', + ' if ((addr & 3u) != 0u) return;', + ' buf.Store(addr, asuint(f16tof32(h)));', + ' return;', + ' }', + ' if ((addr & 1u) != 0u) return;', + ' uint out16 = h;', + ' if (fmt == 7u) out16 = d16_to_unorm16(h);', + ' else if (fmt == 8u) out16 = d16_to_snorm16(h);', + ' uint base = addr & 0xfffffffcu;', + ' uint shift = (addr & 2u) << 3u;', + ' uint keep = ~(0xffffu << shift);', + ' uint ins = (out16 & 0xffffu) << shift;', + ' uint cur = buf.Load(base);', + ' for (;;) {', + ' uint next = (cur & keep) | ins;', + ' uint prev = 0u;', + ' buf.InterlockedCompareExchange(base, cur, next, prev);', + ' if (prev == cur) break;', + ' cur = prev;', + ' }', + '}', + )) return out def interface(self, for_pixel): @@ -5325,6 +5544,7 @@ def __init__(self, cs_code, root_blob, rsrc2, group, sampler_heap=None, refusals self.sampler_heap = os.environ.get('X2W_SAMPLER_HEAP') == '1' if sampler_heap is None else sampler_heap self.uses_sampler_heap = False self.uses_gather_2d_lod = False + self.uses_store_d16_x = False self.resources, self.uavs, self.samplers, self.uds = {}, {}, {}, [] self.notes, self.modified, self.other_modified = set(), set(), set() # other: anything but a stride clear self.lod_unvalidated = set() From f9236795d0f0c04c0cbb0629e3e07e488261be64 Mon Sep 17 00:00:00 2001 From: Vladimir <39053957+Vladimir-Human@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:22:27 -0600 Subject: [PATCH 2/6] shader: guard buffer_store_format_d16_x against host UAV bounds --- CMakeLists.txt | 2 +- docs/experiments.md | 4 +- tests/compute_check.cpp | 36 ++++--- tests/desktop_gpu.h | 2 +- tests/offscreen_check.cpp | 16 ++- tests/startup_compute_store_d16_x_check.py | 108 ++++++++++++++++++--- tools/startup/gfx2hlsl.py | 7 +- 7 files changed, 140 insertions(+), 35 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 09686117e5..faef34c43e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3351,7 +3351,7 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/startup_compute_store_d16_x_check.py" dispatch "${DXC_EXECUTABLE}" "$" ${adapter}) set_tests_properties(startup_compute_store_d16_x_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) - foreach(control IN ITEMS f32-drop-store f32-wrong-half f32-drop-oob unorm16-trunc p-drop-soffset p-drop-keep s-fold-soff-stride e-drop-exec) + foreach(control IN ITEMS f32-drop-store f32-wrong-half f32-drop-oob unorm16-trunc p-drop-soffset p-drop-keep s-fold-soff-stride e-drop-exec b-short-binding b-tight-host-guard) add_test(NAME startup_compute_store_d16_x_${control}_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_compute_store_d16_x_check.py" control ${control} "${DXC_EXECUTABLE}" "$" ${adapter}) diff --git a/docs/experiments.md b/docs/experiments.md index 12c8eacbe8..0d73a522ee 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -14019,9 +14019,9 @@ ctest --preset dev --no-tests=error -j 1 -R '^startup_gfx2hlsl_compute_(controls [The startup translator](../tools/startup/gfx2hlsl.py) (`op_buffer_store_format_d16_x`, refs `#2274`) lowers compute MUBUF `buffer_store_format_d16_x` (`0x84`) through four untouched words of a fixed native table descriptor (`uav table `), requesting `udsrc` entries `uav_descword3`, `uav_stride` (unmasked `DW1 >> 16`, so `stride > 0x3fffu` rejects nonzero `CACHE_SWIZZLE`/`SWIZZLE_ENABLE` bits 31:30) and `uav_numrecords` for that UAV slot. After a branch, the descriptor must come from a local table load with a proven entry root pointer; non-compute stages, modified descriptors (including stride clears), shared load/store descriptors, lane-mask `soffset`, illegal binary `lds`/reserved MUBUF bits, and unsupported modifiers (`glc`, `slc`, `dlc`, `tfe`, `lds`) are refused with `Unsupported`. -Supported 1-channel formats (`BUF_FMT_32_FLOAT` 22, `BUF_FMT_16_FLOAT` 13, `BUF_FMT_16_UNORM` 7, `BUF_FMT_16_SNORM` 8, `BUF_FMT_16_UINT` 11, `BUF_FMT_16_SINT` 12, in both GFX10 unified and legacy `DFMT`/`NFMT` encodings) extract the low 16 bits of `vdata`, enforce `DST_SEL_X == 4`, zero reserved/swizzle/`ADD_TID_ENABLE`/`TYPE` bits, and RDNA 2 ISA §8.1.5 Table 35 bounds modes: `OOB_SELECT == 0` (`SQ_OOB_INDEX_AND_OFFSET`, requires `stride != 0`, checks `idx < num_records` and `rec_off + elem_bytes <= stride` where `rec_off = voff + imm_off`, while `soffset` adds to base address) and `OOB_SELECT == 3` (`SQ_OOB_COMPLETE` raw mode, requires `stride == 0`, checks `soffset + rec_off + elem_bytes <= num_records`). `OOB_SELECT` `1` (`INDEX_ONLY`) and `2` (`NUM_RECORDS_0` / disabled bounds), mismatched `stride`/`OOB_SELECT`, 32-bit address overflow, misaligned addresses, and OOB lanes are no-ops. Stores use 4-byte aligned `Store` for `32_FLOAT` and a lock-free `InterlockedCompareExchange` CAS loop for 2-byte aligned 16-bit formats, under an `if (exec & 1)` lane guard when `EXEC` is not proven entry-full. +Supported 1-channel formats (`BUF_FMT_32_FLOAT` 22, `BUF_FMT_16_FLOAT` 13, `BUF_FMT_16_UNORM` 7, `BUF_FMT_16_SNORM` 8, `BUF_FMT_16_UINT` 11, `BUF_FMT_16_SINT` 12, in both GFX10 unified and legacy `DFMT`/`NFMT` encodings) extract the low 16 bits of `vdata`, enforce `DST_SEL_X == 4`, zero reserved/swizzle/`ADD_TID_ENABLE`/`TYPE` bits, and RDNA 2 ISA §8.1.5 Table 35 bounds modes: `OOB_SELECT == 0` (`SQ_OOB_INDEX_AND_OFFSET`, requires `stride != 0`, checks `idx < num_records` and `rec_off + elem_bytes <= stride` where `rec_off = voff + imm_off`, while `soffset` adds to base address) and `OOB_SELECT == 3` (`SQ_OOB_COMPLETE` raw mode, requires `stride == 0`, checks `soffset + rec_off + elem_bytes <= num_records`). `OOB_SELECT` `1` (`INDEX_ONLY`) and `2` (`NUM_RECORDS_0` / disabled bounds), mismatched `stride`/`OOB_SELECT`, 32-bit address overflow, misaligned addresses, and OOB lanes are no-ops. Separately from guest `num_records`/`stride`, `store_format_d16_x` queries `buf.GetDimensions(uav_bytes)` on the bound raw UAV and exits before `buf.Store` (`uav_bytes < 4u || addr > uav_bytes - 4u`) or before `buf.Load(base)` and `buf.InterlockedCompareExchange(base, ...)` (`uav_bytes < 4u || base > uav_bytes - 4u`) whenever the enclosing aligned DWORD `[base, base + 4)` exceeds the host view. Stores use 4-byte aligned `Store` for `32_FLOAT` and a lock-free `InterlockedCompareExchange` CAS loop for 2-byte aligned 16-bit formats, under an `if (exec & 1)` lane guard when `EXEC` is not proven entry-full. -[The `buffer_store_format_d16_x` check](../tests/startup_compute_store_d16_x_check.py) covers pure-Python unit/manifest/encoding/provenance/refusal checks and dispatches five source-built `gfx1013` compute programs: `F` (all six formats + legacy encodings + 7 no-op descriptor/OOB/swizzle checks), `P` (`OOB_SELECT=3` raw bounds + `stride=0` + `offen` + SGPR `soffset` + concurrent adjacent halves), `S` (`OOB_SELECT=0` structured with `soffset=16 > stride=8`), `E` (`idxen offen` + local descriptor reload after `s_cbranch_execz` + inner `s_and_saveexec_b32` EXEC guard), and `C` (256 concurrent threads hammering the same low/high 16-bit halfwords to verify atomic CAS without bitwise-OR or torn corruption). On both WARP (`Microsoft Basic Render Driver` `1414:008c`, driver `10.0.26100.9818`) and `NVIDIA GeForce RTX 4070 SUPER` (`10de:2783`, driver `32.0.16.2114`) with the D3D12 debug layer enabled, all 16 deterministic dispatch cases matched all `320` words (`mismatches=0`, `debug_errors=0 debug_warnings=0`), Case `C` produced valid atomic halfword values with 319 untouched sentinels (`debug_errors=0 debug_warnings=0`), and all eight shader mutants rejected cleanly on both adapters (`f32-drop-store`, `f32-wrong-half`, `f32-drop-oob`, `unorm16-trunc`, `p-drop-soffset`, `p-drop-keep`, `s-fold-soff-stride`, `e-drop-exec`). +[The `buffer_store_format_d16_x` check](../tests/startup_compute_store_d16_x_check.py) covers pure-Python unit/manifest/encoding/provenance/refusal checks (including static ordering of `GetDimensions` and host-backing guards before `Store`, `Load`, and `InterlockedCompareExchange`) and dispatches six source-built `gfx1013` compute programs through descriptor-table raw views (`offscreen_check --compute-store-sized-case` with optional `uav_words`): `F` (all six formats + legacy encodings + 7 no-op descriptor/OOB/swizzle checks), `P` (`OOB_SELECT=3` raw bounds + `stride=0` + `offen` + SGPR `soffset` + concurrent adjacent halves), `S` (`OOB_SELECT=0` structured with `soffset=16 > stride=8`), `E` (`idxen offen` + local descriptor reload after `s_cbranch_execz` + inner `s_and_saveexec_b32` EXEC guard), `B`/`B-short` (`OOB_SELECT=3, stride=0, num_records=6` writing `addr = 0, 2, 4` against padded `uav_words=2` and short `uav_words=1` host bindings), and `C` (256 concurrent threads hammering the same low/high 16-bit halfwords to verify atomic CAS without bitwise-OR or torn corruption). On both WARP (`Microsoft Basic Render Driver` `1414:008c`, driver `10.0.26100.9818`) and `NVIDIA GeForce RTX 4070 SUPER` (`10de:2783`, driver `32.0.16.2114`) with the D3D12 debug layer enabled, all 18 deterministic dispatch cases matched all `320` words (`mismatches=0`, `debug_errors=0 debug_warnings=0`), Case `C` produced valid atomic halfword values with 319 untouched sentinels (`debug_errors=0 debug_warnings=0`), and all ten controls rejected cleanly on both adapters (`f32-drop-store`, `f32-wrong-half`, `f32-drop-oob`, `unorm16-trunc`, `p-drop-soffset`, `p-drop-keep`, `s-fold-soff-stride`, `e-drop-exec`, plus `b-short-binding` and `b-tight-host-guard` at `word=1` with `debug_errors=0 debug_warnings=0`). ```powershell . .\tools\dev.ps1 diff --git a/tests/compute_check.cpp b/tests/compute_check.cpp index a9975c8685..813a6197c4 100644 --- a/tests/compute_check.cpp +++ b/tests/compute_check.cpp @@ -59,7 +59,8 @@ UINT texture_words_per_texel(DXGI_FORMAT format) static UINT input_word(UINT i) { return 0x8b02a7f1u + i * 0x413b1u; } // source replaces the generated t0 words when a store case supplies its own. -static void fill_upload(ID3D12Resource* upload, const std::array* source = nullptr) +static void fill_upload(ID3D12Resource* upload, const std::array* source = nullptr, + const std::array* root_constants = nullptr) { void* mapped = nullptr; const D3D12_RANGE no_reads{}; @@ -71,7 +72,8 @@ static void fill_upload(ID3D12Resource* upload, const std::array } auto* cb = static_cast(mapped) + constants_offset; std::memset(cb, 0, 4 * alignment); - std::memcpy(cb, constants.data(), sizeof(constants)); + const auto& cb0 = root_constants ? *root_constants : constants; + std::memcpy(cb, cb0.data(), sizeof(cb0)); for (UINT i = 1; i < 4; ++i) std::memcpy(cb + i * alignment, &constants[12 + i], sizeof(UINT)); upload->Unmap(0, nullptr); } @@ -131,8 +133,11 @@ static ComPtr upload_texture(ID3D12Device* device, ID3D12Graphic static ComPtr bind_tables(ID3D12Device* device, ID3D12GraphicsCommandList* list, ID3D12Resource* input, ID3D12Resource* output, ID3D12Resource* texture = nullptr, UINT output_register = uavs - 1, UINT output_mip = 0, - UINT input_register = srvs - 1, UINT texture_first_mip = 0) + UINT input_register = srvs - 1, UINT texture_first_mip = 0, + UINT output_words = capacity) { + if (output_words == 0 || output_words > capacity) + throw std::runtime_error("Invalid compute UAV word count"); D3D12_DESCRIPTOR_HEAP_DESC desc{}; desc.NumDescriptors = uavs + srvs; desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; @@ -144,7 +149,7 @@ static ComPtr bind_tables(ID3D12Device* device, ID3D12Grap D3D12_UNORDERED_ACCESS_VIEW_DESC uav{}; uav.Format = DXGI_FORMAT_R32_TYPELESS; uav.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; - uav.Buffer.NumElements = capacity; + uav.Buffer.NumElements = output_words; uav.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; if (output_register >= uavs) throw std::runtime_error("Invalid output register"); for (UINT i = 0; i < uavs; ++i, cpu.ptr += stride) { @@ -210,9 +215,11 @@ static void run_compute(ID3D12Device* device, bool tables, D3D12_SHADER_BYTECODE D3D12_SHADER_BYTECODE rootBytes, bool conversion_pair = false, const StoreCase* store = nullptr, const std::vector* texels = nullptr, DXGI_FORMAT texture_format = DXGI_FORMAT_UNKNOWN, ID3D12Resource* rendered_texture = nullptr, - bool dpp_case = false, bool sized_views = false, UINT texture_first_mip = 0) + bool dpp_case = false, bool sized_views = false, UINT texture_first_mip = 0, + UINT uav_words = capacity) { if ((texels || rendered_texture) && !tables) throw std::runtime_error("An image load needs the descriptor-table signature"); + if (uav_words == 0 || uav_words > capacity) throw std::runtime_error("Invalid compute UAV word count"); ComPtr signature; check(device->CreateRootSignature(0, rootBytes.pShaderBytecode, rootBytes.BytecodeLength, IID_PPV_ARGS(&signature)), "Create compute root signature"); @@ -226,7 +233,8 @@ static void run_compute(ID3D12Device* device, bool tables, D3D12_SHADER_BYTECODE auto output = make_buffer(device, bytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); auto readback = make_buffer(device, bytes, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); - fill_upload(input.Get(), store && store->has_source ? &store->source : nullptr); + fill_upload(input.Get(), store && store->has_source ? &store->source : nullptr, + store ? &store->root_constants : nullptr); ComputeCommands commands(device, pipeline.Get()); auto& list = commands.list; ComPtr texture_upload, texture; @@ -241,7 +249,7 @@ static void run_compute(ID3D12Device* device, bool tables, D3D12_SHADER_BYTECODE // signature's UAV range starts at u0, while the root-descriptor path keeps u12. auto* image = rendered_texture ? rendered_texture : texture.Get(); // A sized-view case binds both raw buffers at u0 and t0, so GetDimensions reports the view's byte size. - heap = sized_views ? bind_tables(device, list.Get(), input.Get(), output.Get(), nullptr, 0, 0, 0) + heap = sized_views ? bind_tables(device, list.Get(), input.Get(), output.Get(), nullptr, 0, 0, 0, 0, uav_words) : bind_tables(device, list.Get(), input.Get(), output.Get(), image, image ? 0 : uavs - 1, 0, srvs - 1, texture_first_mip); } else { @@ -309,8 +317,10 @@ void check_compute(ID3D12Device* device, bool tables) } void check_compute_file(ID3D12Device* device, const char* path, bool conversion_pair, const char* reference, - bool dpp_case, bool sized_views) + bool dpp_case, bool sized_views, UINT uav_words) { + if (sized_views && uav_words > capacity) + throw std::runtime_error("Invalid compute UAV word count"); std::ifstream file(path, std::ios::binary | std::ios::ate); if (!file) throw std::runtime_error(std::string("Could not open compute shader: ") + path); const auto size = file.tellg(); @@ -341,12 +351,16 @@ void check_compute_file(ID3D12Device* device, const char* path, bool conversion_ store.has_source = true; } } - if (sized_views) + if (sized_views) { + const UINT effective_uav_words = uav_words ? uav_words : capacity; + if (effective_uav_words > capacity) + throw std::runtime_error("Invalid compute UAV word count"); run_compute(device, true, shader, {compute_tables, sizeof(compute_tables)}, false, &store, nullptr, - DXGI_FORMAT_UNKNOWN, nullptr, dpp_case, true); - else + DXGI_FORMAT_UNKNOWN, nullptr, dpp_case, true, 0, effective_uav_words); + } else { run_compute(device, false, shader, {compute_root, sizeof(compute_root)}, false, &store, nullptr, DXGI_FORMAT_UNKNOWN, nullptr, dpp_case); + } } else { run_compute(device, false, shader, shader, conversion_pair); } diff --git a/tests/desktop_gpu.h b/tests/desktop_gpu.h index e01c44fd7e..f6c90c7019 100644 --- a/tests/desktop_gpu.h +++ b/tests/desktop_gpu.h @@ -42,7 +42,7 @@ void check_spirv_compaction(ID3D12Device* device, const char* shader_path); void check_spirv_compare_sampler(ID3D12Device* device, const char* shader_path, const char* ordinary_register, const char* reference_path, const char* descriptors = nullptr); void check_compute_file(ID3D12Device* device, const char* path, bool conversion_pair, const char* reference = nullptr, - bool dpp_case = false, bool sized_views = false); + bool dpp_case = false, bool sized_views = false, UINT uav_words = 0); void check_compute_texture_file(ID3D12Device* device, const char* path, const char* reference); bool check_compute_texture_msaa_file(ID3D12Device* device, const char* path, const char* reference, const char* vs_path, const char* ps_path); diff --git a/tests/offscreen_check.cpp b/tests/offscreen_check.cpp index 12b394a58c..eb269b34df 100644 --- a/tests/offscreen_check.cpp +++ b/tests/offscreen_check.cpp @@ -537,11 +537,19 @@ OperationResult run_compute_store_case(const OperationContext& ctx) return {OutcomeKind::pass, nullptr}; } -// The store case with both raw buffers bound as descriptor-table views of the full 1280 bytes, so a -// shader reading a descriptor's size sees the view size (root descriptors carry none). +// The store case with both raw buffers bound as descriptor-table views (defaulting to the full 1280 +// bytes, or an explicit uav_words count in [1, 320]), so a shader reading a descriptor's size sees +// the view size (root descriptors carry none). OperationResult run_compute_store_sized_case(const OperationContext& ctx) { - check_compute_file(ctx.device, ctx.argv[3], false, ctx.argv[4], false, true); + UINT uav_words = 0; + if (ctx.argc == 6) { + const std::string_view text = ctx.argv[5]; + const auto [end, error] = std::from_chars(text.data(), text.data() + text.size(), uav_words); + if (error != std::errc{} || end != text.data() + text.size() || uav_words == 0) + throw std::runtime_error("Invalid compute UAV word count"); + } + check_compute_file(ctx.device, ctx.argv[3], false, ctx.argv[4], false, true, uav_words); return {OutcomeKind::pass, nullptr}; } @@ -1559,7 +1567,7 @@ const OperationSpec kOperations[] = { {"--compute-root-file", 4, 4, nullptr, kNoGate, run_compute_root_file}, {"--ffx-immediate-conversion", 4, 4, nullptr, kNoGate, run_ffx_immediate_conversion}, {"--compute-store-case", 5, 5, nullptr, kNoGate, run_compute_store_case}, - {"--compute-store-sized-case", 5, 5, nullptr, kNoGate, run_compute_store_sized_case}, + {"--compute-store-sized-case", 5, 6, nullptr, kNoGate, run_compute_store_sized_case}, {"--compute-store-dpp-case", 5, 5, nullptr, kGateShaderWave, run_compute_store_dpp_case}, {"--compute-store-case-atomic64", 5, 5, nullptr, kGateComputeAtomic64, run_compute_store_case}, {"--compute-texture-case", 5, 5, nullptr, kNoGate, run_compute_texture_case}, diff --git a/tests/startup_compute_store_d16_x_check.py b/tests/startup_compute_store_d16_x_check.py index 7966c9cb94..1255ff5083 100644 --- a/tests/startup_compute_store_d16_x_check.py +++ b/tests/startup_compute_store_d16_x_check.py @@ -20,6 +20,10 @@ inactive lanes 6..15 must preserve sentinel. - Case C: 256 concurrent threads (4 groups x 64 lanes) repeatedly write competing values ({0x1111, 0x2222} to byte 0, {0x4444, 0x8888} to byte 2) to the same 16-bit halfwords, verifying atomic CAS prevents bitwise-OR or torn corruption. +- Case B / B-short: 4 lanes write 3 in-bounds 16-bit halves at addr = 0, 2, 4 under guest OOB_SELECT=3, stride=0, + num_records=6. Case B binds a padded host raw UAV (uav_words=2, 8 bytes) so DWORD 0 updates and DWORD 1 updates only + its low half while preserving the high-half sentinel; Case B-short binds the same shader/inputs to a short host raw + UAV (uav_words=1, 4 bytes) proving the host backing guard exits before Load/InterlockedCompareExchange on DWORD 1. """ import math @@ -165,10 +169,25 @@ def desc_word3(fmt_code, *, legacy=False, oob_select=0, dst_sel=0xFAC): + '000081bf' ) +SOURCE_B = PREAMBLE_X8 + """\ +v_lshlrev_b32 v4, 2, v0 +buffer_load_dword v5, v4, s[12:15], 0 offen +v_lshlrev_b32 v1, 1, v0 +s_waitcnt vmcnt(0) +buffer_store_format_d16_x v5, v1, s[16:19], 0 offen +s_endpgm +""" +WORDS_B = bytes.fromhex( + '06038abe' '80038bbe' '05030cf4000000fa' '7fc08cbf' + '82000834' '001030e004050380' '81000234' '703f8cbf' + '001010e201050480' '000081bf' +) + VERIFIED_SNIPPETS = { 'buffer_store_format_d16_x v5, off, s[16:19], 0 offset:4': '040010e200050480', 'buffer_store_format_d16_x v5, v0, s[16:19], 0 idxen offset:4': '042010e200050480', 'buffer_store_format_d16_x v5, v0, s[16:19], s4 idxen offset:4': '042010e200050404', + 'buffer_store_format_d16_x v5, v1, s[16:19], 0 offen': '001010e201050480', 'buffer_store_format_d16_x v5, v1, s[16:19], s4 offen offset:2': '021010e201050404', 'buffer_store_format_d16_x v5, v[2:3], s[16:19], 0 idxen offen': '003010e202050480', 'buffer_store_format_d16_x v5, v0, s[16:19], 0 idxen glc': '006010e200050480', @@ -226,9 +245,10 @@ def desc_word3(fmt_code, *, legacy=False, oob_select=0, dst_sel=0xFAC): 'S': (SOURCE_S, WORDS_S, USER7, (16, 1, 1), (1, 1, 1)), 'E': (SOURCE_E, WORDS_E, USER7, (16, 1, 1), (1, 1, 1)), 'C': (SOURCE_C, WORDS_C, USER7, (64, 1, 1), (4, 1, 1)), + 'B': (SOURCE_B, WORDS_B, USER7, (4, 1, 1), (1, 1, 1)), } -DISPATCH_CASES = (*F_VARIANTS.keys(), 'P', 'S', 'E') +DISPATCH_CASES = (*F_VARIANTS.keys(), 'P', 'S', 'E', 'B', 'B-short') CONTENTION_VALID_LO = (0x1111, 0x2222) CONTENTION_VALID_HI = (0x4444, 0x8888) @@ -275,7 +295,7 @@ def put_half(buf, byte_addr, half): def case_inputs(name): - """Return (program_key, source_bytes, constants_16, expected_words_320).""" + """Return (program_key, source_bytes, constants_16, expected_words_320, uav_words).""" buf = bytearray(struct.pack('<%dI' % WORDS, *([SENTINEL] * WORDS))) if name in F_VARIANTS: word3, stride, num_records, kind, active = F_VARIANTS[name] @@ -297,7 +317,7 @@ def case_inputs(name): put_half(buf, addr, f16_to_snorm16(h)) else: put_half(buf, addr, h) - return 'F', source, constants, list(struct.unpack('<%dI' % WORDS, buf)) + return 'F', source, constants, list(struct.unpack('<%dI' % WORDS, buf)), None if name == 'P': # 32 lanes, s4 = 2 (soffset), offset:2 -> base byte offset 4; lane i writes at 4 + 2*i. @@ -311,7 +331,7 @@ def case_inputs(name): addr = 4 + 2 * lane if addr + 2 <= 50: put_half(buf, addr, halves[lane]) - return 'P', source, constants, list(struct.unpack('<%dI' % WORDS, buf)) + return 'P', source, constants, list(struct.unpack('<%dI' % WORDS, buf)), None if name == 'S': # Structured OOB_SELECT=0 with soffset (s4=16) > stride (8) and imm_off=4. @@ -322,7 +342,7 @@ def case_inputs(name): constants = [16, 0, word3, 8, 12] + [0] * 11 for lane in range(12): struct.pack_into(' word 0 updated, word 1 low half updated (high half sentinel). + # Case B-short binds a short 1-word (4-byte) raw UAV -> word 0 updated, word 1 untouched sentinel. + halves = (0x1234, 0x5678, 0x9abc, 0xdef0) + source = poisoned_source(halves) + word3 = desc_word3(11, oob_select=3, dst_sel=0xFAC) # BUF_FMT_16_UINT, OOB_SELECT=3 (RAW) + constants = [0, 0, word3, 0, 6] + [0] * 11 + uav_words = 2 if name == 'B' else 1 + uav_bytes = uav_words * 4 + for lane in range(4): + addr = 2 * lane + if addr + 2 <= 6 and (addr & ~3) + 4 <= uav_bytes: + put_half(buf, addr, halves[lane]) + return 'B', source, constants, list(struct.unpack('<%dI' % WORDS, buf)), uav_words if name == 'C': # Even lanes read t0[0]=0x1111, t0[2]=0x4444; odd lanes read t0[1]=0x2222, t0[3]=0x8888. @@ -341,7 +378,7 @@ def case_inputs(name): # Sentinel 0xdeadbeef at word 0 forces offscreen_check to report actual word 0 while asserting words 1..319 == SENTINEL. exp = [SENTINEL] * WORDS exp[0] = 0xdeadbeef - return 'C', source, constants, exp + return 'C', source, constants, exp, None raise KeyError(name) @@ -406,6 +443,14 @@ def check_controls(): assert 'buf.InterlockedCompareExchange(' in hlsl_f assert 'InterlockedAnd' not in hlsl_f and 'InterlockedOr' not in hlsl_f assert ' store_format_d16_x(u0, ud2, ud3, ud4, v0, 0u, 0u, 4u, v5);' in hlsl_f, hlsl_f + dim_pos = hlsl_f.index('buf.GetDimensions(uav_bytes);') + store_guard_pos = hlsl_f.index('if ((addr & 3u) != 0u || uav_bytes < 4u || addr > uav_bytes - 4u) return;') + store_pos = hlsl_f.index('buf.Store(addr, asuint(f16tof32(h)));') + cas_guard_pos = hlsl_f.index('if (uav_bytes < 4u || base > uav_bytes - 4u) return;') + load_pos = hlsl_f.index('buf.Load(base)') + cas_pos = hlsl_f.index('buf.InterlockedCompareExchange(') + assert dim_pos < store_guard_pos < store_pos < cas_guard_pos < load_pos < cas_pos, ( + dim_pos, store_guard_pos, store_pos, cas_guard_pos, load_pos, cas_pos) hlsl_p = translate('P').hlsl_cs() assert ' store_format_d16_x(u0, ud2, ud3, ud4, 0u, v1, ud0, 2u, v5);' in hlsl_p, hlsl_p @@ -416,6 +461,9 @@ def check_controls(): hlsl_e = translate('E').hlsl_cs() assert 'if (exec & 1) store_format_d16_x(u0, ud2, ud3, ud4, v2, v3, 0u, 0u, v5);' in hlsl_e, hlsl_e + hlsl_b = translate('B').hlsl_cs() + assert ' store_format_d16_x(u0, ud2, ud3, ud4, 0u, v1, 0u, 0u, v5);' in hlsl_b, hlsl_b + # 'off' addressing mode with inline soffset=8 and offset:4 must keep soff=8u and imm_off=4u SEPARATE! store_f = '042010e200050480' off_store = encode_mubuf(MUBUF_STORE_FORMAT_D16_X, 5, 0, 16, 0x80 + 8, offset=4) @@ -528,53 +576,75 @@ def check_binary(llvm_mc): 'F-f32', ' store_format_d16_x(u0, ud2, ud3, ud4, v0, 0u, 0u, 4u, v5);\n', '', + None, ), 'f32-wrong-half': ( 'F-f32', ' uint h = val & 0xffffu;\n', ' uint h = (val >> 16u) & 0xffffu;\n', + None, ), 'f32-drop-oob': ( 'F-f32', ' if (idx >= num_records || elem_bytes > stride || rec_off > stride - elem_bytes) return;\n', ' if (elem_bytes > stride || rec_off > stride - elem_bytes) return;\n', + None, ), 'unorm16-trunc': ( 'F-unorm16', ' return (uint)floor(scaled + 0.5f);\n', ' return (uint)floor(scaled);\n', + None, ), 'p-drop-soffset': ( 'P', ' store_format_d16_x(u0, ud2, ud3, ud4, 0u, v1, ud0, 2u, v5);\n', ' store_format_d16_x(u0, ud2, ud3, ud4, 0u, v1, 0u, 2u, v5);\n', + None, ), 'p-drop-keep': ( 'P', ' uint next = (cur & keep) | ins;\n', ' uint next = ins;\n', + None, ), 's-fold-soff-stride': ( 'S', ' if (idx >= num_records || elem_bytes > stride || rec_off > stride - elem_bytes) return;\n', ' if (idx >= num_records || elem_bytes > stride || (rec_off + soff) > stride - elem_bytes) return;\n', + None, ), 'e-drop-exec': ( 'E', 'if (exec & 1) store_format_d16_x(', 'store_format_d16_x(', + None, + ), + 'b-short-binding': ( + 'B', + None, + None, + 1, + ), + 'b-tight-host-guard': ( + 'B', + ' if (uav_bytes < 4u || base > uav_bytes - 4u) return;\n', + ' if (uav_bytes < 4u || base > uav_bytes - 8u) return;\n', + None, ), } def mutate(hlsl, control): - _, old, new = CONTROLS[control] + _, old, new, _ = CONTROLS[control] + if old is None: + return hlsl assert hlsl.count(old) == 1, (control, hlsl) return hlsl.replace(old, new) -def run_case(name, dxc, runner, adapter, directory, control=None): - prog_key, source, constants, exp = case_inputs(name) +def run_case(name, dxc, runner, adapter, directory, control=None, uav_words=None): + prog_key, source, constants, exp, case_uav_words = case_inputs(name) hlsl = translate(prog_key).hlsl_cs() if control: hlsl = mutate(hlsl, control) @@ -588,7 +658,11 @@ def run_case(name, dxc, runner, adapter, directory, control=None): + struct.pack('<16I', *constants) + source ) - return subprocess.run([runner, adapter, '--compute-store-case', str(cso), str(case)], capture_output=True, text=True) + bound_uav_words = case_uav_words if uav_words is None else uav_words + cmd = [runner, adapter, '--compute-store-sized-case', str(cso), str(case)] + if bound_uav_words is not None: + cmd.append(str(bound_uav_words)) + return subprocess.run(cmd, capture_output=True, text=True) def check_dispatch(dxc, runner, adapter, control=None): @@ -596,9 +670,11 @@ def check_dispatch(dxc, runner, adapter, control=None): out = ROOT / 'out' out.mkdir(exist_ok=True) with tempfile.TemporaryDirectory(dir=out) as tmp: - runs = [(CONTROLS[control][0], control)] if control else [(name, None) for name in DISPATCH_CASES] - for name, mutation in runs: - run = run_case(name, dxc, runner, adapter, Path(tmp), mutation) + runs = [(CONTROLS[control][0], control, CONTROLS[control][3])] if control else [ + (name, None, None) for name in DISPATCH_CASES + ] + for name, mutation, uav_words in runs: + run = run_case(name, dxc, runner, adapter, Path(tmp), mutation, uav_words=uav_words) print(run.stdout, end='') if run.returncode == 77: return 77 @@ -607,10 +683,14 @@ def check_dispatch(dxc, runner, adapter, control=None): if mutation: if run.returncode != 1 or not any('expected=' in line for line in diagnostics): raise AssertionError('control %s: not rejected (exit %d) %s' % (mutation, run.returncode, run.stderr)) + if mutation in ('b-short-binding', 'b-tight-host-guard'): + assert diagnostics[0].startswith('word=1 '), (mutation, diagnostics) + assert 'debug_errors=0 debug_warnings=0' in run.stdout, (mutation, run.stdout) print('control %s: rejected at %s' % (mutation, diagnostics[0])) elif run.returncode or diagnostics: raise AssertionError('case %s: %s' % (name, run.stderr or 'exit %d' % run.returncode)) else: + assert 'debug_errors=0 debug_warnings=0' in run.stdout, (name, run.stdout) print('case %s: all %d words match' % (name, WORDS)) if not control: diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 81fb06d9dc..64910051ef 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -192,7 +192,7 @@ def strip_header(code): (2 << 3) | 7: 13, # DFMT_16 + NFMT_FLOAT (4 << 3) | 7: 22, # DFMT_32 + NFMT_FLOAT } -STORE_D16_X_WORD3_ZERO_MASK = 0xcef80000 +STORE_D16_X_WORD3_ZERO_MASK = 0xcef80000 # bits 31:30 TYPE | 27:25 reserved | 23 ADD_TID_ENABLE | 22:21 INDEX_STRIDE | 20:19 reserved def validate_store_d16_x_word3(word3): @@ -5389,9 +5389,11 @@ def common(self): ' if (soff > 0xffffffffu - elem_addr) return;', ' addr = elem_addr + soff;', ' }', + ' uint uav_bytes = 0u;', + ' buf.GetDimensions(uav_bytes);', ' uint h = val & 0xffffu;', ' if (fmt == 22u) {', - ' if ((addr & 3u) != 0u) return;', + ' if ((addr & 3u) != 0u || uav_bytes < 4u || addr > uav_bytes - 4u) return;', ' buf.Store(addr, asuint(f16tof32(h)));', ' return;', ' }', @@ -5400,6 +5402,7 @@ def common(self): ' if (fmt == 7u) out16 = d16_to_unorm16(h);', ' else if (fmt == 8u) out16 = d16_to_snorm16(h);', ' uint base = addr & 0xfffffffcu;', + ' if (uav_bytes < 4u || base > uav_bytes - 4u) return;', ' uint shift = (addr & 2u) << 3u;', ' uint keep = ~(0xffffu << shift);', ' uint ins = (out16 & 0xffffu) << shift;', From 9bdc73114e421407e81f13b13cf337ba5652aa42 Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 20:41:28 +0100 Subject: [PATCH 3/6] shader: lower compute buffer_store_format_xyzw in gfx2hlsl Refs #2274. Depends on #2478, whose descriptor, entry-constant, bounds and EXEC handling this reuses. Lowers compute MUBUF buffer_store_format_xyzw (0x07) in the idxen form with a non-negative inline soffset and optional offset:. FORMAT, stride and num_records are read at dispatch from uav_descword3, uav_stride and uav_numrecords, with the OOB_SELECT 0/3 bounds of buffer_store_format_d16_x (the bounds lines are checked identical). Only the 4-channel formats of tools/compute_store_aot.py write (32x4 UINT/FLOAT, 16x4 FLOAT through pack16_rne, 8_8_8_8 and 2_10_10_10 UNORM, unified and legacy encodings, identity DST_SEL); as in that tool, a format of another channel count writes nothing. offen, off, register soffset, cache/tfe/lds modifiers and non-compute stages are refused by name. Adds tests/startup_compute_store_format_xyzw_check.py, registered in CMakeLists.txt, .github/workflows/windows.yml and AGENTS.md, and a docs/experiments.md entry. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/windows.yml | 2 + AGENTS.md | 1 + CMakeLists.txt | 16 + docs/experiments.md | 16 + ...startup_compute_store_format_xyzw_check.py | 519 ++++++++++++++++++ tools/startup/gfx2hlsl.py | 157 ++++++ 6 files changed, 711 insertions(+) create mode 100644 tests/startup_compute_store_format_xyzw_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index ebd4659deb..00a65df180 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -96,6 +96,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"], {}), @@ -212,6 +213,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 c9f5762366..b4a5023f1a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -166,6 +166,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_mad_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_compute_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_image_2d_array_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 44662b8f88..a48130e3ee 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3412,6 +3412,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 19a1555aa5..47e76c6cfe 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -14248,6 +14248,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. 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`, non-compute stages and the descriptor cases refused for `d16_x` are refused by name. + +[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 20 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, all 20 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`). + +```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 (in the measured programs every store writes one value to all four components, which suggests a narrower target, so such stores would currently write nothing), `OOB_SELECT` 1, 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..409859140e --- /dev/null +++ b/tests/startup_compute_store_format_xyzw_check.py @@ -0,0 +1,519 @@ +#!/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; + 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'): + stage = G.Stage.__new__(G.Stage) + stage.kind = kind + refused('buffer_store_format_xyzw outside a compute stage', + lambda s=stage: s.op_buffer_store_format_xyzw(['v[4:7]', 'v0', 's[16:19]', '0'], ['idxen'])) + 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) + 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)) + data = 'uint4(%s)' % ', '.join(self.u('v%d' % n) for n in range(src[1], src[2] + 1)) + 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, self.u(ops[1]), 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) @@ -5669,6 +5768,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 @@ -5702,6 +5802,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 @@ -6017,6 +6118,62 @@ 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;', + ' 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): From ece5f059cfc5e9a11d12b8ccfbf2378f66d379b7 Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 20:49:33 +0100 Subject: [PATCH 4/6] shader: keep the unknown-op refusal for xyzw stores outside compute Outside a compute stage buffer_store_format_xyzw keeps the bare mnemonic, as buffer_store_format_d16_x and buffer_store_dword do. The index and data are evaluated before the UAV and its entry constants are registered. The experiments entry drops a claim about captured programs and names the prebuilt WARP runner. Co-Authored-By: Claude Opus 5.5 --- docs/experiments.md | 6 +++--- tests/startup_compute_store_format_xyzw_check.py | 10 +++++++--- tools/startup/gfx2hlsl.py | 7 ++++--- 3 files changed, 14 insertions(+), 9 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 47e76c6cfe..c15b501cfb 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -14250,9 +14250,9 @@ Not covered here: `llvm-mc-15` assembly step on Linux CI (`binary`), `OOB_SELECT ### 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. 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`, non-compute stages and the descriptor cases refused for `d16_x` are refused by name. +[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. 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 20 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, all 20 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 `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 20 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, all 20 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`). ```powershell . .\tools\dev.ps1 @@ -14262,7 +14262,7 @@ ctest --preset release --no-tests=error -j 1 -R "^startup_compute_store_format_x 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 (in the measured programs every store writes one value to all four components, which suggests a narrower target, so such stores would currently write nothing), `OOB_SELECT` 1, and runtime binding of the three entry constants. +Not covered here: hardware adapters, the `llvm-mc-15` `binary` step, formats with fewer than four channels (they write nothing), `OOB_SELECT` 1, and runtime binding of the three entry constants. ### First active lane at compute entry diff --git a/tests/startup_compute_store_format_xyzw_check.py b/tests/startup_compute_store_format_xyzw_check.py index 409859140e..0f5323f236 100644 --- a/tests/startup_compute_store_format_xyzw_check.py +++ b/tests/startup_compute_store_format_xyzw_check.py @@ -384,11 +384,15 @@ def check_controls(): ('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'): + for kind in ('ps', 'vs'): # outside compute: the unknown-op refusal, the bare mnemonic stage = G.Stage.__new__(G.Stage) stage.kind = kind - refused('buffer_store_format_xyzw outside a compute stage', - lambda s=stage: s.op_buffer_store_format_xyzw(['v[4:7]', 'v0', 's[16:19]', '0'], ['idxen'])) + 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 ( diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index bd8f07683f..9edcf7459b 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -3972,7 +3972,7 @@ def op_buffer_store_format_xyzw(self, ops, mods): """ name = 'buffer_store_format_xyzw' if self.kind != 'cs': - raise Unsupported('%s outside a compute stage' % name) + raise Unsupported(name) # the unknown-op refusal raw = getattr(self, 'raw_code', b'') pc = getattr(self, 'pc', None) if raw and pc is not None and pc + 8 <= len(raw): @@ -4011,15 +4011,16 @@ def op_buffer_store_format_xyzw(self, ops, mods): 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)) - data = 'uint4(%s)' % ', '.join(self.u('v%d' % n) for n in range(src[1], src[2] + 1)) 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, self.u(ops[1]), int(ops[3], 0), imm_offset or 0, data) + 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): From 41879f063157b34a4bd5387a9d0d3feaed792366 Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 20:58:46 +0100 Subject: [PATCH 5/6] shader: guard buffer_store_format_xyzw against host UAV bounds The xyzw helper now takes the host-view check that #2478 added to the d16_x helper: after the guest bounds and the alignment check it reads the bound view size with GetDimensions and drops an element that would pass its end. The expected helper text and the experiments entry follow; the entry also corrects the case count to 19. Co-Authored-By: Claude Opus 5.5 --- docs/experiments.md | 6 +++--- tests/startup_compute_store_format_xyzw_check.py | 3 +++ tools/startup/gfx2hlsl.py | 3 +++ 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index c15b501cfb..10238eb0bf 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -14250,9 +14250,9 @@ Not covered here: `llvm-mc-15` assembly step on Linux CI (`binary`), `OOB_SELECT ### 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. 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 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 20 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, all 20 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 `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, 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`). ```powershell . .\tools\dev.ps1 @@ -14262,7 +14262,7 @@ ctest --preset release --no-tests=error -j 1 -R "^startup_compute_store_format_x 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, and runtime binding of the three entry constants. +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 diff --git a/tests/startup_compute_store_format_xyzw_check.py b/tests/startup_compute_store_format_xyzw_check.py index 0f5323f236..a737f12da3 100644 --- a/tests/startup_compute_store_format_xyzw_check.py +++ b/tests/startup_compute_store_format_xyzw_check.py @@ -108,6 +108,9 @@ 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) { diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 9edcf7459b..ffdd55716c 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -6161,6 +6161,9 @@ def common(self): ' 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) {', From 3014c7b78b28d209b954b1924bf5e18d3e1fc220 Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 21:03:16 +0100 Subject: [PATCH 6/6] test: dispatch xyzw stores through sized descriptor-table views The helper reads the bound view size with GetDimensions, which has no defined result on a root descriptor. Dispatch through --compute-store-sized-case, as the d16_x check does. The experiments entry records which runner mode produced the local WARP result. Co-Authored-By: Claude Opus 5.5 --- docs/experiments.md | 2 +- tests/startup_compute_store_format_xyzw_check.py | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 10238eb0bf..d52d3c07c1 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -14252,7 +14252,7 @@ Not covered here: `llvm-mc-15` assembly step on Linux CI (`binary`), `OOB_SELECT [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, 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 `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 diff --git a/tests/startup_compute_store_format_xyzw_check.py b/tests/startup_compute_store_format_xyzw_check.py index a737f12da3..5886077dfd 100644 --- a/tests/startup_compute_store_format_xyzw_check.py +++ b/tests/startup_compute_store_format_xyzw_check.py @@ -486,7 +486,9 @@ def run_case(name, dxc, runner, adapter, directory, control=None): groups = PROGRAMS[prog][4] case.write_bytes(struct.pack('