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