diff --git a/docs/design.md b/docs/design.md index 6a82596eb..1f282467c 100644 --- a/docs/design.md +++ b/docs/design.md @@ -367,7 +367,7 @@ How the generated SPIR-V expects the runtime to work: | Wave size | **Most of the game's shaders are wave64: 23,841 of 26,503** (`fssm_header.wave_size()`: FSSM header flags word `u32[0xD4]` bit 5, `0x20` = wave32, `0` = wave64; 0 contradictions against GFX10 code-proven wave32/wave64 instructions across all 26,503 blobs): 10,974 of 12,101 PS, 9,282 of 9,282 mesh shaders, 2,236 of 2,236 VS, 1,154 of 2,689 CS and 195 of 195 GS, against 2,662 wave32 (1,535 CS and 1,127 PS). A full-corpus translation at `ec8ec4c9` marks exactly these 23,841 `wave64` (`subgroup_size` 64) in the index. Before the FSSM flag (#1900) the wave size came from code markers (64-bit EXEC/mask writes, `exec_hi`, `*_saveexec_b64`): at `6a6704df` they made 21,538 of the 26,487 shaders translated then wave64 (the figure quoted here was 21,545). 10,031 PS, 9,282 mesh shaders, 1,179 VS, 851 CS and 195 GS (the 16 shaders refused then are all wave64 CS by the flag; the figure quoted here was 21,545). Against the flag they call 2,287 wave64 shaders wave32 (943 PS, 1,057 VS, 287 CS), whose code has no 64-bit EXEC/mask marker, and none the other way. An older marker scan (`s_mov_b64 exec, -1`, `exec_hi`, `s_and/or_saveexec_b64` and 64-bit masks) counted 9,930 PS, 8,666 mesh shaders, 1,115 VS and 923 CS, but it left out the 769 listings whose names start with `.` (616 of them mesh shaders; Python's `glob` skips such names). Over all 26,503, the translator's own marker test (`WAVE64_RE`, or a 64-bit op on EXEC/VCC) on the code `translate()` keeps finds 21,554 wave64: 10,031 PS, 9,282 mesh shaders, 1,179 VS, 867 CS and 195 GS. With the 2,287 above that is exactly the flag's 23,841, and none contradicts it; read raw, 104 more wave32 listings (80 CS, 24 PS) seem to carry a marker, all from embedded data words decoded as instructions. The first marker scan (`s_mov_b64 exec, -1`, `exec_hi`, `s_and/or_saveexec_b64` and 64-bit masks, written into this row at `0082ad53`) counted 9,930 PS, 8,666 mesh shaders, 1,115 VS and 923 CS: 20,634 without the GS, so not the 21,545 total either. The translator maps a wave to a subgroup, and NVIDIA subgroups are 32 wide. What that means: (1) lane-independent code, which is most pixel-shader math, is exact; (2) wave-wide branch decisions and reductions are made per 32-lane half, which is exact unless scalar state computed for one half is later consumed by the other; (3) lane indices from `v_mbcnt_lo/hi` and wave IDs from the merged-wave SGPR must be 64-lane values. Mesh and compute shaders build thread IDs as wave_id·64 + mbcnt, so those need a mapping from `LocalInvocationIndex` (lane = index & 63, wave = index >> 6). Full fidelity needs either 64-wide subgroups (AMD GPUs, via `VK_EXT_subgroup_size_control` requiredSubgroupSize = 64) or emulating cross-half ops (ballot, readlane, shuffles across halves) through workgroup memory. | | Mesh shaders | NGG wave64 programs → `VK_EXT_mesh_shader` (`MeshEXT`). **PSV0** (DXBC) gives NumThreads (128×1×1 in the corpus), MaxOutputVertices/Primitives (128/128) and the topology (triangles). System inputs, from Mesa's RADV setup for mesh as NGG on GFX10.3: v5 = first launch vertex ID of the lane (the "vertex_id" slot), `linearGroupIndex * NumThreads + LocalInvocationIndex` with the linear index from WorkgroupId/NumWorkgroups; all 9,282/9,282 corpus mesh shaders read `v5` once with `v_readfirstlane_b32 sX, v5` and use `sX` only via `s_lshr_b32 D, sX, 7` to recover the group index (NumThreads is 128 in the corpus), matching TomBox's mesh ABI (`gid.x * numThreads + gi`) on 1D launches. GPU-checked with `runtime/test/shaders/ms_v5_workgroup.asm` (24/24 groups exact on RTX 4060 Ti and RTX 3080, and on an RTX 4050 Laptop and an AMD Radeon 740M (RADV)); still unverified on Xbox hardware: the low 7 bits of `v5` on lanes 1..127 and whether 3D `DispatchMesh` flattens XYZ or uses X only. The merged-wave-info SGPR (s3 in this ABI) = wave ID << 24, from LocalInvocationIndex >> 6; `v_mbcnt` lanes = LocalInvocationIndex & 63; user data in s16.. as usual. All 9,282 mesh-shader listings of 1.0.2.1 (names starting with `.` included) read exactly v5 before writing anything (`rdna2spirv.read_before_write_vgprs` over the code `translate()` keeps). An earlier sample of 1,500 put 27 aside as adding loop-carried registers; over the corpus no extra read is loop-carried. Read raw, 266 of the 309 listings with embedded data words seem to read more VGPRs, each after a branch (in 101 the register is written after the read); they come from data words decoded as instructions and are gone once the listing is re-anchored to the FSSM code and cut to reachable code, as `translate()` does. 1,473 of 1,500 sampled mesh shaders read exactly v5, and the rest only add loop-carried registers. Exports: on NGG, thread t exports vertex t (`pos0`, `paramN`) and primitive t (`prim`). They're staged per invocation; an all-`off` export is the dummy a wave with no vertices must issue, and writes nothing. `s_sendmsg GS_ALLOC_REQ` (m0 = prims << 12 \| verts, sent by thread 0) stores the counts in a workgroup variable. At shader end, in uniform control flow: workgroup barrier, `OpSetMeshOutputsEXT(min(verts, max), min(prims, max))`, then each thread writes its staged vertex (Position + Location N) and primitive (`PrimitiveTriangleIndicesEXT` = bits [8:0], [18:10], [28:20]; `CullPrimitiveEXT` = bit 31). `pos1..pos3` clip/cull distances are staged per invocation and emitted in a per-vertex `Block` output struct (`Position` + `ClipDistance`/`CullDistance` arrays, `VK_EXT_mesh_shader`) when used, keeping the standalone `%ms_out_pos` layout unchanged for shaders without `pos1+`. The distances are copied to that struct one float at a time, not as a whole array: SPIRV-Cross 1.4.363.0 turns a whole-array store into a mesh output into a C array assignment that Metal rejects (SHADER-155; `ms_clip` then compiles and draws its 2048/4096 pixels in a native Metal mesh draw on an Apple A18 Pro). `%ms_cull` (the `PerPrimitiveEXT` `CullPrimitiveEXT` `Block`) is listed before `%ms_out_vtx` in `OpEntryPoint MeshEXT`'s interface list: AMD's proprietary Windows Vulkan driver `24.10.24` (LLPC) was reported, on one Ryzen 5 7600 iGPU, to segfault (`0xC0000005`) during `vkCreateGraphicsPipelines` when the per-vertex clip/cull `Block` precedes the per-primitive `Block` (even on `glslangValidator` output), while driver `32.0.32029.2010` on an RX 9070 XT and an RX 7900 XT accepts either order; the order has no meaning in SPIR-V, so this one costs nothing on other drivers; reordering the interface list fixes `ms_clip` on AMD Ryzen 5 7600 RDNA2 iGPU (`2048/2048` clipped, `2048/2048` drawn, `4096/4096` culled when `CullPrimitiveEXT = true`, 0 validation errors) while keeping `CullPrimitiveEXT` in its `Block+bool` form for SPIRV-Tools ≤2025.1 (`SHADER-MS-CLIP-IFACE`). GPU-checked with `runtime/test/shaders/ms_tri.asm` (`VKH_MESH=1 vk_harness`), built from the game's own idioms (thread ID from s3 and mbcnt across two waves, thread-0 ALLOC_REQ, per-thread exports): 0 error on every pixel. `Layer` and `ViewportIndex` from the `pos1` misc vector (`z[10:0]`, `z[19:16]`) are per-primitive members of `%ms_cull` (`Gen.export_misc_pos1`): each lane stages the value it exports and writes it to the primitive with its own index. That is exact when the value is the same for all vertices of a primitive; whether the hardware takes it from the primitive's provoking vertex instead is not measured. Confirmed by the translator tests (`tests/test_translate.py`); none of the 1,906 mesh shaders of the corpus that export `pos1` writes either, so the game's mesh shaders only gain unused declarations. Compressed exports (`exp pos1` / `exp param` with `compr`) unpack their two f16 pairs the way the pixel-shader compressed export does (`Gen.export_comps`): LLVM lists each register twice (`v4, v4, v5, v5`), so the pair is operands 1 and 3, each unpacked with `UnpackHalf2x16` into (x, y) and (z, w), and an `off` register leaves its two components unwritten. Before, such an export was refused. Confirmed by the translator tests (`tests/test_translate.py`); none of the 9,282 mesh shaders of the corpus uses one, so the game's translation does not change. | | Mesh shaders as compute (`--mesh-compute`) | For devices without `VK_EXT_mesh_shader` (NVIDIA Pascal, for one), and on by itself in `make_game.py` on Intel's Windows Vulkan driver (`VK_DRIVER_ID_INTEL_PROPRIETARY_WINDOWS` with mesh shaders, `runtime_gpu_mesh_draws_crash`): there `vkCmdDrawMeshTasksEXT` crashes (0xC0000409 in `igvk64.dll`) for a mesh shader with a live push-constant load at byte 32 or later, which every corpus mesh shader has, while `--mesh-compute` is exact (BUILD-2202, Arc A770, driver 32.0.101.9175; no fixed version known; `--native-mesh` keeps native mesh shaders). Each mesh shader becomes a `GLCompute` module with the same workgroup size and code; only the epilogue changes. Instead of `OpSetMeshOutputsEXT` and the mesh outputs, after the same barrier lane 0 writes the vertex and primitive counts, lane i < vertex count writes its vertex and lane i < primitive count its primitive into this workgroup's **slot** of an output buffer: slot = linear workgroup index (x + y·nx + z·nx·ny) × `slot_bytes`, computed in 64 bits. The buffer's device address is in push-constant dwords 36–37, so these modules declare 152 bytes. Slot layout (`rdna2spirv.mesh_compute_layout`, recorded per shader as `mesh_compute` in the index), all 16-byte aligned: a header (vertex count, primitive count), then `max_vertices` vertices, each holding the position, the clip and then cull distances padded to whole vec4s, and one vec4 per param location; then `max_primitives` primitives of three vertex indices plus 1 if culled. The modules need no mesh capability, extension or `shaderClipDistance`. `tools/mesh_compute_vs.py` writes the vertex shader that draws the slots with a non-indexed `vkCmdDraw(groups × max_primitives × 3)`: vertex v is workgroup v / (3·max_primitives), primitive (v / 3) mod max_primitives, corner v mod 3. A primitive past the count, or one culled, gets one position outside the clip volume at all three corners and is clipped. Otherwise the corner's index, clamped to `max_vertices` − 1, selects the vertex, and its position, distances and params go out at the mesh shader's locations, so the pixel shader is unchanged. One draw rasterizes in vertex order, which is workgroup then primitive order, as with mesh workgroups. Corpus: all 9,282 mesh shaders are 128×1×1 with 128/128 outputs, wave64, 0–18 params, clip distances in 1,906, cull distances and per-primitive attributes in none, no task shaders. On a 32-wide device combine it with `--wave64-emulate`. GPU-checked on an NVIDIA GeForce GTX 1060 6GB (Pascal: no mesh shaders; driver 560.94, Windows 10) with `LEONIDA_MESH_COMPUTE=1 LEONIDA_W64_EMULATE=1`: `ms_tri`, `ms_w64x_ballot` and `ms_wave_info_s3` 4096/4096 pixels exact, `ms_clip` 2048/4096 covered as expected, `ms_v5_workgroup` 24/24 workgroup coordinates, zero Khronos validation messages. Checked in `tests/test_mesh_compute.py`. The runtime side, turning a `DispatchMesh` into that dispatch, a barrier and the draw, is the follow-up (it needs the graphics pipelines of #291). Unused primitives still run the vertex shader; compaction with an indirect draw would avoid that. | -| Mesh primitive export and allocation (`exp prim`, `MSG_GS_ALLOC_REQ`) | The GFX10 NGG formats, from Mesa 22.3 `src/amd/llvm/ac_llvm_build.c`: `ac_build_sendmsg_gs_alloc_req` (lines 4475–4477) puts `prim_cnt << 12 \| vtx_cnt` in m0, and `ac_pack_prim_export` (lines 4518–4539) packs index 0, 1 and 2 in bits 0–8, 10–18 and 20–28, the edge flags in bits 9, 19 and 29 and "null primitive (skip)" in bit 31. Thread t exports vertex t and primitive t, only below the vertex and primitive counts (`src/amd/common/ac_nir_lower_ngg.c`, `emit_ms_finale`, lines 4056–4067). Translated: the counts from m0 (each clamped to PSV0's maximum) go to `OpSetMeshOutputsEXT` or the `--mesh-compute` header; `PrimitiveTriangleIndicesEXT` takes the three 9-bit fields without the edge flags, and `CullPrimitiveEXT` (or the slot's culled word) is bit 31; invocations at or past a count write nothing. Executed for both paths in `tests/semantic/test_ms_prim_export.py` (72 threads in two wave64 waves: odd threads set the edge flags, threads with t & 2 the null bit). Open: the index fields are not clamped to the vertex count as Mesa's mesh lowering clamps them (`ac_nir_lower_ngg.c` line 4112), so a null primitive whose fields point past the count (skipped on hardware) would be undefined in SPIR-V; no corpus count of such exports exists. | +| Mesh primitive export and allocation (`exp prim`, `MSG_GS_ALLOC_REQ`) | The GFX10 NGG formats, from Mesa 22.3 `src/amd/llvm/ac_llvm_build.c`: `ac_build_sendmsg_gs_alloc_req` (lines 4475–4477) puts `prim_cnt << 12 \| vtx_cnt` in m0, and `ac_pack_prim_export` (lines 4518–4539) packs index 0, 1 and 2 in bits 0–8, 10–18 and 20–28, the edge flags in bits 9, 19 and 29 and "null primitive (skip)" in bit 31. Thread t exports vertex t and primitive t, only below the vertex and primitive counts (`src/amd/common/ac_nir_lower_ngg.c`, `emit_ms_finale`, lines 4056–4067). Translated: the counts from m0 (each clamped to PSV0's maximum) go to `OpSetMeshOutputsEXT` or the `--mesh-compute` header; `PrimitiveTriangleIndicesEXT` takes the three 9-bit fields without the edge flags, and `CullPrimitiveEXT` (or the slot's culled word) is bit 31; invocations at or past a count write nothing. **Indices stay below the vertex count**: every `exp prim` in the corpus comes from an epilogue that compares each 10-bit field with the vertex count and, when one is at or past it, sets bit 31 and keeps the fields (count over the 1.0.2.1 corpus: all 8,666 listings with `exp prim`), so a null primitive can carry indices up to 511. The hardware skips it, but `VK_EXT_mesh_shader` leaves an index at or past the vertex count undefined even on a culled primitive. The translator writes index k as `null ? 0 : umin(field_k, vertex count - 1)`, as Mesa's mesh lowering clamps them (`ac_nir_lower_ngg.c` line 4112), and a primitive count of 0 when the vertex count is 0 (so `vertex count - 1` never wraps); `CullPrimitiveEXT` is unchanged. Until 2026-11-26 the raw fields were written, a suspected cause of device losses in mesh draws on NVIDIA (not confirmed). Executed for both paths in `tests/semantic/test_ms_prim_export.py` (72 threads in two wave64 waves: odd threads set the edge flags, threads with t & 2 the null bit; and `fixtures/ms_prim_null_clamp.asm`, 128 threads at vertex counts 0, 10, 100 and 128, whose null primitives carry fields 300, 511, 0x3FF and the vertex count itself: its assertions fail on the old translator); `spirv-val` accepts both modules, plain and `--wave64-emulate`. **Not GPU-checked.** | | Geometry shaders | On output stream zero, `GS_OP_EMIT_CUT` emits the staged vertex and ends its strip under the same EXEC guard. The synthetic `gs_emit_cut.asm` checks that six vertices form two separate triangles. [RDNA 2 ISA, S_SENDMSG](https://docs.amd.com/api/khub/documents/Et~wpu9g~Ffl7d9q0QZ~Og/content). All 195 are `$GS_VoxelizeGeneric` permutations: legacy (merged ES/GS) wave32 programs on LDS rings, with no `exp`. All 195 are `$GS_VoxelizeGeneric` permutations: legacy (merged ES/GS) programs on LDS rings, with no `exp`, written for wave64 (the FSSM header's wave-size flag says wave64 in 195 of 195, see *Wave size*, and the translator's index marks all 195 `wave64` with `subgroup_size` 64 at `f847748c`; the code agrees: the EXEC prologue that `gs_tri.asm` mirrors compares the thread count with 64 and writes a 64-bit EXEC, the count in #94 finds `v_mbcnt_hi_u32_b32` in all 195, and the translator marks all 195 `wave64`; an earlier version of this row said wave32, TEST-251). Inputs: vertex i sits at the dword offset in v0 lo / v0 hi / v1 lo; an LDS read at vertex base + 4·(4·reg + comp) is input-signature register reg, component comp (checked: SV_Position xyz in dwords 0–2 and TEXCOORD0.xy in 4–5, as ISG1 declares). Outputs: emitted vertex k is dwords [k·4·nreg, (k+1)·4·nreg) of the lane's GSVS area, dword = 4·reg + comp of the output signature (20 dwords = 5 OSG1 registers; every write matches a declared mask). Translation: synthetic offsets (vertex i at dword 64·i), LDS reads → `gl_in[i]` inputs, LDS writes → staged slots, `MSG_GS EMIT` → copy slot (emit count) to the outputs + `OpEmitVertex`, `CUT` → `OpEndPrimitive`, `GS_DONE` → nothing. The prologue's `s_bfm_b64`/`s_cselect` EXEC setup is fed s3 = 64 << 8. GPU-checked with `runtime/test/shaders/gs_tri.asm` (`VKH_GS=… vk_harness`): 0 error. Without a geometry stage (Apple GPUs: Metal, MoltenVK), `tools/spirv_gs_to_compute.py` lowers the translated module to a compute capture pass, one invocation per input primitive: inputs come from a buffer, each `OpEmitVertex` guards its record/meta stores and `%gsc_n` increment on `n < OutputVertices` (dropping excess vertices rather than overflowing into the next primitive's slots, and updating `OpPhi` predecessors across split blocks, and rejecting (`Unsupported`) an `OpEmitVertex` in a loop header before its `OpLoopMerge`, which the split would move; SHADER-617, checked on the CPU by `tests/test_spirv_gs_to_compute_bounds.py`), and a meta buffer holds each primitive's vertex count (`<= OutputVertices`) and strip ends, for an ordinary draw afterwards (SHADER-159). Metal, MoltenVK), `tools/spirv_gs_to_compute.py` lowers the translated module to a compute capture pass, one invocation per input primitive: inputs come from a buffer, each `OpEmitVertex` writes the outputs to a record buffer, and a meta buffer holds each primitive's vertex count and strip ends, for an ordinary draw afterwards (SHADER-159). `gs_tri` lowered this way, converted with SPIRV-Cross and run natively on an Apple A18 Pro: 195/195 records exact for 65 random triangles, and the captured fullscreen triangle drawn from the records matches all 4096 gradient pixels. Not done: wiring it into a draw path, and GS that use cross-lane operations or more than one invocation. | | Integer clamp | The VOP3 `clamp` bit on `v_add_nc_u32`, `v_sub_nc_u32`, `v_subrev_nc_u32` saturates the result to [0, 0xFFFFFFFF], and on `v_add_nc_i32`/`v_sub_nc_i32` to [0x80000000, 0x7FFFFFFF]; without it they wrap. GFX9+ semantics: LLVM selects `uaddsat`/`usubsat` and `saddsat`/`ssubsat` to exactly these ops with clamp set. **Until this change clamp was silently ignored on the unsigned ops** (and the signed ones were `Unsupported`). Checked on the CPU by `tests/semantic/test_alu_add_nc_clamp.py`. The carry-out unsigned ops (`v_add_co_u32`, `v_sub_co_u32`, `v_subrev_co_u32`, `v_add_co_ci_u32`, `v_sub_co_ci_u32`, `v_subrev_co_ci_u32`) with VOP3 `clamp` likewise saturate D to `0xFFFFFFFF` on add carry or `0` on sub borrow while still reporting the real carry/borrow bit in `sdst` (**until 2026-11-22 the translator ignored `clamp` on all six**); confirmed natively on RDNA2 (AMD Radeon 680M `gfx1035` wave32 & wave64 via `tools/hw_oracle`, and independently on `gfx1036` in #1746) and CPU-checked by `tests/semantic/test_alu_add_co_clamp.py`. The 16-bit unsigned add/sub (`v_add_nc_u16`, `v_sub_nc_u16`, and the `v_add_u16`/`v_sub_u16`/`v_subrev_u16` `_e64` names) saturate to [0, 0xFFFF] with `clamp` (llvm-mc 21 gfx1030 encodes the bit on them, and LLVM selects i16 `uaddsat`/`usubsat` to them); **until 2026-11-22 the translator wrapped instead**. `clamp` on any other 16-bit integer op raises `Unsupported`. CPU-checked by `tests/semantic/test_alu_u16_clamp.py` (the high half of the destination is kept), **not GPU-verified**. CPU-checked by `tests/semantic/test_alu_u16_clamp.py` (the high half of the destination is kept), and **Hardware-verified on RDNA2** (AMD Radeon 680M, `gfx1035`, Windows 11, driver `26.5.1`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137): all 32-bit and 16-bit `*_nc_*` `clamp` cases (including `op_sel` and kept destination half on u16) match hardware bit-for-bit. **Open divergence measured on the same hardware:** `v_add_co_u32`, `v_sub_co_u32`, `v_subrev_co_u32`, `v_add_co_ci_u32`, `v_sub_co_ci_u32` and `v_subrev_co_ci_u32` with `clamp` saturate D (`0xFFFFFFFF` / `0`) while still reporting the real carry/borrow in `sdst`, whereas the translator currently ignores `clamp` on these carry-out ops. | | Carry-out subtract of a register from itself | `v_sub_co_u32`, `v_subrev_co_u32`, `v_sub_co_ci_u32` and `v_subrev_co_ci_u32` whose two sources are the same operand (`vD, sdst, vX, vX`) are written out as what x - x gives: D = 0 - carry in and borrow out = carry in (D = 0 and no borrow without a carry in; `clamp` saturates D to 0 on that borrow), with no `OpISubBorrow %x %x`. The values are the same as before; the form is there for AMD's Windows driver, whose compiler dies with an access violation (`0xC0000005` in `amdvlk64.dll`, at `0xafeb87` in 32.0.21037.1004 and `0xaff2d7` in 32.0.21045.29003, Radeon iGPU of a Ryzen 9 9950X3D, gfx1036) creating a native wave64 compute pipeline in which the borrow of an `OpISubBorrow` of one value with itself predicates the value operand of an `OpGroupNonUniformShuffle`. Measured by editing the translated module of a reduced `crosslane_fuzz.py` program (`v_sub_co_u32_e64 v4, s[18:19], v1, v1`, `s_and_saveexec_b64`, `ds_bpermute_b32`): `OpISubBorrow %x %x` crashes 3 of 3, also with the same id written twice, while a borrow of two different registers, `x < x`, `x != x`, `x - 0`, a literal `false` mask, the shuffle of a literal 0 and the same module without the shuffle all compile and run. The `--wave64-emulate` form of the same programs has no shuffle and never crashed. Found with `crosslane_fuzz.py --seed 880317 --wave 64 --w64-native --no-maskdata --dpp --ext --programs 400`: programs 1 and 181 were harness errors (exit 3221225477) on both drivers and match with this form (399 of 400 match, the other one differs only in a hypothesis op, as before). Checked on the CPU by `tests/semantic/test_sub_co_same_operand.py` (wave32 and native wave64 run, the emulated form by its text). **Not counted over the corpus**: whether a game shader subtracts a register from itself with a carry out is unmeasured (no package here), and other ways for that driver to see an `OpISubBorrow` of two equal values (two registers holding the same value) are not covered. | diff --git a/tests/semantic/fixtures/ms_prim_null_clamp.asm b/tests/semantic/fixtures/ms_prim_null_clamp.asm new file mode 100644 index 000000000..21e7522ea --- /dev/null +++ b/tests/semantic/fixtures/ms_prim_null_clamp.asm @@ -0,0 +1,37 @@ +; Mesh shader (NGG, wave64), PSV0: 128 threads, 128/128 outputs, triangles. Two waves of 64 lanes. +; Thread t = s3[27:24] * 64 + mbcnt. Both waves send GS_ALLOC_REQ with m0 = M0 (the test puts +; 128 prims << 12 | V there, V the vertex count it checks). +; Every thread exports vertex t, pos0 = (t, 0, 0, 1), and primitive t, chosen by t & 3: +; 0: indices (t & 7, (t & 7) + 1, (t & 7) + 2) +; 1: null primitive (bit 31) whose fields are 300, 511 and 0x3FF (bit 9 set), all >= V +; 2: null primitive whose fields are (V, 0, 1): only field 0 is out of range, at the count itself +; 3: as 0, with the three edge flags (bits 9, 19, 29) +; The test replaces the tokens M0 and NULL_AT_COUNT (the whole word of case 2) with literals. +v_mbcnt_lo_u32_b32 v0, -1, 0 +v_mbcnt_hi_u32_b32 v0, -1, v0 +s_bfe_u32 s4, s3, 0x40018 +v_lshl_add_u32 v0, s4, 6, v0 +s_mov_b32 m0, M0 +s_sendmsg sendmsg(MSG_GS_ALLOC_REQ) +v_cvt_f32_u32_e32 v1, v0 +v_mov_b32_e32 v2, 0 +v_mov_b32_e32 v3, 1.0 +exp pos0 v1, v2, v2, v3 done +v_and_b32_e32 v4, 7, v0 +v_add_nc_u32_e32 v5, 1, v4 +v_add_nc_u32_e32 v6, 2, v4 +v_lshlrev_b32_e32 v5, 10, v5 +v_lshlrev_b32_e32 v6, 20, v6 +v_or3_b32 v7, v4, v5, v6 +v_and_b32_e32 v8, 3, v0 +v_cmp_eq_u32_e32 vcc, 3, v8 +v_cndmask_b32_e64 v9, 0, 0x20080200, vcc +v_or_b32_e32 v7, v7, v9 +v_mov_b32_e32 v10, 0xbff7fd2c +v_cmp_eq_u32_e32 vcc, 1, v8 +v_cndmask_b32_e32 v7, v7, v10, vcc +v_mov_b32_e32 v11, NULL_AT_COUNT +v_cmp_eq_u32_e32 vcc, 2, v8 +v_cndmask_b32_e32 v7, v7, v11, vcc +exp prim v7, off, off, off done +s_endpgm diff --git a/tests/semantic/test_ms_prim_export.py b/tests/semantic/test_ms_prim_export.py index 08a6089bf..16d5ebba9 100644 --- a/tests/semantic/test_ms_prim_export.py +++ b/tests/semantic/test_ms_prim_export.py @@ -14,9 +14,16 @@ vertex and primitive counts. Thread t exports vertex t and primitive t; only threads below the vertex count have a vertex and only threads below the primitive count a primitive (Mesa ac_nir_lower_ngg.c, emit_ms_finale, 4056-4067). -Expected: counts (70, 68); vertex t at (t, 0, 0, 1) for t < 70; primitive t = (t, t + 1, t + 2), culled exactly -when t & 2, for t < 68; nothing for vertices 70, 71 and primitives 68..71. Vertices 64..69 and primitives 64..67 +Expected: counts (70, 68); vertex t at (t, 0, 0, 1) for t < 70; primitive t = (t, t + 1, t + 2), or (0, 0, 0) +and culled when t & 2, for t < 68; nothing for vertices 70, 71 and primitives 68..71. Vertices 64..69 and primitives 64..67 come from the second wave (s3[27:24] = 1). + +The null primitive's index fields are not kept. Every GFX10 mesh epilogue sets bit 31 when an index field is at or +past the vertex count and leaves the fields as they are; Vulkan leaves a primitive index at or past the vertex count +undefined even on a culled primitive (VK_EXT_mesh_shader: PrimitiveTriangleIndicesEXT), so a null primitive writes +the indices (0, 0, 0) and every other index is clamped to the vertex count - 1, as Mesa's mesh lowering clamps them +(Mesa 22.3 ac_nir_lower_ngg.c line 4112). With no vertex the primitive count is 0. MeshNullPrimitiveClamp +checks this on fixtures/ms_prim_null_clamp.asm (128 threads, two wave64 waves) at several vertex counts. """ import os import struct @@ -26,7 +33,8 @@ import rdna2spirv import spirv_mini_interp as si -FIXTURE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures", "ms_prim_export.asm") +FIXTURES = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures") +FIXTURE = os.path.join(FIXTURES, "ms_prim_export.asm") THREADS = MAX_OUT = 72 VERTS, PRIMS = 70, 68 OUT = 0x10000 # --mesh-compute: the workgroup's slot, at the output address @@ -46,23 +54,25 @@ def _dxbc_psv0(threads, max_vertices, max_primitives): b"PSV0" + struct.pack("= _clamp_counts(verts)[1]: + return None + if t & 3 in (1, 2): + return (0, 0, 0), True + return (t & 7, (t & 7) + 1, (t & 7) + 2), False + + +class MeshNullPrimitiveClamp(unittest.TestCase): + def test_mesh_shader_indices_in_range(self): + for verts in CLAMP_VERTS: + spv, _ = _clamp_translate(False, verts) + _, outs = _run(spv, [0] * 36, CLAMP_THREADS) + for t, out in enumerate(outs): + with self.subTest(vertices=verts, invocation=t): + self.assertEqual(out["OpSetMeshOutputsEXT"], _clamp_counts(verts)) + idx, cull = out["%ms_prim_idx"][3 * t:3 * t + 3], out["%ms_cull"][t] + prim = _clamp_primitive(t, verts) + if prim: + self.assertTrue(all(i < verts for i in idx), idx) + self.assertEqual(idx, prim[0] if prim else (0, 0, 0)) + self.assertEqual(cull, int(prim[1]) if prim else 0) + + def test_mesh_compute_indices_in_range(self): + for verts in CLAMP_VERTS: + spv, lay = _clamp_translate(True, verts) + memory, _ = _run(spv, [0] * 36 + [OUT, 0], CLAMP_THREADS) + self.assertEqual((memory.get(OUT), memory.get(OUT + 4)), _clamp_counts(verts)) + for t in range(CLAMP_THREADS): + with self.subTest(vertices=verts, thread=t): + p = OUT + lay["primitives"] + t * lay["primitive_stride"] + words = tuple(memory.get(p + 4 * k) for k in range(4)) + prim = _clamp_primitive(t, verts) + if prim: + self.assertTrue(all(i < verts for i in words[:3]), words) + self.assertEqual(words, prim[0] + (int(prim[1]),) if prim else (None,) * 4) + + if __name__ == "__main__": unittest.main() diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index b10de728e..2b2f77cce 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -15976,6 +15976,30 @@ def dedupe_types(text): return pattern.sub(lambda m: alias[m.group(0)], "\n".join(out)) +def ms_prim_indices(c): + """The mesh epilogue's primitive: from %mpr (the `exp prim` word) and %msv (the vertex count), %mnb = bit 31 + (null primitive) as 0/1, %mnull as a bool and %mi0..%mi2 the three indices. The 9-bit fields leave out the edge + flags. GFX10 epilogues mark a primitive null when a field is at or past the vertex count and keep the field, but + Vulkan leaves such an index undefined even on a culled primitive (VK_EXT_mesh_shader), so a null primitive's + indices are 0 and the others are clamped to the vertex count - 1, as Mesa 22.3 clamps them (ac_nir_lower_ngg.c + line 4112). A primitive is written only when %msv > 0 (the primitive count is 0 otherwise).""" + L = [f"%mnb = OpShiftRightLogical %uint %mpr {c(31)}", f"%mnull = OpINotEqual %bool %mnb {c(0)}", + f"%mvl = OpISub %uint %msv {c(1)}"] + for k in range(3): + src = f"%mfr{k}" if k else "%mpr" + if k: + L.append(f"%mfr{k} = OpShiftRightLogical %uint %mpr {c(10 * k)}") + L += [f"%mfi{k} = OpBitwiseAnd %uint {src} {c(0x1FF)}", f"%mci{k} = OpExtInst %uint %glsl UMin %mfi{k} %mvl", + f"%mi{k} = OpSelect %uint %mnull {c(0)} %mci{k}"] + return L + + +def ms_prim_count(c, maxp): + """%msp from the allocation's primitive count %msp0: clamped to PSV0's maximum, and 0 without a vertex.""" + return [f"%mspc = OpExtInst %uint %glsl UMin %msp0 {c(maxp)}", f"%mvz = OpIEqual %bool %msv {c(0)}", + f"%msp = OpSelect %uint %mvz {c(0)} %mspc"] + + def mesh_compute_epilogue(gen): """--mesh-compute: the mesh epilogue as buffer stores. Same barrier and counts as the mesh path; then lane 0 writes the header, lane i < vertex count its vertex and lane i < primitive count its primitive, at the offsets @@ -15986,7 +16010,7 @@ def mesh_compute_epilogue(gen): f"%msv0 = OpBitwiseAnd %uint %msc {c(0xFFF)}", f"%msp1 = OpShiftRightLogical %uint %msc {c(12)}", f"%msp0 = OpBitwiseAnd %uint %msp1 {c(0xFFF)}", f"%msv = OpExtInst %uint %glsl UMin %msv0 {c(gen.ms['maxv'])}", - f"%msp = OpExtInst %uint %glsl UMin %msp0 {c(gen.ms['maxp'])}", + *ms_prim_count(c, gen.ms['maxp']), "%mli = OpLoad %uint %local_index", # Slot base = output address (push-constant dwords 36..37, or --pc-tail-ubo dwords 4..5) + linear # workgroup index * slot bytes. @@ -16062,16 +16086,12 @@ def store_floats(base, values): vals.append(f"%mq{loc}_{i}") store_floats(at("%mvb", off), vals) L += ["OpBranch %msc_vend", "%msc_vend = OpLabel"] - # Primitive mli: three 9-bit indices and the null-primitive bit (bit 31), as in the mesh path. + # Primitive mli: three indices and the null-primitive bit (bit 31), as in the mesh path. L += ["%mhp = OpLoad %bool %ms_has_prim", "%mpi = OpULessThan %bool %mli %msp", "%mwp = OpLogicalAnd %bool %mhp %mpi", "OpSelectionMerge %msc_pend None", "OpBranchConditional %mwp %msc_pdo %msc_pend", "%msc_pdo = OpLabel", f"%mps = OpIMul %uint %mli {c(16)}", f"%mpb = OpIAdd %uint %mps {c(lay['primitives'])}", - "%mpr = OpLoad %uint %ms_prim", - f"%mi0 = OpBitwiseAnd %uint %mpr {c(0x1FF)}", - f"%mr1 = OpShiftRightLogical %uint %mpr {c(10)}", f"%mi1 = OpBitwiseAnd %uint %mr1 {c(0x1FF)}", - f"%mr2 = OpShiftRightLogical %uint %mpr {c(20)}", f"%mi2 = OpBitwiseAnd %uint %mr2 {c(0x1FF)}", - f"%mnb = OpShiftRightLogical %uint %mpr {c(31)}"] + "%mpr = OpLoad %uint %ms_prim", *ms_prim_indices(c)] for i, w in enumerate(("%mi0", "%mi1", "%mi2", "%mnb")): store(at("%mpb", 4 * i), w) L += ["OpBranch %msc_pend", "%msc_pend = OpLabel"] @@ -17078,7 +17098,7 @@ def label(prefix): f"%msv0 = OpBitwiseAnd %uint %msc {c(0xFFF)}", f"%msp1 = OpShiftRightLogical %uint %msc {c(12)}", f"%msp0 = OpBitwiseAnd %uint %msp1 {c(0xFFF)}", f"%msv = OpExtInst %uint %glsl UMin %msv0 {c(gen.ms['maxv'])}", - f"%msp = OpExtInst %uint %glsl UMin %msp0 {c(gen.ms['maxp'])}", + *ms_prim_count(c, gen.ms['maxp']), "OpSetMeshOutputsEXT %msv %msp", "%mli = OpLoad %uint %local_index", "%mhv = OpLoad %bool %ms_has_vtx", "%mvi = OpULessThan %bool %mli %msv", @@ -17123,13 +17143,9 @@ def label(prefix): "%mwp = OpLogicalAnd %bool %mhp %mpi", "OpSelectionMerge %ms_pend None", "OpBranchConditional %mwp %ms_pdo %ms_pend", "%ms_pdo = OpLabel", - "%mpr = OpLoad %uint %ms_prim", - f"%mi0 = OpBitwiseAnd %uint %mpr {c(0x1FF)}", - f"%mr1 = OpShiftRightLogical %uint %mpr {c(10)}", f"%mi1 = OpBitwiseAnd %uint %mr1 {c(0x1FF)}", - f"%mr2 = OpShiftRightLogical %uint %mpr {c(20)}", f"%mi2 = OpBitwiseAnd %uint %mr2 {c(0x1FF)}", + "%mpr = OpLoad %uint %ms_prim", *ms_prim_indices(c), "%mix = OpCompositeConstruct %v3uint %mi0 %mi1 %mi2", "%mixp = OpAccessChain %_ptr_Out_v3u_ms %ms_prim_idx %mli", "OpStore %mixp %mix", - f"%mnb = OpShiftRightLogical %uint %mpr {c(31)}", "%mnull = OpINotEqual %bool %mnb %c0", f"%mcp = OpAccessChain %_ptr_Out_bool_ms %ms_cull %mli {c(0)}", # CullPrimitiveEXT gets a constant on each side of a branch, not the computed bool: llvmpipe # (Mesa 25.2.8, LLVM 20) aborts compiling a computed per-primitive bool store in the wave64-emulated