diff --git a/CMakeLists.txt b/CMakeLists.txt index 1d3ee56d1b..7ea0791ce8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -9979,6 +9979,11 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter}) set_tests_properties(compute_store_aot_descriptor_load_format_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + add_test(NAME compute_store_aot_descriptor_load_format_d16_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/compute_load_format_check.py" draw-d16 "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(compute_store_aot_descriptor_load_format_d16_${adapter} PROPERTIES TIMEOUT 120 + SKIP_RETURN_CODE 77) add_test(NAME compute_store_aot_heap_view_load_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/compute_heap_view_check.py" draw "${DXC_EXECUTABLE}" "$" ${adapter}) diff --git a/README.md b/README.md index a82343fc15..b0e70f346e 100644 --- a/README.md +++ b/README.md @@ -168,7 +168,7 @@ The control-flow CPU translator supports [source-built string memory transfers]( | gfx1030 formatted UINT buffer reads | Lower [indexed `buffer_load_format_*` with caller-declared RGBA32 UINT](docs/experiments.md#indexed-gfx1030-formatted-uint-buffer-reads) and verify one to four channels in the UAV readback. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_format_'` | | gfx1030 formatted D16 UINT writes | Lower [indexed packed `buffer_store_format_d16_x/xy/xyzw`](docs/experiments.md#indexed-gfx1030-formatted-d16-uint-buffer-writes) and verify the untouched halfword and record padding. The experimental `xyz` form requires a caller-verified W-preservation contract. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_store_format_'` | | gfx1030 formatted UINT buffer writes | Lower [indexed `buffer_store_format_*` with matching caller-declared UINT texels](docs/experiments.md#indexed-gfx1030-formatted-uint-buffer-writes) and compare full UAV readback with a CPU reference. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_store_format_'` | -| Descriptor-format buffer loads | Lower [gfx1013 indexed `buffer_load_format_x/xy/xyz/xyzw`](docs/experiments.md#descriptor-format-buffer-loads), reading the GFX10 or legacy format from V# word 3 at run time with integer-exact conversions. An unsupported format or opcode width leaves the output unwritten. The descriptor itself is still static. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_descriptor_load_format_'` | +| Descriptor-format buffer loads | Lower [gfx1013 indexed `buffer_load_format_x/xy/xyz/xyzw` and the d16 forms](docs/experiments.md#descriptor-format-buffer-loads), reading the GFX10 or legacy format from V# word 3 at run time with integer-exact conversions. An unsupported format or opcode width leaves the output unwritten. The descriptor itself is still static. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_descriptor_load_format_'` | | Heap-view buffer loads | Lower [gfx1013 indexed `buffer_load_format_xy/xyzw` from a run-time view record](docs/experiments.md#heap-view-buffer-loads): base, stride, `num_records` and format come from the record at a chosen slot. An index past `num_records` reads zero; a view that is not live, a bad slot or a bad format leaves the output unwritten. The record table is a side table inside t0; the SM 6.6 heap lookup is not wired yet. | `ctest --preset dev --no-tests=error -R '^compute_(store_aot_heap_view_load_\|heap_view_controls$)'` | | Descriptor-format buffer stores | Lower [indexed `buffer_store_format_x/xy/xyz/xyzw` and the d16 forms](docs/experiments.md#descriptor-format-buffer-stores), reading the GFX10 or legacy format from V# word 3. Unknown formats are refused. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_descriptor_store_format_'` | | gfx1030 depth-comparison sampling | Lower [2D comparison samples with and without offsets](docs/experiments.md#gfx1030-2d-comparison-sampling). | `ctest --preset dev --no-tests=error -R '^pixel_aot_compare_sample_' -V` | diff --git a/docs/experiments.md b/docs/experiments.md index 6cb1d14599..ff3ed6391d 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -6226,7 +6226,6 @@ The gfx1013 compute store profile lowers `buffer_load_format_x`, `_xy`, `_xyz` a This is the format decoder of item A of #2022. The descriptor still comes from the static table offset (`--source-descriptor`, `--source-stride`). Taking the descriptor from a run-time view record is the [next slice](#heap-view-buffer-loads), so this alone does not count as coverage of any application dispatch. The address is `idxen` only and 4-byte aligned, and four bytes per opcode channel must fit inside the stated stride. These stay refused with this flag: -- the `d16_` forms; - `offen`; - gfx1030; - `--source-format`. @@ -6299,6 +6298,35 @@ one D3D12 device, root signature and pipeline. Each case gets fresh buffers, sub compares all 320 words after the fence. The renderer reports `pass`, `mismatch` or `error` for each case and exits with status 1 if any case fails. The eleven shader mutations still compile and dispatch separately. +#### d16 forms + +`buffer_load_format_d16_x`, `_xy`, `_xyz` and `_xyzw` use the same format word, validity rule and refusal, and pack two 16-bit channels per result word, x in the low half. The format's type decides the 16-bit value: +- **FLOAT16 formats:** the stored halves, unchanged. +- **UNORM and SNORM16:** binary16 of the value above (`x / (2^n - 1)` or `max(x / 32767, -1)`), rounded to nearest even by long division. Binary16 denormals are kept, so `1/65535` is `0x0100`. +- **16-bit UINT and SINT:** the 16-bit integer, not a float. +- **32-bit formats:** no d16 rule is established here, so `32_UINT` and `32_FLOAT` in one to four channels are invalid under d16 and publish nothing. + +Whether the RDNA format unit rounds the same way, or keeps binary16 denormals, is not verified. + +An odd channel count leaves the high half of the last result word undefined. That word is low-16 only: it reaches a whole-word store or an ALU operand only through `v_and_b32 0xffff`, as for the existing caller-format D16 reads. + +The d16 fixture makes ten loads over the same t0 words, one per format with a d16 rule, and stores them in a 64-byte u0 record. The checks: +- **Readback:** WARP and the hardware adapter compare all 320 words for one group and for two. +- **Invalid formats:** three runs each make one load invalid, and each must leave u0 unwritten. They use `32_32_FLOAT` under `d16_xy`, `16_16_UNORM` under `d16_x`, and `8_SNORM`. +- **Wrong references:** on the two-group run, each of these must fail at its first differing word: + - truncated binary16, and flushed binary16 denormals; + - 16-bit UINT converted like 16-bit UNORM, and 16-bit SINT converted like 16-bit SNORM; + - halves packed high first; + - the legacy word ignored; + - the neighbouring thread's element. +- **Mutated HLSL:** each of these must also fail: + - a binary16 ratio that never rounds up, and flushed binary16 denormals; + - the two integer formats converted; + - halves packed high first, and the SNORM16 half sign dropped; + - the binary32 conversion used under d16; + - on the invalid runs, a 32-bit format accepted under d16, and the refusal removed. +- **Translation controls:** they reject the odd half when the mask is missing, when an ALU operation uses it, and when the destination range is too wide. With the d16 flag dropped, the low-half marking removed, or 32-bit formats given a d16 arm, they fail. + ```powershell cmake --build --preset dev --target offscreen_check ctest --preset dev --no-tests=error -R '^compute_(store_aot_descriptor_load_format_|load_format_controls$)' -V diff --git a/tests/compute_load_format_check.py b/tests/compute_load_format_check.py index 90ba550ee2..ddc297c865 100644 --- a/tests/compute_load_format_check.py +++ b/tests/compute_load_format_check.py @@ -2,6 +2,7 @@ The t0 format is V# word 3, read from a constant word at run time (--load-format-constant), as the descriptor-format stores read theirs. The case file supplies the t0 words, so each format sees chosen edge values. +Two suites share the t0 layout: binary32 results (draw) and d16 results packed two per word (draw-d16). """ from concurrent.futures import ThreadPoolExecutor from fractions import Fraction @@ -21,6 +22,7 @@ GROUP = (4, 1, 1) SOURCE_STRIDE = 80 OUTPUT_STRIDE = 120 +D16_STRIDE = 64 THREADS = 8 # opcode suffix, t0 byte offset, GFX10 format code, legacy word 3, u0 byte offset of the results. LOADS = ( @@ -39,7 +41,20 @@ ("x", 68, 20, False, 108), # 32_UINT ("xy", 72, 64, False, 112), # 32_32_FLOAT ) -# Format words that make one load invalid: load index, V# word 3. Each must leave every u0 word unwritten. +# The same t0 fields through the d16 opcodes. Every format with a d16 rule appears once. +D16_LOADS = ( + ("d16_xyzw", 0, 56, False, 0), # 8_8_8_8_UNORM + ("d16_xy", 4, 23, False, 8), # 16_16_UNORM + ("d16_xyzw", 8, 50, False, 12), # 2_10_10_10_UNORM + ("d16_xy", 12, 29, True, 20), # 16_16_FLOAT, legacy + ("d16_xyzw", 16, 71, False, 24), # 16_16_16_16_FLOAT + ("d16_x", 24, 7, False, 32), # 16_UNORM + ("d16_x", 28, 8, False, 36), # 16_SNORM + ("d16_x", 32, 11, False, 40), # 16_UINT + ("d16_x", 36, 12, False, 44), # 16_SINT + ("d16_x", 40, 13, False, 48), # 16_FLOAT +) +# Format words that make one load invalid: label, load index, V# word 3. Each must leave every u0 word unwritten. IDENTITY_32_UINT = aot.descriptor_format_word(20) INVALID = ( ("unknown format 8_SNORM", 0, aot.DESCRIPTOR_GFX10_FIXED | (2 << 12)), @@ -49,6 +64,11 @@ # 10_10_10_2_UNORM has a 2-bit x in bits 1:0; only the 2_10_10_10 layout is handled. ("10_10_10_2_UNORM", 2, aot.DESCRIPTOR_GFX10_FIXED | (44 << 12)), ) +D16_INVALID = ( + ("d16_xy on 32_32_FLOAT", 1, aot.descriptor_format_word(64)), + ("d16_x on 16_16_UNORM", 5, aot.descriptor_format_word(23)), + ("unknown format 8_SNORM", 0, aot.DESCRIPTOR_GFX10_FIXED | (2 << 12)), +) # Thread 0-3 t0 words: edge values per field. Threads 4-7 are pseudo-random. CURATED = ( (0x8001ff00, 0x0001ffff, 0xa00007ff, 0x80000001, 0xfc007c00, 0x7bff7e01, 0xdeadffff, 0x12348000, 0xabcdffff, @@ -79,6 +99,15 @@ def source_words(): return words + [base.SENTINEL] * (320 - len(words)) +def _exponent(value): + exponent = value.numerator.bit_length() - value.denominator.bit_length() + while value >= Fraction(2) ** exponent * 2: + exponent += 1 + while value < Fraction(2) ** exponent: + exponent -= 1 + return exponent + + def f32_bits(value): """binary32 bits of a Fraction or exact value, rounded to nearest even (no double rounding).""" value = Fraction(value) @@ -86,11 +115,7 @@ def f32_bits(value): return 0 sign = 0x80000000 if value < 0 else 0 value = abs(value) - exponent = value.numerator.bit_length() - value.denominator.bit_length() - while value >= Fraction(2) ** exponent * 2: - exponent += 1 - while value < Fraction(2) ** exponent: - exponent -= 1 + exponent = _exponent(value) assert -126 <= exponent < 128, value mantissa = round(value / Fraction(2) ** (exponent - 23)) if mantissa == 1 << 24: @@ -98,6 +123,25 @@ def f32_bits(value): return sign | ((exponent + 127) << 23) | (mantissa - (1 << 23)) +def f16_bits(value, *, truncate=False, flush=False): + """binary16 bits of a Fraction in [-1, 1], rounded to nearest even, denormals kept (IEEE 754 rounding).""" + value = Fraction(value) + if value == 0: + return 0 + sign = 0x8000 if value < 0 else 0 + value = abs(value) + exponent = _exponent(value) + rounding = (lambda q: int(q)) if truncate else round + if exponent < -14: + if flush: + return sign + return sign | rounding(value / Fraction(2) ** -24) # a carry to 0x400 is the smallest normal + mantissa = rounding(value / Fraction(2) ** (exponent - 10)) + if mantissa == 1 << 11: + mantissa, exponent = 1 << 10, exponent + 1 + return sign | ((exponent + 15) << 10) | (mantissa - (1 << 10)) + + def half_to_f32(half): """IEEE 754 widening of binary16: exact for numbers; a NaN keeps its payload (IEEE 754-2008 6.2.3).""" sign, exponent, mantissa = (half >> 15) & 1, (half >> 10) & 31, half & 0x3ff @@ -126,7 +170,7 @@ def snorm16(half, *, clamp=True): def load(code, words, channels, *, wrong=()): - """Independent reference for one load: the definition of each format, from the t0 words at its offset. + """Independent reference for one binary32 load: the definition of each format, from the t0 words at its offset. The profile handles an opcode that reads exactly the format's channels; anything else is a refusal. """ @@ -162,31 +206,82 @@ def load(code, words, channels, *, wrong=()): return result[:channels] -def expected_words(groups, *, wrong=(), source=None, placeholder=None): - """u0 after a valid dispatch. placeholder=(load index, words) publishes those words for that load instead.""" - source = source or source_words() - words = [base.SENTINEL] * 320 - for thread in range(GROUP[0] * groups): - index = thread + 1 if "neighbour element" in wrong else thread - element = source[index * SOURCE_STRIDE // 4:(index + 1) * SOURCE_STRIDE // 4] - for number, (suffix, src, code, legacy, dst) in enumerate(LOADS): - if placeholder and placeholder[0] == number: - values = placeholder[1](element[src // 4:]) - elif legacy and "legacy ignored" in wrong: - values = [0] * len(suffix) - else: - values = load(code, element[src // 4:], len(suffix), wrong=wrong) - start = (thread * OUTPUT_STRIDE + dst) // 4 - words[start:start + len(values)] = values - return words - +def load_d16(code, words, channels, *, wrong=()): + """Independent reference for one d16 load: binary16 for float-type formats, the 16-bit integer for UINT and + SINT, packed two per word with x low. An odd final half is stored masked to its low 16 bits.""" + _code, kind, format_channels = aot.decode_buffer_descriptor_format(aot.descriptor_format_word(code)) + assert channels == format_channels and kind != "raw32", (code, channels) + w = words[0] + rounding = dict(truncate="half truncated" in wrong, flush="flush halves" in wrong) -def constants(): - words = [aot.descriptor_format_word(code, legacy=legacy) for _s, _o, code, legacy, _d in LOADS] - return words + [0] * (16 - len(words)) + def ratio(x, d): + return f16_bits(Fraction(x, d), **rounding) + def snorm(h): + value = h - 0x10000 if h & 0x8000 else h + return 0xbc00 if value <= -32767 else f16_bits(Fraction(value, 32767), **rounding) -def program(): + if kind == "unorm8": + halves = [ratio((w >> (8 * i)) & 0xff, 255) for i in range(4)] + elif kind == "unorm16x2": + halves = [ratio(w & 0xffff, 65535), ratio(w >> 16, 65535)] + elif kind == "unorm10": + halves = [ratio((w >> (10 * i)) & 0x3ff, 1023) for i in range(3)] + [ratio(w >> 30, 3)] + elif kind == "f16x2": + halves = [w & 0xffff, w >> 16] + elif kind == "f16x4": + halves = [w & 0xffff, w >> 16, words[1] & 0xffff, words[1] >> 16] + elif kind == "unorm16": + halves = [ratio(w & 0xffff, 65535)] + elif kind == "snorm16": + halves = [snorm(w & 0xffff)] + elif kind == "uint16": + halves = [ratio(w & 0xffff, 65535) if "integer as unorm" in wrong else w & 0xffff] + elif kind == "sint16": + halves = [snorm(w & 0xffff) if "integer as snorm" in wrong else w & 0xffff] + else: + halves = [w & 0xffff] + if "pack high first" in wrong: + halves = [h for pair in zip(halves[1::2], halves[0::2]) for h in pair] + halves[len(halves) & ~1:] + return [halves[i] | ((halves[i + 1] if i + 1 < len(halves) else 0) << 16) for i in range(0, len(halves), 2)] + + +class Suite: + def __init__(self, name, loads, stride, model, invalid, wrong, mutations): + self.name, self.loads, self.stride, self.model = name, loads, stride, model + self.invalid, self.wrong, self.mutations = invalid, wrong, mutations + self.lines, self.binding = program(loads, stride) + + def expected(self, groups, *, wrong=(), placeholder=None): + """u0 after a valid dispatch. placeholder=(load index, function) publishes other words for that load.""" + source = source_words() + words = [base.SENTINEL] * 320 + for thread in range(GROUP[0] * groups): + index = thread + 1 if "neighbour element" in wrong else thread + element = source[index * SOURCE_STRIDE // 4:(index + 1) * SOURCE_STRIDE // 4] + for number, (suffix, src, code, legacy, dst) in enumerate(self.loads): + channels = len(suffix.removeprefix("d16_")) + if placeholder and placeholder[0] == number: + values = placeholder[1](element[src // 4:]) + elif legacy and "legacy ignored" in wrong: + values = [0] * registers(suffix) + else: + values = self.model(code, element[src // 4:], channels, wrong=wrong) + start = (thread * self.stride + dst) // 4 + words[start:start + len(values)] = values + return words + + def constants(self): + words = [aot.descriptor_format_word(code, legacy=legacy) for _s, _o, code, legacy, _d in self.loads] + return words + [0] * (16 - len(words)) + + +def registers(suffix): + channels = len(suffix.removeprefix("d16_")) + return (channels + 1) // 2 if suffix.startswith("d16_") else channels + + +def program(loads, stride): lines = [ "s_mov_b32 s12, s7", "s_mov_b32 s13, 0", "s_load_dwordx4 s[20:23], s[12:13], 0x30", @@ -200,36 +295,35 @@ def program(): "s_buffer_load_dwordx2 s[36:37], s[16:19], 0x30", "s_waitcnt lgkmcnt(0)", ] - reg, stores = 10, [] - for suffix, src, _code, _legacy, dst in LOADS: - n = len(suffix) + reg, masks, stores = 10, [], [] + for suffix, src, _code, _legacy, dst in loads: + n = registers(suffix) regs = f"v{reg}" if n == 1 else f"v[{reg}:{reg + n - 1}]" lines.append(f"buffer_load_format_{suffix} {regs}, v8, s[40:43], 0 idxen" + (f" offset:{src}" if src else "")) + if suffix.startswith("d16_") and len(suffix) % 2: + # An odd d16 count leaves the high half of the last word undefined; keep only the low half. + last = reg + n - 1 + masks.append(f"v_and_b32_e32 v{last}, 0xffff, v{last}") width = "" if n == 1 else f"x{n}" stores.append(f"buffer_store_dword{width} {regs}, v8, s[20:23], 0 idxen" + (f" offset:{dst}" if dst else "")) reg += n - lines += ["s_waitcnt vmcnt(0)", *stores, "s_endpgm"] + lines += ["s_waitcnt vmcnt(0)", *masks, *stores, "s_endpgm"] binding = dict(table_reg=7, descriptor_offset=0x30, constant_descriptor=0x40, source_descriptor=0x50, - source_stride=SOURCE_STRIDE, group_reg=11, stride=OUTPUT_STRIDE, cpu="gfx1013", - load_format_constant=tuple(range(len(LOADS)))) + source_stride=SOURCE_STRIDE, group_reg=11, stride=stride, cpu="gfx1013", + load_format_constant=tuple(range(len(loads)))) return lines, binding -LINES, BINDING = program() -FIRST_LOAD = (" bool format_valid_0;\n" - " uint4 format_load_0 = load_descriptor_format(params[0].x, tid.x * 80u + 0u, 4u, format_valid_0);") -FIRST_STORE = (" outputData.Store4(tid.x * 120u + 0u, uint4(format_load_0.x, format_load_0.y, format_load_0.z, " - "format_load_0.w));") -LAST_LOAD = " uint4 format_load_13 = load_descriptor_format(params[3].y, tid.x * 80u + 72u, 2u, format_valid_13);" -REFUSE = " if (!(" + " && ".join(f"format_valid_{i}" for i in range(len(LOADS))) + ")) return;" -WRONG = (("UNORM divided by 2^n", ("unorm divisor",)), ("UNORM truncated", ("unorm truncated",)), - ("SNORM without the clamp", ("snorm unclamped",)), ("SINT16 zero-extended", ("sint zero-extended",)), - ("FLOAT16 halves swapped", ("swap halves",)), ("FLOAT16 denormals flushed", ("flush halves",)), - ("legacy format ignored", ("legacy ignored",)), ("neighbouring element", ("neighbour element",))) # Independent launches (the mutation ones also compile a mutated source); the Win2025 slots have 11 vCPUs. LAUNCH_THREADS = 6 FIXED = f"{aot.DESCRIPTOR_LEGACY_FIXED:#x}u" -# label, old, new, and the run it must fail: None for the valid two-group run, else an INVALID index. + + +def refuse_line(count): + return " if (!(" + " && ".join(f"format_valid_{i}" for i in range(count)) + ")) return;" + + +# label, old, new, and the run it must fail: None for the valid two-group run, else an invalid-run index. MUTATIONS = ( ("ratio never rounds up", " if ((bits & 1u) != 0u && (r != 0u || (result & 1u) != 0u)) ++result;\n", "", None), ("denormal halves flushed", " if (m == 0u) return sign;\n", " return sign;\n", None), @@ -239,76 +333,139 @@ def program(): ("SINT16 zero-extended", "(uint)((int)(raw.x << 16u) >> 16u)", "(raw.x & 0xffffu)", None), ("legacy fixed bits ignored", f"}} else if (fixedBits == {FIXED}) {{", "} else if (false) {", None), ("format word from params[0].y", "load_descriptor_format(params[0].x,", "load_descriptor_format(params[0].y,", None), - ("invalid loads still store", REFUSE, "", 0), + ("invalid loads still store", refuse_line(len(LOADS)), "", 0), ("narrower opcode accepted", "format == 77u) && channels == 4u)", "format == 77u) && channels <= 4u)", 1), ("wider opcode accepted", "format == 22u) && channels == 1u)", "format == 22u) && channels >= 1u)", 2), ("selectors ignored", f"uint fixedBits = formatWord & {aot.DESCRIPTOR_FIXED_MASK:#x}u;", f"uint fixedBits = formatWord & {aot.DESCRIPTOR_FIXED_MASK & ~0xfff:#x}u | 0xfacu;", 3), ) +D16_MUTATIONS = ( + ("binary16 ratio never rounds up", + " if (roundBit != 0u && (sticky || (result & 1u) != 0u)) ++result;\n", "", None), + ("binary16 denormals flushed", " : (f >> shift);\n", " : 0u;\n", None), + ("16_UINT converted like 16_UNORM", "(format == 11u) && channels == 1u) { h.x = raw.x & 0xffffu;", + "(format == 11u) && channels == 1u) { h.x = descriptor_ratio16(raw.x & 0xffffu, 65535u);", None), + ("16_SINT converted like 16_SNORM", "(format == 12u) && channels == 1u) { h.x = raw.x & 0xffffu;", + "(format == 12u) && channels == 1u) { h.x = descriptor_snorm16_half(raw.x & 0xffffu);", None), + ("halves packed high first", "r = uint4(h.x | (h.y << 16u), h.z | (h.w << 16u), 0u, 0u);", + "r = uint4(h.y | (h.x << 16u), h.w | (h.z << 16u), 0u, 0u);", None), + ("SNORM16 half sign dropped", "0x8000u | descriptor_ratio16(", "descriptor_ratio16(", None), + ("binary32 conversion under d16", "(d16 != 0u && (format == 23u)", "(d16 == 0u && (format == 23u)", None), + ("32-bit format accepted under d16", "(d16 == 0u && (format == 62u || format == 64u) && channels == 2u)", + "(true && (format == 62u || format == 64u) && channels == 2u)", 0), + ("invalid loads still store", refuse_line(len(D16_LOADS)), "", 2), +) +SUITES = { + "draw": Suite(NAME, LOADS, OUTPUT_STRIDE, load, INVALID, ( + ("UNORM divided by 2^n", ("unorm divisor",)), ("UNORM truncated", ("unorm truncated",)), + ("SNORM without the clamp", ("snorm unclamped",)), ("SINT16 zero-extended", ("sint zero-extended",)), + ("FLOAT16 halves swapped", ("swap halves",)), ("FLOAT16 denormals flushed", ("flush halves",)), + ("legacy format ignored", ("legacy ignored",)), ("neighbouring element", ("neighbour element",))), + MUTATIONS), + "draw-d16": Suite(NAME + "_d16", D16_LOADS, D16_STRIDE, load_d16, D16_INVALID, ( + ("binary16 truncated", ("half truncated",)), ("binary16 denormals flushed", ("flush halves",)), + ("16_UINT converted like 16_UNORM", ("integer as unorm",)), + ("16_SINT converted like 16_SNORM", ("integer as snorm",)), + ("halves packed high first", ("pack high first",)), ("legacy format ignored", ("legacy ignored",)), + ("neighbouring element", ("neighbour element",))), + D16_MUTATIONS), +} +LINES, BINDING = SUITES["draw"].lines, SUITES["draw"].binding +D16_LINES, D16_BINDING = SUITES["draw-d16"].lines, SUITES["draw-d16"].binding +FIRST_LOAD = (" bool format_valid_0;\n" + " uint4 format_load_0 = load_descriptor_format(params[0].x, tid.x * 80u + 0u, 4u, 0u, format_valid_0);") +FIRST_STORE = (" outputData.Store4(tid.x * 120u + 0u, uint4(format_load_0.x, format_load_0.y, format_load_0.z, " + "format_load_0.w));") +LAST_LOAD = (" uint4 format_load_13 = load_descriptor_format(params[3].y, tid.x * 80u + 72u, 2u, 0u, " + "format_valid_13);") +D16_FIRST_LOAD = " uint4 format_load_0 = load_descriptor_format(params[0].x, tid.x * 80u + 0u, 4u, 1u, format_valid_0);" +D16_ODD_STORE = " outputData.Store(tid.x * 64u + 32u, (format_load_5.x & 0xffffu));" def lower(lines=None, **binding): return aot.lower(LINES if lines is None else lines, GROUP, **(BINDING | binding)) +def lower_d16(lines=None, **binding): + return aot.lower(D16_LINES if lines is None else lines, GROUP, **(D16_BINDING | binding)) + + def controls(): """Exact staged loads and stores, model checks, then one rejection per form outside the profile.""" assert f32_bits(Fraction(1, 255)) == 0x3b808081 and f32_bits(Fraction(128, 255)) == 0x3f008081 assert unorm(1, 16) == 0x37800080 and unorm(2, 2) == 0x3f2aaaab and snorm16(0x8000) == 0xbf800000 assert snorm16(0x8000, clamp=False) == 0xbf800100 and snorm16(0xffff) == 0xb8000100 assert half_to_f32(0x0001) == 0x33800000 and half_to_f32(0x03ff) == 0x387fc000 and half_to_f32(0x7e01) == 0x7fc02000 + # binary16: 100/1023 rounds up, 1/65535 and -1/32767 are denormals, and 1/3 rounds down. + assert f16_bits(Fraction(1, 255)) == 0x1c04 and f16_bits(Fraction(128, 255)) == 0x3804 + assert f16_bits(Fraction(1, 65535)) == 0x0100 and f16_bits(Fraction(1, 3)) == 0x3555 + assert f16_bits(Fraction(100, 1023)) == 0x2e42 and f16_bits(Fraction(100, 1023), truncate=True) == 0x2e41 + assert f16_bits(Fraction(-1, 32767)) == 0x8200 and f16_bits(Fraction(1, 65535), flush=True) == 0 source = lower() lines = source.splitlines() + refuse = refuse_line(len(LOADS)) assert source.count("= load_descriptor_format(") == len(LOADS) - assert FIRST_LOAD in source and LAST_LOAD in lines and FIRST_STORE in lines and REFUSE in lines, source + assert FIRST_LOAD in source and LAST_LOAD in lines and FIRST_STORE in lines and refuse in lines, source assert "outputData.Store(tid.x * 120u + 108u, format_load_12.x);" in source assert "outputData.Store2(tid.x * 120u + 112u, uint2(format_load_13.x, format_load_13.y));" in source # Every load and the refusal come before the first store. - assert lines.index(LAST_LOAD) < lines.index(REFUSE) < lines.index(FIRST_STORE) + assert lines.index(LAST_LOAD) < lines.index(refuse) < lines.index(FIRST_STORE) assert "&& channels == 4u) {" in source and "channels <=" not in source and "valid = false;" in source # Without the load constants the profile keeps the gfx1030 caller-format path and refuses gfx1013. base.rejects("Unsupported formatted buffer read target or address mode", lower, load_format_constant=None) for _name, old_lines, old_binding in base.mubuf_format_cases(): old = aot.lower(old_lines, 32, **old_binding) assert "load_descriptor_format(" not in old and "inputData.Load" in old and " return;" not in old + # d16: the flag reaches the helper, the odd final half is masked before a whole-word store, and no 32-bit + # format has a d16 arm. + d16 = lower_d16() + assert D16_FIRST_LOAD in d16 and D16_ODD_STORE in d16 and refuse_line(len(D16_LOADS)) in d16, d16 + assert "outputData.Store2(tid.x * 64u + 0u, uint2(format_load_0.x, format_load_0.y));" in d16 + assert "(d16 != 0u && (format == 20u" not in d16 and "(d16 != 0u && (format == 56u)" in d16 xyzw = LINES[12] assert xyzw == "buffer_load_format_xyzw v[10:13], v8, s[40:43], 0 idxen", xyzw + d16x = D16_LINES[17] + assert d16x == "buffer_load_format_d16_x v18, v8, s[40:43], 0 idxen offset:24", d16x + mask = "v_and_b32_e32 v18, 0xffff, v18" wait = LINES.index("s_waitcnt lgkmcnt(0)", 7) - for message, lines_, binding in ( - ("Descriptor-format d16 loads are not lowered", - base.variant(LINES, (xyzw, "buffer_load_format_d16_xyzw v[10:11], v8, s[40:43], 0 idxen")), {}), - ("Descriptor-format d16 loads are not lowered", - base.variant(LINES, (xyzw, "buffer_load_format_d16_x v10, v8, s[40:43], 0 idxen")), {}), - ("Unsupported formatted buffer read target or address mode", + for message, function, lines_, binding in ( + # The odd d16 half is low-16 only: stored or used without the mask, it is not a known word. + ("Store data is not a known word", lower_d16, base.variant(D16_LINES, (mask, "")), {}), + ("Unverified ALU operand", lower_d16, base.variant(D16_LINES, (mask, "v_xor_b32_e32 v18, 1, v18")), {}), + ("Unverified buffer read destination", lower_d16, base.variant(D16_LINES, (d16x, d16x.replace("v18,", "v[18:19],"))), {}), + ("Unsupported formatted buffer read target or address mode", lower, base.variant(LINES, (xyzw, xyzw.replace(" idxen", " offen"))), {}), - ("Unsupported formatted buffer read target or address mode", + ("Unsupported formatted buffer read target or address mode", lower, base.variant(LINES, (xyzw, xyzw.replace(" idxen", ""))), {}), - ("Unverified read offset", base.variant(LINES, (xyzw, xyzw + " offset:2")), {}), - ("Read leaves its source element", base.variant(LINES, (xyzw, xyzw + " offset:68")), {}), - ("Unsupported compute instruction", base.variant(LINES, (xyzw, xyzw + " glc")), {}), - ("Formatted buffer load is missing a format constant", None, dict(load_format_constant=(0,))), - ("Unused buffer load format constant", None, dict(load_format_constant=tuple(range(len(LOADS) + 1)))), - ("Formatted buffer load format constant is not ready", None, + ("Unverified read offset", lower, base.variant(LINES, (xyzw, xyzw + " offset:2")), {}), + ("Read leaves its source element", lower, base.variant(LINES, (xyzw, xyzw + " offset:68")), {}), + ("Unsupported compute instruction", lower, base.variant(LINES, (xyzw, xyzw + " glc")), {}), + ("Formatted buffer load is missing a format constant", lower, None, dict(load_format_constant=(0,))), + ("Unused buffer load format constant", lower, None, dict(load_format_constant=tuple(range(len(LOADS) + 1)))), + ("Formatted buffer load format constant is not ready", lower, None, dict(load_format_constant=(15,) + BINDING["load_format_constant"][1:])), - ("Formatted buffer load format constant is not ready", LINES[:wait] + LINES[wait + 1:], {}), - ("Invalid buffer load format constant", None, dict(cpu="gfx1030")), - ("Unsupported formatted source binding", None, dict(source_format="BUF_FMT_32_32_32_32_UINT")), - ("Invalid buffer load format constant", None, dict(cpu="gfx1030", source_format="BUF_FMT_32_32_32_32_UINT")), - ("Invalid buffer load format constant", None, dict(load_format_constant=(16,))), - ("Invalid buffer load format constant", None, dict(load_format_constant=())), - ("Invalid buffer load format constant", None, dict(constant_descriptor=None)), - ("Invalid buffer load format constant", None, dict(source_stride=None)), + ("Formatted buffer load format constant is not ready", lower, LINES[:wait] + LINES[wait + 1:], {}), + ("Invalid buffer load format constant", lower, None, dict(cpu="gfx1030")), + ("Unsupported formatted source binding", lower, None, dict(source_format="BUF_FMT_32_32_32_32_UINT")), + ("Invalid buffer load format constant", lower, None, + dict(cpu="gfx1030", source_format="BUF_FMT_32_32_32_32_UINT")), + ("Invalid buffer load format constant", lower, None, dict(load_format_constant=(16,))), + ("Invalid buffer load format constant", lower, None, dict(load_format_constant=())), + ("Invalid buffer load format constant", lower, None, dict(constant_descriptor=None)), + ("Invalid buffer load format constant", lower, None, dict(source_stride=None)), # A load result is data only. - ("Unsupported store address", base.variant(LINES, (", v8, s[20:23], 0 idxen offset:16", ", v10, s[20:23], 0 idxen offset:16")), {}), + ("Unsupported store address", lower, + base.variant(LINES, (", v8, s[20:23], 0 idxen offset:16", ", v10, s[20:23], 0 idxen offset:16")), {}), ): - base.rejects(message, lower, lines_, **binding) + base.rejects(message, function, lines_, **binding) def binary(directory, assembler, objcopy, library): - """LLVM 15 assembles the fixture; lower of the disassembly and the CLI both match lower of the source.""" + """LLVM 15 assembles both fixtures; lower of the disassembly and the CLI both match lower of the source.""" controls() - base.descriptor_store_round_trip(directory, LINES, BINDING, "mc", assembler, objcopy, library) - print(f"{NAME}: llvm15_round_trip=match") + for suite in SUITES.values(): + base.descriptor_store_round_trip(directory, suite.lines, suite.binding, "mc", assembler, objcopy, library) + print(f"{NAME}: llvm15_round_trip=match ({len(SUITES)} fixtures)") return 0 @@ -342,14 +499,14 @@ def check_references(name, renderer, backend, shader, cases, *, allow_hardware_s return 0 -def draw(directory, compiler, renderer, backend): +def draw(directory, compiler, renderer, backend, suite): """Dispatch with chosen t0 words; wrong references and mutated sources must fail. The reference cases share one device and compute pipeline. Each independently compiled mutation keeps its own renderer process so compilation and readback can overlap with the reference checks. """ src, cso = directory / "load.hlsl", directory / "load.cso" - source = lower() + source = aot.lower(suite.lines, GROUP, **suite.binding) src.write_text(source, encoding="ascii") subprocess.run([compiler, "-T", "cs_6_0", "-E", "main", "-Fo", cso, src], check=True) words = source_words() @@ -358,7 +515,7 @@ def draw(directory, compiler, renderer, backend): def write_case(number, groups, reference, formats): case = directory / f"case{number}.bin" - data = (struct.pack("<321I", groups, *reference) + struct.pack("<16I", *(formats or constants())) + data = (struct.pack("<321I", groups, *reference) + struct.pack("<16I", *(formats or suite.constants())) + struct.pack("<320I", *words)) case.write_bytes(data) return case @@ -375,54 +532,54 @@ def run_mutation(number, label, case, mutated): result = subprocess.run([renderer, backend, "--compute-store-case", shader, case], capture_output=True, text=True) if result.returncode != 1 or "Compute readback differs" not in result.stderr: - raise AssertionError(f"{NAME}: mutation '{label}' escaped detection\n{result.stderr}") + raise AssertionError(f"{suite.name}: mutation '{label}' escaped detection\n{result.stderr}") for groups in (1, 2): - add_reference("dispatch", groups, expected_words(groups)) + add_reference("dispatch", groups, suite.expected(groups)) def invalid_formats(number): - formats = constants() - formats[INVALID[number][1]] = INVALID[number][2] + formats = suite.constants() + formats[suite.invalid[number][1]] = suite.invalid[number][2] return formats # Each invalid format must leave all of u0 at the sentinel, and so fail a reference that publishes - # placeholder words for that load: zeros, or the D3D (0, 0, 0, 1) fill for the wider opcode. + # placeholder words for that load. unwritten = [base.SENTINEL] * 320 - zeros = (lambda channels: (lambda words: [0] * channels)) - for number, (label, index, _word) in enumerate(INVALID): + for number, (label, index, _word) in enumerate(suite.invalid): add_reference(f"refused {label}", 2, unwritten, invalid_formats(number)) - channels = len(LOADS[index][0]) - placeholders = [("published as zeros", zeros(channels))] - if number == 2: + count = registers(suite.loads[index][0]) + placeholders = [("published as zeros", lambda words, count=count: [0] * count)] + if suite.loads is LOADS and number == 2: placeholders.append(("published with the (0, 0, 0, 1) fill", lambda words: [words[0], 0])) for what, values in placeholders: - published = expected_words(2, placeholder=(index, values)) + published = suite.expected(2, placeholder=(index, values)) add_reference(f"{label} {what}", 2, published, invalid_formats(number), diagnostic=f"word=0 expected={published[0]:08x} actual=c5c5c5c5") - expected = expected_words(2) - for label, wrong in WRONG: - reference = expected_words(2, wrong=wrong) + expected = suite.expected(2) + for label, wrong in suite.wrong: + reference = suite.expected(2, wrong=wrong) word = next((i for i, (a, b) in enumerate(zip(expected, reference)) if a != b), None) if word is None: - raise AssertionError(f"{NAME}: reference '{label}' matches the expected words") + raise AssertionError(f"{suite.name}: reference '{label}' matches the expected words") add_reference(f"reference '{label}'", 2, reference, diagnostic=f"word={word} expected=") - for label, old, new, run_index in MUTATIONS: + for label, old, new, run_index in suite.mutations: mutated = source.replace(old, new, 1) if mutated == source: - raise AssertionError(f"{NAME}: mutation '{label}' did not change the source") + raise AssertionError(f"{suite.name}: mutation '{label}' did not change the source") number = len(references) + len(mutations) reference, formats = (expected, None) if run_index is None else (unwritten, invalid_formats(run_index)) case = write_case(number, 2, reference, formats) mutations.append((number, label, case, mutated)) with ThreadPoolExecutor(max_workers=min(LAUNCH_THREADS, os.cpu_count() or 1)) as pool: - batch = pool.submit(check_references, NAME, renderer, backend, cso, references) + batch = pool.submit(check_references, suite.name, renderer, backend, cso, references) mutants = [pool.submit(run_mutation, *mutation) for mutation in mutations] batch.result() for future in mutants: future.result() - print(f"{NAME}: {2 + len(INVALID)} dispatches, {len(WRONG) + len(INVALID) + 1} wrong references and " - f"{len(MUTATIONS)} mutated sources checked") + count = len(suite.wrong) + len(suite.invalid) + (1 if suite.loads is LOADS else 0) + print(f"{suite.name}: {2 + len(suite.invalid)} dispatches, {count} wrong references and " + f"{len(suite.mutations)} mutated sources checked") return 0 @@ -434,7 +591,7 @@ def invalid_formats(number): with tempfile.TemporaryDirectory() as tmp: if mode == "binary" and len(args) == 3: sys.exit(binary(Path(tmp), *args)) - if mode == "draw" and len(args) == 3: - sys.exit(draw(Path(tmp), *args)) + if mode in SUITES and len(args) == 3: + sys.exit(draw(Path(tmp), *args, SUITES[mode])) sys.exit("usage: compute_load_format_check.py controls | binary " - "| draw ") + "| draw | draw-d16 ") diff --git a/tools/compute_store_aot.py b/tools/compute_store_aot.py index eb22a3fafb..fdb550aa11 100644 --- a/tools/compute_store_aot.py +++ b/tools/compute_store_aot.py @@ -641,6 +641,11 @@ def descriptor_load_hlsl(): Every conversion is integer arithmetic, so the result does not depend on the GPU's float division. UNORM is x / (2^n - 1) and SNORM16 is max(x / 32767, -1), rounded to nearest even binary32 by long division. FLOAT16 widens exactly, keeping NaN payloads. 16-bit UINT and SINT zero- and sign-extend the low halfword. + + With d16 the channels pack two per result word, x in the low half. Float-type formats give binary16: the + FLOAT16 halves as stored, and UNORM and SNORM16 rounded to nearest even binary16 (denormals kept) by long + division. 16-bit UINT and SINT give the 16-bit integer, not a float. A 32-bit format has no d16 rule here and + is invalid. """ legacy = [] for field, code in sorted(LEGACY_DESCRIPTOR_FORMATS.items()): @@ -665,14 +670,32 @@ def descriptor_load_hlsl(): grouped = {} for code, (kind, channels) in DESCRIPTOR_STORE_FORMATS.items(): grouped.setdefault((kind, channels), []).append(code) + halves = { + "unorm8": ("h = uint4(descriptor_ratio16(raw.x & 0xffu, 255u), descriptor_ratio16((raw.x >> 8u) & 0xffu, 255u), " + "descriptor_ratio16((raw.x >> 16u) & 0xffu, 255u), descriptor_ratio16(raw.x >> 24u, 255u));"), + "unorm16x2": ("h.xy = uint2(descriptor_ratio16(raw.x & 0xffffu, 65535u), " + "descriptor_ratio16(raw.x >> 16u, 65535u));"), + "unorm10": ("h = uint4(descriptor_ratio16(raw.x & 0x3ffu, 1023u), " + "descriptor_ratio16((raw.x >> 10u) & 0x3ffu, 1023u), " + "descriptor_ratio16((raw.x >> 20u) & 0x3ffu, 1023u), descriptor_ratio16(raw.x >> 30u, 3u));"), + "f16x2": "h.xy = uint2(raw.x & 0xffffu, raw.x >> 16u);", + "f16x4": "h = uint4(raw.x & 0xffffu, raw.x >> 16u, raw.y & 0xffffu, raw.y >> 16u);", + "unorm16": "h.x = descriptor_ratio16(raw.x & 0xffffu, 65535u);", + "snorm16": "h.x = descriptor_snorm16_half(raw.x & 0xffffu);", + "uint16": "h.x = raw.x & 0xffffu;", + "sint16": "h.x = raw.x & 0xffffu;", + "f16": "h.x = raw.x & 0xffffu;", + } arms = [] - for kind in _DESCRIPTOR_KIND_ORDER: - for channels in range(1, 5): - codes = grouped.get((kind, channels)) - if codes: - test = " || ".join(f"format == {code}u" for code in sorted(codes)) - keyword = "if" if not arms else "else if" - arms.append(f" {keyword} (({test}) && channels == {channels}u) {{ {bodies[kind]} valid = true; }}") + for d16, table in ((False, bodies), (True, halves)): + for kind in _DESCRIPTOR_KIND_ORDER: + for channels in range(1, 5): + codes = grouped.get((kind, channels)) + if codes and kind in table: + test = " || ".join(f"format == {code}u" for code in sorted(codes)) + keyword = "if" if not arms else "else if" + arms.append(f" {keyword} (d16 {'!=' if d16 else '=='} 0u && ({test}) && channels == {channels}u) " + f"{{ {table[kind]} valid = true; }}") return ( "uint descriptor_ratio(uint x, uint d) {\n" " // binary32 bits of x / d for 0 <= x <= d < 2^16, rounded to nearest even by long division.\n" @@ -691,6 +714,31 @@ def descriptor_load_hlsl(): " if ((bits & 1u) != 0u && (r != 0u || (result & 1u) != 0u)) ++result;\n" " return result;\n" "}\n" + "uint descriptor_ratio16(uint x, uint d) {\n" + " // binary16 bits of x / d for 0 <= x <= d < 2^16, rounded to nearest even, denormals kept.\n" + " if (x == 0u) return 0u;\n" + " if (x == d) return 0x3c00u;\n" + " uint r = x, f = 0u;\n" + " for (uint i = 0u; i < 26u; ++i) {\n" + " r <<= 1u;\n" + " uint bit = r >= d ? 1u : 0u;\n" + " r -= bit * d;\n" + " f = (f << 1u) | bit;\n" + " }\n" + " // x / d = f / 2^26 plus a remainder. A normal result keeps 11 bits; a denormal counts units of 2^-24.\n" + " uint lead = firstbithigh(f);\n" + " uint shift = lead >= 12u ? lead - 10u : 2u;\n" + " uint result = lead >= 12u ? (((lead - 11u) << 10u) | ((f >> shift) & 0x3ffu)) : (f >> shift);\n" + " uint roundBit = (f >> (shift - 1u)) & 1u;\n" + " bool sticky = (f & ((1u << (shift - 1u)) - 1u)) != 0u || r != 0u;\n" + " if (roundBit != 0u && (sticky || (result & 1u) != 0u)) ++result;\n" + " return result;\n" + "}\n" + "uint descriptor_snorm16_half(uint bits16) {\n" + " int value = (int)(bits16 << 16u) >> 16;\n" + " if (value <= -32767) return 0xbc00u;\n" + " return value < 0 ? 0x8000u | descriptor_ratio16((uint)(-value), 32767u) : descriptor_ratio16((uint)value, 32767u);\n" + "}\n" "uint descriptor_snorm16_load(uint bits16) {\n" " int value = (int)(bits16 << 16u) >> 16;\n" " if (value <= -32767) return 0xbf800000u;\n" @@ -704,7 +752,7 @@ def descriptor_load_hlsl(): " uint top = firstbithigh(m);\n" " return sign | ((top + 103u) << 23u) | ((m << (23u - top)) & 0x7fffffu);\n" "}\n" - "uint4 load_descriptor_format(uint formatWord, uint addr, uint channels, out bool valid) {\n" + "uint4 load_descriptor_format(uint formatWord, uint addr, uint channels, uint d16, out bool valid) {\n" " valid = false;\n" f" uint fixedBits = formatWord & {DESCRIPTOR_FIXED_MASK:#x}u;\n" f" uint field = (formatWord >> {DESCRIPTOR_FORMAT_SHIFT}u) & {DESCRIPTOR_FORMAT_MASK:#x}u;\n" @@ -715,8 +763,9 @@ def descriptor_load_hlsl(): + "\n".join(legacy) + "\n" " }\n" " uint4 raw = inputData.Load4(addr);\n" - " uint4 r = uint4(0u, 0u, 0u, 0u);\n" + " uint4 r = uint4(0u, 0u, 0u, 0u), h = uint4(0u, 0u, 0u, 0u);\n" + "\n".join(arms) + "\n" + " if (d16 != 0u) r = uint4(h.x | (h.y << 16u), h.z | (h.w << 16u), 0u, 0u);\n" " return r;\n" "}\n" ) @@ -761,7 +810,7 @@ def heap_view_hlsl(table_offset, view_count, buffer_bytes): " inRange = inRange && instOffset + 4u * channels <= left - start;\n" " addr = v.x + start + instOffset;\n" " }\n" - " uint4 r = load_descriptor_format(v.w, inRange ? addr : 0u, channels, valid);\n" + " uint4 r = load_descriptor_format(v.w, inRange ? addr : 0u, channels, 0u, valid);\n" " return inRange ? r : zero;\n" "}\n" ) @@ -2122,11 +2171,12 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N raise ValueError("Unverified plane byte offset") vector[dst] = ("plane_bytes", row_tag[1], shift, *column_tag[1:]) elif ((m := re.fullmatch(r"v_and_b32_e32 v(\d+), (?:0xffff|65535), v(\d+)", line)) - and isinstance(partial := vector.get(int(m[2])), tuple) and partial[0] == "source_low16"): + and isinstance(partial := vector.get(int(m[2])), tuple) and partial[0] in ("source_low16", "alu_low16")): dst = int(m[1]) if dst > 255: raise ValueError("Invalid vector destination") - vector[dst] = ("alu", f"(inputData.Load({partial[1]}) & 0xffffu)") + word = f"inputData.Load({partial[1]})" if partial[0] == "source_low16" else partial[1] + vector[dst] = ("alu", f"({word} & 0xffffu)") elif ((m := re.fullmatch(r"(v_(?:add|sub|subrev|mul)_f32)_e64 v(\d+), ([^,\s]+), ([^,\s]+)( .+)?", line)) and any(token.startswith(("-", "|", "neg(", "abs(")) and not re.fullmatch(FLOAT_SOURCE, token) for token in m.groups()[2:4])): @@ -2396,8 +2446,6 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N descriptor_load = None if resource_channels and load_format_words is not None: # The format is V# word 3 from a constant word, decoded in the shader (descriptor_load_hlsl). - if packed: - raise ValueError("Descriptor-format d16 loads are not lowered") if not idxen or offen: raise ValueError("Unsupported formatted buffer read target or address mode") if format_load_index >= len(load_format_words): @@ -2475,15 +2523,19 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N if descriptor_load is not None: result = f"format_load_{format_load_index - 1}" slot = hlsl_word(('constant_word', descriptor_load)) + if heap_view is not None and packed: + raise ValueError("D16 descriptor-format loads are not lowered through a heap view") call = (f"load_heap_view_format({slot}, tid.{AXES[tag[1]]}, {aligned}u, {components}u, " f"format_valid_{format_load_index - 1})" if heap_view is not None else - f"load_descriptor_format({slot}, {addresses[0]}, {components}u, " + f"load_descriptor_format({slot}, {addresses[0]}, {components}u, {int(packed)}u, " f"format_valid_{format_load_index - 1})") staged_steps.append((None, f" bool format_valid_{format_load_index - 1};\n" f" uint4 {result} = {call};")) for reg in range(dst, dst + count): vector.pop(reg, None) - loading[reg] = ("alu", f"{result}.{'xyzw'[reg - dst]}") + # An odd d16 count leaves the high half of the last word undefined, as for source_low16. + low16 = packed and components % 2 and reg == dst + count - 1 + loading[reg] = ("alu_low16" if low16 else "alu", f"{result}.{'xyzw'[reg - dst]}") continue # The address has been captured, so the index can alias a destination. for reg, address in enumerate(addresses, dst):