"""Semantic interpreter tests for buffer_load_format_* (the V# FORMAT decode in tools/rdna2spirv.py). The element is read from PhysicalStorageBuffer memory at V#.base + offset. An element under 4 bytes starts at a byte shift inside its first dword, and the translation merges dword 1 above it: (w0 >> bsh) | (w1 << (32 - bsh)), picking w0 when bsh is 0. The interpreter rejects shifts of 32 or more (undefined in SPIR-V, even on the discarded side of an OpSelect), so every dword-aligned load here also checks that the merge keeps its shift below 32. Integer and f16 formats are used: their decode is exact, so the expected words need no rounding model. """ from __future__ import annotations import atexit import os import struct import sys import tempfile import unittest import warnings HERE = os.path.dirname(os.path.abspath(__file__)) ROOT = os.path.dirname(os.path.dirname(HERE)) TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") sys.dont_write_bytecode = True sys.path.insert(0, TOOLS_DIR) sys.path.insert(0, HERE) import rdna2spirv # noqa: E402 import spirv_mini_interp as si # noqa: E402 STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" tuple: """Return four MRT words for a formatted load. D16 packs two components per register. For a fixed-format load, pass its instruction name in op and its optional format modifier in mods.""" if _TMP_DIR is None: setUpModule() suffix = ("d16_" if d16 else "") + "xyzw"[:ncomp] nregs = (ncomp + 1) // 2 if d16 else ncomp vdata = "v2" if nregs == 1 else f"v[2:{1 + nregs}]" regs = [f"v{2 + min(i, nregs - 1)}" for i in range(4)] seed = "\tv_mov_b32 v2, 0x12345678\n\tv_mov_b32 v3, 0xa9bcdef0\n" if d16 else "" asm = ( "; test_buffer_load_format\n" f"\ts_mov_b32 s0, {BASE:#x}\n" "\ts_mov_b32 s1, 0\n" # base high bits 0, stride 0 (raw) "\ts_mov_b32 s2, 0x100\n" # num_records (bytes) f"\ts_mov_b32 s3, {fmt << 12 | dst_sel | 0x30000000:#x}\n" f"\tv_mov_b32 v1, {offset:#x}\n" f"{seed}" f"\t{op}_{suffix} {vdata}, v1, s[0:3], 0{mods} offen\n" "\ts_waitcnt vmcnt(0)\n" f"\texp mrt0 {', '.join(regs)} done vm\n" "\ts_endpgm\n" ) with open(_SRC_PATH, "w", encoding="utf-8") as f: f.write(asm) with warnings.catch_warnings(): warnings.simplefilter("ignore", ResourceWarning) spv = rdna2spirv.translate(_SRC_PATH) return si.run_fragment(spv, memory=dict(memory if memory is not None else MEMORY))["%out_mrt0"] def f32_bits(x: float) -> int: return struct.unpack(" int: return struct.unpack(" 1.0 and 0x00 -> 0.0, so the expected words are exact. """ MEM = {BASE: 0x112200FF} EXPLICIT = " format:[BUF_FMT_8_UNORM]" def tload(self, offset, ncomp, mods=""): return load_format(FMT_U32, offset, ncomp, memory=self.MEM, op="tbuffer_load_format", mods=mods) def test_x_unorm_endpoints_ignore_descriptor_format(self): for off, want in ((0, 0x3F800000), (1, 0)): with self.subTest(off=off): self.assertEqual(self.tload(off, 1)[0], want) def test_every_suffix_matches_explicit_8_unorm(self): for ncomp in (1, 2, 3, 4): with self.subTest(suffix="xyzw"[:ncomp]): got = self.tload(0, ncomp)[:ncomp] self.assertEqual(got[0], 0x3F800000) self.assertEqual(got, self.tload(0, ncomp, self.EXPLICIT)[:ncomp]) def test_packed_load_uses_instruction_format(self): # The V# declares one u32. The instruction specifies four u8s at byte 4: EF BE AD DE. expected = ((0x123400EF,), (0x00BE00EF,), (0x00BE00EF, 0xA9BC00AD), (0x00BE00EF, 0x00DE00AD)) for ncomp, want in enumerate(expected, 1): with self.subTest(ncomp=ncomp): got = load_format(FMT_U32, 4, ncomp, d16=True, op="tbuffer_load_format", mods=" format:[BUF_FMT_8_8_8_8_UINT]") self.assertEqual(got[:len(want)], want) def test_fixed_format_identity_ignores_descriptor_selectors(self): # Descriptor selectors are 0,0,0,1. MTBUF supplies its own X000, XY00 or XYZW. for fmt, source, want in (("32_UINT", 0x44, (0x44, 0, 0, 0)), ("16_16_UINT", 0x00330044, (0x44, 0x33, 0, 0)), ("8_8_8_8_UINT", 0x11223344, (0x44, 0x33, 0x22, 0x11))): for d16 in (False, True): with self.subTest(fmt=fmt, d16=d16): got = load_format(FMT_U32, 0, 4, dst_sel=1 << 9, memory={BASE: source}, d16=d16, op="tbuffer_load_format", mods=f" format:[BUF_FMT_{fmt}]") if d16: self.assertEqual(got[:2], (want[0] | want[1] << 16, want[2] | want[3] << 16)) else: self.assertEqual(got, want) self.assertEqual(load_format(FMT_UINT8X4, 0, 4, dst_sel=1 << 9), (0, 0, 0, 1)) def test_invalid_descriptor_suppresses_fixed_format_load(self): # Same address, 256-byte bound and instruction format. Only the V# FORMAT changes. cases = ((False, 4, (0x44, 0x33, 0x22, 0x11), (0, 0, 0, 0)), (True, 3, (0x00330044, 0xa9bc0022), (0, 0xa9bc0000))) for d16, n, bound, unbound in cases: for fmt, want in ((FMT_U32, bound), (0, unbound)): with self.subTest(d16=d16, fmt=fmt): got = load_format(fmt, 0, n, memory={BASE: 0x11223344}, d16=d16, op="tbuffer_load_format", mods=" format:[BUF_FMT_8_8_8_8_UINT]") self.assertEqual(got[:len(want)], want) def test_packed_default_8_unorm(self): # The first byte is 0xff: 1.0 in f16 is 0x3c00. Preserve the upper destination half. got = load_format(FMT_U32, 0, 1, memory=self.MEM, d16=True, op="tbuffer_load_format") self.assertEqual(got[0], 0x12343C00) def test_explicit_invalid_still_rejected(self): with self.assertRaises(rdna2spirv.Unsupported): self.tload(0, 1, " format:[BUF_FMT_INVALID]") class InterpreterConversions(unittest.TestCase): """The ops the format decode needs from spirv_mini_interp: integer to float and GLSL FMin/FMax.""" HEADER = ( "OpCapability Shader\n%glsl = OpExtInstImport \"GLSL.std.450\"\nOpMemoryModel Logical GLSL450\n" "OpEntryPoint Fragment %main \"main\" %out\n%void = OpTypeVoid\n%fn = OpTypeFunction %void\n" "%uint = OpTypeInt 32 0\n%float = OpTypeFloat 32\n%_ptr_Output_uint = OpTypePointer Output %uint\n" "%out = OpVariable %_ptr_Output_uint Output\n" ) def run_expr(self, consts, body): text = (self.HEADER + consts + "%main = OpFunction %void None %fn\n%entry = OpLabel\n" + body + "%bits = OpBitcast %uint %r\nOpStore %out %bits\nOpReturn\nOpFunctionEnd\n") return si.run_fragment(text)["%out"][0] def test_convert_u_and_s_to_f(self): consts = "%c = OpConstant %uint 4294967295\n" self.assertEqual(self.run_expr(consts, "%r = OpConvertUToF %float %c\n"), 0x4F800000) # 4294967296.0 self.assertEqual(self.run_expr(consts, "%r = OpConvertSToF %float %c\n"), 0xBF800000) # -1.0 def test_fmin_fmax(self): consts = "%a = OpConstant %float 1.5\n%b = OpConstant %float -2\n" self.assertEqual(self.run_expr(consts, "%r = OpExtInst %float %glsl FMax %a %b\n"), 0x3FC00000) self.assertEqual(self.run_expr(consts, "%r = OpExtInst %float %glsl FMin %a %b\n"), 0xC0000000) def test_fdiv_correctly_rounded(self): consts = "%a = OpConstant %float 3\n%b = OpConstant %float 255\n" self.assertEqual(self.run_expr(consts, "%r = OpFDiv %float %a %b\n"), 0x3C40C0C1) if __name__ == "__main__": unittest.main()