upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--docs/design.md2
-rw-r--r--docs/shader_validation.md17
-rw-r--r--tests/semantic/spirv_mini_interp.py12
-rw-r--r--tests/semantic/test_buffer_load_format.py66
-rw-r--r--tests/test_mem_diff.py24
-rw-r--r--tools/mem_diff.py45
-rw-r--r--tools/rdna2spirv.py35
7 files changed, 122 insertions, 79 deletions
diff --git a/docs/design.md b/docs/design.md
index b2c642dbb..c73d6b55e 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -221,7 +221,7 @@ How the generated SPIR-V expects the runtime to work:
221| Global memory | `global_load/store_dword*`: address = (64-bit SGPR base + zero-extended 32-bit VGPR offset, or a 64-bit VGPR address) + the instruction offset, translated through the heap base. Inactive lanes don't access memory, and loads merge their previous values with OpPhi. The offset is the **signed 12-bit** byte value as llvm-mc prints it, -2048..2047 (`offset:-4` is the field 0xffc; llvm-mc rejects `offset:0xffc` and disassembles that field as `offset:-4`, so no repo path delivers the raw unsigned field), added to the address as is; a tool that printed the raw field (`0xffc`) would mean the same offset, and a value outside 12 bits is rejected. Measured on an AMD Radeon RX 6800 (gfx1030) running `global_load_dword` as a raw compute kernel, wave32 and wave64 alike, with the dword at byte n = 0x10000000+n and the pointer at 0x1000: offset 0 reads 0x10001000, -4 0x10000ffc, -2048 0x10000800, 2044 0x100017fc, -1024 0x10000c00. The translator used to subtract 0x1000 from an already negative value (4096 bytes too low). Checked by `tests/semantic/test_global_mem_offset.py` (both addressing modes, dword/x2/x4, byte/short loads and stores at -4, -2048, 2047 and 0) and the GPU test `runtime/test/shaders/cs_global_neg_offset.asm` (`vk_compute_test ... 40 dump`). | 221| Global memory | `global_load/store_dword*`: address = (64-bit SGPR base + zero-extended 32-bit VGPR offset, or a 64-bit VGPR address) + the instruction offset, translated through the heap base. Inactive lanes don't access memory, and loads merge their previous values with OpPhi. The offset is the **signed 12-bit** byte value as llvm-mc prints it, -2048..2047 (`offset:-4` is the field 0xffc; llvm-mc rejects `offset:0xffc` and disassembles that field as `offset:-4`, so no repo path delivers the raw unsigned field), added to the address as is; a tool that printed the raw field (`0xffc`) would mean the same offset, and a value outside 12 bits is rejected. Measured on an AMD Radeon RX 6800 (gfx1030) running `global_load_dword` as a raw compute kernel, wave32 and wave64 alike, with the dword at byte n = 0x10000000+n and the pointer at 0x1000: offset 0 reads 0x10001000, -4 0x10000ffc, -2048 0x10000800, 2044 0x100017fc, -1024 0x10000c00. The translator used to subtract 0x1000 from an already negative value (4096 bytes too low). Checked by `tests/semantic/test_global_mem_offset.py` (both addressing modes, dword/x2/x4, byte/short loads and stores at -4, -2048, 2047 and 0) and the GPU test `runtime/test/shaders/cs_global_neg_offset.asm` (`vk_compute_test ... 40 dump`). |
222| Literal samplers | Some shaders build their S# from immediates (for example `0x92, 0xC00000, 0x14500000, 0`). The runtime registers those in the descriptor hash table too, by scanning the translated shaders' constant S# values, not only S#s the game binds. | 222| Literal samplers | Some shaders build their S# from immediates (for example `0x92, 0xC00000, 0x14500000, 0`). The runtime registers those in the descriptor hash table too, by scanning the translated shaders' constant S# values, not only S#s the game binds. |
223| Scalar/buffer memory | `s_load*`, `s_buffer_load*`, `buffer_load*` and `buffer_store*` use buffer device addresses (`PhysicalStorageBuffer64`). The base comes from the 64-bit SGPR pointer or the V# (dword0 \| dword1[15:0] << 32), and the stride is V# dword1[29:16]. **The runtime must put the game's GPU heap in buffer-device-addressable memory at the same addresses the game writes into descriptors** (or remap them). `s_load*` and `s_buffer_load*` take an immediate or an SGPR offset, or both at once (llvm-mc prints `sOFF offset:IMM`): the address is base + sOFF + IMM + 4·i for dword i. Measured on AMD Radeon RX 6800 (gfx1030) by running the instructions as a raw compute kernel: soffset 8 + imm 4 reads +12 (`s_buffer_load_dword`, `x2`, `x4`, `x8`); `s_load_dword*` with both offsets wasn't measured and gets the same rule because it shares the SMEM encoding. The translator used to drop the immediate of that form. The translator's arithmetic is checked by `tests/semantic/test_scalar_mem_smem.py` (`SmemSoffsetImmTranslatorTests`); a GPU test, `runtime/test/shaders/cs_smem_soffset_imm.asm`, is in `check.py` and `scripts/run_gpu_tests.py`. Known remaining differences, from the same measurement of `s_buffer_load*`: the hardware truncates base, sOFF and IMM each to a multiple of 4 and returns 0 past NUM_RECORDS; the translator does neither yet. See *Buffer bounds checking* below for the MUBUF `num_records` checks. | 223| Scalar/buffer memory | `s_load*`, `s_buffer_load*`, `buffer_load*` and `buffer_store*` use buffer device addresses (`PhysicalStorageBuffer64`). The base comes from the 64-bit SGPR pointer or the V# (dword0 \| dword1[15:0] << 32), and the stride is V# dword1[29:16]. **The runtime must put the game's GPU heap in buffer-device-addressable memory at the same addresses the game writes into descriptors** (or remap them). `s_load*` and `s_buffer_load*` take an immediate or an SGPR offset, or both at once (llvm-mc prints `sOFF offset:IMM`): the address is base + sOFF + IMM + 4·i for dword i. Measured on AMD Radeon RX 6800 (gfx1030) by running the instructions as a raw compute kernel: soffset 8 + imm 4 reads +12 (`s_buffer_load_dword`, `x2`, `x4`, `x8`); `s_load_dword*` with both offsets wasn't measured and gets the same rule because it shares the SMEM encoding. The translator used to drop the immediate of that form. The translator's arithmetic is checked by `tests/semantic/test_scalar_mem_smem.py` (`SmemSoffsetImmTranslatorTests`); a GPU test, `runtime/test/shaders/cs_smem_soffset_imm.asm`, is in `check.py` and `scripts/run_gpu_tests.py`. Known remaining differences, from the same measurement of `s_buffer_load*`: the hardware truncates base, sOFF and IMM each to a multiple of 4 and returns 0 past NUM_RECORDS; the translator does neither yet. See *Buffer bounds checking* below for the MUBUF `num_records` checks. |
224| Typed buffer loads | The format is V# word3[18:12] (GFX10_FORMAT, from Mesa's `gfx10-rsrc.json`, saved as `tools\gfx10_formats.json`). Supported: f32 ×1–4, u32 ×1/2/4, f16 ×1/2/4, unorm8 ×1/2/4, snorm8 ×4, uint8 ×4, unorm16 ×1/2/4, snorm16 ×2/4, 10-10-10-2 and 2-10-10-10 unorm. Others give 0. DST_SEL swizzle is applied. Format names list the channel widths from the top bit, so `2_10_10_10` (50) is R10G10B10A2 and `10_10_10_2` (44) has a 2-bit x (Mesa `gfx10_format_table.py`, `ac_formats.c`). Until 2026-11-22 the two were swapped, in stores too. Until 2026-11-21 an element that started mid-dword re-read dword 0 for its tail (`need` was `ceil(size/4)` and only the first dword was shifted); loads now take `need = ceil((byte_shift + size) / 4)` dwords and shift the whole window so the packed stream starts at the element (FUZZ-5, leftover from #234). The 10:10:10:2 order is checked by `cs_fmt_1010102` in `tests/semantic/test_value_semantics.py` (the shader decodes the format, so a GPU run can't check it). Mid-dword spanning elements are checked by `tests/semantic/test_buffer_load_format.py` (`CrossingDwordBoundary`). | 224| Typed buffer loads | The format is V# word3[18:12] (GFX10_FORMAT, from Mesa's `gfx10-rsrc.json`, saved as `tools\gfx10_formats.json`). Supported: f32 ×1–4, u32 ×1/2/4, f16 ×1/2/4, unorm8 ×1/2/4, snorm8 ×4, uint8 ×4, unorm16 ×1/2/4, snorm16 ×2/4, 10-10-10-2 and 2-10-10-10 unorm. Others give 0. DST_SEL swizzle is applied (0→0, 1→1.0f for float/norm or integer 1 for UINT/SINT, 4..7→X..W). Missing channels repeat the format's own (component *c* = *c* mod *n*), measured on an RX 6700 (SHADER-86). UNORM/SNORM decode with correctly rounded `OpFDiv` by (2ⁿ−1), not a reciprocal multiply (0 mismatches vs hardware over 395,776 conversions on that GPU). Format names list the channel widths from the top bit, so `2_10_10_10` (50) is R10G10B10A2 and `10_10_10_2` (44) has a 2-bit x (Mesa `gfx10_format_table.py`, `ac_formats.c`). Until 2026-11-22 the two were swapped, in stores too. Until 2026-11-21 an element that started mid-dword re-read dword 0 for its tail (`need` was `ceil(size/4)` and only the first dword was shifted); loads now take `need = ceil((byte_shift + size) / 4)` dwords and shift the whole window so the packed stream starts at the element (FUZZ-5, leftover from #234). The 10:10:10:2 order is checked by `cs_fmt_1010102` in `tests/semantic/test_value_semantics.py` (the shader decodes the format, so a GPU run can't check it). Mid-dword spanning elements are checked by `tests/semantic/test_buffer_load_format.py` (`CrossingDwordBoundary`); repeat / UNORM / DST_SEL 1 by the SHADER-86 cases in the same file. |
225| Images and samplers | `image_sample_l` on 2D arrays used to read its LOD from the array layer; it now reads the LOD after all coordinates. `image_get_lod` and `image_gather4_lz` also work on 2D arrays. With `d16` every sample result is f16, packed two to a VGPR from the low half (the packed D16 of GFX10, as LLVM returns D16 image data); `image_sample_c_lz`/`_c_lz_o` follow it too, and until 2026-11-21 their compare result was written as f32 bits, which read as 0 in the low half. Checked by `tests/test_translate.py` (`test_depth_compare_sample_result_width`). | 225| Images and samplers | `image_sample_l` on 2D arrays used to read its LOD from the array layer; it now reads the LOD after all coordinates. `image_get_lod` and `image_gather4_lz` also work on 2D arrays. With `d16` every sample result is f16, packed two to a VGPR from the low half (the packed D16 of GFX10, as LLVM returns D16 image data); `image_sample_c_lz`/`_c_lz_o` follow it too, and until 2026-11-21 their compare result was written as f32 bits, which read as 0 in the low half. Checked by `tests/test_translate.py` (`test_depth_compare_sample_result_width`). |
226| Images and samplers (core) | Bindless. Set 0: binding 0 = 2D sampled images, 1 = samplers, 2 = descriptor hash table (storage buffer), 3 = 2D-array images (**cube textures are bound here as 6-layer 2D-array views**, cube arrays as 6N layers: the shader already selected the face with `v_cube*`), 4 = r32ui storage images, 5 = 1D, 6 = 3D. A cube sample's s and t come in [1, 2] and its third coordinate is 8·slice + face, as the hardware takes them (Mesa `ac_nir_lower_tex_coords.c`, LLPC `ImageBuilder.cpp`); the view is read at (s − 1, t − 1), layer 6·slice + face. GPU-checked with `runtime/test/shaders/ps_cube_sample.asm` (`vk_texture_test cube`). | 226| Images and samplers (core) | Bindless. Set 0: binding 0 = 2D sampled images, 1 = samplers, 2 = descriptor hash table (storage buffer), 3 = 2D-array images (**cube textures are bound here as 6-layer 2D-array views**, cube arrays as 6N layers: the shader already selected the face with `v_cube*`), 4 = r32ui storage images, 5 = 1D, 6 = 3D. A cube sample's s and t come in [1, 2] and its third coordinate is 8·slice + face, as the hardware takes them (Mesa `ac_nir_lower_tex_coords.c`, LLPC `ImageBuilder.cpp`); the view is read at (s − 1, t − 1), layer 6·slice + face. GPU-checked with `runtime/test/shaders/ps_cube_sample.asm` (`vk_texture_test cube`). |
227| Descriptor hash table | `uint mask; entries[mask+1] of 10 uints: key[0..7], index, pad`. The key is a T# or a padded S#. FNV-1a over the eight key words selects the first slot. The shared SPIR-V lookup probes up to eight slots and returns index 0 on a miss. The runtime supplies a fallback at index 0 and maps live descriptor keys to bindless indices. | 227| Descriptor hash table | `uint mask; entries[mask+1] of 10 uints: key[0..7], index, pad`. The key is a T# or a padded S#. FNV-1a over the eight key words selects the first slot. The shared SPIR-V lookup probes up to eight slots and returns index 0 on a miss. The runtime supplies a fallback at index 0 and maps live descriptor keys to bindless indices. |
diff --git a/docs/shader_validation.md b/docs/shader_validation.md
index ee508a567..2cf16b234 100644
--- a/docs/shader_validation.md
+++ b/docs/shader_validation.md
@@ -249,19 +249,16 @@ fields the translator does not model yet, so they need a GPU-confirmed rule befo
249this. Not covered yet: images. 249this. Not covered yet: images.
250 250
251The `buffer_format` family covers `buffer_load_format_*` on every format the translator decodes, with a 251The `buffer_format` family covers `buffer_load_format_*` on every format the translator decodes, with a
252random DST_SEL of 0/X/Y/Z/W, and `tbuffer_load_format_*` on the five formats the 1.0.2.1 corpus uses 252random DST_SEL of 0/1/X/Y/Z/W, and `tbuffer_load_format_*` on the five formats the 1.0.2.1 corpus uses
253(`16_16_SNORM`, `8_8_8_8_UNORM`, `8_8_8_8_UINT`, `2_10_10_10_UNORM`, `16_16_16_16_UINT`, about 53,000 253(`16_16_SNORM`, `8_8_8_8_UNORM`, `8_8_8_8_UINT`, `2_10_10_10_UNORM`, `16_16_16_16_UINT`, about 53,000
254instructions) with an identity swizzle. Its reference decodes each element from the GFX10 format *name* 254instructions) with an identity swizzle. Its reference decodes each element from the GFX10 format *name*
255(`tools/gfx10_formats.json`; channel widths listed from the top bit), not from the translator's own 255(`tools/gfx10_formats.json`; channel widths listed from the top bit), not from the translator's own
256table: UNORM/SNORM correctly rounded, missing channels 0, 0, 0, 1. Elements are naturally aligned. Left 256table: UNORM/SNORM correctly rounded (`x/(2ⁿ−1)`), missing channels *c* mod *n*, DST_SEL 1 = integer 1
257out: DST_SEL 1 on integer formats, and whether `tbuffer` applies the V#'s DST_SEL (neither is measured). 257for UINT/SINT and 1.0f otherwise (SHADER-86, RX 6700). Elements are naturally aligned. Left out: whether
258 258`tbuffer` applies the V#'s DST_SEL (unmeasured).
259Two results are counted apart, not as mismatches, until a gfx10 hardware measurement settles them 259
260(posted in #374): `norm-ulp1`, a UNORM/SNORM result 1 ULP from the correctly rounded value (the 260Over 5,000 programs the reference and translator match bit for bit; breaking the `16_16_SNORM` kind, the
261translator multiplies by a rounded reciprocal), and `missing-w32`, the missing W of a 32-bit format, 261`8_8_8_8_UINT` widths or the DST_SEL order in the translator makes 33, 37 and 191 of 300 programs fail.
262where the translator returns 0 and every other format 1 / 1.0. Over 5,000 programs, everything else
263matches; breaking the `16_16_SNORM` kind, the `8_8_8_8_UINT` widths or the DST_SEL order in the
264translator makes 33, 37 and 191 of 300 programs fail.
265 262
266A mutation check (inst offset dropped, V# stride narrowed, the SMEM pointer's high word dropped) makes 263A mutation check (inst offset dropped, V# stride narrowed, the SMEM pointer's high word dropped) makes
26776, 45 and 42 of 150 programs fail, so the runner does catch address errors. 26476, 45 and 42 of 150 programs fail, so the runner does catch address errors.
diff --git a/tests/semantic/spirv_mini_interp.py b/tests/semantic/spirv_mini_interp.py
index a4b871f22..8bb599003 100644
--- a/tests/semantic/spirv_mini_interp.py
+++ b/tests/semantic/spirv_mini_interp.py
@@ -709,10 +709,16 @@ def _invocation(text, inputs, push_constants, memory, step=False):
709 values[res] = x or y 709 values[res] = x or y
710 elif op == "OpLogicalNot": 710 elif op == "OpLogicalNot":
711 values[res] = not val(a[1]) 711 values[res] = not val(a[1])
712 elif op in ("OpFAdd", "OpFSub", "OpFMul"): 712 elif op in ("OpFAdd", "OpFSub", "OpFMul", "OpFDiv"):
713 x, y = val(a[1]), val(a[2]) 713 x, y = val(a[1]), val(a[2])
714 fn = (lambda p, q: f32(p + q)) if op == "OpFAdd" else ( 714
715 (lambda p, q: f32(p - q)) if op == "OpFSub" else (lambda p, q: f32(p * q))) 715 def _fdiv(p, q):
716 if q != 0.0:
717 return f32(p / q)
718 return f32(math.copysign(math.inf, p) if p != 0.0 else math.nan)
719
720 fn = {"OpFAdd": (lambda p, q: f32(p + q)), "OpFSub": (lambda p, q: f32(p - q)),
721 "OpFMul": (lambda p, q: f32(p * q)), "OpFDiv": _fdiv}[op]
716 if isinstance(x, tuple) and isinstance(y, tuple) and len(x) == len(y) and all( 722 if isinstance(x, tuple) and isinstance(y, tuple) and len(x) == len(y) and all(
717 isinstance(p, float) and isinstance(q, float) for p, q in zip(x, y)): 723 isinstance(p, float) and isinstance(q, float) for p, q in zip(x, y)):
718 values[res] = tuple(fn(p, q) for p, q in zip(x, y)) 724 values[res] = tuple(fn(p, q) for p, q in zip(x, y))
diff --git a/tests/semantic/test_buffer_load_format.py b/tests/semantic/test_buffer_load_format.py
index 0e6a369a4..d20706f4c 100644
--- a/tests/semantic/test_buffer_load_format.py
+++ b/tests/semantic/test_buffer_load_format.py
@@ -7,6 +7,8 @@ OpSelect), so every dword-aligned load here also checks that the merge keeps its
7 7
8Integer and f16 formats are used: their decode is exact, so the expected words need no rounding model. 8Integer and f16 formats are used: their decode is exact, so the expected words need no rounding model.
9""" 9"""
10from __future__ import annotations
11
10import os 12import os
11import struct 13import struct
12import sys 14import sys
@@ -30,7 +32,10 @@ BASE = 0x1000
30MEMORY = {BASE: 0x11223344, BASE + 4: 0xDEADBEEF, BASE + 8: 0xCAFEF00D, BASE + 12: 0x0BADC0DE} 32MEMORY = {BASE: 0x11223344, BASE + 4: 0xDEADBEEF, BASE + 8: 0xCAFEF00D, BASE + 12: 0x0BADC0DE}
31# V# FORMAT codes (word3 bits 12-18), from rdna2spirv.FORMATS 33# V# FORMAT codes (word3 bits 12-18), from rdna2spirv.FORMATS
32FMT_U32, FMT_U32X2, FMT_U32X4, FMT_UINT8X4, FMT_UINT16X2, FMT_UINT16X4, FMT_F16 = 20, 62, 75, 60, 27, 69, 13 34FMT_U32, FMT_U32X2, FMT_U32X4, FMT_UINT8X4, FMT_UINT16X2, FMT_UINT16X4, FMT_F16 = 20, 62, 75, 60, 27, 69, 13
35FMT_F32, FMT_F32X2, FMT_F32X3, FMT_UNORM8, FMT_UNORM8X4 = 22, 64, 74, 1, 56
33DST_SEL_XYZW = 4 | 5 << 3 | 6 << 6 | 7 << 9 36DST_SEL_XYZW = 4 | 5 << 3 | 6 << 6 | 7 << 9
37# DST_SEL (X, 0, 1, 1): code 4, 0, 1, 1 — SHADER-86 measures float 1.0 vs integer 1
38DST_SEL_X_0_1_1 = 4 | 0 << 3 | 1 << 6 | 1 << 9
34 39
35_TMP_DIR = None 40_TMP_DIR = None
36_SRC_PATH = None 41_SRC_PATH = None
@@ -53,8 +58,9 @@ def tearDownModule():
53 _TMP_DIR = None 58 _TMP_DIR = None
54 59
55 60
56def load_format(fmt: int, offset: int, ncomp: int = 4) -> tuple: 61def load_format(fmt: int, offset: int, ncomp: int = 4, dst_sel: int = DST_SEL_XYZW,
57 """buffer_load_format_<x..xyzw> of format `fmt` at byte `offset` of MEMORY; returns the four mrt0 words.""" 62 memory: dict | None = None) -> tuple:
63 """buffer_load_format_<x..xyzw> of format `fmt` at byte `offset`; returns the four mrt0 words."""
58 if _TMP_DIR is None: 64 if _TMP_DIR is None:
59 setUpModule() 65 setUpModule()
60 suffix = "xyzw"[:ncomp] 66 suffix = "xyzw"[:ncomp]
@@ -65,7 +71,7 @@ def load_format(fmt: int, offset: int, ncomp: int = 4) -> tuple:
65 f"\ts_mov_b32 s0, {BASE:#x}\n" 71 f"\ts_mov_b32 s0, {BASE:#x}\n"
66 "\ts_mov_b32 s1, 0\n" # base high bits 0, stride 0 (raw) 72 "\ts_mov_b32 s1, 0\n" # base high bits 0, stride 0 (raw)
67 "\ts_mov_b32 s2, 0x100\n" # num_records (bytes) 73 "\ts_mov_b32 s2, 0x100\n" # num_records (bytes)
68 f"\ts_mov_b32 s3, {fmt << 12 | DST_SEL_XYZW:#x}\n" 74 f"\ts_mov_b32 s3, {fmt << 12 | dst_sel:#x}\n"
69 f"\tv_mov_b32 v1, {offset:#x}\n" 75 f"\tv_mov_b32 v1, {offset:#x}\n"
70 f"\tbuffer_load_format_{suffix} {vdata}, v1, s[0:3], 0 offen\n" 76 f"\tbuffer_load_format_{suffix} {vdata}, v1, s[0:3], 0 offen\n"
71 "\ts_waitcnt vmcnt(0)\n" 77 "\ts_waitcnt vmcnt(0)\n"
@@ -77,7 +83,11 @@ def load_format(fmt: int, offset: int, ncomp: int = 4) -> tuple:
77 with warnings.catch_warnings(): 83 with warnings.catch_warnings():
78 warnings.simplefilter("ignore", ResourceWarning) 84 warnings.simplefilter("ignore", ResourceWarning)
79 spv = rdna2spirv.translate(_SRC_PATH) 85 spv = rdna2spirv.translate(_SRC_PATH)
80 return si.run_fragment(spv, memory=dict(MEMORY))["%out_mrt0"] 86 return si.run_fragment(spv, memory=dict(memory if memory is not None else MEMORY))["%out_mrt0"]
87
88
89def f32_bits(x: float) -> int:
90 return struct.unpack("<I", struct.pack("<f", x))[0]
81 91
82 92
83def f16_word(h: int) -> int: 93def f16_word(h: int) -> int:
@@ -134,6 +144,50 @@ class CrossingDwordBoundary(unittest.TestCase):
134 self.assertEqual(load_format(FMT_UINT16X4, 6), (0xDEAD, 0xF00D, 0xCAFE, 0xC0DE)) 144 self.assertEqual(load_format(FMT_UINT16X4, 6), (0xDEAD, 0xF00D, 0xCAFE, 0xC0DE))
135 145
136 146
147class MissingComponentsRepeat(unittest.TestCase):
148 """SHADER-86 / RX 6700: missing channels are c mod n, not 0 or 1."""
149
150 def test_one_component_formats_xxxx(self):
151 self.assertEqual(load_format(FMT_U32, 4), (0xDEADBEEF,) * 4)
152 self.assertEqual(load_format(FMT_F32, 4), (0xDEADBEEF,) * 4)
153 # 8_UNORM at offset 4: low byte 0xEF → 239/255; all four channels match.
154 want = f32_bits(239.0 / 255.0)
155 self.assertEqual(load_format(FMT_UNORM8, 4), (want,) * 4)
156
157 def test_two_and_three_component_xyxy_and_xyzx(self):
158 self.assertEqual(load_format(FMT_U32X2, 4), (0xDEADBEEF, 0xCAFEF00D, 0xDEADBEEF, 0xCAFEF00D))
159 self.assertEqual(load_format(FMT_F32X2, 4), (0xDEADBEEF, 0xCAFEF00D, 0xDEADBEEF, 0xCAFEF00D))
160 self.assertEqual(load_format(FMT_F32X3, 0), (0x11223344, 0xDEADBEEF, 0xCAFEF00D, 0x11223344))
161
162
163class UnormCorrectlyRounded(unittest.TestCase):
164 """SHADER-86: UNORM is OpFDiv by (2^n-1), not a reciprocal multiply. Raw 3 → 0x3c40c0c1."""
165
166 def test_unorm8x4_raw_3(self):
167 mem = {BASE: 0x03030303}
168 want = 0x3C40C0C1
169 self.assertEqual(load_format(FMT_UNORM8X4, 0, memory=mem), (want,) * 4)
170 # f32 reciprocal multiply disagrees (BetterJdue: 504 mismatches on rgba8).
171 recip = f32_bits(struct.unpack("<f", struct.pack("<f", 3.0))[0]
172 * struct.unpack("<f", struct.pack("<f", 1.0 / 255.0))[0])
173 self.assertNotEqual(want, recip)
174
175
176class DstSelOneByFormat(unittest.TestCase):
177 """SHADER-86: DST_SEL 1 is 1.0f for float/unorm, integer 1 for UINT."""
178
179 def test_dst_sel_one_float_vs_uint(self):
180 # DST_SEL (X, 0, 1, 1): Z and W come from the constant-1 code.
181 f32 = load_format(FMT_F32, 4, dst_sel=DST_SEL_X_0_1_1)
182 self.assertEqual(f32, (0xDEADBEEF, 0, 0x3F800000, 0x3F800000))
183 u32 = load_format(FMT_U32, 4, dst_sel=DST_SEL_X_0_1_1)
184 self.assertEqual(u32, (0xDEADBEEF, 0, 1, 1))
185 unorm = load_format(FMT_UNORM8, 4, dst_sel=DST_SEL_X_0_1_1)
186 self.assertEqual(unorm[2:], (0x3F800000, 0x3F800000))
187 u8 = load_format(FMT_UINT8X4, 4, dst_sel=DST_SEL_X_0_1_1)
188 self.assertEqual(u8[2:], (1, 1))
189
190
137class InterpreterConversions(unittest.TestCase): 191class InterpreterConversions(unittest.TestCase):
138 """The ops the format decode needs from spirv_mini_interp: integer to float and GLSL FMin/FMax.""" 192 """The ops the format decode needs from spirv_mini_interp: integer to float and GLSL FMin/FMax."""
139 193
@@ -159,6 +213,10 @@ class InterpreterConversions(unittest.TestCase):
159 self.assertEqual(self.run_expr(consts, "%r = OpExtInst %float %glsl FMax %a %b\n"), 0x3FC00000) 213 self.assertEqual(self.run_expr(consts, "%r = OpExtInst %float %glsl FMax %a %b\n"), 0x3FC00000)
160 self.assertEqual(self.run_expr(consts, "%r = OpExtInst %float %glsl FMin %a %b\n"), 0xC0000000) 214 self.assertEqual(self.run_expr(consts, "%r = OpExtInst %float %glsl FMin %a %b\n"), 0xC0000000)
161 215
216 def test_fdiv_correctly_rounded(self):
217 consts = "%a = OpConstant %float 3\n%b = OpConstant %float 255\n"
218 self.assertEqual(self.run_expr(consts, "%r = OpFDiv %float %a %b\n"), 0x3C40C0C1)
219
162 220
163if __name__ == "__main__": 221if __name__ == "__main__":
164 unittest.main() 222 unittest.main()
diff --git a/tests/test_mem_diff.py b/tests/test_mem_diff.py
index 4a1ded18e..a46249860 100644
--- a/tests/test_mem_diff.py
+++ b/tests/test_mem_diff.py
@@ -39,10 +39,7 @@ class Harness(unittest.TestCase):
39 self.assertEqual(counts["mismatch"], 0, first) 39 self.assertEqual(counts["mismatch"], 0, first)
40 self.assertEqual(counts["harness-error"], 0, first) 40 self.assertEqual(counts["harness-error"], 0, first)
41 self.assertEqual(counts["skip"], {}, counts["skip"]) 41 self.assertEqual(counts["skip"], {}, counts["skip"])
42 # Two typed-buffer questions await a hardware measurement and are counted apart (see mem_diff.py). 42 self.assertEqual(counts["pass"], 60)
43 self.assertEqual(counts["pass"] + counts["norm-ulp1"] + counts["missing-w32"], 60)
44 if family != "buffer_format":
45 self.assertEqual(counts["pass"], 60)
46 43
47 44
48class Reference(unittest.TestCase): 45class Reference(unittest.TestCase):
@@ -95,29 +92,28 @@ class FormatDecode(unittest.TestCase):
95 def test_decode_examples(self): 92 def test_decode_examples(self):
96 # 8_8_8_8_UINT: X in the low byte; four channels, nothing missing. 93 # 8_8_8_8_UINT: X in the low byte; four channels, nothing missing.
97 self.assertEqual(md.decode_element(0xDDCCBBAA, [8, 8, 8, 8], "UINT"), [0xAA, 0xBB, 0xCC, 0xDD]) 94 self.assertEqual(md.decode_element(0xDDCCBBAA, [8, 8, 8, 8], "UINT"), [0xAA, 0xBB, 0xCC, 0xDD])
98 # 16_16_SNORM: X = 0x8000 clamps to -1.0, Y = 0x7FFF is 1.0; Z/W missing -> 0, 1.0. 95 # 16_16_SNORM: X = 0x8000 clamps to -1.0, Y = 0x7FFF is 1.0; Z/W repeat XYXY (SHADER-86).
99 self.assertEqual(md.decode_element(0x7FFF8000, [16, 16], "SNORM"), [0xBF800000, 0x3F800000, 0, 0x3F800000]) 96 self.assertEqual(md.decode_element(0x7FFF8000, [16, 16], "SNORM"),
97 [0xBF800000, 0x3F800000, 0xBF800000, 0x3F800000])
100 # 2_10_10_10_UNORM: X10 at bit 0 ... W2 at bit 30. All ones in X, W = 3 -> 1.0, Y = Z = 0. 98 # 2_10_10_10_UNORM: X10 at bit 0 ... W2 at bit 30. All ones in X, W = 3 -> 1.0, Y = Z = 0.
101 self.assertEqual(md.decode_element(0xC00003FF, [10, 10, 10, 2], "UNORM"), 99 self.assertEqual(md.decode_element(0xC00003FF, [10, 10, 10, 2], "UNORM"),
102 [0x3F800000, 0, 0, 0x3F800000]) 100 [0x3F800000, 0, 0, 0x3F800000])
103 # 32_UINT: missing Y, Z, W -> 0, 0, 1 (integer one). 101 # 32_UINT: missing Y/Z/W repeat X (SHADER-86).
104 self.assertEqual(md.decode_element(7, [32], "UINT"), [7, 0, 0, 1]) 102 self.assertEqual(md.decode_element(7, [32], "UINT"), [7, 7, 7, 7])
105 103
106 def test_open_questions_are_counted_apart(self): 104 def test_shader86_closed_open_questions(self):
107 """A 32-bit format's missing W (translator 0) and a UNORM 1-ULP difference are their own statuses.""" 105 """Missing W repeats X; UNORM raw 3 matches correctly rounded 0x3c40c0c1 (no 1-ULP split)."""
108 base = ["s_mov_b32 s0, 0x7000", "s_mov_b32 s1, 0", "s_mov_b32 s2, 0x100"] 106 base = ["s_mov_b32 s0, 0x7000", "s_mov_b32 s1, 0", "s_mov_b32 s2, 0x100"]
109 w32 = program(base + [f"s_mov_b32 s3, {22 << 12 | md.XYZW:#x}", "v_mov_b32 v2, 0", 107 w32 = program(base + [f"s_mov_b32 s3, {22 << 12 | md.XYZW:#x}", "v_mov_b32 v2, 0",
110 "buffer_load_format_xyzw v[4:7], v2, s[0:3], 0 offen", "s_waitcnt vmcnt(0)", 108 "buffer_load_format_xyzw v[4:7], v2, s[0:3], 0 offen", "s_waitcnt vmcnt(0)",
111 "v_mov_b32 v8, v4", "v_mov_b32 v9, v5", "v_mov_b32 v10, v6", "v_mov_b32 v11, v7"], 109 "v_mov_b32 v8, v4", "v_mov_b32 v9, v5", "v_mov_b32 v10, v6", "v_mov_b32 v11, v7"],
112 {0x7000: 0x40000000}) 110 {0x7000: 0x40000000})
113 w32.missing_w32_regs, w32.export_sources = {7}, {0: 4, 1: 5, 2: 6, 3: 7} 111 self.assertEqual(md.run_one("ps_mem_w32", w32)[0], "match")
114 self.assertEqual(md.run_one("ps_mem_w32", w32)[0], "missing-w32")
115 unorm = program(base + [f"s_mov_b32 s3, {56 << 12 | md.XYZW:#x}", "v_mov_b32 v2, 0", 112 unorm = program(base + [f"s_mov_b32 s3, {56 << 12 | md.XYZW:#x}", "v_mov_b32 v2, 0",
116 "buffer_load_format_x v4, v2, s[0:3], 0 offen", "s_waitcnt vmcnt(0)", 113 "buffer_load_format_x v4, v2, s[0:3], 0 offen", "s_waitcnt vmcnt(0)",
117 "v_mov_b32 v8, v4", "v_mov_b32 v9, v4", "v_mov_b32 v10, v4", "v_mov_b32 v11, v4"], 114 "v_mov_b32 v8, v4", "v_mov_b32 v9, v4", "v_mov_b32 v10, v4", "v_mov_b32 v11, v4"],
118 {0x7000: 3}) 115 {0x7000: 3})
119 unorm.norm_regs, unorm.export_sources = {4}, {0: 4, 1: 4, 2: 4, 3: 4} 116 self.assertEqual(md.run_one("ps_mem_unorm3", unorm)[0], "match")
120 self.assertEqual(md.run_one("ps_mem_unorm3", unorm)[0], "norm-ulp1")
121 117
122 118
123class GlobalOffsetRegression(unittest.TestCase): 119class GlobalOffsetRegression(unittest.TestCase):
diff --git a/tools/mem_diff.py b/tools/mem_diff.py
index b6bae05fa..0469d763e 100644
--- a/tools/mem_diff.py
+++ b/tools/mem_diff.py
@@ -20,9 +20,8 @@ s_buffer_load alignment truncation and swizzling depend on descriptor fields doc
20so they are left to a GPU-confirmed follow-up instead of being guessed here. 20so they are left to a GPU-confirmed follow-up instead of being guessed here.
21 21
22Typed buffer loads (buffer_load_format_*, tbuffer_load_format_*) are decoded from the GFX10 format names in 22Typed buffer loads (buffer_load_format_*, tbuffer_load_format_*) are decoded from the GFX10 format names in
23tools/gfx10_formats.json, not from the translator's table. Two outcomes awaiting a hardware measurement are 23tools/gfx10_formats.json, not from the translator's table. Missing channels repeat (*c* mod *n*), UNORM/SNORM
24counted apart instead of as mismatches: 'norm-ulp1' (a UNORM/SNORM result one ULP from the correctly rounded 24use correctly rounded division, and DST_SEL 1 is integer 1 for UINT/SINT (SHADER-86, RX 6700).
25value) and 'missing-w32' (the missing W of a 32-bit format: the translator returns 0, every other format 1).
26 25
27Usage: 26Usage:
28 python -I tools/mem_diff.py [--programs N] [--seed S] [--max-ops N] 27 python -I tools/mem_diff.py [--programs N] [--seed S] [--max-ops N]
@@ -72,8 +71,6 @@ class Program:
72 def __init__(self): 71 def __init__(self):
73 self.lines = [] 72 self.lines = []
74 self.memory = {} 73 self.memory = {}
75 self.norm_regs = set() # VGPRs that hold a UNORM/SNORM result (rounding differences are counted apart)
76 self.missing_w32_regs = set() # VGPRs that select the missing W of a 32-bit format (counted apart)
77 74
78 75
79# ---------------------------------------------------------------- typed-buffer formats (reference decode) 76# ---------------------------------------------------------------- typed-buffer formats (reference decode)
@@ -126,7 +123,7 @@ def f32_round(q):
126 123
127 124
128def decode_element(raw, widths, kind): 125def decode_element(raw, widths, kind):
129 """Decode one element (an int of sum(widths) bits) -> 4 result words, missing channels 0, 0, 0, 1.""" 126 """Decode one element (an int of sum(widths) bits) -> 4 result words; missing channels repeat (*c* mod *n*)."""
130 from fractions import Fraction 127 from fractions import Fraction
131 out, bit = [], 0 128 out, bit = [], 0
132 for w in widths: 129 for w in widths:
@@ -147,9 +144,9 @@ def decode_element(raw, widths, kind):
147 out.append(v) 144 out.append(v)
148 else: # FLOAT 16 -> f32 bits (exact) 145 else: # FLOAT 16 -> f32 bits (exact)
149 out.append(struct.unpack("<I", struct.pack("<f", struct.unpack("<e", struct.pack("<H", v))[0]))[0]) 146 out.append(struct.unpack("<I", struct.pack("<f", struct.unpack("<e", struct.pack("<H", v))[0]))[0])
150 one = 1 if kind in ("UINT", "SINT") else ONE_F32 147 n = len(out)
151 while len(out) < 4: 148 while len(out) < 4:
152 out.append(0 if len(out) < 3 else one) 149 out.append(out[len(out) % n])
153 return out 150 return out
154 151
155 152
@@ -551,7 +548,7 @@ def gen_buffer_format(rng, prog):
551 else: 548 else:
552 code = rng.choice(_typed_codes()) 549 code = rng.choice(_typed_codes())
553 widths, kind = parse_format(FORMAT_NAMES[code]) 550 widths, kind = parse_format(FORMAT_NAMES[code])
554 sels = [rng.choice((0, 4, 5, 6, 7)) for _ in range(4)] # no SEL_1: its integer value is unconfirmed 551 sels = [rng.choice((0, 1, 4, 5, 6, 7)) for _ in range(4)]
555 word3 = code << 12 | sels[0] | sels[1] << 3 | sels[2] << 6 | sels[3] << 9 552 word3 = code << 12 | sels[0] | sels[1] << 3 | sels[2] << 6 | sels[3] << 9
556 size = sum(widths) // 8 553 size = sum(widths) // 8
557 base = _buffer_base(rng) 554 base = _buffer_base(rng)
@@ -580,12 +577,6 @@ def gen_buffer_format(rng, prog):
580 else: 577 else:
581 prog.lines.append(f"buffer_load_format_{suffix} {vdata}, {operands} {addr_mods}") 578 prog.lines.append(f"buffer_load_format_{suffix} {vdata}, {operands} {addr_mods}")
582 prog.lines.append("s_waitcnt vmcnt(0)") 579 prog.lines.append("s_waitcnt vmcnt(0)")
583 if kind in ("UNORM", "SNORM"):
584 prog.norm_regs.update(VDATA + c for c in range(ncomp))
585 if set(widths) == {32} and len(widths) < 4:
586 for c in range(ncomp):
587 if (word3 >> (3 * c)) & 7 == 7:
588 prog.missing_w32_regs.add(VDATA + c)
589 return [("v", VDATA + c) for c in range(ncomp)] 580 return [("v", VDATA + c) for c in range(ncomp)]
590 581
591 582
@@ -608,13 +599,9 @@ def generate_program(rng, n_ops, families=None):
608 for _ in range(n_ops): 599 for _ in range(n_ops):
609 family = rng.choice(names) 600 family = rng.choice(names)
610 prog.lines.append(f"; {family}") 601 prog.lines.append(f"; {family}")
611 prog.norm_regs = set() # only the last operation's results are exported
612 prog.missing_w32_regs = set()
613 results = GENERATORS[family](rng, prog) or results 602 results = GENERATORS[family](rng, prog) or results
614 picks = [results[min(i, len(results) - 1)] for i in range(4)] if results else [] 603 picks = [results[min(i, len(results) - 1)] for i in range(4)] if results else []
615 prog.export_sources = {} 604 for dst, (kind, reg) in zip(EXPORT, picks):
616 for k, (dst, (kind, reg)) in enumerate(zip(EXPORT, picks)):
617 prog.export_sources[k] = reg if kind == "v" else None
618 if not (kind == "v" and reg == dst): 605 if not (kind == "v" and reg == dst):
619 prog.lines.append(f"v_mov_b32 v{dst}, {kind}{reg}") 606 prog.lines.append(f"v_mov_b32 v{dst}, {kind}{reg}")
620 return prog 607 return prog
@@ -659,16 +646,6 @@ def run_one(name, prog):
659 i = bad[0] 646 i = bad[0]
660 g = f"{got[i]:#010x}" if i < len(got) else "missing" 647 g = f"{got[i]:#010x}" if i < len(got) else "missing"
661 detail = f"export word {i}: expected {want[i]:#010x}, translated {g}" 648 detail = f"export word {i}: expected {want[i]:#010x}, translated {g}"
662 # A UNORM/SNORM result one ULP from the correctly rounded value is a rounding-convention question (the
663 # translator multiplies by a rounded reciprocal), kept apart so it can't hide a real decode error.
664 sources = prog.export_sources if hasattr(prog, "export_sources") else {}
665 if all(k < len(got) and sources.get(k) in prog.norm_regs and abs(got[k] - want[k]) == 1 for k in bad):
666 return "norm-ulp1", detail
667 # The missing W of a 32-bit format: the translator gives 0, every other format (and this model) 1 / 1.0.
668 # Posted as a finding awaiting a hardware measurement; counted apart until then.
669 if all(k < len(got) and sources.get(k) in prog.missing_w32_regs and got[k] == 0 and want[k] in (1, ONE_F32)
670 for k in bad):
671 return "missing-w32", detail
672 return "mismatch", detail 649 return "mismatch", detail
673 if memory != ref.mem: 650 if memory != ref.mem:
674 bad = sorted(a for a in set(memory) | set(ref.mem) if memory.get(a, 0) != ref.mem.get(a, 0)) 651 bad = sorted(a for a in set(memory) | set(ref.mem) if memory.get(a, 0) != ref.mem.get(a, 0))
@@ -679,7 +656,7 @@ def run_one(name, prog):
679 656
680 657
681def run_suite(programs, seed, max_ops, families=None): 658def run_suite(programs, seed, max_ops, families=None):
682 counts = {"pass": 0, "mismatch": 0, "norm-ulp1": 0, "missing-w32": 0, "skip": {}, "harness-error": 0} 659 counts = {"pass": 0, "mismatch": 0, "skip": {}, "harness-error": 0}
683 first = None 660 first = None
684 rng = random.Random(seed) 661 rng = random.Random(seed)
685 for i in range(programs): 662 for i in range(programs):
@@ -693,8 +670,6 @@ def run_suite(programs, seed, max_ops, families=None):
693 continue 670 continue
694 if status == "match": 671 if status == "match":
695 counts["pass"] += 1 672 counts["pass"] += 1
696 elif status in ("norm-ulp1", "missing-w32"):
697 counts[status] += 1
698 elif status == "mismatch": 673 elif status == "mismatch":
699 counts["mismatch"] += 1 674 counts["mismatch"] += 1
700 if first is None: 675 if first is None:
@@ -748,9 +723,7 @@ def main(argv=None):
748 counts, first = run_suite(a.programs, a.seed, a.max_ops, a.family) 723 counts, first = run_suite(a.programs, a.seed, a.max_ops, a.family)
749 skips = sum(counts["skip"].values()) 724 skips = sum(counts["skip"].values())
750 print(f"{a.programs} programs (seed {a.seed}): {counts['pass']} pass, {counts['mismatch']} mismatch, " 725 print(f"{a.programs} programs (seed {a.seed}): {counts['pass']} pass, {counts['mismatch']} mismatch, "
751 f"{counts['norm-ulp1']} UNORM/SNORM 1-ULP rounding differences, " 726 f"{skips} skipped, {counts['harness-error']} harness errors")
752 f"{counts['missing-w32']} missing-W-of-a-32-bit-format differences, {skips} skipped, "
753 f"{counts['harness-error']} harness errors")
754 for reason, n in sorted(counts["skip"].items()): 727 for reason, n in sorted(counts["skip"].items()):
755 print(f" skip x{n}: {reason}") 728 print(f" skip x{n}: {reason}")
756 if first: 729 if first:
diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py
index fcb4e0f9f..8dbbbbcfb 100644
--- a/tools/rdna2spirv.py
+++ b/tools/rdna2spirv.py
@@ -842,16 +842,20 @@ class Gen:
842 return words 842 return words
843 843
844 def decode_format(self, words, code): 844 def decode_format(self, words, code):
845 """Decode one element of format `code` from raw dwords -> 4 uint ids holding f32 bits (or uint for *_UINT/uint).""" 845 """Decode one element of format `code` from raw dwords -> 4 uint ids holding f32 bits (or uint for *_UINT/uint).
846
847 Missing channels repeat the format's own (component c = c mod n): measured on RX 6700 for SHADER-86.
848 UNORM/SNORM use correctly rounded OpFDiv by (2^n-1), not a reciprocal multiply."""
846 try: 849 try:
847 size, kind, widths = self.FORMATS[code] 850 size, kind, widths = self.FORMATS[code]
848 except KeyError: 851 except KeyError:
849 raise Unsupported(f"format {code} (not in FORMATS)") 852 raise Unsupported(f"format {code} (not in FORMATS)")
850 if kind in ("f32", "u32"): 853 if kind in ("f32", "u32"):
851 vals = list(words[:len(widths)]) 854 n = len(widths)
852 if kind == "u32": 855 vals = list(words[:n])
853 vals = vals # integers are passed through as their bits 856 while len(vals) < 4:
854 return vals + [self.cu(0)] * (3 - len(vals) + 1 if len(vals) < 4 else 0) 857 vals.append(vals[len(vals) % n])
858 return vals
855 out, bit = [], 0 859 out, bit = [], 0
856 for w in widths: 860 for w in widths:
857 src = words[bit // 32] 861 src = words[bit // 32]
@@ -865,21 +869,21 @@ class Gen:
865 elif kind == "unorm": 869 elif kind == "unorm":
866 c, x = self.tmp(), self.tmp() 870 c, x = self.tmp(), self.tmp()
867 self.emit(f"{c} = OpConvertUToF %float {f}") 871 self.emit(f"{c} = OpConvertUToF %float {f}")
868 self.emit(f"{x} = OpFMul %float {c} {self.fconst(1.0 / ((1 << w) - 1))}") 872 self.emit(f"{x} = OpFDiv %float {c} {self.fconst(float((1 << w) - 1))}")
869 out.append(self.tou(x)) 873 out.append(self.tou(x))
870 elif kind == "snorm": 874 elif kind == "snorm":
871 si, c, x, cl = self.tmp(), self.tmp(), self.tmp(), self.tmp() 875 si, c, x, cl = self.tmp(), self.tmp(), self.tmp(), self.tmp()
872 self.emit(f"{si} = OpBitFieldSExtract %int {self.as_int(src)} {self.cu(bit % 32)} {self.cu(w)}") 876 self.emit(f"{si} = OpBitFieldSExtract %int {self.as_int(src)} {self.cu(bit % 32)} {self.cu(w)}")
873 self.emit(f"{c} = OpConvertSToF %float {si}") 877 self.emit(f"{c} = OpConvertSToF %float {si}")
874 self.emit(f"{x} = OpFMul %float {c} {self.fconst(1.0 / ((1 << (w - 1)) - 1))}") 878 self.emit(f"{x} = OpFDiv %float {c} {self.fconst(float((1 << (w - 1)) - 1))}")
875 self.emit(f"{cl} = OpExtInst %float %glsl FMax {x} {self.fconst(-1.0)}") 879 self.emit(f"{cl} = OpExtInst %float %glsl FMax {x} {self.fconst(-1.0)}")
876 out.append(self.tou(cl)) 880 out.append(self.tou(cl))
877 else: # uint: raw integer 881 else: # uint: raw integer
878 out.append(f) 882 out.append(f)
879 bit += w 883 bit += w
880 one = self.cu(0x3F800000) if kind in ("f16", "unorm", "snorm") else self.cu(1) 884 n = len(out)
881 while len(out) < 4: 885 while len(out) < 4:
882 out.append(self.cu(0) if len(out) < 3 else one) 886 out.append(out[len(out) % n])
883 return out 887 return out
884 888
885 BUF_ATOMICS = {"add": ("OpAtomicIAdd", 0), "sub": ("OpAtomicISub", 0), "umin": ("OpAtomicUMin", 0xFFFFFFFF), 889 BUF_ATOMICS = {"add": ("OpAtomicIAdd", 0), "sub": ("OpAtomicISub", 0), "umin": ("OpAtomicUMin", 0xFFFFFFFF),
@@ -1055,13 +1059,22 @@ class Gen:
1055 self.emit(f"{s} = OpSelect %uint {e} {dec[c]} {comps[c]}") 1059 self.emit(f"{s} = OpSelect %uint {e} {dec[c]} {comps[c]}")
1056 nxt.append(s) 1060 nxt.append(s)
1057 comps = nxt 1061 comps = nxt
1058 # DST_SEL swizzle: 0 -> 0, 1 -> 1.0, 4..7 -> X..W. 1062 # DST_SEL swizzle: 0 -> 0, 1 -> 1.0 (float/norm) or integer 1 (UINT/SINT; SHADER-86), 4..7 -> X..W.
1063 is_int_fmt = "%false"
1064 for code_v, (_, kind, _) in self.FORMATS.items():
1065 if kind in ("u32", "uint"):
1066 e, o = self.tmp(), self.tmp()
1067 self.emit(f"{e} = OpIEqual %bool {fmt} {self.cu(code_v)}")
1068 self.emit(f"{o} = OpLogicalOr %bool {is_int_fmt} {e}")
1069 is_int_fmt = o
1070 dst1 = self.tmp()
1071 self.emit(f"{dst1} = OpSelect %uint {is_int_fmt} {self.cu(1)} {self.cu(0x3F800000)}")
1059 outs = [] 1072 outs = []
1060 for c in range(ncomp): 1073 for c in range(ncomp):
1061 sel = self.tmp() 1074 sel = self.tmp()
1062 self.emit(f"{sel} = OpBitFieldUExtract %uint {d3} {self.cu(3 * c)} {self.cu(3)}") 1075 self.emit(f"{sel} = OpBitFieldUExtract %uint {d3} {self.cu(3 * c)} {self.cu(3)}")
1063 r = self.cu(0) 1076 r = self.cu(0)
1064 for code_v, src in ((1, self.cu(0x3F800000)), (4, comps[0]), (5, comps[1]), (6, comps[2]), (7, comps[3])): 1077 for code_v, src in ((1, dst1), (4, comps[0]), (5, comps[1]), (6, comps[2]), (7, comps[3])):
1065 e, s = self.tmp(), self.tmp() 1078 e, s = self.tmp(), self.tmp()
1066 self.emit(f"{e} = OpIEqual %bool {sel} {self.cu(code_v)}") 1079 self.emit(f"{e} = OpIEqual %bool {sel} {self.cu(code_v)}")
1067 self.emit(f"{s} = OpSelect %uint {e} {src} {r}") 1080 self.emit(f"{s} = OpSelect %uint {e} {src} {r}")