From 475a23255124a8850aaedb97df95f729a08ee4cf Mon Sep 17 00:00:00 2001 From: legacy-code-archaeologist <359844974+legacy-code-archaeologist@users.noreply.github.com> Date: Sat, 28 Nov 2026 07:20:58 +0100 Subject: [PATCH] shader: lower v_sin_f16 and v_cos_f16 in direct Compute DXIL Adds v_sin_f16 and v_cos_f16 to binary16_unary() and shares a DirectCompute::trig_turns() helper with v_sin_f32/v_cos_f32, rounding via packed_half_rne() while preserving D[31:16], -0.0 on v_sin_f16, exact quarter/half-turn zeros, and Inf/NaN -> 0x7e00. Fixes #3298. Refs #2935. AI-assisted. --- docs/experiments/native-sin-cos-f16.md | 32 +++ src/gfx1013_compute_native.cpp | 2 +- src/gfx1013_direct_compute.inl | 33 ++- tests/cmake/native_sin_cos_f16.cmake | 17 ++ tests/native_sin_cos_f16_check.py | 326 +++++++++++++++++++++++++ 5 files changed, 401 insertions(+), 9 deletions(-) create mode 100644 docs/experiments/native-sin-cos-f16.md create mode 100644 tests/cmake/native_sin_cos_f16.cmake create mode 100644 tests/native_sin_cos_f16_check.py diff --git a/docs/experiments/native-sin-cos-f16.md b/docs/experiments/native-sin-cos-f16.md new file mode 100644 index 0000000000..48e98824d5 --- /dev/null +++ b/docs/experiments/native-sin-cos-f16.md @@ -0,0 +1,32 @@ +# Binary16 VOP1/VOP3/SDWA `v_sin_f16` and `v_cos_f16` in direct Compute DXIL + +Issue #3298 (Refs #2935) lowers `v_sin_f16` (`0x60` / `0x1e0`) and `v_cos_f16` +(`0x61` / `0x1e1`) in the direct Compute DXIL translator via +`binary16_unary()` (`src/gfx1013_compute_native.cpp`) and `DirectCompute::trig_turns()` +/ `float_alu()` (`src/gfx1013_direct_compute.inl`). + +## Lowering & Semantics + +- Both instructions share `trig_turns()` with `v_sin_f32` and `v_cos_f32`, + reducing the widened binary32 angle in revolutions (`part = a - trunc(a)` with + signed zero preserved) before multiplying by `2 * pi`, and selecting exact + `+0.0` at exact quarter/half turns (`|part| == 0.5` for `v_sin_f16`; + `|part| == 0.25` or `0.75` for `v_cos_f16`) prior to `packed_half_rne()`. +- Special values on the modified binary16 source: + - `±Inf` and `NaN` (`|source| >= 0x7c00`) map to canonical quiet NaN (`0x7e00`). + - `v_sin_f16(-0.0)` (`0x8000`) preserves `-0.0` (`0x8000`); `v_cos_f16(±0.0)` + returns `+1.0` (`0x3c00`). +- Preserves destination high bits `D[31:16]` on VOP1/VOP3 and supports SDWA + subword selection/padding/preservation, `abs`/`neg`, SGPR/VGPR/literal, and + inline float/integer constants under the default binary16 RNE + keep-denormals + `MODE` contract. +- Refuses `clamp`, `omod`, high-half VOP3 `op_sel`, DPP16/DPP8 encodings, + non-default binary16 `MODE`, and SDWA high-half selection on inline constants. + +## Verification + +- [native_sin_cos_f16_check.py](../../tests/native_sin_cos_f16_check.py) checks + 34 cases (`VOP1`, `VOP3`, `SDWA`, `abs`/`neg`, inline/literal/SGPR/overlap, + `±0`, `±0.25`, `±0.5`, `±0.75`, `-1.75`, `2048.0`, `65504.0`, `±Inf`, `qNaN`, + `sNaN`, subnormals, general angles) and 8 negative refusal cases across `ir`, + `controls`, and `hardware` (`tests/cmake/native_sin_cos_f16.cmake`). diff --git a/src/gfx1013_compute_native.cpp b/src/gfx1013_compute_native.cpp index 4cab3d4508..dffbdb99b1 100644 --- a/src/gfx1013_compute_native.cpp +++ b/src/gfx1013_compute_native.cpp @@ -31,7 +31,7 @@ static bool binary16_alu(std::string_view name) { static bool binary16_unary(std::string_view name) { return name == "v_rcp_f16" || name == "v_sqrt_f16" || name == "v_exp_f16" || - name == "v_rsq_f16"; + name == "v_rsq_f16" || name == "v_sin_f16" || name == "v_cos_f16"; } [[noreturn]] void refuse(unsigned pc, const string &reason) { diff --git a/src/gfx1013_direct_compute.inl b/src/gfx1013_direct_compute.inl index d31110a5fe..5a644ea297 100644 --- a/src/gfx1013_direct_compute.inl +++ b/src/gfx1013_direct_compute.inl @@ -737,6 +737,21 @@ struct DirectCompute { string select_float(const string &condition, const string &yes, const string &no) { return ir.value("select i1 " + condition + ", float " + yes + ", float " + no); } + // Reduce an angle in turns before converting to radians, preserving signed + // zero and exact quarter-turn zeros (0.5 for sin; 0.25 and 0.75 for cos). + string trig_turns(bool cosine, const string &a) { + auto unary_f32 = [&](unsigned op, const string &v) { + return ir.invoke("float", "unary.f32", op, {{"float", v}}, "nounwind readnone"); + }; + auto part = ir.value("fsub float " + a + ", " + unary_f32(26, a)); + part = select_float(ir.value("fcmp oeq float " + a + ", 0.0"), a, part); + auto radians = ir.value("fmul float " + part + ", 0x401921FB60000000"); + auto mag_part = unary_f32(6, part); + auto exact = ir.value("fcmp oeq float " + mag_part + (cosine ? ", 0.25" : ", 0.5")); + if (cosine) + exact = ir.value("or i1 " + exact + ", " + ir.value("fcmp oeq float " + mag_part + ", 0.75")); + return select_float(exact, "0.0", unary_f32(cosine ? 12 : 13, radians)); + } // Invert the cube projection. Each pair of faces has a common major // axis, with the negative face second. The two minor axes span [-1,1]. std::array cube_axes(const string &face, const string &u, const string &v, bool tangent) { @@ -1899,9 +1914,12 @@ struct DirectCompute { const auto source = half_bits(0); auto a = widen(source); const bool rsq = n == "v_rsq_f16", exp = n == "v_exp_f16"; + const bool trig = n == "v_sin_f16" || n == "v_cos_f16"; string widened; if (n == "v_rcp_f16") { widened = ir.value("fdiv float 1.000000e+00, " + a); + } else if (trig) { + widened = trig_turns(n == "v_cos_f16", a); } else if (binary16_unary(n)) { const unsigned opcode = rsq ? 25 : exp ? 21 : 24; widened = ir.invoke("float", "unary.f32", opcode, {{"float", a}}, "nounwind readnone"); @@ -1932,6 +1950,12 @@ struct DirectCompute { rounded = select(cmp("eq", source, to_string(0xce40)), "0", rounded); const auto magnitude = ir.binary("and", source, "32767"); rounded = select(cmp("ugt", magnitude, "31744"), "32256", rounded); + } else if (trig) { + const auto magnitude = ir.binary("and", source, "32767"); + // Map +/-Inf and NaN to canonical quiet NaN; preserve -0.0 on v_sin_f16. + rounded = select(cmp("uge", magnitude, "31744"), "32256", rounded); + if (n == "v_sin_f16") + rounded = select(cmp("eq", source, "32768"), "32768", rounded); } // D[31:16] keeps its value: LLVM GCNSubtarget::zeroesHigh16BitsOfDest says // "On gfx10, all 16-bit instructions preserve the high bits", as v_cvt_f16_f32 above already does. @@ -2154,14 +2178,7 @@ struct DirectCompute { ir.value("fcmp oeq float " + b + ", 0.0")); result = select_float(zero, "0.0", ir.value("fmul float " + a + ", " + b)); } else if (n == "v_sin_f32" || n == "v_cos_f32") { - // Victory trig_turns: reduce in turns before converting to - // radians, preserving signed zero and exact quarter-turn zeros. - auto part = ir.value("fsub float " + a + ", " + unary(26, a)); - part = select_float(ir.value("fcmp oeq float " + a + ", 0.0"), a, part); - const bool cosine = n == "v_cos_f32"; - auto radians = ir.value("fmul float " + part + ", 0x401921FB60000000"); - auto exact = ir.value("fcmp oeq float " + unary(6, part) + (cosine ? ", 0.25" : ", 0.5")); - result = select_float(exact, "0.0", unary(cosine ? 12 : 13, radians)); + result = trig_turns(n == "v_cos_f32", a); } else if (cube) result = cube_alu(n, a, fp(1), fp(2)); else if (n == "v_add_f32" || n == "v_sub_f32" || n == "v_subrev_f32" || n == "v_mul_f32") { diff --git a/tests/cmake/native_sin_cos_f16.cmake b/tests/cmake/native_sin_cos_f16.cmake new file mode 100644 index 0000000000..8b3b774a29 --- /dev/null +++ b/tests/cmake/native_sin_cos_f16.cmake @@ -0,0 +1,17 @@ +if(EXISTS "${INTAKE_PYTHON}") + add_test(NAME native_sin_cos_f16_ir COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_sin_cos_f16_check.py" ir + "$") + set_tests_properties(native_sin_cos_f16_ir PROPERTIES TIMEOUT 60) +endif() +if(TARGET compile_dxil AND TARGET native_store_replay AND EXISTS "${INTAKE_PYTHON}" AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_sin_cos_f16_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_sin_cos_f16_check.py" controls + "$" "${DXC_BIN_DIR}") + set_tests_properties(native_sin_cos_f16_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_sin_cos_f16_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_sin_cos_f16_check.py" hardware + "$" "${DXC_BIN_DIR}") + set_tests_properties(native_sin_cos_f16_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) +endif() diff --git a/tests/native_sin_cos_f16_check.py b/tests/native_sin_cos_f16_check.py new file mode 100644 index 0000000000..39c8e00116 --- /dev/null +++ b/tests/native_sin_cos_f16_check.py @@ -0,0 +1,326 @@ +"""Binary16 VOP1/VOP3/SDWA v_sin_f16 and v_cos_f16 in direct Compute DXIL (#3298, Refs #2935).""" +from dataclasses import dataclass +import math +from pathlib import Path +import re +import struct +import subprocess +import sys +import tempfile + +import f16_packed_model as M +import native_f16_alu_check as F +from native_compute_clear_check import write_request +from native_sdwa_f16_check import ABS, NEG, PAD, PRESERVE, SCALAR, WORD_0, WORD_1, DWORD, OLD, sdwa + + +TRIG_OPS = {'sin': 0x60, 'cos': 0x61} +TWO_PI_F32 = struct.unpack('>d', bytes.fromhex('401921FB60000000'))[0] + + +def _f32_literal(token): + if token.startswith('0x'): + raw = token[2:].zfill(16) + return struct.unpack('d', bytes.fromhex(raw))[0]))[0] + return struct.unpack('= 0x7C00: + return 0x7E00 + if op == 'sin' and bits == 0x8000: + return 0x8000 + a = struct.unpack('= 193 else (self.inline_code - 128) & 0xFFFF + if self.encoding == 'sdwa': + sel = self.sdwa_src0 & 7 + picked = (self.src_val >> 16) if sel == WORD_1 else (self.src_val & 0xFFFF) + return F.modified(picked, bool(self.sdwa_src0 & ABS), bool(self.sdwa_src0 & NEG), 0) + return F.modified(self.src_val & 0xFFFF, self.abs_mask, self.neg, 0) + + def want(self): + return expected_trig_f16(self.op, self.source_half()) + + def emit(self): + opcode = TRIG_OPS[self.op] + if self.encoding == 'sdwa': + return (F.mov(1, self.src_val) + F.mov(3, OLD) + + sdwa(opcode, self.sdwa_dst, self.sdwa_unused, self.sdwa_src0, unary=True)) + if self.encoding == 'overlap': + return F.mov(3, F.HI_A | self.src_val) + F.vop1(opcode, 3, 259) + if self.encoding == 'literal': + return F.mov(3, F.HI_A) + F.vop1(opcode, 3, 255) + [self.src_val] + if self.encoding == 'sgpr': + return F.smov(8, F.HI_B | self.src_val) + F.mov(3, F.HI_A) + F.vop1(opcode, 3, 8) + if self.encoding in ('inline', 'inline_int'): + return F.mov(3, F.HI_A) + F.vop1(opcode, 3, self.inline_code) + if self.encoding == 'vop3': + return F.mov(1, F.HI_B | self.src_val) + F.mov(3, F.HI_A) + F.vop3( + opcode, 3, 257, 0, self.abs_mask, self.neg, unary=True) + return F.mov(1, F.HI_B | self.src_val) + F.mov(3, F.HI_A) + F.vop1(opcode, 3, 257) + + def matches(self, got, *, hardware=False): + want_h = self.want() + if self.encoding == 'sdwa': + shift = 16 if self.sdwa_dst == WORD_1 else 0 + mask = 0xFFFF << shift + other = OLD & ~mask if self.sdwa_unused == PRESERVE else 0 + if (got & ~mask) != other: + return False + got_h = (got & mask) >> shift + else: + if (got >> 16) != (F.HI_A >> 16): + return False + got_h = got & 0xFFFF + if not hardware or M.is_nan(want_h) or want_h in (0x0000, 0x8000, 0x3C00, 0xBC00): + return F.same_binary16(got_h, want_h) + return abs(M.h2f(got_h) - M.h2f(want_h)) <= 0.001 + + +def all_cases(): + cases = [ + # Exact specials & quarter/half turns across both VOP1 and VOP3. + Case('sin_pos_zero', 'sin', 'vop1', 0x0000), + Case('sin_neg_zero', 'sin', 'vop1', 0x8000), + Case('cos_pos_zero', 'cos', 'vop1', 0x0000), + Case('cos_neg_zero', 'cos', 'vop1', 0x8000), + Case('sin_qtr_pos', 'sin', 'vop1', 0x3400), # +0.25 -> +1.0 + Case('sin_qtr_neg', 'sin', 'vop1', 0xB400), # -0.25 -> -1.0 + Case('cos_qtr_pos', 'cos', 'vop1', 0x3400), # +0.25 -> +0.0 + Case('cos_qtr_neg', 'cos', 'vop1', 0xB400), # -0.25 -> +0.0 + Case('sin_half_pos', 'sin', 'vop1', 0x3800), # +0.5 -> +0.0 + Case('sin_half_neg', 'sin', 'vop1', 0xB800), # -0.5 -> +0.0 + Case('cos_half_pos', 'cos', 'vop1', 0x3800), # +0.5 -> -1.0 + Case('cos_half_neg', 'cos', 'vop1', 0xB800), # -0.5 -> -1.0 + Case('sin_3qtr_pos', 'sin', 'vop3', 0x3A00), # +0.75 -> -1.0 + Case('cos_3qtr_pos', 'cos', 'vop3', 0x3A00), # +0.75 -> +0.0 (kills drop 0.75) + Case('cos_3qtr_neg', 'cos', 'vop3', 0xBA00), # -0.75 -> +0.0 + Case('cos_1_75_neg', 'cos', 'vop1', 0xBF00), # -1.75 -> +0.0 + Case('sin_int_2048', 'sin', 'vop1', 0x6800), # 2048.0 -> +0.0 + Case('cos_max_norm', 'cos', 'vop1', 0x7BFF), # 65504.0 -> +1.0 + Case('sin_pos_inf', 'sin', 'vop1', 0x7C00), # +Inf -> NaN + Case('cos_neg_inf', 'cos', 'vop3', 0xFC00), # -Inf -> NaN + Case('sin_qnan', 'sin', 'vop1', 0x7E01), # NaN -> NaN + Case('cos_snan', 'cos', 'vop3', 0x7D02), # sNaN -> NaN + # General angles, modifiers (abs/neg), source kinds, overlap, and SDWA. + Case('sin_0125', 'sin', 'vop1', 0x3000), # 0.125 + Case('cos_0125_neg', 'cos', 'vop3', 0x3000, neg=1), + Case('sin_0375_abs', 'sin', 'vop3', 0xB600, abs_mask=1), + Case('cos_00625', 'cos', 'vop1', 0x2C00), # 0.0625 + Case('sin_subnormal', 'sin', 'vop1', 0x0001), + Case('cos_inline_f16', 'cos', 'inline', inline_code=240), # 0.5 -> -1.0 + Case('sin_inline_int', 'sin', 'inline_int', inline_code=193), # -1 -> +0.0 + Case('cos_literal', 'cos', 'literal', 0x12343800), # low half 0.5 -> -1.0 + Case('sin_sgpr', 'sin', 'sgpr', 0x3400), + Case('cos_overlap', 'cos', 'overlap', 0x3800), + Case('sin_sdwa_w1_pres', 'sin', 'sdwa', 0x34003800, sdwa_dst=WORD_1, sdwa_unused=PRESERVE, sdwa_src0=WORD_1), + Case('cos_sdwa_w0_pad', 'cos', 'sdwa', 0x34003800, sdwa_dst=WORD_0, sdwa_unused=PAD, sdwa_src0=DWORD | ABS), + ] + assert len(cases) < F.STRIDE + return cases + + +def program(cases): + code = F.preamble() + for slot, c in enumerate(cases): + code += c.emit() + F.store(slot * 4, 3) + return code + [0xBF810000] + + +def refusal_programs(): + return [ + (F.vop3(TRIG_OPS['sin'], 3, 257, 0, clamp=1, unary=True) + [0xBF810000], 'unsupported v_sin_f16 clamp or omod'), + (F.vop3(TRIG_OPS['cos'], 3, 257, 0, omod=1, unary=True) + [0xBF810000], 'unsupported v_cos_f16 clamp or omod'), + (F.vop3(TRIG_OPS['sin'], 3, 257, 0, opsel=1, unary=True) + [0xBF810000], 'unsupported v_sin_f16 high-half op_sel'), + (F.vop1(TRIG_OPS['cos'], 3, 250) + [0x010101B1, 0xBF810000], 'unsupported v_cos_f16 DPP form'), + (F.vop1(TRIG_OPS['sin'], 3, 233) + [0x01010101, 0xBF810000], 'unsupported v_sin_f16 DPP form'), + ([0xBFA40004] + F.vop1(TRIG_OPS['sin'], 3, 257) + [0xBF810000], 'unsupported binary16 rounding or denormal mode'), + ([0xBFA50000] + F.vop1(TRIG_OPS['cos'], 3, 257) + [0xBF810000], 'unsupported binary16 rounding or denormal mode'), + (sdwa(TRIG_OPS['sin'], WORD_0, PRESERVE, WORD_1 | SCALAR, reg0=242, unary=True) + [0xBF810000], + 'unsupported SDWA binary16 inline constant selection'), + ] + + +def _float_val(token, values): + if token.startswith('%'): + kind, bits = values[token] + assert kind == 'float', (token, kind) + return struct.unpack(' b) + else: + raise AssertionError(line) + values[m.group(1)] = ('i1', int(res)) + elif (m := re.fullmatch(r'(%\w+) = select i1 (\S+), float (\S+), float (\S+)', line)): + val = _float_val(m.group(3) if F._i1(m.group(2), values) else m.group(4), values) + values[m.group(1)] = ('float', _f32_bits(val)) + elif (m := re.fullmatch(r'(%\w+) = fmul float (\S+), (\S+)', line)): + res = _float_val(m.group(2), values) * _float_val(m.group(3), values) + values[m.group(1)] = ('float', _f32_bits(struct.unpack('