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