upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/tests
diff options
context:
space:
mode:
authorJan Trencansky <jan.trencansky@protonmail.com>2026-11-26 16:55:04 -0500
committerJan Trencansky <jan.trencansky@protonmail.com>2026-11-26 16:55:04 -0500
commitdf92abca8ee2a8f9093efea7fcaa4dadc3ddaebc (patch)
tree97ef8f95544fe263049d3f7360823f16100de209 /tests
parent49a0b69fcdb80db1f2a44ce7ca0ab8dfdec1e403 (diff)
parente5a7c8942678b323f655939c81f5d8855d20c248 (diff)
Merge main e5a7c8942 into shadow-aliased-guard (#1867)
One conflict, runtime/README.md: this branch rewrote the LEONIDA_SHADOW_ALIAS_MS row, main (#2163) added the LEONIDA_SHADOW_KEEP row after it. Both rows kept; the keep row's "aliased" now reads "aliased while they can't be guarded at every address", since aliased pages are no longer copied without a sign of a write. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'tests')
-rw-r--r--tests/conftest.py15
-rw-r--r--tests/semantic/fixtures/disasm/cs_address_guard.s35
-rw-r--r--tests/semantic/fixtures/disasm/cs_dpp_cmpx.s15
-rw-r--r--tests/semantic/fixtures/wave64_single_wave_barrier.asm22
-rw-r--r--tests/semantic/test_address_guard.py177
-rw-r--r--tests/semantic/test_dpp_compare.py152
-rw-r--r--tests/semantic/test_fma_mix_literal.py14
-rw-r--r--tests/semantic/test_library_compute_forms.py10
-rw-r--r--tests/semantic/test_loop_ballot_barrier.py21
-rw-r--r--tests/semantic/test_loop_iteration_guard.py9
-rw-r--r--tests/semantic/test_wave64_emulate_opt.py68
-rw-r--r--tests/semantic/test_wave64_halves.py20
-rw-r--r--tests/semantic/test_wave64_single_wave_barrier.py123
-rw-r--r--tests/test_dds_png_dx10.py109
-rw-r--r--tests/test_dstorage_history.py52
-rw-r--r--tests/test_indirect_clamp_telemetry.py5
-rw-r--r--tests/test_make_game_wave64.py70
-rw-r--r--tests/test_tex_export.py30
-rw-r--r--tests/test_tex_headers.py6
-rw-r--r--tests/test_translate.py22
20 files changed, 904 insertions, 71 deletions
diff --git a/tests/conftest.py b/tests/conftest.py
index 115282761..308590f67 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -156,6 +156,10 @@ KNOWN_VAL_ISSUES = {}
156# 0x8088 = 4 user SGPRs, TGID_X, 512 B of LDS; group 64x1x1 (the header the cs_* samples in runtime/test/shaders use). 156# 0x8088 = 4 user SGPRs, TGID_X, 512 B of LDS; group 64x1x1 (the header the cs_* samples in runtime/test/shaders use).
157DEFAULT_CS_HEADER = (0x8088, (64, 1, 1)) 157DEFAULT_CS_HEADER = (0x8088, (64, 1, 1))
158 158
159# The comment line a sample carries when llvm-mc cannot assemble it (cs_dpp_cmp.asm: a VOPC compare in DPP form).
160# scripts/run_gpu_tests.py has the same line; tests/test_translate.py checks that the two agree.
161TEXT_ONLY_MARK = "; run_gpu_tests: text only, llvm-mc has no gfx1013 encoding for an instruction here"
162
159 163
160class Shader: 164class Shader:
161 def __init__(self, workdir, name, asm, cs_header=DEFAULT_CS_HEADER, dxbc=EMPTY_DXBC): 165 def __init__(self, workdir, name, asm, cs_header=DEFAULT_CS_HEADER, dxbc=EMPTY_DXBC):
@@ -167,6 +171,15 @@ class Shader:
167 rsrc2, (lx, ly, lz) = cs_header 171 rsrc2, (lx, ly, lz) = cs_header
168 (workdir / "fssm").mkdir(exist_ok=True) 172 (workdir / "fssm").mkdir(exist_ok=True)
169 (workdir / "fssm" / f"{name}.fssm").write_bytes(bytes(0x138) + struct.pack("<4I", rsrc2, lx, ly, lz)) 173 (workdir / "fssm" / f"{name}.fssm").write_bytes(bytes(0x138) + struct.pack("<4I", rsrc2, lx, ly, lz))
174 self.path = disasm / f"{name}.s"
175 self.workdir = workdir
176 if any(ln.strip() == TEXT_ONLY_MARK for ln in asm.splitlines()):
177 # llvm-mc has no gfx1013 encoding for an instruction of this sample, so its text is the listing, as in
178 # assemble_to_s of scripts/run_gpu_tests.py: the translator reads straight-line code from the text alone.
179 lines = [f"; {name} code 0x0..0x0 (synthetic), gfx1013, 0 invalid words"]
180 lines += ["\t" + ln.strip() for ln in asm.splitlines() if ln.strip() and not ln.lstrip().startswith(";")]
181 self.path.write_text("\n".join(lines) + "\n", encoding="utf-8", newline="\n")
182 return
170 cmd = LLVM_MC + ["-triple=amdgcn--amdpal", "-mcpu=gfx1013"] 183 cmd = LLVM_MC + ["-triple=amdgcn--amdpal", "-mcpu=gfx1013"]
171 for ln in asm.splitlines(): 184 for ln in asm.splitlines():
172 s = ln.strip() 185 s = ln.strip()
@@ -181,9 +194,7 @@ class Shader:
181 cmd.append("-show-encoding") 194 cmd.append("-show-encoding")
182 r = subprocess.run(cmd, input=asm, capture_output=True, text=True) 195 r = subprocess.run(cmd, input=asm, capture_output=True, text=True)
183 assert r.returncode == 0, r.stderr 196 assert r.returncode == 0, r.stderr
184 self.path = disasm / f"{name}.s"
185 self.path.write_text(f"; {name} synthetic\n{r.stdout}") 197 self.path.write_text(f"; {name} synthetic\n{r.stdout}")
186 self.workdir = workdir
187 198
188 def translate(self): 199 def translate(self):
189 return rdna2spirv.translate(str(self.path)) 200 return rdna2spirv.translate(str(self.path))
diff --git a/tests/semantic/fixtures/disasm/cs_address_guard.s b/tests/semantic/fixtures/disasm/cs_address_guard.s
new file mode 100644
index 000000000..ad3c79be7
--- /dev/null
+++ b/tests/semantic/fixtures/disasm/cs_address_guard.s
@@ -0,0 +1,35 @@
1; cs_address_guard test fixture generated by tests/semantic/regen_fixtures.py from runtime/test/shaders/cs_address_guard.asm
2 v_mov_b32_e32 v0, 0x90000
3 v_mov_b32_e32 v1, 0
4 global_load_dword v2, v[0:1], off
5 v_mov_b32_e32 v0, 0xa0000
6 global_load_dword v3, v[0:1], off
7 v_mov_b32_e32 v4, 0x5707
8 global_store_dword v[0:1], v4, off offset:4
9 v_mov_b32_e32 v5, 1
10 global_atomic_add v5, v[0:1], v5, off offset:8 glc
11 v_mov_b32_e32 v0, 0x90ffc
12 global_load_dwordx2 v[6:7], v[0:1], off
13 s_mov_b32 s4, 0xa0000
14 s_mov_b32 s5, 0
15 s_mov_b32 s6, 0x100
16 s_mov_b32 s7, 0x31016fac
17 v_mov_b32_e32 v8, 0
18 buffer_load_dword v8, v8, s[4:7], 0 offen
19 s_mov_b32 s8, 0x90000
20 s_mov_b32 s9, 0
21 s_load_dword s10, s[8:9], 0x4
22 s_load_dword s11, s[4:5], 0x0
23 s_waitcnt vmcnt(0) lgkmcnt(0)
24 v_mov_b32_e32 v9, 0
25 buffer_store_dword v2, v9, s[0:3], 0 offen
26 buffer_store_dword v3, v9, s[0:3], 0 offen offset:4
27 buffer_store_dword v5, v9, s[0:3], 0 offen offset:8
28 buffer_store_dword v6, v9, s[0:3], 0 offen offset:12
29 buffer_store_dword v7, v9, s[0:3], 0 offen offset:16
30 buffer_store_dword v8, v9, s[0:3], 0 offen offset:20
31 v_mov_b32_e32 v10, s10
32 buffer_store_dword v10, v9, s[0:3], 0 offen offset:24
33 v_mov_b32_e32 v11, s11
34 buffer_store_dword v11, v9, s[0:3], 0 offen offset:28
35 s_endpgm
diff --git a/tests/semantic/fixtures/disasm/cs_dpp_cmpx.s b/tests/semantic/fixtures/disasm/cs_dpp_cmpx.s
new file mode 100644
index 000000000..90172ddfa
--- /dev/null
+++ b/tests/semantic/fixtures/disasm/cs_dpp_cmpx.s
@@ -0,0 +1,15 @@
1; cs_dpp_cmpx test fixture generated by tests/semantic/regen_fixtures.py from runtime/test/shaders/cs_dpp_cmpx.asm
2 v_mbcnt_lo_u32_b32 v0, -1, 0
3 v_add_nc_u32 v7, -4, v0
4 v_cvt_f32_i32 v1, v7
5 v_mov_b32 v6, 0
6 s_mov_b32 s10, exec_lo
7 v_cmpx_gt_f32_dpp v1, v1 quad_perm:[2,3,0,1] row_mask:0xf bank_mask:0xf bound_ctrl:1 fi:1
8 v_mov_b32 v6, 1
9 s_mov_b32 exec_lo, s10
10 v_cmpx_gt_f32_dpp v1, -v1 quad_perm:[2,3,0,1] row_mask:0xf bank_mask:0xf bound_ctrl:1 fi:1
11 v_add_nc_u32 v6, 2, v6
12 s_mov_b32 exec_lo, s10
13 v_lshlrev_b32 v2, 2, v0
14 buffer_store_dword v6, v2, s[0:3], 0 offen
15 s_endpgm
diff --git a/tests/semantic/fixtures/wave64_single_wave_barrier.asm b/tests/semantic/fixtures/wave64_single_wave_barrier.asm
new file mode 100644
index 000000000..ffbb6aba2
--- /dev/null
+++ b/tests/semantic/fixtures/wave64_single_wave_barrier.asm
@@ -0,0 +1,22 @@
1; One wave64 workgroup: a uniform loop and a uniform branch, each with a read of another wave32 half's lane, which
2; the emulation exchanges through %x_buf behind a workgroup barrier. s4 is a push constant: 0 skips the branch.
3v_lshlrev_b32_e32 v2, 2, v0
4v_mov_b32_e32 v1, v0
5s_mov_b32 s8, 0
6s_mov_b32 s9, 0
7again:
8v_add_nc_u32_e32 v1, 1, v1
9v_readlane_b32 s10, v1, 40
10s_add_u32 s9, s9, s10
11s_add_u32 s8, s8, 1
12s_cmp_eq_u32 s8, 3
13s_cbranch_scc0 again
14s_cmp_eq_u32 s4, 0
15s_cbranch_scc1 done
16v_add_nc_u32_e32 v1, 100, v1
17v_readlane_b32 s11, v1, 41
18s_add_u32 s9, s9, s11
19done:
20v_mov_b32_e32 v3, s9
21buffer_store_dword v3, v2, s[0:3], 0 offen
22s_endpgm
diff --git a/tests/semantic/test_address_guard.py b/tests/semantic/test_address_guard.py
new file mode 100644
index 000000000..e503ed732
--- /dev/null
+++ b/tests/semantic/test_address_guard.py
@@ -0,0 +1,177 @@
1"""rdna2spirv.py --address-guard: every heap_base + VA access is checked against the runtime's page table.
2
3Standard library only; no GPU, no LLVM, no game files.
4
5docs/d3d12_vulkan.md, "Address guard": an access whose first and last byte are below the header's limit (the arena)
6passes on a compare; any other passes only when the page table (tools/address_guard.py, runtime/src/address_guard.h)
7backs the 4 KiB pages of both. A refused load reads the zero area, a refused store or atomic writes the dump area
8and an atomic returns 0; each refusal adds 1 to the header's count and writes its offset. Without the header's magic
9(the runtime's guard off) every access passes. Without --address-guard the module is what it was.
10
11cs_address_guard (runtime/test/shaders/cs_address_guard.asm, header: the expected words) runs here on the heap
12scripts/run_address_guard_gpu_test.py gives it on the GPU, through spirv_mini_interp, with the guard on and off.
13"""
14import os
15import re
16import struct
17import sys
18import unittest
19
20HERE = os.path.dirname(os.path.abspath(__file__))
21if HERE not in sys.path:
22 sys.path.insert(0, HERE) # python -I leaves the script's folder off sys.path
23
24import support # noqa: E402 (support puts tools/ on sys.path, honouring LEONIDA_TOOLS_DIR)
25import spirv_mini_interp as si # noqa: E402
26import rdna2spirv # noqa: E402
27import address_guard as ag # noqa: E402
28
29ROOT = os.path.dirname(os.path.dirname(HERE))
30SCRIPTS = os.path.join(ROOT, "scripts")
31if SCRIPTS not in sys.path:
32 sys.path.insert(0, SCRIPTS)
33import run_address_guard_gpu_test as gpu # noqa: E402 (the heap and the expected words, shared with the GPU run)
34
35# build.py's compute header for "; group: 1,1,1" and "; rsrc2: 0x8090": 8 user SGPRs, one thread.
36FSSM = bytearray(0x148)
37struct.pack_into("<4I", FSSM, 0x138, 0x8090, 1, 1, 1)
38FSSM = bytes(FSSM)
39VSHARP = [0, 0, 0x100, 0x31016FAC] # out[]: base 0, 0x100 bytes, raw bounds
40
41
42def translate(name="cs_address_guard", guard=True, lines=None):
43 saved = rdna2spirv.ADDRESS_GUARD
44 rdna2spirv.ADDRESS_GUARD = guard
45 try:
46 if lines is not None:
47 return support.translate_lines(name, lines, fssm=FSSM)
48 return support.translate_fixture(name, fssm=FSSM)
49 finally:
50 rdna2spirv.ADDRESS_GUARD = saved
51
52
53def run(spv, heap):
54 """Run one invocation on a copy of `heap` (heap_base 0, so a host address is the heap offset)."""
55 mem = {i * 4: w for i, w in enumerate(struct.unpack(f"<{len(heap) // 4}I", heap)) if w}
56 si.run_workgroup(spv, 1, 32, inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i},
57 push_constants=VSHARP + [0] * 32, memory=mem)
58 return mem
59
60
61class GuardedFixture(unittest.TestCase):
62 @classmethod
63 def setUpClass(cls):
64 cls.spv = translate()
65
66 def test_guard_on(self):
67 mem = run(self.spv, gpu.heap(True))
68 self.assertEqual([mem.get(4 * k, 0) for k in range(8)], gpu.EXPECTED_ON)
69 for at, want in gpu.MEMORY_ON.items():
70 with self.subTest(at=hex(at)):
71 self.assertEqual(mem.get(at, 0), want)
72
73 def test_guard_off_at_run_time(self):
74 """The same module on a heap without the magic: every access goes where it points."""
75 mem = run(self.spv, gpu.heap(False))
76 self.assertEqual([mem.get(4 * k, 0) for k in range(8)], gpu.EXPECTED_OFF)
77 for at, want in gpu.MEMORY_OFF.items():
78 with self.subTest(at=hex(at)):
79 self.assertEqual(mem.get(at, 0), want)
80
81 def test_unguarded_module(self):
82 """Without --address-guard nothing reads the header, and the program behaves as with the guard off."""
83 spv = translate(guard=False)
84 self.assertNotIn("guard", spv)
85 mem = run(spv, gpu.heap(True))
86 self.assertEqual([mem.get(4 * k, 0) for k in range(8)], gpu.EXPECTED_OFF)
87
88 def test_every_access_is_guarded(self):
89 """Each PhysicalStorageBuffer pointer of %main comes from a %guard_fn call, except the header read itself."""
90 main = re.search(r"%main = OpFunction .*?OpFunctionEnd", self.spv, re.S).group(0)
91 calls = set(re.findall(r"(%\S+) = OpFunctionCall %ulong %guard_fn", main))
92 sources = re.findall(r"= OpConvertUToPtr %_ptr_PSB_\w+ (%\S+)", main)
93 self.assertEqual(sources.count("%gd_hp"), 1)
94 others = [s for s in sources if s != "%gd_hp"]
95 # 2 global loads, the store, the atomic, the x2 load, the buffer load, 2 s_loads and the 8 stores to out[]
96 self.assertEqual(len(others), 16)
97 self.assertTrue(set(others) <= calls, set(others) - calls)
98
99
100class GuardForms(unittest.TestCase):
101 """The kind and span each instruction family passes, read off the %guard_fn calls (sink, last-byte delta)."""
102
103 def calls(self, lines):
104 spv = translate("cs_guard_forms", lines=lines + ["s_endpgm"])
105 consts = {m.group(1): int(m.group(2)) for m in re.finditer(r"(%\S+) = OpConstant %ulong (\d+)", spv)}
106 out = []
107 for m in re.finditer(r"OpFunctionCall %ulong %guard_fn %heap_base %gd_on %gd_limit %gd_table \S+ (\S+) (\S+)",
108 spv):
109 out.append((consts.get(m.group(1), m.group(1)), consts[m.group(2)]))
110 return out
111
112 def test_loads_read_the_zero_area(self):
113 self.assertEqual(self.calls(["global_load_dwordx4 v[2:5], v[0:1], off"]), [(15, ag.ZERO)])
114 self.assertEqual(self.calls(["s_load_dwordx8 s[8:15], s[0:1], 0x0"]), [(31, ag.ZERO)])
115 self.assertEqual(self.calls(["global_load_ubyte v2, v[0:1], off"]), [(3, ag.ZERO)])
116
117 def test_stores_and_atomics_write_the_dump_area(self):
118 self.assertEqual(self.calls(["global_store_dwordx3 v[0:1], v[2:4], off"]), [(11, ag.DUMP)])
119 self.assertEqual(self.calls(["global_atomic_or_x2 v[0:1], v[2:3], off"]), [(7, ag.DUMP)])
120 self.assertEqual(self.calls(["buffer_atomic_add v2, v1, s[0:3], 0 offen glc"]), [(3, ag.DUMP)])
121 # a byte store merges into its dword with atomic and/or: one guarded dword
122 self.assertEqual(self.calls(["global_store_byte v[0:1], v2, off"]), [(3, ag.DUMP)])
123
124 def test_atomic_result_is_zero_when_refused(self):
125 spv = translate("cs_guard_atomic", lines=["global_atomic_add v5, v[0:1], v5, off glc", "s_endpgm"])
126 call = re.search(r"(%\S+) = OpFunctionCall %ulong %guard_fn", spv).group(1)
127 ok = re.search(rf"(%\S+) = OpIEqual %bool {re.escape(call)} ", spv)
128 self.assertIsNotNone(ok)
129 self.assertRegex(spv, rf"= OpSelect %uint {re.escape(ok.group(1))} %\S+ %c0\b")
130
131
132class TableModel(unittest.TestCase):
133 """tools/address_guard.py, the Python reference of the table the runtime writes."""
134
135 def test_pages_and_chunks(self):
136 words = ag.table_words([(0x90000, 0x90001), (0x5_0000_1000, 0x5_0000_3000), (-0x2000 & ag.MASK48, 0)])
137 self.assertTrue(ag.passes(words, 0x80000, 0x90000, 4))
138 self.assertTrue(ag.passes(words, 0x80000, 0x90ffc, 4))
139 self.assertFalse(ag.passes(words, 0x80000, 0x90ffc, 8)) # the last byte is on the next page
140 self.assertTrue(ag.passes(words, 0x80000, 0x5_0000_2ff0, 16))
141 self.assertFalse(ag.passes(words, 0x80000, 0x5_0000_3000, 4))
142 self.assertFalse(ag.passes(words, 0x80000, 0x6_0000_0000, 4)) # another chunk, nothing backed
143 self.assertTrue(ag.passes(words, 0x80000, 0x7fffc, 4)) # the arena, no lookup
144 self.assertFalse(ag.passes(words, 0x80000, 0x7fffc, 8)) # past the arena, page 0x80 unbacked
145
146 def test_negative_offsets(self):
147 """A buffer below the arena (LEONIDA_IMPORT_BELOW_ARENA=1): its 48-bit offset, sign-extended."""
148 words = ag.table_words([((-0x2000) & ag.MASK48, (-0x1000) & ag.MASK48)])
149 self.assertTrue(ag.passes(words, 0x80000, (-0x2000) & ag.MASK48, 4))
150 self.assertFalse(ag.passes(words, 0x80000, (-0x1000) & ag.MASK48, 4))
151 self.assertFalse(ag.passes(words, 0x80000, (-4) & ag.MASK48, 8)) # wraps through 0: not the arena
152
153 def test_full_block_when_out_of_room(self):
154 words = ag.table_words([(1 << 32, (1 << 32) + 1), (2 << 32, (2 << 32) + 1)], max_blocks=1)
155 self.assertTrue(ag.passes(words, 0x80000, 1 << 32, 4))
156 self.assertFalse(ag.passes(words, 0x80000, (1 << 32) + 0x1000, 4))
157 self.assertTrue(ag.passes(words, 0x80000, (2 << 32) + 0x5000, 4)) # the full block: all of chunk 2
158
159 def test_constants_match_the_translator_and_the_runtime(self):
160 self.assertEqual((rdna2spirv.GUARD_HEADER, rdna2spirv.GUARD_ZERO, rdna2spirv.GUARD_DUMP, rdna2spirv.GUARD_MAGIC,
161 rdna2spirv.GUARD_L1, rdna2spirv.GUARD_BLOCK_WORDS),
162 (ag.HEADER, ag.ZERO, ag.DUMP, ag.MAGIC, ag.L1, ag.BLOCK_WORDS))
163 with open(os.path.join(ROOT, "runtime", "src", "address_guard.h"), encoding="utf-8") as f:
164 text = f.read()
165 for name, value in (("kGuardHeader", ag.HEADER), ("kGuardZero", ag.ZERO), ("kGuardDump", ag.DUMP),
166 ("kGuardEnd", ag.RESERVED_END), ("kGuardLevel1", ag.L1),
167 ("kGuardBlockWords", ag.BLOCK_WORDS)):
168 with self.subTest(name=name):
169 m = re.search(rf"{name} = (1u << \d+|0x[0-9a-fA-F]+|\d+)", text)
170 self.assertIsNotNone(m)
171 v = m.group(1)
172 self.assertEqual(1 << int(v.split("<<")[1]) if "<<" in v else int(v, 0), value)
173 self.assertIn('"LGUARD01"', text)
174
175
176if __name__ == "__main__":
177 unittest.main()
diff --git a/tests/semantic/test_dpp_compare.py b/tests/semantic/test_dpp_compare.py
index c6f429fb5..46cdc0b3e 100644
--- a/tests/semantic/test_dpp_compare.py
+++ b/tests/semantic/test_dpp_compare.py
@@ -9,6 +9,9 @@ own src1), with 0 for src0 when the selected lane is out of its row or inactive.
9writes are translated: all rows and banks enabled and either `bound_ctrl:1` or DPP8. A form that leaves a lane 9writes are translated: all rows and banks enabled and either `bound_ctrl:1` or DPP8. A form that leaves a lane
10unwritten is refused, because what that lane's mask bit becomes is not measured. 10unwritten is refused, because what that lane's mask bit becomes is not measured.
11 11
12`v_cmpx` in DPP form (SHADER-VOPCX-DPP) takes the same forms and writes EXEC instead of VCC. 78 pipeline-library
13pixel shaders of 1.0.2.1 hold it, all as `v_cmpx_gt_f32_dpp vN, -vM quad_perm:[2,3,0,1] ... bound_ctrl:1 fi:1`.
14
12The values come from running the translated module in tests/semantic/spirv_wave_interp.py. 15The values come from running the translated module in tests/semantic/spirv_wave_interp.py.
13 16
14Standard library only; no GPU, no LLVM, no SPIRV-Tools, no game files. 17Standard library only; no GPU, no LLVM, no SPIRV-Tools, no game files.
@@ -66,34 +69,40 @@ def compare_vs(op, form, exec_off=None):
66 69
67def compare_reference(op, form, exec_off=None, wave=32): 70def compare_reference(op, form, exec_off=None, wave=32):
68 """The VCC bit per lane after compare_vs: an inactive lane's bit is 0, as for a plain compare.""" 71 """The VCC bit per lane after compare_vs: an inactive lane's bit is 0, as for a plain compare."""
69 mods = form.split()
70 fi = any(m == "fi:1" for m in mods)
71 relation = COMPARES[op][1] 72 relation = COMPARES[op][1]
72 active = [lane != exec_off for lane in range(wave)] 73 active = [lane != exec_off for lane in range(wave)]
73 out = [] 74 out = []
74 for lane in range(wave): 75 for lane in range(wave):
75 loc, ok = lane & 15, True 76 src = source_lane(form, lane, active)
76 if mods[0].startswith("dpp8:"): 77 out.append(int(active[lane] and relation(src if src is not None else 0, lane)))
77 src = (lane & ~7) | [int(x) for x in mods[0][6:-1].split(",")][lane & 7]
78 elif mods[0].startswith("quad_perm:"):
79 src = (lane & ~3) | [int(x) for x in mods[0][11:-1].split(",")][lane & 3]
80 else:
81 kind, _, n = mods[0].partition(":")
82 n = int(n or 0)
83 if kind == "row_shr":
84 ok, s = loc >= n, loc - n
85 elif kind == "row_shl":
86 ok, s = loc + n < 16, loc + n
87 elif kind == "row_ror":
88 s = (loc - n) & 15
89 else: # row_mirror
90 s = 15 - loc
91 src = (lane & ~15) | (s & 15)
92 valid = ok and (active[src] or fi)
93 out.append(int(active[lane] and relation(src if valid else 0, lane)))
94 return out 78 return out
95 79
96 80
81def source_lane(form, lane, active):
82 """The lane DPP `form` reads src0 from for `lane`, or None where src0 reads 0 (out of the row, or inactive
83 without fi:1)."""
84 mods = form.split()
85 fi = any(m == "fi:1" for m in mods)
86 loc, ok = lane & 15, True
87 if mods[0].startswith("dpp8:"):
88 src = (lane & ~7) | [int(x) for x in mods[0][6:-1].split(",")][lane & 7]
89 elif mods[0].startswith("quad_perm:"):
90 src = (lane & ~3) | [int(x) for x in mods[0][11:-1].split(",")][lane & 3]
91 else:
92 kind, _, n = mods[0].partition(":")
93 n = int(n or 0)
94 if kind == "row_shr":
95 ok, s = loc >= n, loc - n
96 elif kind == "row_shl":
97 ok, s = loc + n < 16, loc + n
98 elif kind == "row_ror":
99 s = (loc - n) & 15
100 else: # row_mirror
101 s = 15 - loc
102 src = (lane & ~15) | (s & 15)
103 return src if ok and (active[src] or fi) else None
104
105
97def run(op, form, exec_off=None): 106def run(op, form, exec_off=None):
98 res = wi.run_wave(compare_vs(op, form, exec_off), wave=32, 107 res = wi.run_wave(compare_vs(op, form, exec_off), wave=32,
99 builtins={"VertexIndex": lambda lane: lane, "InstanceIndex": lambda lane: 0}) 108 builtins={"VertexIndex": lambda lane: lane, "InstanceIndex": lambda lane: 0})
@@ -124,30 +133,105 @@ class DppCompare(unittest.TestCase):
124 def test_a_form_that_leaves_a_lane_unwritten_is_refused(self): 133 def test_a_form_that_leaves_a_lane_unwritten_is_refused(self):
125 for form in UNWRITTEN_FORMS: 134 for form in UNWRITTEN_FORMS:
126 with self.subTest(form=form): 135 with self.subTest(form=form):
127 with self.assertRaisesRegex(Unsupported, "DPP compare with lanes that keep their mask bit"): 136 with self.assertRaisesRegex(Unsupported, "DPP compare with lanes DPP leaves unwritten"):
128 compare_vs("v_cmp_gt_f32_dpp", form) 137 compare_vs("v_cmp_gt_f32_dpp", form)
129 138
130 def test_cmpx_is_refused(self): 139
131 lines = ["v_mbcnt_lo_u32_b32 v0, -1, 0", 140# v_cmpx in DPP form (SHADER-VOPCX-DPP): the same lane selection, with the result written to EXEC. src0 is the first
132 "v_cmpx_gt_u32_dpp v0, v0 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf bound_ctrl:1", 141# operand, since v_cmpx prints no destination. f32 compares read v1 = float(lane - 4), so a negated src1 changes the
142# result; integer compares read v0 = lane.
143CMPX = {
144 "v_cmpx_gt_f32_dpp": ("v1", lambda a, b: a > b),
145 "v_cmpx_lt_u32_dpp": ("v0", lambda a, b: a < b),
146 "v_cmpx_eq_u32_dpp": ("v0", lambda a, b: a == b),
147}
148# The form all 113 DPP v_cmpx of the 78 refused pipeline-library pixel shaders of 1.0.2.1 use, with src1 negated.
149GAME_FORM = "quad_perm:[2,3,0,1] row_mask:0xf bank_mask:0xf bound_ctrl:1 fi:1"
150
151
152def cmpx_vs(op, form, exec_off=None, neg=False):
153 """A vertex shader: EXEC = `op`(DPP(src), [-]src) over the lanes on (all but `exec_off`); param0.x exports 1
154 where the new EXEC keeps the lane and 0 where it drops it."""
155 src = CMPX[op][0]
156 lines = ["v_mbcnt_lo_u32_b32 v0, -1, 0", "v_add_nc_u32_e32 v7, -4, v0", "v_cvt_f32_i32_e32 v1, v7",
157 "v_mov_b32 v4, 1", "v_mov_b32 v6, 0", "s_mov_b32 s10, exec_lo"]
158 if exec_off is not None:
159 lines.append(f"v_cmpx_ne_u32_e32 {exec_off}, v0")
160 lines += [f"{op} {src}, {'-' if neg else ''}{src} {form}", "v_mov_b32 v6, v4", "s_mov_b32 exec_lo, s10",
161 "v_mov_b32 v5, 0", "exp pos0 v5, v5, v5, v5 done", "exp param0 v6, v5, v5, v5", "s_endpgm"]
162 return support.translate_lines("vs_dpp_cmpx", lines)
163
164
165def cmpx_reference(op, form, exec_off=None, neg=False, wave=32):
166 """The EXEC bit per lane after the v_cmpx of cmpx_vs: 0 for a lane that was off, as for a plain v_cmpx."""
167 src, relation = CMPX[op]
168 value = (lambda lane: float(lane - 4)) if src == "v1" else (lambda lane: lane)
169 active = [lane != exec_off for lane in range(wave)]
170 out = []
171 for lane in range(wave):
172 s = source_lane(form, lane, active)
173 a = value(s) if s is not None else 0
174 b = -value(lane) if neg else value(lane)
175 out.append(int(active[lane] and relation(a, b)))
176 return out
177
178
179def run_cmpx(op, form, exec_off=None, neg=False):
180 res = wi.run_wave(cmpx_vs(op, form, exec_off, neg), wave=32,
181 builtins={"VertexIndex": lambda lane: lane, "InstanceIndex": lambda lane: 0})
182 return [o["%out_param0"][0] for o in res["outputs"]]
183
184
185class DppCompareExec(unittest.TestCase):
186 def test_values(self):
187 for op in CMPX:
188 for form in WRITTEN_FORMS + [GAME_FORM]:
189 for exec_off in (None, 5, 16):
190 with self.subTest(op=op, form=form, exec_off=exec_off):
191 self.assertEqual(run_cmpx(op, form, exec_off), cmpx_reference(op, form, exec_off))
192
193 def test_game_form_with_negated_src1(self):
194 for exec_off in (None, 1, 6):
195 with self.subTest(exec_off=exec_off):
196 want = cmpx_reference("v_cmpx_gt_f32_dpp", GAME_FORM, exec_off, neg=True)
197 self.assertEqual(run_cmpx("v_cmpx_gt_f32_dpp", GAME_FORM, exec_off, neg=True), want)
198 self.assertNotEqual(want, cmpx_reference("v_cmpx_gt_f32_dpp", GAME_FORM, exec_off))
199
200 def test_reference_by_hand(self):
201 # quad_perm:[2,3,0,1] swaps the halves of each quad, and lanes 0-7 hold -4..3: lane 0 compares lane 2's -2
202 # with its own -4, so -2 > -4 keeps it and, src1 negated, -2 > 4 drops it.
203 self.assertEqual(cmpx_reference("v_cmpx_gt_f32_dpp", GAME_FORM)[:8], [1, 1, 0, 0, 1, 1, 0, 0])
204 self.assertEqual(cmpx_reference("v_cmpx_gt_f32_dpp", GAME_FORM, neg=True)[:8], [0, 0, 0, 0, 1, 1, 1, 1])
205 # A lane that was off stays off, whatever its compare gives.
206 self.assertEqual(cmpx_reference("v_cmpx_gt_f32_dpp", GAME_FORM, exec_off=5)[:8], [1, 1, 0, 0, 1, 0, 0, 0])
207
208 def test_a_form_that_leaves_a_lane_unwritten_is_refused(self):
209 for form in UNWRITTEN_FORMS:
210 with self.subTest(form=form):
211 with self.assertRaisesRegex(Unsupported, "DPP compare with lanes DPP leaves unwritten"):
212 cmpx_vs("v_cmpx_gt_f32_dpp", form)
213
214 def test_a_destination_operand_is_refused(self):
215 # v_cmpx prints no destination: a line with one is not a form the disassembler writes.
216 lines = ["v_mbcnt_lo_u32_b32 v0, -1, 0", f"v_cmpx_gt_u32_dpp vcc_lo, v0, v0 {WRITTEN_FORMS[0]}",
133 "v_mov_b32 v5, 0", "exp pos0 v5, v5, v5, v5 done", "s_endpgm"] 217 "v_mov_b32 v5, 0", "exp pos0 v5, v5, v5, v5 done", "s_endpgm"]
134 with self.assertRaises(Unsupported): 218 with self.assertRaisesRegex(Unsupported, "DPP compare operands"):
135 support.translate_lines("vs_dpp_cmpx", lines) 219 support.translate_lines("vs_dpp_cmpx_dst", lines)
136 220
137 221
138def vopc(opcode, src0, vsrc1): 222def vopc(opcode, src0, vsrc1):
139 return 0x3E << 25 | opcode << 17 | vsrc1 << 9 | src0 223 return 0x3E << 25 | opcode << 17 | vsrc1 << 9 | src0
140 224
141 225
142def dpp16_word(src0_reg, ctrl, bound=0, fi=0, bank_mask=0xF, row_mask=0xF): 226def dpp16_word(src0_reg, ctrl, bound=0, fi=0, bank_mask=0xF, row_mask=0xF, src1_neg=0):
143 return row_mask << 28 | bank_mask << 24 | bound << 19 | fi << 18 | ctrl << 8 | src0_reg 227 return row_mask << 28 | bank_mask << 24 | src1_neg << 22 | bound << 19 | fi << 18 | ctrl << 8 | src0_reg
144 228
145 229
146def dpp8_word(src0_reg, lanes): 230def dpp8_word(src0_reg, lanes):
147 return sum(lane << (8 + 3 * i) for i, lane in enumerate(lanes)) | src0_reg 231 return sum(lane << (8 + 3 * i) for i, lane in enumerate(lanes)) | src0_reg
148 232
149 233
150GT_F32, LT_U32 = 0x04, 0xC1 # VOPC opcodes (tools/rdna2_tables.py) 234GT_F32, LT_U32, CMPX_GT_F32 = 0x04, 0xC1, 0x14 # VOPC opcodes (tools/rdna2_tables.py)
151S_ENDPGM = 0xBF810000 235S_ENDPGM = 0xBF810000
152# (first word, second word, the line both printers give) 236# (first word, second word, the line both printers give)
153PAIRS = [ 237PAIRS = [
@@ -161,6 +245,9 @@ PAIRS = [
161 "v_cmp_gt_f32_dpp vcc_lo, v20, v20 dpp8:[4,5,6,7,0,1,2,3]"), 245 "v_cmp_gt_f32_dpp vcc_lo, v20, v20 dpp8:[4,5,6,7,0,1,2,3]"),
162 (vopc(GT_F32, 234, 6), dpp8_word(5, [7, 6, 5, 4, 3, 2, 1, 0]), 246 (vopc(GT_F32, 234, 6), dpp8_word(5, [7, 6, 5, 4, 3, 2, 1, 0]),
163 "v_cmp_gt_f32_dpp vcc_lo, v5, v6 dpp8:[7,6,5,4,3,2,1,0] fi:1"), 247 "v_cmp_gt_f32_dpp vcc_lo, v5, v6 dpp8:[7,6,5,4,3,2,1,0] fi:1"),
248 # The game's v_cmpx form: no destination, src1 negated (bytes fa 02 28 7c 01 4e 4c ff).
249 (vopc(CMPX_GT_F32, 250, 1), dpp16_word(1, 0x4E, bound=1, fi=1, src1_neg=1),
250 "v_cmpx_gt_f32_dpp v1, -v1 quad_perm:[2,3,0,1] row_mask:0xf bank_mask:0xf bound_ctrl:1 fi:1"),
164] 251]
165 252
166 253
@@ -175,6 +262,7 @@ class DppCompareDecode(unittest.TestCase):
175 import rdna2_decode 262 import rdna2_decode
176 self.assertEqual(rdna2_decode.T.VOPC[GT_F32][0], "v_cmp_gt_f32") 263 self.assertEqual(rdna2_decode.T.VOPC[GT_F32][0], "v_cmp_gt_f32")
177 self.assertEqual(rdna2_decode.T.VOPC[LT_U32][0], "v_cmp_lt_u32") 264 self.assertEqual(rdna2_decode.T.VOPC[LT_U32][0], "v_cmp_lt_u32")
265 self.assertEqual(rdna2_decode.T.VOPC[CMPX_GT_F32][0], "v_cmpx_gt_f32")
178 266
179 def test_python_decoder(self): 267 def test_python_decoder(self):
180 import rdna2_decode 268 import rdna2_decode
@@ -186,8 +274,8 @@ class DppCompareDecode(unittest.TestCase):
186 self.assertEqual((lines, bad), ([want, "s_endpgm"], 0)) 274 self.assertEqual((lines, bad), ([want, "s_endpgm"], 0))
187 275
188 def test_a_decoded_line_translates(self): 276 def test_a_decoded_line_translates(self):
189 # What the disassembler prints is what the translator takes: the two forms it accepts, from PAIRS. 277 # What the disassembler prints is what the translator takes: the forms it accepts, from PAIRS.
190 for _, _, line in (PAIRS[0], PAIRS[3]): 278 for _, _, line in (PAIRS[0], PAIRS[3], PAIRS[5]):
191 with self.subTest(line=line): 279 with self.subTest(line=line):
192 lines = ["v_mbcnt_lo_u32_b32 v0, -1, 0", line, "v_mov_b32 v5, 0", "exp pos0 v5, v5, v5, v5 done", 280 lines = ["v_mbcnt_lo_u32_b32 v0, -1, 0", line, "v_mov_b32 v5, 0", "exp pos0 v5, v5, v5, v5 done",
193 "s_endpgm"] 281 "s_endpgm"]
diff --git a/tests/semantic/test_fma_mix_literal.py b/tests/semantic/test_fma_mix_literal.py
index 75608f4a9..488e12b95 100644
--- a/tests/semantic/test_fma_mix_literal.py
+++ b/tests/semantic/test_fma_mix_literal.py
@@ -77,6 +77,20 @@ class FmaMixLiteralTest(unittest.TestCase):
77 def test_reanchored_listing_takes_it_too(self): 77 def test_reanchored_listing_takes_it_too(self):
78 self.assertEqual(self.run_ps(listing(PRINTED, invalid=True), blob(STORED)), [f2u(8.0)] * 4) 78 self.assertEqual(self.run_ps(listing(PRINTED, invalid=True), blob(STORED)), [f2u(8.0)] * 4)
79 79
80 def test_text_cut_but_printed_encoding_whole(self):
81 # llvm-mc 21.1.8 can also print the literal cut to its low half in the text alone, with all 32 bits in the
82 # printed encoding: same_encoding then passes, and before the change the high half read +0.0 (6.0).
83 self.assertEqual(self.run_ps(listing(STORED), blob(STORED)), [f2u(8.0)] * 4)
84 self.assertEqual(self.run_ps(listing(STORED, invalid=True), blob(STORED)), [f2u(8.0)] * 4)
85 # The printed encoding is all it needs: no blob next to the listing.
86 self.assertEqual(self.run_ps(listing(STORED), None), [f2u(8.0)] * 4)
87
88 def test_text_immediate_other_than_the_low_half_is_left_alone(self):
89 # The text shows 0x4000 (2.0), not the encoded literal's low half 0x4200: the text is taken as it reads,
90 # fma(2.0, 2.0, +0.0) = 4.0, not the encoding's fma(3.0, 2.0, 2.0) = 8.0.
91 text = MIX_TEXT.replace("0x4200", "0x4000")
92 self.assertEqual(self.run_ps(listing(program(0x40004200, text=text)), None), [f2u(4.0)] * 4)
93
80 def test_without_the_blob_the_printed_literal_is_all_there_is(self): 94 def test_without_the_blob_the_printed_literal_is_all_there_is(self):
81 # LLVM's text alone: the high half reads +0.0, fma(3.0, 2.0, 0.0) = 6.0 (what the listing says). 95 # LLVM's text alone: the high half reads +0.0, fma(3.0, 2.0, 0.0) = 6.0 (what the listing says).
82 self.assertEqual(self.run_ps(listing(PRINTED), None), [f2u(6.0)] * 4) 96 self.assertEqual(self.run_ps(listing(PRINTED), None), [f2u(6.0)] * 4)
diff --git a/tests/semantic/test_library_compute_forms.py b/tests/semantic/test_library_compute_forms.py
index 0e1c84bf4..a650b240c 100644
--- a/tests/semantic/test_library_compute_forms.py
+++ b/tests/semantic/test_library_compute_forms.py
@@ -100,6 +100,16 @@ class LibraryComputeForms(unittest.TestCase):
100 self.assertEqual((recovered["pc"], recovered["enc"]), (0, blob.hex())) 100 self.assertEqual((recovered["pc"], recovered["enc"]), (0, blob.hex()))
101 self.assertFalse(rdna2_decode.decode_bytes(blob[:4])["insns"]) 101 self.assertFalse(rdna2_decode.decode_bytes(blob[:4])["insns"])
102 102
103 def test_vopcx_dpp_recovery(self):
104 # SHADER-VOPCX-DPP: the same pass recovers v_cmpx in DPP form (opcode 0x14, v_cmpx_gt_f32), which prints no
105 # destination: the game's form, quad_perm:[2,3,0,1] bound_ctrl:1 fi:1 with src1 negated (fa 02 28 7c 01 4e 4c ff).
106 blob = bytes.fromhex("fa02287c014e4cff")
107 row, = rdna2_decode.decode_bytes(blob, wave32=True)["insns"]
108 self.assertEqual((row["op"], len(row["args"]), row["args"][0]["r"]), ("v_cmpx_gt_f32_dpp", 2, 1))
109 junk = {"pc": 4, "enc": blob[4:].hex(), "op": "s_nop", "args": [{"k": "imm", "v": 0}], "mods": []}
110 recovered, = rdna2spirv.restore_vcc_tuples([junk], blob, 0, len(blob), wave32=True)
111 self.assertEqual((recovered["pc"], recovered["enc"], recovered["op"]), (0, blob.hex(), "v_cmpx_gt_f32_dpp"))
112
103 def test_vopc_dpp_reads_the_selected_lane(self): 113 def test_vopc_dpp_reads_the_selected_lane(self):
104 spv, _ = translate_fspx(fixture("vopc_dpp_compare")[:-1], wave32=False) 114 spv, _ = translate_fspx(fixture("vopc_dpp_compare")[:-1], wave32=False)
105 memory = {} 115 memory = {}
diff --git a/tests/semantic/test_loop_ballot_barrier.py b/tests/semantic/test_loop_ballot_barrier.py
index 9f5c6ffb2..103dc94bd 100644
--- a/tests/semantic/test_loop_ballot_barrier.py
+++ b/tests/semantic/test_loop_ballot_barrier.py
@@ -1059,11 +1059,12 @@ class DivergentLoopBallotTests(unittest.TestCase):
1059 configs = [ 1059 configs = [
1060 ("native_64", 64, 64, False, True), 1060 ("native_64", 64, 64, False, True),
1061 ("native_128", 128, 64, False, True), 1061 ("native_128", 128, 64, False, True),
1062 # Single-wave inline exchange barriers in this loop require a round fallback. 1062 # a reducible multi-block loop takes the structured emulation since #2089 (no round OpSwitch); a
1063 # single wave keeps its exchange barriers under `%pc`-only guards (inline_all, no round fallback) ...
1063 ("emulate_64_sg32", 64, 32, True, True), 1064 ("emulate_64_sg32", 64, 32, True, True),
1064 ("emulate_128_sg32", 128, 32, True, True), 1065 ("emulate_128_sg32", 128, 32, True, True),
1065 ("emulate_40_partial_sg32", 40, 32, True, True), 1066 ("emulate_40_partial_sg32", 40, 32, True, True),
1066 # Forced dispatch must produce the same per-lane reference words. 1067 # ... and --dispatch-loop keeps the round scheduler: both must give the native words
1067 ("emulate_64_sg32_rounds", 64, 32, True, False), 1068 ("emulate_64_sg32_rounds", 64, 32, True, False),
1068 ("emulate_128_sg32_rounds", 128, 32, True, False), 1069 ("emulate_128_sg32_rounds", 128, 32, True, False),
1069 ("emulate_40_partial_sg32_rounds", 40, 32, True, False), 1070 ("emulate_40_partial_sg32_rounds", 40, 32, True, False),
@@ -1073,10 +1074,14 @@ class DivergentLoopBallotTests(unittest.TestCase):
1073 spv, gen = _translate_cs("cs_div_loop_" + label, prog, threads=threads, emulate=emulate, 1074 spv, gen = _translate_cs("cs_div_loop_" + label, prog, threads=threads, emulate=emulate,
1074 structured=structured) 1075 structured=structured)
1075 if emulate: 1076 if emulate:
1076 use_hybrid = structured and threads == 128 1077 self.assertEqual(gen.control_flow,
1077 expected_flow = "emulated wave64 structured" if use_hybrid else "emulated wave64 rounds" 1078 "emulated wave64 structured" if structured else "emulated wave64 rounds")
1078 self.assertEqual(gen.control_flow, expected_flow) 1079 if structured and threads <= 64:
1079 self.assertFalse(rdna2spirv.barriers_under_control_flow(spv)) 1080 self.assertEqual(gen.emulate_plan["mode"], "inline_all")
1081 self.assertNotIn("OpSwitch", spv)
1082 else:
1083 # multi-wave (and the round scheduler): every barrier in uniform control flow
1084 self.assertFalse(rdna2spirv.barriers_under_control_flow(spv))
1080 mem = run_compute_workgroup(spv, threads, sg_sz, push_constants=VSHARP) 1085 mem = run_compute_workgroup(spv, threads, sg_sz, push_constants=VSHARP)
1081 want = expected_for(threads) 1086 want = expected_for(threads)
1082 for t in range(threads): 1087 for t in range(threads):
@@ -1394,7 +1399,7 @@ class BarrierInLoopsTests(unittest.TestCase):
1394 """ 1399 """
1395 prog = self._ring_shift_loop_cs(wave64=True, threads=128, iters=5) 1400 prog = self._ring_shift_loop_cs(wave64=True, threads=128, iters=5)
1396 spv, gen = _translate_cs("cs_bar_loop_w64_emulate", prog, threads=128, lds_bytes=512, emulate=True) 1401 spv, gen = _translate_cs("cs_bar_loop_w64_emulate", prog, threads=128, lds_bytes=512, emulate=True)
1397 self.assertEqual(gen.control_flow, "emulated wave64 rounds") 1402 self.assertEqual(gen.control_flow, "emulated wave64 structured") # the loop is in the tail scheduler
1398 for rev in (False, True): 1403 for rev in (False, True):
1399 with self.subTest(reverse_subgroups=rev): 1404 with self.subTest(reverse_subgroups=rev):
1400 mem = run_compute_workgroup(spv, 128, 32, push_constants=VSHARP, reverse_subgroups=rev) 1405 mem = run_compute_workgroup(spv, 128, 32, push_constants=VSHARP, reverse_subgroups=rev)
@@ -1467,7 +1472,7 @@ class BarrierInLoopsTests(unittest.TestCase):
1467 spv_em, gen_em = _translate_cs( 1472 spv_em, gen_em = _translate_cs(
1468 "cs_div_bar_em", self._wave_divergent_barrier_loop_cs(True), threads=128, lds_bytes=512, emulate=True 1473 "cs_div_bar_em", self._wave_divergent_barrier_loop_cs(True), threads=128, lds_bytes=512, emulate=True
1469 ) 1474 )
1470 self.assertEqual(gen_em.control_flow, "emulated wave64 rounds") 1475 self.assertEqual(gen_em.control_flow, "emulated wave64 structured") # the loop is in the tail scheduler
1471 mem_em = run_compute_workgroup(spv_em, 128, 32, push_constants=VSHARP) 1476 mem_em = run_compute_workgroup(spv_em, 128, 32, push_constants=VSHARP)
1472 self.assertEqual([mem_em[4 * t] for t in range(128)], [2] * 64 + [4] * 64) 1477 self.assertEqual([mem_em[4 * t] for t in range(128)], [2] * 64 + [4] * 64)
1473 1478
diff --git a/tests/semantic/test_loop_iteration_guard.py b/tests/semantic/test_loop_iteration_guard.py
index a990031dd..e6666f81a 100644
--- a/tests/semantic/test_loop_iteration_guard.py
+++ b/tests/semantic/test_loop_iteration_guard.py
@@ -32,18 +32,17 @@ class LoopGuardTests(unittest.TestCase):
32 for lanes in (32, 64): 32 for lanes in (32, 64):
33 with self.subTest(lanes=lanes): 33 with self.subTest(lanes=lanes):
34 (plain, plain_flow), (guarded, flow) = module(lanes, 0), module(lanes, 16) 34 (plain, plain_flow), (guarded, flow) = module(lanes, 0), module(lanes, 16)
35 expected_flow = "structured" if lanes == 32 else "emulated wave64 rounds" 35 # A single-wave emulated program keeps the structured form (no round fallback for `inline_all`).
36 expected_flow = "structured" if lanes == 32 else "emulated wave64 structured"
36 self.assertEqual((plain_flow, flow), (expected_flow, expected_flow)) 37 self.assertEqual((plain_flow, flow), (expected_flow, expected_flow))
37 self.assertNotIn("%loop_guard_", plain) 38 self.assertNotIn("%loop_guard_", plain)
38 self.assertIn("%loop_guard_", guarded) 39 self.assertIn("%loop_guard_", guarded)
39 self.assertEqual(execute(plain, lanes, 6), [6] * lanes) 40 self.assertEqual(execute(plain, lanes, 6), [6] * lanes)
40 self.assertEqual(execute(guarded, lanes, 6), [6] * lanes) 41 self.assertEqual(execute(guarded, lanes, 6), [6] * lanes)
41 # Round zero initializes the guest PC. Each remaining round adds two. 42 self.assertEqual(execute(guarded, lanes, 1), [32] * lanes)
42 expected = 32 if lanes == 32 else 30
43 self.assertEqual(execute(guarded, lanes, 1), [expected] * lanes)
44 43
45 def test_round_budget_uses_the_scheduler_exit(self): 44 def test_round_budget_uses_the_scheduler_exit(self):
46 text, flow = module(64, 16) 45 text, flow = module(64, 16, structured=False)
47 self.assertEqual(flow, "emulated wave64 rounds") 46 self.assertEqual(flow, "emulated wave64 rounds")
48 # Counters and synchronization execute on the final round too. The guard 47 # Counters and synchronization execute on the final round too. The guard
49 # augments the scheduler's termination condition at its original branch. 48 # augments the scheduler's termination condition at its original branch.
diff --git a/tests/semantic/test_wave64_emulate_opt.py b/tests/semantic/test_wave64_emulate_opt.py
index 6593a668b..995504234 100644
--- a/tests/semantic/test_wave64_emulate_opt.py
+++ b/tests/semantic/test_wave64_emulate_opt.py
@@ -1281,9 +1281,12 @@ class LocalExecFoldTests(unittest.TestCase):
1281class StructuredEmulationTests(unittest.TestCase): 1281class StructuredEmulationTests(unittest.TestCase):
1282 """Structured --wave64-emulate (`inline_all` for <=64 threads, `structured_hybrid` for >64 threads).""" 1282 """Structured --wave64-emulate (`inline_all` for <=64 threads, `structured_hybrid` for >64 threads)."""
1283 1283
1284 def test_single_wave_round_fallback_and_loop_carried_war(self): 1284 def test_single_wave_inline_all_zero_switch_and_loop_carried_war(self):
1285 # 64-thread and partial 40-thread shaders with live-out scalars, loop-carried store->load->store WAR/RAW, 1285 # 64-thread and partial 40-thread shaders with live-out scalars, loop-carried store->load->store WAR/RAW,
1286 # and v_readfirstlane require uniform exchange barriers on both scheduling orders. 1286 # and v_readfirstlane emit 0 OpSwitch cases and 0 x_spills while staying bit-exact on both scheduling
1287 # orders. Their exchange barriers sit under `%pc`-only guards, which a single wave takes as one, so the
1288 # barrier fallback of translate() does not apply to them (docs/design.md, "Wave64 emulation:
1289 # single-wave barrier fallback").
1287 insns = [ 1290 insns = [
1288 ("s_mov_b64 exec, -1", 4), 1291 ("s_mov_b64 exec, -1", 4),
1289 ("s_mov_b32 s16, 10", 4), 1292 ("s_mov_b32 s16, 10", 4),
@@ -1314,10 +1317,11 @@ class StructuredEmulationTests(unittest.TestCase):
1314 for threads in (64, 40): 1317 for threads in (64, 40):
1315 with self.subTest(threads=threads): 1318 with self.subTest(threads=threads):
1316 spv, gen = _translate_encoded(f"cs_inline_{threads}", insns, (threads, 1, 1), emulate=True) 1319 spv, gen = _translate_encoded(f"cs_inline_{threads}", insns, (threads, 1, 1), emulate=True)
1317 self.assertEqual(gen.control_flow, "emulated wave64 rounds") 1320 self.assertEqual(gen.control_flow, "emulated wave64 structured")
1318 self.assertIsNone(gen.emulate_plan) 1321 self.assertEqual(gen.emulate_plan["mode"], "inline_all")
1319 self.assertIn("OpSwitch", spv) 1322 self.assertNotIn("OpSwitch", spv)
1320 self.assertFalse(rdna2spirv.barriers_under_control_flow(spv)) 1323 self.assertEqual(len(gen.x_spills), 0)
1324 self.assertNotIn("OpGroupNonUniform", spv)
1321 for rev in (False, True): 1325 for rev in (False, True):
1322 mem, _ = run_emulated_workgroup(spv, (threads, 1, 1), push_constants=VSHARP + [0] * 28, reverse_order=rev) 1326 mem, _ = run_emulated_workgroup(spv, (threads, 1, 1), push_constants=VSHARP + [0] * 28, reverse_order=rev)
1323 # Reference simulation 1327 # Reference simulation
@@ -1429,8 +1433,8 @@ class StructuredEmulationTests(unittest.TestCase):
1429 want = isa_v4_before_sbar(l) + isa_v4_before_sbar(l ^ 64) 1433 want = isa_v4_before_sbar(l) + isa_v4_before_sbar(l ^ 64)
1430 self.assertEqual(mem_new[1024 + l * 4], want, f"lane {l} rev={rev}") 1434 self.assertEqual(mem_new[1024 + l * 4], want, f"lane {l} rev={rev}")
1431 1435
1432 def test_multiwave_divergent_sbarrier_falls_back_to_rounds(self): 1436 def test_multiwave_divergent_sbarrier_stays_in_tail_rounds(self):
1433 # Wave 0 hits s_barrier in one arm while Wave 1 hits s_barrier in another -> MUST keep global rounds. 1437 # Wave 0 hits s_barrier in one arm while Wave 1 hits s_barrier in another -> both arms MUST keep the rounds.
1434 insns = [ 1438 insns = [
1435 ("s_mov_b64 exec, -1", 4), 1439 ("s_mov_b64 exec, -1", 4),
1436 ("v_lshlrev_b32_e32 v2, 2, v0", 4), 1440 ("v_lshlrev_b32_e32 v2, 2, v0", 4),
@@ -1448,11 +1452,49 @@ class StructuredEmulationTests(unittest.TestCase):
1448 ("s_endpgm", 4), 1452 ("s_endpgm", 4),
1449 ] 1453 ]
1450 spv, gen = _translate_encoded("cs_div_sbar_w64", insns, (128, 1, 1), emulate=True, rsrc2=0x20088) 1454 spv, gen = _translate_encoded("cs_div_sbar_w64", insns, (128, 1, 1), emulate=True, rsrc2=0x20088)
1451 self.assertEqual(gen.control_flow, "emulated wave64 rounds") 1455 self.assertEqual(gen.control_flow, "emulated wave64 structured")
1452 self.assertIsNone(gen.emulate_plan) 1456 plan = gen.emulate_plan
1453 mem, _ = run_emulated_workgroup(spv, (128, 1, 1), push_constants=VSHARP + [0] * 28) 1457 self.assertEqual(plan["inline_blocks"], {0})
1454 for lane in range(64): 1458 self.assertEqual(plan["tail_blocks"], {1, 2}) # both s_barrier arms
1455 self.assertEqual(mem[lane * 4], lane + 64, f"lane {lane}") 1459 for rev in (False, True):
1460 mem, _ = run_emulated_workgroup(spv, (128, 1, 1), push_constants=VSHARP + [0] * 28, reverse_order=rev)
1461 for lane in range(64):
1462 self.assertEqual(mem[lane * 4], lane + 64, f"lane {lane}, reverse={rev}")
1463
1464 def test_multiwave_guarded_sbarrier_epilogue_keeps_body_structured(self):
1465 # The shape of an NGG mesh epilogue: a body with a wave vote, then a guarded s_barrier both waves skip or
1466 # reach (s_cbranch_vccnz), then a top-level s_barrier. Only the part from the guard on stays in rounds.
1467 def insns(vcc):
1468 return [
1469 ("s_mov_b64 exec, -1", 4),
1470 ("v_lshlrev_b32_e32 v2, 2, v0", 4),
1471 ("v_add_nc_u32_e32 v5, 7, v0", 4),
1472 ("v_readfirstlane_b32 s5, v0", 4),
1473 ("v_add_nc_u32_e32 v5, s5, v5", 4),
1474 ("ds_write_b32 v2, v5", 8),
1475 (f"s_mov_b64 vcc, {vcc}", 4),
1476 ("s_cbranch_vccnz 1", 4),
1477 ("s_barrier", 4),
1478 ("s_barrier", 4),
1479 ("v_xor_b32_e32 v3, 64, v0", 4),
1480 ("v_lshlrev_b32_e32 v3, 2, v3", 4),
1481 ("ds_read_b32 v4, v3", 8),
1482 ("buffer_store_dword v4, v2, s[0:3], 0 offen", 8),
1483 ("s_endpgm", 4),
1484 ]
1485 for vcc in ("0", "-1"):
1486 spv, gen = _translate_encoded("cs_sbar_epilogue_w64", insns(vcc), (128, 1, 1), emulate=True,
1487 rsrc2=0x20088)
1488 self.assertEqual(gen.control_flow, "emulated wave64 structured")
1489 plan = gen.emulate_plan
1490 self.assertEqual(plan["inline_blocks"], {0})
1491 self.assertEqual(plan["tail_blocks"], {1, 2})
1492 for rev in (False, True):
1493 mem, _ = run_emulated_workgroup(spv, (128, 1, 1), push_constants=VSHARP + [0] * 28,
1494 reverse_order=rev)
1495 for lane in range(128):
1496 other = lane ^ 64
1497 self.assertEqual(mem[lane * 4], other + 7 + (other & 64), f"lane {lane}, vcc={vcc}, rev={rev}")
1456 1498
1457 def test_monotone_dirty_transfer_no_phantom_clear_after_x_round(self): 1499 def test_monotone_dirty_transfer_no_phantom_clear_after_x_round(self):
1458 # Regression: an x_round (v_readlane_b32) clears g.x_dirty in codegen before a subsequent 1500 # Regression: an x_round (v_readlane_b32) clears g.x_dirty in codegen before a subsequent
diff --git a/tests/semantic/test_wave64_halves.py b/tests/semantic/test_wave64_halves.py
index 15a942654..b112ce331 100644
--- a/tests/semantic/test_wave64_halves.py
+++ b/tests/semantic/test_wave64_halves.py
@@ -1348,5 +1348,25 @@ class PixelShaders(unittest.TestCase):
1348 self.assertEqual(slots64, slots32) 1348 self.assertEqual(slots64, slots32)
1349 1349
1350 1350
1351class VcmpxDppExec(unittest.TestCase):
1352 """SHADER-VOPCX-DPP review: a v_cmpx in DPP form writes EXEC like any v_cmpx, and the cross-lane branch of the
1353 analysis must not drop that write. The repro from the review: after the compare, v5 = s4 is not one value in every
1354 lane, so v_readlane_b32 of it is not a uniform read."""
1355
1356 BODY = ["v_mov_b32_e32 v5, 0", "s_mov_b64 s[10:11], exec", None, "v_mov_b32_e32 v5, s4", "s_mov_b64 exec, s[10:11]",
1357 "v_readlane_b32 s5, v5, 0", "v_mov_b32_e32 v6, s5"]
1358
1359 def meta(self, compare):
1360 body = [compare if line is None else line for line in self.BODY]
1361 return meta_of("ps_vcmpx_dpp_exec", ps(body))[0]
1362
1363 def test_dpp_form_is_classified_as_the_e32_form(self):
1364 e32 = self.meta("v_cmpx_gt_f32_e32 v1, v2")
1365 dpp = self.meta("v_cmpx_gt_f32_dpp v1, -v1 quad_perm:[2,3,0,1] row_mask:0xf bank_mask:0xf bound_ctrl:1 fi:1")
1366 self.assertEqual(e32, ("C", ["cross-lane"], []))
1367 self.assertEqual(dpp, e32)
1368 self.assertNotIn("readlane-uniform", dpp[2])
1369
1370
1351if __name__ == "__main__": 1371if __name__ == "__main__":
1352 unittest.main() 1372 unittest.main()
diff --git a/tests/semantic/test_wave64_single_wave_barrier.py b/tests/semantic/test_wave64_single_wave_barrier.py
new file mode 100644
index 000000000..4723393e3
--- /dev/null
+++ b/tests/semantic/test_wave64_single_wave_barrier.py
@@ -0,0 +1,123 @@
1"""A single-wave emulated program keeps its exchange barriers in the structured form (docs/design.md, "Wave64
2emulation: single-wave barrier fallback").
3
4`translate()` re-translates an emulated program as the round loop when an `OpControlBarrier` sits under a branch or
5loop, because a barrier only part of the workgroup reaches hangs NVIDIA. A one-wave workgroup (`inline_all` plan)
6does not need that: every guard around its barriers tests only `%pc`, which all 64 invocations hold alike. The
7fixture puts a cross-half `v_readlane_b32` (an exchange behind a barrier) in a uniform loop and in a uniform branch.
8
9 python -I tests/semantic/test_wave64_single_wave_barrier.py -v
10"""
11import os
12import re
13import sys
14import unittest
15from pathlib import Path
16
17HERE = os.path.dirname(os.path.abspath(__file__))
18if HERE not in sys.path:
19 sys.path.insert(0, HERE)
20
21from test_loop_ballot_barrier import _translate_cs, rdna2spirv
22from spirv_mini_interp import run_workgroup
23
24FIXTURE = Path(HERE) / "fixtures" / "wave64_single_wave_barrier.asm"
25_DEF = re.compile(r"^\s*(%[\w.]+) = (Op\w+)([^\n]*)$", re.M)
26_HEAD = re.compile(r"^\s*(?:(%[\w.]+) = )?(OpLabel|OpSelectionMerge|OpLoopMerge|OpBranchConditional|OpControlBarrier)"
27 r"\b([^\n]*)$", re.M)
28
29
30def module(lanes, structured=True):
31 lines = [s for s in FIXTURE.read_text().splitlines() if s and not s.startswith(";")]
32 lines.insert(0, "s_mov_b64 exec, -1")
33 return _translate_cs("cs_single_wave_barrier", lines, threads=lanes, emulate=True, structured=structured)
34
35
36def execute(text, lanes, s4):
37 mem = run_workgroup(
38 text, lanes, 32,
39 inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i % 32, "%local_index": i},
40 push_constants=[0, 0, lanes * 4, 0x31016FAC, s4] + [0] * 27, memory={})
41 return [mem[i * 4] for i in range(lanes)]
42
43
44def barrier_guard_loads(text):
45 """For every OpControlBarrier, the variables the conditions of its enclosing constructs load.
46
47 A selection's condition is the OpBranchConditional after its OpSelectionMerge; a loop's are the conditional
48 branches inside it that leave it or go back to its header."""
49 defs = {name: (op, rest.split()) for name, op, rest in _DEF.findall(text)}
50
51 def loads(value, seen):
52 if value in seen or value not in defs:
53 return set()
54 seen.add(value)
55 op, args = defs[value]
56 if op == "OpLoad":
57 return {args[1]}
58 found = set()
59 for arg in args:
60 if arg.startswith("%"):
61 found |= loads(arg, seen)
62 return found
63
64 events = [(m.start(), m.group(1), m.group(2), m.group(3).split()) for m in _HEAD.finditer(text)]
65 label_at = {name: at for at, name, op, _ in events if op == "OpLabel"}
66 constructs, header = [], None
67 for i, (at, name, op, args) in enumerate(events):
68 if op == "OpLabel":
69 header = name
70 elif op in ("OpSelectionMerge", "OpLoopMerge"):
71 constructs.append((op, header, args[0], i))
72 result = []
73 for at, _, op, _ in events:
74 if op != "OpControlBarrier":
75 continue
76 loaded = set()
77 for kind, head, merge, index in constructs:
78 if not label_at[head] <= at < label_at[merge]:
79 continue
80 if kind == "OpSelectionMerge":
81 conds = [events[index + 1][3][0]]
82 else:
83 conds = [args[0] for b_at, _, b_op, args in events
84 if b_op == "OpBranchConditional" and label_at[head] <= b_at < label_at[merge]
85 and {merge, head} & set(args[1:])]
86 for cond in conds:
87 loaded |= loads(cond, set())
88 result.append(loaded)
89 return result
90
91
92class SingleWaveBarrierTests(unittest.TestCase):
93 def test_single_wave_stays_structured_with_pc_only_guards(self):
94 text, gen = module(64)
95 self.assertEqual(gen.control_flow, "emulated wave64 structured")
96 self.assertEqual(gen.emulate_plan["mode"], "inline_all")
97 self.assertNotIn("OpSwitch", text)
98 # The barriers are under control flow (so the multi-wave fallback would fire), but only under `%pc`.
99 self.assertTrue(rdna2spirv.barriers_under_control_flow(text))
100 guards = barrier_guard_loads(text)
101 self.assertTrue(any(guards), "no barrier inside the loop or the branch")
102 for loaded in guards:
103 self.assertLessEqual(loaded, {"%pc"})
104
105 def test_structured_and_round_forms_agree(self):
106 # lane 40 after each of the 3 iterations: 41 + 42 + 43; the branch adds lane 41's 41 + 3 + 100.
107 structured, _ = module(64)
108 rounds, gen = module(64, structured=False)
109 self.assertEqual(gen.control_flow, "emulated wave64 rounds")
110 for s4, want in ((0, 126), (1, 126 + 144)):
111 with self.subTest(s4=s4):
112 self.assertEqual(execute(structured, 64, s4), [want] * 64)
113 self.assertEqual(execute(rounds, 64, s4), [want] * 64)
114
115 def test_partial_single_wave_is_structured_too(self):
116 text, gen = module(48)
117 self.assertEqual(gen.control_flow, "emulated wave64 structured")
118 self.assertEqual(gen.emulate_plan["mode"], "inline_all")
119 self.assertEqual(execute(text, 48, 1), [126 + 144] * 48)
120
121
122if __name__ == "__main__":
123 unittest.main()
diff --git a/tests/test_dds_png_dx10.py b/tests/test_dds_png_dx10.py
index a0d55d324..159d542e2 100644
--- a/tests/test_dds_png_dx10.py
+++ b/tests/test_dds_png_dx10.py
@@ -63,6 +63,19 @@ class SingleChannelTests(unittest.TestCase):
63 self.assertEqual((width, height), (4, 2)) 63 self.assertEqual((width, height), (4, 2))
64 self.assertEqual(rgba, b"".join(bytes((r, 0, 0, 255)) for r in (0, 0, 128, 64, 255, 255, 0, 0))) 64 self.assertEqual(rgba, b"".join(bytes((r, 0, 0, 255)) for r in (0, 0, 128, 64, 255, 255, 0, 0)))
65 65
66 def test_byte_unorm_masks_respect_pitch_and_channel_order(self):
67 for dxgi, fmt, payload, expected in (
68 (61, "R8_UNORM", bytes([1, 2, 99, 99, 3, 4]), bytes([1,0,0,255, 2,0,0,255, 3,0,0,255, 4,0,0,255])),
69 (49, "R8G8_UNORM", bytes([1,2,3,4, 99,99, 5,6,7,8]), bytes([1,2,0,255, 3,4,0,255, 5,6,0,255, 7,8,0,255])),
70 ):
71 with self.subTest(fmt=fmt):
72 data = _dx10(2, 2, dxgi, payload, pitch=4 if dxgi == 61 else 6)
73 self.assertEqual(dds.parse_dds_header(data)["format"], fmt)
74 self.assertEqual(dds.decode_dds(data), (2, 2, expected))
75 self.assertEqual(dds.dds_to_png_bytes(data), dds.encode_png(2, 2, expected))
76 with self.assertRaises(dds.DdsError):
77 dds.decode_dds(data[:-1])
78
66 def test_r16_unorm_red_opaque(self): 79 def test_r16_unorm_red_opaque(self):
67 px = struct.pack("<HHHH", 0, 65535, 32768, 257) 80 px = struct.pack("<HHHH", 0, 65535, 32768, 257)
68 _, _, rgba = dds.decode_dds(_dx10(2, 2, 56, px)) 81 _, _, rgba = dds.decode_dds(_dx10(2, 2, 56, px))
@@ -74,11 +87,107 @@ class SingleChannelTests(unittest.TestCase):
74 self.assertEqual(rgba[3::4], bytes([1, 2, 3, 4, 5, 6])) 87 self.assertEqual(rgba[3::4], bytes([1, 2, 3, 4, 5, 6]))
75 self.assertEqual(set(rgba[0::4]) | set(rgba[1::4]) | set(rgba[2::4]), {0}) 88 self.assertEqual(set(rgba[0::4]) | set(rgba[1::4]) | set(rgba[2::4]), {0})
76 89
90 def test_rgba16_unorm_normalizes_all_channels_with_row_padding(self):
91 payload = struct.pack("<4H", 0, 65535, 32768, 257) + b"pad!"
92 payload += struct.pack("<4H", 65535, 0, 32767, 32768)
93 data = _dx10(1, 2, 11, payload, pitch=12)
94 self.assertEqual(dds.parse_dds_header(data)["format"], "RGBA16_UNORM")
95 self.assertEqual(dds.decode_dds(data)[2], bytes((
96 0, 255, 128, 1,
97 255, 0, 127, 128,
98 )))
99
100 def test_rgba16_snorm_maps_signed_extremes_and_zero(self):
101 payload = struct.pack("<4h", -32768, -32767, 0, 32767)
102 data = _dx10(1, 1, 13, payload)
103 self.assertEqual(dds.parse_dds_header(data)["format"], "RGBA16_SNORM")
104 self.assertEqual(dds.decode_dds(data)[2], bytes((0, 0, 128, 255)))
105
106 def test_rgba16_snorm_padded_rows_and_truncation(self):
107 payload = struct.pack("<4h", -16384, 16384, -32768, 32767) + b"pad!"
108 payload += struct.pack("<4h", 0, 0, 0, 0)
109 data = _dx10(1, 2, 13, payload, pitch=12)
110 self.assertEqual(dds.decode_dds(data)[2], bytes((64, 191, 0, 255, 128, 128, 128, 128)))
111 with self.assertRaises(dds.DdsError):
112 dds.decode_dds(_dx10(1, 1, 13, bytes(7)))
113
77 def test_truncated_rejected(self): 114 def test_truncated_rejected(self):
78 for dxgi, n in ((56, 7), (65, 3), (41, 15)): 115 for dxgi, n in ((56, 7), (65, 3), (41, 15)):
79 with self.assertRaises(dds.DdsError): 116 with self.assertRaises(dds.DdsError):
80 dds.decode_dds(_dx10(2, 2, dxgi, bytes(n))) 117 dds.decode_dds(_dx10(2, 2, dxgi, bytes(n)))
81 118
82 119
120def _opaque(*pairs):
121 """RGBA bytes for (red, green) pairs with blue 0 and alpha 255."""
122 return b"".join(bytes((r, g, 0, 255)) for r, g in pairs)
123
124
125class PackedAndIntegerTests(unittest.TestCase):
126 """Hand-built texels for the formats added by #2218, #2314, #2317, #2319, #2320, #2321, #2323 and #2324.
127
128 Each case is 2x2 with a padded row pitch, so the second row starts after the padding bytes,
129 and a payload one byte short must be refused.
130 """
131
132 def check(self, dxgi, fmt, row0, row1, pitch, expected):
133 payload = row0 + b"\xee" * (pitch - len(row0)) + row1
134 data = _dx10(2, 2, dxgi, payload, pitch=pitch)
135 self.assertEqual(dds.parse_dds_header(data)["format"], fmt)
136 self.assertEqual(dds.decode_dds(data), (2, 2, expected))
137 self.assertEqual(dds.dds_to_png_bytes(data), dds.encode_png(2, 2, expected))
138 with self.assertRaises(dds.DdsError):
139 dds.decode_dds(data[:-1])
140
141 def test_r9g9b9e5_sharedexp(self):
142 def texel(r, g, b, e):
143 return struct.pack("<I", r | (g << 9) | (b << 18) | (e << 27))
144 # value = mantissa * 2^(e - 24): (256, 128, 0) at e=16 is (1, 0.5, 0); 511/512 rounds to 255, 64/512 to 32,
145 # 1/512 to 0; 300 * 2^-4 saturates; e=0 is 2^-24 per step, so 511 * 2^-24 is still 0.
146 self.check(67, "R9G9B9E5_FLOAT",
147 texel(256, 128, 0, 16) + texel(511, 64, 1, 15),
148 texel(300, 0, 0, 20) + texel(511, 511, 511, 0), 12,
149 bytes((255, 128, 0, 255, 255, 32, 0, 255, 255, 0, 0, 255, 0, 0, 0, 255)))
150
151 def test_b5g6r5_unorm(self):
152 # Blue in bits 0-4, green 5-10, red 11-15; 5 and 6 bits widen by bit replication.
153 texels = struct.pack("<4H", 31 << 11, 63 << 5, 1, (16 << 11) | (32 << 5) | 16)
154 self.check(85, "B5G6R5_UNORM", texels[:4], texels[4:], 6,
155 bytes((255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 8, 255, 132, 130, 132, 255)))
156
157 def test_b5g5r5a1_unorm(self):
158 # Blue in bits 0-4, green 5-9, red 10-14, alpha bit 15.
159 texels = struct.pack("<4H", 0x8000 | (31 << 10), 0x7FFF, 31 << 5, 0x8001)
160 self.check(86, "B5G5R5A1_UNORM", texels[:4], texels[4:], 6,
161 bytes((255, 0, 0, 255, 255, 255, 255, 0, 0, 255, 0, 0, 0, 0, 8, 255)))
162
163 def test_r8g8_snorm(self):
164 # round((v / 127 / 2 + 0.5) * 255), with -128 clamped to -127 as for BC5_SNORM.
165 self.check(51, "RG8_SNORM", struct.pack("<4b", -128, -127, 0, 127), struct.pack("<4b", 64, -64, 1, -1), 6,
166 _opaque((0, 0), (128, 255), (192, 63), (129, 126)))
167
168 def test_r8g8_uint_and_sint(self):
169 self.check(50, "RG8_UINT", bytes((0, 255, 7, 128)), bytes((1, 2, 254, 3)), 5,
170 _opaque((0, 255), (7, 128), (1, 2), (254, 3)))
171 self.check(52, "RG8_SINT", struct.pack("<4b", -128, 127, 0, -1), struct.pack("<4b", 1, -127, 64, -64), 5,
172 _opaque((0, 255), (128, 127), (129, 1), (192, 64)))
173
174 def test_r8_snorm_uint_and_sint(self):
175 red = lambda *values: b"".join(bytes((v, 0, 0, 255)) for v in values) # noqa: E731
176 self.check(63, "R8_SNORM", struct.pack("<2b", -128, -127), struct.pack("<2b", 0, 127), 3, red(0, 0, 128, 255))
177 self.check(63, "R8_SNORM", struct.pack("<2b", 64, -64), struct.pack("<2b", 1, -1), 3, red(192, 63, 129, 126))
178 self.check(62, "R8_UINT", bytes((0, 255)), bytes((7, 128)), 3, red(0, 255, 7, 128))
179 self.check(64, "R8_SINT", struct.pack("<2b", -128, 127), struct.pack("<2b", -1, 0), 3, red(0, 255, 127, 128))
180
181 def test_r10g10b10a2_uint_and_typeless_read_like_unorm(self):
182 # R in bits 0-9, G 10-19, B 20-29, A 30-31; each field scaled to 0-255 from its own bit width.
183 def texel(r, g, b, a):
184 return struct.pack("<I", r | (g << 10) | (b << 20) | (a << 30))
185 row0, row1 = texel(1023, 0, 512, 3) + texel(0, 1023, 0, 1), texel(1, 2, 3, 0) + texel(511, 1022, 0, 2)
186 expected = bytes((255, 0, 128, 255, 0, 255, 0, 85, 0, 0, 1, 0, 127, 255, 0, 170))
187 for dxgi in (23, 24, 25): # TYPELESS, UNORM, UINT
188 with self.subTest(dxgi=dxgi):
189 self.check(dxgi, "RGBA8", row0, row1, 12, expected)
190
191
83if __name__ == "__main__": 192if __name__ == "__main__":
84 unittest.main() 193 unittest.main()
diff --git a/tests/test_dstorage_history.py b/tests/test_dstorage_history.py
index 77e8179d7..be00af80a 100644
--- a/tests/test_dstorage_history.py
+++ b/tests/test_dstorage_history.py
@@ -85,6 +85,58 @@ class RuntimeHistoryTest(unittest.TestCase):
85 self.assertEqual(bc7["historyEndpointConfirmedBits"][255][field], 0) 85 self.assertEqual(bc7["historyEndpointConfirmedBits"][255][field], 0)
86 self.assertLessEqual(abs(bc7["historyEndpoints"][255][field] - 128), 4) 86 self.assertLessEqual(abs(bc7["historyEndpoints"][255][field] - 128), 4)
87 87
88 def test_packed_tail_fits_against_decoded_bcpack_sibling(self):
89 # Mip 0 is zlib, mip 1 a self-contained BCPack stream and the packed tail (mips 2-4) starts its
90 # chains at history entry 255, whose alpha no raw or zlib sibling of the tail can show.
91 solid = bytes([0x40]) + bytes(15)
92 secret = (0, 0, 0, 128) * 6
93 tail = _encode_bc7_mode6_tiled(solid * 256, secret_entry=255, secret_ep=secret, ref_count=255)
94 with tempfile.TemporaryDirectory() as name:
95 pool = Path(name)/"bcpack-parent.ttpf"
96 record = _pack_etpf(128, 128, 4, 1, 98, 4096)
97 _write_custom_rds5_pool(pool, [record], [(7, 4096, tail), (7, 4096, _encode_bc7_mode6_tiled(solid * 256)),
98 (8, 16384, zlib.compress(solid * 1024))])
99 fits = {6: history.calib.Bc6hCalibrator(), 7: history.calib.Bc7Calibrator()}
100 history.calib.calibrate_from_pools([str(pool)], fits)
101 docs = {history.calib.CODEC_KEYS[c]: f.build_document()[0] for c, f in fits.items()}
102 history.extend_missing(docs, history.fit_slices([pool]))
103 bcpack = history.calib.bcpack
104 with self.assertRaises(bcpack.BcpackProvisionalError):
105 bcpack.decode(tail, 7, 4096, allow_provisional=True, history=docs)
106 history.fit_decoded_neighbors([pool], docs)
107 bc7 = docs["bc7"]
108 for field in (3, 7):
109 self.assertGreaterEqual(bc7["historyEndpointBits"][255][field], 4)
110 self.assertEqual(bc7["historyEndpointConfirmedBits"][255][field], 0)
111 self.assertLessEqual(abs(bc7["historyEndpoints"][255][field] - 128), 4)
112 self.assertEqual(bcpack.decode(tail, 7, 4096, allow_provisional=True, history=docs), solid * 256)
113
114 def test_packed_tail_fits_against_its_own_refused_stream(self):
115 # One BCPack stream holds the packed tail (blocks 0-255) and mip 1 (blocks 256-511). Chains from history
116 # entry 255 stay inside the tail, so the stream is refused and no fit reaches the entry, but mip 1 is
117 # determined and is the reference.
118 solid = bytes([0x40]) + bytes(15)
119 secret = (0, 0, 0, 128) * 6
120 stream = _encode_bc7_mode6_tiled(solid * 512, secret_entry=255, secret_ep=secret, ref_count=200)
121 with tempfile.TemporaryDirectory() as name:
122 pool = Path(name)/"one-stream.ttpf"
123 record = _pack_etpf(128, 128, 4, 1, 98, 4096)
124 _write_custom_rds5_pool(pool, [record], [(7, 8192, stream), (8, 16384, zlib.compress(solid * 1024))])
125 fits = {6: history.calib.Bc6hCalibrator(), 7: history.calib.Bc7Calibrator()}
126 history.calib.calibrate_from_pools([str(pool)], fits)
127 docs = {history.calib.CODEC_KEYS[c]: f.build_document()[0] for c, f in fits.items()}
128 history.extend_missing(docs, history.fit_slices([pool]))
129 bcpack = history.calib.bcpack
130 with self.assertRaises(bcpack.BcpackProvisionalError):
131 bcpack.decode(stream, 7, 8192, allow_provisional=True, history=docs)
132 history.fit_decoded_neighbors([pool], docs)
133 bc7 = docs["bc7"]
134 for field in (3, 7):
135 self.assertGreaterEqual(bc7["historyEndpointBits"][255][field], 4)
136 self.assertEqual(bc7["historyEndpointConfirmedBits"][255][field], 0)
137 self.assertLessEqual(abs(bc7["historyEndpoints"][255][field] - 128), 4)
138 self.assertEqual(bcpack.decode(stream, 7, 8192, allow_provisional=True, history=docs), solid * 512)
139
88 def test_build_resume_and_repair(self): 140 def test_build_resume_and_repair(self):
89 trainer = os.environ.get("LEONIDA_TEST_BCPACK_TRAINER") 141 trainer = os.environ.get("LEONIDA_TEST_BCPACK_TRAINER")
90 if not trainer and not shutil.which("cl" if os.name == "nt" else "c++"): 142 if not trainer and not shutil.which("cl" if os.name == "nt" else "c++"):
diff --git a/tests/test_indirect_clamp_telemetry.py b/tests/test_indirect_clamp_telemetry.py
index df73bf763..4e65ecf1d 100644
--- a/tests/test_indirect_clamp_telemetry.py
+++ b/tests/test_indirect_clamp_telemetry.py
@@ -47,9 +47,10 @@ def mesh_counter_ops(header):
47class TestIndirectClampTelemetry(unittest.TestCase): 47class TestIndirectClampTelemetry(unittest.TestCase):
48 def test_embedded_preclamp_mesh_counters(self): 48 def test_embedded_preclamp_mesh_counters(self):
49 src = Path(__file__).resolve().parents[1] / "runtime" / "src" 49 src = Path(__file__).resolve().parents[1] / "runtime" / "src"
50 # Active mesh records + records requesting y/z > 1; max y and max z before clamping. 50 # Active mesh records + records requesting y/z > 1; max y and max z before clamping. Then the dispatch
51 # records: wider than 65 535 groups in x, the widest x, cut at the device's limits, and all of them.
51 self.assertEqual(mesh_counter_ops((src / "indirect_clamp_spv.h").read_text(encoding="ascii")), 52 self.assertEqual(mesh_counter_ops((src / "indirect_clamp_spv.h").read_text(encoding="ascii")),
52 {(8, 234), (9, 234), (10, 239), (11, 239)}) 53 {(8, 234), (9, 234), (10, 239), (11, 239), (12, 234), (13, 239), (14, 234), (15, 234)})
53 54
54 55
55if __name__ == "__main__": 56if __name__ == "__main__":
diff --git a/tests/test_make_game_wave64.py b/tests/test_make_game_wave64.py
index 74d36ecbb..9ceb87c07 100644
--- a/tests/test_make_game_wave64.py
+++ b/tests/test_make_game_wave64.py
@@ -49,6 +49,76 @@ class SmallestMaxSubgroupTest(unittest.TestCase):
49 self.assertIsNone(make_game.smallest_max_subgroup("\tminSubgroupSize = 32\n")) 49 self.assertIsNone(make_game.smallest_max_subgroup("\tminSubgroupSize = 32\n"))
50 50
51 51
52def typed_device(name, kind, size):
53 """vulkaninfo's plain-text layout for one device as a real run prints it: deviceType just before deviceName."""
54 return ("VkPhysicalDeviceProperties:\n---------------------------\n"
55 f"\tdeviceType = PHYSICAL_DEVICE_TYPE_{kind}\n"
56 f"\tdeviceName = {name}\n"
57 "VkPhysicalDeviceVulkan13Properties:\n-----------------------------------\n"
58 "\tminSubgroupSize = "
59 f"{min(size, 32) if size >= 32 else size}\n"
60 f"\tmaxSubgroupSize = {size}\n")
61
62
63class CpuDeviceTest(unittest.TestCase):
64 """A CPU device (llvmpipe: maxSubgroupSize 8) does not decide when a GPU is listed: the runtime ranks it last."""
65
66 def test_llvmpipe_beside_a_wave64_gpu_is_left_out(self):
67 text = (typed_device("AMD Radeon RX 7900 XTX (RADV NAVI31)", "DISCRETE_GPU", 64)
68 + typed_device("AMD Ryzen 9 7950X3D (RADV RAPHAEL_MENDOCINO)", "INTEGRATED_GPU", 64)
69 + typed_device("llvmpipe (LLVM 23.1.5, 256 bits)", "CPU", 8))
70 self.assertEqual(make_game.smallest_max_subgroup(text), 64)
71 size, device, left_out = make_game.max_subgroup_decider(text)
72 self.assertEqual((size, device), (64, "AMD Radeon RX 7900 XTX (RADV NAVI31)"))
73 self.assertEqual(left_out, ["llvmpipe (LLVM 23.1.5, 256 bits)"])
74
75 def test_the_cpu_device_listed_first_is_left_out_too(self):
76 text = typed_device("llvmpipe", "CPU", 8) + typed_device("GPU", "DISCRETE_GPU", 64)
77 self.assertEqual(make_game.max_subgroup_decider(text), (64, "GPU", ["llvmpipe"]))
78
79 def test_a_32_wide_gpu_still_decides(self):
80 text = (typed_device("A", "DISCRETE_GPU", 64) + typed_device("B", "INTEGRATED_GPU", 32)
81 + typed_device("llvmpipe", "CPU", 8))
82 self.assertEqual(make_game.max_subgroup_decider(text), (32, "B", ["llvmpipe"]))
83
84 def test_only_a_cpu_device_decides(self):
85 self.assertEqual(make_game.max_subgroup_decider(typed_device("llvmpipe", "CPU", 8)), (8, "llvmpipe", []))
86
87 def test_a_cpu_device_without_a_size_does_not_make_it_unknown(self):
88 text = (typed_device("GPU", "DISCRETE_GPU", 64)
89 + "VkPhysicalDeviceProperties:\n\tdeviceType = PHYSICAL_DEVICE_TYPE_CPU\n"
90 "\tdeviceName = old lavapipe\n")
91 self.assertEqual(make_game.smallest_max_subgroup(text), 64)
92 # ...but a GPU without one still does.
93 old_gpu = ("VkPhysicalDeviceProperties:\n\tdeviceType = PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU\n"
94 "\tdeviceName = old GPU\n")
95 self.assertIsNone(make_game.smallest_max_subgroup(text + old_gpu))
96
97 def test_json_key_order(self):
98 text = ('{"VkPhysicalDeviceProperties": {\n\t\t"deviceName": "llvmpipe",\n'
99 '\t\t"deviceType": "VK_PHYSICAL_DEVICE_TYPE_CPU"},\n'
100 '\t"VkPhysicalDeviceSubgroupSizeControlProperties": {\n\t\t"maxSubgroupSize": 8}}\n'
101 '{"VkPhysicalDeviceProperties": {\n\t\t"deviceName": "GPU",\n'
102 '\t\t"deviceType": "VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU"},\n'
103 '\t"VkPhysicalDeviceSubgroupSizeControlProperties": {\n\t\t"maxSubgroupSize": 64}}')
104 self.assertEqual(make_game.max_subgroup_decider(text), (64, "GPU", ["llvmpipe"]))
105
106 def test_auto_logs_the_deciding_device_and_the_left_out_one(self):
107 text = typed_device("GPU", "DISCRETE_GPU", 64) + typed_device("llvmpipe", "CPU", 8)
108 lines = []
109
110 def fake_run(args, **kw):
111 if os.path.basename(str(args[-1])) == "vk_subgroup_info.py":
112 return subprocess.CompletedProcess(args, 0, stdout='{"native64": true}', stderr="")
113 return subprocess.CompletedProcess(args, 0, stdout=text, stderr="")
114 with mock.patch.object(make_game.shutil, "which", return_value="vulkaninfo"), \
115 mock.patch.object(make_game.subprocess, "run", side_effect=fake_run), \
116 mock.patch.object(make_game, "log", lambda *a: lines.append(" ".join(map(str, a)))):
117 self.assertFalse(make_game.wave64_emulate("auto"))
118 self.assertTrue(any("llvmpipe" in line and "left out" in line for line in lines), lines)
119 self.assertTrue(any("is 64 (GPU)" in line and "emulation off" in line for line in lines), lines)
120
121
52class Wave64EmulateTest(unittest.TestCase): 122class Wave64EmulateTest(unittest.TestCase):
53 """wave64_emulate(): on and off are taken as given; auto asks vulkaninfo and falls back to on.""" 123 """wave64_emulate(): on and off are taken as given; auto asks vulkaninfo and falls back to on."""
54 124
diff --git a/tests/test_tex_export.py b/tests/test_tex_export.py
index eef043f68..e6e5e2d59 100644
--- a/tests/test_tex_export.py
+++ b/tests/test_tex_export.py
@@ -219,7 +219,7 @@ def test_export_picks_the_top_mip_placement_and_writes_dds(eq, tmp_path, fmt, na
219def test_fmt_reuses_the_indexer_table_without_12_byte_rgb32(): 219def test_fmt_reuses_the_indexer_table_without_12_byte_rgb32():
220 from tex_headers import FMT_INFO 220 from tex_headers import FMT_INFO
221 assert T.FMT == {f: v for f, v in FMT_INFO.items() if f not in (6, 7, 8)} 221 assert T.FMT == {f: v for f, v in FMT_INFO.items() if f not in (6, 7, 8)}
222 assert len(T.FMT) == 56 222 assert len(T.FMT) == 57
223 223
224 224
225@pytest.mark.parametrize("fmt", sorted(T.FMT)) 225@pytest.mark.parametrize("fmt", sorted(T.FMT))
@@ -478,14 +478,30 @@ def test_packed_r10g10b10a2_writes_a_png(eq, tmp_path, monkeypatch, capsys):
478 assert read_png(stem.with_suffix(".png")) == (2, 1, bytes((255, 0, 0, 255, 0, 0, 255, 85))) 478 assert read_png(stem.with_suffix(".png")) == (2, 1, bytes((255, 0, 0, 255, 0, 0, 255, 85)))
479 479
480 480
481def test_shared_exponent_r9g9b9e5_writes_a_png(eq, tmp_path, monkeypatch, capsys):
482 # The indexer's table lists DXGI 67, so the export reaches dds_png instead of stopping at "unsupported format".
483 # Texels (R, G, B mantissa, exponent): (256, 128, 0, 16) -> 1.0, 0.5, 0; (511, 64, 1, 15) -> 511/512, 1/8, 1/512.
484 eq(4)
485 packed = struct.pack("<II", 256 | (128 << 9) | (16 << 27), 511 | (64 << 9) | (1 << 18) | (15 << 27))
486 carve = str(tmp_path / "carve")
487 write_blob(carve, "x.rpf", 0x1000, packed + bytes(4096 - len(packed)))
488 t = texture(67, "R9G9B9E5_SHAREDEXP", 2, 1, mips=1)
489 out, code, text = png_main(tmp_path, monkeypatch, capsys, [t], carve, "--png")
490 assert code is None
491 assert text.splitlines() == ["1 textures: {'ok:first': 1} -> " + str(out), "png: {'written': 1}"]
492 stem = out / "x.rpf" / f"{0xABC:012x}_3_2x1_R9G9B9E5_SHAREDEXP"
493 assert stem.with_suffix(".dds").read_bytes()[148:] == packed
494 assert read_png(stem.with_suffix(".png")) == (2, 1, bytes((255, 128, 0, 255, 255, 32, 0, 255)))
495
496
481def test_undecodable_format_keeps_the_dds_and_counts_unsupported(eq, tmp_path, monkeypatch, capsys): 497def test_undecodable_format_keeps_the_dds_and_counts_unsupported(eq, tmp_path, monkeypatch, capsys):
482 # R10G10B10A2_UNORM_SRGB: dds_png has no decoder for its DXGI code 498 # R8G8B8A8_UINT: dds_png has no decoder for its DXGI code
483 carve, expected = build_case(eq, tmp_path, 25, top_first=True) 499 carve, expected = build_case(eq, tmp_path, 30, top_first=True)
484 t = texture(25, "R10G10B10A2_UNORM_SRGB", 64, 64, mips=2) 500 t = texture(30, "R8G8B8A8_UINT", 64, 64, mips=2)
485 out, code, text = png_main(tmp_path, monkeypatch, capsys, [t], carve, "--png") 501 out, code, text = png_main(tmp_path, monkeypatch, capsys, [t], carve, "--png")
486 assert code is None # main() returns None, so the process exits 0 502 assert code is None # main() returns None, so the process exits 0
487 assert tree(out) == ["export_log.json", f"x.rpf{os.sep}{0xABC:012x}_3_64x64_R10G10B10A2_UNORM_SRGB.dds"] 503 assert tree(out) == ["export_log.json", f"x.rpf{os.sep}{0xABC:012x}_3_64x64_R8G8B8A8_UINT.dds"]
488 assert (out / "x.rpf" / f"{0xABC:012x}_3_64x64_R10G10B10A2_UNORM_SRGB.dds").read_bytes()[148:] == expected 504 assert (out / "x.rpf" / f"{0xABC:012x}_3_64x64_R8G8B8A8_UINT.dds").read_bytes()[148:] == expected
489 assert json.loads((out / "export_log.json").read_text(encoding="utf-8"))[0]["export"]["png"] == "unsupported" 505 assert json.loads((out / "export_log.json").read_text(encoding="utf-8"))[0]["export"]["png"] == "unsupported"
490 assert text.splitlines()[1:] == ["png: {'unsupported': 1}"] 506 assert text.splitlines()[1:] == ["png: {'unsupported': 1}"]
491 507
@@ -495,7 +511,7 @@ def test_mixed_run_counts_each_kind(eq, tmp_path, monkeypatch, capsys):
495 with open(os.path.join(carve, "x.rpf", f"{0x1000:012x}.bin"), "rb") as f: 511 with open(os.path.join(carve, "x.rpf", f"{0x1000:012x}.bin"), "rb") as f:
496 write_blob(carve, "x.rpf", 0x2000, f.read()) # same 4 bpe size, so the equation is already in place 512 write_blob(carve, "x.rpf", 0x2000, f.read()) # same 4 bpe size, so the equation is already in place
497 textures = [texture(28, "R8G8B8A8_UNORM", 64, 64, mips=2), 513 textures = [texture(28, "R8G8B8A8_UNORM", 64, 64, mips=2),
498 texture(25, "R10G10B10A2_UNORM_SRGB", 64, 64, mips=2, gpu=0x2000), 514 texture(30, "R8G8B8A8_UINT", 64, 64, mips=2, gpu=0x2000),
499 texture(9999, "X", 4, 4, 1, gpu=0x3000)] 515 texture(9999, "X", 4, 4, 1, gpu=0x3000)]
500 out, code, text = png_main(tmp_path, monkeypatch, capsys, textures, carve, "--png") 516 out, code, text = png_main(tmp_path, monkeypatch, capsys, textures, carve, "--png")
501 assert text.splitlines()[1] == "png: {'written': 1, 'unsupported': 1}" 517 assert text.splitlines()[1] == "png: {'written': 1, 'unsupported': 1}"
diff --git a/tests/test_tex_headers.py b/tests/test_tex_headers.py
index 836f55ca2..2b0af6f29 100644
--- a/tests/test_tex_headers.py
+++ b/tests/test_tex_headers.py
@@ -102,6 +102,12 @@ class TestGFX10FormatMapping(unittest.TestCase):
102 with self.assertRaises(ValueError): 102 with self.assertRaises(ValueError):
103 tex_headers.dxgi_to_gfx10(99999) 103 tex_headers.dxgi_to_gfx10(99999)
104 104
105 def test_shared_exponent_format_is_indexed_and_sized(self):
106 # dds_png decodes DXGI 67; without these entries the indexer drops it and tex_export --png never sees it.
107 self.assertEqual(tex_headers.DXGI[67], "R9G9B9E5_SHAREDEXP")
108 self.assertEqual(tex_headers.FMT_INFO[67], (4, 1))
109 self.assertEqual(tex_headers.calc_mip_level_bytes(3, 2, fmt=67), 24)
110
105 def test_dxgi_dict_integrity(self): 111 def test_dxgi_dict_integrity(self):
106 for dxgi_id, name in tex_headers.DXGI.items(): 112 for dxgi_id, name in tex_headers.DXGI.items():
107 self.assertIsInstance(dxgi_id, int) 113 self.assertIsInstance(dxgi_id, int)
diff --git a/tests/test_translate.py b/tests/test_translate.py
index fe2df1288..24299f6d1 100644
--- a/tests/test_translate.py
+++ b/tests/test_translate.py
@@ -13,8 +13,8 @@ from pathlib import Path
13import pytest 13import pytest
14 14
15import rdna2spirv 15import rdna2spirv
16from conftest import (EMPTY_DXBC, KNOWN_VAL_ISSUES, ROOT, SAMPLE_DXBC, Shader, make_dxbc, mesh_psv0_chunk, 16from conftest import (EMPTY_DXBC, KNOWN_VAL_ISSUES, ROOT, SAMPLE_DXBC, TEXT_ONLY_MARK, Shader, make_dxbc,
17 requires_tools, signature_chunk) 17 mesh_psv0_chunk, requires_tools, signature_chunk)
18 18
19pytestmark = requires_tools 19pytestmark = requires_tools
20 20
@@ -64,6 +64,24 @@ def test_gpu_samples_translate_and_validate(path, make_shader):
64 shader.validate(shader.translate(), KNOWN_VAL_ISSUES.get(stem)) 64 shader.validate(shader.translate(), KNOWN_VAL_ISSUES.get(stem))
65 65
66 66
67def test_text_only_mark_is_spelled_as_in_the_gpu_runner():
68 """conftest.Shader and scripts/run_gpu_tests.py have to agree on the comment line that marks a sample llvm-mc
69 cannot assemble: with two spellings, a marked sample is handed to llvm-mc here and fails."""
70 runner = Path(ROOT, "scripts", "run_gpu_tests.py").read_text(encoding="utf-8")
71 assert f'\nTEXT_ONLY_MARK = "{TEXT_ONLY_MARK}"\n' in runner
72
73
74def test_only_a_marked_sample_skips_llvm_mc(make_shader):
75 """A sample with the text-only line becomes its own listing, comment lines dropped, whatever llvm-mc makes of
76 its instructions; the same lines without it still go to llvm-mc and fail there."""
77 body = "v_mov_b32 v1, 1.0\n v_no_such_instruction v0, v1\n\ns_endpgm\n"
78 shader = make_shader(f"; a sample llvm-mc cannot assemble\n{TEXT_ONLY_MARK}\n{body}", "cs_text_only")
79 assert shader.path.read_text(encoding="utf-8").splitlines()[1:] == [
80 "\tv_mov_b32 v1, 1.0", "\tv_no_such_instruction v0, v1", "\ts_endpgm"]
81 with pytest.raises(AssertionError, match="v_no_such_instruction"):
82 make_shader(body, "cs_not_marked")
83
84
67@pytest.mark.parametrize("case", sorted(SUPPORTED)) 85@pytest.mark.parametrize("case", sorted(SUPPORTED))
68def test_supported_instruction(case, make_shader): 86def test_supported_instruction(case, make_shader):
69 shader = make_shader(program(SUPPORTED[case])) 87 shader = make_shader(program(SUPPORTED[case]))