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