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