update test_sim.py to do a simple execution loop: decode-execute-decode-execute
[soc.git] / src / soc / decoder / isa / caller.py
1 """core of the python-based POWER9 simulator
2
3 this is part of a cycle-accurate POWER9 simulator. its primary purpose is
4 not speed, it is for both learning and educational purposes, as well as
5 a method of verifying the HDL.
6 """
7
8 from functools import wraps
9 from soc.decoder.orderedset import OrderedSet
10 from soc.decoder.selectable_int import (FieldSelectableInt, SelectableInt,
11 selectconcat)
12 from soc.decoder.power_enums import spr_dict, XER_bits
13 from soc.decoder.helpers import exts
14 from collections import namedtuple
15 import math
16
17 instruction_info = namedtuple('instruction_info',
18 'func read_regs uninit_regs write_regs ' + \
19 'special_regs op_fields form asmregs')
20
21 special_sprs = {
22 'LR': 8,
23 'CTR': 9,
24 'TAR': 815,
25 'XER': 1,
26 'VRSAVE': 256}
27
28
29 def swap_order(x, nbytes):
30 x = x.to_bytes(nbytes, byteorder='little')
31 x = int.from_bytes(x, byteorder='big', signed=False)
32 return x
33
34
35 def create_args(reglist, extra=None):
36 args = OrderedSet()
37 for reg in reglist:
38 args.add(reg)
39 args = list(args)
40 if extra:
41 args = [extra] + args
42 return args
43
44
45 class Mem:
46
47 def __init__(self, row_bytes=8, initial_mem=None):
48 self.mem = {}
49 self.bytes_per_word = row_bytes
50 self.word_log2 = math.ceil(math.log2(row_bytes))
51 print ("Sim-Mem", initial_mem, self.bytes_per_word, self.word_log2)
52 if not initial_mem:
53 return
54
55 # different types of memory data structures recognised (for convenience)
56 if isinstance(initial_mem, list):
57 initial_mem = (0, initial_mem)
58 if isinstance(initial_mem, tuple):
59 startaddr, mem = initial_mem
60 initial_mem = {}
61 for i, val in enumerate(mem):
62 initial_mem[startaddr + row_bytes*i] = (val, row_bytes)
63
64 for addr, (val, width) in initial_mem.items():
65 #val = swap_order(val, width)
66 self.st(addr, val, width, swap=False)
67
68 def _get_shifter_mask(self, wid, remainder):
69 shifter = ((self.bytes_per_word - wid) - remainder) * \
70 8 # bits per byte
71 # XXX https://bugs.libre-soc.org/show_bug.cgi?id=377
72 # BE/LE mode?
73 shifter = remainder * 8
74 mask = (1 << (wid * 8)) - 1
75 print ("width,rem,shift,mask", wid, remainder, hex(shifter), hex(mask))
76 return shifter, mask
77
78 # TODO: Implement ld/st of lesser width
79 def ld(self, address, width=8, swap=True, check_in_mem=False):
80 print("ld from addr 0x{:x} width {:d}".format(address, width))
81 remainder = address & (self.bytes_per_word - 1)
82 address = address >> self.word_log2
83 assert remainder & (width - 1) == 0, "Unaligned access unsupported!"
84 if address in self.mem:
85 val = self.mem[address]
86 elif check_in_mem:
87 return None
88 else:
89 val = 0
90 print("mem @ 0x{:x} rem {:d} : 0x{:x}".format(address, remainder, val))
91
92 if width != self.bytes_per_word:
93 shifter, mask = self._get_shifter_mask(width, remainder)
94 print ("masking", hex(val), hex(mask<<shifter), shifter)
95 val = val & (mask << shifter)
96 val >>= shifter
97 if swap:
98 val = swap_order(val, width)
99 print("Read 0x{:x} from addr 0x{:x}".format(val, address))
100 return val
101
102 def st(self, addr, v, width=8, swap=True):
103 staddr = addr
104 remainder = addr & (self.bytes_per_word - 1)
105 addr = addr >> self.word_log2
106 print("Writing 0x{:x} to ST 0x{:x} memaddr 0x{:x}/{:x}".format(v,
107 staddr, addr, remainder, swap))
108 assert remainder & (width - 1) == 0, "Unaligned access unsupported!"
109 if swap:
110 v = swap_order(v, width)
111 if width != self.bytes_per_word:
112 if addr in self.mem:
113 val = self.mem[addr]
114 else:
115 val = 0
116 shifter, mask = self._get_shifter_mask(width, remainder)
117 val &= ~(mask << shifter)
118 val |= v << shifter
119 self.mem[addr] = val
120 else:
121 self.mem[addr] = v
122 print("mem @ 0x{:x}: 0x{:x}".format(addr, self.mem[addr]))
123
124 def __call__(self, addr, sz):
125 val = self.ld(addr.value, sz)
126 print ("memread", addr, sz, val)
127 return SelectableInt(val, sz*8)
128
129 def memassign(self, addr, sz, val):
130 print ("memassign", addr, sz, val)
131 self.st(addr.value, val.value, sz)
132
133
134 class GPR(dict):
135 def __init__(self, decoder, regfile):
136 dict.__init__(self)
137 self.sd = decoder
138 for i in range(32):
139 self[i] = SelectableInt(regfile[i], 64)
140
141 def __call__(self, ridx):
142 return self[ridx]
143
144 def set_form(self, form):
145 self.form = form
146
147 def getz(self, rnum):
148 #rnum = rnum.value # only SelectableInt allowed
149 print("GPR getzero", rnum)
150 if rnum == 0:
151 return SelectableInt(0, 64)
152 return self[rnum]
153
154 def _get_regnum(self, attr):
155 getform = self.sd.sigforms[self.form]
156 rnum = getattr(getform, attr)
157 return rnum
158
159 def ___getitem__(self, attr):
160 print("GPR getitem", attr)
161 rnum = self._get_regnum(attr)
162 return self.regfile[rnum]
163
164 def dump(self):
165 for i in range(0, len(self), 8):
166 s = []
167 for j in range(8):
168 s.append("%08x" % self[i+j].value)
169 s = ' '.join(s)
170 print("reg", "%2d" % i, s)
171
172 class PC:
173 def __init__(self, pc_init=0):
174 self.CIA = SelectableInt(pc_init, 64)
175 self.NIA = self.CIA + SelectableInt(4, 64)
176
177 def update(self, namespace):
178 self.CIA = namespace['NIA'].narrow(64)
179 self.NIA = self.CIA + SelectableInt(4, 64)
180 namespace['CIA'] = self.CIA
181 namespace['NIA'] = self.NIA
182
183
184 class SPR(dict):
185 def __init__(self, dec2, initial_sprs={}):
186 self.sd = dec2
187 dict.__init__(self)
188 self.update(initial_sprs)
189
190 def __getitem__(self, key):
191 # if key in special_sprs get the special spr, otherwise return key
192 if isinstance(key, SelectableInt):
193 key = key.value
194 key = special_sprs.get(key, key)
195 if key in self:
196 return dict.__getitem__(self, key)
197 else:
198 info = spr_dict[key]
199 dict.__setitem__(self, key, SelectableInt(0, info.length))
200 return dict.__getitem__(self, key)
201
202 def __setitem__(self, key, value):
203 if isinstance(key, SelectableInt):
204 key = key.value
205 key = special_sprs.get(key, key)
206 dict.__setitem__(self, key, value)
207
208 def __call__(self, ridx):
209 return self[ridx]
210
211
212 class ISACaller:
213 # decoder2 - an instance of power_decoder2
214 # regfile - a list of initial values for the registers
215 # initial_{etc} - initial values for SPRs, Condition Register, Mem, MSR
216 # respect_pc - tracks the program counter. requires initial_insns
217 def __init__(self, decoder2, regfile, initial_sprs=None, initial_cr=0,
218 initial_mem=None, initial_msr=0,
219 initial_insns=None, respect_pc=False,
220 disassembly=None):
221
222 self.respect_pc = respect_pc
223 if initial_sprs is None:
224 initial_sprs = {}
225 if initial_mem is None:
226 initial_mem = {}
227 if initial_insns is None:
228 initial_insns = {}
229 assert self.respect_pc == False, "instructions required to honor pc"
230
231 print ("ISACaller insns", respect_pc, initial_insns, disassembly)
232
233 # "fake program counter" mode (for unit testing)
234 self.fake_pc = 0
235 if not respect_pc:
236 if isinstance(initial_mem, tuple):
237 self.fake_pc = initial_mem[0]
238
239 # disassembly: we need this for now (not given from the decoder)
240 self.disassembly = {}
241 if disassembly:
242 for i, code in enumerate(disassembly):
243 self.disassembly[i*4 + self.fake_pc] = code
244
245 # set up registers, instruction memory, data memory, PC, SPRs, MSR
246 self.gpr = GPR(decoder2, regfile)
247 self.mem = Mem(row_bytes=8, initial_mem=initial_mem)
248 self.imem = Mem(row_bytes=4, initial_mem=initial_insns)
249 self.pc = PC()
250 self.spr = SPR(decoder2, initial_sprs)
251 self.msr = SelectableInt(initial_msr, 64) # underlying reg
252
253 # TODO, needed here:
254 # FPR (same as GPR except for FP nums)
255 # 4.2.2 p124 FPSCR (definitely "separate" - not in SPR)
256 # note that mffs, mcrfs, mtfsf "manage" this FPSCR
257 # 2.3.1 CR (and sub-fields CR0..CR6 - CR0 SO comes from XER.SO)
258 # note that mfocrf, mfcr, mtcr, mtocrf, mcrxrx "manage" CRs
259 # -- Done
260 # 2.3.2 LR (actually SPR #8) -- Done
261 # 2.3.3 CTR (actually SPR #9) -- Done
262 # 2.3.4 TAR (actually SPR #815)
263 # 3.2.2 p45 XER (actually SPR #1) -- Done
264 # 3.2.3 p46 p232 VRSAVE (actually SPR #256)
265
266 # create CR then allow portions of it to be "selectable" (below)
267 self._cr = SelectableInt(initial_cr, 64) # underlying reg
268 self.cr = FieldSelectableInt(self._cr, list(range(32,64)))
269
270 # "undefined", just set to variable-bit-width int (use exts "max")
271 self.undefined = SelectableInt(0, 256) # TODO, not hard-code 256!
272
273 self.namespace = {'GPR': self.gpr,
274 'MEM': self.mem,
275 'SPR': self.spr,
276 'memassign': self.memassign,
277 'NIA': self.pc.NIA,
278 'CIA': self.pc.CIA,
279 'CR': self.cr,
280 'MSR': self.msr,
281 'undefined': self.undefined,
282 'mode_is_64bit': True,
283 'SO': XER_bits['SO']
284 }
285
286 # field-selectable versions of Condition Register TODO check bitranges?
287 self.crl = []
288 for i in range(8):
289 bits = tuple(range(i*4, (i+1)*4))# errr... maybe?
290 _cr = FieldSelectableInt(self.cr, bits)
291 self.crl.append(_cr)
292 self.namespace["CR%d" % i] = _cr
293
294 self.decoder = decoder2.dec
295 self.dec2 = decoder2
296
297 def TRAP(self, trap_addr=0x700):
298 print ("TRAP: TODO")
299 # store CIA(+4?) in SRR0, set NIA to 0x700
300 # store MSR in SRR1, set MSR to um errr something, have to check spec
301
302 def memassign(self, ea, sz, val):
303 self.mem.memassign(ea, sz, val)
304
305 def prep_namespace(self, formname, op_fields):
306 # TODO: get field names from form in decoder*1* (not decoder2)
307 # decoder2 is hand-created, and decoder1.sigform is auto-generated
308 # from spec
309 # then "yield" fields only from op_fields rather than hard-coded
310 # list, here.
311 fields = self.decoder.sigforms[formname]
312 for name in op_fields:
313 if name == 'spr':
314 sig = getattr(fields, name.upper())
315 else:
316 sig = getattr(fields, name)
317 val = yield sig
318 if name in ['BF', 'BFA']:
319 self.namespace[name] = val
320 else:
321 self.namespace[name] = SelectableInt(val, sig.width)
322
323 self.namespace['XER'] = self.spr['XER']
324 self.namespace['CA'] = self.spr['XER'][XER_bits['CA']].value
325 self.namespace['CA32'] = self.spr['XER'][XER_bits['CA32']].value
326
327 def handle_carry_(self, inputs, outputs, already_done):
328 inv_a = yield self.dec2.e.invert_a
329 if inv_a:
330 inputs[0] = ~inputs[0]
331
332 imm_ok = yield self.dec2.e.imm_data.ok
333 if imm_ok:
334 imm = yield self.dec2.e.imm_data.data
335 inputs.append(SelectableInt(imm, 64))
336 assert len(outputs) >= 1
337 output = outputs[0]
338 gts = [(x > output) for x in inputs]
339 print(gts)
340 cy = 1 if any(gts) else 0
341 if not (1 & already_done):
342 self.spr['XER'][XER_bits['CA']] = cy
343
344 print ("inputs", inputs)
345 # 32 bit carry
346 gts = [(x[32:64] > output[32:64]) == SelectableInt(1, 1)
347 for x in inputs]
348 cy32 = 1 if any(gts) else 0
349 if not (2 & already_done):
350 self.spr['XER'][XER_bits['CA32']] = cy32
351
352 def handle_overflow(self, inputs, outputs):
353 inv_a = yield self.dec2.e.invert_a
354 if inv_a:
355 inputs[0] = ~inputs[0]
356
357 imm_ok = yield self.dec2.e.imm_data.ok
358 if imm_ok:
359 imm = yield self.dec2.e.imm_data.data
360 inputs.append(SelectableInt(imm, 64))
361 assert len(outputs) >= 1
362 print ("handle_overflow", inputs, outputs)
363 if len(inputs) >= 2:
364 output = outputs[0]
365
366 # OV (64-bit)
367 input_sgn = [exts(x.value, x.bits) < 0 for x in inputs]
368 output_sgn = exts(output.value, output.bits) < 0
369 ov = 1 if input_sgn[0] == input_sgn[1] and \
370 output_sgn != input_sgn[0] else 0
371
372 # OV (32-bit)
373 input32_sgn = [exts(x.value, 32) < 0 for x in inputs]
374 output32_sgn = exts(output.value, 32) < 0
375 ov32 = 1 if input32_sgn[0] == input32_sgn[1] and \
376 output32_sgn != input32_sgn[0] else 0
377
378 self.spr['XER'][XER_bits['OV']] = ov
379 self.spr['XER'][XER_bits['OV32']] = ov32
380 so = self.spr['XER'][XER_bits['SO']]
381 so = so | ov
382 self.spr['XER'][XER_bits['SO']] = so
383
384 def handle_comparison(self, outputs):
385 out = outputs[0]
386 out = exts(out.value, out.bits)
387 zero = SelectableInt(out == 0, 1)
388 positive = SelectableInt(out > 0, 1)
389 negative = SelectableInt(out < 0, 1)
390 SO = self.spr['XER'][XER_bits['SO']]
391 cr_field = selectconcat(negative, positive, zero, SO)
392 self.crl[0].eq(cr_field)
393
394 def set_pc(self, pc_val):
395 self.namespace['NIA'] = SelectableInt(pc_val, 64)
396 self.pc.update(self.namespace)
397
398 def setup_one(self):
399 """set up one instruction
400 """
401 if self.respect_pc:
402 pc = self.pc.CIA.value
403 else:
404 pc = self.fake_pc
405 self._pc = pc
406 ins = self.imem.ld(pc, 4, False, True)
407 if ins is None:
408 raise KeyError("no instruction at 0x%x" % pc)
409 print("setup: 0x{:X} 0x{:X}".format(pc, ins & 0xffffffff))
410 print ("NIA, CIA", self.pc.CIA.value, self.pc.NIA.value)
411
412 yield self.dec2.dec.raw_opcode_in.eq(ins)
413 yield self.dec2.dec.bigendian.eq(0) # little / big?
414
415 def execute_one(self):
416 """execute one instruction
417 """
418 # get the disassembly code for this instruction
419 code = self.disassembly[self._pc]
420 print("sim-execute", hex(self._pc), code)
421 opname = code.split(' ')[0]
422 yield from self.call(opname)
423
424 if not self.respect_pc:
425 self.fake_pc += 4
426 print ("NIA, CIA", self.pc.CIA.value, self.pc.NIA.value)
427
428 def call(self, name):
429 # TODO, asmregs is from the spec, e.g. add RT,RA,RB
430 # see http://bugs.libre-riscv.org/show_bug.cgi?id=282
431 info = self.instrs[name]
432 yield from self.prep_namespace(info.form, info.op_fields)
433
434 # preserve order of register names
435 input_names = create_args(list(info.read_regs) + list(info.uninit_regs))
436 print(input_names)
437
438 # main registers (RT, RA ...)
439 inputs = []
440 for name in input_names:
441 regnum = yield getattr(self.decoder, name)
442 regname = "_" + name
443 self.namespace[regname] = regnum
444 print('reading reg %d' % regnum)
445 inputs.append(self.gpr(regnum))
446
447 # "special" registers
448 for special in info.special_regs:
449 if special in special_sprs:
450 inputs.append(self.spr[special])
451 else:
452 inputs.append(self.namespace[special])
453
454 print(inputs)
455 results = info.func(self, *inputs)
456 print(results)
457
458 # detect if CA/CA32 already in outputs (sra*, basically)
459 already_done = 0
460 if info.write_regs:
461 output_names = create_args(info.write_regs)
462 for name in output_names:
463 if name == 'CA':
464 already_done |= 1
465 if name == 'CA32':
466 already_done |= 2
467
468 print ("carry already done?", bin(already_done))
469 carry_en = yield self.dec2.e.output_carry
470 if carry_en:
471 yield from self.handle_carry_(inputs, results, already_done)
472 ov_en = yield self.dec2.e.oe.oe
473 ov_ok = yield self.dec2.e.oe.ok
474 if ov_en & ov_ok:
475 yield from self.handle_overflow(inputs, results)
476 rc_en = yield self.dec2.e.rc.data
477 if rc_en:
478 self.handle_comparison(results)
479
480 # any modified return results?
481 if info.write_regs:
482 for name, output in zip(output_names, results):
483 if isinstance(output, int):
484 output = SelectableInt(output, 256)
485 if name in ['CA', 'CA32']:
486 if carry_en:
487 print ("writing %s to XER" % name, output)
488 self.spr['XER'][XER_bits[name]] = output.value
489 else:
490 print ("NOT writing %s to XER" % name, output)
491 elif name in info.special_regs:
492 print('writing special %s' % name, output, special_sprs)
493 if name in special_sprs:
494 self.spr[name] = output
495 else:
496 self.namespace[name].eq(output)
497 else:
498 regnum = yield getattr(self.decoder, name)
499 print('writing reg %d %s' % (regnum, str(output)))
500 if output.bits > 64:
501 output = SelectableInt(output.value, 64)
502 self.gpr[regnum] = output
503
504 # update program counter
505 self.pc.update(self.namespace)
506
507
508 def inject():
509 """Decorator factory.
510
511 this decorator will "inject" variables into the function's namespace,
512 from the *dictionary* in self.namespace. it therefore becomes possible
513 to make it look like a whole stack of variables which would otherwise
514 need "self." inserted in front of them (*and* for those variables to be
515 added to the instance) "appear" in the function.
516
517 "self.namespace['SI']" for example becomes accessible as just "SI" but
518 *only* inside the function, when decorated.
519 """
520 def variable_injector(func):
521 @wraps(func)
522 def decorator(*args, **kwargs):
523 try:
524 func_globals = func.__globals__ # Python 2.6+
525 except AttributeError:
526 func_globals = func.func_globals # Earlier versions.
527
528 context = args[0].namespace # variables to be injected
529 saved_values = func_globals.copy() # Shallow copy of dict.
530 func_globals.update(context)
531 result = func(*args, **kwargs)
532 args[0].namespace = func_globals
533 #exec (func.__code__, func_globals)
534
535 #finally:
536 # func_globals = saved_values # Undo changes.
537
538 return result
539
540 return decorator
541
542 return variable_injector
543