9d3008ba1e5a48c12b8e6dc00e791085e7aa0b23
[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 PIb, MSRb # big-endian (PowerISA versions)
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=PIb.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'][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[MSRb.IR] = 0
357 self.msr[MSRb.DR] = 0
358 self.msr[MSRb.FE0] = 0
359 self.msr[MSRb.FE1] = 0
360 self.msr[MSRb.EE] = 0
361 self.msr[MSRb.RI] = 0
362 self.msr[MSRb.SF] = 1
363 self.msr[MSRb.TM] = 0
364 self.msr[MSRb.VEC] = 0
365 self.msr[MSRb.VSX] = 0
366 self.msr[MSRb.PR] = 0
367 self.msr[MSRb.FP] = 0
368 self.msr[MSRb.PMM] = 0
369 self.msr[MSRb.TEs] = 0
370 self.msr[MSRb.TEe] = 0
371 self.msr[MSRb.UND] = 0
372 self.msr[MSRb.LE] = 1
373
374 def memassign(self, ea, sz, val):
375 self.mem.memassign(ea, sz, val)
376
377 def prep_namespace(self, formname, op_fields):
378 # TODO: get field names from form in decoder*1* (not decoder2)
379 # decoder2 is hand-created, and decoder1.sigform is auto-generated
380 # from spec
381 # then "yield" fields only from op_fields rather than hard-coded
382 # list, here.
383 fields = self.decoder.sigforms[formname]
384 for name in op_fields:
385 if name == 'spr':
386 sig = getattr(fields, name.upper())
387 else:
388 sig = getattr(fields, name)
389 val = yield sig
390 if name in ['BF', 'BFA']:
391 self.namespace[name] = val
392 else:
393 self.namespace[name] = SelectableInt(val, sig.width)
394
395 self.namespace['XER'] = self.spr['XER']
396 self.namespace['CA'] = self.spr['XER'][XER_bits['CA']].value
397 self.namespace['CA32'] = self.spr['XER'][XER_bits['CA32']].value
398
399 def handle_carry_(self, inputs, outputs, already_done):
400 inv_a = yield self.dec2.e.do.invert_a
401 if inv_a:
402 inputs[0] = ~inputs[0]
403
404 imm_ok = yield self.dec2.e.do.imm_data.ok
405 if imm_ok:
406 imm = yield self.dec2.e.do.imm_data.data
407 inputs.append(SelectableInt(imm, 64))
408 assert len(outputs) >= 1
409 print ("outputs", repr(outputs))
410 if isinstance(outputs, list) or isinstance(outputs, tuple):
411 output = outputs[0]
412 else:
413 output = outputs
414 gts = []
415 for x in inputs:
416 print ("gt input", x, output)
417 gt = (x > output)
418 gts.append(gt)
419 print(gts)
420 cy = 1 if any(gts) else 0
421 if not (1 & already_done):
422 self.spr['XER'][XER_bits['CA']] = cy
423
424 print ("inputs", inputs)
425 # 32 bit carry
426 gts = []
427 for x in inputs:
428 print ("input", x, output)
429 gt = (x[32:64] > output[32:64]) == SelectableInt(1, 1)
430 gts.append(gt)
431 cy32 = 1 if any(gts) else 0
432 if not (2 & already_done):
433 self.spr['XER'][XER_bits['CA32']] = cy32
434
435 def handle_overflow(self, inputs, outputs, div_overflow):
436 inv_a = yield self.dec2.e.do.invert_a
437 if inv_a:
438 inputs[0] = ~inputs[0]
439
440 imm_ok = yield self.dec2.e.do.imm_data.ok
441 if imm_ok:
442 imm = yield self.dec2.e.do.imm_data.data
443 inputs.append(SelectableInt(imm, 64))
444 assert len(outputs) >= 1
445 print ("handle_overflow", inputs, outputs, div_overflow)
446 if len(inputs) < 2 and div_overflow is None:
447 return
448
449 # div overflow is different: it's returned by the pseudo-code
450 # because it's more complex than can be done by analysing the output
451 if div_overflow is not None:
452 ov, ov32 = div_overflow, div_overflow
453 # arithmetic overflow can be done by analysing the input and output
454 elif len(inputs) >= 2:
455 output = outputs[0]
456
457 # OV (64-bit)
458 input_sgn = [exts(x.value, x.bits) < 0 for x in inputs]
459 output_sgn = exts(output.value, output.bits) < 0
460 ov = 1 if input_sgn[0] == input_sgn[1] and \
461 output_sgn != input_sgn[0] else 0
462
463 # OV (32-bit)
464 input32_sgn = [exts(x.value, 32) < 0 for x in inputs]
465 output32_sgn = exts(output.value, 32) < 0
466 ov32 = 1 if input32_sgn[0] == input32_sgn[1] and \
467 output32_sgn != input32_sgn[0] else 0
468
469 self.spr['XER'][XER_bits['OV']] = ov
470 self.spr['XER'][XER_bits['OV32']] = ov32
471 so = self.spr['XER'][XER_bits['SO']]
472 so = so | ov
473 self.spr['XER'][XER_bits['SO']] = so
474
475 def handle_comparison(self, outputs):
476 out = outputs[0]
477 print ("handle_comparison", out.bits, hex(out.value))
478 # TODO - XXX *processor* in 32-bit mode
479 # https://bugs.libre-soc.org/show_bug.cgi?id=424
480 #if is_32bit:
481 # o32 = exts(out.value, 32)
482 # print ("handle_comparison exts 32 bit", hex(o32))
483 out = exts(out.value, out.bits)
484 print ("handle_comparison exts", hex(out))
485 zero = SelectableInt(out == 0, 1)
486 positive = SelectableInt(out > 0, 1)
487 negative = SelectableInt(out < 0, 1)
488 SO = self.spr['XER'][XER_bits['SO']]
489 print ("handle_comparison SO", SO)
490 cr_field = selectconcat(negative, positive, zero, SO)
491 self.crl[0].eq(cr_field)
492
493 def set_pc(self, pc_val):
494 self.namespace['NIA'] = SelectableInt(pc_val, 64)
495 self.pc.update(self.namespace)
496
497 def setup_one(self):
498 """set up one instruction
499 """
500 if self.respect_pc:
501 pc = self.pc.CIA.value
502 else:
503 pc = self.fake_pc
504 self._pc = pc
505 ins = self.imem.ld(pc, 4, False, True)
506 if ins is None:
507 raise KeyError("no instruction at 0x%x" % pc)
508 print("setup: 0x%x 0x%x %s" % (pc, ins & 0xffffffff, bin(ins)))
509 print ("CIA NIA", self.respect_pc, self.pc.CIA.value, self.pc.NIA.value)
510
511 yield self.dec2.dec.raw_opcode_in.eq(ins & 0xffffffff)
512 yield self.dec2.dec.bigendian.eq(self.bigendian)
513 yield self.dec2.msr.eq(self.msr.value)
514 yield self.dec2.cia.eq(pc)
515
516 def execute_one(self):
517 """execute one instruction
518 """
519 # get the disassembly code for this instruction
520 code = self.disassembly[self._pc]
521 print("sim-execute", hex(self._pc), code)
522 opname = code.split(' ')[0]
523 yield from self.call(opname)
524
525 if not self.respect_pc:
526 self.fake_pc += 4
527 print ("execute one, CIA NIA", self.pc.CIA.value, self.pc.NIA.value)
528
529 def get_assembly_name(self):
530 # TODO, asmregs is from the spec, e.g. add RT,RA,RB
531 # see http://bugs.libre-riscv.org/show_bug.cgi?id=282
532 asmcode = yield self.dec2.dec.op.asmcode
533 print ("get assembly name asmcode", asmcode)
534 asmop = insns.get(asmcode, None)
535 int_op = yield self.dec2.dec.op.internal_op
536
537 # sigh reconstruct the assembly instruction name
538 ov_en = yield self.dec2.e.do.oe.oe
539 ov_ok = yield self.dec2.e.do.oe.ok
540 rc_en = yield self.dec2.e.do.rc.data
541 rc_ok = yield self.dec2.e.do.rc.ok
542 # grrrr have to special-case MUL op (see DecodeOE)
543 print ("ov en rc en", ov_ok, ov_en, rc_ok, rc_en, int_op)
544 if int_op in [MicrOp.OP_MUL_H64.value, MicrOp.OP_MUL_H32.value]:
545 print ("mul op")
546 if rc_en & rc_ok:
547 asmop += "."
548 else:
549 if ov_en & ov_ok:
550 asmop += "."
551 lk = yield self.dec2.e.do.lk
552 if lk:
553 asmop += "l"
554 print ("int_op", int_op)
555 if int_op in [MicrOp.OP_B.value, MicrOp.OP_BC.value]:
556 AA = yield self.dec2.dec.fields.FormI.AA[0:-1]
557 print ("AA", AA)
558 if AA:
559 asmop += "a"
560 spr_msb = yield from self.get_spr_msb()
561 if int_op == MicrOp.OP_MFCR.value:
562 if spr_msb:
563 asmop = 'mfocrf'
564 else:
565 asmop = 'mfcr'
566 # XXX TODO: for whatever weird reason this doesn't work
567 # https://bugs.libre-soc.org/show_bug.cgi?id=390
568 if int_op == MicrOp.OP_MTCRF.value:
569 if spr_msb:
570 asmop = 'mtocrf'
571 else:
572 asmop = 'mtcrf'
573 return asmop
574
575 def get_spr_msb(self):
576 dec_insn = yield self.dec2.e.do.insn
577 return dec_insn & (1<<20) != 0 # sigh - XFF.spr[-1]?
578
579 def call(self, name):
580 name = name.strip() # remove spaces if not already done so
581 if self.halted:
582 print ("halted - not executing", name)
583 return
584
585 # TODO, asmregs is from the spec, e.g. add RT,RA,RB
586 # see http://bugs.libre-riscv.org/show_bug.cgi?id=282
587 asmop = yield from self.get_assembly_name()
588 print ("call", name, asmop)
589
590 # check privileged
591 int_op = yield self.dec2.dec.op.internal_op
592 spr_msb = yield from self.get_spr_msb()
593
594 instr_is_privileged = False
595 if int_op in [MicrOp.OP_ATTN.value,
596 MicrOp.OP_MFMSR.value,
597 MicrOp.OP_MTMSR.value,
598 MicrOp.OP_MTMSRD.value,
599 # TODO: OP_TLBIE
600 MicrOp.OP_RFID.value]:
601 instr_is_privileged = True
602 if int_op in [MicrOp.OP_MFSPR.value,
603 MicrOp.OP_MTSPR.value] and spr_msb:
604 instr_is_privileged = True
605
606 print ("is priv", instr_is_privileged, hex(self.msr.value),
607 self.msr[MSRb.PR])
608 # check MSR priv bit and whether op is privileged: if so, throw trap
609 if instr_is_privileged and self.msr[MSRb.PR] == 1:
610 self.TRAP(0x700, PIb.PRIV)
611 self.namespace['NIA'] = self.trap_nia
612 self.pc.update(self.namespace)
613 return
614
615 # check halted condition
616 if name == 'attn':
617 self.halted = True
618 return
619
620 # check illegal instruction
621 illegal = False
622 if name not in ['mtcrf', 'mtocrf']:
623 illegal = name != asmop
624
625 if illegal:
626 self.TRAP(0x700, PIb.ILLEG)
627 self.namespace['NIA'] = self.trap_nia
628 self.pc.update(self.namespace)
629 print ("name %s != %s - calling ILLEGAL trap, PC: %x" % \
630 (name, asmop, self.pc.CIA.value))
631 return
632
633 info = self.instrs[name]
634 yield from self.prep_namespace(info.form, info.op_fields)
635
636 # preserve order of register names
637 input_names = create_args(list(info.read_regs) +
638 list(info.uninit_regs))
639 print(input_names)
640
641 # main registers (RT, RA ...)
642 inputs = []
643 for name in input_names:
644 regnum = yield getattr(self.decoder, name)
645 regname = "_" + name
646 self.namespace[regname] = regnum
647 print('reading reg %d' % regnum)
648 inputs.append(self.gpr(regnum))
649
650 # "special" registers
651 for special in info.special_regs:
652 if special in special_sprs:
653 inputs.append(self.spr[special])
654 else:
655 inputs.append(self.namespace[special])
656
657 # clear trap (trap) NIA
658 self.trap_nia = None
659
660 print(inputs)
661 results = info.func(self, *inputs)
662 print(results)
663
664 # "inject" decorator takes namespace from function locals: we need to
665 # overwrite NIA being overwritten (sigh)
666 if self.trap_nia is not None:
667 self.namespace['NIA'] = self.trap_nia
668
669 print ("after func", self.namespace['CIA'], self.namespace['NIA'])
670
671 # detect if CA/CA32 already in outputs (sra*, basically)
672 already_done = 0
673 if info.write_regs:
674 output_names = create_args(info.write_regs)
675 for name in output_names:
676 if name == 'CA':
677 already_done |= 1
678 if name == 'CA32':
679 already_done |= 2
680
681 print ("carry already done?", bin(already_done))
682 carry_en = yield self.dec2.e.do.output_carry
683 if carry_en:
684 yield from self.handle_carry_(inputs, results, already_done)
685
686 # detect if overflow was in return result
687 overflow = None
688 if info.write_regs:
689 for name, output in zip(output_names, results):
690 if name == 'overflow':
691 overflow = output
692
693 ov_en = yield self.dec2.e.do.oe.oe
694 ov_ok = yield self.dec2.e.do.oe.ok
695 print ("internal overflow", overflow, ov_en, ov_ok)
696 if ov_en & ov_ok:
697 yield from self.handle_overflow(inputs, results, overflow)
698
699 rc_en = yield self.dec2.e.do.rc.data
700 if rc_en:
701 self.handle_comparison(results)
702
703 # any modified return results?
704 if info.write_regs:
705 for name, output in zip(output_names, results):
706 if name == 'overflow': # ignore, done already (above)
707 continue
708 if isinstance(output, int):
709 output = SelectableInt(output, 256)
710 if name in ['CA', 'CA32']:
711 if carry_en:
712 print ("writing %s to XER" % name, output)
713 self.spr['XER'][XER_bits[name]] = output.value
714 else:
715 print ("NOT writing %s to XER" % name, output)
716 elif name in info.special_regs:
717 print('writing special %s' % name, output, special_sprs)
718 if name in special_sprs:
719 self.spr[name] = output
720 else:
721 self.namespace[name].eq(output)
722 if name == 'MSR':
723 print ('msr written', hex(self.msr.value))
724 else:
725 regnum = yield getattr(self.decoder, name)
726 print('writing reg %d %s' % (regnum, str(output)))
727 if output.bits > 64:
728 output = SelectableInt(output.value, 64)
729 self.gpr[regnum] = output
730
731 print ("end of call", self.namespace['CIA'], self.namespace['NIA'])
732 # UPDATE program counter
733 self.pc.update(self.namespace)
734
735
736 def inject():
737 """Decorator factory.
738
739 this decorator will "inject" variables into the function's namespace,
740 from the *dictionary* in self.namespace. it therefore becomes possible
741 to make it look like a whole stack of variables which would otherwise
742 need "self." inserted in front of them (*and* for those variables to be
743 added to the instance) "appear" in the function.
744
745 "self.namespace['SI']" for example becomes accessible as just "SI" but
746 *only* inside the function, when decorated.
747 """
748 def variable_injector(func):
749 @wraps(func)
750 def decorator(*args, **kwargs):
751 try:
752 func_globals = func.__globals__ # Python 2.6+
753 except AttributeError:
754 func_globals = func.func_globals # Earlier versions.
755
756 context = args[0].namespace # variables to be injected
757 saved_values = func_globals.copy() # Shallow copy of dict.
758 func_globals.update(context)
759 result = func(*args, **kwargs)
760 print ("globals after", func_globals['CIA'], func_globals['NIA'])
761 print ("args[0]", args[0].namespace['CIA'],
762 args[0].namespace['NIA'])
763 args[0].namespace = func_globals
764 #exec (func.__code__, func_globals)
765
766 #finally:
767 # func_globals = saved_values # Undo changes.
768
769 return result
770
771 return decorator
772
773 return variable_injector
774