change to instruction template parsing, create one file per instruction
[riscv-isa-sim.git] / id_regs.py
1 #!/usr/bin/env python
2 # Copyright (C) 2018 Luke Kenneth Casson Leighton <lkcl@lkcl.net>
3
4 """ identify registers used in riscv/insns/*.h and create code
5 that can be used in spike at runtime
6
7 the design of spike assumes that once an opcode is identified,
8 the role of decoding the instruction is implicitly rolled into
9 and included inside the function that emulates that opcode.
10
11 however there may be circumstances where the behaviour of an
12 instruction has to change depending on "tags" associated with
13 the registers (security extensions, simple-v extension).
14
15 therefore this code walks the instruction implementations
16 in riscv/insns/*.h looking for register usage patterns.
17 the resultant table can be used *prior* to the emulation,
18 without having to manually maintain such a table.
19 """
20
21 import os
22
23 insns_dir = "./riscv/insns"
24 def list_insns():
25 res = []
26 for fname in os.listdir(insns_dir):
27 if not fname.endswith(".h"):
28 continue
29 insn = fname[:-2]
30 res.append((os.path.join(insns_dir, fname), insn))
31 return res
32
33 patterns = ['WRITE_RD', 'RS1', 'RS2', 'RS3',
34 'WRITE_FRD', 'FRS1', 'FRS2', 'FRS3']
35
36 def find_registers(fname):
37 res = []
38 with open(fname) as f:
39 f = f.read()
40 for pattern in patterns:
41 x = f.find(pattern)
42 if x == -1:
43 continue
44 if pattern.startswith('R') and x != 0 and f[x-1] == 'F':
45 # botch-job/hack: RS1 also matches against FRS1 (etc.)
46 # check letter before match: if "F", skip it.
47 continue
48 p = pattern
49 if p.startswith('WRITE_'):
50 p = p[6:]
51 res.append('#define USING_REG_%s' % p)
52 if len(res) == 0:
53 return "0"
54 return '\n'.join(res)
55
56 if __name__ == '__main__':
57 files = list_insns()
58 for (fname, insn) in files:
59 regsname = "regs_%s.h" % insn
60 regsname = os.path.join(insns_dir, regsname)
61 with open(regsname, "w") as f:
62 f.write(find_registers(fname))