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