f7a015adf44e0f3131d1e2cb540d7aa95c07dc72
[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 if self.svstate is not None:
656 yield self.dec2.state.svstate.eq(self.svstate.spr.value)
657
658 # SVP64. first, check if the opcode is EXT001, and SVP64 id bits set
659 yield Settle()
660 opcode = yield self.dec2.dec.opcode_in
661 pfx = SVP64PrefixFields() # TODO should probably use SVP64PrefixDecoder
662 pfx.insn.value = opcode
663 major = pfx.major.asint(msb0=True) # MSB0 inversion
664 print ("prefix test: opcode:", major, bin(major),
665 pfx.insn[7] == 0b1, pfx.insn[9] == 0b1)
666 self.is_svp64_mode = ((major == 0b000001) and
667 pfx.insn[7].value == 0b1 and
668 pfx.insn[9].value == 0b1)
669 self.pc.update_nia(self.is_svp64_mode)
670 self.namespace['NIA'] = self.pc.NIA
671 if not self.is_svp64_mode:
672 return
673
674 # in SVP64 mode. decode/print out svp64 prefix, get v3.0B instruction
675 print ("svp64.rm", bin(pfx.rm.asint(msb0=True)))
676 print (" svstate.vl", self.svstate.vl.asint(msb0=True))
677 print (" svstate.mvl", self.svstate.maxvl.asint(msb0=True))
678 sv_rm = pfx.rm.asint(msb0=True)
679 ins = self.imem.ld(pc+4, 4, False, True)
680 print(" svsetup: 0x%x 0x%x %s" % (pc+4, ins & 0xffffffff, bin(ins)))
681 yield self.dec2.dec.raw_opcode_in.eq(ins & 0xffffffff) # v3.0B suffix
682 yield self.dec2.sv_rm.eq(sv_rm) # svp64 prefix
683 yield Settle()
684
685 def execute_one(self):
686 """execute one instruction
687 """
688 # get the disassembly code for this instruction
689 if self.is_svp64_mode:
690 code = self.disassembly[self._pc+4]
691 print(" svp64 sim-execute", hex(self._pc), code)
692 else:
693 code = self.disassembly[self._pc]
694 print("sim-execute", hex(self._pc), code)
695 opname = code.split(' ')[0]
696 yield from self.call(opname)
697
698 # don't use this except in special circumstances
699 if not self.respect_pc:
700 self.fake_pc += 4
701
702 print("execute one, CIA NIA", self.pc.CIA.value, self.pc.NIA.value)
703
704 def get_assembly_name(self):
705 # TODO, asmregs is from the spec, e.g. add RT,RA,RB
706 # see http://bugs.libre-riscv.org/show_bug.cgi?id=282
707 dec_insn = yield self.dec2.e.do.insn
708 asmcode = yield self.dec2.dec.op.asmcode
709 print("get assembly name asmcode", asmcode, hex(dec_insn))
710 asmop = insns.get(asmcode, None)
711 int_op = yield self.dec2.dec.op.internal_op
712
713 # sigh reconstruct the assembly instruction name
714 if hasattr(self.dec2.e.do, "oe"):
715 ov_en = yield self.dec2.e.do.oe.oe
716 ov_ok = yield self.dec2.e.do.oe.ok
717 else:
718 ov_en = False
719 ov_ok = False
720 if hasattr(self.dec2.e.do, "rc"):
721 rc_en = yield self.dec2.e.do.rc.rc
722 rc_ok = yield self.dec2.e.do.rc.ok
723 else:
724 rc_en = False
725 rc_ok = False
726 # grrrr have to special-case MUL op (see DecodeOE)
727 print("ov %d en %d rc %d en %d op %d" %
728 (ov_ok, ov_en, rc_ok, rc_en, int_op))
729 if int_op in [MicrOp.OP_MUL_H64.value, MicrOp.OP_MUL_H32.value]:
730 print("mul op")
731 if rc_en & rc_ok:
732 asmop += "."
733 else:
734 if not asmop.endswith("."): # don't add "." to "andis."
735 if rc_en & rc_ok:
736 asmop += "."
737 if hasattr(self.dec2.e.do, "lk"):
738 lk = yield self.dec2.e.do.lk
739 if lk:
740 asmop += "l"
741 print("int_op", int_op)
742 if int_op in [MicrOp.OP_B.value, MicrOp.OP_BC.value]:
743 AA = yield self.dec2.dec.fields.FormI.AA[0:-1]
744 print("AA", AA)
745 if AA:
746 asmop += "a"
747 spr_msb = yield from self.get_spr_msb()
748 if int_op == MicrOp.OP_MFCR.value:
749 if spr_msb:
750 asmop = 'mfocrf'
751 else:
752 asmop = 'mfcr'
753 # XXX TODO: for whatever weird reason this doesn't work
754 # https://bugs.libre-soc.org/show_bug.cgi?id=390
755 if int_op == MicrOp.OP_MTCRF.value:
756 if spr_msb:
757 asmop = 'mtocrf'
758 else:
759 asmop = 'mtcrf'
760 return asmop
761
762 def get_spr_msb(self):
763 dec_insn = yield self.dec2.e.do.insn
764 return dec_insn & (1 << 20) != 0 # sigh - XFF.spr[-1]?
765
766 def call(self, name):
767 """call(opcode) - the primary execution point for instructions
768 """
769 name = name.strip() # remove spaces if not already done so
770 if self.halted:
771 print("halted - not executing", name)
772 return
773
774 # TODO, asmregs is from the spec, e.g. add RT,RA,RB
775 # see http://bugs.libre-riscv.org/show_bug.cgi?id=282
776 asmop = yield from self.get_assembly_name()
777 print("call", name, asmop)
778
779 # check privileged
780 int_op = yield self.dec2.dec.op.internal_op
781 spr_msb = yield from self.get_spr_msb()
782
783 instr_is_privileged = False
784 if int_op in [MicrOp.OP_ATTN.value,
785 MicrOp.OP_MFMSR.value,
786 MicrOp.OP_MTMSR.value,
787 MicrOp.OP_MTMSRD.value,
788 # TODO: OP_TLBIE
789 MicrOp.OP_RFID.value]:
790 instr_is_privileged = True
791 if int_op in [MicrOp.OP_MFSPR.value,
792 MicrOp.OP_MTSPR.value] and spr_msb:
793 instr_is_privileged = True
794
795 print("is priv", instr_is_privileged, hex(self.msr.value),
796 self.msr[MSRb.PR])
797 # check MSR priv bit and whether op is privileged: if so, throw trap
798 if instr_is_privileged and self.msr[MSRb.PR] == 1:
799 self.TRAP(0x700, PIb.PRIV)
800 self.namespace['NIA'] = self.trap_nia
801 self.pc.update(self.namespace, self.is_svp64_mode)
802 return
803
804 # check halted condition
805 if name == 'attn':
806 self.halted = True
807 return
808
809 # check illegal instruction
810 illegal = False
811 if name not in ['mtcrf', 'mtocrf']:
812 illegal = name != asmop
813
814 if illegal:
815 print("illegal", name, asmop)
816 self.TRAP(0x700, PIb.ILLEG)
817 self.namespace['NIA'] = self.trap_nia
818 self.pc.update(self.namespace, self.is_svp64_mode)
819 print("name %s != %s - calling ILLEGAL trap, PC: %x" %
820 (name, asmop, self.pc.CIA.value))
821 return
822
823 info = self.instrs[name]
824 yield from self.prep_namespace(info.form, info.op_fields)
825
826 # preserve order of register names
827 input_names = create_args(list(info.read_regs) +
828 list(info.uninit_regs))
829 print(input_names)
830
831 # get SVP64 entry for the current instruction
832 sv_rm = self.svp64rm.instrs.get(name)
833 if sv_rm is not None:
834 dest_cr, src_cr, src_byname, dest_byname = decode_extra(sv_rm)
835 else:
836 dest_cr, src_cr, src_byname, dest_byname = False, False, {}, {}
837 print ("sv rm", sv_rm, dest_cr, src_cr, src_byname, dest_byname)
838
839 # VL=0 in SVP64 mode means "do nothing: skip instruction"
840 if self.is_svp64_mode and vl == 0:
841 self.pc.update(self.namespace, self.is_svp64_mode)
842 print("end of call", self.namespace['CIA'], self.namespace['NIA'])
843 return
844
845 # main input registers (RT, RA ...)
846 inputs = []
847 for name in input_names:
848 # using PowerDecoder2, first, find the decoder index.
849 # (mapping name RA RB RC RS to in1, in2, in3)
850 regnum, is_vec = yield from get_pdecode_idx_in(self.dec2, name)
851 if regnum is None:
852 # doing this is not part of svp64, it's because output
853 # registers, to be modified, need to be in the namespace.
854 regnum, is_vec = yield from get_pdecode_idx_out(self.dec2, name)
855
856 # in case getting the register number is needed, _RA, _RB
857 regname = "_" + name
858 self.namespace[regname] = regnum
859 print('reading reg %s %d' % (name, regnum), is_vec)
860 reg_val = self.gpr(regnum)
861 inputs.append(reg_val)
862
863 # "special" registers
864 for special in info.special_regs:
865 if special in special_sprs:
866 inputs.append(self.spr[special])
867 else:
868 inputs.append(self.namespace[special])
869
870 # clear trap (trap) NIA
871 self.trap_nia = None
872
873 print("inputs", inputs)
874 results = info.func(self, *inputs)
875 print("results", results)
876
877 # "inject" decorator takes namespace from function locals: we need to
878 # overwrite NIA being overwritten (sigh)
879 if self.trap_nia is not None:
880 self.namespace['NIA'] = self.trap_nia
881
882 print("after func", self.namespace['CIA'], self.namespace['NIA'])
883
884 # detect if CA/CA32 already in outputs (sra*, basically)
885 already_done = 0
886 if info.write_regs:
887 output_names = create_args(info.write_regs)
888 for name in output_names:
889 if name == 'CA':
890 already_done |= 1
891 if name == 'CA32':
892 already_done |= 2
893
894 print("carry already done?", bin(already_done))
895 if hasattr(self.dec2.e.do, "output_carry"):
896 carry_en = yield self.dec2.e.do.output_carry
897 else:
898 carry_en = False
899 if carry_en:
900 yield from self.handle_carry_(inputs, results, already_done)
901
902 # detect if overflow was in return result
903 overflow = None
904 if info.write_regs:
905 for name, output in zip(output_names, results):
906 if name == 'overflow':
907 overflow = output
908
909 if hasattr(self.dec2.e.do, "oe"):
910 ov_en = yield self.dec2.e.do.oe.oe
911 ov_ok = yield self.dec2.e.do.oe.ok
912 else:
913 ov_en = False
914 ov_ok = False
915 print("internal overflow", overflow, ov_en, ov_ok)
916 if ov_en & ov_ok:
917 yield from self.handle_overflow(inputs, results, overflow)
918
919 if hasattr(self.dec2.e.do, "rc"):
920 rc_en = yield self.dec2.e.do.rc.rc
921 else:
922 rc_en = False
923 if rc_en:
924 regnum, is_vec = yield from get_pdecode_cr_out(self.dec2, "CR0")
925 self.handle_comparison(results, regnum)
926
927 # any modified return results?
928 if info.write_regs:
929 for name, output in zip(output_names, results):
930 if name == 'overflow': # ignore, done already (above)
931 continue
932 if isinstance(output, int):
933 output = SelectableInt(output, 256)
934 if name in ['CA', 'CA32']:
935 if carry_en:
936 print("writing %s to XER" % name, output)
937 self.spr['XER'][XER_bits[name]] = output.value
938 else:
939 print("NOT writing %s to XER" % name, output)
940 elif name in info.special_regs:
941 print('writing special %s' % name, output, special_sprs)
942 if name in special_sprs:
943 self.spr[name] = output
944 else:
945 self.namespace[name].eq(output)
946 if name == 'MSR':
947 print('msr written', hex(self.msr.value))
948 else:
949 regnum, is_vec = yield from get_pdecode_idx_out(self.dec2,
950 name)
951 if regnum is None:
952 # temporary hack for not having 2nd output
953 regnum = yield getattr(self.decoder, name)
954 is_vec = False
955 print('writing reg %d %s' % (regnum, str(output)), is_vec)
956 if output.bits > 64:
957 output = SelectableInt(output.value, 64)
958 self.gpr[regnum] = output
959
960 # check if it is the SVSTATE.src/dest step that needs incrementing
961 # this is our Sub-Program-Counter loop from 0 to VL-1
962 if self.is_svp64_mode:
963 # XXX twin predication TODO
964 vl = self.svstate.vl.asint(msb0=True)
965 mvl = self.svstate.maxvl.asint(msb0=True)
966 srcstep = self.svstate.srcstep.asint(msb0=True)
967 print (" svstate.vl", vl)
968 print (" svstate.mvl", mvl)
969 print (" svstate.srcstep", srcstep)
970 # check if srcstep needs incrementing by one, stop PC advancing
971 # svp64 loop can end early if the dest is scalar
972 svp64_dest_vector = not (yield self.dec2.no_out_vec)
973 if svp64_dest_vector and srcstep != vl-1:
974 self.svstate.srcstep += SelectableInt(1, 7)
975 self.pc.NIA.value = self.pc.CIA.value
976 self.namespace['NIA'] = self.pc.NIA
977 print("end of sub-pc call", self.namespace['CIA'],
978 self.namespace['NIA'])
979 return # DO NOT allow PC to update whilst Sub-PC loop running
980 # reset to zero
981 self.svstate.srcstep[0:7] = 0
982 print (" svstate.srcstep loop end (PC to update)")
983 self.pc.update_nia(self.is_svp64_mode)
984 self.namespace['NIA'] = self.pc.NIA
985
986 # UPDATE program counter
987 self.pc.update(self.namespace, self.is_svp64_mode)
988 print("end of call", self.namespace['CIA'], self.namespace['NIA'])
989
990
991 def inject():
992 """Decorator factory.
993
994 this decorator will "inject" variables into the function's namespace,
995 from the *dictionary* in self.namespace. it therefore becomes possible
996 to make it look like a whole stack of variables which would otherwise
997 need "self." inserted in front of them (*and* for those variables to be
998 added to the instance) "appear" in the function.
999
1000 "self.namespace['SI']" for example becomes accessible as just "SI" but
1001 *only* inside the function, when decorated.
1002 """
1003 def variable_injector(func):
1004 @wraps(func)
1005 def decorator(*args, **kwargs):
1006 try:
1007 func_globals = func.__globals__ # Python 2.6+
1008 except AttributeError:
1009 func_globals = func.func_globals # Earlier versions.
1010
1011 context = args[0].namespace # variables to be injected
1012 saved_values = func_globals.copy() # Shallow copy of dict.
1013 func_globals.update(context)
1014 result = func(*args, **kwargs)
1015 print("globals after", func_globals['CIA'], func_globals['NIA'])
1016 print("args[0]", args[0].namespace['CIA'],
1017 args[0].namespace['NIA'])
1018 args[0].namespace = func_globals
1019 #exec (func.__code__, func_globals)
1020
1021 # finally:
1022 # func_globals = saved_values # Undo changes.
1023
1024 return result
1025
1026 return decorator
1027
1028 return variable_injector
1029
1030