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
84 changes: 84 additions & 0 deletions tests/test_shader_disasm_input_lines.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
"""shader_disasm.disasm() hands llvm-mc its input in lines of at most 64 bytes, never as one long line.

llvm-mc slows down sharply on one long input line: a 90 KB program took 58.6 s as a single line and 0.2 s in lines
of 64 bytes, with byte-identical disassembly (only the line/column numbers in its diagnostics change). The pipeline
library step disassembles 2,684 programs this way, so one line per program made it take hours.

subprocess.run is stubbed, so this needs no llvm-mc and no game data: it checks the text llvm-mc would receive.

python -I tests/test_shader_disasm_input_lines.py
"""
import os
import subprocess
import sys
import unittest

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.join(ROOT, "tools"))
os.environ.setdefault("LLVM_MC", "llvm-mc") # only builds the command line; nothing is started
import shader_disasm # noqa: E402


class InputLinesTest(unittest.TestCase):
def capture(self, code: bytes) -> str:
"""The `input` text disasm() passes to llvm-mc for `code`."""
seen = {}

def fake_run(cmd, input=None, **kwargs):
seen["input"] = input
return subprocess.CompletedProcess(cmd, 0, stdout="\ts_endpgm\n", stderr="")

real = shader_disasm.subprocess.run
shader_disasm.subprocess.run = fake_run
try:
asm, bad, err = shader_disasm.disasm(code, "gfx1013")
finally:
shader_disasm.subprocess.run = real
self.assertEqual((asm, bad, err), ("\ts_endpgm\n", 0, ""))
return seen["input"]

@staticmethod
def tokens(text: str) -> list:
return text.split()

def test_long_program_is_split_into_lines_of_64_bytes(self):
code = bytes(range(256)) * 40 # 10,240 bytes
text = self.capture(code)
lines = text.split("\n")
self.assertEqual(len(lines), 160)
self.assertTrue(all(len(line.split(" ")) == 64 for line in lines), "every line holds 64 bytes")
self.assertEqual(self.tokens(text), [f"0x{b:02x}" for b in code], "the same bytes, in order")

def test_partial_last_line(self):
code = bytes(range(100))
lines = self.capture(code).split("\n")
self.assertEqual([len(line.split(" ")) for line in lines], [64, 36])

def test_short_input_stays_one_line(self):
# The probe (s_endpgm) and any program of up to 64 bytes go on exactly as before.
self.assertEqual(self.capture(shader_disasm.ENDPGM), shader_disasm.PROBE)
code = bytes(range(64))
self.assertEqual(self.capture(code), " ".join(f"0x{b:02x}" for b in code))

def test_no_empty_or_trailing_lines(self):
for size in (1, 63, 64, 65, 128, 129):
with self.subTest(size=size):
text = self.capture(bytes(size))
self.assertFalse(text.endswith("\n"))
self.assertNotIn("\n\n", text)
self.assertEqual(len(self.tokens(text)), size)

def test_invalid_offsets_maps_multiline_diagnostics(self):
# Each line holds 64 bytes (5 characters per "0xNN " token).
err = (
"<stdin>:1:1: warning: invalid instruction encoding\n"
"<stdin>:1:21: warning: invalid instruction encoding\n"
"<stdin>:2:1: warning: invalid instruction encoding\n"
"<stdin>:2:21: warning: invalid instruction encoding\n"
"<stdin>:3:41: warning: invalid instruction encoding\n"
)
self.assertEqual(shader_disasm.invalid_offsets(err), {0, 4, 64, 68, 136})


if __name__ == "__main__":
unittest.main()
15 changes: 10 additions & 5 deletions tools/shader_disasm.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,9 @@ def probe(mcpu: str) -> None:
f"{install_hint()}")


LINE_BYTES = 64


def disasm(code: bytes, mcpu: str, backend: str = "llvm-mc", wave32: bool = True):
if backend == "python":
asm, bad = rdna2_decode.disasm_bytes(code, mcpu=mcpu, wave32=wave32)
Expand All @@ -102,7 +105,9 @@ def disasm(code: bytes, mcpu: str, backend: str = "llvm-mc", wave32: bool = True

def run_mc(code: bytes, mcpu: str):
"""One llvm-mc pass over `code`: (listing, invalid word count, stderr), or ("", count, reason) when it failed."""
text = " ".join(f"0x{b:02x}" for b in code)
# 64 bytes per line: llvm-mc slows down sharply on one long input line (a 90 KB program took 58.6 s as one line
# and 0.2 s split like this, with byte-identical output); invalid_offsets() maps (line, col) back to byte offsets.
text = "\n".join(" ".join(f"0x{b:02x}" for b in code[i:i + LINE_BYTES]) for i in range(0, len(code), LINE_BYTES))
try:
p = subprocess.run(MC + ["--disassemble", f"-triple={TRIPLE}", f"-mcpu={mcpu}", "-show-encoding"],
input=text, capture_output=True, text=True, errors="replace",
Expand All @@ -116,17 +121,17 @@ def run_mc(code: bytes, mcpu: str):


ENCODING = re.compile(r"; encoding: \[([^\]]*)\]")
INVALID_AT = re.compile(r":1:(\d+): warning: invalid instruction encoding")
INVALID_AT = re.compile(r":(\d+):(\d+): warning: invalid instruction encoding")
VOPC = 0x3E # bits 31..25 of a VOPC word
DPP_SRC0 = (250, 233, 234) # the src0 field of a DPP16, DPP8 and DPP8-with-fi word
STAND_IN = 0x10 # VOP2 v_max_f32: takes the same DPP second word, and llvm-mc decodes it
STAND_IN_TEXT = "v_max_f32_dpp v0, "


def invalid_offsets(err: str) -> set:
"""Byte offsets llvm-mc rejected: its warning names the column of the word in the one line of 5-character
"0xNN " tokens it was given."""
return {(int(col) - 1) // 5 for col in INVALID_AT.findall(err)}
"""Byte offsets llvm-mc rejected: its warning names the 1-based line and column of the word in the
LINE_BYTES-per-line stream of 5-character "0xNN " tokens it was given."""
return {(int(line) - 1) * LINE_BYTES + (int(col) - 1) // 5 for line, col in INVALID_AT.findall(err)}


def vopc_dpp_words(code: bytes, offsets) -> dict:
Expand Down