Basys 3 RISC-V computer
The Basys 3 Z-80 computer with the Z-80 replaced by an RV32IM processor written from scratch (rtl/rv32_cpu.v): multi-cycle, 90 MHz, CSRs and traps, interrupts, two hardware triggers and a resumable NMI for the monitor. Passes riscv-tests rv32ui/um/mi. rv32_system.v keeps all the Z-80 machine's peripherals, with I/O port N at FFFFFF00h + N, 80 KB of RAM with BASIC preloaded, and a 32 KB monitor ROM. BASIC, the five games and the monitor (with an RV32 disassembler, assembler, breakpoints and single step) are ported to RISC-V GCC. Python emulator and tests in tools/; full-system simulation in sim/. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
5930b958b4
103 files changed
+55677
No files matched your search
@@ -0,0 +1,191 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check the monitor's disassembler and assembler (out/monitor-host, built by
|
||||
build.sh) on random instructions of every kind:
|
||||
|
||||
- each word disassembles to the same instruction GNU objdump shows (same
|
||||
mnemonic, registers and values), and
|
||||
- the monitor's assembler turns that text back into the same word.
|
||||
|
||||
python3 test-disasm.py [count per kind]
|
||||
"""
|
||||
import os
|
||||
import random
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, os.path.join(HERE, "..", "tools"))
|
||||
HOST = os.path.join(HERE, "out", "monitor-host")
|
||||
N = int(sys.argv[1]) if len(sys.argv) > 1 else 300
|
||||
random.seed(1)
|
||||
|
||||
|
||||
def prefix():
|
||||
out = subprocess.run(["bash", "-c", "source %s/../scripts/rv_env.sh; echo $RV_PREFIX" % HERE],
|
||||
capture_output=True, text=True).stdout.strip()
|
||||
return out
|
||||
|
||||
|
||||
def r():
|
||||
return random.randrange(32)
|
||||
|
||||
|
||||
def words():
|
||||
"""Random valid RV32IM / Zicsr / system instructions."""
|
||||
ws = []
|
||||
csrs = [0x300, 0x301, 0x304, 0x305, 0x340, 0x341, 0x342, 0x343, 0x344, 0x744, 0xB00,
|
||||
0xC00, 0xC01, 0xC82, 0xF14, 0x7A0, 0x123]
|
||||
for _ in range(N):
|
||||
imm = random.randrange(4096)
|
||||
ws.append(0x37 | r() << 7 | random.randrange(1 << 20) << 12) # lui
|
||||
ws.append(0x17 | r() << 7 | random.randrange(1 << 20) << 12) # auipc
|
||||
j = random.randrange(1 << 20) << 1 # jal
|
||||
v = j
|
||||
ws.append(0x6F | r() << 7 | (v >> 12 & 0xFF) << 12 | (v >> 11 & 1) << 20 |
|
||||
(v >> 1 & 0x3FF) << 21 | (v >> 20 & 1) << 31)
|
||||
ws.append(0x67 | r() << 7 | r() << 15 | imm << 20) # jalr
|
||||
b = random.randrange(1 << 12) << 1
|
||||
f3 = random.choice([0, 1, 4, 5, 6, 7])
|
||||
ws.append(0x63 | f3 << 12 | r() << 15 | r() << 20 | (b >> 11 & 1) << 7 |
|
||||
(b >> 1 & 15) << 8 | (b >> 5 & 0x3F) << 25 | (b >> 12 & 1) << 31)
|
||||
ws.append(0x03 | random.choice([0, 1, 2, 4, 5]) << 12 | r() << 7 | r() << 15 | imm << 20)
|
||||
s = random.randrange(4096)
|
||||
ws.append(0x23 | random.choice([0, 1, 2]) << 12 | (s & 31) << 7 | r() << 15 | r() << 20 |
|
||||
(s >> 5) << 25)
|
||||
ws.append(0x13 | random.choice([0, 2, 3, 4, 6, 7]) << 12 | r() << 7 | r() << 15 | imm << 20)
|
||||
ws.append(0x13 | random.choice([(1, 0), (5, 0), (5, 0x20)])[0] << 12 | r() << 7 | r() << 15 |
|
||||
random.randrange(32) << 20)
|
||||
f = random.choice([(0, 0), (0, 0x20), (1, 0), (2, 0), (3, 0), (4, 0), (5, 0), (5, 0x20),
|
||||
(6, 0), (7, 0)] + [(k, 1) for k in range(8)])
|
||||
ws.append(0x33 | f[0] << 12 | f[1] << 25 | r() << 7 | r() << 15 | r() << 20)
|
||||
ws.append(0x73 | random.choice([1, 2, 3, 5, 6, 7]) << 12 | r() << 7 | r() << 15 |
|
||||
random.choice(csrs) << 20)
|
||||
# the special cases the disassembler shortens
|
||||
ws.append(0x13 | r() << 7 | 0 << 15 | imm << 20) # li
|
||||
ws.append(0x13 | r() << 7 | r() << 15) # mv
|
||||
ws.append(0x00008067) # ret
|
||||
ws += [0x13, 0x73, 0x00100073, 0x30200073, 0x70200073, 0x10500073, 0x0FF0000F, 0x100F]
|
||||
return ws
|
||||
|
||||
|
||||
def norm_gnu(text, addr):
|
||||
"""objdump's operand text -> list of tokens to compare."""
|
||||
text = re.sub(r"<[^>]*>|#.*", "", text).strip()
|
||||
m = text.split(None, 1)
|
||||
mn = m[0].upper()
|
||||
ops = m[1].split(",") if len(m) > 1 else []
|
||||
return mn, [o.strip().upper() for o in ops]
|
||||
|
||||
|
||||
def val(tok, base10_ok=True):
|
||||
tok = tok.strip()
|
||||
if re.fullmatch(r"-?0X[0-9A-F]+", tok):
|
||||
return int(tok, 16)
|
||||
if re.fullmatch(r"-?[0-9A-F]+H", tok):
|
||||
return int(tok[:-1], 16)
|
||||
if re.fullmatch(r"-?\d+", tok):
|
||||
return int(tok)
|
||||
return None
|
||||
|
||||
|
||||
CSRN = {"MSTATUS": 0x300, "MISA": 0x301, "MIE": 0x304, "MTVEC": 0x305, "MSCRATCH": 0x340,
|
||||
"MEPC": 0x341, "MCAUSE": 0x342, "MTVAL": 0x343, "MIP": 0x344, "MNSCRATCH": 0x740,
|
||||
"MNEPC": 0x741, "MNCAUSE": 0x742, "MNSTATUS": 0x744, "TSELECT": 0x7A0, "TDATA1": 0x7A1,
|
||||
"TDATA2": 0x7A2, "TCONTROL": 0x7A5, "MCYCLE": 0xB00, "MINSTRET": 0xB02, "MCYCLEH": 0xB80,
|
||||
"MINSTRETH": 0xB82, "CYCLE": 0xC00, "TIME": 0xC01, "INSTRET": 0xC02, "CYCLEH": 0xC80,
|
||||
"TIMEH": 0xC81, "INSTRETH": 0xC82, "MHARTID": 0xF14}
|
||||
|
||||
|
||||
def same(gnu_mn, gnu_ops, our):
|
||||
m = our.split(None, 1)
|
||||
mn = m[0]
|
||||
ops = [o.strip() for o in m[1].split(",")] if len(m) > 1 else []
|
||||
# objdump's other spellings of the same instructions
|
||||
if gnu_mn == "JR" and gnu_ops and "(" in gnu_ops[0]:
|
||||
gnu_mn, gnu_ops = "JALR", ["ZERO"] + gnu_ops
|
||||
elif gnu_mn == "JALR" and len(gnu_ops) == 1 and "(" in gnu_ops[0]:
|
||||
gnu_ops = ["RA"] + gnu_ops
|
||||
elif gnu_mn.startswith("RD") and gnu_mn[2:] in CSRN:
|
||||
gnu_mn, gnu_ops = "CSRR", gnu_ops + [gnu_mn[2:]]
|
||||
gnu_ops = [str(CSRN[o]) if o in CSRN else o for o in gnu_ops]
|
||||
ops = [str(CSRN[o]) if o in CSRN else o for o in ops]
|
||||
alias = {"FENCE.I": "FENCE.I", "UNIMP": "DW"}
|
||||
if alias.get(gnu_mn, gnu_mn) != mn:
|
||||
return False
|
||||
# objdump writes "fence iorw,iorw"
|
||||
if mn == "FENCE":
|
||||
return True
|
||||
if len(ops) != len(gnu_ops):
|
||||
return False
|
||||
for a, b in zip(gnu_ops, ops):
|
||||
if a == b:
|
||||
continue
|
||||
ma, mb = re.fullmatch(r"(.*)\((\w+)\)", a), re.fullmatch(r"(.*)\((\w+)\)", b)
|
||||
if ma and mb:
|
||||
if ma.group(2) != mb.group(2) or val(ma.group(1) or "0") != val(mb.group(1) or "0"):
|
||||
return False
|
||||
continue
|
||||
va, vb = val(a), val(b)
|
||||
if va is None or vb is None:
|
||||
return False
|
||||
if va & 0xFFFFFFFF != vb & 0xFFFFFFFF:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def main():
|
||||
pre = prefix()
|
||||
ws = words()
|
||||
tmp = tempfile.mkdtemp()
|
||||
with open(os.path.join(tmp, "w.bin"), "wb") as f:
|
||||
for w in ws:
|
||||
f.write(w.to_bytes(4, "little"))
|
||||
dump = subprocess.run([pre + "objdump", "-D", "-b", "binary", "-m", "riscv:rv32",
|
||||
"-M", "numeric", "--adjust-vma=0x1000", os.path.join(tmp, "w.bin")],
|
||||
capture_output=True, text=True).stdout
|
||||
gnu = {}
|
||||
for line in dump.splitlines():
|
||||
mm = re.match(r"\s*([0-9a-f]+):\s+([0-9a-f]{8})\s+(.*)", line)
|
||||
if mm and int(mm.group(1), 16) >= 0x1000:
|
||||
gnu[int(mm.group(1), 16) - 0x1000] = mm.group(3)
|
||||
ours = subprocess.run([HOST, "dis"], input="".join("%08X\n" % w for w in ws),
|
||||
capture_output=True, text=True).stdout.splitlines()
|
||||
regn = ["ZERO", "RA", "SP", "GP", "TP", "T0", "T1", "T2", "S0", "S1"] + \
|
||||
["A%d" % i for i in range(8)] + ["S%d" % i for i in range(2, 12)] + ["T3", "T4", "T5", "T6"]
|
||||
bad_dis = 0
|
||||
for i, (w, o) in enumerate(zip(ws, ours)):
|
||||
g = gnu.get(4 * i)
|
||||
if g is None or w == 0x70200073: # (binutils doesn't know MNRET)
|
||||
continue
|
||||
gm, gops = norm_gnu(g, 0x1000)
|
||||
# objdump -M numeric prints x registers: map to ABI names; and its
|
||||
# branch/jump targets are relative to this word (we disassemble at 1000h)
|
||||
gops = [re.sub(r"\bX(\d+)\b", lambda q: regn[int(q.group(1))], t) for t in gops]
|
||||
if gm in ("J", "JAL", "BEQ", "BNE", "BLT", "BGE", "BLTU", "BGEU", "BEQZ", "BNEZ", "BLTZ",
|
||||
"BGEZ", "BLEZ", "BGTZ"):
|
||||
v = val(gops[-1])
|
||||
if v is not None:
|
||||
gops[-1] = str((v - 4 * i) & 0xFFFFFFFF)
|
||||
if not same(gm, gops, o):
|
||||
bad_dis += 1
|
||||
if bad_dis <= 15:
|
||||
print("DIS %08X: objdump '%s', monitor '%s'" % (w, g, o))
|
||||
# round trip through the monitor's assembler, one instruction at 1000h each
|
||||
bad_asm = 0
|
||||
back = subprocess.run([HOST, "asm"], input="".join("ORG 1000H\n%s\n" % o for o in ours),
|
||||
capture_output=True, text=True).stdout.splitlines()
|
||||
for w, o, b in zip(ws, ours, back):
|
||||
want = 0x0FF0000F if (w & 0x707F) == 0x0F else w
|
||||
if b.startswith("ERROR") or int(b, 16) != want:
|
||||
bad_asm += 1
|
||||
if bad_asm <= 15:
|
||||
print("ASM %08X -> '%s' -> %s" % (w, o, b))
|
||||
print("%d instructions: %d disassembled differently from objdump, %d assembled back wrong"
|
||||
% (len(ws), bad_dis, bad_asm))
|
||||
sys.exit(1 if bad_dis or bad_asm else 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user