add in SVSTATE to ISACaller, not used, just passed in
[soc.git] / src / soc / decoder / isa / caller.py
1 # SPDX-License-Identifier: LGPLv3+
2 # Copyright (C) 2020, 2021 Luke Kenneth Casson Leighton <lkcl@lkcl.net>
3 # Copyright (C) 2020 Michael Nolan
4 # Funded by NLnet http://nlnet.nl
5 """core of the python-based POWER9 simulator
6
7 this is part of a cycle-accurate POWER9 simulator. its primary purpose is
8 not speed, it is for both learning and educational purposes, as well as
9 a method of verifying the HDL.
10
11 related bugs:
12
13 * https://bugs.libre-soc.org/show_bug.cgi?id=424
14 """
15
16 from nmigen.back.pysim import Settle
17 from functools import wraps
18 from copy import copy
19 from soc.decoder.orderedset import OrderedSet
20 from soc.decoder.selectable_int import (FieldSelectableInt, SelectableInt,
21 selectconcat)
22 from soc.decoder.power_enums import (spr_dict, spr_byname, XER_bits,
23 insns, MicrOp, In1Sel, In2Sel, In3Sel,
24 OutSel)
25 from soc.decoder.helpers import exts, gtu, ltu, undefined
26 from soc.consts import PIb, MSRb # big-endian (PowerISA versions)
27 from soc.decoder.power_svp64 import SVP64RM, decode_extra
28
29 from collections import namedtuple
30 import math
31 import sys
32
33 instruction_info = namedtuple('instruction_info',
34 'func read_regs uninit_regs write_regs ' +
35 'special_regs op_fields form asmregs')
36
37 special_sprs = {
38 'LR': 8,
39 'CTR': 9,
40 'TAR': 815,
41 'XER': 1,
42 'VRSAVE': 256}
43
44
45 def swap_order(x, nbytes):
46 x = x.to_bytes(nbytes, byteorder='little')
47 x = int.from_bytes(x, byteorder='big', signed=False)
48 return x
49
50
51 REG_SORT_ORDER = {
52 # TODO (lkcl): adjust other registers that should be in a particular order
53 # probably CA, CA32, and CR
54 "RT": 0,
55 "RA": 0,
56 "RB": 0,
57 "RS": 0,
58 "CR": 0,
59 "LR": 0,
60 "CTR": 0,
61 "TAR": 0,
62 "CA": 0,
63 "CA32": 0,
64 "MSR": 0,
65
66 "overflow": 1,
67 }
68
69
70 def create_args(reglist, extra=None):
71 retval = list(OrderedSet(reglist))
72 retval.sort(key=lambda reg: REG_SORT_ORDER[reg])
73 if extra is not None:
74 return [extra] + retval
75 return retval
76
77
78 class Mem:
79
80 def __init__(self, row_bytes=8, initial_mem=None):
81 self.mem = {}
82 self.bytes_per_word = row_bytes
83 self.word_log2 = math.ceil(math.log2(row_bytes))
84 print("Sim-Mem", initial_mem, self.bytes_per_word, self.word_log2)
85 if not initial_mem:
86 return
87
88 # different types of memory data structures recognised (for convenience)
89 if isinstance(initial_mem, list):
90 initial_mem = (0, initial_mem)
91 if isinstance(initial_mem, tuple):
92 startaddr, mem = initial_mem
93 initial_mem = {}
94 for i, val in enumerate(mem):
95 initial_mem[startaddr + row_bytes*i] = (val, row_bytes)
96
97 for addr, (val, width) in initial_mem.items():
98 #val = swap_order(val, width)
99 self.st(addr, val, width, swap=False)
100
101 def _get_shifter_mask(self, wid, remainder):
102 shifter = ((self.bytes_per_word - wid) - remainder) * \
103 8 # bits per byte
104 # XXX https://bugs.libre-soc.org/show_bug.cgi?id=377
105 # BE/LE mode?
106 shifter = remainder * 8
107 mask = (1 << (wid * 8)) - 1
108 print("width,rem,shift,mask", wid, remainder, hex(shifter), hex(mask))
109 return shifter, mask
110
111 # TODO: Implement ld/st of lesser width
112 def ld(self, address, width=8, swap=True, check_in_mem=False):
113 print("ld from addr 0x{:x} width {:d}".format(address, width))
114 remainder = address & (self.bytes_per_word - 1)
115 address = address >> self.word_log2
116 assert remainder & (width - 1) == 0, "Unaligned access unsupported!"
117 if address in self.mem:
118 val = self.mem[address]
119 elif check_in_mem:
120 return None
121 else:
122 val = 0
123 print("mem @ 0x{:x} rem {:d} : 0x{:x}".format(address, remainder, val))
124
125 if width != self.bytes_per_word:
126 shifter, mask = self._get_shifter_mask(width, remainder)
127 print("masking", hex(val), hex(mask << shifter), shifter)
128 val = val & (mask << shifter)
129 val >>= shifter
130 if swap:
131 val = swap_order(val, width)
132 print("Read 0x{:x} from addr 0x{:x}".format(val, address))
133 return val
134
135 def st(self, addr, v, width=8, swap=True):
136 staddr = addr
137 remainder = addr & (self.bytes_per_word - 1)
138 addr = addr >> self.word_log2
139 print("Writing 0x{:x} to ST 0x{:x} "
140 "memaddr 0x{:x}/{:x}".format(v, staddr, addr, remainder, swap))
141 assert remainder & (width - 1) == 0, "Unaligned access unsupported!"
142 if swap:
143 v = swap_order(v, width)
144 if width != self.bytes_per_word:
145 if addr in self.mem:
146 val = self.mem[addr]
147 else:
148 val = 0
149 shifter, mask = self._get_shifter_mask(width, remainder)
150 val &= ~(mask << shifter)
151 val |= v << shifter
152 self.mem[addr] = val
153 else:
154 self.mem[addr] = v
155 print("mem @ 0x{:x}: 0x{:x}".format(addr, self.mem[addr]))
156
157 def __call__(self, addr, sz):
158 val = self.ld(addr.value, sz, swap=False)
159 print("memread", addr, sz, val)
160 return SelectableInt(val, sz*8)
161
162 def memassign(self, addr, sz, val):
163 print("memassign", addr, sz, val)
164 self.st(addr.value, val.value, sz, swap=False)
165
166
167 class GPR(dict):
168 def __init__(self, decoder, isacaller, svstate, regfile):
169 dict.__init__(self)
170 self.sd = decoder
171 self.isacaller = isacaller
172 self.svstate = svstate
173 for i in range(32):
174 self[i] = SelectableInt(regfile[i], 64)
175
176 def __call__(self, ridx):
177 return self[ridx]
178
179 def set_form(self, form):
180 self.form = form
181
182 def getz(self, rnum):
183 # rnum = rnum.value # only SelectableInt allowed
184 print("GPR getzero", rnum)
185 if rnum == 0:
186 return SelectableInt(0, 64)
187 return self[rnum]
188
189 def _get_regnum(self, attr):
190 getform = self.sd.sigforms[self.form]
191 rnum = getattr(getform, attr)
192 return rnum
193
194 def ___getitem__(self, attr):
195 """ XXX currently not used
196 """
197 rnum = self._get_regnum(attr)
198 offs = self.svstate.srcstep
199 print("GPR getitem", attr, rnum, "srcoffs", offs)
200 return self.regfile[rnum]
201
202 def dump(self):
203 for i in range(0, len(self), 8):
204 s = []
205 for j in range(8):
206 s.append("%08x" % self[i+j].value)
207 s = ' '.join(s)
208 print("reg", "%2d" % i, s)
209
210
211 class PC:
212 def __init__(self, pc_init=0):
213 self.CIA = SelectableInt(pc_init, 64)
214 self.NIA = self.CIA + SelectableInt(4, 64)
215
216 def update(self, namespace):
217 self.CIA = namespace['NIA'].narrow(64)
218 self.NIA = self.CIA + SelectableInt(4, 64)
219 namespace['CIA'] = self.CIA
220 namespace['NIA'] = self.NIA
221
222
223 # Simple-V: see https://libre-soc.org/openpower/sv
224 class SVP64State:
225 def __init__(self, init=0):
226 self.spr = SelectableInt(init, 32)
227 # fields of SVSTATE, see https://libre-soc.org/openpower/sv/sprs/
228 self.maxvl = FieldSelectableInt(self.spr, tuple(range(0,7)))
229 self.vl = FieldSelectableInt(self.spr, tuple(range(7,14)))
230 self.srcstep = FieldSelectableInt(self.spr, tuple(range(14,21)))
231 self.dststep = FieldSelectableInt(self.spr, tuple(range(21,28)))
232 self.subvl = FieldSelectableInt(self.spr, tuple(range(28,30)))
233 self.svstep = FieldSelectableInt(self.spr, tuple(range(30,32)))
234
235
236 # SVP64 ReMap field
237 class SVP64RMFields:
238 def __init__(self, init=0):
239 self.spr = SelectableInt(init, 24)
240 # SVP64 RM fields: see https://libre-soc.org/openpower/sv/svp64/
241 self.mmode = FieldSelectableInt(self.spr, [0])
242 self.mask = FieldSelectableInt(self.spr, tuple(range(1,4)))
243 self.elwidth = FieldSelectableInt(self.spr, tuple(range(4,6)))
244 self.ewsrc = FieldSelectableInt(self.spr, tuple(range(6,8)))
245 self.subvl = FieldSelectableInt(self.spr, tuple(range(8,10)))
246 self.extra = FieldSelectableInt(self.spr, tuple(range(10,19)))
247 self.mode = FieldSelectableInt(self.spr, tuple(range(19,24)))
248
249
250 # SVP64 Prefix fields: see https://libre-soc.org/openpower/sv/svp64/
251 class SVP64PrefixFields:
252 def __init__(self):
253 self.insn = SelectableInt(0, 32)
254 # 6 bit major opcode EXT001, 2 bits "identifying" (7, 9), 24 SV ReMap
255 self.major = FieldSelectableInt(self.insn, tuple(range(0,6)))
256 self.pid = FieldSelectableInt(self.insn, (7, 9)) # must be 0b11
257 rmfields = [6, 8] + list(range(10,32)) # SVP64 24-bit RM (ReMap)
258 self.rm = FieldSelectableInt(self.insn, rmfields)
259
260
261 class SPR(dict):
262 def __init__(self, dec2, initial_sprs={}):
263 self.sd = dec2
264 dict.__init__(self)
265 for key, v in initial_sprs.items():
266 if isinstance(key, SelectableInt):
267 key = key.value
268 key = special_sprs.get(key, key)
269 if isinstance(key, int):
270 info = spr_dict[key]
271 else:
272 info = spr_byname[key]
273 if not isinstance(v, SelectableInt):
274 v = SelectableInt(v, info.length)
275 self[key] = v
276
277 def __getitem__(self, key):
278 print("get spr", key)
279 print("dict", self.items())
280 # if key in special_sprs get the special spr, otherwise return key
281 if isinstance(key, SelectableInt):
282 key = key.value
283 if isinstance(key, int):
284 key = spr_dict[key].SPR
285 key = special_sprs.get(key, key)
286 if key == 'HSRR0': # HACK!
287 key = 'SRR0'
288 if key == 'HSRR1': # HACK!
289 key = 'SRR1'
290 if key in self:
291 res = dict.__getitem__(self, key)
292 else:
293 if isinstance(key, int):
294 info = spr_dict[key]
295 else:
296 info = spr_byname[key]
297 dict.__setitem__(self, key, SelectableInt(0, info.length))
298 res = dict.__getitem__(self, key)
299 print("spr returning", key, res)
300 return res
301
302 def __setitem__(self, key, value):
303 if isinstance(key, SelectableInt):
304 key = key.value
305 if isinstance(key, int):
306 key = spr_dict[key].SPR
307 print("spr key", key)
308 key = special_sprs.get(key, key)
309 if key == 'HSRR0': # HACK!
310 self.__setitem__('SRR0', value)
311 if key == 'HSRR1': # HACK!
312 self.__setitem__('SRR1', value)
313 print("setting spr", key, value)
314 dict.__setitem__(self, key, value)
315
316 def __call__(self, ridx):
317 return self[ridx]
318
319 def get_pdecode_idx_in(dec2, name):
320 op = dec2.dec.op
321 in1_sel = yield op.in1_sel
322 in2_sel = yield op.in2_sel
323 in3_sel = yield op.in3_sel
324 # get the IN1/2/3 from the decoder (includes SVP64 remap and isvec)
325 in1 = yield dec2.e.read_reg1.data
326 in2 = yield dec2.e.read_reg2.data
327 in3 = yield dec2.e.read_reg3.data
328 in1_isvec = yield dec2.in1_isvec
329 in2_isvec = yield dec2.in2_isvec
330 in3_isvec = yield dec2.in3_isvec
331 print ("get_pdecode_idx", in1_sel, In1Sel.RA.value, in1, in1_isvec)
332 # identify which regnames map to in1/2/3
333 if name == 'RA':
334 if (in1_sel == In1Sel.RA.value or
335 (in1_sel == In1Sel.RA_OR_ZERO.value and in1 != 0)):
336 return in1, in1_isvec
337 if in1_sel == In1Sel.RA_OR_ZERO.value:
338 return in1, in1_isvec
339 elif name == 'RB':
340 if in2_sel == In2Sel.RB.value:
341 return in2, in2_isvec
342 if in3_sel == In3Sel.RB.value:
343 return in3, in3_isvec
344 # XXX TODO, RC doesn't exist yet!
345 elif name == 'RC':
346 assert False, "RC does not exist yet"
347 elif name == 'RS':
348 if in1_sel == In1Sel.RS.value:
349 return in1, in1_isvec
350 if in2_sel == In2Sel.RS.value:
351 return in2, in2_isvec
352 if in3_sel == In3Sel.RS.value:
353 return in3, in3_isvec
354 return None, False
355
356
357 def get_pdecode_idx_out(dec2, name):
358 op = dec2.dec.op
359 out_sel = yield op.out_sel
360 # get the IN1/2/3 from the decoder (includes SVP64 remap and isvec)
361 out = yield dec2.e.write_reg.data
362 o_isvec = yield dec2.o_isvec
363 print ("get_pdecode_idx_out", out_sel, OutSel.RA.value, out, o_isvec)
364 # identify which regnames map to out / o2
365 if name == 'RA':
366 if out_sel == OutSel.RA.value:
367 return out, o_isvec
368 elif name == 'RT':
369 if out_sel == OutSel.RT.value:
370 return out, o_isvec
371 print ("get_pdecode_idx_out not found", name)
372 return None, False
373
374
375 # XXX TODO
376 def get_pdecode_idx_out2(dec2, name):
377 op = dec2.dec.op
378 print ("TODO: get_pdecode_idx_out2", name)
379 return None, False
380
381
382 class ISACaller:
383 # decoder2 - an instance of power_decoder2
384 # regfile - a list of initial values for the registers
385 # initial_{etc} - initial values for SPRs, Condition Register, Mem, MSR
386 # respect_pc - tracks the program counter. requires initial_insns
387 def __init__(self, decoder2, regfile, initial_sprs=None, initial_cr=0,
388 initial_mem=None, initial_msr=0,
389 initial_svstate=0,
390 initial_insns=None, respect_pc=False,
391 disassembly=None,
392 initial_pc=0,
393 bigendian=False):
394
395 self.bigendian = bigendian
396 self.halted = False
397 self.is_svp64_mode = False
398 self.respect_pc = respect_pc
399 if initial_sprs is None:
400 initial_sprs = {}
401 if initial_mem is None:
402 initial_mem = {}
403 if initial_insns is None:
404 initial_insns = {}
405 assert self.respect_pc == False, "instructions required to honor pc"
406
407 print("ISACaller insns", respect_pc, initial_insns, disassembly)
408 print("ISACaller initial_msr", initial_msr)
409
410 # "fake program counter" mode (for unit testing)
411 self.fake_pc = 0
412 disasm_start = 0
413 if not respect_pc:
414 if isinstance(initial_mem, tuple):
415 self.fake_pc = initial_mem[0]
416 disasm_start = self.fake_pc
417 else:
418 disasm_start = initial_pc
419
420 # disassembly: we need this for now (not given from the decoder)
421 self.disassembly = {}
422 if disassembly:
423 for i, code in enumerate(disassembly):
424 self.disassembly[i*4 + disasm_start] = code
425
426 # set up registers, instruction memory, data memory, PC, SPRs, MSR
427 self.svp64rm = SVP64RM()
428 if isinstance(initial_svstate, int):
429 initial_svstate = SVP64State(initial_svstate)
430 self.svstate = initial_svstate
431 self.gpr = GPR(decoder2, self, self.svstate, regfile)
432 self.mem = Mem(row_bytes=8, initial_mem=initial_mem)
433 self.imem = Mem(row_bytes=4, initial_mem=initial_insns)
434 self.pc = PC()
435 self.spr = SPR(decoder2, initial_sprs)
436 self.msr = SelectableInt(initial_msr, 64) # underlying reg
437
438 # TODO, needed here:
439 # FPR (same as GPR except for FP nums)
440 # 4.2.2 p124 FPSCR (definitely "separate" - not in SPR)
441 # note that mffs, mcrfs, mtfsf "manage" this FPSCR
442 # 2.3.1 CR (and sub-fields CR0..CR6 - CR0 SO comes from XER.SO)
443 # note that mfocrf, mfcr, mtcr, mtocrf, mcrxrx "manage" CRs
444 # -- Done
445 # 2.3.2 LR (actually SPR #8) -- Done
446 # 2.3.3 CTR (actually SPR #9) -- Done
447 # 2.3.4 TAR (actually SPR #815)
448 # 3.2.2 p45 XER (actually SPR #1) -- Done
449 # 3.2.3 p46 p232 VRSAVE (actually SPR #256)
450
451 # create CR then allow portions of it to be "selectable" (below)
452 #rev_cr = int('{:016b}'.format(initial_cr)[::-1], 2)
453 self.cr = SelectableInt(initial_cr, 64) # underlying reg
454 #self.cr = FieldSelectableInt(self._cr, list(range(32, 64)))
455
456 # "undefined", just set to variable-bit-width int (use exts "max")
457 #self.undefined = SelectableInt(0, 256) # TODO, not hard-code 256!
458
459 self.namespace = {}
460 self.namespace.update(self.spr)
461 self.namespace.update({'GPR': self.gpr,
462 'MEM': self.mem,
463 'SPR': self.spr,
464 'memassign': self.memassign,
465 'NIA': self.pc.NIA,
466 'CIA': self.pc.CIA,
467 'CR': self.cr,
468 'MSR': self.msr,
469 'undefined': undefined,
470 'mode_is_64bit': True,
471 'SO': XER_bits['SO']
472 })
473
474 # update pc to requested start point
475 self.set_pc(initial_pc)
476
477 # field-selectable versions of Condition Register TODO check bitranges?
478 self.crl = []
479 for i in range(8):
480 bits = tuple(range(i*4+32, (i+1)*4+32)) # errr... maybe?
481 _cr = FieldSelectableInt(self.cr, bits)
482 self.crl.append(_cr)
483 self.namespace["CR%d" % i] = _cr
484
485 self.decoder = decoder2.dec
486 self.dec2 = decoder2
487
488 def TRAP(self, trap_addr=0x700, trap_bit=PIb.TRAP):
489 print("TRAP:", hex(trap_addr), hex(self.namespace['MSR'].value))
490 # store CIA(+4?) in SRR0, set NIA to 0x700
491 # store MSR in SRR1, set MSR to um errr something, have to check spec
492 self.spr['SRR0'].value = self.pc.CIA.value
493 self.spr['SRR1'].value = self.namespace['MSR'].value
494 self.trap_nia = SelectableInt(trap_addr, 64)
495 self.spr['SRR1'][trap_bit] = 1 # change *copy* of MSR in SRR1
496
497 # set exception bits. TODO: this should, based on the address
498 # in figure 66 p1065 V3.0B and the table figure 65 p1063 set these
499 # bits appropriately. however it turns out that *for now* in all
500 # cases (all trap_addrs) the exact same thing is needed.
501 self.msr[MSRb.IR] = 0
502 self.msr[MSRb.DR] = 0
503 self.msr[MSRb.FE0] = 0
504 self.msr[MSRb.FE1] = 0
505 self.msr[MSRb.EE] = 0
506 self.msr[MSRb.RI] = 0
507 self.msr[MSRb.SF] = 1
508 self.msr[MSRb.TM] = 0
509 self.msr[MSRb.VEC] = 0
510 self.msr[MSRb.VSX] = 0
511 self.msr[MSRb.PR] = 0
512 self.msr[MSRb.FP] = 0
513 self.msr[MSRb.PMM] = 0
514 self.msr[MSRb.TEs] = 0
515 self.msr[MSRb.TEe] = 0
516 self.msr[MSRb.UND] = 0
517 self.msr[MSRb.LE] = 1
518
519 def memassign(self, ea, sz, val):
520 self.mem.memassign(ea, sz, val)
521
522 def prep_namespace(self, formname, op_fields):
523 # TODO: get field names from form in decoder*1* (not decoder2)
524 # decoder2 is hand-created, and decoder1.sigform is auto-generated
525 # from spec
526 # then "yield" fields only from op_fields rather than hard-coded
527 # list, here.
528 fields = self.decoder.sigforms[formname]
529 for name in op_fields:
530 if name == 'spr':
531 sig = getattr(fields, name.upper())
532 else:
533 sig = getattr(fields, name)
534 val = yield sig
535 # these are all opcode fields involved in index-selection of CR,
536 # and need to do "standard" arithmetic. CR[BA+32] for example
537 # would, if using SelectableInt, only be 5-bit.
538 if name in ['BF', 'BFA', 'BC', 'BA', 'BB', 'BT', 'BI']:
539 self.namespace[name] = val
540 else:
541 self.namespace[name] = SelectableInt(val, sig.width)
542
543 self.namespace['XER'] = self.spr['XER']
544 self.namespace['CA'] = self.spr['XER'][XER_bits['CA']].value
545 self.namespace['CA32'] = self.spr['XER'][XER_bits['CA32']].value
546
547 def handle_carry_(self, inputs, outputs, already_done):
548 inv_a = yield self.dec2.e.do.invert_in
549 if inv_a:
550 inputs[0] = ~inputs[0]
551
552 imm_ok = yield self.dec2.e.do.imm_data.ok
553 if imm_ok:
554 imm = yield self.dec2.e.do.imm_data.data
555 inputs.append(SelectableInt(imm, 64))
556 assert len(outputs) >= 1
557 print("outputs", repr(outputs))
558 if isinstance(outputs, list) or isinstance(outputs, tuple):
559 output = outputs[0]
560 else:
561 output = outputs
562 gts = []
563 for x in inputs:
564 print("gt input", x, output)
565 gt = (gtu(x, output))
566 gts.append(gt)
567 print(gts)
568 cy = 1 if any(gts) else 0
569 print("CA", cy, gts)
570 if not (1 & already_done):
571 self.spr['XER'][XER_bits['CA']] = cy
572
573 print("inputs", already_done, inputs)
574 # 32 bit carry
575 # ARGH... different for OP_ADD... *sigh*...
576 op = yield self.dec2.e.do.insn_type
577 if op == MicrOp.OP_ADD.value:
578 res32 = (output.value & (1 << 32)) != 0
579 a32 = (inputs[0].value & (1 << 32)) != 0
580 if len(inputs) >= 2:
581 b32 = (inputs[1].value & (1 << 32)) != 0
582 else:
583 b32 = False
584 cy32 = res32 ^ a32 ^ b32
585 print("CA32 ADD", cy32)
586 else:
587 gts = []
588 for x in inputs:
589 print("input", x, output)
590 print(" x[32:64]", x, x[32:64])
591 print(" o[32:64]", output, output[32:64])
592 gt = (gtu(x[32:64], output[32:64])) == SelectableInt(1, 1)
593 gts.append(gt)
594 cy32 = 1 if any(gts) else 0
595 print("CA32", cy32, gts)
596 if not (2 & already_done):
597 self.spr['XER'][XER_bits['CA32']] = cy32
598
599 def handle_overflow(self, inputs, outputs, div_overflow):
600 if hasattr(self.dec2.e.do, "invert_in"):
601 inv_a = yield self.dec2.e.do.invert_in
602 if inv_a:
603 inputs[0] = ~inputs[0]
604
605 imm_ok = yield self.dec2.e.do.imm_data.ok
606 if imm_ok:
607 imm = yield self.dec2.e.do.imm_data.data
608 inputs.append(SelectableInt(imm, 64))
609 assert len(outputs) >= 1
610 print("handle_overflow", inputs, outputs, div_overflow)
611 if len(inputs) < 2 and div_overflow is None:
612 return
613
614 # div overflow is different: it's returned by the pseudo-code
615 # because it's more complex than can be done by analysing the output
616 if div_overflow is not None:
617 ov, ov32 = div_overflow, div_overflow
618 # arithmetic overflow can be done by analysing the input and output
619 elif len(inputs) >= 2:
620 output = outputs[0]
621
622 # OV (64-bit)
623 input_sgn = [exts(x.value, x.bits) < 0 for x in inputs]
624 output_sgn = exts(output.value, output.bits) < 0
625 ov = 1 if input_sgn[0] == input_sgn[1] and \
626 output_sgn != input_sgn[0] else 0
627
628 # OV (32-bit)
629 input32_sgn = [exts(x.value, 32) < 0 for x in inputs]
630 output32_sgn = exts(output.value, 32) < 0
631 ov32 = 1 if input32_sgn[0] == input32_sgn[1] and \
632 output32_sgn != input32_sgn[0] else 0
633
634 self.spr['XER'][XER_bits['OV']] = ov
635 self.spr['XER'][XER_bits['OV32']] = ov32
636 so = self.spr['XER'][XER_bits['SO']]
637 so = so | ov
638 self.spr['XER'][XER_bits['SO']] = so
639
640 def handle_comparison(self, outputs):
641 out = outputs[0]
642 assert isinstance(out, SelectableInt), \
643 "out zero not a SelectableInt %s" % repr(outputs)
644 print("handle_comparison", out.bits, hex(out.value))
645 # TODO - XXX *processor* in 32-bit mode
646 # https://bugs.libre-soc.org/show_bug.cgi?id=424
647 # if is_32bit:
648 # o32 = exts(out.value, 32)
649 # print ("handle_comparison exts 32 bit", hex(o32))
650 out = exts(out.value, out.bits)
651 print("handle_comparison exts", hex(out))
652 zero = SelectableInt(out == 0, 1)
653 positive = SelectableInt(out > 0, 1)
654 negative = SelectableInt(out < 0, 1)
655 SO = self.spr['XER'][XER_bits['SO']]
656 print("handle_comparison SO", SO)
657 cr_field = selectconcat(negative, positive, zero, SO)
658 self.crl[0].eq(cr_field)
659
660 def set_pc(self, pc_val):
661 self.namespace['NIA'] = SelectableInt(pc_val, 64)
662 self.pc.update(self.namespace)
663
664 def setup_one(self):
665 """set up one instruction
666 """
667 if self.respect_pc:
668 pc = self.pc.CIA.value
669 else:
670 pc = self.fake_pc
671 self._pc = pc
672 ins = self.imem.ld(pc, 4, False, True)
673 if ins is None:
674 raise KeyError("no instruction at 0x%x" % pc)
675 print("setup: 0x%x 0x%x %s" % (pc, ins & 0xffffffff, bin(ins)))
676 print("CIA NIA", self.respect_pc, self.pc.CIA.value, self.pc.NIA.value)
677
678 yield self.dec2.sv_rm.eq(0)
679 yield self.dec2.dec.raw_opcode_in.eq(ins & 0xffffffff)
680 yield self.dec2.dec.bigendian.eq(self.bigendian)
681 yield self.dec2.state.msr.eq(self.msr.value)
682 yield self.dec2.state.pc.eq(pc)
683
684 # SVP64. first, check if the opcode is EXT001, and SVP64 id bits set
685 yield Settle()
686 opcode = yield self.dec2.dec.opcode_in
687 pfx = SVP64PrefixFields()
688 pfx.insn.value = opcode
689 major = pfx.major.asint(msb0=True) # MSB0 inversion
690 print ("prefix test: opcode:", major, bin(major),
691 pfx.insn[7] == 0b1, pfx.insn[9] == 0b1)
692 self.is_svp64_mode = ((major == 0b000001) and
693 pfx.insn[7].value == 0b1 and
694 pfx.insn[9].value == 0b1)
695 if not self.is_svp64_mode:
696 return
697
698 # in SVP64 mode. decode/print out svp64 prefix, get v3.0B instruction
699 print ("svp64.rm", bin(pfx.rm.asint(msb0=True)))
700 sv_rm = pfx.rm.asint()
701 ins = self.imem.ld(pc+4, 4, False, True)
702 print(" svsetup: 0x%x 0x%x %s" % (pc+4, ins & 0xffffffff, bin(ins)))
703 yield self.dec2.dec.raw_opcode_in.eq(ins & 0xffffffff) # v3.0B suffix
704 yield self.dec2.sv_rm.eq(sv_rm) # svp64 prefix
705 yield Settle()
706
707 def execute_one(self):
708 """execute one instruction
709 """
710 # get the disassembly code for this instruction
711 if self.is_svp64_mode:
712 code = self.disassembly[self._pc+4]
713 print(" svp64 sim-execute", hex(self._pc), code)
714 else:
715 code = self.disassembly[self._pc]
716 print("sim-execute", hex(self._pc), code)
717 opname = code.split(' ')[0]
718 yield from self.call(opname)
719
720 if not self.respect_pc:
721 self.fake_pc += 4
722 print("execute one, CIA NIA", self.pc.CIA.value, self.pc.NIA.value)
723
724 def get_assembly_name(self):
725 # TODO, asmregs is from the spec, e.g. add RT,RA,RB
726 # see http://bugs.libre-riscv.org/show_bug.cgi?id=282
727 dec_insn = yield self.dec2.e.do.insn
728 asmcode = yield self.dec2.dec.op.asmcode
729 print("get assembly name asmcode", asmcode, hex(dec_insn))
730 asmop = insns.get(asmcode, None)
731 int_op = yield self.dec2.dec.op.internal_op
732
733 # sigh reconstruct the assembly instruction name
734 if hasattr(self.dec2.e.do, "oe"):
735 ov_en = yield self.dec2.e.do.oe.oe
736 ov_ok = yield self.dec2.e.do.oe.ok
737 else:
738 ov_en = False
739 ov_ok = False
740 if hasattr(self.dec2.e.do, "rc"):
741 rc_en = yield self.dec2.e.do.rc.rc
742 rc_ok = yield self.dec2.e.do.rc.ok
743 else:
744 rc_en = False
745 rc_ok = False
746 # grrrr have to special-case MUL op (see DecodeOE)
747 print("ov %d en %d rc %d en %d op %d" %
748 (ov_ok, ov_en, rc_ok, rc_en, int_op))
749 if int_op in [MicrOp.OP_MUL_H64.value, MicrOp.OP_MUL_H32.value]:
750 print("mul op")
751 if rc_en & rc_ok:
752 asmop += "."
753 else:
754 if not asmop.endswith("."): # don't add "." to "andis."
755 if rc_en & rc_ok:
756 asmop += "."
757 if hasattr(self.dec2.e.do, "lk"):
758 lk = yield self.dec2.e.do.lk
759 if lk:
760 asmop += "l"
761 print("int_op", int_op)
762 if int_op in [MicrOp.OP_B.value, MicrOp.OP_BC.value]:
763 AA = yield self.dec2.dec.fields.FormI.AA[0:-1]
764 print("AA", AA)
765 if AA:
766 asmop += "a"
767 spr_msb = yield from self.get_spr_msb()
768 if int_op == MicrOp.OP_MFCR.value:
769 if spr_msb:
770 asmop = 'mfocrf'
771 else:
772 asmop = 'mfcr'
773 # XXX TODO: for whatever weird reason this doesn't work
774 # https://bugs.libre-soc.org/show_bug.cgi?id=390
775 if int_op == MicrOp.OP_MTCRF.value:
776 if spr_msb:
777 asmop = 'mtocrf'
778 else:
779 asmop = 'mtcrf'
780 return asmop
781
782 def get_spr_msb(self):
783 dec_insn = yield self.dec2.e.do.insn
784 return dec_insn & (1 << 20) != 0 # sigh - XFF.spr[-1]?
785
786 def call(self, name):
787 """call(opcode) - the primary execution point for instructions
788 """
789 name = name.strip() # remove spaces if not already done so
790 if self.halted:
791 print("halted - not executing", name)
792 return
793
794 # TODO, asmregs is from the spec, e.g. add RT,RA,RB
795 # see http://bugs.libre-riscv.org/show_bug.cgi?id=282
796 asmop = yield from self.get_assembly_name()
797 print("call", name, asmop)
798
799 # check privileged
800 int_op = yield self.dec2.dec.op.internal_op
801 spr_msb = yield from self.get_spr_msb()
802
803 instr_is_privileged = False
804 if int_op in [MicrOp.OP_ATTN.value,
805 MicrOp.OP_MFMSR.value,
806 MicrOp.OP_MTMSR.value,
807 MicrOp.OP_MTMSRD.value,
808 # TODO: OP_TLBIE
809 MicrOp.OP_RFID.value]:
810 instr_is_privileged = True
811 if int_op in [MicrOp.OP_MFSPR.value,
812 MicrOp.OP_MTSPR.value] and spr_msb:
813 instr_is_privileged = True
814
815 print("is priv", instr_is_privileged, hex(self.msr.value),
816 self.msr[MSRb.PR])
817 # check MSR priv bit and whether op is privileged: if so, throw trap
818 if instr_is_privileged and self.msr[MSRb.PR] == 1:
819 self.TRAP(0x700, PIb.PRIV)
820 self.namespace['NIA'] = self.trap_nia
821 self.pc.update(self.namespace)
822 return
823
824 # check halted condition
825 if name == 'attn':
826 self.halted = True
827 return
828
829 # check illegal instruction
830 illegal = False
831 if name not in ['mtcrf', 'mtocrf']:
832 illegal = name != asmop
833
834 if illegal:
835 print("illegal", name, asmop)
836 self.TRAP(0x700, PIb.ILLEG)
837 self.namespace['NIA'] = self.trap_nia
838 self.pc.update(self.namespace)
839 print("name %s != %s - calling ILLEGAL trap, PC: %x" %
840 (name, asmop, self.pc.CIA.value))
841 return
842
843 info = self.instrs[name]
844 yield from self.prep_namespace(info.form, info.op_fields)
845
846 # preserve order of register names
847 input_names = create_args(list(info.read_regs) +
848 list(info.uninit_regs))
849 print(input_names)
850
851 # get SVP64 entry for the current instruction
852 sv_rm = self.svp64rm.instrs.get(name)
853 if sv_rm is not None:
854 dest_cr, src_cr, src_byname, dest_byname = decode_extra(sv_rm)
855 else:
856 dest_cr, src_cr, src_byname, dest_byname = False, False, {}, {}
857 print ("sv rm", sv_rm, dest_cr, src_cr, src_byname, dest_byname)
858
859 # main input registers (RT, RA ...)
860 inputs = []
861 for name in input_names:
862 # using PowerDecoder2, first, find the decoder index.
863 # (mapping name RA RB RC RS to in1, in2, in3)
864 regnum, is_vec = yield from get_pdecode_idx_in(self.dec2, name)
865 if regnum is None:
866 # doing this is not part of svp64, it's because output
867 # registers, to be modified, need to be in the namespace.
868 regnum, is_vec = yield from get_pdecode_idx_out(self.dec2, name)
869 # in case getting the register number is needed, _RA, _RB
870 regname = "_" + name
871 self.namespace[regname] = regnum
872 print('reading reg %s %d' % (name, regnum), is_vec)
873 reg_val = self.gpr(regnum)
874 inputs.append(reg_val)
875
876 # "special" registers
877 for special in info.special_regs:
878 if special in special_sprs:
879 inputs.append(self.spr[special])
880 else:
881 inputs.append(self.namespace[special])
882
883 # clear trap (trap) NIA
884 self.trap_nia = None
885
886 print(inputs)
887 results = info.func(self, *inputs)
888 print(results)
889
890 # "inject" decorator takes namespace from function locals: we need to
891 # overwrite NIA being overwritten (sigh)
892 if self.trap_nia is not None:
893 self.namespace['NIA'] = self.trap_nia
894
895 print("after func", self.namespace['CIA'], self.namespace['NIA'])
896
897 # detect if CA/CA32 already in outputs (sra*, basically)
898 already_done = 0
899 if info.write_regs:
900 output_names = create_args(info.write_regs)
901 for name in output_names:
902 if name == 'CA':
903 already_done |= 1
904 if name == 'CA32':
905 already_done |= 2
906
907 print("carry already done?", bin(already_done))
908 if hasattr(self.dec2.e.do, "output_carry"):
909 carry_en = yield self.dec2.e.do.output_carry
910 else:
911 carry_en = False
912 if carry_en:
913 yield from self.handle_carry_(inputs, results, already_done)
914
915 # detect if overflow was in return result
916 overflow = None
917 if info.write_regs:
918 for name, output in zip(output_names, results):
919 if name == 'overflow':
920 overflow = output
921
922 if hasattr(self.dec2.e.do, "oe"):
923 ov_en = yield self.dec2.e.do.oe.oe
924 ov_ok = yield self.dec2.e.do.oe.ok
925 else:
926 ov_en = False
927 ov_ok = False
928 print("internal overflow", overflow, ov_en, ov_ok)
929 if ov_en & ov_ok:
930 yield from self.handle_overflow(inputs, results, overflow)
931
932 if hasattr(self.dec2.e.do, "rc"):
933 rc_en = yield self.dec2.e.do.rc.rc
934 else:
935 rc_en = False
936 if rc_en:
937 self.handle_comparison(results)
938
939 # any modified return results?
940 if info.write_regs:
941 for name, output in zip(output_names, results):
942 if name == 'overflow': # ignore, done already (above)
943 continue
944 if isinstance(output, int):
945 output = SelectableInt(output, 256)
946 if name in ['CA', 'CA32']:
947 if carry_en:
948 print("writing %s to XER" % name, output)
949 self.spr['XER'][XER_bits[name]] = output.value
950 else:
951 print("NOT writing %s to XER" % name, output)
952 elif name in info.special_regs:
953 print('writing special %s' % name, output, special_sprs)
954 if name in special_sprs:
955 self.spr[name] = output
956 else:
957 self.namespace[name].eq(output)
958 if name == 'MSR':
959 print('msr written', hex(self.msr.value))
960 else:
961 regnum, is_vec = yield from get_pdecode_idx_out(self.dec2,
962 name)
963 if regnum is None:
964 # temporary hack for not having 2nd output
965 regnum = yield getattr(self.decoder, name)
966 is_vec = False
967 print('writing reg %d %s' % (regnum, str(output)), is_vec)
968 if output.bits > 64:
969 output = SelectableInt(output.value, 64)
970 self.gpr[regnum] = output
971
972 print("end of call", self.namespace['CIA'], self.namespace['NIA'])
973 # UPDATE program counter
974 self.pc.update(self.namespace)
975
976
977 def inject():
978 """Decorator factory.
979
980 this decorator will "inject" variables into the function's namespace,
981 from the *dictionary* in self.namespace. it therefore becomes possible
982 to make it look like a whole stack of variables which would otherwise
983 need "self." inserted in front of them (*and* for those variables to be
984 added to the instance) "appear" in the function.
985
986 "self.namespace['SI']" for example becomes accessible as just "SI" but
987 *only* inside the function, when decorated.
988 """
989 def variable_injector(func):
990 @wraps(func)
991 def decorator(*args, **kwargs):
992 try:
993 func_globals = func.__globals__ # Python 2.6+
994 except AttributeError:
995 func_globals = func.func_globals # Earlier versions.
996
997 context = args[0].namespace # variables to be injected
998 saved_values = func_globals.copy() # Shallow copy of dict.
999 func_globals.update(context)
1000 result = func(*args, **kwargs)
1001 print("globals after", func_globals['CIA'], func_globals['NIA'])
1002 print("args[0]", args[0].namespace['CIA'],
1003 args[0].namespace['NIA'])
1004 args[0].namespace = func_globals
1005 #exec (func.__code__, func_globals)
1006
1007 # finally:
1008 # func_globals = saved_values # Undo changes.
1009
1010 return result
1011
1012 return decorator
1013
1014 return variable_injector