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.
8 from functools
import wraps
9 from soc
.decoder
.orderedset
import OrderedSet
10 from soc
.decoder
.selectable_int
import (FieldSelectableInt
, SelectableInt
,
12 from soc
.decoder
.power_enums
import (spr_dict
, spr_byname
, XER_bits
,
14 from soc
.decoder
.helpers
import exts
, trunc_div
, trunc_rem
15 from collections
import namedtuple
19 instruction_info
= namedtuple('instruction_info',
20 'func read_regs uninit_regs write_regs ' + \
21 'special_regs op_fields form asmregs')
31 def swap_order(x
, nbytes
):
32 x
= x
.to_bytes(nbytes
, byteorder
='little')
33 x
= int.from_bytes(x
, byteorder
='big', signed
=False)
37 def create_args(reglist
, extra
=None):
49 def __init__(self
, row_bytes
=8, initial_mem
=None):
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
)
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
63 for i
, val
in enumerate(mem
):
64 initial_mem
[startaddr
+ row_bytes
*i
] = (val
, row_bytes
)
66 for addr
, (val
, width
) in initial_mem
.items():
67 #val = swap_order(val, width)
68 self
.st(addr
, val
, width
, swap
=False)
70 def _get_shifter_mask(self
, wid
, remainder
):
71 shifter
= ((self
.bytes_per_word
- wid
) - remainder
) * \
73 # XXX https://bugs.libre-soc.org/show_bug.cgi?id=377
75 shifter
= remainder
* 8
76 mask
= (1 << (wid
* 8)) - 1
77 print ("width,rem,shift,mask", wid
, remainder
, hex(shifter
), hex(mask
))
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
]
92 print("mem @ 0x{:x} rem {:d} : 0x{:x}".format(address
, remainder
, val
))
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
)
100 val
= swap_order(val
, width
)
101 print("Read 0x{:x} from addr 0x{:x}".format(val
, address
))
104 def st(self
, addr
, v
, width
=8, swap
=True):
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!"
112 v
= swap_order(v
, width
)
113 if width
!= self
.bytes_per_word
:
118 shifter
, mask
= self
._get
_shifter
_mask
(width
, remainder
)
119 val
&= ~
(mask
<< shifter
)
124 print("mem @ 0x{:x}: 0x{:x}".format(addr
, self
.mem
[addr
]))
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)
131 def memassign(self
, addr
, sz
, val
):
132 print ("memassign", addr
, sz
, val
)
133 self
.st(addr
.value
, val
.value
, sz
)
137 def __init__(self
, decoder
, regfile
):
141 self
[i
] = SelectableInt(regfile
[i
], 64)
143 def __call__(self
, ridx
):
146 def set_form(self
, form
):
149 def getz(self
, rnum
):
150 #rnum = rnum.value # only SelectableInt allowed
151 print("GPR getzero", rnum
)
153 return SelectableInt(0, 64)
156 def _get_regnum(self
, attr
):
157 getform
= self
.sd
.sigforms
[self
.form
]
158 rnum
= getattr(getform
, attr
)
161 def ___getitem__(self
, attr
):
162 print("GPR getitem", attr
)
163 rnum
= self
._get
_regnum
(attr
)
164 return self
.regfile
[rnum
]
167 for i
in range(0, len(self
), 8):
170 s
.append("%08x" % self
[i
+j
].value
)
172 print("reg", "%2d" % i
, s
)
175 def __init__(self
, pc_init
=0):
176 self
.CIA
= SelectableInt(pc_init
, 64)
177 self
.NIA
= self
.CIA
+ SelectableInt(4, 64)
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
187 def __init__(self
, dec2
, initial_sprs
={}):
190 for key
, v
in initial_sprs
.items():
191 if isinstance(key
, SelectableInt
):
193 key
= special_sprs
.get(key
, key
)
194 if isinstance(key
, int):
197 info
= spr_byname
[key
]
198 if not isinstance(v
, SelectableInt
):
199 v
= SelectableInt(v
, info
.length
)
202 def __getitem__(self
, key
):
203 print ("get spr", key
)
204 print ("dict", self
.items())
205 # if key in special_sprs get the special spr, otherwise return key
206 if isinstance(key
, SelectableInt
):
208 if isinstance(key
, int):
209 key
= spr_dict
[key
].SPR
210 key
= special_sprs
.get(key
, key
)
212 res
= dict.__getitem
__(self
, key
)
214 if isinstance(key
, int):
217 info
= spr_byname
[key
]
218 dict.__setitem
__(self
, key
, SelectableInt(0, info
.length
))
219 res
= dict.__getitem
__(self
, key
)
220 print ("spr returning", key
, res
)
223 def __setitem__(self
, key
, value
):
224 if isinstance(key
, SelectableInt
):
226 if isinstance(key
, int):
227 key
= spr_dict
[key
].SPR
228 print ("spr key", key
)
229 key
= special_sprs
.get(key
, key
)
230 print ("setting spr", key
, value
)
231 dict.__setitem
__(self
, key
, value
)
233 def __call__(self
, ridx
):
238 # decoder2 - an instance of power_decoder2
239 # regfile - a list of initial values for the registers
240 # initial_{etc} - initial values for SPRs, Condition Register, Mem, MSR
241 # respect_pc - tracks the program counter. requires initial_insns
242 def __init__(self
, decoder2
, regfile
, initial_sprs
=None, initial_cr
=0,
243 initial_mem
=None, initial_msr
=0,
244 initial_insns
=None, respect_pc
=False,
247 self
.respect_pc
= respect_pc
248 if initial_sprs
is None:
250 if initial_mem
is None:
252 if initial_insns
is None:
254 assert self
.respect_pc
== False, "instructions required to honor pc"
256 print ("ISACaller insns", respect_pc
, initial_insns
, disassembly
)
258 # "fake program counter" mode (for unit testing)
261 if isinstance(initial_mem
, tuple):
262 self
.fake_pc
= initial_mem
[0]
264 # disassembly: we need this for now (not given from the decoder)
265 self
.disassembly
= {}
267 for i
, code
in enumerate(disassembly
):
268 self
.disassembly
[i
*4 + self
.fake_pc
] = code
270 # set up registers, instruction memory, data memory, PC, SPRs, MSR
271 self
.gpr
= GPR(decoder2
, regfile
)
272 self
.mem
= Mem(row_bytes
=8, initial_mem
=initial_mem
)
273 self
.imem
= Mem(row_bytes
=4, initial_mem
=initial_insns
)
275 self
.spr
= SPR(decoder2
, initial_sprs
)
276 self
.msr
= SelectableInt(initial_msr
, 64) # underlying reg
279 # FPR (same as GPR except for FP nums)
280 # 4.2.2 p124 FPSCR (definitely "separate" - not in SPR)
281 # note that mffs, mcrfs, mtfsf "manage" this FPSCR
282 # 2.3.1 CR (and sub-fields CR0..CR6 - CR0 SO comes from XER.SO)
283 # note that mfocrf, mfcr, mtcr, mtocrf, mcrxrx "manage" CRs
285 # 2.3.2 LR (actually SPR #8) -- Done
286 # 2.3.3 CTR (actually SPR #9) -- Done
287 # 2.3.4 TAR (actually SPR #815)
288 # 3.2.2 p45 XER (actually SPR #1) -- Done
289 # 3.2.3 p46 p232 VRSAVE (actually SPR #256)
291 # create CR then allow portions of it to be "selectable" (below)
292 self
._cr
= SelectableInt(initial_cr
, 64) # underlying reg
293 self
.cr
= FieldSelectableInt(self
._cr
, list(range(32,64)))
295 # "undefined", just set to variable-bit-width int (use exts "max")
296 self
.undefined
= SelectableInt(0, 256) # TODO, not hard-code 256!
299 self
.namespace
.update(self
.spr
)
300 self
.namespace
.update({'GPR': self
.gpr
,
303 'memassign': self
.memassign
,
308 'undefined': self
.undefined
,
309 'mode_is_64bit': True,
314 # field-selectable versions of Condition Register TODO check bitranges?
317 bits
= tuple(range(i
*4, (i
+1)*4))# errr... maybe?
318 _cr
= FieldSelectableInt(self
.cr
, bits
)
320 self
.namespace
["CR%d" % i
] = _cr
322 self
.decoder
= decoder2
.dec
325 def TRAP(self
, trap_addr
=0x700):
327 #self.namespace['NIA'] = trap_addr
328 #self.SRR0 = self.namespace['CIA'] + 4
329 #self.SRR1 = self.namespace['MSR']
330 #self.namespace['MSR'][45] = 1
331 # store CIA(+4?) in SRR0, set NIA to 0x700
332 # store MSR in SRR1, set MSR to um errr something, have to check spec
334 def memassign(self
, ea
, sz
, val
):
335 self
.mem
.memassign(ea
, sz
, val
)
337 def prep_namespace(self
, formname
, op_fields
):
338 # TODO: get field names from form in decoder*1* (not decoder2)
339 # decoder2 is hand-created, and decoder1.sigform is auto-generated
341 # then "yield" fields only from op_fields rather than hard-coded
343 fields
= self
.decoder
.sigforms
[formname
]
344 for name
in op_fields
:
346 sig
= getattr(fields
, name
.upper())
348 sig
= getattr(fields
, name
)
350 if name
in ['BF', 'BFA']:
351 self
.namespace
[name
] = val
353 self
.namespace
[name
] = SelectableInt(val
, sig
.width
)
355 self
.namespace
['XER'] = self
.spr
['XER']
356 self
.namespace
['CA'] = self
.spr
['XER'][XER_bits
['CA']].value
357 self
.namespace
['CA32'] = self
.spr
['XER'][XER_bits
['CA32']].value
359 def handle_carry_(self
, inputs
, outputs
, already_done
):
360 inv_a
= yield self
.dec2
.e
.invert_a
362 inputs
[0] = ~inputs
[0]
364 imm_ok
= yield self
.dec2
.e
.imm_data
.ok
366 imm
= yield self
.dec2
.e
.imm_data
.data
367 inputs
.append(SelectableInt(imm
, 64))
368 assert len(outputs
) >= 1
369 print ("outputs", repr(outputs
))
370 if isinstance(outputs
, list) or isinstance(outputs
, tuple):
376 print ("gt input", x
, output
)
380 cy
= 1 if any(gts
) else 0
381 if not (1 & already_done
):
382 self
.spr
['XER'][XER_bits
['CA']] = cy
384 print ("inputs", inputs
)
388 print ("input", x
, output
)
389 gt
= (x
[32:64] > output
[32:64]) == SelectableInt(1, 1)
391 cy32
= 1 if any(gts
) else 0
392 if not (2 & already_done
):
393 self
.spr
['XER'][XER_bits
['CA32']] = cy32
395 def handle_overflow(self
, inputs
, outputs
, div_overflow
):
396 inv_a
= yield self
.dec2
.e
.invert_a
398 inputs
[0] = ~inputs
[0]
400 imm_ok
= yield self
.dec2
.e
.imm_data
.ok
402 imm
= yield self
.dec2
.e
.imm_data
.data
403 inputs
.append(SelectableInt(imm
, 64))
404 assert len(outputs
) >= 1
405 print ("handle_overflow", inputs
, outputs
, div_overflow
)
406 if len(inputs
) < 2 and div_overflow
!= 1:
409 # div overflow is different: it's returned by the pseudo-code
410 # because it's more complex than can be done by analysing the output
411 if div_overflow
== 1:
413 # arithmetic overflow can be done by analysing the input and output
414 elif len(inputs
) >= 2:
418 input_sgn
= [exts(x
.value
, x
.bits
) < 0 for x
in inputs
]
419 output_sgn
= exts(output
.value
, output
.bits
) < 0
420 ov
= 1 if input_sgn
[0] == input_sgn
[1] and \
421 output_sgn
!= input_sgn
[0] else 0
424 input32_sgn
= [exts(x
.value
, 32) < 0 for x
in inputs
]
425 output32_sgn
= exts(output
.value
, 32) < 0
426 ov32
= 1 if input32_sgn
[0] == input32_sgn
[1] and \
427 output32_sgn
!= input32_sgn
[0] else 0
429 self
.spr
['XER'][XER_bits
['OV']] = ov
430 self
.spr
['XER'][XER_bits
['OV32']] = ov32
431 so
= self
.spr
['XER'][XER_bits
['SO']]
433 self
.spr
['XER'][XER_bits
['SO']] = so
435 def handle_comparison(self
, outputs
):
437 out
= exts(out
.value
, out
.bits
)
438 zero
= SelectableInt(out
== 0, 1)
439 positive
= SelectableInt(out
> 0, 1)
440 negative
= SelectableInt(out
< 0, 1)
441 SO
= self
.spr
['XER'][XER_bits
['SO']]
442 cr_field
= selectconcat(negative
, positive
, zero
, SO
)
443 self
.crl
[0].eq(cr_field
)
445 def set_pc(self
, pc_val
):
446 self
.namespace
['NIA'] = SelectableInt(pc_val
, 64)
447 self
.pc
.update(self
.namespace
)
450 """set up one instruction
453 pc
= self
.pc
.CIA
.value
457 ins
= self
.imem
.ld(pc
, 4, False, True)
459 raise KeyError("no instruction at 0x%x" % pc
)
460 print("setup: 0x%x 0x%x %s" % (pc
, ins
& 0xffffffff, bin(ins
)))
461 print ("NIA, CIA", self
.pc
.CIA
.value
, self
.pc
.NIA
.value
)
463 yield self
.dec2
.dec
.raw_opcode_in
.eq(ins
& 0xffffffff)
464 yield self
.dec2
.dec
.bigendian
.eq(0) # little / big?
466 def execute_one(self
):
467 """execute one instruction
469 # get the disassembly code for this instruction
470 code
= self
.disassembly
[self
._pc
]
471 print("sim-execute", hex(self
._pc
), code
)
472 opname
= code
.split(' ')[0]
473 yield from self
.call(opname
)
475 if not self
.respect_pc
:
477 print ("NIA, CIA", self
.pc
.CIA
.value
, self
.pc
.NIA
.value
)
479 def get_assembly_name(self
):
480 # TODO, asmregs is from the spec, e.g. add RT,RA,RB
481 # see http://bugs.libre-riscv.org/show_bug.cgi?id=282
482 asmcode
= yield self
.dec2
.dec
.op
.asmcode
483 asmop
= insns
.get(asmcode
, None)
485 # sigh reconstruct the assembly instruction name
486 ov_en
= yield self
.dec2
.e
.oe
.oe
487 ov_ok
= yield self
.dec2
.e
.oe
.ok
490 lk
= yield self
.dec2
.e
.lk
493 int_op
= yield self
.dec2
.dec
.op
.internal_op
494 print ("int_op", int_op
)
495 if int_op
in [InternalOp
.OP_B
.value
, InternalOp
.OP_BC
.value
]:
496 AA
= yield self
.dec2
.dec
.fields
.FormI
.AA
[0:-1]
500 if int_op
== InternalOp
.OP_MFCR
.value
:
501 dec_insn
= yield self
.dec2
.e
.insn
502 if dec_insn
& (1<<20) != 0: # sigh
506 # XXX TODO: for whatever weird reason this doesn't work
507 # https://bugs.libre-soc.org/show_bug.cgi?id=390
508 if int_op
== InternalOp
.OP_MTCRF
.value
:
509 dec_insn
= yield self
.dec2
.e
.insn
510 if dec_insn
& (1<<20) != 0: # sigh
516 def call(self
, name
):
517 # TODO, asmregs is from the spec, e.g. add RT,RA,RB
518 # see http://bugs.libre-riscv.org/show_bug.cgi?id=282
519 asmop
= yield from self
.get_assembly_name()
520 print ("call", name
, asmop
)
521 if name
not in ['mtcrf', 'mtocrf']:
522 assert name
== asmop
, "name %s != %s" % (name
, asmop
)
524 info
= self
.instrs
[name
]
525 yield from self
.prep_namespace(info
.form
, info
.op_fields
)
527 # preserve order of register names
528 input_names
= create_args(list(info
.read_regs
) + list(info
.uninit_regs
))
531 # main registers (RT, RA ...)
533 for name
in input_names
:
534 regnum
= yield getattr(self
.decoder
, name
)
536 self
.namespace
[regname
] = regnum
537 print('reading reg %d' % regnum
)
538 inputs
.append(self
.gpr(regnum
))
540 # "special" registers
541 for special
in info
.special_regs
:
542 if special
in special_sprs
:
543 inputs
.append(self
.spr
[special
])
545 inputs
.append(self
.namespace
[special
])
548 results
= info
.func(self
, *inputs
)
551 # detect if CA/CA32 already in outputs (sra*, basically)
554 output_names
= create_args(info
.write_regs
)
555 for name
in output_names
:
561 print ("carry already done?", bin(already_done
))
562 carry_en
= yield self
.dec2
.e
.output_carry
564 yield from self
.handle_carry_(inputs
, results
, already_done
)
566 # detect if overflow was in return result
569 for name
, output
in zip(output_names
, results
):
570 if name
== 'overflow':
573 ov_en
= yield self
.dec2
.e
.oe
.oe
574 ov_ok
= yield self
.dec2
.e
.oe
.ok
575 print ("internal overflow", overflow
)
577 yield from self
.handle_overflow(inputs
, results
, overflow
)
579 rc_en
= yield self
.dec2
.e
.rc
.data
581 self
.handle_comparison(results
)
583 # any modified return results?
585 for name
, output
in zip(output_names
, results
):
586 if name
== 'overflow': # ignore, done already (above)
588 if isinstance(output
, int):
589 output
= SelectableInt(output
, 256)
590 if name
in ['CA', 'CA32']:
592 print ("writing %s to XER" % name
, output
)
593 self
.spr
['XER'][XER_bits
[name
]] = output
.value
595 print ("NOT writing %s to XER" % name
, output
)
596 elif name
in info
.special_regs
:
597 print('writing special %s' % name
, output
, special_sprs
)
598 if name
in special_sprs
:
599 self
.spr
[name
] = output
601 self
.namespace
[name
].eq(output
)
603 print ('msr written', hex(self
.msr
.value
))
605 regnum
= yield getattr(self
.decoder
, name
)
606 print('writing reg %d %s' % (regnum
, str(output
)))
608 output
= SelectableInt(output
.value
, 64)
609 self
.gpr
[regnum
] = output
611 # update program counter
612 self
.pc
.update(self
.namespace
)
616 """Decorator factory.
618 this decorator will "inject" variables into the function's namespace,
619 from the *dictionary* in self.namespace. it therefore becomes possible
620 to make it look like a whole stack of variables which would otherwise
621 need "self." inserted in front of them (*and* for those variables to be
622 added to the instance) "appear" in the function.
624 "self.namespace['SI']" for example becomes accessible as just "SI" but
625 *only* inside the function, when decorated.
627 def variable_injector(func
):
629 def decorator(*args
, **kwargs
):
631 func_globals
= func
.__globals
__ # Python 2.6+
632 except AttributeError:
633 func_globals
= func
.func_globals
# Earlier versions.
635 context
= args
[0].namespace
# variables to be injected
636 saved_values
= func_globals
.copy() # Shallow copy of dict.
637 func_globals
.update(context
)
638 result
= func(*args
, **kwargs
)
639 args
[0].namespace
= func_globals
640 #exec (func.__code__, func_globals)
643 # func_globals = saved_values # Undo changes.
649 return variable_injector