1 """core of the python-based POWER9 simulator
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.
9 * https://bugs.libre-soc.org/show_bug.cgi?id=424
12 from functools
import wraps
13 from soc
.decoder
.orderedset
import OrderedSet
14 from soc
.decoder
.selectable_int
import (FieldSelectableInt
, SelectableInt
,
16 from soc
.decoder
.power_enums
import (spr_dict
, spr_byname
, XER_bits
,
18 from soc
.decoder
.helpers
import exts
19 from soc
.consts
import PI
, MSR
21 from collections
import namedtuple
25 instruction_info
= namedtuple('instruction_info',
26 'func read_regs uninit_regs write_regs ' + \
27 'special_regs op_fields form asmregs')
37 def swap_order(x
, nbytes
):
38 x
= x
.to_bytes(nbytes
, byteorder
='little')
39 x
= int.from_bytes(x
, byteorder
='big', signed
=False)
43 def create_args(reglist
, extra
=None):
55 def __init__(self
, row_bytes
=8, initial_mem
=None):
57 self
.bytes_per_word
= row_bytes
58 self
.word_log2
= math
.ceil(math
.log2(row_bytes
))
59 print ("Sim-Mem", initial_mem
, self
.bytes_per_word
, self
.word_log2
)
63 # different types of memory data structures recognised (for convenience)
64 if isinstance(initial_mem
, list):
65 initial_mem
= (0, initial_mem
)
66 if isinstance(initial_mem
, tuple):
67 startaddr
, mem
= initial_mem
69 for i
, val
in enumerate(mem
):
70 initial_mem
[startaddr
+ row_bytes
*i
] = (val
, row_bytes
)
72 for addr
, (val
, width
) in initial_mem
.items():
73 #val = swap_order(val, width)
74 self
.st(addr
, val
, width
, swap
=False)
76 def _get_shifter_mask(self
, wid
, remainder
):
77 shifter
= ((self
.bytes_per_word
- wid
) - remainder
) * \
79 # XXX https://bugs.libre-soc.org/show_bug.cgi?id=377
81 shifter
= remainder
* 8
82 mask
= (1 << (wid
* 8)) - 1
83 print ("width,rem,shift,mask", wid
, remainder
, hex(shifter
), hex(mask
))
86 # TODO: Implement ld/st of lesser width
87 def ld(self
, address
, width
=8, swap
=True, check_in_mem
=False):
88 print("ld from addr 0x{:x} width {:d}".format(address
, width
))
89 remainder
= address
& (self
.bytes_per_word
- 1)
90 address
= address
>> self
.word_log2
91 assert remainder
& (width
- 1) == 0, "Unaligned access unsupported!"
92 if address
in self
.mem
:
93 val
= self
.mem
[address
]
98 print("mem @ 0x{:x} rem {:d} : 0x{:x}".format(address
, remainder
, val
))
100 if width
!= self
.bytes_per_word
:
101 shifter
, mask
= self
._get
_shifter
_mask
(width
, remainder
)
102 print ("masking", hex(val
), hex(mask
<<shifter
), shifter
)
103 val
= val
& (mask
<< shifter
)
106 val
= swap_order(val
, width
)
107 print("Read 0x{:x} from addr 0x{:x}".format(val
, address
))
110 def st(self
, addr
, v
, width
=8, swap
=True):
112 remainder
= addr
& (self
.bytes_per_word
- 1)
113 addr
= addr
>> self
.word_log2
114 print("Writing 0x{:x} to ST 0x{:x} memaddr 0x{:x}/{:x}".format(v
,
115 staddr
, addr
, remainder
, swap
))
116 assert remainder
& (width
- 1) == 0, "Unaligned access unsupported!"
118 v
= swap_order(v
, width
)
119 if width
!= self
.bytes_per_word
:
124 shifter
, mask
= self
._get
_shifter
_mask
(width
, remainder
)
125 val
&= ~
(mask
<< shifter
)
130 print("mem @ 0x{:x}: 0x{:x}".format(addr
, self
.mem
[addr
]))
132 def __call__(self
, addr
, sz
):
133 val
= self
.ld(addr
.value
, sz
)
134 print ("memread", addr
, sz
, val
)
135 return SelectableInt(val
, sz
*8)
137 def memassign(self
, addr
, sz
, val
):
138 print ("memassign", addr
, sz
, val
)
139 self
.st(addr
.value
, val
.value
, sz
)
143 def __init__(self
, decoder
, regfile
):
147 self
[i
] = SelectableInt(regfile
[i
], 64)
149 def __call__(self
, ridx
):
152 def set_form(self
, form
):
155 def getz(self
, rnum
):
156 #rnum = rnum.value # only SelectableInt allowed
157 print("GPR getzero", rnum
)
159 return SelectableInt(0, 64)
162 def _get_regnum(self
, attr
):
163 getform
= self
.sd
.sigforms
[self
.form
]
164 rnum
= getattr(getform
, attr
)
167 def ___getitem__(self
, attr
):
168 print("GPR getitem", attr
)
169 rnum
= self
._get
_regnum
(attr
)
170 return self
.regfile
[rnum
]
173 for i
in range(0, len(self
), 8):
176 s
.append("%08x" % self
[i
+j
].value
)
178 print("reg", "%2d" % i
, s
)
181 def __init__(self
, pc_init
=0):
182 self
.CIA
= SelectableInt(pc_init
, 64)
183 self
.NIA
= self
.CIA
+ SelectableInt(4, 64)
185 def update(self
, namespace
):
186 self
.CIA
= namespace
['NIA'].narrow(64)
187 self
.NIA
= self
.CIA
+ SelectableInt(4, 64)
188 namespace
['CIA'] = self
.CIA
189 namespace
['NIA'] = self
.NIA
193 def __init__(self
, dec2
, initial_sprs
={}):
196 for key
, v
in initial_sprs
.items():
197 if isinstance(key
, SelectableInt
):
199 key
= special_sprs
.get(key
, key
)
200 if isinstance(key
, int):
203 info
= spr_byname
[key
]
204 if not isinstance(v
, SelectableInt
):
205 v
= SelectableInt(v
, info
.length
)
208 def __getitem__(self
, key
):
209 print ("get spr", key
)
210 print ("dict", self
.items())
211 # if key in special_sprs get the special spr, otherwise return key
212 if isinstance(key
, SelectableInt
):
214 if isinstance(key
, int):
215 key
= spr_dict
[key
].SPR
216 key
= special_sprs
.get(key
, key
)
218 res
= dict.__getitem
__(self
, key
)
220 if isinstance(key
, int):
223 info
= spr_byname
[key
]
224 dict.__setitem
__(self
, key
, SelectableInt(0, info
.length
))
225 res
= dict.__getitem
__(self
, key
)
226 print ("spr returning", key
, res
)
229 def __setitem__(self
, key
, value
):
230 if isinstance(key
, SelectableInt
):
232 if isinstance(key
, int):
233 key
= spr_dict
[key
].SPR
234 print ("spr key", key
)
235 key
= special_sprs
.get(key
, key
)
236 print ("setting spr", key
, value
)
237 dict.__setitem
__(self
, key
, value
)
239 def __call__(self
, ridx
):
244 # decoder2 - an instance of power_decoder2
245 # regfile - a list of initial values for the registers
246 # initial_{etc} - initial values for SPRs, Condition Register, Mem, MSR
247 # respect_pc - tracks the program counter. requires initial_insns
248 def __init__(self
, decoder2
, regfile
, initial_sprs
=None, initial_cr
=0,
249 initial_mem
=None, initial_msr
=0,
250 initial_insns
=None, respect_pc
=False,
255 self
.bigendian
= bigendian
257 self
.respect_pc
= respect_pc
258 if initial_sprs
is None:
260 if initial_mem
is None:
262 if initial_insns
is None:
264 assert self
.respect_pc
== False, "instructions required to honor pc"
266 print ("ISACaller insns", respect_pc
, initial_insns
, disassembly
)
268 # "fake program counter" mode (for unit testing)
272 if isinstance(initial_mem
, tuple):
273 self
.fake_pc
= initial_mem
[0]
274 disasm_start
= self
.fake_pc
276 disasm_start
= initial_pc
278 # disassembly: we need this for now (not given from the decoder)
279 self
.disassembly
= {}
281 for i
, code
in enumerate(disassembly
):
282 self
.disassembly
[i
*4 + disasm_start
] = code
284 # set up registers, instruction memory, data memory, PC, SPRs, MSR
285 self
.gpr
= GPR(decoder2
, regfile
)
286 self
.mem
= Mem(row_bytes
=8, initial_mem
=initial_mem
)
287 self
.imem
= Mem(row_bytes
=4, initial_mem
=initial_insns
)
289 self
.spr
= SPR(decoder2
, initial_sprs
)
290 self
.msr
= SelectableInt(initial_msr
, 64) # underlying reg
293 # FPR (same as GPR except for FP nums)
294 # 4.2.2 p124 FPSCR (definitely "separate" - not in SPR)
295 # note that mffs, mcrfs, mtfsf "manage" this FPSCR
296 # 2.3.1 CR (and sub-fields CR0..CR6 - CR0 SO comes from XER.SO)
297 # note that mfocrf, mfcr, mtcr, mtocrf, mcrxrx "manage" CRs
299 # 2.3.2 LR (actually SPR #8) -- Done
300 # 2.3.3 CTR (actually SPR #9) -- Done
301 # 2.3.4 TAR (actually SPR #815)
302 # 3.2.2 p45 XER (actually SPR #1) -- Done
303 # 3.2.3 p46 p232 VRSAVE (actually SPR #256)
305 # create CR then allow portions of it to be "selectable" (below)
306 self
._cr
= SelectableInt(initial_cr
, 64) # underlying reg
307 self
.cr
= FieldSelectableInt(self
._cr
, list(range(32,64)))
309 # "undefined", just set to variable-bit-width int (use exts "max")
310 self
.undefined
= SelectableInt(0, 256) # TODO, not hard-code 256!
313 self
.namespace
.update(self
.spr
)
314 self
.namespace
.update({'GPR': self
.gpr
,
317 'memassign': self
.memassign
,
322 'undefined': self
.undefined
,
323 'mode_is_64bit': True,
327 # update pc to requested start point
328 self
.set_pc(initial_pc
)
330 # field-selectable versions of Condition Register TODO check bitranges?
333 bits
= tuple(range(i
*4, (i
+1)*4))# errr... maybe?
334 _cr
= FieldSelectableInt(self
.cr
, bits
)
336 self
.namespace
["CR%d" % i
] = _cr
338 self
.decoder
= decoder2
.dec
341 def TRAP(self
, trap_addr
=0x700, trap_bit
=PI
.TRAP
):
342 print ("TRAP:", hex(trap_addr
))
343 # store CIA(+4?) in SRR0, set NIA to 0x700
344 # store MSR in SRR1, set MSR to um errr something, have to check spec
345 self
.spr
['SRR0'] = self
.pc
.CIA
346 self
.spr
['SRR1'] = self
.namespace
['MSR']
347 self
.trap_nia
= SelectableInt(trap_addr
, 64)
348 self
.namespace
['MSR'][63-trap_bit
] = 1
350 def memassign(self
, ea
, sz
, val
):
351 self
.mem
.memassign(ea
, sz
, val
)
353 def prep_namespace(self
, formname
, op_fields
):
354 # TODO: get field names from form in decoder*1* (not decoder2)
355 # decoder2 is hand-created, and decoder1.sigform is auto-generated
357 # then "yield" fields only from op_fields rather than hard-coded
359 fields
= self
.decoder
.sigforms
[formname
]
360 for name
in op_fields
:
362 sig
= getattr(fields
, name
.upper())
364 sig
= getattr(fields
, name
)
366 if name
in ['BF', 'BFA']:
367 self
.namespace
[name
] = val
369 self
.namespace
[name
] = SelectableInt(val
, sig
.width
)
371 self
.namespace
['XER'] = self
.spr
['XER']
372 self
.namespace
['CA'] = self
.spr
['XER'][XER_bits
['CA']].value
373 self
.namespace
['CA32'] = self
.spr
['XER'][XER_bits
['CA32']].value
375 def handle_carry_(self
, inputs
, outputs
, already_done
):
376 inv_a
= yield self
.dec2
.e
.do
.invert_a
378 inputs
[0] = ~inputs
[0]
380 imm_ok
= yield self
.dec2
.e
.do
.imm_data
.ok
382 imm
= yield self
.dec2
.e
.do
.imm_data
.data
383 inputs
.append(SelectableInt(imm
, 64))
384 assert len(outputs
) >= 1
385 print ("outputs", repr(outputs
))
386 if isinstance(outputs
, list) or isinstance(outputs
, tuple):
392 print ("gt input", x
, output
)
396 cy
= 1 if any(gts
) else 0
397 if not (1 & already_done
):
398 self
.spr
['XER'][XER_bits
['CA']] = cy
400 print ("inputs", inputs
)
404 print ("input", x
, output
)
405 gt
= (x
[32:64] > output
[32:64]) == SelectableInt(1, 1)
407 cy32
= 1 if any(gts
) else 0
408 if not (2 & already_done
):
409 self
.spr
['XER'][XER_bits
['CA32']] = cy32
411 def handle_overflow(self
, inputs
, outputs
, div_overflow
):
412 inv_a
= yield self
.dec2
.e
.do
.invert_a
414 inputs
[0] = ~inputs
[0]
416 imm_ok
= yield self
.dec2
.e
.do
.imm_data
.ok
418 imm
= yield self
.dec2
.e
.do
.imm_data
.data
419 inputs
.append(SelectableInt(imm
, 64))
420 assert len(outputs
) >= 1
421 print ("handle_overflow", inputs
, outputs
, div_overflow
)
422 if len(inputs
) < 2 and div_overflow
is None:
425 # div overflow is different: it's returned by the pseudo-code
426 # because it's more complex than can be done by analysing the output
427 if div_overflow
is not None:
428 ov
, ov32
= div_overflow
, div_overflow
429 # arithmetic overflow can be done by analysing the input and output
430 elif len(inputs
) >= 2:
434 input_sgn
= [exts(x
.value
, x
.bits
) < 0 for x
in inputs
]
435 output_sgn
= exts(output
.value
, output
.bits
) < 0
436 ov
= 1 if input_sgn
[0] == input_sgn
[1] and \
437 output_sgn
!= input_sgn
[0] else 0
440 input32_sgn
= [exts(x
.value
, 32) < 0 for x
in inputs
]
441 output32_sgn
= exts(output
.value
, 32) < 0
442 ov32
= 1 if input32_sgn
[0] == input32_sgn
[1] and \
443 output32_sgn
!= input32_sgn
[0] else 0
445 self
.spr
['XER'][XER_bits
['OV']] = ov
446 self
.spr
['XER'][XER_bits
['OV32']] = ov32
447 so
= self
.spr
['XER'][XER_bits
['SO']]
449 self
.spr
['XER'][XER_bits
['SO']] = so
451 def handle_comparison(self
, outputs
):
453 print ("handle_comparison", out
.bits
, hex(out
.value
))
454 # TODO - XXX *processor* in 32-bit mode
455 # https://bugs.libre-soc.org/show_bug.cgi?id=424
457 # o32 = exts(out.value, 32)
458 # print ("handle_comparison exts 32 bit", hex(o32))
459 out
= exts(out
.value
, out
.bits
)
460 print ("handle_comparison exts", hex(out
))
461 zero
= SelectableInt(out
== 0, 1)
462 positive
= SelectableInt(out
> 0, 1)
463 negative
= SelectableInt(out
< 0, 1)
464 SO
= self
.spr
['XER'][XER_bits
['SO']]
465 print ("handle_comparison SO", SO
)
466 cr_field
= selectconcat(negative
, positive
, zero
, SO
)
467 self
.crl
[0].eq(cr_field
)
469 def set_pc(self
, pc_val
):
470 self
.namespace
['NIA'] = SelectableInt(pc_val
, 64)
471 self
.pc
.update(self
.namespace
)
474 """set up one instruction
477 pc
= self
.pc
.CIA
.value
481 ins
= self
.imem
.ld(pc
, 4, False, True)
483 raise KeyError("no instruction at 0x%x" % pc
)
484 print("setup: 0x%x 0x%x %s" % (pc
, ins
& 0xffffffff, bin(ins
)))
485 print ("CIA NIA", self
.respect_pc
, self
.pc
.CIA
.value
, self
.pc
.NIA
.value
)
487 yield self
.dec2
.dec
.raw_opcode_in
.eq(ins
& 0xffffffff)
488 yield self
.dec2
.dec
.bigendian
.eq(self
.bigendian
)
490 def execute_one(self
):
491 """execute one instruction
493 # get the disassembly code for this instruction
494 code
= self
.disassembly
[self
._pc
]
495 print("sim-execute", hex(self
._pc
), code
)
496 opname
= code
.split(' ')[0]
497 yield from self
.call(opname
)
499 if not self
.respect_pc
:
501 print ("execute one, CIA NIA", self
.pc
.CIA
.value
, self
.pc
.NIA
.value
)
503 def get_assembly_name(self
):
504 # TODO, asmregs is from the spec, e.g. add RT,RA,RB
505 # see http://bugs.libre-riscv.org/show_bug.cgi?id=282
506 asmcode
= yield self
.dec2
.dec
.op
.asmcode
507 print ("get assembly name asmcode", asmcode
)
508 asmop
= insns
.get(asmcode
, None)
509 int_op
= yield self
.dec2
.dec
.op
.internal_op
511 # sigh reconstruct the assembly instruction name
512 ov_en
= yield self
.dec2
.e
.do
.oe
.oe
513 ov_ok
= yield self
.dec2
.e
.do
.oe
.ok
514 rc_en
= yield self
.dec2
.e
.do
.rc
.data
515 rc_ok
= yield self
.dec2
.e
.do
.rc
.ok
516 # grrrr have to special-case MUL op (see DecodeOE)
517 print ("ov en rc en", ov_ok
, ov_en
, rc_ok
, rc_en
, int_op
)
518 if int_op
in [InternalOp
.OP_MUL_H64
.value
, InternalOp
.OP_MUL_H32
.value
]:
525 lk
= yield self
.dec2
.e
.do
.lk
528 print ("int_op", int_op
)
529 if int_op
in [InternalOp
.OP_B
.value
, InternalOp
.OP_BC
.value
]:
530 AA
= yield self
.dec2
.dec
.fields
.FormI
.AA
[0:-1]
534 if int_op
== InternalOp
.OP_MFCR
.value
:
535 dec_insn
= yield self
.dec2
.e
.do
.insn
536 if dec_insn
& (1<<20) != 0: # sigh
540 # XXX TODO: for whatever weird reason this doesn't work
541 # https://bugs.libre-soc.org/show_bug.cgi?id=390
542 if int_op
== InternalOp
.OP_MTCRF
.value
:
543 dec_insn
= yield self
.dec2
.e
.do
.insn
544 if dec_insn
& (1<<20) != 0: # sigh
550 def call(self
, name
):
551 name
= name
.strip() # remove spaces if not already done so
553 print ("halted - not executing", name
)
556 # TODO, asmregs is from the spec, e.g. add RT,RA,RB
557 # see http://bugs.libre-riscv.org/show_bug.cgi?id=282
558 asmop
= yield from self
.get_assembly_name()
559 print ("call", name
, asmop
)
561 # check halted condition
566 # check illegal instruction
568 if name
not in ['mtcrf', 'mtocrf']:
569 illegal
= name
!= asmop
572 print ("name %s != %s - calling ILLEGAL trap" % (name
, asmop
))
573 self
.TRAP(0x700, PI
.ILLEG
)
574 self
.namespace
['NIA'] = self
.trap_nia
575 self
.pc
.update(self
.namespace
)
578 info
= self
.instrs
[name
]
579 yield from self
.prep_namespace(info
.form
, info
.op_fields
)
581 # preserve order of register names
582 input_names
= create_args(list(info
.read_regs
) +
583 list(info
.uninit_regs
))
586 # main registers (RT, RA ...)
588 for name
in input_names
:
589 regnum
= yield getattr(self
.decoder
, name
)
591 self
.namespace
[regname
] = regnum
592 print('reading reg %d' % regnum
)
593 inputs
.append(self
.gpr(regnum
))
595 # "special" registers
596 for special
in info
.special_regs
:
597 if special
in special_sprs
:
598 inputs
.append(self
.spr
[special
])
600 inputs
.append(self
.namespace
[special
])
602 # clear trap (trap) NIA
606 results
= info
.func(self
, *inputs
)
609 # "inject" decorator takes namespace from function locals: we need to
610 # overwrite NIA being overwritten (sigh)
611 if self
.trap_nia
is not None:
612 self
.namespace
['NIA'] = self
.trap_nia
614 print ("after func", self
.namespace
['CIA'], self
.namespace
['NIA'])
616 # detect if CA/CA32 already in outputs (sra*, basically)
619 output_names
= create_args(info
.write_regs
)
620 for name
in output_names
:
626 print ("carry already done?", bin(already_done
))
627 carry_en
= yield self
.dec2
.e
.do
.output_carry
629 yield from self
.handle_carry_(inputs
, results
, already_done
)
631 # detect if overflow was in return result
634 for name
, output
in zip(output_names
, results
):
635 if name
== 'overflow':
638 ov_en
= yield self
.dec2
.e
.do
.oe
.oe
639 ov_ok
= yield self
.dec2
.e
.do
.oe
.ok
640 print ("internal overflow", overflow
, ov_en
, ov_ok
)
642 yield from self
.handle_overflow(inputs
, results
, overflow
)
644 rc_en
= yield self
.dec2
.e
.do
.rc
.data
646 self
.handle_comparison(results
)
648 # any modified return results?
650 for name
, output
in zip(output_names
, results
):
651 if name
== 'overflow': # ignore, done already (above)
653 if isinstance(output
, int):
654 output
= SelectableInt(output
, 256)
655 if name
in ['CA', 'CA32']:
657 print ("writing %s to XER" % name
, output
)
658 self
.spr
['XER'][XER_bits
[name
]] = output
.value
660 print ("NOT writing %s to XER" % name
, output
)
661 elif name
in info
.special_regs
:
662 print('writing special %s' % name
, output
, special_sprs
)
663 if name
in special_sprs
:
664 self
.spr
[name
] = output
666 self
.namespace
[name
].eq(output
)
668 print ('msr written', hex(self
.msr
.value
))
670 regnum
= yield getattr(self
.decoder
, name
)
671 print('writing reg %d %s' % (regnum
, str(output
)))
673 output
= SelectableInt(output
.value
, 64)
674 self
.gpr
[regnum
] = output
676 print ("end of call", self
.namespace
['CIA'], self
.namespace
['NIA'])
677 # UPDATE program counter
678 self
.pc
.update(self
.namespace
)
682 """Decorator factory.
684 this decorator will "inject" variables into the function's namespace,
685 from the *dictionary* in self.namespace. it therefore becomes possible
686 to make it look like a whole stack of variables which would otherwise
687 need "self." inserted in front of them (*and* for those variables to be
688 added to the instance) "appear" in the function.
690 "self.namespace['SI']" for example becomes accessible as just "SI" but
691 *only* inside the function, when decorated.
693 def variable_injector(func
):
695 def decorator(*args
, **kwargs
):
697 func_globals
= func
.__globals
__ # Python 2.6+
698 except AttributeError:
699 func_globals
= func
.func_globals
# Earlier versions.
701 context
= args
[0].namespace
# variables to be injected
702 saved_values
= func_globals
.copy() # Shallow copy of dict.
703 func_globals
.update(context
)
704 result
= func(*args
, **kwargs
)
705 print ("globals after", func_globals
['CIA'], func_globals
['NIA'])
706 print ("args[0]", args
[0].namespace
['CIA'],
707 args
[0].namespace
['NIA'])
708 args
[0].namespace
= func_globals
709 #exec (func.__code__, func_globals)
712 # func_globals = saved_values # Undo changes.
718 return variable_injector