Skip to content
Closed
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
9 changes: 9 additions & 0 deletions docs/design.md
Original file line number Diff line number Diff line change
Expand Up @@ -606,6 +606,15 @@ with that reason instead of writing empty `.s` files. To disassemble by hand ins
LLVM_MC=/usr/lib/llvm-21/bin/llvm-mc python3 -I <repo>/tools/shader_disasm.py <work>/shaders/fssm
```

llvm-mc lists the lane-mask operands of a VALU instruction for the wave size it is told, and wave32 is its default for
these CPUs: a compare's destination as `s8` or `vcc_lo`, where a wave64 program writes `s[8:9]` or `vcc`. For a wave64
program `shader_disasm.disasm()` therefore adds `-mattr=-wavefrontsize32,+wavefrontsize64`. `shader_disasm.py` takes
the wave size from the FSSM header, `fspx_unpack.py --disasm` and `shader_library.py --disasm` from the program's
dispatch state; a graphics program of the pipeline library has none and keeps the default. Only those operands differ
between the two listings (llvm-mc 23.1.5: the compares, `v_cndmask`, the carry instructions, `v_div_scale` and
`v_mad_[ui]64_[ui]32`); the instructions and their encodings are the same, and `--backend python` prints the same
forms. `tests/test_shader_disasm.py` and `tests/semantic/test_disasm_wave64_mask_pair.py` check it.

Code starts at the u32 at FSSM offset 0xC0 (the code-section offset) plus 0x28 bytes into that section, and ends at the
last `s_endpgm`. Use `--mcpu gfx1013`. Over the whole 26,503-blob 1.0.2.1 corpus (`shader_disasm.py` at `d90444f2`,
llvm-mc 23.1.5, data blocks excluded as below) gfx1013 decodes all 26,503 blobs with no invalid word; gfx1010, gfx1011
Expand Down
81 changes: 81 additions & 0 deletions tests/semantic/test_disasm_wave64_mask_pair.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
"""A wave64 program listed by tools/shader_disasm.py is translated as the program it is.

llvm-mc lists the lane-mask operands of a VALU instruction for the wave size it is told, and wave32 is its default
for the CPUs used here. Listed that way, the compare below writes `s8` where a wave64 writes s[8:9]; the translator
then leaves s9 as it was, and `s_mov_b64 exec, s[8:9]` takes lanes 32..63 from the old word. shader_disasm.disasm()
gets the wave size from the caller (the FSSM header, or the dispatch state of an FSPX or pipeline-library program)
and has to pass it on to llvm-mc, as it already does to the Python decoder.

The program is hand-written, no game data. The Python decoder case needs nothing else; the llvm-mc case is skipped
without an llvm-mc that has the AMDGPU target (LLVM_MC, tools/mc_command.py).

python -I tests/semantic/test_disasm_wave64_mask_pair.py
"""
import os
import sys
import unittest

HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(os.path.dirname(HERE))
sys.dont_write_bytecode = True
sys.path.insert(0, os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools"))
sys.path.insert(0, HERE)

import shader_disasm # noqa: E402
import spirv_mini_interp as si # noqa: E402
from test_fspx_wave_size import VSHARP, translate # noqa: E402

# Each instruction with its words as llvm-mc 23.1.5 assembles it (gfx1013, +wavefrontsize64).
PROGRAM = (
("s_mov_b32 s9, 0x100001", "ff0389be 01001000"), # what s9 held before: lanes 32 and 52
("v_mov_b32_e32 v5, 7", "87020a7e"),
("v_cmp_gt_u32_e64 s[8:9], 40, v0", "0800c4d4 a8000202"), # lanes 0..39
("s_mov_b64 exec, s[8:9]", "0804febe"),
("v_mov_b32_e32 v5, 9", "89020a7e"),
("s_mov_b64 exec, -1", "c104febe"),
("v_lshlrev_b32_e32 v6, 2, v0", "82000c34"),
("buffer_store_dword v5, v6, s[0:3], 0 offen", "001070e0 06050080"),
("s_endpgm", "000081bf"),
)
CODE = bytes.fromhex("".join(words for _, words in PROGRAM))
EXPECTED = [9] * 40 + [7] * 24
PAIR = "\tv_cmp_gt_u32_e64 s[8:9], 40, v0 "


class Wave64MaskPair(unittest.TestCase):
def run_listing(self, listing):
"""Translate the listing as a wave64 compute program and run its 64 lanes: the word each one stores."""
body = [ln.strip() for ln in listing.splitlines() if ln.startswith("\t")]
self.assertEqual([ln.split()[0] for ln in body], [text.split()[0] for text, _ in PROGRAM])
spv, wave64 = translate(body[:-1], wave32=False)
self.assertTrue(wave64)
memory = {}
si.run_workgroup(spv, 64, 64, inputs_for=lambda i: {
"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%local_index": i, "%sg_lane": i,
}, push_constants=VSHARP + [0] * 32, memory=memory)
return [memory.get(4 * lane) for lane in range(64)]

def test_python_decoder_listing(self):
asm, bad, _ = shader_disasm.disasm(CODE, "gfx1013", backend="python", wave32=False)
self.assertEqual(bad, 0)
self.assertEqual(self.run_listing(asm), EXPECTED)
self.assertIn(PAIR, asm)

def test_llvm_mc_listing(self):
asm, bad, err = shader_disasm.disasm(CODE, "gfx1013", wave32=False)
if not asm.strip():
self.skipTest("needs llvm-mc with the AMDGPU target: " + (err.strip().splitlines() or ["no output"])[0])
self.assertEqual(bad, 0, err)
self.assertEqual(self.run_listing(asm), EXPECTED)
self.assertIn(PAIR, asm)

def test_wave32_listing_keeps_single_registers(self):
asm, _, _ = shader_disasm.disasm(CODE, "gfx1013", backend="python", wave32=True)
self.assertIn("v_cmp_gt_u32_e64 s8, 40, v0", asm)
asm, _, _ = shader_disasm.disasm(CODE, "gfx1013", wave32=True)
if asm.strip(): # with an llvm-mc: the default listing is unchanged
self.assertIn("v_cmp_gt_u32_e64 s8, 40, v0", asm)


if __name__ == "__main__":
unittest.main()
20 changes: 18 additions & 2 deletions tests/test_fspx_unpack.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,12 +179,12 @@ def run_tool(self, *argv):
code = fspx_unpack.main(list(argv))
return code, out.getvalue(), err.getvalue()

def disassemble(self, body):
def disassemble(self, body, state=None):
tmp = tempfile.TemporaryDirectory()
self.addCleanup(tmp.cleanup)
src = os.path.join(tmp.name, "one.fspx")
with open(src, "wb") as f:
f.write(make_fspx([(0, kind0()), (6, program())]))
f.write(make_fspx([(0, state or kind0()), (6, program())]))
mc = os.path.join(tmp.name, "fake_mc.py")
with open(mc, "w", encoding="utf-8", newline="\n") as f:
f.write(body)
Expand Down Expand Up @@ -235,6 +235,22 @@ def test_clean_disassembly_keeps_listing(self):
self.assertIn("0 invalid words", listing)
self.assertIn("\ts_endpgm", listing)

def test_disassembler_is_told_the_wave_size_of_the_dispatch_state(self):
# The stand-in prints the -mattr option it was started with. A wave64 program's lane masks are listed as
# register pairs only when llvm-mc is told the wave size; wave32 is its default and gets no option.
fake = ("import sys\n"
"sys.stdin.read()\n"
"attrs = [a for a in sys.argv[1:] if a.startswith('-mattr')]\n"
"print('\\ts_endpgm ; ' + (' '.join(attrs) or 'no -mattr'))\n")
for wave32, expected in ((False, "-mattr=-wavefrontsize32,+wavefrontsize64"), (True, "no -mattr")):
with self.subTest(wave32=wave32):
result, out = self.disassemble(fake, kind0(wave32=wave32))
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
with open(os.path.join(out, "index.json"), encoding="utf-8") as f:
self.assertEqual(json.load(f)[0]["wave32"], wave32)
with open(os.path.join(out, "disasm", "one.s"), encoding="utf-8") as f:
self.assertIn(f"\ts_endpgm ; {expected}\n", f.read())

def test_dll_like_file(self):
c = Containers().container()
with tempfile.TemporaryDirectory() as t:
Expand Down
34 changes: 32 additions & 2 deletions tests/test_shader_library.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import json
import os
import struct
import subprocess
import sys
import tempfile
import unittest
Expand Down Expand Up @@ -40,9 +41,9 @@ def prog(tag, body=2):
return code + CODE_END * ((-len(code)) % 256 // 4)


def kind0(threads=(8, 8, 1), rsrc2=0xB8A):
def kind0(threads=(8, 8, 1), rsrc2=0xB8A, wave32=False):
x, y, z = threads
return struct.pack("<7I", 0x4005CF00, 0x6C090102, 0, x | y << 16, z, 0x402C0343, rsrc2)
return struct.pack("<7I", 0x4005CF00, 0x6C090102, 0, x | y << 16, z | wave32 << 20, 0x402C0343, rsrc2)


def layout_blob(kind, digest, records=1):
Expand Down Expand Up @@ -428,6 +429,35 @@ def test_compute_hash_filter_keeps_distinct_states(self):
self.assertEqual(f.read(), state)
with open(os.path.join(out, "library.json"), encoding="utf-8") as f:
self.assertEqual([e["program"] for e in json.load(f)["compute"][:3]], [*names, names[0]])
def test_disassembler_is_told_the_wave_size_of_each_compute_state(self):
# The stand-in for llvm-mc prints the -mattr option it was started with. A compute program is listed for the
# wave size of its dispatch state; a graphics program has no state and keeps llvm-mc's default (wave32).
fake = ("import sys\n"
"sys.stdin.read()\n"
"attrs = [a for a in sys.argv[1:] if a.startswith('-mattr')]\n"
"print('\\ts_endpgm ; ' + (' '.join(attrs) or 'no -mattr'))\n")
lib = build([(NONE, NONE, {0: (2, 2)})], [(0, NONE, 0, NONE), (1, NONE, 1, NONE)],
[kind0(), kind0(wave32=True), layout_blob(2, D_PS)], [prog(1), prog(2), prog(3)])
with tempfile.TemporaryDirectory() as tmp:
src = os.path.join(tmp, "lib.bin")
with open(src, "wb") as f:
f.write(lib)
mc = os.path.join(tmp, "fake_mc.py")
with open(mc, "w", encoding="utf-8", newline="\n") as f:
f.write(fake)
out = os.path.join(tmp, "out")
env = dict(os.environ, LLVM_MC=f'"{sys.executable}" "{mc}"')
result = subprocess.run([sys.executable, "-I", os.path.join(ROOT, "tools", "shader_library.py"),
src, "--out", out, "--disasm", "--jobs", "1"],
capture_output=True, text=True, env=env)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
names = [sl.program_name(0, {"cs"}), sl.program_name(1, {"cs"}), sl.program_name(2, {"ps"})]
with open(os.path.join(out, "index.json"), encoding="utf-8") as f:
self.assertEqual([(e["file"], e.get("wave32")) for e in json.load(f)],
[(names[0] + ".dxbc", False), (names[1] + ".dxbc", True), (names[2] + ".dxbc", None)])
for name, expected in zip(names, ("-mattr=-wavefrontsize32,+wavefrontsize64", "no -mattr", "no -mattr")):
with open(os.path.join(out, "disasm", name + ".s"), encoding="utf-8") as f:
self.assertIn(f"\ts_endpgm ; {expected}\n", f.read(), name)

def test_carve_names_sources_and_copies_containers(self):
with tempfile.TemporaryDirectory() as tmp:
Expand Down
Loading