# SPDX-License-Identifier: MIT """Rung 0: every opcode's bus schedule, written from docs/timing.md rather than from the core. Research documentation where anomie is specific; on C4, C6, C7 the rows are SingleStepTests' order as the doc says, so this file pins what rung 1 finds, not a higher tier. Each row is a template of cycles after the opcode fetch; ``R@``, ``D@`` (dummy read) and ``W@`` take an address expression over the instruction's bytes and the random state, ``I`` is an internal cycle. pc1 pc2 the bytes after the opcode d d1 the first / second operand byte's direct-page address, unindexed dx dx1 dp + (d + X), dp + (d + X + 1) (U2) dy dp + (d + Y) ix iy dp + X, dp + Y ptrx ptry the word a pointer holds, plus Y for ptry a ax ay the absolute operand, plus X or Y m the 13-bit address of m.b sN $0100 + (SP - N) & $FF for a push, sP1.. for a pull FFDE... a literal address """ import random import re from pathlib import Path import pytest from spc700_python import SPC700, CPUState from spc700_python._flags import FLAG_P from spc700_python._opcodes import OPCODES TIMING = Path(__file__).resolve().parents[1] / "docs" / "timing.md" ALU_ROWS = (0x00, 0x20, 0x40, 0x60, 0x80, 0xA0) def alu(column: int) -> list[int]: return [row + column for row in ALU_ROWS] def rows(*columns: int) -> list[int]: return [c + r * 0x10 for r in range(16) for c in columns] SCHEDULE: list[tuple[list[int], str]] = [ # implied ([0x00, 0x1C, 0x3C, 0x5C, 0x7C, 0x9C, 0xBC, 0x1D, 0x3D, 0xDC, 0xFC], "D@pc1"), ([0x5D, 0x7D, 0x9D, 0xBD, 0xDD, 0xFD, 0x20, 0x40, 0x60, 0x80, 0xE0], "D@pc1"), ([0xED, 0xDF, 0xBE, 0xA0, 0xC0], "D@pc1 I"), ([0x9F], "D@pc1 I I I"), ([0xCF], "D@pc1 I I I I I I I"), ([0x9E], "D@pc1 I I I I I I I I I I"), # ALU and loads by addressing mode ([*alu(0x08), 0xC8, 0xAD, 0xE8, 0xCD, 0x8D], "R@pc1"), ([*alu(0x04), 0xE4, 0xF8, 0xEB, 0x3E, 0x7E], "R@pc1 R@d"), ([*alu(0x14), 0xF4, 0xFB], "R@pc1 I R@dx"), ([0xF9], "R@pc1 I R@dy"), ([*alu(0x06), 0xE6], "D@pc1 R@ix"), ([0xBF], "D@pc1 R@ix I"), ([*alu(0x07), 0xE7], "R@pc1 I R@dx R@dx1 R@ptrx"), ([*alu(0x17), 0xF7], "R@pc1 I R@d R@d1 R@ptry"), ([*alu(0x05), 0xE5, 0xE9, 0xEC, 0x1E, 0x5E], "R@pc1 R@pc2 R@a"), ([*alu(0x15), 0xF5], "R@pc1 R@pc2 I R@ax"), ([*alu(0x16), 0xF6], "R@pc1 R@pc2 I R@ay"), # memory-destination ALU ([0x18, 0x38, 0x58, 0x98, 0xB8], "R@pc1 R@pc2 R@d2 W@d2"), ([0x8F], "R@pc1 R@pc2 D@d2 W@d2"), ([0x78], "R@pc1 R@pc2 R@d2 I"), ([0x09, 0x29, 0x49, 0x89, 0xA9], "R@pc1 R@d R@pc2 R@d2 W@d2"), ([0x69], "R@pc1 R@d R@pc2 R@d2 I"), ([0xFA], "R@pc1 R@d R@pc2 W@d2"), ([0x19, 0x39, 0x59, 0x99, 0xB9], "D@pc1 R@iy R@ix W@ix"), ([0x79], "D@pc1 R@iy R@ix I"), # stores (U1) ([0xC4, 0xD8, 0xCB], "R@pc1 D@d W@d"), ([0xD4, 0xDB], "R@pc1 I D@dx W@dx"), ([0xD9], "R@pc1 I D@dy W@dy"), ([0xC6], "D@pc1 D@ix W@ix"), ([0xAF], "D@pc1 I W@ix"), ([0xC7], "R@pc1 I R@dx R@dx1 D@ptrx W@ptrx"), ([0xD7], "R@pc1 R@d R@d1 I D@ptry W@ptry"), ([0xC5, 0xC9, 0xCC], "R@pc1 R@pc2 D@a W@a"), ([0xD5], "R@pc1 R@pc2 I D@ax W@ax"), ([0xD6], "R@pc1 R@pc2 I D@ay W@ay"), # RMW ([0x0B, 0x2B, 0x4B, 0x6B, 0x8B, 0xAB], "R@pc1 R@d W@d"), ([op for op in range(256) if op & 0x0F == 2], "R@pc1 R@d W@d"), ([0x1B, 0x3B, 0x5B, 0x7B, 0x9B, 0xBB], "R@pc1 I R@dx W@dx"), ([0x0C, 0x2C, 0x4C, 0x6C, 0x8C, 0xAC], "R@pc1 R@pc2 R@a W@a"), ([0x0E, 0x4E], "R@pc1 R@pc2 R@a D@a W@a"), ([0xEA], "R@pc1 R@pc2 R@m W@m"), ([0xAA, 0x4A, 0x6A], "R@pc1 R@pc2 R@m"), ([0x0A, 0x2A, 0x8A], "R@pc1 R@pc2 R@m I"), ([0xCA], "R@pc1 R@pc2 R@m I W@m"), # words ([0xBA, 0x7A, 0x9A], "R@pc1 R@d I R@d1"), ([0x5A], "R@pc1 R@d R@d1"), ([0xDA], "R@pc1 D@d W@d W@d1"), ([0x3A, 0x1A], "R@pc1 R@d W@d R@d1 W@d1"), # stack ([0x0D, 0x2D, 0x4D, 0x6D], "D@pc1 W@s0 I"), ([0x8E, 0xAE, 0xCE, 0xEE], "D@pc1 I R@s+1"), # jumps, calls, returns ([0x5F], "R@pc1 R@pc2"), ([0x1F], "R@pc1 R@pc2 I R@ax R@ax1"), ([0x3F], "R@pc1 R@pc2 I W@s0 W@s1 I I"), ([0x4F], "R@pc1 I W@s0 W@s1 I"), ([op for op in range(256) if op & 0x0F == 1], "D@pc1 I W@s0 W@s1 I R@tcall R@tcall1"), ([0x0F], "D@pc1 W@s0 W@s1 W@s2 I R@FFDE R@FFDF"), ([0x6F], "D@pc1 I R@s+1 R@s+2"), ([0x7F], "D@pc1 I R@s+1 R@s+2 R@s+3"), # branches: the taken suffix is added from the opcode table's two cycle counts ([op for op in range(256) if op & 0x1F == 0x10], "R@pc1"), ([0x2F], "R@pc1 I I"), ([op for op in range(256) if op & 0x0F == 3], "R@pc1 R@d I R@pc2"), ([0x2E], "R@pc1 R@d I R@pc2"), ([0xDE], "R@pc1 I R@dx I R@pc2"), ([0x6E], "R@pc1 R@d W@d R@pc2"), ([0xFE], "D@pc1 I R@pc1"), ] BY_OPCODE = {opcode: template for opcodes, template in SCHEDULE for opcode in opcodes} def test_schedule_covers_every_opcode_but_sleep_and_stop(): assert set(BY_OPCODE) == set(range(256)) - {0xEF, 0xFF} class Bench: def __init__(self, seed: int) -> None: self.rng = random.Random(seed) self.memory = bytearray(self.rng.randbytes(0x10000)) self.log: list[tuple[str, int | None]] = [] self.cpu = SPC700(self.read, self.write, self.idle) def read(self, address: int) -> int: self.log.append(("D" if self.cpu.dummy else "R", address)) return self.memory[address] def write(self, address: int, value: int) -> None: self.log.append(("W", address)) self.memory[address] = value def idle(self) -> None: self.log.append(("I", None)) def expressions(memory: bytearray, state: CPUState) -> dict[str, int]: """What each address word in a template means for this instruction and state.""" pc = state.pc m = lambda address: memory[address & 0xFFFF] # noqa: E731 pc1, pc2 = (pc + 1) & 0xFFFF, (pc + 2) & 0xFFFF byte1, byte2 = m(pc1), m(pc2) dp = 0x100 if state.psw & FLAG_P else 0 word = byte2 << 8 | byte1 dx, dx1 = dp + ((byte1 + state.x) & 0xFF), dp + ((byte1 + state.x + 1) & 0xFF) d, d1 = dp + byte1, dp + ((byte1 + 1) & 0xFF) ptrx = m(dx1) << 8 | m(dx) ptry = ((m(d1) << 8 | m(d)) + state.y) & 0xFFFF opcode = m(pc) tcall = 0xFFDE - 2 * (opcode >> 4) table = { "pc1": pc1, "pc2": pc2, "d": d, "d1": d1, "d2": dp + byte2, "dx": dx, "dx1": dx1, "dy": dp + ((byte1 + state.y) & 0xFF), "ix": dp + state.x, "iy": dp + state.y, "ptrx": ptrx, "ptry": ptry, "a": word, "ax": (word + state.x) & 0xFFFF, "ax1": (word + state.x + 1) & 0xFFFF, "ay": (word + state.y) & 0xFFFF, "m": word & 0x1FFF, "tcall": tcall, "tcall1": tcall + 1, "FFDE": 0xFFDE, "FFDF": 0xFFDF, } for n in range(3): table[f"s{n}"] = 0x100 | (state.sp - n) & 0xFF table[f"s+{n + 1}"] = 0x100 | (state.sp + n + 1) & 0xFF return table def expected(template: str, table: dict[str, int]) -> list[tuple[str, int | None]]: cycles: list[tuple[str, int | None]] = [] for word in template.split(): if word == "I": cycles.append(("I", None)) else: kind, name = word.split("@") cycles.append((kind, table[name])) return cycles @pytest.mark.parametrize("opcode", sorted(BY_OPCODE), ids=lambda o: f"{o:02X}") def test_bus_schedule(opcode): entry = OPCODES[opcode] seen = set() bench = Bench(opcode) # one random memory: the state and PC move around in it rng = bench.rng for seed in range(300): bench.log.clear() state = CPUState( a=rng.randrange(256), x=rng.randrange(256), y=1 if opcode == 0xFE and seed % 4 == 0 else rng.randrange(256), sp=rng.randrange(256), pc=rng.randrange(0x10000), psw=rng.randrange(256), ) bench.memory[state.pc] = opcode table = expressions(bench.memory, state) if seed % 4 == 0: # the paths random data rarely takes: the compare that matches match opcode: case 0x2E: bench.memory[table["d"]] = state.a case 0xDE: bench.memory[table["dx"]] = state.a case 0x6E: bench.memory[table["d"]] = 1 cycles = expected(BY_OPCODE[opcode], table) bench.cpu.restore_state(state) taken = bench.cpu.step() seen.add(taken) if len(entry.cycles) == 2 and taken == entry.cycles[1]: cycles += [("I", None), ("I", None)] assert bench.log[0] == ("R", state.pc) assert bench.log[1:] == cycles, f"state {state}" assert seen == set(entry.cycles), "a path was never exercised" def timing_doc_rows() -> dict[int, list[str]]: """The "Every opcode" table of docs/timing.md: opcode -> the SST kind strings.""" found: dict[int, list[str]] = {} pattern = re.compile(r"^\| ([0-9A-F]{2}) \| `[^`]+` \| [^|]+ \| ([^|]+) \|") for line in TIMING.read_text(encoding="utf-8").splitlines(): match = pattern.match(line) if match: found[int(match[1], 16)] = re.findall(r"`([RDWI]+)`", match[2]) return found def test_kinds_equal_the_every_opcode_table(): """Each template's kinds equal the doc's table, ``R`` and ``D`` both meaning a read.""" table = timing_doc_rows() assert len(table) == 256 for opcode, template in BY_OPCODE.items(): kinds = "R" + "".join(word[0] for word in template.split()) kinds = kinds.replace("D", "R") documented = [text.replace("D", "R") for text in table[opcode]] assert kinds == documented[0], f"${opcode:02X}" def test_spec_rows_match_the_core_through_one_store_to_timer(): """U1: the read half of a store is a real bus read of the destination.""" bench = Bench(1) bench.memory[0x300:0x302] = bytes((0xC4, 0xFD)) bench.cpu.restore_state(CPUState(pc=0x300, a=0)) bench.cpu.step() assert ("D", 0x00FD) in bench.log