From b176c9f5aafff117a49d22a84e54c64803aca632 Mon Sep 17 00:00:00 2001 From: ShotTechOp Date: Thu, 26 Nov 2026 21:15:52 +0530 Subject: [PATCH] rdna2spirv: route remaining 16-bit high-half readers through u16_half/i16_half (SHADER-HIGH-HALF-SHARED-READERS) --- docs/design.md | 2 +- .../semantic/test_high_half_shared_readers.py | 223 ++++++++++++++++++ tools/rdna2spirv.py | 48 ++-- 3 files changed, 246 insertions(+), 27 deletions(-) create mode 100644 tests/semantic/test_high_half_shared_readers.py diff --git a/docs/design.md b/docs/design.md index 656418c99a..a30e814ae4 100644 --- a/docs/design.md +++ b/docs/design.md @@ -529,7 +529,7 @@ How the generated SPIR-V expects the runtime to work: | Float-to-byte pack | `v_cvt_pk_u8_f32` rounds to nearest even (the default MODE round mode; the hardware follows the MODE register's f32 round mode, which the translator ignores, see #358), clamps to [0, 255], and gives 0 for NaN and negative values, then inserts the byte at `src1[1:0]` of `src2` and keeps the other three. NaN is replaced by +0 before `FClamp`, which is undefined for a NaN operand. **Measured natively** on RDNA2 (gfx1036, the Ryzen 7 9800X3D iGPU, AMD driver 25.10, the instruction run through inline assembly): all 256 inputs k + 0.5 round to even, 0.5 gives 0, 0x3f000001 gives 1, +inf and 300.0 give 255, -inf, -1.0, ±0, denormals and quiet, signalling and negative NaNs give 0 (#358). `cs_cvt_pk_u8.asm` holds eight of these words, checked by `check.py`/`run_gpu_tests.py` and bit-for-bit by `tests/semantic/test_cvt_pk_u8.py`. | | Known approximations | `v_cvt_pkrtz_f16_f32` is now **exact round-toward-zero** (finite overflow gives ±65504, not inf). The GPU smoke test caught the old round-to-nearest version producing inf in `PS_ImposterShadow`. The other f16 packs (`v_cvt_f16_f32`, d16 results, mix ops) round to nearest, which matches the default mode; the ALU ones follow a MODE toward-zero write (see the f16 rounding row). `v_fma_mixlo/mixhi_f16` round the exact `x*y+z` once in every mode (measured on an RDNA2 iGPU, gfx1036, 7 of 7 discriminating tie inputs, SHADER-135); the translator does that in both modes through `Gen.fma_mix_odd`; the ALU ones follow a MODE toward-zero write (below; `v_fma_mixlo/mixhi_f16` round the exact `x*y+z` once in every mode (measured on an RDNA2 iGPU, gfx1036, 7 of 7 discriminating tie inputs, SHADER-135); toward zero the translator does that already, while in nearest-even mode it still narrows an f32 `Fma`, which is 1 f16 ulp off on ties until #1774 (SHADER-296) lands; the ALU ones follow a MODE toward-zero write (below; ALU sites: see the f16 rounding row). MODE: `s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2)` (f16/f64 rounding) is tracked in a per-invocation variable, the only MODE field the corpus writes (9,417 writes in 6,333 shaders: 6,694 toward zero, 2,723 back to nearest even). While it is toward zero, every VALU f16 result except the transcendentals listed below (`v_cvt_f16_f32`, f16 arithmetic, `v_pk_*_f16`, `v_fma_mix{lo,hi}_f16`, `v_interp_p2_f16`) rounds toward zero exactly, with the integer conversion `v_cvt_pkrtz_f16_f32` uses (`f16_bits(rtz=True)`, see the f16 rounding row), and `v_add_f64` steps back one ulp when the TwoSum error shows it rounded away from zero; finite overflow gives the largest finite value. The `v_add_f64` output modifiers apply after that step and round to nearest, so an omod that overflows or lands on a subnormal is not toward zero. **omod versus denormal mode is unmodelled:** the translator applies `mul:2`/`mul:4`/`div:2` regardless of the MODE denormal fields (as before this change), whereas hardware ignores omod when denormals are kept (denorm fields = 3) and applies it when they are flushed (both measured on an RX 6800: `v_add_f64 (1 - 2^-60) mul:2` with denormals kept gave 3ff00000:00000000 nearest and 3fefffff:ffffffff toward zero, unscaled; mul:2 was applied with denormals flushed); the tests therefore claim no omod order. CPU-checked by `tests/test_mode_round.py` (the RX 6800 words for f16 add/sub, `v_fma_mix`, the transcendentals, f64 overflow). f16 add and sub (f16 operands) and `v_pk_add_f16` take the exact TwoSum error of the f32 result into account, so they are exact toward zero too (f32 then f16 rounding alone would be wrong: 2 - 2^-24 is an f32 tie that rounds up to 2.0); f16 FMAs need nothing extra, since their round-to-odd f32 value (SHADER-55) narrows exactly in either mode. `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, in both nearest-even and toward-zero modes (measured on AMD RDNA2 gfx1036, finding 7079901079; an RX 6800 gave 0x3fff for 1 * 2 - 2^-30, where rounding to f32 first and then narrowing gives 0x4000): `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, in both nearest-even and toward-zero modes (measured on AMD RDNA2 gfx1036 across 7 of 7 discriminating tie inputs with `tools/fma_mix_probe.py --oracle hw`, SHADER-135, finding 7079901079, and on an RX 6800 where toward zero gave 0x3fff for 1 * 2 - 2^-30 vs 0x4000 with double rounding; fixed for nearest mode in SHADER-296 / #1774; see docs/shader_validation.md, "`v_fma_mix*` f16 rounding in nearest mode"): `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, toward zero (an RX 6800 gave 0x3fff for 1 * 2 - 2^-30, where rounding to f32 first and then narrowing gives 0x4000): `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, in both nearest-even and toward-zero modes (measured on AMD RDNA2 gfx1036 and verified by `tools/fma_mix_probe.py`; finding 7079901079; toward zero an RX 6800 gave 0x3fff for 1 * 2 - 2^-30, where rounding to f32 first and then narrowing gives 0x4000): `Gen.fma_mix_odd` corrects the f32 `Fma` to round-to-odd by the sign of its exact residual (product error by `Fma(x, y, -x*y)`, TwoSum of the sum), which narrows exactly in either direction; the nearest-even path is unchanged (f32 `Fma`, then narrow). `fma_mix_odd` also handles a tiny product ( \| a x*y \| >= < 2^-64: its error underflows or is flushed, so the residual sign is sign(x) xor sign(y), independent of the driver's denormal mode) and an f32 overflow with finite operands (toward zero gives ±FLT_MAX, so f16 ±65504). `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16`, `v_sin_f16`, `v_cos_f16`, `v_exp_f16` and `v_log_f16` ignore the rounding mode on hardware, so they always narrow to nearest even; all seven are measured (an RX 6700 XT gave the same words with FP_ROUND round-toward-zero and round-to-nearest on every input of each; see the f16 transcendentals row). `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16`, `v_sin_f16`, `v_cos_f16`, `v_exp_f16` and `v_log_f16` ignore the rounding mode on hardware (RX 6800 for the first four, plus an exhaustive 65,536-input RNE vs RTZ sweep of all seven in wave32 and wave64 on native `gfx1036` via `tools/mode_round_probe.py`, SHADER-132: 0/65,536 inputs differ on every op; the same probe also confirmed all 17 f16/f64 RNE vs RTZ cases including `v_cvt_f16_f32`, `v_add/sub/mul/fma_f16`, `v_pk_add/fma_f16`, `v_fma_mix{lo,hi}_f16` and `v_add_f64` overflow saturation in both wave32 and wave64), so they always narrow to nearest even. In nearest mode the hardware rounds once as well: `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16`, `v_sin_f16`, `v_cos_f16`, `v_exp_f16` and `v_log_f16` ignore the rounding mode on hardware, so they always narrow to nearest even; all seven are measured (an RX 6700 XT gave the same words with FP_ROUND round-toward-zero and round-to-nearest on every input of each, see the f16 transcendentals row; independently confirmed by an exhaustive 65,536-input RNE vs RTZ sweep of all seven in wave32 and wave64 on native `gfx1036` via `tools/mode_round_probe.py`, SHADER-132: `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16` and `v_sin_f16` ignore the rounding mode on hardware (RX 6800: the same words in every mode), so they always narrow to nearest even; `v_cos_f16`, `v_exp_f16` and `v_log_f16` are unmeasured, assumed like those four and treated the same. The "every VALU f16 result rounds toward zero" sentence above therefore excludes these seven; the f16 results of `v_floor/ceil/trunc/rndne/fract_f16` are exact and need no rounding. `tools/fma_mix_probe.py --oracle hw` on an RDNA2 iGPU (gfx1036, SHADER-135) gave the single-rounded word for all seven inputs where the two rules differ by one f16 ulp, as `Gen.fma_mix_odd` produces (docs/shader_validation.md, "`v_fma_mix*` f16 rounding in nearest mode"). In nearest mode the translator still rounds `v_fma_mix{lo,hi}_f16` twice (f32 `Fma`, then narrow), but the hardware rounds once there as well: `tools/fma_mix_probe.py --oracle hw` on an RDNA2 iGPU (gfx1036, SHADER-135) gave the single-rounded word for all seven inputs where the two rules differ by one f16 ulp, so the translator, which rounded twice there (f32 `Fma`, then narrow) until #1774, was one f16 ulp off on exactly those ties (docs/shader_validation.md, "`v_fma_mix*` f16 rounding in nearest mode"; the fix is `Gen.fma_mix_odd` in nearest mode too, SHADER-296). Nearest-mode `v_fma_mix*` still rounds twice (f32 `Fma`, then narrow): main's behaviour, unmeasured. `tools/fma_mix_probe.py --oracle hw` measures it on an AMD GPU, with seven inputs where the two rules differ by one f16 ulp (docs/shader_validation.md). The `v_add_f64` step needs f64 denormals preserved (not flushed) by the driver for subnormal sums. Shaders that never write MODE emit the same code as without this. Writes to other MODE bits (f32 rounding, denormals), directed rounding (+inf/-inf) and register-valued writes are refused, so nothing changes silently; none occur in the corpus. Denormal behaviour is still Vulkan's default. Format conversions in memory and texture units don't follow MODE. `v_mul_legacy_f32` now keeps the `0 × anything = 0` rule like `v_mad_legacy_f32` (GPU-checked with `runtime/test/shaders/ps_legacy_mul.asm` on AMD Radeon RX 9070 XT). \| b \| `, `FastTwoSum`: `bb = r - a`, `e = b - bb`) and steps back one ulp when the rounding error shows it rounded away from zero; finite overflow gives the largest finite value (unordered `TwoSum` `r - x` can overflow to `±inf` and yield `NaN` error for opposite-sign finite operands with ` \| x \| < \| y \| ` near `±DBL_MAX`, e.g. `0x7fdd9bb47daa1333 + 0xffefffffffffffff` found by `@Jolymmiles`; GPU-checked with `runtime/test/shaders/ps_f64_round.asm` on NVIDIA GeForce RTX 5060 Ti, 4096/4096 pixels exact). The `v_add_f64` output modifiers apply after that step and round to nearest, so an omod that overflows or lands on a subnormal is not toward zero. **omod versus denormal mode is unmodelled:** the translator applies `mul:2`/`mul:4`/`div:2` regardless of the MODE denormal fields (as before this change), whereas hardware ignores omod when denormals are kept (denorm fields = 3) and applies it when they are flushed (both measured on an RX 6800: `v_add_f64 (1 - 2^-60) mul:2` with denormals kept gave 3ff00000:00000000 nearest and 3fefffff:ffffffff toward zero, unscaled; mul:2 was applied with denormals flushed); the tests therefore claim no omod order. CPU-checked by `tests/test_mode_round.py` (the RX 6800 words for f16 add/sub, `v_fma_mix`, the transcendentals, f64 overflow). f16 add and sub (f16 operands) and `v_pk_add_f16` take the exact TwoSum error of the f32 result into account, so they are exact toward zero too (f32 then f16 rounding alone would be wrong: 2 - 2^-24 is an f32 tie that rounds up to 2.0); f16 FMAs need nothing extra, since their round-to-odd f32 value (SHADER-55) narrows exactly in either mode. `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, in both nearest-even and toward-zero modes (measured on AMD RDNA2 gfx1036 across 7 of 7 discriminating tie inputs with `tools/fma_mix_probe.py --oracle hw`, SHADER-135, finding 7079901079, and on an RX 6800 where toward zero gave 0x3fff for 1 * 2 - 2^-30 vs 0x4000 with double rounding; fixed for nearest mode in SHADER-296 / #1774; see docs/shader_validation.md, "`v_fma_mix*` f16 rounding in nearest mode"): `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, toward zero (an RX 6800 gave 0x3fff for 1 * 2 - 2^-30, where rounding to f32 first and then narrowing gives 0x4000): `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, in both nearest-even and toward-zero modes (measured on AMD RDNA2 gfx1036 and verified by `tools/fma_mix_probe.py`; finding 7079901079; toward zero an RX 6800 gave 0x3fff for 1 * 2 - 2^-30, where rounding to f32 first and then narrowing gives 0x4000): `Gen.fma_mix_odd` corrects the f32 `Fma` to round-to-odd by the sign of its exact residual (product error by `Fma(x, y, -x*y)`, TwoSum of the sum), which narrows exactly in either direction; the nearest-even path is unchanged (f32 `Fma`, then narrow). `fma_mix_odd` also handles a tiny product ( \| x*y \| < 2^-64: its error underflows or is flushed, so the residual sign is sign(x) xor sign(y), independent of the driver's denormal mode) and an f32 overflow with finite operands (toward zero gives ±FLT_MAX, so f16 ±65504). `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16`, `v_sin_f16`, `v_cos_f16`, `v_exp_f16` and `v_log_f16` ignore the rounding mode on hardware (RX 6800 for the first four, plus an exhaustive 65,536-input RNE vs RTZ sweep of all seven in wave32 and wave64 on native `gfx1036` via `tools/mode_round_probe.py`, SHADER-132: 0/65,536 inputs differ on every op; the same probe also confirmed all 17 f16/f64 RNE vs RTZ cases including `v_cvt_f16_f32`, `v_add/sub/mul/fma_f16`, `v_pk_add/fma_f16`, `v_fma_mix{lo,hi}_f16` and `v_add_f64` overflow saturation in both wave32 and wave64), so they always narrow to nearest even. In nearest mode the hardware rounds once as well: `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16`, `v_sin_f16`, `v_cos_f16`, `v_exp_f16` and `v_log_f16` ignore the rounding mode on hardware, so they always narrow to nearest even; all seven are measured (an RX 6700 XT gave the same words with FP_ROUND round-toward-zero and round-to-nearest on every input of each; see the f16 transcendentals row). `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16` and `v_sin_f16` ignore the rounding mode on hardware (RX 6800: the same words in every mode), so they always narrow to nearest even; `v_cos_f16`, `v_exp_f16` and `v_log_f16` are unmeasured, assumed like those four and treated the same. The "every VALU f16 result rounds toward zero" sentence above therefore excludes these seven; the f16 results of `v_floor/ceil/trunc/rndne/fract_f16` are exact and need no rounding. In nearest mode the translator still rounds `v_fma_mix{lo,hi}_f16` twice (f32 `Fma`, then narrow), but the hardware rounds once there as well: `tools/fma_mix_probe.py --oracle hw` on an RDNA2 iGPU (gfx1036, SHADER-135) gave the single-rounded word for all seven inputs where the two rules differ by one f16 ulp, so the translator, which rounded twice there (f32 `Fma`, then narrow) until #1774, was one f16 ulp off on exactly those ties (docs/shader_validation.md, "`v_fma_mix*` f16 rounding in nearest mode"; the fix is `Gen.fma_mix_odd` in nearest mode too, SHADER-296). Nearest-mode `v_fma_mix*` still rounds twice (f32 `Fma`, then narrow): main's behaviour, unmeasured. `tools/fma_mix_probe.py --oracle hw` measures it on an AMD GPU, with seven inputs where the two rules differ by one f16 ulp (docs/shader_validation.md). The `v_add_f64` step needs f64 denormals preserved (not flushed) by the driver for subnormal sums. Shaders that never write MODE emit the same code as without this. Writes to other MODE bits (f32 rounding, denormals), directed rounding (+inf/-inf) and register-valued writes are refused, so nothing changes silently; none occur in the corpus. Denormal behaviour is still Vulkan's default. Format conversions in memory and texture units don't follow MODE. `v_mul_legacy_f32` now keeps the `0 × anything = 0` rule like `v_mad_legacy_f32` (GPU-checked with `runtime/test/shaders/ps_legacy_mul.asm` on AMD Radeon RX 9070 XT). | | Denormal flush in `v_mad_f32`, `v_mac_f32`, `v_mad_legacy_f32` (SHADER-118) | The three have no f32 denormal support: a subnormal operand, the rounded product or the result reads as signed zero, whatever the MODE register says. `Gen.flush_f32` emits ` \| x \| < FLT_MIN → copysign(0, x)` on the three operands, after the product rounding and (via `Gen.flush_f32_mods`) both before and after `omod`/`clamp`; inf and NaN compare false and pass through, and 0 keeps its sign. Source: LLVM AMDGPU `SIISelLowering.cpp`, `SITargetLowering::isFMADLegal` (llvm-project `1922c0c`), which forms `v_mad_f32`/`v_mac_f32` only when f32 denormals are flushed. Corpus count with `tools/shader_profile.py` over the 26,503 gfx1013 shaders: `v_mad_f32` in 7,298 shaders (139,287 occurrences), `v_mac_f32` in 5,889 (276,806: 265,901 `_e32`, 10,811 `_e64`, 94 `_dpp`), `v_mad_legacy_f32` in 6,059 (24,765); 9,297 shaders (35.1%) use at least one, 440,858 occurrences (0.99% of the corpus's 44,406,870 instructions). **Measured natively on RDNA1** (`AMD Radeon RX 5600 XT`, `gfx1010`, Windows driver `32.0.21045.29003`, `tools/mad_denorm_probe.py --oracle hw`, SHADER-340): 48 of 48 cases match in wave32 and wave64 across `game` (`IEEE=0`, `denorm32=0`), `dx10_clamp=0` and `denorm32=3` (`v_mul_f32(FLT_MIN, 0.5)` confirms `denorm32=3` keeps subnormals on the GPU while the mad/mac ops still flush them), and all 40 non-`omod` cases match under `IEEE=1` (where hardware ignores `mul:2`/`mul:4`/`div:2` as for other f32 VALU ops). Before SHADER-340 the translator ran `flush_f32` only after `clamp_mods`, which gave `FLT_MIN` (`0x00800000`) instead of `+0` (`0x00000000`) on `(1.5*2^-126 - 2^-126) mul:2` (and `0x01000000` on `mul:4`), whereas hardware flushes the sum before `omod` (`+0`) as well as after (`FLT_MIN div:2` → `+0`, `-FLT_MIN div:2` → `-0`). Checked on the CPU by `tests/semantic/test_valu_f32_min3_max3_mad.py` (`DenormalFlushTests`: the flush column, pre- and post-`omod` cases, NaN/inf/zero pass-through, and a sabotaged pass-through that fails) and `tests/test_mad_denorm_probe.py`. No RDNA2 part has these opcodes, and on gfx103x the encodings of `v_mad_legacy_f32` (VOP3 0x140) and `v_mac_legacy_f32` (VOP2 0x06) are the fused `v_fma_legacy_f32` / `v_fmac_legacy_f32`, so a raw-encoding run on a gfx1036 oracle would measure a different instruction (see the GFX10.1/GFX10.3 opcode row). | -| 16-bit high-half reads (`Gen.u16_half` / `Gen.i16_half`, #1506) | Reading the high 16 bits of a 32-bit word emits `OpShiftRightLogical %uint u 16` (`u16_half`) or `OpShiftRightArithmetic %int (as_int(u)) 16` (`i16_half`) alone, without a trailing `OpBitwiseAnd ... 0xFFFF` or `OpBitFieldSExtract ... 0 16` (used for the low half only). On 32-bit inputs `>> 16` already zero- or sign-extends bits 31..16, and AMD's Windows LLPC compiler (measured on RDNA2, drivers 22.40.84.06 in #1506 and 24.10.24 on Ryzen 5 7600 iGPU) miscompiles both `(u >> 16) & 0xFFFF` and `OpBitFieldSExtract (u >> 16) 0 16` after two partial-half writes to `u` by dropping the `>> 16` when the result feeds `OpIAdd`, `OpIMul`, or `OpShiftLeftLogical` (e.g. `(0x41b1 << 1) & 0xFFFF` became `0x0000` instead of `0x8362` in `cs_f16fuzz_s2_163_w64`, `s_bitreplicate`'s `((0x41b1 << 8) \| 0x41b1) & 0x00ff00ff` became `0xb10000` instead of `0x4100b1`, and `SExtract(0x91b1138b >> 16, 0, 16) + 1` became `0x91b10001` instead of `0xffff91b2`). Applies across all 16-bit half readers (`v_*_b16`/`u16`/`i16`, `v_mad_{u,i}16`, `v_min3/max3/med3_{u,i}16`, `v_cvt_f16_{u,i}16`, `v_pack_b32_f16`, `v_frexp_*_f16`, `v_ldexp_f16`, `s_bitreplicate_b64_b32`, and `buffer_store_format_d16_*`). Checked by the unit tests in `tests/test_u16_high_half.py` and `tools/valu_fuzz.py --family f16 --seed 2 --programs 200 --wave both` on AMD Ryzen 5 7600 iGPU (driver 24.10.24: 400/400 native, up from 399/400; 200/200 wave64 emulated on both AMD and NVIDIA). **The packed 16-bit shifts follow the same rule** (`v_pk_lshlrev_b16`, `v_pk_lshrrev_b16`, `v_pk_ashrrev_i16`, since 2026-11-23): the shift amount comes from `OpShiftRightLogical %uint s0 16` then `& 15`, and the value from `OpShiftRight{Logical,Arithmetic} %uint s1 16`, where the code used `OpBitField{S,U}Extract … 16 16`. A field extract at offset 16 is what an AMD Windows driver 25.10.36 on a gfx1036 iGPU reads with the offset taken mod 16, so both result halves got the **low** half of the source: 5 of 2,000 `tools/valu_fuzz.py --family f16 --programs 2000 --seed 1 --wave 32` programs, all in wave32 and none in native wave64 (@Darkz0rz, reported in the coordination issue as SHADER-777). The same 2,000 programs match 2000/2000 on a second gfx1036 (Radeon iGPU of a Ryzen 7 7800X3D, driver 31.0.24002.92), where the field-extract form was already correct, and its SPIR-V does contain the offset-16 extracts, so the change is a lowering that survives both drivers, not a value change: `OpBitField{S,U}Extract(x, 16, 16)` equals `x >> 16` with the matching right shift and `OpBitFieldUExtract(x, 16, 4)` equals `(x >> 16) & 15`, checked for 200,010 inputs including 0, 1, 0xFFFF, 0x10000, 0x80000000, 0xFFFFFFFF, 0x7FFFFFFF and 0x8000. Counted over the 26,503 listings: 1 `v_pk_lshlrev_b16` in 1 compute listing (`op_sel_hi:[0,1]`) and 1 `v_pk_lshrrev_b16` in 1 other (`op_sel:[1,0] op_sel_hi:[0,0]`), no `v_pk_ashrrev_i16` and no `_sdwa` form; those two modules are the only ones whose output changes. Values are checked by the unit tests in `tests/test_pk16_diff.py` and the `ps_ops4` / `ps_ops6` fixtures. | +| 16-bit high-half reads (`Gen.u16_half` / `Gen.i16_half`, #1506) | Reading the high 16 bits of a 32-bit word emits `OpShiftRightLogical %uint u 16` (`u16_half`) or `OpShiftRightArithmetic %int (as_int(u)) 16` (`i16_half`) alone, without a trailing `OpBitwiseAnd ... 0xFFFF` or `OpBitFieldSExtract ... 0 16` (used for the low half only). On 32-bit inputs `>> 16` already zero- or sign-extends bits 31..16, and AMD's Windows LLPC compiler (measured on RDNA2, drivers 22.40.84.06 in #1506 and 24.10.24 on Ryzen 5 7600 iGPU) miscompiles both `(u >> 16) & 0xFFFF` and `OpBitFieldSExtract (u >> 16) 0 16` after two partial-half writes to `u` by dropping the `>> 16` when the result feeds `OpIAdd`, `OpIMul`, or `OpShiftLeftLogical` (e.g. `(0x41b1 << 1) & 0xFFFF` became `0x0000` instead of `0x8362` in `cs_f16fuzz_s2_163_w64`, `s_bitreplicate`'s `((0x41b1 << 8) \| 0x41b1) & 0x00ff00ff` became `0xb10000` instead of `0x4100b1`, and `SExtract(0x91b1138b >> 16, 0, 16) + 1` became `0x91b10001` instead of `0xffff91b2`). Applies across all 16-bit half readers (`v_*_b16`/`u16`/`i16`, `v_mad_{u,i}16`, `v_min3/max3/med3_{u,i}16`, `v_cvt_f16_{u,i}16`, `v_pack_b32_f16`, `v_frexp_*_f16`, `v_ldexp_f16`, `s_bitreplicate_b64_b32`, and `buffer_store_format_d16_*`). Checked by the unit tests in `tests/test_u16_high_half.py` and `tools/valu_fuzz.py --family f16 --seed 2 --programs 200 --wave both` on AMD Ryzen 5 7600 iGPU (driver 24.10.24: 400/400 native, up from 399/400; 200/200 wave64 emulated on both AMD and NVIDIA). **The packed 16-bit shifts follow the same rule** (`v_pk_lshlrev_b16`, `v_pk_lshrrev_b16`, `v_pk_ashrrev_i16`, since 2026-11-23): the shift amount comes from `OpShiftRightLogical %uint s0 16` then `& 15`, and the value from `OpShiftRight{Logical,Arithmetic} %uint s1 16`, where the code used `OpBitField{S,U}Extract … 16 16`. A field extract at offset 16 is what an AMD Windows driver 25.10.36 on a gfx1036 iGPU reads with the offset taken mod 16, so both result halves got the **low** half of the source: 5 of 2,000 `tools/valu_fuzz.py --family f16 --programs 2000 --seed 1 --wave 32` programs, all in wave32 and none in native wave64 (@Darkz0rz, reported in the coordination issue as SHADER-777). The same 2,000 programs match 2000/2000 on a second gfx1036 (Radeon iGPU of a Ryzen 7 7800X3D, driver 31.0.24002.92), where the field-extract form was already correct, and its SPIR-V does contain the offset-16 extracts, so the change is a lowering that survives both drivers, not a value change: `OpBitField{S,U}Extract(x, 16, 16)` equals `x >> 16` with the matching right shift and `OpBitFieldUExtract(x, 16, 4)` equals `(x >> 16) & 15`, checked for 200,010 inputs including 0, 1, 0xFFFF, 0x10000, 0x80000000, 0xFFFFFFFF, 0x7FFFFFFF and 0x8000. Counted over the 26,503 listings: 1 `v_pk_lshlrev_b16` in 1 compute listing (`op_sel_hi:[0,1]`) and 1 `v_pk_lshrrev_b16` in 1 other (`op_sel:[1,0] op_sel_hi:[0,0]`), no `v_pk_ashrrev_i16` and no `_sdwa` form; those two modules are the only ones whose output changes. Values are checked by the unit tests in `tests/test_pk16_diff.py` and the `ps_ops4` / `ps_ops6` fixtures. **All remaining 16-bit high-half readers follow the same rule (`SHADER-HIGH-HALF-SHARED-READERS`)**: `v_cmp(x)_*_{u16,i16}`, `sdwa_src` `WORD_1` (with and without `sext()`), `v_pk_{add,sub,mul_lo,mad,max,min}_{u16,i16}`, `v_qsad_pk_u16_u8`/`v_mqsad_pk_u16_u8`, `v_sad_u16`, `v_mad_{u32_u16,i32_i16}`, and `image_store d16` now route through `Gen.u16_half` / `Gen.i16_half` so no 16-bit half reader emits `OpBitField{S,U}Extract ... 16 16`. CPU-checked by `tests/semantic/test_high_half_shared_readers.py` (structural + `spirv_mini_interp` parity); not yet GPU-verified. | | `v_mac_legacy_f32` | The GFX10.1 VOP2 form of `v_mad_legacy_f32` with D as the addend: D = legacy(S0 * S1) + D, where 0 times anything (inf and NaN included) is +0, with the same denormal flush and VOP3 modifiers. D is read before it is written, as for `v_mac_f32` (LLVM `VOP2Instructions.td`: `V_MAC_LEGACY_F32` has `$src2` tied to `$vdst`). Until 2026-11-22 it raised `Unsupported`. CPU-checked by `MacLegacyF32Tests` in `tests/semantic/test_valu_f32_min3_max3_mad.py` (a 15x8x6 grid against the `v_mad_legacy_f32` reference, the zero rule, clamp/neg, D aliased as a source). **Not GPU-verified**: like the other mad opcodes it exists on gfx1010-1013 only, so no RDNA2 desktop part runs it. | | `v_cmp_*_f64`, `v_cmpx_*_f64` | All 16 binary64 vector compare predicates (`f`, `lt`, `eq`, `le`, `gt`, `lg`, `ge`, `o`, `u`, `nge`, `nlg`, `ngt`, `nle`, `neq`, `nlt`, `tru`) for both `v_cmp_` (VCC/SGPR lane mask) and `v_cmpx_` (EXEC narrowing), lowered in `Gen.compare_f64_cond` via pure 32-bit `%uint` IEEE-754 ordering (NaN detection, `-0.0` canonicalized to `+0.0`, sign-magnitude to monotonic unsigned 64-bit key) with no `Float64` capability required and no denormal flushing. Supports VGPR/SGPR pairs, `fimm`, sign-extended inline integers (`-16..64`), 32-bit upper-half literals, and VOP3 `abs`/`neg` sign-bit modifiers on both sources; inactive lanes write 0 for `v_cmp_*_f64` and stay inactive for `v_cmpx_*_f64`. Source: AMD RDNA2 ISA VOPC/VOP3 binary64 compares. CPU-checked by `tests/semantic/test_cmp_f64.py` (all 16 predicates across full IEEE-754 edge grid including subnormals/1-ULP pairs/±0/±inf/sNaN/qNaN, SGPR pairs, constants, `abs`/`neg`, `v_cmpx_*_f64`, inactive lanes, no `Float64` capability, bad-operand rejections). GPU-checked by `runtime/test/shaders/cs_w32_cmp_f64.asm`: all 16 predicates of both forms on 256 memory-fed pairs (the product of 16 values: ±inf, ±max, the 1-ULP neighbours of ±1, the smallest subnormals, ±0, the smallest normal, a NaN with its payload in the low dword only, a negative quiet NaN), `tru` with the odd threads off (an inactive lane gets VCC 0 and stays off through `v_cmpx_`), and `lt`/`nge` with `abs`/`neg`, all 1536 heap words exact on an RTX 4070 Ti (NVIDIA 620.70.06, Linux) and on llvmpipe (subgroup 8). That run checks the translated SPIR-V on a driver against IEEE-754, not RDNA2 itself; SGPR-pair and constant operands are not in it. Measured on native gfx1100 (single thread, 116 cases): all 16 predicates return IEEE-754 results (`eq` on `NaN` is 0 while `neq`/`nlt`/`nge`/`ngt` are 1, `lg` is 0 for `NaN` with `o`/`u` splitting on it, `eq(+0.0, -0.0)` is 1, `inf` compares equal to itself) and `v_cmpx_*_f64` narrows `EXEC` instead of writing `VCC`. | | Whole-quad mode (`s_wqm_b64` / `s_wqm_b32`) | A lane mask register holds only this lane's bit, so WQM on one (EXEC, VCC, an SGPR the mask analysis found) ORs the bit of the lane's quad, lanes 4n..4n+3 of the wave: two `OpGroupNonUniformQuadSwap` (horizontal, then vertical; capability `GroupNonUniformQuad`) in the default mode in fragment and compute shaders (quad operations are only guaranteed there; vertex, geometry and mesh shaders shuffle from the quad's four lanes), or the four lanes' values read through `%x_buf` under `--wave64-emulate` (no subgroup operation there). A quad never crosses lane 31/32, so the mask bits are exact per half on a 32-wide subgroup; SCC is a wave vote, so on wave64 it needs a 64-wide subgroup or `--wave64-emulate` (as every wave-wide mask op). The result goes to EXEC, VCC or an SGPR pair as a mask, SCC = the wave-wide any of it (same vote as the other mask ops). A 32-bit form in wave64 (`exec_lo`/`exec_hi`, `vcc_lo`/`vcc_hi`, a half-mask SGPR) writes only its own half (`exec_half_write`) and votes SCC over that half only (`cs_wqm_w64_half`). A source that is not a lane mask (a value loaded from memory, a literal) is data: `((x \| x>>1 \| x>>2 \| x>>3) & 0x11111111) * 15` per 32-bit word and SCC = result != 0, no subgroup operation. Assumptions: in compute and mesh shaders the subgroup lane is `LocalInvocationIndex` mod the subgroup size (as for every cross-lane op); a hardware quad is four consecutive lanes of a wave, and in a pixel shader Vulkan's quad (the 2x2 pixels, helper invocations included) is the same four lanes; GPU-checked on both AMD and NVIDIA with `ps_wqm.asm` (every 2x2 block of a 64x64 target, fully covered). **Helper lanes at a triangle edge, measured on RDNA2** (gfx1036, wave64, raw ISA through `tools/ps_oracle.py` on RADV; `tools/ps_helper_probe.py`, docs/shader_validation.md): a pixel wave's entry EXEC is exactly its covered pixels (helpers off); `s_wqm_b64 exec, exec` turns on exactly the quads with a covered pixel, which are packed from lane 0 (a quad with no covered pixel isn't in the wave); lane % 4 = (x & 1) + 2 (y & 1), so lanes 0-3 are top-left, top-right, bottom-left, bottom-right; a helper's `v_interp` gives its own pixel centre (extrapolated, as precisely as a covered pixel), and its v0/v1 hold its own I/J before `s_wqm` too; without `s_wqm` its VGPRs aren't written; an `exp ... vm` with helpers on in EXEC writes no pixel outside the triangle. Not covered: helper-invocation behaviour at triangle edges is untested, and in native mode an absent invocation in a partial quad (a compute group whose size is not a multiple of 4) gives an undefined value (emulated, the missing lanes of a partial wave read as 0). Before this the instruction was the identity, so helper lanes stayed off (#156 SHADER-34: `s_wqm_b64` appears in 4,285 pixel shaders). GPU-checked with `runtime/test/shaders/cs_wqm_w64.asm`, `cs_wqm_w64_half.asm`, `cs_wqm_w32.asm` and `ps_wqm.asm` on AMD Radeon 880M (subgroup 64) and NVIDIA GeForce RTX 5070 Laptop (subgroup 32; `cs_wqm_w64` there needs `LEONIDA_W64_EMULATE=1`), with and without `--wave64-emulate`. | diff --git a/tests/semantic/test_high_half_shared_readers.py b/tests/semantic/test_high_half_shared_readers.py new file mode 100644 index 0000000000..b8cc76c251 --- /dev/null +++ b/tests/semantic/test_high_half_shared_readers.py @@ -0,0 +1,223 @@ +"""Regression tests ensuring all 16-bit high-half readers use Gen.u16_half / Gen.i16_half. + +AMD Windows driver 25.10.36 (gfx1036) miscompiles `OpBitField{S,U}Extract ... 16 16` by +taking the offset mod 16 (reading the low half instead of the high half; docs/design.md +"16-bit high-half reads", #1506 / SHADER-777). Routing all remaining 16-bit half readers +through `Gen.u16_half` / `Gen.i16_half` eliminates every remaining offset-16 width-16 +field extract while keeping bit-exact semantics: + 1. `v_cmp_*_{u16,i16}` / `v_cmpx_*_{u16,i16}` (`op_sel` high half) + 2. `Gen.sdwa_src` `WORD_1` (unsigned and `sext()`) + 3. `v_pk_{add,sub,mul_lo,mad,max,min}_{u16,i16}` + 4. `v_qsad_pk_u16_u8` / `v_mqsad_pk_u16_u8` + 5. `v_sad_u16` + 6. `v_mad_u32_u16` / `v_mad_i32_i16` + 7. `image_store` with `d16` + + python -I tests/semantic/test_high_half_shared_readers.py +""" +import gc +import os +import re +import struct +import sys +import tempfile +import unittest +import warnings + +SEMANTIC_DIR = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(os.path.dirname(SEMANTIC_DIR)) +TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") +for _p in (TOOLS_DIR, SEMANTIC_DIR): + if _p not in sys.path: + sys.path.insert(0, _p) + +import rdna2spirv # noqa: E402 +import spirv_mini_interp as si # noqa: E402 + +STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" str: + with tempfile.TemporaryDirectory() as td: + os.mkdir(os.path.join(td, "disasm")) + src = os.path.join(td, "disasm", f"ps_{name}.s") + with open(src, "w", encoding="utf-8", newline="\n") as f: + f.write(f"; ps_{name}\n") + for ln in body_lines: + f.write(f"\t{ln}\n") + f.write("\ts_endpgm\n") + with open(os.path.join(td, f"ps_{name}.dxbc"), "wb") as f: + f.write(STUB_DXBC) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ResourceWarning) + spv = rdna2spirv.translate(src) + gc.collect() + return spv + + +def translate_cs(name: str, body_lines: list[str]) -> str: + with tempfile.TemporaryDirectory() as td: + os.mkdir(os.path.join(td, "disasm")) + os.mkdir(os.path.join(td, "fssm")) + src = os.path.join(td, "disasm", f"cs_{name}.s") + with open(src, "w", encoding="utf-8", newline="\n") as f: + f.write(f"; cs_{name}\n") + for ln in body_lines: + f.write(f"\t{ln}\n") + f.write("\ts_endpgm\n") + with open(os.path.join(td, f"cs_{name}.dxbc"), "wb") as f: + f.write(STUB_DXBC) + fssm = bytearray(0x148) + fssm[0:4] = b"FSSM" + struct.pack_into(" tuple[str, int]: + spv = translate_ps(name, body_lines + [f"exp mrt0 {out_reg}, {out_reg}, {out_reg}, {out_reg} done vm"]) + return spv, si.run_fragment(spv)["%out_mrt0"][0] + + +class HighHalfSharedReadersTests(unittest.TestCase): + def assertNoOffset16Extract(self, spv: str, label: str): + self.assertIsNone( + BAD_EXTRACT_16_16.search(spv), + f"{label} still emitted OpBitField{{S,U}}Extract at offset 16 width 16", + ) + + def test_vcmp_u16_and_i16_high_half(self): + # v1.hi = 0x9E00 (unsigned 40448, signed -25088), v1.lo = 0x0001 + # v2.hi = 0x41B1 (unsigned 16817, signed +16817), v2.lo = 0xFFFF + # Unsigned: v1.hi > v2.hi -> 1. Signed: v1.hi < v2.hi -> 1. + spv_u, got_u = run_ps_u32("vcmp_u16_hi", [ + "v_mov_b32 v1, 0x9e000001", + "v_mov_b32 v2, 0x41b1ffff", + "v_cmp_gt_u16_e64 vcc_lo, v1, v2 op_sel:[1,1]", + "v_cndmask_b32_e32 v0, 0, 1, vcc_lo", + ]) + self.assertNoOffset16Extract(spv_u, "v_cmp_gt_u16") + self.assertIn("OpShiftRightLogical %uint", spv_u) + self.assertEqual(got_u, 1) + + spv_i, got_i = run_ps_u32("vcmp_i16_hi", [ + "v_mov_b32 v1, 0x9e000001", + "v_mov_b32 v2, 0x41b1ffff", + "v_cmp_lt_i16_e64 vcc_lo, v1, v2 op_sel:[1,1]", + "v_cndmask_b32_e32 v0, 0, 1, vcc_lo", + ]) + self.assertNoOffset16Extract(spv_i, "v_cmp_lt_i16") + self.assertIn("OpShiftRightArithmetic %int", spv_i) + self.assertEqual(got_i, 1) + + def test_sdwa_word1_unsigned_and_sext(self): + # Unsigned WORD_1: 0x9E001234 -> 0x00009E00; sext(WORD_1): 0x9E001234 -> 0xFFFF9E00. + spv_u, got_u = run_ps_u32("sdwa_w1_u", [ + "v_mov_b32 v1, 0x9e001234", + "v_mov_b32_sdwa v0, v1 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_1", + ]) + self.assertNoOffset16Extract(spv_u, "sdwa WORD_1 unsigned") + self.assertIn("OpShiftRightLogical %uint", spv_u) + self.assertEqual(got_u, 0x00009E00) + + spv_s, got_s = run_ps_u32("sdwa_w1_s", [ + "v_mov_b32 v1, 0x9e001234", + "v_mov_b32_sdwa v0, sext(v1) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_1", + ]) + self.assertNoOffset16Extract(spv_s, "sdwa WORD_1 sext") + self.assertIn("OpShiftRightArithmetic %int", spv_s) + self.assertEqual(got_s, 0xFFFF9E00) + + def test_v_pk_u16_and_i16_ops(self): + # v1 = {0x9E00 (-25088), 0x0010 (16)}, v2 = {0x41B1 (16817), 0x0005 (5)}, v3 = {0x0003, 0x0002} + cases = [ + ("v_pk_add_u16", "v_pk_add_u16 v0, v1, v2", + (((0x9E00 + 0x41B1) & 0xFFFF) << 16) | ((0x0010 + 0x0005) & 0xFFFF)), + ("v_pk_sub_i16", "v_pk_sub_i16 v0, v1, v2 clamp", + (0x8000 << 16) | (16 - 5)), + ("v_pk_mul_lo_u16", "v_pk_mul_lo_u16 v0, v1, v2", + (((0x9E00 * 0x41B1) & 0xFFFF) << 16) | ((0x0010 * 0x0005) & 0xFFFF)), + ("v_pk_min_i16", "v_pk_min_i16 v0, v1, v2", + (0x9E00 << 16) | 0x0005), + ("v_pk_max_u16", "v_pk_max_u16 v0, v1, v2", + (0x9E00 << 16) | 0x0010), + ("v_pk_mad_i16", "v_pk_mad_i16 v0, v1, v3, v2", + ((((-25088 * 3) + 16817) & 0xFFFF) << 16) | (((16 * 2) + 5) & 0xFFFF)), + ] + for name, asm, expected in cases: + with self.subTest(op=name): + spv, got = run_ps_u32(name, [ + "v_mov_b32 v1, 0x9e000010", + "v_mov_b32 v2, 0x41b10005", + "v_mov_b32 v3, 0x00030002", + asm, + ]) + self.assertNoOffset16Extract(spv, name) + self.assertEqual(got, expected) + + def test_v_mad_u32_u16_and_i32_i16_high_half(self): + # v1.hi = 0xFFFE (-2 signed, 65534 unsigned), v2.hi = 0x0003, v3.hi = 0x0005 + spv_u, got_u = run_ps_u32("vmad_u32_u16", [ + "v_mov_b32 v1, 0xfffe0001", + "v_mov_b32 v2, 0x00030002", + "v_mov_b32 v3, 0x00050004", + "v_mad_u32_u16 v0, v1, v2, v3 op_sel:[1,1,1,0]", + ]) + self.assertNoOffset16Extract(spv_u, "v_mad_u32_u16") + self.assertEqual(got_u, 65534 * 3 + 5) + + spv_i, got_i = run_ps_u32("vmad_i32_i16", [ + "v_mov_b32 v1, 0xfffe0001", + "v_mov_b32 v2, 0x00030002", + "v_mov_b32 v3, 0x00050004", + "v_mad_i32_i16 v0, v1, v2, v3 op_sel:[1,1,1,0]", + ]) + self.assertNoOffset16Extract(spv_i, "v_mad_i32_i16") + self.assertIn("OpShiftRightArithmetic %int", spv_i) + self.assertEqual(got_i, (-2 * 3 + 5) & 0xFFFFFFFF) + + def test_v_sad_u16_and_qsad_pk_u16_u8(self): + # v_sad_u16: |0x1000 - 0x0500| + |0x0020 - 0x0005| + 0x100 = 0x0B00 + 0x001B + 0x0100 = 0x0C1B + spv_sad, got_sad = run_ps_u32("vsad_u16", [ + "v_mov_b32 v1, 0x10000020", + "v_mov_b32 v2, 0x05000005", + "v_mov_b32 v3, 0x00000100", + "v_sad_u16 v0, v1, v2, v3", + ]) + self.assertNoOffset16Extract(spv_sad, "v_sad_u16") + self.assertEqual(got_sad, 0x0C1B) + + # v_qsad_pk_u16_u8 with zero bytes in src0/src1 simply forwards the 4 packed 16-bit accumulators. + spv_qsad, got_qsad = run_ps_u32("vqsad_pk", [ + "v_mov_b32 v2, 0", + "v_mov_b32 v3, 0", + "v_mov_b32 v4, 0", + "v_mov_b32 v6, 0x12345678", + "v_mov_b32 v7, 0x9abcdef0", + "v_qsad_pk_u16_u8 v[0:1], v[2:3], v4, v[6:7]", + ], out_reg="v0") + self.assertNoOffset16Extract(spv_qsad, "v_qsad_pk_u16_u8") + self.assertEqual(got_qsad, 0x12345678) + + def test_image_store_d16_uses_shared_high_half_shifts(self): + spv = translate_cs("img_store_d16_hi", [ + "v_mov_b32 v0, 0x9e004000", + "v_mov_b32 v1, 0x80003c00", + "v_mov_b32 v2, 0", + "v_mov_b32 v3, 0", + "image_store v[0:1], v[2:3], s[0:7] dmask:0xf dim:SQ_RSRC_IMG_2D unorm d16", + ]) + self.assertNoOffset16Extract(spv, "image_store d16") + self.assertIn("OpShiftRightLogical %uint", spv) + self.assertIn("OpShiftRightArithmetic %int", spv) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 73df48ed8e..8666cab5ff 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -2116,13 +2116,10 @@ def compare(self, op, a, scalar, exec_only=False, mods=()): elif ty in ("u16", "i16"): sel, _ = self.opsel_bits(mods, 2) x, y = self.src_u(srcs[0]), self.src_u(srcs[1]) - xs, ys = self.tmp(), self.tmp() - f = "OpBitFieldSExtract" if ty == "i16" else "OpBitFieldUExtract" - self.emit(f"{xs} = {f} %uint {x} {self.cu(16 if sel[0] else 0)} {self.cu(16)}") - self.emit(f"{ys} = {f} %uint {y} {self.cu(16 if sel[1] else 0)} {self.cu(16)}") - x, y = xs, ys if ty == "i16": - x, y = self.as_int(x), self.as_int(y) + x, y = self.i16_half(x, sel[0]), self.i16_half(y, sel[1]) + else: + x, y = self.u16_half(x, sel[0]), self.u16_half(y, sel[1]) s = ty == "i16" ops = {"lt": "OpSLessThan" if s else "OpULessThan", "le": "OpSLessThanEqual" if s else "OpULessThanEqual", "gt": "OpSGreaterThan" if s else "OpUGreaterThan", @@ -7539,6 +7536,8 @@ def sdwa_src(self, v, a): off, width = self.SDWA_SEL[a["sdwa_sel"]] if width == 32: return v + if off == 16 and width == 16: + return self.as_uint(self.i16_half(v, 1)) if a.get("sext") else self.u16_half(v, 1) r = self.tmp() f = "OpBitFieldSExtract" if a.get("sext") else "OpBitFieldUExtract" self.emit(f"{r} = {f} %uint {v} {self.cu(off)} {self.cu(width)}") @@ -8167,7 +8166,7 @@ def _insn(self, ins): # rather than saturating to 0xFFFF, and max/min results are unchanged). neg_lo/neg_hi are float-only. # Constant operands are treated as 32-bit dwords: op_sel=0 selects bits [15:0], op_sel=1 selects [31:16] # (measured on gfx1036). Positive inlines zero-extend, negative inlines sign-extend, 32-bit literals - # retain their full dword; OpBitField*Extract at 16*sl[i] lowers this directly. + # retain their full dword; u16_half/i16_half lowers this without OpBitField{S,U}Extract at offset 16. def bits(name, default): m = next((m for m in mods if m.startswith(name + ":")), None) return [int(v) for v in m.split("[")[1].rstrip("]").split(",")] if m else default @@ -8181,14 +8180,10 @@ def bits(name, default): signed = op.endswith("i16") clamp = "clamp" in mods and kind in ("add", "sub", "mad") srcs = [self.src_u(t) for t in a[1:1 + ns]] - ext = "OpBitFieldSExtract" if signed else "OpBitFieldUExtract" halves = [] for sl in (sel, selhi): - v = [] - for i in range(ns): - e = self.tmp() - self.emit(f"{e} = {ext} %uint {srcs[i]} {self.cu(16 * sl[i])} {self.cu(16)}") - v.append(e) + v = [self.as_uint(self.i16_half(srcs[i], sl[i])) if signed else self.u16_half(srcs[i], sl[i]) + for i in range(ns)] r = self.tmp() if kind in ("add", "sub"): self.emit(f"{r} = {'OpIAdd' if kind == 'add' else 'OpISub'} %uint {v[0]} {v[1]}") @@ -9999,8 +9994,7 @@ def bits(name, default): self.emit(f"{t2} = OpShiftLeftLogical %uint {x_hi} {self.cu(32 - 8 * k)}") self.emit(f"{win} = OpBitwiseOr %uint {t1} {t2}") acc_w = c_lo if k < 2 else c_hi - total = self.tmp() - self.emit(f"{total} = OpBitFieldUExtract %uint {acc_w} {self.cu(16 * (k % 2))} {self.cu(16)}") + total = self.u16_half(acc_w, k % 2) for off in (0, 8, 16, 24): xb, yb, hi_, lo_, d, t = (self.tmp() for _ in range(6)) self.emit(f"{xb} = OpBitFieldUExtract %uint {win} {self.cu(off)} {self.cu(8)}") @@ -10041,6 +10035,8 @@ def bits(name, default): for off in range(0, 32, width): if width == 32: xa, ya = x, y + elif width == 16: + xa, ya = self.u16_half(x, off // 16), self.u16_half(y, off // 16) else: xa, ya = self.tmp(), self.tmp() self.emit(f"{xa} = OpBitFieldUExtract %uint {x} {self.cu(off)} {self.cu(width)}") @@ -12781,12 +12777,9 @@ def _emit(expr): # (u16) or [0x80000000, 0x7fffffff] (i16), before that shift. sel, dhi = self.opsel_bits(mods, 3) signed = op == "v_mad_i32_i16" - ext = "OpBitFieldSExtract" if signed else "OpBitFieldUExtract" - hs = [] - for i, src in enumerate(a[1:3]): - h = self.tmp() - self.emit(f"{h} = {ext} %uint {self.src_u(src)} {self.cu(16 * sel[i])} {self.cu(16)}") - hs.append(h) + hs = [self.as_uint(self.i16_half(self.src_u(src), sel[i])) if signed + else self.u16_half(self.src_u(src), sel[i]) + for i, src in enumerate(a[1:3])] c = self.src_u(a[3]) if sel[2]: c2 = self.tmp() @@ -14680,13 +14673,11 @@ def image_store(self, a, mods, dim): if (dmask >> c) & 1: ri, hi = pos >> 1, pos & 1 reg = d16_regs[ri] - fc, uc, sc = self.tmp(), self.tmp(), self.tmp() + fc = self.tmp() self.emit(f"{fc} = OpCompositeExtract %float {f_pairs[ri]} {hi}") - self.emit(f"{uc} = OpBitFieldUExtract %uint {reg} {self.cu(16 * hi)} {self.cu(16)}") - self.emit(f"{sc} = OpBitFieldSExtract %uint {reg} {self.cu(16 * hi)} {self.cu(16)}") fv.append(fc) - uv.append(uc) - sv.append(self.as_int(sc)) + uv.append(self.u16_half(reg, hi)) + sv.append(self.i16_half(reg, hi)) pos += 1 else: fv.append(self.tof(self.cu(0))) @@ -15273,6 +15264,11 @@ def as_int(self, u): self.emit(f"{i} = OpBitcast %int {u}") return i + def as_uint(self, i): + u = self.tmp() + self.emit(f"{u} = OpBitcast %uint {i}") + return u + # ---- legacy (merged ES/GS) geometry shader on LDS rings ---- # Inputs: input vertex i sits at the dword offset the system VGPRs give (v0 lo/hi, v1 lo); the entry sets them # to 64*i, so an LDS read at byte address A + offset is vertex A >> 8, dword ((offset/4) mod 64) = 4*reg + comp