12cb66478cca422e5261abc2650801706ef62a45
[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, str):
192 key = spr_byname[key].SPR
193 if isinstance(key, SelectableInt):
194 key = key.value
195 key = special_sprs.get(key, key)
196 if isinstance(key, int):
197 info = spr_dict[key]
198 else:
199 info = spr_byname[key]
200 if not isinstance(v, SelectableInt):
201 v = SelectableInt(v, info.length)
202 self[key] = v
203
204 def __getitem__(self, key):
205 print ("get spr", key)
206 print ("dict", self.items())
207 # if key in special_sprs get the special spr, otherwise return key
208 if isinstance(key, SelectableInt):
209 key = key.value
210 key = special_sprs.get(key, key)
211 if key in self:
212 res = dict.__getitem__(self, key)
213 else:
214 info = spr_dict[key]
215 dict.__setitem__(self, key, SelectableInt(0, info.length))
216 res = dict.__getitem__(self, key)
217 print ("spr returning", key, res)
218 return res
219
220 def __setitem__(self, key, value):
221 if isinstance(key, SelectableInt):
222 key = key.value
223 key = special_sprs.get(key, key)
224 print ("setting spr", key, value)
225 dict.__setitem__(self, key, value)
226
227 def __call__(self, ridx):
228 return self[ridx]
229
230
231 class ISACaller:
232 # decoder2 - an instance of power_decoder2
233 # regfile - a list of initial values for the registers
234 # initial_{etc} - initial values for SPRs, Condition Register, Mem, MSR
235 # respect_pc - tracks the program counter. requires initial_insns
236 def __init__(self, decoder2, regfile, initial_sprs=None, initial_cr=0,
237 initial_mem=None, initial_msr=0,
238 initial_insns=None, respect_pc=False,
239 disassembly=None):
240
241 self.respect_pc = respect_pc
242 if initial_sprs is None:
243 initial_sprs = {}
244 if initial_mem is None:
245 initial_mem = {}
246 if initial_insns is None:
247 initial_insns = {}
248 assert self.respect_pc == False, "instructions required to honor pc"
249
250 print ("ISACaller insns", respect_pc, initial_insns, disassembly)
251
252 # "fake program counter" mode (for unit testing)
253 self.fake_pc = 0
254 if not respect_pc:
255 if isinstance(initial_mem, tuple):
256 self.fake_pc = initial_mem[0]
257
258 # disassembly: we need this for now (not given from the decoder)
259 self.disassembly = {}
260 if disassembly:
261 for i, code in enumerate(disassembly):
262 self.disassembly[i*4 + self.fake_pc] = code
263
264 # set up registers, instruction memory, data memory, PC, SPRs, MSR
265 self.gpr = GPR(decoder2, regfile)
266 self.mem = Mem(row_bytes=8, initial_mem=initial_mem)
267 self.imem = Mem(row_bytes=4, initial_mem=initial_insns)
268 self.pc = PC()
269 self.spr = SPR(decoder2, initial_sprs)
270 self.msr = SelectableInt(initial_msr, 64) # underlying reg
271
272 # TODO, needed here:
273 # FPR (same as GPR except for FP nums)
274 # 4.2.2 p124 FPSCR (definitely "separate" - not in SPR)
275 # note that mffs, mcrfs, mtfsf "manage" this FPSCR
276 # 2.3.1 CR (and sub-fields CR0..CR6 - CR0 SO comes from XER.SO)
277 # note that mfocrf, mfcr, mtcr, mtocrf, mcrxrx "manage" CRs
278 # -- Done
279 # 2.3.2 LR (actually SPR #8) -- Done
280 # 2.3.3 CTR (actually SPR #9) -- Done
281 # 2.3.4 TAR (actually SPR #815)
282 # 3.2.2 p45 XER (actually SPR #1) -- Done
283 # 3.2.3 p46 p232 VRSAVE (actually SPR #256)
284
285 # create CR then allow portions of it to be "selectable" (below)
286 self._cr = SelectableInt(initial_cr, 64) # underlying reg
287 self.cr = FieldSelectableInt(self._cr, list(range(32,64)))
288
289 # "undefined", just set to variable-bit-width int (use exts "max")
290 self.undefined = SelectableInt(0, 256) # TODO, not hard-code 256!
291
292 self.namespace = {}
293 self.namespace.update(self.spr)
294 self.namespace.update({'GPR': self.gpr,
295 'MEM': self.mem,
296 'SPR': self.spr,
297 'memassign': self.memassign,
298 'NIA': self.pc.NIA,
299 'CIA': self.pc.CIA,
300 'CR': self.cr,
301 'MSR': self.msr,
302 'undefined': self.undefined,
303 'mode_is_64bit': True,
304 'SO': XER_bits['SO']
305 })
306
307
308 # field-selectable versions of Condition Register TODO check bitranges?
309 self.crl = []
310 for i in range(8):
311 bits = tuple(range(i*4, (i+1)*4))# errr... maybe?
312 _cr = FieldSelectableInt(self.cr, bits)
313 self.crl.append(_cr)
314 self.namespace["CR%d" % i] = _cr
315
316 self.decoder = decoder2.dec
317 self.dec2 = decoder2
318
319 def TRAP(self, trap_addr=0x700):
320 print ("TRAP: TODO")
321 #self.namespace['NIA'] = trap_addr
322 #self.SRR0 = self.namespace['CIA'] + 4
323 #self.SRR1 = self.namespace['MSR']
324 #self.namespace['MSR'][45] = 1
325 # store CIA(+4?) in SRR0, set NIA to 0x700
326 # store MSR in SRR1, set MSR to um errr something, have to check spec
327
328 def memassign(self, ea, sz, val):
329 self.mem.memassign(ea, sz, val)
330
331 def prep_namespace(self, formname, op_fields):
332 # TODO: get field names from form in decoder*1* (not decoder2)
333 # decoder2 is hand-created, and decoder1.sigform is auto-generated
334 # from spec
335 # then "yield" fields only from op_fields rather than hard-coded
336 # list, here.
337 fields = self.decoder.sigforms[formname]
338 for name in op_fields:
339 if name == 'spr':
340 sig = getattr(fields, name.upper())
341 else:
342 sig = getattr(fields, name)
343 val = yield sig
344 if name in ['BF', 'BFA']:
345 self.namespace[name] = val
346 else:
347 self.namespace[name] = SelectableInt(val, sig.width)
348
349 self.namespace['XER'] = self.spr['XER']
350 self.namespace['CA'] = self.spr['XER'][XER_bits['CA']].value
351 self.namespace['CA32'] = self.spr['XER'][XER_bits['CA32']].value
352
353 def handle_carry_(self, inputs, outputs, already_done):
354 inv_a = yield self.dec2.e.invert_a
355 if inv_a:
356 inputs[0] = ~inputs[0]
357
358 imm_ok = yield self.dec2.e.imm_data.ok
359 if imm_ok:
360 imm = yield self.dec2.e.imm_data.data
361 inputs.append(SelectableInt(imm, 64))
362 assert len(outputs) >= 1
363 print ("outputs", repr(outputs))
364 if isinstance(outputs, list) or isinstance(outputs, tuple):
365 output = outputs[0]
366 else:
367 output = outputs
368 gts = []
369 for x in inputs:
370 print ("gt input", x, output)
371 gt = (x > output)
372 gts.append(gt)
373 print(gts)
374 cy = 1 if any(gts) else 0
375 if not (1 & already_done):
376 self.spr['XER'][XER_bits['CA']] = cy
377
378 print ("inputs", inputs)
379 # 32 bit carry
380 gts = []
381 for x in inputs:
382 print ("input", x, output)
383 gt = (x[32:64] > output[32:64]) == SelectableInt(1, 1)
384 gts.append(gt)
385 cy32 = 1 if any(gts) else 0
386 if not (2 & already_done):
387 self.spr['XER'][XER_bits['CA32']] = cy32
388
389 def handle_overflow(self, inputs, outputs, div_overflow):
390 inv_a = yield self.dec2.e.invert_a
391 if inv_a:
392 inputs[0] = ~inputs[0]
393
394 imm_ok = yield self.dec2.e.imm_data.ok
395 if imm_ok:
396 imm = yield self.dec2.e.imm_data.data
397 inputs.append(SelectableInt(imm, 64))
398 assert len(outputs) >= 1
399 print ("handle_overflow", inputs, outputs, div_overflow)
400 if len(inputs) < 2 and div_overflow != 1:
401 return
402
403 # div overflow is different: it's returned by the pseudo-code
404 # because it's more complex than can be done by analysing the output
405 if div_overflow == 1:
406 ov, ov32 = 1, 1
407 # arithmetic overflow can be done by analysing the input and output
408 elif len(inputs) >= 2:
409 output = outputs[0]
410
411 # OV (64-bit)
412 input_sgn = [exts(x.value, x.bits) < 0 for x in inputs]
413 output_sgn = exts(output.value, output.bits) < 0
414 ov = 1 if input_sgn[0] == input_sgn[1] and \
415 output_sgn != input_sgn[0] else 0
416
417 # OV (32-bit)
418 input32_sgn = [exts(x.value, 32) < 0 for x in inputs]
419 output32_sgn = exts(output.value, 32) < 0
420 ov32 = 1 if input32_sgn[0] == input32_sgn[1] and \
421 output32_sgn != input32_sgn[0] else 0
422
423 self.spr['XER'][XER_bits['OV']] = ov
424 self.spr['XER'][XER_bits['OV32']] = ov32
425 so = self.spr['XER'][XER_bits['SO']]
426 so = so | ov
427 self.spr['XER'][XER_bits['SO']] = so
428
429 def handle_comparison(self, outputs):
430 out = outputs[0]
431 out = exts(out.value, out.bits)
432 zero = SelectableInt(out == 0, 1)
433 positive = SelectableInt(out > 0, 1)
434 negative = SelectableInt(out < 0, 1)
435 SO = self.spr['XER'][XER_bits['SO']]
436 cr_field = selectconcat(negative, positive, zero, SO)
437 self.crl[0].eq(cr_field)
438
439 def set_pc(self, pc_val):
440 self.namespace['NIA'] = SelectableInt(pc_val, 64)
441 self.pc.update(self.namespace)
442
443 def setup_one(self):
444 """set up one instruction
445 """
446 if self.respect_pc:
447 pc = self.pc.CIA.value
448 else:
449 pc = self.fake_pc
450 self._pc = pc
451 ins = self.imem.ld(pc, 4, False, True)
452 if ins is None:
453 raise KeyError("no instruction at 0x%x" % pc)
454 print("setup: 0x%x 0x%x %s" % (pc, ins & 0xffffffff, bin(ins)))
455 print ("NIA, CIA", self.pc.CIA.value, self.pc.NIA.value)
456
457 yield self.dec2.dec.raw_opcode_in.eq(ins & 0xffffffff)
458 yield self.dec2.dec.bigendian.eq(0) # little / big?
459
460 def execute_one(self):
461 """execute one instruction
462 """
463 # get the disassembly code for this instruction
464 code = self.disassembly[self._pc]
465 print("sim-execute", hex(self._pc), code)
466 opname = code.split(' ')[0]
467 yield from self.call(opname)
468
469 if not self.respect_pc:
470 self.fake_pc += 4
471 print ("NIA, CIA", self.pc.CIA.value, self.pc.NIA.value)
472
473 def get_assembly_name(self):
474 # TODO, asmregs is from the spec, e.g. add RT,RA,RB
475 # see http://bugs.libre-riscv.org/show_bug.cgi?id=282
476 asmcode = yield self.dec2.dec.op.asmcode
477 asmop = insns.get(asmcode, None)
478
479 # sigh reconstruct the assembly instruction name
480 ov_en = yield self.dec2.e.oe.oe
481 ov_ok = yield self.dec2.e.oe.ok
482 if ov_en & ov_ok:
483 asmop += "."
484 lk = yield self.dec2.e.lk
485 if lk:
486 asmop += "l"
487 int_op = yield self.dec2.dec.op.internal_op
488 print ("int_op", int_op)
489 if int_op in [InternalOp.OP_B.value, InternalOp.OP_BC.value]:
490 AA = yield self.dec2.dec.fields.FormI.AA[0:-1]
491 print ("AA", AA)
492 if AA:
493 asmop += "a"
494 if int_op == InternalOp.OP_MFCR.value:
495 dec_insn = yield self.dec2.e.insn
496 if dec_insn & (1<<20) != 0: # sigh
497 asmop = 'mfocrf'
498 else:
499 asmop = 'mfcr'
500 # XXX TODO: for whatever weird reason this doesn't work
501 # https://bugs.libre-soc.org/show_bug.cgi?id=390
502 if int_op == InternalOp.OP_MTCRF.value:
503 dec_insn = yield self.dec2.e.insn
504 if dec_insn & (1<<20) != 0: # sigh
505 asmop = 'mtocrf'
506 else:
507 asmop = 'mtcrf'
508 return asmop
509
510 def call(self, name):
511 # TODO, asmregs is from the spec, e.g. add RT,RA,RB
512 # see http://bugs.libre-riscv.org/show_bug.cgi?id=282
513 asmop = yield from self.get_assembly_name()
514 print ("call", name, asmop)
515 if name not in ['mtcrf', 'mtocrf']:
516 assert name == asmop, "name %s != %s" % (name, asmop)
517
518 info = self.instrs[name]
519 yield from self.prep_namespace(info.form, info.op_fields)
520
521 # preserve order of register names
522 input_names = create_args(list(info.read_regs) + list(info.uninit_regs))
523 print(input_names)
524
525 # main registers (RT, RA ...)
526 inputs = []
527 for name in input_names:
528 regnum = yield getattr(self.decoder, name)
529 regname = "_" + name
530 self.namespace[regname] = regnum
531 print('reading reg %d' % regnum)
532 inputs.append(self.gpr(regnum))
533
534 # "special" registers
535 for special in info.special_regs:
536 if special in special_sprs:
537 inputs.append(self.spr[special])
538 else:
539 inputs.append(self.namespace[special])
540
541 print(inputs)
542 results = info.func(self, *inputs)
543 print(results)
544
545 # detect if CA/CA32 already in outputs (sra*, basically)
546 already_done = 0
547 if info.write_regs:
548 output_names = create_args(info.write_regs)
549 for name in output_names:
550 if name == 'CA':
551 already_done |= 1
552 if name == 'CA32':
553 already_done |= 2
554
555 print ("carry already done?", bin(already_done))
556 carry_en = yield self.dec2.e.output_carry
557 if carry_en:
558 yield from self.handle_carry_(inputs, results, already_done)
559
560 # detect if overflow was in return result
561 overflow = None
562 if info.write_regs:
563 for name, output in zip(output_names, results):
564 if name == 'overflow':
565 overflow = output
566
567 ov_en = yield self.dec2.e.oe.oe
568 ov_ok = yield self.dec2.e.oe.ok
569 print ("internal overflow", overflow)
570 if ov_en & ov_ok:
571 yield from self.handle_overflow(inputs, results, overflow)
572
573 rc_en = yield self.dec2.e.rc.data
574 if rc_en:
575 self.handle_comparison(results)
576
577 # any modified return results?
578 if info.write_regs:
579 for name, output in zip(output_names, results):
580 if name == 'overflow': # ignore, done already (above)
581 continue
582 if isinstance(output, int):
583 output = SelectableInt(output, 256)
584 if name in ['CA', 'CA32']:
585 if carry_en:
586 print ("writing %s to XER" % name, output)
587 self.spr['XER'][XER_bits[name]] = output.value
588 else:
589 print ("NOT writing %s to XER" % name, output)
590 elif name in info.special_regs:
591 print('writing special %s' % name, output, special_sprs)
592 if name in special_sprs:
593 self.spr[name] = output
594 else:
595 self.namespace[name].eq(output)
596 if name == 'MSR':
597 print ('msr written', hex(self.msr.value))
598 else:
599 regnum = yield getattr(self.decoder, name)
600 print('writing reg %d %s' % (regnum, str(output)))
601 if output.bits > 64:
602 output = SelectableInt(output.value, 64)
603 self.gpr[regnum] = output
604
605 # update program counter
606 self.pc.update(self.namespace)
607
608
609 def inject():
610 """Decorator factory.
611
612 this decorator will "inject" variables into the function's namespace,
613 from the *dictionary* in self.namespace. it therefore becomes possible
614 to make it look like a whole stack of variables which would otherwise
615 need "self." inserted in front of them (*and* for those variables to be
616 added to the instance) "appear" in the function.
617
618 "self.namespace['SI']" for example becomes accessible as just "SI" but
619 *only* inside the function, when decorated.
620 """
621 def variable_injector(func):
622 @wraps(func)
623 def decorator(*args, **kwargs):
624 try:
625 func_globals = func.__globals__ # Python 2.6+
626 except AttributeError:
627 func_globals = func.func_globals # Earlier versions.
628
629 context = args[0].namespace # variables to be injected
630 saved_values = func_globals.copy() # Shallow copy of dict.
631 func_globals.update(context)
632 result = func(*args, **kwargs)
633 args[0].namespace = func_globals
634 #exec (func.__code__, func_globals)
635
636 #finally:
637 # func_globals = saved_values # Undo changes.
638
639 return result
640
641 return decorator
642
643 return variable_injector
644