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