Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions docs/experiments/native-packed-minmax.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# Packed 16-bit min/max in direct DXIL

The native frontend lowers the six gfx1013 VOP3P forms
`v_pk_min/max_{i16,u16,f16}`. Each source supplies one halfword to each
result lane through `op_sel` and `op_sel_hi`. The instruction writes one
packed word and uses the existing vector write predicate. It accepts
numeric VGPRs and SGPRs, literal words and inline zero. It refuses
noncanonical unused source fields, negation and clamp.

Signed and unsigned integer lanes compare the selected 16-bit values.
Binary16 lanes compare the bit patterns using the startup HLSL
`minmax16_bits` contract. This preserves signed-zero ordering and
subnormal encodings and prefers the numeric operand over a NaN. Two NaNs
produce the repository's canonical quiet NaN, a payload convention that
still needs RDNA hardware evidence. A non-preserving or unproven binary16
denormal mode is refused.

The public shadPS4 packed-FP16 work helped identify this family as a
recompiler capability to check. The observation was made on 2026-11-27
at its merged commit `34b35b526e3bfbb8a6f22c11035cb051174ac6f1` under
GPL-2.0. The DXIL lowering and fixtures were written in Xbox2Windows.
[shadPS4 PR #4354](https://github.com/shadps4-emu/shadPS4/pull/4354)
[Pinned shadPS4 commit](https://github.com/shadps4-emu/shadPS4/commit/34b35b526e3bfbb8a6f22c11035cb051174ac6f1)

Instruction forms and half selectors follow AMD's public ISA and LLVM
21.1.0 syntax documentation. The LLVM revision observed on 2026-11-27
was `3623fe661ae35c6c80ac221f14d85be76aa870f1` (Apache-2.0 with the
LLVM exception). The existing HLSL path provides the Xbox2Windows
reference for the selected halves and floating-point edge behavior.
[AMD RDNA 2 ISA, §12.10](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf)
[LLVM 21.1.0 GFX1030 syntax](https://releases.llvm.org/21.1.0/docs/AMDGPU/AMDGPUAsmGFX1030.html#vop3p)
[LLVM licence](https://github.com/llvm/llvm-project/blob/3623fe661ae35c6c80ac221f14d85be76aa870f1/llvm/LICENSE.TXT)

```powershell
cmake --build --preset dev --target compile_dxil native_store_replay offscreen_check
ctest --preset dev --no-tests=error -j 1 -R '^native_packed_minmax_' -V
```

The synthetic Compute replays compare 2,064 words per type, including the
untouched words and guards. A sparse EXEC replay checks that inactive lanes
keep their previous word. Swapping the low and high selector groups changes
the binary16 readback. The Pixel fixture exports each resulting
halfword as an exactly representable binary32 integer and checks both
results. Compute replay requires shader model 6.6 and wave32.
64 changes: 61 additions & 3 deletions src/gfx1013_direct_compute.inl
Original file line number Diff line number Diff line change
Expand Up @@ -1754,6 +1754,59 @@ struct DirectCompute {
auto overflow = ir.binary("and", ir.binary("xor", a, sum), ir.binary("xor", b, sum));
return select(cmp("slt", overflow, "0"), select(cmp("slt", a, "0"), "2147483648", "2147483647"), sum);
}
bool packed_minmax(const Inst &i, const State &state) {
if (i.enc != Encoding::Mix)
return false;
const auto n = i.name;
const bool floating = n == "v_pk_min_f16" || n == "v_pk_max_f16";
const bool signed_int = n == "v_pk_min_i16" || n == "v_pk_max_i16";
if (!floating && !signed_int && n != "v_pk_min_u16" && n != "v_pk_max_u16")
return false;
// VOP3P NEG_HI/LO occupy the usual ABS/NEG fields. The third
// OP_SEL_HI bit is unused here, like the packed add and shift forms.
if (i.clamp || i.abs || i.neg || i.src[2] || (i.a & 0x2000))
refuse(i.pc, "unsupported packed 16-bit min/max encoding");
if (floating && (!half_mode_known || (mode_bits & 0xc0u) != 0xc0u))
refuse(i.pc, "unsupported packed binary16 min/max denormal mode");
auto source = [&](unsigned src) {
if (src <= 105) {
if (state[src].type == Symbol::Type::masked || state[src].type == Symbol::Type::uniform_mask)
refuse(i.pc, "packed 16-bit min/max uses a lane mask");
} else if (src < 256 && src != 128 && src != 255) {
refuse(i.pc, "unsupported packed 16-bit min/max source");
}
return operand32(i, src);
};
const auto a = source(i.src[0]), b = source(i.src[1]);
const bool maximum = n.substr(5, 3) == "max";
auto half = [&](const string &word, bool high) {
return high ? ir.binary("lshr", word, "16") : ir.binary("and", word, "65535");
};
auto order_key = [&](const string &bits) -> string {
if (floating) {
// Binary16 encodings are monotone within each sign. Reverse
// the negative half of that order and keep -0 below +0.
auto negative = cmp("uge", bits, "32768");
return ir.binary("xor", bits, select(negative, "65535", "32768"));
}
return signed_int ? ir.binary("xor", bits, "32768") : bits;
};
auto lane = [&](unsigned selectors) {
auto x = half(a, selectors & 1), y = half(b, selectors & 2);
auto result = select(cmp(maximum ? "ugt" : "ult", order_key(x), order_key(y)), x, y);
if (floating) {
// Follow the existing startup contract. One NaN selects
// the numeric side. Two NaNs use the canonical quiet NaN.
auto x_nan = cmp("ugt", ir.binary("and", x, "32767"), "31744");
auto y_nan = cmp("ugt", ir.binary("and", y, "32767"), "31744");
result = select(x_nan, select(y_nan, "32256", y), select(y_nan, x, result));
}
return result;
};
auto low = lane((i.a >> 11) & 3), high = lane((i.b >> 27) & 3);
vector_write(i.dst, ir.binary("or", low, ir.binary("shl", high, "16")));
return true;
}
void arithmetic(const Inst &i, const State &state, const string *permuted = nullptr, bool compute = false) {
auto n = i.name;
if (compute && (n == "v_dot4_i32_i8" || n == "v_dot4_u32_u8")) {
Expand Down Expand Up @@ -1960,7 +2013,7 @@ struct DirectCompute {
if (graphics_input) write(i.dst, {});
return;
}
if (float_alu(i, permuted))
if (packed_minmax(i, state) || float_alu(i, permuted))
return;
if (i.enc == Encoding::Vopc && !i.clamp && !i.scale &&
(n.find("class") == n.npos || n.find("_f16") != n.npos || n.find("_f32") != n.npos)) {
Expand Down Expand Up @@ -3128,8 +3181,13 @@ struct DirectCompute {
if (!p.reached[k])
continue;
const auto &op = p.code[k];
if (binary16_alu(op.name) || op.name == "v_cvt_f16_u16" || op.name == "v_cvt_f16_i16" ||
op.name == "v_cvt_u16_f16" || op.name == "v_cvt_i16_f16")
if (binary16_alu(op.name) ||
op.name == "v_pk_min_f16" ||
op.name == "v_pk_max_f16" ||
op.name == "v_cvt_f16_u16" ||
op.name == "v_cvt_f16_i16" ||
op.name == "v_cvt_u16_f16" ||
op.name == "v_cvt_i16_f16")
half_binary = true;
if (op.name == "s_round_mode" || op.name == "s_denorm_mode" || op.name == "s_setreg_b32" ||
op.name == "s_setreg_imm32_b32")
Expand Down
16 changes: 16 additions & 0 deletions tests/cmake/native_packed_minmax.cmake
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
if(TARGET compile_dxil AND TARGET native_store_replay AND TARGET offscreen_check AND
EXISTS "${INTAKE_PYTHON}" AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll")
set(checker "${CMAKE_SOURCE_DIR}/tests/native_packed_minmax_check.py")
add_test(NAME native_packed_minmax_controls COMMAND "${INTAKE_PYTHON}" -B
"${checker}" controls "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}")
set_tests_properties(native_packed_minmax_controls PROPERTIES TIMEOUT 60)
add_test(NAME native_packed_minmax_compute_hardware COMMAND "${INTAKE_PYTHON}" -B
"${checker}" compute "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}")
set_tests_properties(native_packed_minmax_compute_hardware PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77)
foreach(adapter IN ITEMS warp hardware)
add_test(NAME native_packed_minmax_pixel_${adapter} COMMAND "${INTAKE_PYTHON}" -B
"${checker}" pixel "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}" "$<TARGET_FILE:offscreen_check>" ${adapter})
set_tests_properties(native_packed_minmax_pixel_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77)
endforeach()
unset(checker)
endif()
198 changes: 198 additions & 0 deletions tests/native_packed_minmax_check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
"""Source-built direct DXIL checks for the six packed 16-bit min/max opcodes."""
import math
from pathlib import Path
import struct
import subprocess
import sys
import tempfile

from native_direct_container_check import patched_pixel
from native_dpp_mirror_check import vop2
from native_dpp_quad_check import request
from native_scalar_lds_check import sop1
from startup_image_3d_check import FULLSCREEN_VS, compile_hlsl

OPS = {'i16': (8, 7), 'u16': (13, 12), 'f16': (17, 18)}
CASES = (
(0x00008000, 0x80000000, 0, 3),
(0x8000FFFF, 0x7FFF0001, 1, 2),
(0x7E013C00, 0x4000FE00, 0, 3),
(0x7C010001, 0xFE7F8001, 0, 3),
(0xFC007C00, 0x7BFFFBFF, 3, 0),
(0x80010000, 0x00017C00, 2, 1),
(0xFFFF0000, 0x0000FFFF, 0, 3),
(0x4400C000, 0x3C003800, 1, 1),
(0x00000000, 0x00018000, 3, 2),
)
SENTINEL = 0x69696969
INACTIVE = 0x13579bdf
PROLOGUE = [0xBE940304, 0xBE950380, 0xF408080A, 0xFA000020, 0x8F078C05, 0x34100087, 0x4A101007, 0xBF8CC07F]


def packed(op, dst, lo, hi, *, first=257, second=258, bad=0):
return [0xCC004000 | op << 16 | lo << 11 | dst | bad, first | second << 9 | hi << 27]


def compute_program(kind, *, bad=0, swap=False, flush=False, sparse=False):
code = list(PROLOGUE)
if flush:
code.append(0xBFA50003) # s_denorm_mode: keep f32 denormals and flush f16
for slot, (a, b, lo, hi) in enumerate(CASES):
source = {1: 23, 2: 255, 8: 128}.get(slot, 257)
if source == 23:
code += [0xBE9703FF, a] # s_mov_b32 s23, literal
elif source == 257:
code += [0x7E0202FF, a]
code += [0x7E0402FF, b]
for j, op in enumerate(OPS[kind]):
if sparse:
code += [0x7E0802FF, INACTIVE, sop1(3, 126, 255), 0x55555555]
code += packed(op, 4, hi if swap else lo, lo if swap else hi, first=source, bad=bad)
if source == 255:
code.append(a)
if sparse:
code.append(sop1(3, 126, 193))
code += [0xE0701000 | (slot * 2 + j) * 4, 0x80080408]
return code + [0xBF810000]


def compile_compute(cli, sdk, work, root, kind, **options):
source = request(work, root, compute_program(kind, **options))
output = source.with_suffix('.cso')
run = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', source, output],
capture_output=True, text=True, timeout=30)
return output, run


def root_signature(sdk, work):
hlsl = work / 'root.hlsl'
hlsl.write_text('#define RS "DescriptorTable(UAV(u0,numDescriptors=8))"')
root = work / 'root.bin'
subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'RS', '-Fo', root, hlsl], check=True)
return root.read_bytes()


def controls(cli, sdk, work, root, baseline=False):
for kind in OPS:
_, run = compile_compute(cli, sdk, work, root, kind)
if baseline:
assert run.returncode, (kind, run.stdout)
print(kind, run.stderr.strip())
continue
assert run.returncode == 0, run.stdout + run.stderr
for bad in (1 << 15, 1 << 8, 1 << 13):
_, run = compile_compute(cli, sdk, work, root, kind, bad=bad)
assert run.returncode and 'packed 16-bit min/max encoding' in run.stderr, (kind, run.stderr)
if not baseline:
_, run = compile_compute(cli, sdk, work, root, 'f16', flush=True)
assert run.returncode and 'denormal mode' in run.stderr, run.stderr
print('six opcodes compiled; clamp, negation, noncanonical third selector and f16 flush mode refused')


def half_result(kind, maximum, a, b):
if kind == 'f16':
x, y = (struct.unpack('<e', struct.pack('<H', v))[0] for v in (a, b))
if math.isnan(x):
return 0x7e00 if math.isnan(y) else b
if math.isnan(y):
return a
if x == y == 0:
return a & b if maximum else a | b
elif kind == 'i16':
x, y = (struct.unpack('<h', struct.pack('<H', v))[0] for v in (a, b))
else:
x, y = a, b
return a if (x > y if maximum else x < y) else b


def expected(kind, case, maximum, *, swap=False):
a, b, lo, hi = case
halves = []
for select in (hi, lo) if swap else (lo, hi):
x, y = (a >> (16 * (select & 1))) & 0xffff, (b >> (16 * (select >> 1))) & 0xffff
halves.append(half_result(kind, maximum, x, y))
return halves[0] | halves[1] << 16


def compute_replay(replay, sdk, work, root, kind, **options):
source = request(work, root, compute_program(kind, **options))
output = work / 'readback.bin'
run = subprocess.run([replay, sdk, source, work / 'cache', '0', output, '--direct'])
if run.returncode == 77:
raise SystemExit(77)
run.check_returncode()
return struct.unpack('<2064I', output.read_bytes())


def expected_buffer(kind, *, swap=False, sparse=False):
lane_words = [expected(kind, case, maximum, swap=swap) for case in CASES for maximum in (False, True)]
unused = [SENTINEL] * (32 - len(lane_words))
inactive = [INACTIVE] * len(lane_words) if sparse else lane_words
pair = lane_words + unused + inactive + unused
return (SENTINEL,) * 8 + tuple(pair * 32) + (SENTINEL,) * 8


def draw_compute(replay, sdk, work, root):
for kind in OPS:
actual = compute_replay(replay, sdk, work, root, kind)
reference = expected_buffer(kind)
for index, (word, want) in enumerate(zip(actual, reference, strict=True)):
assert word == want, (kind, index, hex(word), hex(want))
print(f'{kind}: 2064 Compute readback words matched')
actual = compute_replay(replay, sdk, work, root, 'f16', swap=True)
assert actual == expected_buffer('f16', swap=True)
count = sum(a != b for a, b in zip(actual, expected_buffer('f16'), strict=True))
assert count > 0
print(f'Compute swapped selectors: {count} readback words differ from the original reference')
actual = compute_replay(replay, sdk, work, root, 'f16', sparse=True)
assert actual == expected_buffer('f16', sparse=True)
print('Compute sparse EXEC: inactive lanes kept their original packed word')


def pixel_program(kind, case):
a, b, lo, hi = case
code = [0x7E0202FF, a, 0x7E0402FF, b]
for j, op in enumerate(OPS[kind]):
src, low, high = 4 + j, 8 + 2 * j, 9 + 2 * j
code += packed(op, src, lo, hi)
code += [vop2(0x1b, low, 255, src), 65535, vop2(0x16, high, 144, src)]
# Each unsigned halfword is exactly representable as binary32, even
# if the packed result as a whole would encode a float NaN.
code += [0x7E000C00 | reg << 17 | (256 + reg) for reg in (low, high)]
return patched_pixel(len(code), code, export=(0xF800180F, 0x0B0A0908))


def draw_pixel(cli, sdk, renderer, adapter, work):
vs = compile_hlsl(str(Path(sdk) / 'dxc.exe'), 'dxc', FULLSCREEN_VS, 'fullscreen', 'vs_6_0', work)
for kind in OPS:
for index in (0, 1, 3, 7):
case = CASES[index]
shader = work / f'{kind}-{index}.ps'
shader.write_bytes(pixel_program(kind, case))
cso = shader.with_suffix('.cso')
build = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-container-ps', shader, cso],
capture_output=True, text=True, timeout=30)
assert build.returncode == 0, build.stdout + build.stderr
minimum, maximum = (expected(kind, case, flag) for flag in (False, True))
reference = work / 'expected.bin'
reference.write_bytes(struct.pack('<4f', minimum & 0xffff, minimum >> 16, maximum & 0xffff, maximum >> 16))
run = subprocess.run([renderer, adapter, '--startup-pixel-words', vs, cso, '1', '1', reference],
capture_output=True, text=True, timeout=30)
if run.returncode == 77:
raise SystemExit(77)
assert run.returncode == 0, (kind, index, run.stdout, run.stderr)
if 'debug_layer=enabled' in run.stdout:
assert 'debug_errors=0 debug_warnings=0' in run.stdout, run.stdout
print(f'{kind}: four Pixel cases matched for both packed results')


if __name__ == '__main__':
mode, tool, sdk, *args = sys.argv[1:]
with tempfile.TemporaryDirectory() as temp:
work = Path(temp)
if mode == 'pixel':
draw_pixel(tool, sdk, *args, work)
elif mode == 'compute':
draw_compute(tool, sdk, work, root_signature(sdk, work))
else:
controls(tool, sdk, work, root_signature(sdk, work), baseline=mode == 'baseline')
Loading