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