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