#!/usr/bin/env python3 """Charge a MAME trace of the DL-1425 program by the manual's timing rules. Reads a trace written by ``scripts/mame_lle_trace.py`` (one ``tracelog`` line per instruction, ending ``t=``), decodes the word at each ``pc`` from ``dl-1425.bin`` (read in place, SHA-1 checked), and charges it by the Information Manual's rules (tables 3-3 and section 3.8.1, page 4-6 example): - multiply/ALU: 1 cycle; 2 with a RAM write (``Y = aT[l]``, ``Y = y[l]``, any ``Z``); ``x = X`` forms 2 outside the cache, 1 inside; - special function (``if CON F2``, ``ifc``), short immediate, ``do``: 1; - data moves and ``R = N``: 2; ``redo``: 2; ``goto``/``call``/``return``: 2; a conditional qualifier with its branch: 3; ``icall``: 3; - cache: the first pass runs at normal (out-of-cache) timing except its last instruction, which takes 2; later passes run at in-cache timing, except the last instruction of the last pass, which runs at out-of-cache timing. MAME's cost of an instruction is the difference of ``totalcycles`` between its line and the next. The output lists every opcode class where the two differ, and the sample period measured between successive visits of ``--marker`` (default 0x0525, an address the main loop passes once per sample). python -I scripts/cycle_audit.py tests/mame_traces/tone/dsp.trace This is a measuring tool, not emulator code: it charges, it does not execute. """ from __future__ import annotations import os import argparse import collections import hashlib import re import struct import sys import zipfile from pathlib import Path def _find_set(name: str = "qsound.zip") -> Path: """The device set, searched for in the MAME_ROMPATH folders (';'-separated).""" for folder in os.environ.get("MAME_ROMPATH", "").split(";"): if folder and (Path(folder) / name).exists(): return Path(folder) / name sys.exit(f"{name} not found: set MAME_ROMPATH to the folder(s) holding it") SET = None # found at run time by _find_set() SHA1 = "555f50fe5cdf127619da7d854c03f4a244a0c501" LINE = re.compile(r"^([0-9A-F]{4}): pt=.* t=(\d+)$") RAM_WRITE = {0x04, 0x05, 0x14, 0x15, 0x1C, 0x1D} # Y = a1[l], Z forms, Y = y[l], Y = a0[l] ROM_READ = {0x19, 0x1B, 0x1F} # y = aT x = X, y = Y x = X (2 out, 1 in) ONE_CYCLE = {0x02, 0x03, 0x06, 0x07, 0x12, 0x13, 0x16, 0x17} DATA_MOVE = {0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0F} BRANCH = {0x00, 0x01, 0x10, 0x11, 0x18} def cost(word: int, in_cache: bool) -> int: kind = word >> 11 if kind in RAM_WRITE or kind in DATA_MOVE or kind in BRANCH: return 2 if kind in ROM_READ: return 1 if in_cache else 2 if kind in ONE_CYCLE: return 1 if kind == 0x0E: return 1 if (word >> 7) & 15 else 2 if kind == 0x1A: return 3 # if CON + its branch, or icall raise ValueError(f"reserved opcode {word:04X}") def label(word: int) -> str: kind = word >> 11 if kind == 0x0E: return "do" if (word >> 7) & 15 else "redo" return f"T={kind:05b}" def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("trace", type=Path) parser.add_argument("--marker", type=lambda text: int(text, 0), default=0x0525) args = parser.parse_args() data = zipfile.ZipFile(SET or _find_set()).read("dl-1425.bin") if hashlib.sha1(data).hexdigest() != SHA1: print("dl-1425.bin does not match its SHA-1") return 1 words = struct.unpack(f"<{len(data) // 2}H", data) # Each instruction is two lines: the tracelog line (registers, totalcycles # before the instruction) and MAME's disassembly line "0:ADDR: ...". The # address must come from the second: while the cache runs, `pc` holds the # ROM address after the block, not the address of the cached instruction. steps = [] pending = None with args.trace.open(encoding="ascii", errors="replace") as handle: for line in handle: match = LINE.match(line.rstrip("\n")) if match: pending = int(match[2]) elif pending is not None and line.startswith("0:"): steps.append((int(line.split(":")[1], 16), pending)) pending = None # Cache bookkeeping: (first address, last address, passes, pass number). block = None expected_total = mame_total = 0 mismatches = collections.Counter() examples = {} period_mame, period_manual = [], [] mark_mame = mark_manual = None for (pc, t), (_, t_next) in zip(steps, steps[1:], strict=False): word = words[pc] mame = t_next - t in_cache = False last_of_block = False if block and block[0] <= pc <= block[1]: first, last, passes, number, redo = block last_of_block = pc == last if number == 1 and not redo: in_cache = False else: in_cache = not (last_of_block and number == passes) expected = cost(word, in_cache) if number == 1 and not redo and last_of_block: expected = 2 if last_of_block: number += 1 block = None if number > passes else (first, last, passes, number, redo) else: block = None expected = cost(word, False) kind = word >> 11 if kind == 0x0E: ni, k = (word >> 7) & 15, word & 127 if ni: block = (pc + 1, pc + ni, k, 1, False) last_do = block else: block = (last_do[0], last_do[1], k, 1, True) if pc == args.marker: if mark_mame is not None: period_mame.append(mame_total - mark_mame) period_manual.append(expected_total - mark_manual) mark_mame, mark_manual = mame_total, expected_total expected_total += expected mame_total += mame if expected != mame: key = (label(word), "cache" if in_cache else "rom", expected, mame) mismatches[key] += 1 examples.setdefault(key, pc) print(f"instructions charged: {len(steps) - 1}") print(f"MAME cycles {mame_total}, manual cycles {expected_total}") if period_mame: print(f"sample period, MAME: {collections.Counter(period_mame).most_common(4)}") print(f"sample period, manual: {collections.Counter(period_manual).most_common(4)}") executed = {pc for pc, _ in steps} kinds = collections.Counter(words[pc] >> 11 for pc in executed) print(f"distinct addresses executed: {len(executed)}; by T field (distinct addresses): " + ", ".join(f"{kind:05b}:{count}" for kind, count in sorted(kinds.items()))) # fmt: skip print("classes where MAME and the manual differ (class, where, manual, MAME): count, first pc") for key, count in mismatches.most_common(): print(f" {key}: {count}, 0x{examples[key]:04X}") return 0 if __name__ == "__main__": sys.exit(main())