diff --git a/docs/design.md b/docs/design.md index ba4c33fa1c..f74ca4147c 100644 --- a/docs/design.md +++ b/docs/design.md @@ -392,7 +392,7 @@ How the generated SPIR-V expects the runtime to work: | Multiply-add with a literal | `v_fmamk_f32`/`v_madmk_f32` are D = S0 × K + S1 and `v_fmaak_f32`/`v_madak_f32` are D = S0 × S1 + K, K being the 32-bit literal. LLVM prints them `vdst, src0, K, vsrc1` and `vdst, src0, vsrc1, K`, so in print order all four are a[1] × a[2] + a[3] (fused for fmamk/fmaak). **Until 2026-11-21 fmamk and madmk computed S0 × S1 + K.** Source: RDNA2 ISA (V_FMAMK_F32, V_MADMK_F32) and the operand fields of the llvm-mc encoding. Checked by `tests/semantic` and GPU-checked with `runtime/test/shaders/ps_fma_literal.asm` on an NVIDIA GeForce RTX 2060 SUPER (Linux, driver 620.70.06): 4096/4096 pixels exact, and 4096/4096 differ with the old translator. | | Multiply-add and output modifiers | `v_mac_f32` is the VOP2 form of `v_mad_f32`, **not** of `v_fma_f32`: the product is rounded before the add (`OpFMul` + `OpFAdd`, both `NoContraction`). It used to emit `Fma`, one ULP off on some inputs. Source: LLVM `SIInstrInfo.cpp` `getNewFMAInst` (`V_MAC_F32` -> `V_MAD_F32_e64`, `V_FMAC_F32` -> `V_FMA_F32_e64`). VOP3 `clamp` and `mul:2`/`mul:4`/`div:2` now apply to `v_cvt_f32_i32`/`u32`/`ubyte0..3`, `v_cvt_f32_f16` and `v_rcp_iflag_f32` (they were dropped). Source: LLVM `VOPProfileI2F` (`Ins64 = $src0, $clamp, $omod`) and the float-source profiles. Found by `tools/f32_fuzz.py` (FUZZ-3: an exact-arithmetic model against the translated SPIR-V; 0 mismatches over 10,000 seeded programs after the fix) and pinned by `runtime/test/shaders/ps_f32_mods.asm` (`tests/semantic/test_f32_valu.py`); **GPU-checked** (TEST-298): `ps_f32_mods` gives the expected four words (`0xc0256a01 0x3f800000 0x41e00000 0x3fc00000`, so the `v_mac_f32` product is not fused and the `clamp`, `mul:4` and `div:2` on `v_cvt_f32_ubyte1`/`u32`/`f16` and `v_rcp_iflag_f32` apply) on an NVIDIA GeForce RTX 2060 SUPER (Linux, driver 615.78.08); `mul:2` on the conversions is not in that fixture. **not yet GPU-verified**. Still open: on some inputs the ISA defines a result but the emitted SPIR-V is undefined: `v_rcp_f32(±0)` (`OpFDiv` by zero), `v_rsq_f32`/`v_log_f32` of ±0 or a negative, `v_sqrt_f32` of a negative. `v_cvt_pk_u8_f32(NaN)` now selects +0 before `FClamp` (see "Float-to-byte pack"). `v_rcp_f32(±0)` (`OpFDiv` by zero), `v_rsq_f32`/`v_log_f32` of ±0 or a negative, `v_sqrt_f32` of a negative (`v_cvt_pk_u8_f32(NaN)` now selects +0 before `FClamp`, see "Float-to-byte pack"). | | Output modifiers on hardware (gfx1150, RDNA2) | Measured on a Radeon 880M (gfx1150, RDNA3.5; **not** RDNA2) with `tools/f32_fuzz.py --oracle hw`, 46,967 programs: `mul:2`/`mul:4`/`div:2` turn a -0 result (a flushed denormal result included) into +0, and are ignored with MODE.IEEE = 1; with f32 denormals kept they are also ignored for the ALU ops (the transcendental and cube ops still apply them). LLVM notes that omod mishandles signed zeros (`SIFoldOperands.cpp`) and D30209 describes -0 being forced to +0 before the modifier. The translator keeps -0 (`OpFMul`), so on that evidence it likely differs from hardware (see #1006). **RDNA2 does the same, rule for rule** (SHADER-353): on an RX 6700 XT (gfx1031, a discrete RDNA2 part, not the console's gfx1013; AMD Windows driver 26.11.2), seeds 1 to 6, 39,101 programs, 0 mismatch and 66 omod -0 → +0 deviations. Per MODE, counting only the programs where the omod changes the result: with IEEE off and f32 denormals flushed (the game's mode) it is applied every time (2,680, and the 66 -0 results become +0); with denormals kept it is ignored by the ALU ops (1,811) and applied by `v_rcp/rcp_iflag/rsq/sqrt/exp/log_f32` and the four cube ops (869, -0 → +0 only there); with IEEE on it is ignored (2,650) and a -0 result stays -0. Earlier, gfx1036 (the integrated GPUs of a Ryzen 9 7950X3D and a Ryzen 7 9800X3D) gave seeds 1 to 6, 38,858 programs, 0 mismatch and 56 such deviations, with identical counts through the Linux libdrm launcher and the Windows HIP launcher; `v_rcp_iflag_f32` with `clamp`/`omod` on the same GPU, 6,552 programs, 0 mismatch and 35 such deviations, otherwise behaves like `v_rcp_f32`. Also measured there: with `denorm_mode_32 = 0` f32 denormal operands read as zero and denormal results flush (add/mul/fma/min/max/rounding ops, DX9 mul), exact with 3. `v_fma_mix*` f32 operands read as zero when denormal too (SHADER-298: gfx1036, `0x00000001`, `0x807fffff`, and the integer inline constants 1 and 64; f16 operands widen to normal values); its result is not flushed, since that was not measured. Invalid operations give `0xffc00000`; a signalling NaN passes unchanged with IEEE off and is quieted with IEEE on. Details in docs/shader_validation.md ("32-bit float VALU on the GPU"). | -| Float min/max/med3 with NaN, `v_fract` | Measured on an AMD Radeon RX 6800 (gfx1030, not the console's gfx1013) with the hw-oracle tool from the AnyPS5 project, 537 input rows in all four IEEE/DX10_CLAMP combinations and in wave32 and wave64, the same for every combination with quiet NaNs. `v_min_f32`/`v_max_f32`, `v_min_f16`/`v_max_f16` and each half of `v_pk_min_f16`/`v_pk_max_f16`: one NaN operand gives the other operand, bits unchanged; both NaN give src0; -0 < +0. `v_min3`/`v_max3` = f(f(s0, s1), s2) with that min/max. `v_med3_f32`/`_f16`: with any NaN operand the result is min3(s0, s1, s2), otherwise the median (-0 < +0). `v_fract_f32` rounds x − floor(x) once and returns 0x3f7fffff (the largest float below 1) where that gives 1.0, e.g. fract(-1e-10); f16 gives 0x3bff; fract(-0) = +0, fract(±inf) = NaN, a NaN passes through. Measured natively on gfx1036 (RDNA2) in the MODE inferred for the game (IEEE 0, f32 denormals flushed): `v_floor_f32`, `v_ceil_f32` and `v_fract_f32` read a denormal operand as a zero of its sign (floor(-1e-45) = -0, ceil(+1e-45) = +0, fract of either 0), fract(±inf) is exactly `0xffc00000`, and a NaN operand comes back unchanged, a signalling one too. The translator flushes the operand and selects those words itself (`Gen.round_f32_flushed`) instead of leaving them to the driver's f32 denormal handling, which Vulkan does not fix; until 2026-11-22 a driver that keeps denormals gave -1.0, +1.0 and 0x3f7fffff there. `v_cvt_flr_i32_f32` likewise returns 0 for a negative denormal (the translator gave -1). Checked against 119 measured words by `tests/semantic/test_alu_floor_ceil_fract_hw.py`. For `v_fract_f16`, either infinity gives the gfx1036 word `0xfe00`, or +0 with the DX10 clamp. The translator selects these results explicitly. The hand-written `ps_fract_f16_infinity.asm` fixture checks both signs, the preserved destination bits and a color channel computed from the result sign in the CPU interpreter (`tests/semantic/test_fract_f16_infinity.py`). A source `neg` on a signalling NaN operand still quiets it in the translator. Not changed: f16 fract(±inf) is `0xfe00` on the hardware and a quiet positive NaN in the translator, and `neg` on a signalling NaN operand quiets it in the translator. The translator emits `NMin`/`NMax` for these min/max ops (before: `FMin`/`FMax`, whose NaN result GLSL.std.450 leaves to the implementation). med3 is `NMin(NMax(z, NMin(x, y)), NMax(x, y))` (until 2026-11-22 this used `FClamp(z, lo, hi)`, which was GLSL.std.450 undefined whenever `z` was NaN or both `x` and `y` were NaN), and when an operand can be a NaN, `OpIsNan` of each such operand (none for an inline or literal constant that is not a NaN) selects `NMin(NMin(x, y), z)` instead; all 1-, 2-, and 3-NaN operand positions for both `v_med3_f32` and `v_med3_f16` were hardware-verified on RDNA2 (`gfx1035`, wave32 & wave64). `FMin`/`FMax`, whose NaN result GLSL.std.450 leaves to the implementation). med3 is `FClamp(z, NMin(x, y), NMax(x, y))`, and when an operand can be a NaN, `OpIsNan` of each such operand (none for an inline or literal constant that is not a NaN) selects `NMin(NMin(x, y), z)` instead. `v_fract_f32` is `Fract` followed by `OpFOrdEqual` with 1.0 and an `OpSelect` of 0x3f7fffff, so the NaN of fract(±inf) is kept; `v_fract_f16` does the same before packing and then replaces a packed 0x3c00 with 0x3bff (not after an output multiplier, where 1.0 can be a true result). Other `FMin`/`FMax`/`FClamp` uses (the `clamp` bit, LOD and conversion clamps, `v_cvt_pk_u8_f32`, the BVH slab test) are unchanged. Not modelled: signalling NaNs under IEEE mode; NaN under the `clamp` bit (hardware gives +0 with DX10_CLAMP=1 and the NaN with DX10_CLAMP=0; the translator still emits `FClamp`). All-NaN float min/max/med3 ops (`v_min/max/min3/max3/med3_f32` via `Gen.nminmax_f32`, `v_min/max/min3/max3/med3_f16` via `Gen.f16_in_bits`/`Gen.all_f16_nan_cond`, and per-half `v_pk_min/max_f16` when `clamp` is unset) explicitly preserve `src0`'s NaN bits (including sign, payload, and signalling bit under `IEEE = 0`, matching the RX 6800 and `gfx1036` hardware rules). The CPU tests `tests/semantic/test_minmax_f32_payload.py` and `tests/semantic/test_alu_min3_max3_med3_16_hw.py` check operand-order payload and signalling NaN preservation. Also, without the `SignedZeroInfNanPreserve` execution mode Vulkan does not strictly guarantee NaN or signed-zero behaviour, so these rules hold where the driver keeps them. NaN under the `clamp` bit (hardware gives +0 with DX10_CLAMP=1 and the NaN with DX10_CLAMP=0; the translator still emits `FClamp`); the NaN payload when both operands are NaN (`NMin` only promises a NaN); and without the `SignedZeroInfNanPreserve` execution mode Vulkan does not strictly guarantee NaN or signed-zero behaviour, so these rules hold where the driver keeps them. With an output modifier (`mul:2`, `mul:4`, `div:2`) on `v_fract_f16` the translator applies the modifier to the f32 fract before narrowing to f16; the hardware order of rounding and modifier for that case was not measured, so a result can differ by one f16 step for tiny negative inputs (e.g. x = -1e-4 with `div:2`). GPU-checked with `runtime/test/shaders/ps_fnan_med3.asm` and `ps_fnan_fract.asm` (inputs read from memory at run time) on an AMD Radeon RX 6800, Windows 11, driver 26.11.2: 4096/4096 pixels exact; on that driver the two med3 words differed before the change (0x40e00000 and 0x40600000 instead of 0x40a00000 and 0xc0200000), and so did the f16 fract word (0x3c00 instead of 0x3bff) once f16 results were narrowed with integer round-to-nearest; the f32 fract and the min/max words were already the hardware words there. `tests/semantic/test_float_nan_fract.py` runs the measured rows through the translator and the interpreter. | +| Float min/max/med3 with NaN, `v_fract` | Measured on an AMD Radeon RX 6800 (gfx1030, not the console's gfx1013) with the hw-oracle tool from the AnyPS5 project, 537 input rows in all four IEEE/DX10_CLAMP combinations and in wave32 and wave64, the same for every combination with quiet NaNs. `v_min_f32`/`v_max_f32`, `v_min_f16`/`v_max_f16` and each half of `v_pk_min_f16`/`v_pk_max_f16`: one NaN operand gives the other operand, bits unchanged; both NaN give src0; -0 < +0. `v_min3`/`v_max3` = f(f(s0, s1), s2) with that min/max. `v_med3_f32`/`_f16`: with any NaN operand the result is min3(s0, s1, s2), otherwise the median (-0 < +0). `v_fract_f32` rounds x − floor(x) once and returns 0x3f7fffff (the largest float below 1) where that gives 1.0, e.g. fract(-1e-10); f16 gives 0x3bff; fract(-0) = +0, fract(±inf) = NaN, a NaN passes through. Measured natively on gfx1036 (RDNA2) in the MODE inferred for the game (IEEE 0, f32 denormals flushed): `v_floor_f32`, `v_ceil_f32` and `v_fract_f32` read a denormal operand as a zero of its sign (floor(-1e-45) = -0, ceil(+1e-45) = +0, fract of either 0), fract(±inf) is exactly `0xffc00000`, and a NaN operand comes back unchanged, a signalling one too. The translator flushes the operand and selects those words itself (`Gen.round_f32_flushed`) instead of leaving them to the driver's f32 denormal handling, which Vulkan does not fix; until 2026-11-22 a driver that keeps denormals gave -1.0, +1.0 and 0x3f7fffff there. `v_cvt_flr_i32_f32` likewise returns 0 for a negative denormal (the translator gave -1). Checked against 119 measured words by `tests/semantic/test_alu_floor_ceil_fract_hw.py`. For `v_fract_f16`, either infinity gives the gfx1036 word `0xfe00`, or +0 with the DX10 clamp. The translator selects these results explicitly. The hand-written `ps_fract_f16_infinity.asm` fixture checks both signs, the preserved destination bits and a color channel computed from the result sign in the CPU interpreter (`tests/semantic/test_fract_f16_infinity.py`). A source `neg` on a signalling NaN operand still quiets it in the translator. Not changed: f16 fract(±inf) is `0xfe00` on the hardware and a quiet positive NaN in the translator, and `neg` on a signalling NaN operand quiets it in the translator. The translator emits `NMin`/`NMax` for these min/max ops (before: `FMin`/`FMax`, whose NaN result GLSL.std.450 leaves to the implementation). med3 is `NMin(NMax(z, NMin(x, y)), NMax(x, y))` (until 2026-11-22 this used `FClamp(z, lo, hi)`, which was GLSL.std.450 undefined whenever `z` was NaN or both `x` and `y` were NaN), and when an operand can be a NaN, `OpIsNan` of each such operand (none for an inline or literal constant that is not a NaN) selects `NMin(NMin(x, y), z)` instead; all 1-, 2-, and 3-NaN operand positions for both `v_med3_f32` and `v_med3_f16` were hardware-verified on RDNA2 (`gfx1035`, wave32 & wave64). `FMin`/`FMax`, whose NaN result GLSL.std.450 leaves to the implementation). med3 is `FClamp(z, NMin(x, y), NMax(x, y))`, and when an operand can be a NaN, `OpIsNan` of each such operand (none for an inline or literal constant that is not a NaN) selects `NMin(NMin(x, y), z)` instead. `v_fract_f32` is `Fract` followed by `OpFOrdEqual` with 1.0 and an `OpSelect` of 0x3f7fffff, so the NaN of fract(±inf) is kept; `v_fract_f16` does the same before packing and then replaces a packed 0x3c00 with 0x3bff (not after an output multiplier, where 1.0 can be a true result). Other `FMin`/`FMax`/`FClamp` uses (LOD and conversion clamps, `v_cvt_pk_u8_f32`, the BVH slab test) are unchanged; for the `clamp` bit see below. Not modelled: signalling NaNs under IEEE mode. NaN under the `clamp` bit: the hardware gives +0 with DX10_CLAMP=1 (the game's MODE) and the NaN with DX10_CLAMP=0, measured on gfx1036 for `v_rcp_iflag_f32` (169 programs, `docs/shader_validation.md`, "32-bit float VALU on the GPU") and for `v_fmac_f16`, `v_fma_mixlo_f16` and `v_fma_mix_f32` (SHADER-186, "f16 output modifiers, clamp and `v_fma_mix*` operands on RDNA2"). The f32 and f16 ops that apply `clamp` through `Gen.clamp_mods`/`Gen.clamp_f16` now select +0 for a NaN before `FClamp`, which GLSL.std.450 leaves undefined for a NaN operand, so they give the DX10_CLAMP=1 word, as `v_div_fixup_f32`, `v_cvt_pk_u8_f32` and the f16 frexp/ldexp clamps already did (**until 2026-11-24 `clamp_mods` emitted a bare `FClamp`**). CPU-checked by `tests/semantic/test_vop3_clamp_nan.py`; not GPU-checked. Still a bare `FClamp`: the f64 clamp (`clamp_mods_f64`) and the packed `v_pk_*` clamp. `v_dot2_f32_f16` routes its `clamp` through `clamp_mods` too, but its clamp is measured as a hardware no-op (open PR #410). All-NaN float min/max/med3 ops (`v_min/max/min3/max3/med3_f32` via `Gen.nminmax_f32`, `v_min/max/min3/max3/med3_f16` via `Gen.f16_in_bits`/`Gen.all_f16_nan_cond`, and per-half `v_pk_min/max_f16` when `clamp` is unset) explicitly preserve `src0`'s NaN bits (including sign, payload, and signalling bit under `IEEE = 0`, matching the RX 6800 and `gfx1036` hardware rules). The CPU tests `tests/semantic/test_minmax_f32_payload.py` and `tests/semantic/test_alu_min3_max3_med3_16_hw.py` check operand-order payload and signalling NaN preservation. Also, without the `SignedZeroInfNanPreserve` execution mode Vulkan does not strictly guarantee NaN or signed-zero behaviour, so these rules hold where the driver keeps them. With an output modifier (`mul:2`, `mul:4`, `div:2`) on `v_fract_f16` the translator applies the modifier to the f32 fract before narrowing to f16; the hardware order of rounding and modifier for that case was not measured, so a result can differ by one f16 step for tiny negative inputs (e.g. x = -1e-4 with `div:2`). GPU-checked with `runtime/test/shaders/ps_fnan_med3.asm` and `ps_fnan_fract.asm` (inputs read from memory at run time) on an AMD Radeon RX 6800, Windows 11, driver 26.11.2: 4096/4096 pixels exact; on that driver the two med3 words differed before the change (0x40e00000 and 0x40600000 instead of 0x40a00000 and 0xc0200000), and so did the f16 fract word (0x3c00 instead of 0x3bff) once f16 results were narrowed with integer round-to-nearest; the f32 fract and the min/max words were already the hardware words there. `tests/semantic/test_float_nan_fract.py` runs the measured rows through the translator and the interpreter. | | `ds_swizzle_b32` | An active destination reads the selected source lane's VGPR. If EXEC disables that source, the read returns zero; a disabled destination keeps its prior value. The [hardware measurements](shader_validation.md#hardware-oracle-for-the-lds-programs---oracle-hw) confirm the disabled-source result on gfx1036 and gfx1150. In the seven-invocation CPU fixture, lane 6 selects lane 7, which is absent. The translator returns zero in that case; the corresponding result on hardware is unverified. The fixture exercises `QUAD_PERM` and `SWAP` in `test_ds_permute.py`. A numeric `offset:N` below 0xC000 is decoded like its symbolic `swizzle(...)` form since #4177; 0xC000–0xFFFF is refused (`Unsupported`), which RDNA2 treats as a separate mode (measured on gfx1036 for all 16,384 offsets). **No game shader is affected either way** (SHADER-811): over the 1.0.2.1 package's 26,503 DXBC listings and the FidelityFX DLL's 29 FSPX programs, llvm-mc prints all 105,529 `ds_swizzle_b32` (in 6,296 DXBC programs; the FSPX programs have none) in a symbolic form, with 17 distinct offsets: 101,913 in 0x8000–0xBFFF (`QUAD_PERM`), 3,616 below 0x8000 (the bitmask mode: `BROADCAST`, `SWAP`, `BITMASK_PERM`) and none at or above 0xC000. Counted from each instruction's printed encoding (offset = bits 15:0 of the first dword) in every listing, the 1,473 with embedded data words included (only decoded instructions count), and matched by a count of the printed offset classes on a second copy (#4566). | | Output modifiers on hardware (gfx1150) | Measured on a Radeon 880M (gfx1150, RDNA3.5; **not** RDNA2) with `tools/f32_fuzz.py --oracle hw`, 46,967 programs: `mul:2`/`mul:4`/`div:2` turn a -0 result (a flushed denormal result included) into +0, and are ignored with MODE.IEEE = 1; with f32 denormals kept they are also ignored for the ALU ops (the transcendental and cube ops still apply them). LLVM notes that omod mishandles signed zeros (`SIFoldOperands.cpp`) and D30209 describes -0 being forced to +0 before the modifier. The translator keeps -0 (`OpFMul`), so on that evidence it likely differs from hardware (see #1006). RDNA2 itself is unmeasured (see #1006). Also measured there: with `denorm_mode_32 = 0` f32 denormal operands read as zero and denormal results flush (add/mul/fma/min/max/rounding ops, DX9 mul), exact with 3. `v_fma_mix*` f32 operands read as zero when denormal too (SHADER-298: gfx1036, `0x00000001`, `0x807fffff`, and the integer inline constants 1 and 64; f16 operands widen to normal values); its result is not flushed, since that was not measured. Invalid operations give `0xffc00000`; a signalling NaN passes unchanged with IEEE off and is quieted with IEEE on. RDNA2 does the same: gfx1036 (the integrated GPUs of a Ryzen 9 7950X3D and a Ryzen 7 9800X3D; RDNA2, but not the console's gfx1013), seeds 1 to 6, 38,858 programs, 0 mismatch and 56 omod -0 → +0 deviations, with identical counts through the Linux libdrm launcher and the Windows HIP launcher; `v_rcp_iflag_f32` with `clamp`/`omod` on the same GPU, 6,552 programs, 0 mismatch and 35 such deviations, otherwise behaves like `v_rcp_f32`. Also measured there: with `denorm_mode_32 = 0` f32 denormal operands read as zero and denormal results flush (add/mul/fma/min/max/rounding ops, DX9 mul), exact with 3; invalid operations give `0xffc00000`; a signalling NaN passes unchanged with IEEE off and is quieted with IEEE on. Details in docs/shader_validation.md ("32-bit float VALU on the GPU"). | | Wave64 handling | Wave size is detected per shader from the code (64-bit EXEC writes, `exec_hi`, `v_mbcnt_hi`, `*_saveexec_b64`/`*_wrexec_b64`, and 64-bit lane-mask SOP ops `s_bcnt[01]_i32_b64` / `s_ff[01]_i32_b64` / `s_wqm_b64` / `s_bfm_b64` even when the mask is an ordinary SGPR pair; mesh shaders are always wave64). In wave32 code (a header or FSPX dispatch state that says so) `s_bfm_b64` is 64-bit data instead: the translator writes `((1 << (S0 & 63)) - 1) << (S1 & 63)` to the pair, `tools/lane_masks.py` leaves it data, and it doesn't count against an FSPX program's wave32 state. The pipeline library's wave32 compute programs build an S# in place with it (`s_bfm_b64 s[88:89], 2, 54`, then `s_mov_b64` of words 2-3; 958 programs, [shader_library.md](shader_library.md)). Only constant operands are translated there; none other is seen. `tests/semantic/test_wave32_bfm64_data.py`. Wave size comes from the sidecar `fssm/.fssm` header flags word `u32[0xD4]` bit 5 (`0x20` = wave32, `0` = wave64; `fssm_header.wave_size()`), cross-checked against wave64/wave32 code markers (`WAVE64_RE` / `WAVE32_RE`: a contradicting header and code listing raises `Unsupported`), and falls back to the code-marker heuristic (64-bit EXEC/VCC writes, `exec_hi`, `v_mbcnt_hi`, `*_saveexec_b64`/`*_wrexec_b64`, and 64-bit lane-mask SOP ops `s_bcnt[01]_i32_b64` / `s_ff[01]_i32_b64` / `s_wqm_b64` / `s_bfm_b64`, plus wave64 for mesh shaders) when no `FSSM`-magic sidecar is present (synthetic listings). **An FSPX program** (the FidelityFX DLL's, no FSSM blob) takes its wave size from its dispatch state instead: kind 0 word 4 bit 20, set = wave32 (`fspx/.json` `wave32`). Only a strict marker (`WAVE64_RE` against wave32, `WAVE32_RE` against wave64) contradicts it and raises `Unsupported`; a `_b64` op on `vcc` or `exec` does not, since these programs move `vcc` as an ordinary SGPR pair. Without that field the heuristic stays. Confirmed on the 29 programs of 1.0.2.1: strict markers never contradict the bit, the `RSRC1` VGPR granule fits it in all 21 programs that decode cleanly, and `PSV0` lane counts agree with it in all 5 that state one ([fspx.md](fspx.md), "Kind 0: dispatch state"). Translated with the bit, the 4 programs the heuristic got wrong change size, and the other 22 translated modules are byte-identical. CPU-checked by `tests/semantic/test_fspx_wave_size.py`, including a `v_readlane_b32` whose result differs between the two sizes; `vk_pipeline_check` builds all 26 modules. Not GPU-checked on these programs' own data. Confirmed across all 26,503 corpus blobs with 0 contradictions against GFX10 SOP1/SOP2/SOPC/VOP3 encodings: 23,841 wave64 (1,154 CS, 195 GS, 9,282 MS, 10,974 PS, 2,236 VS) and 2,662 wave32 (1,535 CS, 1,127 PS); the code-marker heuristic alone misclassified 2,287 markerless wave64 shaders as wave32 (287 CS: 162 straight-line and 125 branchy, including 11 with `v_readlane_b32`, 35 `v_readfirstlane_b32`, 29 `ds_swizzle_b32`, 14 `s_barrier`; 943 PS: 906 straight-line and 37 branchy; 1,057 VS: 1,020 straight-line and 37 branchy); CPU-checked by `tests/test_fssm_header.py` and `tests/test_fssm_wave_size.py`. Until 2026-11-21 a mask-only wave64 program with no EXEC markers was translated as wave32, so `s_bcnt1_i32_b64` counted one half (#210). GPU-checked with `runtime/test/shaders/cs_w64_mask_detect.asm` (48 set bits of `(lane & 5) != 0`) on NVIDIA GeForce RTX 5060 under `LEONIDA_W64_EMULATE=1`. The hardware lane is exact in compute and mesh shaders (LocalInvocationIndex mod 64 or 32) and is used by `v_mbcnt` and EXEC writes. In other stages it's the subgroup lane. Constant EXEC writes (`s_mov_b32 exec_lo/exec_hi, K`) set each lane from its own bit of K, as `(K >> lane) & 1` (shift and mask: Intel's Windows driver evaluated `OpBitFieldUExtract` of a constant that fits in 16 bits with the lane taken mod 16, so `exec_lo = 0xffff` ran all 32 lanes; GPU-checked with `runtime/test/shaders/cs_exec_const.asm` on Intel UHD Graphics 770, driver 32.0.101.6129, and NVIDIA GeForce RTX 4080 SUPER); before, any non-zero constant turned every lane on. A register written to `exec_hi` sets lanes 32–63 only. VCC's halves follow the same rule while VCC holds a lane mask: a 32-bit write to `vcc_lo` sets lanes 0–31 of the mask and one to `vcc_hi` lanes 32–63 (until 2026-11-22 a `vcc_lo` write set all 64 lanes and a `vcc_hi` write never reached the mask that `s_cbranch_vccz`/`v_cndmask` read; CPU-checked by `tests/semantic/test_wave64_vcc_half_write.py`, not GPU-checked). Mask and `0`/`-1` half-writes to `vcc_lo`/`vcc_hi` keep VCC tracked as a lane mask across subsequent ops (`s_bcnt1_i32_b64`, further half-writes), whereas plain-data writes (`s_buffer_load_dword vcc_lo`, `s_load_dword`, scalar ALU, non-mask constants) end VCC's mask state and store the scalar word across all 64 lanes instead of updating only one mask half (confirmed on 1 wave64 PS in the 1.0.2.1 corpus and `tests/semantic/test_wave64_vcc_half_write.py`). GPU-checked with `runtime/test/shaders/cs_exec64.asm`: lanes 16–47 enabled from two constants, exact on a 32-wide-subgroup GPU. Still approximate on 32-wide subgroups: cross-lane ops between the two halves of a wave64 (readlane/permlane/DPP/shuffles across lane 31/32, wave-wide reductions). The metadata index marks every wave64 shader so a runtime can request `requiredSubgroupSize = 64` where supported (AMD), which makes those exact too. | @@ -438,7 +438,7 @@ How the generated SPIR-V expects the runtime to work: | `image_atomic_{swap,inc,dec,fmin,fmax,fcmpswap}` | The six remaining 32-bit MIMG image atomics on 2D (binding 4) and 3D (binding 7) `r32ui` storage images (including `a16` packed coordinates and optional `glc` return), guarded by `active_b` so inactive lanes skip memory access and preserve `vdata`. `image_atomic_swap` emits `OpAtomicExchange`; `inc`/`dec`/`fmin`/`fmax`/`fcmpswap` emit `OpAtomicLoad` (valid on `OpImageTexelPointer` `Image` pointers) followed by a Device-scope `OpAtomicCompareExchange` CAS loop (`inc`: `(M >= D) ? 0 : M + 1`; `dec`: `(M == 0 \|\| M > D) ? D : M - 1`; `fmin`/`fmax`: GLSL.std.450 `NMin`/`NMax`, no float-atomic extension required; `fcmpswap`: integer IEEE-754 binary32 ordered equality on raw 32-bit words — equal iff neither is NaN and `(cur == cmp) \|\| (both ±0.0)`, preserving subnormals even on Vulkan drivers reporting `shaderDenormPreserveFloat32 = false`, exiting without writing on mismatch or NaN; native RDNA2 subnormal behavior under denormal flush is unmeasured). Source: AMD RDNA2 ISA MIMG `IMAGE_ATOMIC_*`. CPU-checked structurally (including `spirv_mini_interp.check_structure` CFG validation) by `tests/semantic/test_image_atomics_32.py` (all 6 ops on 2D and 3D images, `a16`, `glc` and non-`glc`, no `AtomicFloat` capability, rejected widths/coords/dims). **Not GPU-verified on RDNA2.** | | Hand-written short assembler forms | `llvm-mc` accepts `v_add_co_ci_u32 vD, src0, src1` (also `v_sub_co_ci_u32`, `v_subrev_co_ci_u32`) with the carry out and in left to VCC, and a modifier list shorter than the operands (`op_sel_hi:[0,0]`, `neg_lo:[1,0]` on a three-source op), whose missing entries are 0; it prints them as `v_add_co_ci_u32_e32 vD, vcc_lo, src0, src1, vcc_lo` and `[0,0,0]`. The GPU runner assembles through `llvm-mc -show-encoding`, so it sees the printed form; `tests/semantic/regen_fixtures.py` copies the `.asm` text as written, so the translator takes the source spelling too (it used to raise `IndexError` for these: the carry forms, `v_pk_fma_f16`, `v_fma_mix_*`). A probe of 42,000 operand and modifier variations of 302 ALU mnemonics, in the source spelling and as `llvm-mc` prints them, found no other `IndexError`, `KeyError` or `TypeError`. CPU-checked by `tests/semantic/test_short_asm_forms.py`. | | SDWA | `_sdwa` forms: each source is narrowed to `src0_sel`/`src1_sel` (BYTE_n/WORD_n, zero-extended, or sign-extended under `sext()`) **before** neg/abs and the op. A VGPR result goes to `dst_sel`, with `dst_unused` setting the other bits: PAD = 0, SEXT = sign copies above the field, PRESERVE = old bits kept. A byte or word destination with PRESERVE reads its incoming VGPR on first use. The synthetic `sdwa_bary_input.asm` checks this with two raw fragment weights, following the [LLVM SDWA destination rules](https://llvm.org/docs/AMDGPUModifierSyntax.html#dst-unused). VOPC has no `dst_sel`, and GFX10 `v_cmpx` has no written destination. **Until 2026-11-20 the selects were silently ignored.** That affected 3,826 of the 13,926 translated shaders: they passed `spirv-val` but computed wrong values. GPU-checked with `runtime/test/shaders/ps_sdwa.asm` and `ps_ops.asm` (also `v_pk_fma_f16`, `v_min3_u32`, `v_max3_i32`, `v_bfe_i32`): byte/word source selects, `sext()`, `UNUSED_PRESERVE` into WORD_1 and `UNUSED_SEXT` at BYTE_2 all match on every pixel. **Measured natively on RDNA2** (gfx1036 iGPU, `tools/hw_oracle`, the game's MODE): all 172 distinct SDWA forms of the 26,503 listings (79,307 instructions: opcode, operand kinds, sels, `sext`, neg/abs, `dst_unused`, omod), 12 operand words per source, 21,204 cases. 18,885 give the translator's word. The rest are: a 16-bit result with `dst_sel:DWORD`, where the hardware zeroes the high half and the translator keeps it (1,888, #2187); a NaN result, where the hardware keeps the input's sign and payload (826, of which 556 also fall in the first group, so the groups add up to 21,204; as in the f16 transcendentals row); `div:2` on -0, which gives +0 (1, as in the output-modifier rows); and 160 cases whose translation is undefined in SPIR-V (`FClamp`/`FDiv`/`Sqrt` on NaN, zero or negative operands). `tests/semantic/test_alu_sdwa_hw.py` replays 624 of the matching words, up to four per form. | -| VOP3 output and source modifiers in the game's forms, on RDNA2 | Every distinct float VALU form in the 26,503 listings that carries `clamp`, an omod (`mul:2`/`mul:4`/`div:2`), `op_sel`/`op_sel_hi` or neg/abs: 572 forms, 1,270,932 instructions (`v_mul_legacy_f32 … clamp` alone is 147,499; `v_fma_mix_f32` has 222 forms), up to 120 random operand triples each, run natively on gfx1036 (`tools/hw_oracle`, the game's MODE) and through the translator: 542 forms, 64,802 cases (the GFX10.1-only `v_mad_f32`/`v_mad_legacy_f32`/`v_mac_f32` and `v_permlanex16` are left out). 51,761 give the translator's word. The rest are differences already on record: NaN sign and payload (5,074); f32 denormal operands or results, and a denormal intermediate that the hardware flushes before the omod or clamp (1,178; SHADER-377); an omod turning a -0 result into +0 (121; the Output modifiers rows, #1281); 1 ulp or the known sin/cos precision in `v_rcp/v_rcp_iflag/v_log/v_sin/v_cos` with an omod (56); and 6,430 whose translation is undefined in SPIR-V, mostly `FClamp` of a NaN, where the hardware gives +0 under DX10_CLAMP (#2437). 182 cases were my harness's (three distinct SGPRs, over GFX10's two-read limit). No other modifier difference. `tests/semantic/test_alu_vop3_mods_hw.py` replays 1,616 matching words, up to three per form; it fails without `clamp` (326 rows) or without the omod (237). | +| VOP3 output and source modifiers in the game's forms, on RDNA2 | Every distinct float VALU form in the 26,503 listings that carries `clamp`, an omod (`mul:2`/`mul:4`/`div:2`), `op_sel`/`op_sel_hi` or neg/abs: 572 forms, 1,270,932 instructions (`v_mul_legacy_f32 … clamp` alone is 147,499; `v_fma_mix_f32` has 222 forms), up to 120 random operand triples each, run natively on gfx1036 (`tools/hw_oracle`, the game's MODE) and through the translator: 542 forms, 64,802 cases (the GFX10.1-only `v_mad_f32`/`v_mad_legacy_f32`/`v_mac_f32` and `v_permlanex16` are left out). 51,761 give the translator's word. The rest are differences already on record: NaN sign and payload (5,074); f32 denormal operands or results, and a denormal intermediate that the hardware flushes before the omod or clamp (1,178; SHADER-377); an omod turning a -0 result into +0 (121; the Output modifiers rows, #1281); 1 ulp or the known sin/cos precision in `v_rcp/v_rcp_iflag/v_log/v_sin/v_cos` with an omod (56); and 6,430 whose translation is undefined in SPIR-V, mostly `FClamp` of a NaN, where the hardware gives +0 under DX10_CLAMP (#2437; the f32/f16 clamp of a NaN gives +0 since 2026-11-24, see "Float min/max/med3 with NaN"). 182 cases were my harness's (three distinct SGPRs, over GFX10's two-read limit). No other modifier difference. `tests/semantic/test_alu_vop3_mods_hw.py` replays 1,616 matching words, up to three per form; it fails without `clamp` (326 rows) or without the omod (237). | | Byte permute | `v_perm_b32`: result byte i = BYTE_PERMUTE({src0, src1}, selector byte i), src1 = bytes 0–3 (AMD "RDNA 2" ISA reference, VOP3 opcode 836 V_PERM_B32, `byte_permute` pseudocode, page 189 of the PDF). Selector 0–7 picks that byte; **8, 9, 10, 11 give 0xff if bit 7 of byte 1, 3, 5, 7 is set, else 0x00**; 12 gives 0x00; 13 and above give 0xff. **Until 2026-11-21 selectors 8–11 gave 0x00 regardless of the sign bit**. In the 26,503-shader disassembled corpus (measured via `tools/feature_scan.py`), 0 of 10,500 shaders (11,930 `v_perm_b32` instructions) use selectors 8–11 or >= 13: all 11,258 immediate and 672 constant-register selectors (0 unresolved) use only bytes 0–7 (36,234) and 12 (11,486). GPU-checked with `runtime/test/shaders/ps_ops7.asm` (also `v_alignbit_b32` with a shift of 36, `v_med3_i32` vs `v_med3_u32`) and `ps_ops8.asm` (`v_mul_hi_u32/i32`, `v_bcnt_u32_b32`, `v_ffbl_b32`, `v_ffbh_u32` of 0, `v_xad_u32`, `v_add3_u32`), 4096/4096 pixels on an AMD Radeon iGPU (Ryzen 7 9800X3D, RDNA2, AMD driver 25.10.36) and an NVIDIA GeForce RTX 5070 (driver 621.24); before the fix `ps_ops7` gave 0x00000000 for the sign-selector word on both. Also executed by `tests/semantic/test_value_semantics.py`. When S2 is a literal or a currently known SGPR constant, the translator emits fixed byte extracts/inserts (including sign replication), folds the zero and 0xff bytes, and uses the selected source directly for a whole-word identity. `tests/semantic/test_perm_known_selector.py` checks the resulting words and that selector dispatch only remains for a clobbered SGPR. | | Sum of absolute differences (`v_sad_u8`, `v_sad_hi_u8`, `v_sad_u16`, `v_sad_u32`, `v_msad_u8`) | Unsigned, wrapping at 32 bits, with ABSDIFF(x, y) = `UMax − UMin`: `v_sad_u8` = S2 + the sum over the four bytes; `v_sad_hi_u8` = (that byte sum << 16) + S2; `v_sad_u16` = S2 + the sum over the two halves; `v_sad_u32` = \ \| S0 − S1\ \| + S2; `v_msad_u8` skips a byte where S1's byte is 0. `clamp` raises `Unsupported`: the ISA pseudocode doesn't say what it does to these ops. Source: RDNA2 ISA VOP3 opcodes 346–349 and 369 (pseudocode re-read for this row). CPU-checked by `tests/semantic/test_alu_sad.py` (#544): a 9×9 grid of edge words per op, 40 seeded cases, masked bytes, an SGPR source, `clamp` rejected; the PR also reports a 300-case differential run per op with 0 mismatches. None of them is in the translated corpus, and none is GPU-checked. **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137). Measured on native gfx1036 (AMD Radeon Graphics, RDNA2) through tools/hw_oracle across edge byte/half patterns, zero masks, and wrap cases: all match the ISA reference with 0 mismatches. | | Quad-byte SAD 64-bit source operands | The GFX10.3 `null` operand supplies zero for the 64-bit input window in all three quad-byte SAD operations and for the 64-bit addend of the two packed forms. Confirmed with LLVM gfx1030 assembly and scalar byte-difference references in `tests/semantic/test_alu_qsad.py` (`test_null_pixel_source_and_null_accumulator`) and `tests/semantic/test_alu_mqsad_u32.py` (`test_null_pixel_source`). | diff --git a/docs/shader_validation.md b/docs/shader_validation.md index 381b116428..ac33debfaf 100644 --- a/docs/shader_validation.md +++ b/docs/shader_validation.md @@ -1997,7 +1997,7 @@ the two wave sizes agree on every word. `tools/fma_mix_probe.py --oracle hw` (th `tests/semantic/spirv_mini_interp.py`, then compared with the hardware under the MODE the translator assumes for the game (IEEE 0, DX10_CLAMP 1, f32 denormals flushed, f16 denormals kept). It gives the same word for the float constants in every `op_sel`/`op_sel_hi` combination, for the integer constants as f16 halves, for clamp on values that -are not NaN, and for the f16 denormals. It differs in five ways, none fixed here: +are not NaN, and for the f16 denormals. It differs in five ways; item 2 is fixed since 2026-11-24: 1. **f16 omod.** The translator applies `mul:2`/`mul:4`/`div:2` to every f16 result. The hardware ignores them in this MODE (24 words: `v_add/mul/fma/fmac/exp/rcp_f16`). `v_cvt_f16_f32` drops its omod and clamp today, so its omod @@ -2007,6 +2007,7 @@ are not NaN, and for the f16 denormals. It differs in five ways, none fixed here when "output denormals" are off, the `SIFoldOperands.cpp` comment quoted above). That count needs the game files. 2. **clamp of a NaN.** The interpreter refuses `FClamp` with a NaN operand, which GLSL.std.450 leaves undefined. The hardware gives +0 with DX10_CLAMP 1, for `v_fmac_f16`, `v_fma_mixlo_f16` and `v_fma_mix_f32` alike (SHADER-186). + **Fixed since 2026-11-24:** `Gen.clamp_mods` selects +0 for a NaN before `FClamp` (`tests/semantic/test_vop3_clamp_nan.py`). 3. **Mix-op rounding.** The hardware rounds once (the section above). 4. **f32 denormal operands of the mix ops.** They are not flushed with `denorm_mode_32 = 0`: `0x00000001`, `0x807fffff` and the integer constants `1` and `64` used as f32 give the denormal, where the hardware gives a zero of its sign diff --git a/tests/semantic/f16_unary_cases.py b/tests/semantic/f16_unary_cases.py index 361563ece5..a24b2b7c08 100644 --- a/tests/semantic/f16_unary_cases.py +++ b/tests/semantic/f16_unary_cases.py @@ -162,15 +162,15 @@ def test_neg_and_abs_source_modifiers(self): def test_output_modifiers_and_clamp(self): for a in self.MOD_INPUTS: base = self.ref(a) - # `clamp` of a NaN result is not modelled (the translator emits FClamp; docs/design.md, float min/max/med3 with - # NaN), so a NaN result is only checked with the output multipliers. + # `clamp` of a NaN result gives +0 (DX10_CLAMP 1 in the game's MODE; Gen.clamp_mods selects +0 for a NaN + # before FClamp, docs/design.md, float min/max/med3 with NaN). # #4542, measured on gfx1036: an f16 destination ignores omod (mul:2/mul:4/div:2) under the game's MODE # (IEEE=0, f16 denormals kept) and keeps clamp (docs/design.md, f16 output modifiers). for suffix, want in ((" mul:2", base), (" mul:4", base), (" div:2", base), (" clamp", clamp01(base)), (" mul:2 clamp", clamp01(base))): if is_nan(base) and "clamp" in suffix: - continue + want = 0 with self.subTest(a=hex(a), mod=suffix): got = run(self.line("_e64") + suffix, {"v1": a}) self.assertEqual(got >> 16, OLD >> 16) diff --git a/tests/semantic/test_alu_f32_min_max.py b/tests/semantic/test_alu_f32_min_max.py index 123d92faec..af8ed533bd 100644 --- a/tests/semantic/test_alu_f32_min_max.py +++ b/tests/semantic/test_alu_f32_min_max.py @@ -808,10 +808,11 @@ def test_python_default_nan_divergence(self) -> None: # The reference oracle correctly returns 2.0. self.assertEqual(ref_min_f32(QNAN, TWO), TWO) - def test_clamp_on_all_nan_raises_unsupported(self) -> None: - # Clamping an all-NaN result is undefined in GLSL.std.450 / SPIR-V and raises UnsupportedConstruct. - with self.assertRaises(si.UnsupportedConstruct): - run_f32_2op("v_min_f32", QNAN, QNAN, e64=True, clamp=True) + def test_clamp_on_all_nan_gives_plus_zero(self) -> None: + # The all-NaN result is a NaN; the clamp bit turns it into +0 under the game's DX10_CLAMP 1 + # (docs/shader_validation.md), selected before FClamp, which is undefined for a NaN operand. + self.assertEqual(run_f32_2op("v_min_f32", QNAN, QNAN, e64=True, clamp=True), POS_ZERO) + self.assertEqual(run_f32_2op("v_max_f32", NEG_QNAN, SNAN, e64=True, clamp=True), POS_ZERO) def test_med3_third_operand_nan_is_min3(self) -> None: # Since #2029 a NaN operand gives min3 of the operands (measured on gfx1030), not an eager FClamp on NaN. diff --git a/tests/semantic/test_alu_min3_max3.py b/tests/semantic/test_alu_min3_max3.py index ec7bd3ce76..fe774fb9bf 100644 --- a/tests/semantic/test_alu_min3_max3.py +++ b/tests/semantic/test_alu_min3_max3.py @@ -17,8 +17,9 @@ - Signed zeros are ordered with -0.0 below +0.0 (the hardware order measured on AMD RDNA2, docs/design.md): min(+0.0, -0.0) = -0.0 and max(+0.0, -0.0) = +0.0 in either operand order. - VOP3 input modifiers: absolute value (|src|), negation (-src), and neg-abs (-|src|). -- VOP3 output modifier: clamp to [0.0, 1.0]. If all operands are NaN, clamp raises - UnsupportedConstruct because GLSL.std.450 FClamp on NaN is undefined. +- VOP3 output modifier: clamp to [0.0, 1.0]. If all operands are NaN, the NaN result clamps to +0 + (DX10_CLAMP 1 in the game's MODE; the translator selects +0 before GLSL.std.450 FClamp, which is + undefined for a NaN operand). Integer min/max: - v_min3_i32 and v_max3_i32 evaluate operands as signed 32-bit integers in two's complement. @@ -142,7 +143,7 @@ def ref_float(op: str, a: float, b: float, c: float, *, clamp: bool = False) -> r = ref_nmin_nmax(fn, ref_nmin_nmax(fn, a, b), c) if clamp: if math.isnan(r): - raise si.UnsupportedConstruct("clamp on NaN is undefined") + return 0.0 # DX10_CLAMP 1: the clamp bit turns a NaN into +0 r = max(0.0, min(1.0, r)) return r @@ -330,8 +331,7 @@ class FloatNanSkippingTests(unittest.TestCase): """GLSL.std.450 NMin and NMax implement IEEE 754-2008 NaN-skipping: - If one or two operands are NaN, the non-NaN operand is chosen. - If all three operands are NaN, NaN is returned. - - If clamp modifier is specified on all-NaN, UnsupportedConstruct is raised because - FClamp on NaN is undefined. + - If clamp modifier is specified on all-NaN, the result is +0 (DX10_CLAMP 1). """ def test_single_nan_operand_skipped(self) -> None: @@ -370,11 +370,10 @@ def test_all_three_nans_produce_nan(self) -> None: res = run_alu(op, QNAN_BITS, SNAN_BITS, NEG_QNAN_BITS) self.assertTrue(math.isnan(u32_to_f32(res))) - def test_clamp_on_all_nan_rejected(self) -> None: + def test_clamp_on_all_nan_gives_plus_zero(self) -> None: for op in FLOAT_OPS: with self.subTest(op=op): - with self.assertRaises(si.UnsupportedConstruct): - run_alu(op, QNAN_BITS, SNAN_BITS, NEG_QNAN_BITS, clamp=True) + self.assertEqual(run_alu(op, QNAN_BITS, SNAN_BITS, NEG_QNAN_BITS, clamp=True), 0) class FloatModifiersTests(unittest.TestCase): diff --git a/tests/semantic/test_alu_vop3_mods_hw.py b/tests/semantic/test_alu_vop3_mods_hw.py index 8f680afefe..4ced572ad8 100644 --- a/tests/semantic/test_alu_vop3_mods_hw.py +++ b/tests/semantic/test_alu_vop3_mods_hw.py @@ -12,7 +12,8 @@ sample, up to three per form with distinct results. The measured cases not listed match too, except for differences already on record: an omod turning a -0 result into +0 (docs/design.md, Output modifiers rows; #1281), f32 denormal operands or intermediate results (SHADER-377), NaN sign/payload, 1-ulp differences in v_rcp/v_log/v_sin, and cases -whose translation is undefined in SPIR-V (FClamp of a NaN, the root or log of a negative or zero). +whose translation is undefined in SPIR-V (FClamp of a NaN, the root or log of a negative or zero). The f32/f16 clamp of a +NaN gives +0 since 2026-11-24 (test_vop3_clamp_nan.py); those rows are not replayed here. """ import os import struct diff --git a/tests/semantic/test_valu_f32_min3_max3_mad.py b/tests/semantic/test_valu_f32_min3_max3_mad.py index 58d06bbd92..db75232df5 100644 --- a/tests/semantic/test_valu_f32_min3_max3_mad.py +++ b/tests/semantic/test_valu_f32_min3_max3_mad.py @@ -12,8 +12,8 @@ Observed translator / interpreter findings (kept out of failing assertions and documented here): 1. v_min3_f32 / v_max3_f32 with NaN operands: tools/rdna2spirv.py emits GLSL.std.450 NMin / NMax, which give the other operand for a NaN, as RDNA2 hardware does. Those rows are asserted in tests/semantic/ - test_float_nan_fract.py; NaN inputs stay out of the value assertions here (clamp-on-NaN is still FClamp, which - spirv_mini_interp.py rejects). NaN semantics are tested on v_mad_f32, v_fmac_f32, and v_mad_legacy_f32. + test_float_nan_fract.py; NaN inputs stay out of the value assertions here (clamp-on-NaN, which gives +0, is + checked in test_vop3_clamp_nan.py). NaN semantics are tested on v_mad_f32, v_fmac_f32, and v_mad_legacy_f32. 2. v_min3_f32 / v_max3_f32 signed-zero ties: RDNA2 hardware orders -0.0 below +0.0 (measured on an AMD Radeon RX 6800: min(+0, -0) = -0 and max(+0, -0) = +0 in either operand order), and spirv_mini_interp.py's NMin / NMax do the same, so every zero triple asserts exact bit patterns. diff --git a/tests/semantic/test_vop3_clamp_nan.py b/tests/semantic/test_vop3_clamp_nan.py new file mode 100644 index 0000000000..6b4db1b945 --- /dev/null +++ b/tests/semantic/test_vop3_clamp_nan.py @@ -0,0 +1,137 @@ +"""VOP3 `clamp` of a NaN result gives +0 (Gen.clamp_mods). + +The game's MODE has DX10_CLAMP 1, and with it the clamp bit turns a NaN result into +0: measured on RDNA2 (gfx1036) +for v_rcp_iflag_f32 (docs/shader_validation.md, "32-bit float VALU on the GPU": a NaN result +0 except with DX10_CLAMP +off, 169 programs) and for v_fmac_f16, v_fma_mixlo_f16 and v_fma_mix_f32 (SHADER-186, "f16 output modifiers, clamp and +v_fma_mix* operands on RDNA2"). +GLSL.std.450 leaves FClamp undefined for a NaN operand, so the translator selects +0 for a NaN before FClamp, as the +div_fixup and cvt_pknorm clamps already did. Before that the shared helper emitted a bare FClamp, which the CPU +interpreter refuses (UnsupportedConstruct) and which a driver may return as the NaN. + +Each program computes one value in v4 and exports it. The NaN comes from a NaN operand (quiet, negative, signalling) +or from an invalid operation (inf - inf, -inf * 0); controls without a NaN check that the clamp itself is unchanged. +Standard library only; no game data. +""" +import os +import sys +import unittest + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from support import mrt0_words, translate_lines # noqa: E402 + +QNAN = 0x7FC00000 +NEG_QNAN = 0xFFC00000 +SNAN = 0x7F800001 +POS_INF = 0x7F800000 +NEG_INF = 0xFF800000 +ONE = 0x3F800000 +TWO = 0x40000000 +QUARTER = 0x3E800000 +NEG_ONE = 0xBF800000 +F16_QNAN = 0x7E00 +F16_NEG_QNAN = 0xFE00 +F16_ONE = 0x3C00 +F16_HALF = 0x3800 + + +def run(op_line, v1, v2, v3=0): + """mrt0.x after `op_line` (which writes v4) with v1..v3 set to the given words.""" + spv = translate_lines("ps_clamp_nan", [ + f"v_mov_b32 v1, {v1:#x}", + f"v_mov_b32 v2, {v2:#x}", + f"v_mov_b32 v3, {v3:#x}", + "v_mov_b32 v4, 0xdeadbeef", + op_line, + "exp mrt0 v4, v4, v4, v4 done vm", + "s_endpgm", + ]) + return mrt0_words(spv)[0] + + +class ClampNanF32Tests(unittest.TestCase): + def test_nan_operand_clamps_to_plus_zero(self): + for nan in (QNAN, NEG_QNAN, SNAN): + for line in ("v_add_f32_e64 v4, v1, v2 clamp", + "v_sub_f32_e64 v4, v1, v2 clamp", + "v_mul_f32_e64 v4, v1, v2 clamp", + "v_fma_f32 v4, v1, v2, v2 clamp", + "v_mul_f32_e64 v4, v1, v2 mul:2 clamp"): + with self.subTest(op=line, nan=hex(nan)): + self.assertEqual(run(line, nan, ONE), 0) + + def test_invalid_operation_clamps_to_plus_zero(self): + self.assertEqual(run("v_sub_f32_e64 v4, v1, v2 clamp", POS_INF, POS_INF), 0) # inf - inf + self.assertEqual(run("v_add_f32_e64 v4, v1, v2 clamp", POS_INF, NEG_INF), 0) # inf + -inf + self.assertEqual(run("v_mul_f32_e64 v4, v1, v2 clamp", NEG_INF, 0), 0) # -inf * 0 + self.assertEqual(run("v_fma_f32 v4, v1, v2, v3 clamp", POS_INF, 0, ONE), 0) # inf * 0 + 1 + + def test_all_nan_min_max_clamps_to_plus_zero(self): + # Without clamp an all-NaN min/max keeps src0's NaN (docs/design.md); the clamp then gives +0. + for op in ("v_min_f32_e64", "v_max_f32_e64"): + with self.subTest(op=op): + self.assertEqual(run(f"{op} v4, v1, v2 clamp", QNAN, NEG_QNAN), 0) + for op in ("v_min3_f32", "v_max3_f32"): + with self.subTest(op=op): + self.assertEqual(run(f"{op} v4, v1, v2, v3 clamp", QNAN, SNAN, NEG_QNAN), 0) + + def test_nan_without_clamp_is_still_nan(self): + # The select is only on the clamp path: without clamp a NaN result stays a NaN. + w = run("v_add_f32_e64 v4, v1, v2", QNAN, ONE) + self.assertEqual(w & 0x7F800000, 0x7F800000) + self.assertNotEqual(w & 0x007FFFFF, 0) + + def test_clamp_controls_unchanged(self): + self.assertEqual(run("v_add_f32_e64 v4, v1, v2 clamp", TWO, TWO), ONE) + self.assertEqual(run("v_add_f32_e64 v4, v1, v2 clamp", NEG_ONE, 0), 0) + self.assertEqual(run("v_add_f32_e64 v4, v1, v2 clamp", QUARTER, 0), QUARTER) + self.assertEqual(run("v_mul_f32_e64 v4, v1, v2 clamp", POS_INF, ONE), ONE) + self.assertEqual(run("v_mul_f32_e64 v4, v1, v2 clamp", NEG_INF, ONE), 0) + + + def test_legacy_ops_nan_clamps_to_plus_zero(self): + # v_mul_legacy_f32 ... clamp is the most common clamp form in the game's listings (docs/design.md). + self.assertEqual(run("v_mul_legacy_f32_e64 v4, v1, v2 clamp", QNAN, ONE), 0) + self.assertEqual(run("v_mad_legacy_f32 v4, v1, v2, v3 clamp", QNAN, ONE, 0), 0) + + +# An f16 result written to the low half keeps the high half of v4 (0xdead); op_sel:[0,0,1] and v_fma_mixhi_f16 write +# the high half and keep the low one (0xbeef). +LO_ZERO = 0xDEAD0000 +HI_ZERO = 0x0000BEEF + + +class ClampNanF16Tests(unittest.TestCase): + def test_f16_nan_clamps_to_plus_zero(self): + for nan in (F16_QNAN, F16_NEG_QNAN): + for line in ("v_add_f16_e64 v4, v1, v2 clamp", + "v_mul_f16_e64 v4, v1, v2 clamp", + "v_fmac_f16_e64 v4, v1, v2 clamp", + "v_fma_f16 v4, v1, v2, v3 clamp"): + with self.subTest(op=line, nan=hex(nan)): + self.assertEqual(run(line, nan, F16_ONE), LO_ZERO) + + def test_f16_high_half_nan_clamps_to_plus_zero(self): + self.assertEqual(run("v_add_f16_e64 v4, v1, v2 op_sel:[0,0,1] clamp", F16_QNAN, F16_ONE), HI_ZERO) + self.assertEqual(run("v_fma_mixhi_f16 v4, v1, v2, v3 clamp", QNAN, ONE, 0), HI_ZERO) + + def test_f16_all_nan_med3_clamps_to_plus_zero(self): + self.assertEqual(run("v_med3_f16 v4, v1, v2, v3 clamp", F16_QNAN, F16_NEG_QNAN, 0x7E01), LO_ZERO) + + def test_conversions_nan_clamp_to_plus_zero(self): + self.assertEqual(run("v_cvt_f32_f16_e64 v4, v1 clamp", F16_QNAN, 0), 0) + self.assertEqual(run("v_cvt_f16_f32_e64 v4, v1 clamp", QNAN, 0), LO_ZERO) + self.assertEqual(run("v_cvt_f16_f32_e64 v4, v1 mul:2 clamp", NEG_QNAN, 0), LO_ZERO) + + def test_mix_ops_nan_clamp_to_plus_zero(self): + # SHADER-186 measured +0 on gfx1036 for these (docs/shader_validation.md). + self.assertEqual(run("v_fma_mix_f32 v4, v1, v2, v3 op_sel_hi:[1,1,1] clamp", F16_QNAN, F16_ONE, 0), 0) + self.assertEqual(run("v_fma_mixlo_f16 v4, v1, v2, v3 clamp", QNAN, ONE, 0), LO_ZERO) + + def test_f16_clamp_controls_unchanged(self): + self.assertEqual(run("v_add_f16_e64 v4, v1, v2 clamp", F16_ONE, F16_ONE), 0xDEAD0000 | F16_ONE) + self.assertEqual(run("v_add_f16_e64 v4, v1, v2 clamp", F16_HALF, 0), 0xDEAD0000 | F16_HALF) + self.assertEqual(run("v_fma_mixlo_f16 v4, v1, v2, v3 clamp", TWO, ONE, 0), 0xDEAD0000 | F16_ONE) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_f64_conversion.py b/tests/test_f64_conversion.py index 514ef2398b..7601c595b4 100644 --- a/tests/test_f64_conversion.py +++ b/tests/test_f64_conversion.py @@ -46,6 +46,9 @@ def result(instruction): scale = result(rf"OpBitcast %float {constant}") value = result(rf"OpFMul %float {value} {scale}") if clamp: + # DX10_CLAMP: a NaN is replaced by +0 before FClamp (Gen.clamp_mods). + nan = result(rf"OpIsNan %bool {value}") + value = result(rf"OpSelect %float {nan} %f0 {value}") value = result(rf"OpExtInst %float %glsl FClamp {value} %f0 %f1") word = result(rf"OpBitcast %uint {value}") dest = result(r"OpAccessChain %_ptr_Function_uint %vgpr %c3") diff --git a/tests/test_rcp_iflag_mods.py b/tests/test_rcp_iflag_mods.py index f355106119..5439aef92e 100644 --- a/tests/test_rcp_iflag_mods.py +++ b/tests/test_rcp_iflag_mods.py @@ -74,6 +74,9 @@ def match_result(pattern): self.assertNotRegex(spv, r"\bOpFMul %float\b") if clamp: + # DX10_CLAMP: a NaN is replaced by +0 before FClamp (Gen.clamp_mods). + nan = match_result(rf"OpIsNan %bool {value}") + value = match_result(rf"OpSelect %float {nan} %f0 {value}") value = match_result(rf"OpExtInst %float %glsl FClamp {value} %f0 %f1") else: self.assertNotIn("FClamp", spv) diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 920e858ae8..37b0698087 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -6593,8 +6593,13 @@ def clamp_mods(self, v, mods, allow_omod=True): self.emit(f"{g} = OpFMul %float {v} {c}") v = g if "clamp" in mods: - g = self.tmp() - self.emit(f"{g} = OpExtInst %float %glsl FClamp {v} %f0 %f1") + # The game's MODE has DX10_CLAMP=1, so the clamp bit turns a NaN result into +0 + # (docs/shader_validation.md). GLSL.std.450 FClamp leaves a NaN operand undefined, + # so select +0 for a NaN first, as the div_fixup and cvt_pknorm clamps do. + nan, safe, g = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{nan} = OpIsNan %bool {v}") + self.emit(f"{safe} = OpSelect %float {nan} %f0 {v}") + self.emit(f"{g} = OpExtInst %float %glsl FClamp {safe} %f0 %f1") return g return v