bec44541b8f9404f2a5828165f7122b24bd656a2
1 # SPDX-License-Identifier: LGPLv3+
2 # Copyright (C) 2020, 2021 Luke Kenneth Casson Leighton <lkcl@lkcl.net>
3 # Copyright (C) 2020 Michael Nolan
4 # Funded by NLnet http://nlnet.nl
5 """core of the python-based POWER9 simulator
7 this is part of a cycle-accurate POWER9 simulator. its primary purpose is
8 not speed, it is for both learning and educational purposes, as well as
9 a method of verifying the HDL.
13 * https://bugs.libre-soc.org/show_bug.cgi?id=424
16 from functools
import wraps
18 from soc
.decoder
.orderedset
import OrderedSet
19 from soc
.decoder
.selectable_int
import (FieldSelectableInt
, SelectableInt
,
21 from soc
.decoder
.power_enums
import (spr_dict
, spr_byname
, XER_bits
,
23 from soc
.decoder
.helpers
import exts
, gtu
, ltu
, undefined
24 from soc
.consts
import PIb
, MSRb
# big-endian (PowerISA versions)
26 from collections
import namedtuple
30 instruction_info
= namedtuple('instruction_info',
31 'func read_regs uninit_regs write_regs ' +
32 'special_regs op_fields form asmregs')
42 def swap_order(x
, nbytes
):
43 x
= x
.to_bytes(nbytes
, byteorder
='little')
44 x
= int.from_bytes(x
, byteorder
='big', signed
=False)
49 # TODO (lkcl): adjust other registers that should be in a particular order
50 # probably CA, CA32, and CR
67 def create_args(reglist
, extra
=None):
68 retval
= list(OrderedSet(reglist
))
69 retval
.sort(key
=lambda reg
: REG_SORT_ORDER
[reg
])
71 return [extra
] + retval
77 def __init__(self
, row_bytes
=8, initial_mem
=None):
79 self
.bytes_per_word
= row_bytes
80 self
.word_log2
= math
.ceil(math
.log2(row_bytes
))
81 print("Sim-Mem", initial_mem
, self
.bytes_per_word
, self
.word_log2
)
85 # different types of memory data structures recognised (for convenience)
86 if isinstance(initial_mem
, list):
87 initial_mem
= (0, initial_mem
)
88 if isinstance(initial_mem
, tuple):
89 startaddr
, mem
= initial_mem
91 for i
, val
in enumerate(mem
):
92 initial_mem
[startaddr
+ row_bytes
*i
] = (val
, row_bytes
)
94 for addr
, (val
, width
) in initial_mem
.items():
95 #val = swap_order(val, width)
96 self
.st(addr
, val
, width
, swap
=False)
98 def _get_shifter_mask(self
, wid
, remainder
):
99 shifter
= ((self
.bytes_per_word
- wid
) - remainder
) * \
101 # XXX https://bugs.libre-soc.org/show_bug.cgi?id=377
103 shifter
= remainder
* 8
104 mask
= (1 << (wid
* 8)) - 1
105 print("width,rem,shift,mask", wid
, remainder
, hex(shifter
), hex(mask
))
108 # TODO: Implement ld/st of lesser width
109 def ld(self
, address
, width
=8, swap
=True, check_in_mem
=False):
110 print("ld from addr 0x{:x} width {:d}".format(address
, width
))
111 remainder
= address
& (self
.bytes_per_word
- 1)
112 address
= address
>> self
.word_log2
113 assert remainder
& (width
- 1) == 0, "Unaligned access unsupported!"
114 if address
in self
.mem
:
115 val
= self
.mem
[address
]
120 print("mem @ 0x{:x} rem {:d} : 0x{:x}".format(address
, remainder
, val
))
122 if width
!= self
.bytes_per_word
:
123 shifter
, mask
= self
._get
_shifter
_mask
(width
, remainder
)
124 print("masking", hex(val
), hex(mask
<< shifter
), shifter
)
125 val
= val
& (mask
<< shifter
)
128 val
= swap_order(val
, width
)
129 print("Read 0x{:x} from addr 0x{:x}".format(val
, address
))
132 def st(self
, addr
, v
, width
=8, swap
=True):
134 remainder
= addr
& (self
.bytes_per_word
- 1)
135 addr
= addr
>> self
.word_log2
136 print("Writing 0x{:x} to ST 0x{:x} "
137 "memaddr 0x{:x}/{:x}".format(v
, staddr
, addr
, remainder
, swap
))
138 assert remainder
& (width
- 1) == 0, "Unaligned access unsupported!"
140 v
= swap_order(v
, width
)
141 if width
!= self
.bytes_per_word
:
146 shifter
, mask
= self
._get
_shifter
_mask
(width
, remainder
)
147 val
&= ~
(mask
<< shifter
)
152 print("mem @ 0x{:x}: 0x{:x}".format(addr
, self
.mem
[addr
]))
154 def __call__(self
, addr
, sz
):
155 val
= self
.ld(addr
.value
, sz
, swap
=False)
156 print("memread", addr
, sz
, val
)
157 return SelectableInt(val
, sz
*8)
159 def memassign(self
, addr
, sz
, val
):
160 print("memassign", addr
, sz
, val
)
161 self
.st(addr
.value
, val
.value
, sz
, swap
=False)
165 def __init__(self
, decoder
, regfile
):
169 self
[i
] = SelectableInt(regfile
[i
], 64)
171 def __call__(self
, ridx
):
174 def set_form(self
, form
):
177 def getz(self
, rnum
):
178 # rnum = rnum.value # only SelectableInt allowed
179 print("GPR getzero", rnum
)
181 return SelectableInt(0, 64)
184 def _get_regnum(self
, attr
):
185 getform
= self
.sd
.sigforms
[self
.form
]
186 rnum
= getattr(getform
, attr
)
189 def ___getitem__(self
, attr
):
190 print("GPR getitem", attr
)
191 rnum
= self
._get
_regnum
(attr
)
192 return self
.regfile
[rnum
]
195 for i
in range(0, len(self
), 8):
198 s
.append("%08x" % self
[i
+j
].value
)
200 print("reg", "%2d" % i
, s
)
204 def __init__(self
, pc_init
=0):
205 self
.CIA
= SelectableInt(pc_init
, 64)
206 self
.NIA
= self
.CIA
+ SelectableInt(4, 64)
208 def update(self
, namespace
):
209 self
.CIA
= namespace
['NIA'].narrow(64)
210 self
.NIA
= self
.CIA
+ SelectableInt(4, 64)
211 namespace
['CIA'] = self
.CIA
212 namespace
['NIA'] = self
.NIA
215 # Simple-V: see https://libre-soc.org/openpower/sv
216 # also soc.sv.svp64 SVP64Rec
218 def __init__(self
, init
=0):
219 self
.spr
= SelectableInt(init
, 32)
220 # fields of SVSTATE, see https://libre-soc.org/openpower/sv/sprs/
221 self
.mmode
= FieldSelectableInt(self
.spr
, [0])
222 self
.mask
= FieldSelectableInt(self
.spr
, tuple(range(1,4)))
223 self
.elwidth
= FieldSelectableInt(self
.spr
, tuple(range(4,6)))
224 self
.ewsrc
= FieldSelectableInt(self
.spr
, tuple(range(6,8)))
225 self
.subvl
= FieldSelectableInt(self
.spr
, tuple(range(8,10)))
226 self
.extra
= FieldSelectableInt(self
.spr
, tuple(range(10,19)))
227 self
.mode
= FieldSelectableInt(self
.spr
, tuple(range(19,24)))
231 def __init__(self
, dec2
, initial_sprs
={}):
234 for key
, v
in initial_sprs
.items():
235 if isinstance(key
, SelectableInt
):
237 key
= special_sprs
.get(key
, key
)
238 if isinstance(key
, int):
241 info
= spr_byname
[key
]
242 if not isinstance(v
, SelectableInt
):
243 v
= SelectableInt(v
, info
.length
)
246 def __getitem__(self
, key
):
247 print("get spr", key
)
248 print("dict", self
.items())
249 # if key in special_sprs get the special spr, otherwise return key
250 if isinstance(key
, SelectableInt
):
252 if isinstance(key
, int):
253 key
= spr_dict
[key
].SPR
254 key
= special_sprs
.get(key
, key
)
255 if key
== 'HSRR0': # HACK!
257 if key
== 'HSRR1': # HACK!
260 res
= dict.__getitem
__(self
, key
)
262 if isinstance(key
, int):
265 info
= spr_byname
[key
]
266 dict.__setitem
__(self
, key
, SelectableInt(0, info
.length
))
267 res
= dict.__getitem
__(self
, key
)
268 print("spr returning", key
, res
)
271 def __setitem__(self
, key
, value
):
272 if isinstance(key
, SelectableInt
):
274 if isinstance(key
, int):
275 key
= spr_dict
[key
].SPR
276 print("spr key", key
)
277 key
= special_sprs
.get(key
, key
)
278 if key
== 'HSRR0': # HACK!
279 self
.__setitem
__('SRR0', value
)
280 if key
== 'HSRR1': # HACK!
281 self
.__setitem
__('SRR1', value
)
282 print("setting spr", key
, value
)
283 dict.__setitem
__(self
, key
, value
)
285 def __call__(self
, ridx
):
290 # decoder2 - an instance of power_decoder2
291 # regfile - a list of initial values for the registers
292 # initial_{etc} - initial values for SPRs, Condition Register, Mem, MSR
293 # respect_pc - tracks the program counter. requires initial_insns
294 def __init__(self
, decoder2
, regfile
, initial_sprs
=None, initial_cr
=0,
295 initial_mem
=None, initial_msr
=0,
297 initial_insns
=None, respect_pc
=False,
302 self
.bigendian
= bigendian
304 self
.respect_pc
= respect_pc
305 if initial_sprs
is None:
307 if initial_mem
is None:
309 if initial_insns
is None:
311 assert self
.respect_pc
== False, "instructions required to honor pc"
313 print("ISACaller insns", respect_pc
, initial_insns
, disassembly
)
314 print("ISACaller initial_msr", initial_msr
)
316 # "fake program counter" mode (for unit testing)
320 if isinstance(initial_mem
, tuple):
321 self
.fake_pc
= initial_mem
[0]
322 disasm_start
= self
.fake_pc
324 disasm_start
= initial_pc
326 # disassembly: we need this for now (not given from the decoder)
327 self
.disassembly
= {}
329 for i
, code
in enumerate(disassembly
):
330 self
.disassembly
[i
*4 + disasm_start
] = code
332 # set up registers, instruction memory, data memory, PC, SPRs, MSR
333 self
.gpr
= GPR(decoder2
, regfile
)
334 self
.mem
= Mem(row_bytes
=8, initial_mem
=initial_mem
)
335 self
.imem
= Mem(row_bytes
=4, initial_mem
=initial_insns
)
337 self
.svstate
= SVSTATE(initial_svstate
)
338 self
.spr
= SPR(decoder2
, initial_sprs
)
339 self
.msr
= SelectableInt(initial_msr
, 64) # underlying reg
342 # FPR (same as GPR except for FP nums)
343 # 4.2.2 p124 FPSCR (definitely "separate" - not in SPR)
344 # note that mffs, mcrfs, mtfsf "manage" this FPSCR
345 # 2.3.1 CR (and sub-fields CR0..CR6 - CR0 SO comes from XER.SO)
346 # note that mfocrf, mfcr, mtcr, mtocrf, mcrxrx "manage" CRs
348 # 2.3.2 LR (actually SPR #8) -- Done
349 # 2.3.3 CTR (actually SPR #9) -- Done
350 # 2.3.4 TAR (actually SPR #815)
351 # 3.2.2 p45 XER (actually SPR #1) -- Done
352 # 3.2.3 p46 p232 VRSAVE (actually SPR #256)
354 # create CR then allow portions of it to be "selectable" (below)
355 #rev_cr = int('{:016b}'.format(initial_cr)[::-1], 2)
356 self
.cr
= SelectableInt(initial_cr
, 64) # underlying reg
357 #self.cr = FieldSelectableInt(self._cr, list(range(32, 64)))
359 # "undefined", just set to variable-bit-width int (use exts "max")
360 #self.undefined = SelectableInt(0, 256) # TODO, not hard-code 256!
363 self
.namespace
.update(self
.spr
)
364 self
.namespace
.update({'GPR': self
.gpr
,
367 'memassign': self
.memassign
,
372 'undefined': undefined
,
373 'mode_is_64bit': True,
377 # update pc to requested start point
378 self
.set_pc(initial_pc
)
380 # field-selectable versions of Condition Register TODO check bitranges?
383 bits
= tuple(range(i
*4+32, (i
+1)*4+32)) # errr... maybe?
384 _cr
= FieldSelectableInt(self
.cr
, bits
)
386 self
.namespace
["CR%d" % i
] = _cr
388 self
.decoder
= decoder2
.dec
391 def TRAP(self
, trap_addr
=0x700, trap_bit
=PIb
.TRAP
):
392 print("TRAP:", hex(trap_addr
), hex(self
.namespace
['MSR'].value
))
393 # store CIA(+4?) in SRR0, set NIA to 0x700
394 # store MSR in SRR1, set MSR to um errr something, have to check spec
395 self
.spr
['SRR0'].value
= self
.pc
.CIA
.value
396 self
.spr
['SRR1'].value
= self
.namespace
['MSR'].value
397 self
.trap_nia
= SelectableInt(trap_addr
, 64)
398 self
.spr
['SRR1'][trap_bit
] = 1 # change *copy* of MSR in SRR1
400 # set exception bits. TODO: this should, based on the address
401 # in figure 66 p1065 V3.0B and the table figure 65 p1063 set these
402 # bits appropriately. however it turns out that *for now* in all
403 # cases (all trap_addrs) the exact same thing is needed.
404 self
.msr
[MSRb
.IR
] = 0
405 self
.msr
[MSRb
.DR
] = 0
406 self
.msr
[MSRb
.FE0
] = 0
407 self
.msr
[MSRb
.FE1
] = 0
408 self
.msr
[MSRb
.EE
] = 0
409 self
.msr
[MSRb
.RI
] = 0
410 self
.msr
[MSRb
.SF
] = 1
411 self
.msr
[MSRb
.TM
] = 0
412 self
.msr
[MSRb
.VEC
] = 0
413 self
.msr
[MSRb
.VSX
] = 0
414 self
.msr
[MSRb
.PR
] = 0
415 self
.msr
[MSRb
.FP
] = 0
416 self
.msr
[MSRb
.PMM
] = 0
417 self
.msr
[MSRb
.TEs
] = 0
418 self
.msr
[MSRb
.TEe
] = 0
419 self
.msr
[MSRb
.UND
] = 0
420 self
.msr
[MSRb
.LE
] = 1
422 def memassign(self
, ea
, sz
, val
):
423 self
.mem
.memassign(ea
, sz
, val
)
425 def prep_namespace(self
, formname
, op_fields
):
426 # TODO: get field names from form in decoder*1* (not decoder2)
427 # decoder2 is hand-created, and decoder1.sigform is auto-generated
429 # then "yield" fields only from op_fields rather than hard-coded
431 fields
= self
.decoder
.sigforms
[formname
]
432 for name
in op_fields
:
434 sig
= getattr(fields
, name
.upper())
436 sig
= getattr(fields
, name
)
438 # these are all opcode fields involved in index-selection of CR,
439 # and need to do "standard" arithmetic. CR[BA+32] for example
440 # would, if using SelectableInt, only be 5-bit.
441 if name
in ['BF', 'BFA', 'BC', 'BA', 'BB', 'BT', 'BI']:
442 self
.namespace
[name
] = val
444 self
.namespace
[name
] = SelectableInt(val
, sig
.width
)
446 self
.namespace
['XER'] = self
.spr
['XER']
447 self
.namespace
['CA'] = self
.spr
['XER'][XER_bits
['CA']].value
448 self
.namespace
['CA32'] = self
.spr
['XER'][XER_bits
['CA32']].value
450 def handle_carry_(self
, inputs
, outputs
, already_done
):
451 inv_a
= yield self
.dec2
.e
.do
.invert_in
453 inputs
[0] = ~inputs
[0]
455 imm_ok
= yield self
.dec2
.e
.do
.imm_data
.ok
457 imm
= yield self
.dec2
.e
.do
.imm_data
.data
458 inputs
.append(SelectableInt(imm
, 64))
459 assert len(outputs
) >= 1
460 print("outputs", repr(outputs
))
461 if isinstance(outputs
, list) or isinstance(outputs
, tuple):
467 print("gt input", x
, output
)
468 gt
= (gtu(x
, output
))
471 cy
= 1 if any(gts
) else 0
473 if not (1 & already_done
):
474 self
.spr
['XER'][XER_bits
['CA']] = cy
476 print("inputs", already_done
, inputs
)
478 # ARGH... different for OP_ADD... *sigh*...
479 op
= yield self
.dec2
.e
.do
.insn_type
480 if op
== MicrOp
.OP_ADD
.value
:
481 res32
= (output
.value
& (1 << 32)) != 0
482 a32
= (inputs
[0].value
& (1 << 32)) != 0
484 b32
= (inputs
[1].value
& (1 << 32)) != 0
487 cy32
= res32 ^ a32 ^ b32
488 print("CA32 ADD", cy32
)
492 print("input", x
, output
)
493 print(" x[32:64]", x
, x
[32:64])
494 print(" o[32:64]", output
, output
[32:64])
495 gt
= (gtu(x
[32:64], output
[32:64])) == SelectableInt(1, 1)
497 cy32
= 1 if any(gts
) else 0
498 print("CA32", cy32
, gts
)
499 if not (2 & already_done
):
500 self
.spr
['XER'][XER_bits
['CA32']] = cy32
502 def handle_overflow(self
, inputs
, outputs
, div_overflow
):
503 if hasattr(self
.dec2
.e
.do
, "invert_in"):
504 inv_a
= yield self
.dec2
.e
.do
.invert_in
506 inputs
[0] = ~inputs
[0]
508 imm_ok
= yield self
.dec2
.e
.do
.imm_data
.ok
510 imm
= yield self
.dec2
.e
.do
.imm_data
.data
511 inputs
.append(SelectableInt(imm
, 64))
512 assert len(outputs
) >= 1
513 print("handle_overflow", inputs
, outputs
, div_overflow
)
514 if len(inputs
) < 2 and div_overflow
is None:
517 # div overflow is different: it's returned by the pseudo-code
518 # because it's more complex than can be done by analysing the output
519 if div_overflow
is not None:
520 ov
, ov32
= div_overflow
, div_overflow
521 # arithmetic overflow can be done by analysing the input and output
522 elif len(inputs
) >= 2:
526 input_sgn
= [exts(x
.value
, x
.bits
) < 0 for x
in inputs
]
527 output_sgn
= exts(output
.value
, output
.bits
) < 0
528 ov
= 1 if input_sgn
[0] == input_sgn
[1] and \
529 output_sgn
!= input_sgn
[0] else 0
532 input32_sgn
= [exts(x
.value
, 32) < 0 for x
in inputs
]
533 output32_sgn
= exts(output
.value
, 32) < 0
534 ov32
= 1 if input32_sgn
[0] == input32_sgn
[1] and \
535 output32_sgn
!= input32_sgn
[0] else 0
537 self
.spr
['XER'][XER_bits
['OV']] = ov
538 self
.spr
['XER'][XER_bits
['OV32']] = ov32
539 so
= self
.spr
['XER'][XER_bits
['SO']]
541 self
.spr
['XER'][XER_bits
['SO']] = so
543 def handle_comparison(self
, outputs
):
545 assert isinstance(out
, SelectableInt
), \
546 "out zero not a SelectableInt %s" % repr(outputs
)
547 print("handle_comparison", out
.bits
, hex(out
.value
))
548 # TODO - XXX *processor* in 32-bit mode
549 # https://bugs.libre-soc.org/show_bug.cgi?id=424
551 # o32 = exts(out.value, 32)
552 # print ("handle_comparison exts 32 bit", hex(o32))
553 out
= exts(out
.value
, out
.bits
)
554 print("handle_comparison exts", hex(out
))
555 zero
= SelectableInt(out
== 0, 1)
556 positive
= SelectableInt(out
> 0, 1)
557 negative
= SelectableInt(out
< 0, 1)
558 SO
= self
.spr
['XER'][XER_bits
['SO']]
559 print("handle_comparison SO", SO
)
560 cr_field
= selectconcat(negative
, positive
, zero
, SO
)
561 self
.crl
[0].eq(cr_field
)
563 def set_pc(self
, pc_val
):
564 self
.namespace
['NIA'] = SelectableInt(pc_val
, 64)
565 self
.pc
.update(self
.namespace
)
568 """set up one instruction
571 pc
= self
.pc
.CIA
.value
575 ins
= self
.imem
.ld(pc
, 4, False, True)
577 raise KeyError("no instruction at 0x%x" % pc
)
578 print("setup: 0x%x 0x%x %s" % (pc
, ins
& 0xffffffff, bin(ins
)))
579 print("CIA NIA", self
.respect_pc
, self
.pc
.CIA
.value
, self
.pc
.NIA
.value
)
581 yield self
.dec2
.dec
.raw_opcode_in
.eq(ins
& 0xffffffff)
582 yield self
.dec2
.dec
.bigendian
.eq(self
.bigendian
)
583 yield self
.dec2
.state
.msr
.eq(self
.msr
.value
)
584 yield self
.dec2
.state
.pc
.eq(pc
)
586 def execute_one(self
):
587 """execute one instruction
589 # get the disassembly code for this instruction
590 code
= self
.disassembly
[self
._pc
]
591 print("sim-execute", hex(self
._pc
), code
)
592 opname
= code
.split(' ')[0]
593 yield from self
.call(opname
)
595 if not self
.respect_pc
:
597 print("execute one, CIA NIA", self
.pc
.CIA
.value
, self
.pc
.NIA
.value
)
599 def get_assembly_name(self
):
600 # TODO, asmregs is from the spec, e.g. add RT,RA,RB
601 # see http://bugs.libre-riscv.org/show_bug.cgi?id=282
602 dec_insn
= yield self
.dec2
.e
.do
.insn
603 asmcode
= yield self
.dec2
.dec
.op
.asmcode
604 print("get assembly name asmcode", asmcode
, hex(dec_insn
))
605 asmop
= insns
.get(asmcode
, None)
606 int_op
= yield self
.dec2
.dec
.op
.internal_op
608 # sigh reconstruct the assembly instruction name
609 if hasattr(self
.dec2
.e
.do
, "oe"):
610 ov_en
= yield self
.dec2
.e
.do
.oe
.oe
611 ov_ok
= yield self
.dec2
.e
.do
.oe
.ok
615 if hasattr(self
.dec2
.e
.do
, "rc"):
616 rc_en
= yield self
.dec2
.e
.do
.rc
.rc
617 rc_ok
= yield self
.dec2
.e
.do
.rc
.ok
621 # grrrr have to special-case MUL op (see DecodeOE)
622 print("ov %d en %d rc %d en %d op %d" %
623 (ov_ok
, ov_en
, rc_ok
, rc_en
, int_op
))
624 if int_op
in [MicrOp
.OP_MUL_H64
.value
, MicrOp
.OP_MUL_H32
.value
]:
629 if not asmop
.endswith("."): # don't add "." to "andis."
632 if hasattr(self
.dec2
.e
.do
, "lk"):
633 lk
= yield self
.dec2
.e
.do
.lk
636 print("int_op", int_op
)
637 if int_op
in [MicrOp
.OP_B
.value
, MicrOp
.OP_BC
.value
]:
638 AA
= yield self
.dec2
.dec
.fields
.FormI
.AA
[0:-1]
642 spr_msb
= yield from self
.get_spr_msb()
643 if int_op
== MicrOp
.OP_MFCR
.value
:
648 # XXX TODO: for whatever weird reason this doesn't work
649 # https://bugs.libre-soc.org/show_bug.cgi?id=390
650 if int_op
== MicrOp
.OP_MTCRF
.value
:
657 def get_spr_msb(self
):
658 dec_insn
= yield self
.dec2
.e
.do
.insn
659 return dec_insn
& (1 << 20) != 0 # sigh - XFF.spr[-1]?
661 def call(self
, name
):
662 name
= name
.strip() # remove spaces if not already done so
664 print("halted - not executing", name
)
667 # TODO, asmregs is from the spec, e.g. add RT,RA,RB
668 # see http://bugs.libre-riscv.org/show_bug.cgi?id=282
669 asmop
= yield from self
.get_assembly_name()
670 print("call", name
, asmop
)
673 int_op
= yield self
.dec2
.dec
.op
.internal_op
674 spr_msb
= yield from self
.get_spr_msb()
676 instr_is_privileged
= False
677 if int_op
in [MicrOp
.OP_ATTN
.value
,
678 MicrOp
.OP_MFMSR
.value
,
679 MicrOp
.OP_MTMSR
.value
,
680 MicrOp
.OP_MTMSRD
.value
,
682 MicrOp
.OP_RFID
.value
]:
683 instr_is_privileged
= True
684 if int_op
in [MicrOp
.OP_MFSPR
.value
,
685 MicrOp
.OP_MTSPR
.value
] and spr_msb
:
686 instr_is_privileged
= True
688 print("is priv", instr_is_privileged
, hex(self
.msr
.value
),
690 # check MSR priv bit and whether op is privileged: if so, throw trap
691 if instr_is_privileged
and self
.msr
[MSRb
.PR
] == 1:
692 self
.TRAP(0x700, PIb
.PRIV
)
693 self
.namespace
['NIA'] = self
.trap_nia
694 self
.pc
.update(self
.namespace
)
697 # check halted condition
702 # check illegal instruction
704 if name
not in ['mtcrf', 'mtocrf']:
705 illegal
= name
!= asmop
708 print("illegal", name
, asmop
)
709 self
.TRAP(0x700, PIb
.ILLEG
)
710 self
.namespace
['NIA'] = self
.trap_nia
711 self
.pc
.update(self
.namespace
)
712 print("name %s != %s - calling ILLEGAL trap, PC: %x" %
713 (name
, asmop
, self
.pc
.CIA
.value
))
716 info
= self
.instrs
[name
]
717 yield from self
.prep_namespace(info
.form
, info
.op_fields
)
719 # preserve order of register names
720 input_names
= create_args(list(info
.read_regs
) +
721 list(info
.uninit_regs
))
724 # main registers (RT, RA ...)
726 for name
in input_names
:
727 regnum
= yield getattr(self
.decoder
, name
)
729 self
.namespace
[regname
] = regnum
730 print('reading reg %d' % regnum
)
731 inputs
.append(self
.gpr(regnum
))
733 # "special" registers
734 for special
in info
.special_regs
:
735 if special
in special_sprs
:
736 inputs
.append(self
.spr
[special
])
738 inputs
.append(self
.namespace
[special
])
740 # clear trap (trap) NIA
744 results
= info
.func(self
, *inputs
)
747 # "inject" decorator takes namespace from function locals: we need to
748 # overwrite NIA being overwritten (sigh)
749 if self
.trap_nia
is not None:
750 self
.namespace
['NIA'] = self
.trap_nia
752 print("after func", self
.namespace
['CIA'], self
.namespace
['NIA'])
754 # detect if CA/CA32 already in outputs (sra*, basically)
757 output_names
= create_args(info
.write_regs
)
758 for name
in output_names
:
764 print("carry already done?", bin(already_done
))
765 if hasattr(self
.dec2
.e
.do
, "output_carry"):
766 carry_en
= yield self
.dec2
.e
.do
.output_carry
770 yield from self
.handle_carry_(inputs
, results
, already_done
)
772 # detect if overflow was in return result
775 for name
, output
in zip(output_names
, results
):
776 if name
== 'overflow':
779 if hasattr(self
.dec2
.e
.do
, "oe"):
780 ov_en
= yield self
.dec2
.e
.do
.oe
.oe
781 ov_ok
= yield self
.dec2
.e
.do
.oe
.ok
785 print("internal overflow", overflow
, ov_en
, ov_ok
)
787 yield from self
.handle_overflow(inputs
, results
, overflow
)
789 if hasattr(self
.dec2
.e
.do
, "rc"):
790 rc_en
= yield self
.dec2
.e
.do
.rc
.rc
794 self
.handle_comparison(results
)
796 # any modified return results?
798 for name
, output
in zip(output_names
, results
):
799 if name
== 'overflow': # ignore, done already (above)
801 if isinstance(output
, int):
802 output
= SelectableInt(output
, 256)
803 if name
in ['CA', 'CA32']:
805 print("writing %s to XER" % name
, output
)
806 self
.spr
['XER'][XER_bits
[name
]] = output
.value
808 print("NOT writing %s to XER" % name
, output
)
809 elif name
in info
.special_regs
:
810 print('writing special %s' % name
, output
, special_sprs
)
811 if name
in special_sprs
:
812 self
.spr
[name
] = output
814 self
.namespace
[name
].eq(output
)
816 print('msr written', hex(self
.msr
.value
))
818 regnum
= yield getattr(self
.decoder
, name
)
819 print('writing reg %d %s' % (regnum
, str(output
)))
821 output
= SelectableInt(output
.value
, 64)
822 self
.gpr
[regnum
] = output
824 print("end of call", self
.namespace
['CIA'], self
.namespace
['NIA'])
825 # UPDATE program counter
826 self
.pc
.update(self
.namespace
)
830 """Decorator factory.
832 this decorator will "inject" variables into the function's namespace,
833 from the *dictionary* in self.namespace. it therefore becomes possible
834 to make it look like a whole stack of variables which would otherwise
835 need "self." inserted in front of them (*and* for those variables to be
836 added to the instance) "appear" in the function.
838 "self.namespace['SI']" for example becomes accessible as just "SI" but
839 *only* inside the function, when decorated.
841 def variable_injector(func
):
843 def decorator(*args
, **kwargs
):
845 func_globals
= func
.__globals
__ # Python 2.6+
846 except AttributeError:
847 func_globals
= func
.func_globals
# Earlier versions.
849 context
= args
[0].namespace
# variables to be injected
850 saved_values
= func_globals
.copy() # Shallow copy of dict.
851 func_globals
.update(context
)
852 result
= func(*args
, **kwargs
)
853 print("globals after", func_globals
['CIA'], func_globals
['NIA'])
854 print("args[0]", args
[0].namespace
['CIA'],
855 args
[0].namespace
['NIA'])
856 args
[0].namespace
= func_globals
857 #exec (func.__code__, func_globals)
860 # func_globals = saved_values # Undo changes.
866 return variable_injector