From 22a8be16cdcc9f2bd51ebb10f2a41b27cec19477 Mon Sep 17 00:00:00 2001 From: OreoFR <29048345+OreoFR@users.noreply.github.com> Date: Fri, 27 Nov 2026 08:58:14 +0100 Subject: [PATCH 1/2] rdna2spirv: decode only the components a typed load writes; fconst is an OpConstant (SHADER-FORMAT-DECODE-ONE-COMPONENT) A buffer_load_format_* with a run-time FORMAT called the four per-component decode functions %fmt_dec_c0..3 at every load, whatever it wrote. One function %fmt_dec(format, element, component) replaces them, and a load calls it once per register it writes, with the component that register's DST_SEL picks: _x makes one call, not four. The function computes the four components' channel width and offset as before and the parameter selects one, so the values are the same. fconst (and tof of a uint constant) emitted a new OpBitcast of the uint constant at every use; they now give one cached OpConstant %float per bit pattern, written so spirv-as reads back the same 32 bits (float_literal: shortest decimal for a finite value, the SPIRV-Tools hex-float spelling for an infinity or a NaN). The test interpreters read that spelling. Tests: test_buffer_format_decode_one.py with hand-written fixtures (calls per load, values for 16 codes, swizzles, out of bounds, _x/_xy against _xyzw for all 128 codes) and test_fconst_constant.py (exact bits of +-0, denormals, infinities and NaN payloads). Co-Authored-By: Claude Opus 5.5 --- docs/design.md | 2 +- .../fixtures/typed_load_runtime_x.asm | 11 + .../fixtures/typed_load_runtime_xy.asm | 11 + .../fixtures/typed_load_runtime_xyzw.asm | 11 + tests/semantic/spirv_mini_interp.py | 22 +- tests/semantic/spirv_wave_interp.py | 15 +- tests/semantic/test_alu_sincos.py | 7 +- tests/semantic/test_bitcast_round_trip.py | 2 +- .../semantic/test_buffer_format_decode_one.py | 123 ++++++++++ tests/semantic/test_fconst_constant.py | 99 ++++++++ tests/semantic/test_format_decode_table.py | 39 ++-- tests/semantic/test_image_store_dmask.py | 1 + tests/spirv_interp.py | 20 +- tests/test_rcp_iflag_mods.py | 5 +- tests/test_rdna2spirv_decode.py | 15 +- tests/test_translate.py | 6 +- tools/rdna2spirv.py | 213 ++++++++++++------ 17 files changed, 491 insertions(+), 111 deletions(-) create mode 100644 tests/semantic/fixtures/typed_load_runtime_x.asm create mode 100644 tests/semantic/fixtures/typed_load_runtime_xy.asm create mode 100644 tests/semantic/fixtures/typed_load_runtime_xyzw.asm create mode 100644 tests/semantic/test_buffer_format_decode_one.py create mode 100644 tests/semantic/test_fconst_constant.py diff --git a/docs/design.md b/docs/design.md index 7bff52e7f9..aa9c8d78c1 100644 --- a/docs/design.md +++ b/docs/design.md @@ -328,7 +328,7 @@ How the generated SPIR-V expects the runtime to work: | 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`). For a native Metal path, `tools/spirv_metal_set0.py` sizes set 0's runtime arrays from `vulkan_bindless.h` and moves each binding to its own argument-buffer ID range (binding b starts at the capacities of bindings 0..b-1 added up), to convert with SPIRV-Cross `--msl-decoration-binding`: SPIRV-Cross 1.4.363.0 otherwise puts every runtime array at one ID and comments all but one out as "Overlapping binding" (SHADER-161). `cs_imgstore` converted this way writes all 3×64 texels correctly in a native Metal dispatch on an Apple A18 Pro. | | 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–4, i32 ×1–4 (formats 21/63/73/76), f16 ×1/2/4, unorm8 ×1/2/4, snorm8 ×1/2/4, uint8 ×1/2/4, sint8 ×1/2/4, unorm16 ×1/2/4, snorm16 ×1/2/4, uint16 ×1/2/4, sint16 ×1/2/4, 10-10-10-2 and 2-10-10-10 unorm, and, since 2026-11-22, the other GFX10 buffer codes 1–77 (every USCALED/SSCALED, 10_11_11 and 11_11_10 FLOAT, the 10_10_10_2 and 2_10_10_10 families, 8_8_8_8 and 16_16_16_16 SINT and SCALED; see *Typed buffer formats*). Others (code 0 and 78 up) give 0. The 8- and 16-bit UINT/SINT formats 5, 6, 11, 12, 18, 19, 28, 61 and 70 were missing until 2026-11-22 and read 0: UINT channels zero-extend, SINT channels sign-extend, d16 packs them as 16-bit integers, measured natively on gfx1036 (wave32 and wave64) with `tools/hw_oracle` and checked word for word by `tests/semantic/test_buffer_format_narrow_int.py`; GPU-checked by `runtime/test/shaders/cs_fmt_int_narrow.asm`, whose 136 expected words are the same program run natively on gfx1036 (exact on an RTX 5080 and on the gfx1036 iGPU through Vulkan). Full-width SINT accesses preserve integer bits. D16 SINT loads saturate to signed 16-bit and D16 stores sign-extend, covered by the synthetic `cs_fmt_sint32.asm` readback. 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 give the correctly rounded quotient by (2ⁿ−1), as the hardware does (0 mismatches vs hardware over 395,776 conversions on that GPU). It is built with integer ops (`Gen.norm_bits`): x/(2ⁿ−1) in binary is x's bits repeated, so a 64-bit multiply by the repeat pattern, `FindUMsb` and the round bit give the f32 exactly (the tail never ends, so there are no ties). `OpFDiv` is not enough on the GPU: Vulkan allows it 2.5 ULP, and on an RX 6700 (AMD Windows 26.11.2) and an RTX 5090 it returned the reciprocal-multiply bits (8_UNORM 130/256 exact, #599). Checked against exact values in `tests/semantic/test_norm_decode.py` (every value up to 8 bits, edges and the reciprocal-multiply misses for 10, 15 and 16 bits). 8_SNORM (2), 16_SNORM (8) and 8_8_SNORM (15) were missing until 2026-11-22 and decoded to 0. 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. The `_xy` and `_xyz` forms (buffer and tbuffer) are GPU-checked by `cs_fmt_xy_xyz.asm`, whose words were measured natively on a Radeon 680M (gfx1035, RDNA2): they write only their 2 or 3 VGPRs, and missing channels repeat there too (TEST-185). | | Descriptor hash table | `uint mask; entries[mask+1] of 10 uints: key[0..7], index, kind`. The last word is 0 in an empty slot; otherwise bit 31 marks it occupied and bits 0..5 / 8..11 name the sampled / storage arrays the index is bound in (docs/d3d12_vulkan.md section 5.1, "Images and samplers (T# dimension)" below). A module reads it only when its index entry says `"descriptor_table": "tagged"`; `--descriptor-table plain` leaves the word unread and gives byte-identical modules to the translator before the marker (checked with a 5-instruction pixel shader: old and plain output are the same bytes). The key is a T# or a padded S#. FNV-1a over the eight key words selects the first slot by default. With `--descriptor-hash=fnv1a_fmix32` the shader applies MurmurHash3 fmix32 before masking the slot. Every translated module then records `"descriptor_hash": "fnv1a_fmix32"` in its index entry. An absent key means `fnv1a`. The runtime and shader must select the same hash. 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. Outside the wave64 emulation, the lookup's result goes through `OpGroupNonUniformBroadcastFirst` before it indexes the image or sampler array. The lookup key words come from SGPRs, so every invocation in a subgroup has the same index; the broadcast is an identity on all drivers and marks the value uniform for the compiler. It declares `GroupNonUniform` and `GroupNonUniformBallot`, without a shuffle capability or subgroup-lane input. The shader index records the capabilities; its `features` field lists optional Vulkan device features. Mesa ANV 26.2.7 on an Intel Alder Lake-S UHD (Xe-LP, Linux) segfaults in `vkCreate*Pipelines` on a sampler index taken straight from the probe loop when that sampler serves both a float and an integer image (`cs_sample_lz_int_d16`, `ps_ssharp`); with the broadcast both pass. Checked by the unit test `test_lookup_result_is_broadcast_before_use` in `tests/test_desc_cache.py` (standard library only: no GPU, LLVM or SPIRV-Tools). | -| Run-time format decode cost | A `buffer_load_format_*` whose format comes from the V# is decoded by table, without a branch: one shared function per output component (`%fmt_dec_c0`…`%fmt_dec_c3`) reads the format's kind, channel count and channel widths from the module table `%fmt_desc_tab`, and the kind picks the conversion with `OpSelect`; the exact UNORM/SNORM quotient comes from the shared `%fmt_norm_bits`, whose width's 64-bit repeat constant is read from `%fmt_norm_rep_tab`. A code outside the table gives zeros, a format with fewer channels repeats its own (component *c* = *c* mod *n*), and the element size is selected from the format alone (`%fmt_size_tab`), the per-lane byte offset added once. Until 2026-11-23 the shared function instead held every format's decode and a binary search over the codes (`OpSelectionMerge` with `DontFlatten`): 3,498 instructions and 306 branches in the module of a shader with one dynamic-format load (250,869 bytes). Now the four functions hold 565 instructions and no branch, and that module is 56,763 bytes. The decode functions take the format code and the element's four dwords as a `v4uint`, so their function type has a structure of its own: a type of `uint` × 5 repeats the type of the `x_round` helpers, and SPIR-V forbids two non-aggregate types with the same structure. Over the 1.0.2.1 corpus the 11,400 shaders that use this path all translate and pass \spirv-val\ (the previous translator included), and their modules shrink from 11,163,872,428 to 10,454,474,528 bytes (-6.35%). The 15,103 shaders without a run-time FORMAT come out byte for byte identical (checked on a 297-shader sample, every 51st of them). The values are unchanged: every one of the 128 codes gives the same words as the branch search, checked by `tests/semantic/test_format_decode_table.py` (each code against a reference decoded from the raw bits with exact quotients, plus the branch-free and shared-per-component shape). The old translation was confirmed on an RTX 4090 (621.01) against the decode-everything translation: identical output buffers for all 128 codes in four configurations (four byte alignments, out-of-range records, constant DST_SEL), xyzw and d16_xyzw. The branch-free decode costs more ALU per load than the search (every kind's conversion is computed and one is kept), so it trades run time for module size and compile time. | +| Run-time format decode cost | A `buffer_load_format_*` whose format comes from the V# is decoded by table, without a branch: one shared function, `%fmt_dec(format, element, component)`, reads the format's kind, channel count and channel widths from the module table `%fmt_desc_tab`, and the kind picks the conversion with `OpSelect`; the exact UNORM/SNORM quotient comes from the shared `%fmt_norm_bits`, whose width's 64-bit repeat constant is read from `%fmt_norm_rep_tab`. A code outside the table gives zeros, a format with fewer channels repeats its own (component *c* = *c* mod *n*), and the element size is selected from the format alone (`%fmt_size_tab`), the per-lane byte offset added once. Until 2026-11-23 the shared function instead held every format's decode and a binary search over the codes (`OpSelectionMerge` with `DontFlatten`): 3,498 instructions and 306 branches in the module of a shader with one dynamic-format load (250,869 bytes). Then four functions, one per output component, held 565 instructions and no branch, and that module was 56,763 bytes; every load called all four. Over the 1.0.2.1 corpus the 11,400 shaders that use this path all translate and pass \spirv-val\ (the previous translator included), and their modules shrink from 11,163,872,428 to 10,454,474,528 bytes (-6.35%). The 15,103 shaders without a run-time FORMAT come out byte for byte identical (checked on a 297-shader sample, every 51st of them). The values are unchanged: every one of the 128 codes gives the same words as the branch search, checked by `tests/semantic/test_format_decode_table.py` (each code against a reference decoded from the raw bits with exact quotients, plus the branch-free and shared shape). The old translation was confirmed on an RTX 4090 (621.01) against the decode-everything translation: identical output buffers for all 128 codes in four configurations (four byte alignments, out-of-range records, constant DST_SEL), xyzw and d16_xyzw. Since 2026-11-27 the component is the function's last parameter (154 instructions), and a load calls it once per register it writes, with the component that register's DST_SEL picks (DST_SEL − 4; a register whose DST_SEL is 0, 1 or reserved discards the call's value): `buffer_load_format_x` makes one call, not four. The values are the same by construction (the four components' channel width and offset are computed as before and the parameter selects one), checked against the previous translator by the mini interpreter on 22,528 loads (`_x` … `_xyzw` and `d16_x` … `d16_xyzw`, all 128 codes, random DST_SEL, byte alignments and out-of-range records) and on an RTX 4070 Laptop (621.40) by the typed-load GPU tests; `tests/semantic/test_buffer_format_decode_one.py` counts the calls. The function takes the format code, the element's four dwords as a `v4uint` and the component, so its function type has a structure of its own: a type of `uint` × 5 repeats the type of the `x_round` helpers, and SPIR-V forbids two non-aggregate types with the same structure. The branch-free decode costs more ALU per load than the search (every kind's conversion is computed and one is kept), so it trades run time for module size and compile time. | | 3D explicit-gradient texture samples | For `image_sample_d` and `image_sample_d_cl` on a 3D view, the first six address VGPRs contain dP/dx.xyz and dP/dy.xyz. XYZ and the optional minimum LOD follow. With `a16`, the six derivative VGPRs still hold f32; the following two words contain packed f16 coordinates and the optional clamp. The hand-written `tests/semantic/fixtures/volume_gradients.asm` checks the source registers of both gradients, coordinates and clamp. LLVM gfx1030 assembles all four forms and their modules validate for Vulkan 1.2. [LLVM GFX10 address sizing](https://reviews.llvm.org/D102231) and [SPIR-V Grad operands](https://registry.khronos.org/SPIR-V/specs/unified1/SPIRV.html#Image_Operands) | | `image_sample_c_l` | Scalar 2D depth comparison (`dmask:0x1`) takes the f32 reference, XY coordinates and explicit mip in that order. Under A16 the reference stays full-width; XY share a VGPR and LOD uses the next low half. D16 returns the comparison in the low half of the destination. Confirmed against LLVM AMDGPU's `llvm.amdgcn.image.sample[.a16].dim.ll` lowering and synthetic Vulkan 1.2 modules in `test_explicit_mip_depth_compare`. | | Packed sample addresses | GFX10 `image_sample_d` with `a16` keeps the non-G16 gradients as f32 and packs the following coordinates as f16 pairs, following LLVM's GFX10 operand layout. `test_a16_sample_gradients_use_full_vgprs` checks the emitted gradient operands, and `ps_texture_grad_a16` checks coordinate selection with a single-mip texture on RTX 5080. The same holds for every extra argument before the coordinates (LLVM `getAddrSizeMIMGOp`: one word each, then the gradients, then the packed halves; llvm-mc takes `v[0:2]` for a 2D `image_sample_c_b ... a16`): an `image_sample_b` bias keeps its VGPR with the f16 in the low half, an `image_sample_c_lz` z-compare its f32 VGPR, and `image_sample_d_cl` its four f32 gradients, with the clamp the half right after the coordinates (an f16 pad may follow it). Until 2026-11-21 those were unpacked as pairs too, and the clamp was taken from the last half. GPU-checked on an NVIDIA GeForce RTX 2060 SUPER (Linux, driver 620.70.06) with `ps_texture_bias_a16`, `ps_sample_c_lz_a16` (`vk_texture_test dref_a16`) and `ps_texture_grad_cl_a16`, which draws on the `--two-mip` texture with the clamp 0 on the left half and 1 on the right: 4096/4096 pixels exact each. The old reading got 4,032 bias pixels and both depth-compare results in 2,048 pixels wrong, a clamp taken from the pad read mip 1 on the left half, and the sample without its clamp mip 0 on the right half (2,048 pixels each). | diff --git a/tests/semantic/fixtures/typed_load_runtime_x.asm b/tests/semantic/fixtures/typed_load_runtime_x.asm new file mode 100644 index 0000000000..4ac803fde1 --- /dev/null +++ b/tests/semantic/fixtures/typed_load_runtime_x.asm @@ -0,0 +1,11 @@ +; buffer_load_format_x with the V# in s[0:3] (push constants): its FORMAT and DST_SEL are known only at run time. +; The registers the load does not write keep their sentinels. +v_mov_b32 v2, 0xA5A5A5A5 +v_mov_b32 v3, 0x5A5A5A5A +v_mov_b32 v4, 0x13579BDF +v_mov_b32 v5, 0x2468ACE0 +v_mov_b32 v1, 0 +buffer_load_format_x v2, v1, s[0:3], 0 offen +s_waitcnt vmcnt(0) +exp mrt0 v2, v3, v4, v5 done vm +s_endpgm diff --git a/tests/semantic/fixtures/typed_load_runtime_xy.asm b/tests/semantic/fixtures/typed_load_runtime_xy.asm new file mode 100644 index 0000000000..536779b7c7 --- /dev/null +++ b/tests/semantic/fixtures/typed_load_runtime_xy.asm @@ -0,0 +1,11 @@ +; buffer_load_format_xy with the V# in s[0:3] (push constants): its FORMAT and DST_SEL are known only at run time. +; The registers the load does not write keep their sentinels. +v_mov_b32 v2, 0xA5A5A5A5 +v_mov_b32 v3, 0x5A5A5A5A +v_mov_b32 v4, 0x13579BDF +v_mov_b32 v5, 0x2468ACE0 +v_mov_b32 v1, 0 +buffer_load_format_xy v[2:3], v1, s[0:3], 0 offen +s_waitcnt vmcnt(0) +exp mrt0 v2, v3, v4, v5 done vm +s_endpgm diff --git a/tests/semantic/fixtures/typed_load_runtime_xyzw.asm b/tests/semantic/fixtures/typed_load_runtime_xyzw.asm new file mode 100644 index 0000000000..faf0820d9c --- /dev/null +++ b/tests/semantic/fixtures/typed_load_runtime_xyzw.asm @@ -0,0 +1,11 @@ +; buffer_load_format_xyzw with the V# in s[0:3] (push constants): its FORMAT and DST_SEL are known only at run time. +; The registers the load does not write keep their sentinels. +v_mov_b32 v2, 0xA5A5A5A5 +v_mov_b32 v3, 0x5A5A5A5A +v_mov_b32 v4, 0x13579BDF +v_mov_b32 v5, 0x2468ACE0 +v_mov_b32 v1, 0 +buffer_load_format_xyzw v[2:5], v1, s[0:3], 0 offen +s_waitcnt vmcnt(0) +exp mrt0 v2, v3, v4, v5 done vm +s_endpgm diff --git a/tests/semantic/spirv_mini_interp.py b/tests/semantic/spirv_mini_interp.py index 8868dd5fb0..61a416de24 100644 --- a/tests/semantic/spirv_mini_interp.py +++ b/tests/semantic/spirv_mini_interp.py @@ -210,6 +210,26 @@ def bits_f32(b): return _F32(b & MASK) +_HEX_FLOAT = re.compile(r"([+-]?)0[xX]([0-9a-fA-F]*)\.?([0-9a-fA-F]*)[pP]([+-]?\d+)") + + +def f32_literal(tok): + """The value of a 32-bit OpConstant %float literal as spirv-as reads it: a decimal, or a hex-float, where exponent + +128 is the SPIRV-Tools spelling of an infinity (0x1p+128) or a NaN with its payload (0x1.8p+128, the quiet NaN), + as rdna2spirv.float_literal writes them.""" + m = _HEX_FLOAT.fullmatch(tok) + if m is None: + return f32(float(tok)) + sign, ipart, fpart, exp = m.groups() + sig = int(ipart + fpart or "0", 16) + top = sig.bit_length() - 1 + if sig and int(exp) - 4 * len(fpart) + top == 128: + frac = sig & ((1 << top) - 1) + mant = frac << (23 - top) if top <= 23 else frac >> (top - 23) + return bits_f32((0x80000000 if sign == "-" else 0) | 0x7F800000 | mant) + return f32(float.fromhex(tok)) + + def half_to_float(h): # Bit-level f16 -> f32 (sign, exponent, fraction; every result is exact in binary32). struct's '> (top - 23) + return (0x80000000 if sign == "-" else 0) | 0x7F800000 | mant + return struct.unpack(" 1.0 = 1065353216) fails the check + # Sabotaging the 2*pi scaling factor (the float constant 0x40c90fdb -> 1.0) fails the check spv = translate_ps([ f"v_mov_b32 v1, {H_QUARTER:#x}", "v_sin_f16 v0, v1", "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm", ]) - self.assertIn("1086918619", spv) + two_pi = "%fc40c90fdb = OpConstant %float 6.2831854820251465" + self.assertIn(two_pi, spv) expected = H_ONE self.assertEqual(si.run_fragment(spv)["%out_mrt0"][0] & 0xFFFF, expected) - sabotaged = spv.replace("1086918619", "1065353216") + sabotaged = spv.replace(two_pi, "%fc40c90fdb = OpConstant %float 1.0") sabotaged_out = si.run_fragment(sabotaged)["%out_mrt0"][0] & 0xFFFF self.assertNotEqual(sabotaged_out, expected) diff --git a/tests/semantic/test_bitcast_round_trip.py b/tests/semantic/test_bitcast_round_trip.py index c1ff18ba3c..a288a75cfe 100644 --- a/tests/semantic/test_bitcast_round_trip.py +++ b/tests/semantic/test_bitcast_round_trip.py @@ -48,7 +48,7 @@ def wrapped(self, x): class BitcastRoundTripTest(unittest.TestCase): def test_helpers_return_the_source(self): g = rdna2spirv.Gen.__new__(rdna2spirv.Gen) - g.body, g.n, g.bitcast_from, g.emulate = [], 0, {}, False + g.body, g.n, g.bitcast_from, g.emulate, g.fconst_of = [], 0, {}, False, {} f = g.tof("%t100") self.assertEqual(g.tou(f), "%t100") u = g.tou("%t200") diff --git a/tests/semantic/test_buffer_format_decode_one.py b/tests/semantic/test_buffer_format_decode_one.py new file mode 100644 index 0000000000..8fd3824ac2 --- /dev/null +++ b/tests/semantic/test_buffer_format_decode_one.py @@ -0,0 +1,123 @@ +"""buffer_load_format_* with a run-time FORMAT decodes only the components its registers take. + +The decode is one shared function, %fmt_dec(format, the element's four dwords, component). A load calls it once per +register it writes, with the component that register's DST_SEL field picks (4..7 -> X..W): buffer_load_format_x +makes one call, _xy two, _xyzw four. Until 2026-11-27 every load called four per-component functions, whatever it +wrote. The values do not change: DST_SEL 1 is 1.0 (integer 1 for an integer format), 0 and the reserved codes are 0, +an out-of-bounds element decodes to 0, and a register the load does not write keeps its value. + +The programs are the hand-written fixtures fixtures/typed_load_runtime_{x,xy,xyzw}.asm: the V# is s[0:3], read from +the push constants, so one translation serves every format and DST_SEL. +""" +import os +import random +import unittest + +import support +from spirv_mini_interp import run_fragment +from test_format_decode_table import BASE, WORDS, function_body, reference + +import rdna2spirv + +HERE = os.path.dirname(os.path.abspath(__file__)) +SENTINELS = (0xA5A5A5A5, 0x5A5A5A5A, 0x13579BDF, 0x2468ACE0) +WIDTHS = {"x": 1, "xy": 2, "xyzw": 4} +XYZW = 4 | 5 << 3 | 6 << 6 | 7 << 9 +# 8_UNORM, 16_UNORM, 16_SNORM, 16_FLOAT, 32_UINT, 32_SINT, 32_FLOAT, 8_8_UNORM, 16_16_UINT, 16_16_FLOAT, +# 8_8_8_8_UNORM, 8_8_8_8_SINT, 32_32_FLOAT, 32_32_32_FLOAT, 32_32_32_32_UINT and a code outside FORMATS +CODES = (1, 7, 8, 13, 20, 21, 22, 14, 27, 29, 56, 61, 64, 74, 75, 127) +_SPV = {} + + +def spv_of(width): + if width not in _SPV: + with open(os.path.join(HERE, "fixtures", f"typed_load_runtime_{width}.asm"), encoding="utf-8") as f: + lines = [ln.strip() for ln in f if ln.strip() and not ln.startswith(";")] + _SPV[width] = support.translate_lines(f"ps_typed_load_runtime_{width}", lines) + return _SPV[width] + + +def run(width, code, dst_sel, num_records=0x100): + w3 = 0x30000000 | code << 12 | dst_sel + memory = {BASE + 4 * i: w for i, w in enumerate(WORDS)} + return run_fragment(spv_of(width), push_constants=[BASE, 0, num_records, w3] + [0] * 28, + memory=memory)["%out_mrt0"] + + +def is_integer(code): + """DST_SEL 1 reads integer 1 for the integer formats and the codes outside FORMATS, 1.0 for the others.""" + return code not in rdna2spirv.Gen.FORMATS or rdna2spirv.Gen.FORMATS[code][1] in ("u32", "i32", "uint", "sint") + + +def expected(width, code, sels, in_bounds=True): + ref = reference(code) if in_bounds else (0, 0, 0, 0) + out = list(SENTINELS) + for c in range(WIDTHS[width]): + s = sels[c] + out[c] = ref[s - 4] if s >= 4 else (1 if is_integer(code) else 0x3F800000) if s == 1 else 0 + return tuple(out) + + +def pack(sels): + return sum(s << (3 * i) for i, s in enumerate(sels)) + + +class DecodeCalls(unittest.TestCase): + def test_one_call_per_written_register(self): + for width, n in WIDTHS.items(): + with self.subTest(width=width): + spv = spv_of(width) + calls = [ln for ln in function_body(spv, "%main") if "OpFunctionCall %uint %fmt_dec " in ln] + self.assertEqual(len(calls), n) + # The component is the call's last argument, a run-time id (DST_SEL - 4), not a constant. + for ln in calls: + self.assertRegex(ln, r"OpFunctionCall %uint %fmt_dec %t\d+ %t\d+ %t\d+$") + self.assertEqual(spv.count("%fmt_dec = OpFunction %uint None %fn_fmt_dec"), 1) + self.assertNotIn("%fmt_dec_c", spv) + + def test_fewer_registers_make_a_smaller_module(self): + sizes = [len(spv_of(w).splitlines()) for w in ("x", "xy", "xyzw")] + self.assertLess(sizes[0], sizes[1]) + self.assertLess(sizes[1], sizes[2]) + + +class DecodeValues(unittest.TestCase): + def test_formats_with_identity_selectors(self): + for code in CODES: + if reference(code) is None: + continue + for width in WIDTHS: + with self.subTest(code=code, width=width): + self.assertEqual(run(width, code, XYZW), expected(width, code, (4, 5, 6, 7))) + + def test_formats_with_swizzled_and_constant_selectors(self): + # Each register takes another component, or 0, 1, or a reserved code (2, 3), from the descriptor. + for sels in ((7, 6, 5, 4), (5, 1, 0, 6), (6, 3, 2, 1), (1, 7, 7, 0), (0, 4, 1, 5)): + for code in CODES: + if reference(code) is None: + continue + for width in WIDTHS: + with self.subTest(sels=sels, code=code, width=width): + self.assertEqual(run(width, code, pack(sels)), expected(width, code, sels)) + + def test_out_of_bounds_reads_zero_and_keeps_the_constant_one(self): + for code in (1, 20, 22, 56, 75): + for width in WIDTHS: + with self.subTest(code=code, width=width): + sels = (1, 4, 0, 7) + self.assertEqual(run(width, code, pack(sels), num_records=0), + expected(width, code, sels, in_bounds=False)) + + def test_narrow_loads_match_the_xyzw_load(self): + # Every code, random selectors: the registers _x and _xy write are the first of what _xyzw writes. + rnd = random.Random(1608) + for code in range(128): + sels = [rnd.randrange(8) for _ in range(4)] + full = run("xyzw", code, pack(sels)) + for width, n in (("x", 1), ("xy", 2)): + with self.subTest(code=code, sels=sels, width=width): + self.assertEqual(run(width, code, pack(sels)), full[:n] + SENTINELS[n:]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantic/test_fconst_constant.py b/tests/semantic/test_fconst_constant.py new file mode 100644 index 0000000000..20b338e9ec --- /dev/null +++ b/tests/semantic/test_fconst_constant.py @@ -0,0 +1,99 @@ +"""Gen.fconst gives an OpConstant %float with the exact f32 bits, one per value, not an OpBitcast at every use. + +Until 2026-11-27 fconst bitcast the uint constant of the bits at every use (4.3% of the instructions of a large +RaytracingResolve module). An OpConstant %float takes the 32-bit word literally, so the value is the same as long as +the literal spells exactly those bits: rdna2spirv.float_literal writes the shortest decimal of a finite value (-0.0 +and the denormals too) and the SPIRV-Tools hex-float spelling of an infinity or a NaN, payload as stored. Checked here +through tools/spirv_asm.py, which reads float literals as spirv-as does, and the mini interpreter. +""" +import re +import struct +import sys +import unittest + +import support +from spirv_mini_interp import f32_bits, f32_literal, run_fragment + +import rdna2spirv + +sys.path.insert(0, support.TOOLS_DIR) +import spirv_asm # noqa: E402 + +# +-0, the smallest and largest denormals, the smallest normal, 1 and its neighbour, the largest finite values, +# +-infinity, quiet and signalling NaNs with payloads and both signs, and a few ordinary values. +TRICKY = (0x00000000, 0x80000000, 0x00000001, 0x80000001, 0x007FFFFF, 0x807FFFFF, 0x00800000, 0x3F800000, + 0x3F800001, 0x7F7FFFFF, 0xFF7FFFFF, 0x7F800000, 0xFF800000, 0x7FC00000, 0xFFC00000, 0x7F800001, + 0xFF800001, 0x7FBFFFFF, 0xFFFFFFFF, 0x7FC00001, 0x40C90FDB, 0x1F800000, 0x5F800000, 0xBF000000) + + +def bits_of(x): + return struct.unpack(" -32767; three turns -> +0. + self.assertEqual(out[0], 0) + self.assertEqual(out[1] & 0xFFFF, (-32767) & 0xFFFF) + self.assertEqual(out[2], 0) + self.assertEqual(out[3], bits_of(0.5)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantic/test_format_decode_table.py b/tests/semantic/test_format_decode_table.py index f868b7a4c3..d2b23c80c0 100644 --- a/tests/semantic/test_format_decode_table.py +++ b/tests/semantic/test_format_decode_table.py @@ -1,11 +1,12 @@ """The run-time FORMAT decode of buffer_load_format (Gen.fmt_dec_component) is table-driven and branch-free. -Every code goes through the translator and the mini interpreter, which runs the shared per-component functions, and is +Every code goes through the translator and the mini interpreter, which runs the shared decode function, and is compared with a reference decoded here from the raw bits with exact quotients. A code outside FORMATS gives zeros. The decode has no branch: the format's kind, channel count and channel widths come from a table, and the kind picks -the conversion with selects. The module carries one copy of the decode, one function per output component, instead of -one copy per format: before, the shared function held every format's decode and a binary search over the codes. +the conversion with selects. The module carries one copy of the decode, one function whose last parameter is the output +component, instead of one copy per format: before, the shared function held every format's decode and a binary search +over the codes. """ import struct import unittest @@ -96,29 +97,29 @@ def test_every_format_and_the_codes_between(self): def test_the_decode_has_no_branch(self): spv = module_of() - for k in range(4): - body = function_body(spv, f"%fmt_dec_c{k}") - self.assertTrue(body, f"the decode of component {k} is missing") - for line in body: - for op in BRANCHES: - self.assertNotIn(op, line, f"the decode branches: {line}") - - def test_the_decode_is_shared_per_component(self): + body = function_body(spv, "%fmt_dec") + self.assertTrue(body, "the decode is missing") + for line in body: + for op in BRANCHES: + self.assertNotIn(op, line, f"the decode branches: {line}") + + def test_the_decode_is_shared(self): spv = module_of() - for k in range(4): - self.assertIn(f"%fmt_dec_c{k} = OpFunction %uint None %fn_fmt_dec", spv) - self.assertIn(f"OpFunctionCall %uint %fmt_dec_c{k} ", spv) - # The load site calls the four functions; the decode itself is not inlined there. + self.assertIn("%fmt_dec = OpFunction %uint None %fn_fmt_dec", spv) + self.assertIn("%fn_fmt_dec = OpTypeFunction %uint %uint %v4uint_fmt %uint", spv) + self.assertNotIn("%fmt_dec_c", spv) + # The xyzw load calls the one function once per register; the decode itself is not inlined there. main = function_body(spv, "%main") - calls = [ln for ln in main if "OpFunctionCall %uint %fmt_dec_c" in ln] + calls = [ln for ln in main if "OpFunctionCall %uint %fmt_dec " in ln] self.assertEqual(len(calls), 4) def test_the_decode_is_small(self): spv = module_of() - count = sum(len(function_body(spv, f"%fmt_dec_c{k}")) for k in range(4)) + count = len(function_body(spv, "%fmt_dec")) # Before, the shared function held every format's decode and a binary search over the codes: 3,498 - # instructions and 306 branches in the module of a shader with one dynamic-format load. - self.assertLess(count, 900, f"the decode is {count} instructions") + # instructions and 306 branches in the module of a shader with one dynamic-format load. One function per + # component (565 instructions for the four) became one with the component as a parameter. + self.assertLess(count, 250, f"the decode is {count} instructions") if __name__ == "__main__": diff --git a/tests/semantic/test_image_store_dmask.py b/tests/semantic/test_image_store_dmask.py index 6d34e05616..427f0653bc 100644 --- a/tests/semantic/test_image_store_dmask.py +++ b/tests/semantic/test_image_store_dmask.py @@ -194,6 +194,7 @@ def texels(line: str) -> dict[str, list[int | None]]: dim = next(m for m in ins["mods"] if m.startswith("dim:")) g.image_store(ins["args"], ins["mods"], dim) consts = {name: value for value, name in g.consts.items()} + consts.update(g.fconst_of) # the float constants (a uint constant's tof is one), by their bits src: dict[str, tuple[str, int]] = {} out: dict[str, list[int | None]] = {} for line_ in g.body: diff --git a/tests/spirv_interp.py b/tests/spirv_interp.py index e70bc6c8a0..46ae5f62f6 100644 --- a/tests/spirv_interp.py +++ b/tests/spirv_interp.py @@ -15,6 +15,23 @@ M32 = 0xFFFFFFFF +def float_literal_bits(tok): + """The binary32 bits of an OpConstant %float literal as spirv-as reads it: a decimal, or a hex-float, where + exponent +128 is the SPIRV-Tools spelling of an infinity (0x1p+128) or a NaN with its payload (0x1.8p+128), + as tools/rdna2spirv.py's float_literal writes them. Raises ValueError for anything else.""" + m = re.fullmatch(r"([+-]?)0[xX]([0-9a-fA-F]*)\.?([0-9a-fA-F]*)[pP]([+-]?\d+)", tok) + if m is None: + return struct.unpack("> (top - 23) + return (0x80000000 if sign == "-" else 0) | 0x7F800000 | mant + return struct.unpack(" its OpConstant %float (these two + # are declared with the types) + self.fconst_of = {v: k for k, v in self.fconsts.items()} # and back: the id -> its bits # tof/tou results -> the id they were bitcast from. A bitcast of a bitcast gives the original id back: wherever # the key is valid its source is too (the key's own definition uses it), so no dominance is lost. self.bitcast_from = {} @@ -1822,6 +1826,14 @@ def tof(self, u): so u must be a %uint and tou's argument a %float; an %int's bits go through int_bits.""" if u in self.bitcast_from: return self.bitcast_from[u] + if u.startswith("%c"): + # A uint constant's bits are the float constant with them (fconst_bits), not a bitcast at every use. + try: + v = int(u[2:], 16) + except ValueError: + v = None + if v is not None and self.consts.get(v) == u: + return self.fconst_bits(v) f = self.tmp() self.emit(f"{f} = OpBitcast %float {u}") self.bitcast_from[f] = u @@ -1830,6 +1842,9 @@ def tof(self, u): def tou(self, f): if f in self.bitcast_from: return self.bitcast_from[f] + if f in self.fconst_of: + # A float constant's bits are the uint constant with them, as when fconst returned tof's bitcast of it. + return self.cu(self.fconst_of[f]) u = self.tmp() self.emit(f"{u} = OpBitcast %uint {f}") self.bitcast_from[u] = f @@ -3577,8 +3592,9 @@ def fmt_norm_function(self): "%fmt_norm_entry = OpLabel"] + lines + [f"OpReturnValue {res}", "OpFunctionEnd"]) return self.fmt_norm_fn - def fmt_dec_component(self, k, params): - """The value of output component k of an element of the run-time FORMAT, branch-free (SHADER-849). + def fmt_dec_component(self, params): + """The value of output component k (the uint params[2], 0..3) of an element of the run-time FORMAT, branch-free + (SHADER-849). The format's kind, channel count and channel widths come from one table word; the conversion the kind names is chosen with selects, so the decode has no branch and the module carries one copy of it, not one per @@ -3605,39 +3621,45 @@ def fmt_dec_component(self, k, params): self.emit(f"{w} = OpBitwiseAnd %uint {raw} {self.cu(63)}") widths.append(w) # The channel of the format that output component k takes: component c = c mod n. - # Its width and its bit offset (the sum of the widths before it). - if k == 0: - wid, off = widths[0], self.cu(0) - else: - offsets = [self.cu(0)] - for i in range(1, 4): - o = self.tmp() - self.emit(f"{o} = OpIAdd %uint {offsets[-1]} {widths[i - 1]}") - offsets.append(o) - if k == 1: - one, wid, off = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{one} = OpIEqual %bool {ncomp} {self.cu(1)}") - self.emit(f"{wid} = OpSelect %uint {one} {widths[0]} {widths[1]}") - self.emit(f"{off} = OpSelect %uint {one} {offsets[0]} {offsets[1]}") - elif k == 2: - two, wid, off = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{two} = OpULessThanEqual %bool {ncomp} {self.cu(2)}") - self.emit(f"{wid} = OpSelect %uint {two} {widths[0]} {widths[2]}") - self.emit(f"{off} = OpSelect %uint {two} {offsets[0]} {offsets[2]}") - else: - one, two, three = self.tmp(), self.tmp(), self.tmp() - w1, w2, wid, o1, o2, off = (self.tmp() for _ in range(6)) - self.emit(f"{one} = OpIEqual %bool {ncomp} {self.cu(1)}") - self.emit(f"{two} = OpIEqual %bool {ncomp} {self.cu(2)}") - self.emit(f"{three} = OpIEqual %bool {ncomp} {self.cu(3)}") - # component 3 takes channel 0 of a one- or three-channel format, channel 1 of a two-channel one - # and channel 3 of a four-channel one - self.emit(f"{w1} = OpSelect %uint {three} {widths[0]} {widths[3]}") - self.emit(f"{w2} = OpSelect %uint {two} {widths[1]} {w1}") - self.emit(f"{wid} = OpSelect %uint {one} {widths[0]} {w2}") - self.emit(f"{o1} = OpSelect %uint {three} {offsets[0]} {offsets[3]}") - self.emit(f"{o2} = OpSelect %uint {two} {offsets[1]} {o1}") - self.emit(f"{off} = OpSelect %uint {one} {offsets[0]} {o2}") + # Its width and its bit offset (the sum of the widths before it), for each k; k is the run-time + # parameter params[2], so the selects below pick among the four candidates. + offsets = [self.cu(0)] + for i in range(1, 4): + o = self.tmp() + self.emit(f"{o} = OpIAdd %uint {offsets[-1]} {widths[i - 1]}") + offsets.append(o) + cands = [(widths[0], offsets[0])] + one, wid, off = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{one} = OpIEqual %bool {ncomp} {self.cu(1)}") + self.emit(f"{wid} = OpSelect %uint {one} {widths[0]} {widths[1]}") + self.emit(f"{off} = OpSelect %uint {one} {offsets[0]} {offsets[1]}") + cands.append((wid, off)) + two, wid, off = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{two} = OpULessThanEqual %bool {ncomp} {self.cu(2)}") + self.emit(f"{wid} = OpSelect %uint {two} {widths[0]} {widths[2]}") + self.emit(f"{off} = OpSelect %uint {two} {offsets[0]} {offsets[2]}") + cands.append((wid, off)) + two_eq, three = self.tmp(), self.tmp() + w1, w2, wid, o1, o2, off = (self.tmp() for _ in range(6)) + self.emit(f"{two_eq} = OpIEqual %bool {ncomp} {self.cu(2)}") + self.emit(f"{three} = OpIEqual %bool {ncomp} {self.cu(3)}") + # component 3 takes channel 0 of a one- or three-channel format, channel 1 of a two-channel one + # and channel 3 of a four-channel one + self.emit(f"{w1} = OpSelect %uint {three} {widths[0]} {widths[3]}") + self.emit(f"{w2} = OpSelect %uint {two_eq} {widths[1]} {w1}") + self.emit(f"{wid} = OpSelect %uint {one} {widths[0]} {w2}") + self.emit(f"{o1} = OpSelect %uint {three} {offsets[0]} {offsets[3]}") + self.emit(f"{o2} = OpSelect %uint {two_eq} {offsets[1]} {o1}") + self.emit(f"{off} = OpSelect %uint {one} {offsets[0]} {o2}") + cands.append((wid, off)) + # k picks its candidate; a k above 3 takes component 0's (the caller discards that result). + wid, off = cands[0] + for i in (1, 2, 3): + eq, ws, os_ = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{eq} = OpIEqual %bool {params[2]} {self.cu(i)}") + self.emit(f"{ws} = OpSelect %uint {eq} {cands[i][0]} {wid}") + self.emit(f"{os_} = OpSelect %uint {eq} {cands[i][1]} {off}") + wid, off = ws, os_ # A code outside FORMATS has no channel: keep the width at 1, so the shifts below stay defined. is0, wid2 = self.tmp(), self.tmp() self.emit(f"{is0} = OpIEqual %bool {wid} {self.cu(0)}") @@ -3713,7 +3735,7 @@ def fmt_dec_component(self, k, params): return res def fmt_dec_functions(self): - """The shared per-component decode functions (SHADER-849), one per output component.""" + """The shared decode function %fmt_dec(fmt, words, k) (SHADER-849): output component k of the element.""" if self.fmt_fn is None: self.uses_fmt_tables = True # The tables are constants: register them here, while the constant section can still take them. @@ -3722,34 +3744,35 @@ def fmt_dec_functions(self): for v in Gen.fmt_norm_reps(): self.cl(v) fns = list(self.fmt_norm_function()) - for k in range(4): - saved, self.body = self.body, [] - params = [f"%fd{k}_fmt", f"%fd{k}_words"] - res = self.fmt_dec_component(k, params) - lines, self.body = self.body, saved - fns += ([f"%fmt_dec_c{k} = OpFunction %uint None %fn_fmt_dec"] + - [f"{params[0]} = OpFunctionParameter %uint", f"{params[1]} = OpFunctionParameter %v4uint_fmt"] + - [f"%fmt_dec_c{k}_entry = OpLabel"] + lines + [f"OpReturnValue {res}", "OpFunctionEnd"]) + saved, self.body = self.body, [] + params = ["%fd_fmt", "%fd_words", "%fd_k"] + res = self.fmt_dec_component(params) + lines, self.body = self.body, saved + fns += (["%fmt_dec = OpFunction %uint None %fn_fmt_dec", f"{params[0]} = OpFunctionParameter %uint", + f"{params[1]} = OpFunctionParameter %v4uint_fmt", f"{params[2]} = OpFunctionParameter %uint", + "%fmt_dec_entry = OpLabel"] + lines + [f"OpReturnValue {res}", "OpFunctionEnd"]) self.fmt_fn = fns return self.fmt_fn - def format_decode_call(self, fmt, words): - """4 uint ids: the element decoded per the run-time FORMAT, through the shared per-component functions. - - One function per output component (SHADER-849): the run-time format picks the conversion with selects, so the - decode has no branch and the module carries one copy of it, not one copy per format. Before, the shared - function held every format's decode and a binary search over the codes: 3,498 instructions and 306 branches - in a module, 250 KB for a shader with one dynamic-format load.""" + def format_decode_words(self, words): + """The element's four dwords as the one v4uint the shared decode function takes.""" self.fmt_dec_functions() - # The four dwords of the element, as one v4uint: the decode functions take them as a vector. wvec = self.tmp() self.emit(f"{wvec} = OpCompositeConstruct %v4uint_fmt " + " ".join(words[:4])) - comps = [] - for k in range(4): - r = self.tmp() - self.emit(f"{r} = OpFunctionCall %uint %fmt_dec_c{k} {fmt} {wvec}") - comps.append(r) - return comps + return wvec + + def format_decode_call(self, fmt, wvec, k): + """A uint id: component k (a uint id, 0..3) of the element decoded per the run-time FORMAT. + + One shared function per module (SHADER-849): the run-time format picks the conversion with selects, so the + decode has no branch and the module carries one copy of it, not one copy per format. Before, the shared + function held every format's decode and a binary search over the codes: 3,498 instructions and 306 branches + in a module, 250 KB for a shader with one dynamic-format load. The component is a parameter, so a load + decodes only the components its DST_SEL fields pick for the registers it writes: buffer_load_format_x + makes one call, not four (one function per component, all four called at every load, until 2026-11-27).""" + r = self.tmp() + self.emit(f"{r} = OpFunctionCall %uint %fmt_dec {fmt} {wvec} {k}") + return r def fmt_size_of(self, fmt): """Byte size of the 7-bit buffer FORMAT code `fmt` (a uint id), 0 for a code FORMATS does not decode: one load @@ -3879,7 +3902,8 @@ def buffer_load_format(self, op, a, mods, fixed_fmt=None): widths = self.FORMATS[fixed_fmt][2] d3 = self.cu(sum((4 + c) << (3 * c) for c in range(len(widths)))) else: - comps = self.format_decode_call(fmt, words) + # Decoded per register below: only the components the written registers' DST_SEL fields pick. + comps, wvec = None, self.format_decode_words(words) # DST_SEL swizzle: 0 -> 0, 1 -> 1.0 (float/norm/scaled) or integer 1 (UINT/SINT, INVALID or reserved; # SHADER-86, SHADER-429), 4..7 -> X..W. On an out-of-bounds MUBUF load `words` are 0 so `comps` decode to 0, # while DST_SEL=1 still produces 1.0f / 1 (MTBUF overrides `d3` above with 4..7 / 0, so OOB and INVALID stay 0). @@ -3907,7 +3931,7 @@ def buffer_load_format(self, op, a, mods, fixed_fmt=None): self.emit(f"{dst1} = OpSelect %uint {is_int_fmt} {self.cu(1)} {self.cu(0x3F800000)}") # In-bounds gate applies to components read from buffer memory, leaving DST_SEL=1 intact (SHADER-429). bounded_comps = [] - for comp in comps: + for comp in comps or (): cb = self.tmp() self.emit(f"{cb} = OpSelect %uint {in_b} {comp} {self.cu(0)}") bounded_comps.append(cb) @@ -3915,12 +3939,27 @@ def buffer_load_format(self, op, a, mods, fixed_fmt=None): for c in range(ncomp): sel = self.tmp() self.emit(f"{sel} = OpBitFieldUExtract %uint {d3} {self.cu(3 * c)} {self.cu(3)}") - r = self.cu(0) - for code_v, src in ((1, dst1), (4, bounded_comps[0]), (5, bounded_comps[1]), (6, bounded_comps[2]), (7, bounded_comps[3])): - e, s = self.tmp(), self.tmp() - self.emit(f"{e} = OpIEqual %bool {sel} {self.cu(code_v)}") - self.emit(f"{s} = OpSelect %uint {e} {src} {r}") - r = s + if comps is None: + # Run-time format: DST_SEL 4..7 decodes component sel - 4 (one call), 1 is dst1, the rest 0. The + # same value as selecting among the four decoded components: a sel below 4 wraps k past 3, and the + # decode of such a k is discarded. + k = self.tmp() + self.emit(f"{k} = OpISub %uint {sel} {self.cu(4)}") + dec = self.format_decode_call(fmt, wvec, k) + cb, e1, s1, picked, r = (self.tmp() for _ in range(5)) + self.emit(f"{cb} = OpSelect %uint {in_b} {dec} {self.cu(0)}") + self.emit(f"{e1} = OpIEqual %bool {sel} {self.cu(1)}") + self.emit(f"{s1} = OpSelect %uint {e1} {dst1} {self.cu(0)}") + self.emit(f"{picked} = OpULessThan %bool {k} {self.cu(4)}") + self.emit(f"{r} = OpSelect %uint {picked} {cb} {s1}") + else: + r = self.cu(0) + for code_v, src in ((1, dst1), (4, bounded_comps[0]), (5, bounded_comps[1]), (6, bounded_comps[2]), + (7, bounded_comps[3])): + e, s = self.tmp(), self.tmp() + self.emit(f"{e} = OpIEqual %bool {sel} {self.cu(code_v)}") + self.emit(f"{s} = OpSelect %uint {e} {src} {r}") + r = s if d16: outs.append(r) else: @@ -7231,8 +7270,19 @@ def trig_exact_zero(self, op, x, r): return out def fconst(self, x): - bits = struct.unpack("> 31 else ''}0x1.{(bits & 0x7FFFFF) << 1:06x}p+128" + + def insert_late_constants(gen, out, written): """Define the uint constants assemble asked gen.cu for after it wrote the others (the format tables' lengths and entries, prologue indices, ...), right after the last written one, so before any type or instruction that uses them. Without this a constant nothing else had used (fmt_size_arr's length 128 in a shader with only a d16 typed store) was an id with no definition, and the module failed spirv-val.""" late = sorted(v for v in gen.consts if v not in written) - if not late: + # fconst's floats asked for after assemble wrote them, after the uint constants (the %float type comes first). + late_f = sorted(v for v in gen.fconsts if v not in gen.fconsts_written and v not in (0, 0x3F800000)) + if not late and not late_f: return last = max(written) at = out.index(f"{written[last]} = OpConstant %uint {last}") + 1 - out[at:at] = [f"{gen.consts[v]} = OpConstant %uint {v}" for v in late] + out[at:at] = ([f"{gen.consts[v]} = OpConstant %uint {v}" for v in late] + + [f"{gen.fconsts[v]} = OpConstant %float {float_literal(v)}" for v in late_f]) def assemble(gen): @@ -16471,7 +16534,11 @@ def assemble(gen): gen.consts.setdefault(0, "%c0") for v, name in sorted(gen.consts.items()): types.append(f"{name} = OpConstant %uint {v}") + # fconst's floats (%f0 and %f1 are declared with the types above). + types += [f"{name} = OpConstant %float {float_literal(v)}" for v, name in sorted(gen.fconsts.items()) + if v not in (0, 0x3F800000)] written = dict(gen.consts) # what the module defines; insert_late_constants adds what assemble asks for later + gen.fconsts_written = set(gen.fconsts) if gen.desc_fn: # --descriptor-table tagged: the probe also returns the entry's kind word, so the function returns (index, # kind) as a uvec2. @@ -16489,9 +16556,9 @@ def assemble(gen): if gen.fmt_fn or gen.fmt_enc_fn: types.append("%v4uint_fmt = OpTypeVector %uint 4") # dedupe_types merges it with any other uvec4 if gen.fmt_fn: - # The decode function takes the format code and the element's four dwords as a v4uint: a type of its own - # structure, so it never repeats another function type in the module (SPIR-V forbids that). - types.append("%fn_fmt_dec = OpTypeFunction %uint %uint %v4uint_fmt") + # The decode function takes the format code, the element's four dwords as a v4uint and the component: a type + # of its own structure, so it never repeats another function type in the module (SPIR-V forbids that). + types.append("%fn_fmt_dec = OpTypeFunction %uint %uint %v4uint_fmt %uint") types.append("%fn_fmt_norm = OpTypeFunction %uint %uint %uint") if gen.fmt_enc_fn: types.append("%fn_fmt_encode = OpTypeFunction %v4uint_fmt " + " ".join(["%uint"] * 29)) From 53d138d2d177f6492527e2a34b20be4ee86a2b1b Mon Sep 17 00:00:00 2001 From: OreoFR <29048345+OreoFR@users.noreply.github.com> Date: Fri, 27 Nov 2026 12:07:15 +0100 Subject: [PATCH 2/2] test_f64_conversion: the omod scale is an OpConstant %float of the same bits fconst now emits one cached OpConstant %float per value (%fc) instead of an OpConstant %uint bitcast at each use, so the v_cvt_f32_f64 omod check looks for %fc = OpConstant %float and checks that its literal gives back exactly the scale's 32 bits. The rest of the data flow is pinned as before. Co-Authored-By: Claude Opus 5.5 --- tests/test_f64_conversion.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/tests/test_f64_conversion.py b/tests/test_f64_conversion.py index 7601c595b4..961f8cdff3 100644 --- a/tests/test_f64_conversion.py +++ b/tests/test_f64_conversion.py @@ -1,6 +1,7 @@ """Check the SPIR-V data flow for output modifiers on v_cvt_f32_f64.""" import re +import struct import sys import tempfile import unittest @@ -42,8 +43,12 @@ def result(instruction): value = result(r"OpFConvert %float %\w+") if scale_bits is not None: - constant = result(rf"OpConstant %uint {scale_bits}") - scale = result(rf"OpBitcast %float {constant}") + # The scale is one OpConstant %float named by its bits (Gen.fconst_bits), not a uint constant bitcast at + # the use; its literal must give back exactly the 32 bits of the omod scale. + scale = f"%fc{scale_bits:x}" + match = re.search(rf"^ *{scale} = OpConstant %float (\S+)$", spv, re.M) + self.assertIsNotNone(match, f"Missing SPIR-V instruction: {scale} = OpConstant %float") + self.assertEqual(struct.unpack("