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