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/3] 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/3] 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 f02b35cd99501abb4f93f9e57fdf746c177eae7a Mon Sep 17 00:00:00 2001 From: Vladimir <39053957+Vladimir-Human@users.noreply.github.com> Date: Wed, 25 Nov 2026 14:49:05 -0600 Subject: [PATCH 3/3] tests: allow unavailable D3D12 debug layer in startup_compute_store_d16_x_check When the optional Windows Graphics Tools debug layer is absent, keep word comparisons and mutant mismatch checks active while reporting `debug_layer=unavailable`; continue requiring zero errors/warnings whenever `debug_layer=enabled` is reported. --- tests/startup_compute_store_d16_x_check.py | 37 ++++++++++++++++++---- 1 file changed, 31 insertions(+), 6 deletions(-) diff --git a/tests/startup_compute_store_d16_x_check.py b/tests/startup_compute_store_d16_x_check.py index 1255ff5083..8dab1979b5 100644 --- a/tests/startup_compute_store_d16_x_check.py +++ b/tests/startup_compute_store_d16_x_check.py @@ -552,6 +552,21 @@ def check_controls(): finally: G.Stage.op_buffer_store_format_d16_x = saved + # 7. Debug-layer status handling (with and without Windows Graphics Tools). + assert _check_debug_layer('backend=hardware debug_layer=enabled\ndebug_errors=0 debug_warnings=0\n', 'unit-ok') == 'debug_errors=0 debug_warnings=0' + assert _check_debug_layer('backend=hardware debug_layer=unavailable\n', 'unit-unavail') == 'debug_layer=unavailable' + for bad_out in ( + 'backend=hardware debug_layer=enabled\ndebug_errors=1 debug_warnings=0\n', + 'backend=hardware debug_layer=enabled\n', + 'backend=hardware\ndebug_errors=0 debug_warnings=0\n', + ): + try: + _check_debug_layer(bad_out, 'unit-fail') + except AssertionError: + pass + else: + raise AssertionError('unexpectedly accepted debug output: %r' % (bad_out,)) + print('buffer_store_format_d16_x unit, format, bounds, CAS, provenance and refusal checks pass') @@ -665,6 +680,15 @@ def run_case(name, dxc, runner, adapter, directory, control=None, uav_words=None return subprocess.run(cmd, capture_output=True, text=True) +def _check_debug_layer(stdout, label): + if 'debug_layer=enabled' in stdout: + assert 'debug_errors=0 debug_warnings=0' in stdout, (label, stdout) + return 'debug_errors=0 debug_warnings=0' + if 'debug_layer=unavailable' in stdout: + return 'debug_layer=unavailable' + raise AssertionError((label, 'missing debug_layer status', stdout)) + + def check_dispatch(dxc, runner, adapter, control=None): runner = str(Path(runner).resolve()) out = ROOT / 'out' @@ -683,15 +707,16 @@ 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)) + suffix = '' 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])) + suffix = ' (%s)' % _check_debug_layer(run.stdout, mutation) + print('control %s: rejected at %s%s' % (mutation, diagnostics[0], suffix)) 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)) + debug_note = _check_debug_layer(run.stdout, name) + print('case %s: all %d words match (%s)' % (name, WORDS, debug_note)) if not control: # Case C: same-halfword concurrent contention (256 threads x 4 writes to both halves of dword 0). @@ -702,7 +727,7 @@ def check_dispatch(dxc, runner, adapter, control=None): return 77 diagnostics = [line for line in run.stderr.splitlines() if not (adapter == 'hardware' and line.startswith('XBOX2WINDOWS_ADAPTER: skipping '))] - assert 'debug_errors=0 debug_warnings=0' in run.stdout, run.stdout + debug_note = _check_debug_layer(run.stdout, 'C') assert 'mismatches=1' in run.stdout, (run.stdout, diagnostics) m = re.fullmatch(r'word=0 expected=deadbeef actual=([0-9a-f]{8})', diagnostics[0] if diagnostics else '') assert m, (diagnostics, run.stdout) @@ -710,7 +735,7 @@ def check_dispatch(dxc, runner, adapter, control=None): lo, hi = actual & 0xffff, (actual >> 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) + print('case C: atomic CAS contention ok (word0=0x%08x, 319 sentinels untouched, %s)' % (actual, debug_note)) return 0