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
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.
13 * https://bugs.libre-soc.org/show_bug.cgi?id=424
16 from nmigen
.back
.pysim
import Settle
17 from functools
import wraps
19 from soc
.decoder
.orderedset
import OrderedSet
20 from soc
.decoder
.selectable_int
import (FieldSelectableInt
, SelectableInt
,
22 from soc
.decoder
.power_enums
import (spr_dict
, spr_byname
, XER_bits
,
23 insns
, MicrOp
, In1Sel
, In2Sel
, In3Sel
,
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
29 from collections
import namedtuple
33 instruction_info
= namedtuple('instruction_info',
34 'func read_regs uninit_regs write_regs ' +
35 'special_regs op_fields form asmregs')
45 def swap_order(x
, nbytes
):
46 x
= x
.to_bytes(nbytes
, byteorder
='little')
47 x
= int.from_bytes(x
, byteorder
='big', signed
=False)
52 # TODO (lkcl): adjust other registers that should be in a particular order
53 # probably CA, CA32, and CR
70 def create_args(reglist
, extra
=None):
71 retval
= list(OrderedSet(reglist
))
72 retval
.sort(key
=lambda reg
: REG_SORT_ORDER
[reg
])
74 return [extra
] + retval
81 //Accessing 2nd double word of partition table (pate1)
82 //Ref: Power ISA Manual v3.0B, Book-III, section 5.7.6.1
84 // ====================================================
85 // -----------------------------------------------
86 // | /// | PATB | /// | PATS |
87 // -----------------------------------------------
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.
95 // Thus, The Partition Table Base is obtained by (PATB << 12)
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).
102 // ====================================================
103 // 0 PATE0 63 PATE1 127
104 // |----------------------|----------------------|
106 // |----------------------|----------------------|
108 // |----------------------|----------------------|
110 // |----------------------|----------------------|
114 // |----------------------|----------------------|
116 // |----------------------|----------------------|
118 // The effective LPID forms the index into the Partition Table.
120 // Each entry in the partition table contains 2 double words, PATE0, PATE1,
121 // corresponding to that partition.
123 // In case of Radix, The structure of PATE0 and PATE1 is as follows.
126 // -----------------------------------------------
127 // |1|RTS1|/| RPDB | RTS2 | RPDS |
128 // -----------------------------------------------
129 // 0 1 2 3 4 55 56 58 59 63
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.
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).
142 // -----------------------------------------------
143 // |///| PRTB | // | PRTS |
144 // -----------------------------------------------
145 // 0 3 4 51 52 58 59 63
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).
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
159 //Ref: Power ISA Manual v3.0B, Book-III, section 5.7.6.2
162 // ==========================
163 // 0 PRTE0 63 PRTE1 127
164 // |----------------------|----------------------|
166 // |----------------------|----------------------|
168 // |----------------------|----------------------|
170 // |----------------------|----------------------|
174 // |----------------------|----------------------|
176 // |----------------------|----------------------|
178 // The effective Process id (PID) forms the index into the Process Table.
180 // Each entry in the partition table contains 2 double words, PRTE0, PRTE1,
181 // corresponding to that process
183 // In case of Radix, The structure of PRTE0 and PRTE1 is as follows.
186 // -----------------------------------------------
187 // |/|RTS1|/| RPDB | RTS2 | RPDS |
188 // -----------------------------------------------
189 // 0 1 2 3 4 55 56 58 59 63
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.
196 // RPDB = Root Page Directory Base.
197 // RPDS = Root Page Directory Size right shifted by 3.
198 // Thus, Root page directory size = RPDS << 3.
202 // -----------------------------------------------
204 // -----------------------------------------------
206 // All bits are reserved.
211 # see qemu/target/ppc/mmu-radix64.c for reference
213 def __init__(self
, mem
, caller
):
217 # cached page table stuff
219 self
.pt0_valid
= False
221 self
.pt3_valid
= False
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
))
226 pte
= self
._walk
_tree
()
227 # use pte to caclculate phys address
228 return self
.mem
.ld(address
, width
, swap
, check_in_mem
)
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
)
235 # def memassign(self, addr, sz, val):
236 def _next_level(self
):
241 ## Prepare for next iteration
243 def _walk_tree(self
):
247 // vaddr |-----------------------------------------------------|
249 // |-----------|-----------------------------------------|
250 // | 0000000 | usefulBits = X bits (typically 52) |
251 // |-----------|-----------------------------------------|
252 // | |<--Cursize---->| |
256 // |-----------------------------------------------------|
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 |
270 // | |--------------------------|
271 // | | usfulBits = X-Cursize |
272 // | |--------------------------|
273 // |---------------------><--NLS-->| |
277 // |--------------------------|
279 // If the next PDE obtained by |
280 // (NLB << 8 + 8 * index) is a |
281 // nonleaf, then repeat the above. |
283 // If the next PDE is a leaf, |
284 // then Leaf PDE structure is as |
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 |
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
304 // 0b10 = Non Idenmpotent
305 // 0b11 = Tolerant I/O
306 // [60:63] = Encoded Access
310 # walk tree starts on prtbl
312 ret
= self
._next
_level
()
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;
323 elsif mbits < 5 or mbits > 16 or mbits > (r.shift + (31 - 12)) then
324 v.state := RADIX_FINISH;
327 v.state := RADIX_LOOKUP;
330 def _check_perms(self
):
331 """check page permissions
333 if data(62) = '1' then
334 -- check permissions and RC bits
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);
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);
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;
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;
359 def __init__(self
, row_bytes
=8, initial_mem
=None):
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
)
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
373 for i
, val
in enumerate(mem
):
374 initial_mem
[startaddr
+ row_bytes
*i
] = (val
, row_bytes
)
376 for addr
, (val
, width
) in initial_mem
.items():
377 #val = swap_order(val, width)
378 self
.st(addr
, val
, width
, swap
=False)
380 def _get_shifter_mask(self
, wid
, remainder
):
381 shifter
= ((self
.bytes_per_word
- wid
) - remainder
) * \
383 # XXX https://bugs.libre-soc.org/show_bug.cgi?id=377
385 shifter
= remainder
* 8
386 mask
= (1 << (wid
* 8)) - 1
387 print("width,rem,shift,mask", wid
, remainder
, hex(shifter
), hex(mask
))
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
]
402 print("mem @ 0x{:x} rem {:d} : 0x{:x}".format(address
, remainder
, val
))
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
)
410 val
= swap_order(val
, width
)
411 print("Read 0x{:x} from addr 0x{:x}".format(val
, address
))
414 def st(self
, addr
, v
, width
=8, swap
=True):
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!"
422 v
= swap_order(v
, width
)
423 if width
!= self
.bytes_per_word
:
428 shifter
, mask
= self
._get
_shifter
_mask
(width
, remainder
)
429 val
&= ~
(mask
<< shifter
)
434 print("mem @ 0x{:x}: 0x{:x}".format(addr
, self
.mem
[addr
]))
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)
441 def memassign(self
, addr
, sz
, val
):
442 print("memassign", addr
, sz
, val
)
443 self
.st(addr
.value
, val
.value
, sz
, swap
=False)
447 def __init__(self
, decoder
, isacaller
, svstate
, regfile
):
450 self
.isacaller
= isacaller
451 self
.svstate
= svstate
453 self
[i
] = SelectableInt(regfile
[i
], 64)
455 def __call__(self
, ridx
):
458 def set_form(self
, form
):
461 def getz(self
, rnum
):
462 # rnum = rnum.value # only SelectableInt allowed
463 print("GPR getzero", rnum
)
465 return SelectableInt(0, 64)
468 def _get_regnum(self
, attr
):
469 getform
= self
.sd
.sigforms
[self
.form
]
470 rnum
= getattr(getform
, attr
)
473 def ___getitem__(self
, attr
):
474 """ XXX currently not used
476 rnum
= self
._get
_regnum
(attr
)
477 offs
= self
.svstate
.srcstep
478 print("GPR getitem", attr
, rnum
, "srcoffs", offs
)
479 return self
.regfile
[rnum
]
482 for i
in range(0, len(self
), 8):
485 s
.append("%08x" % self
[i
+j
].value
)
487 print("reg", "%2d" % i
, s
)
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!
495 def update_nia(self
, is_svp64
):
496 increment
= 8 if is_svp64
else 4
497 self
.NIA
= self
.CIA
+ SelectableInt(increment
, 64)
499 def update(self
, namespace
, is_svp64
):
500 """updates the program counter (PC) by 4 if v3.0B mode or 8 if SVP64
502 self
.CIA
= namespace
['NIA'].narrow(64)
503 self
.update_nia(is_svp64
)
504 namespace
['CIA'] = self
.CIA
505 namespace
['NIA'] = self
.NIA
508 # Simple-V: see https://libre-soc.org/openpower/sv
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)))
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)))
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
)
558 # SVP64 Prefix fields: see https://libre-soc.org/openpower/sv/svp64/
559 class SVP64PrefixFields
:
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
)
569 SV64P_MAJOR_SIZE
= len(SVP64PrefixFields().major
.br
)
570 SV64P_PID_SIZE
= len(SVP64PrefixFields().pid
.br
)
571 SV64P_RM_SIZE
= len(SVP64PrefixFields().rm
.br
)
575 def __init__(self
, dec2
, initial_sprs
={}):
578 for key
, v
in initial_sprs
.items():
579 if isinstance(key
, SelectableInt
):
581 key
= special_sprs
.get(key
, key
)
582 if isinstance(key
, int):
585 info
= spr_byname
[key
]
586 if not isinstance(v
, SelectableInt
):
587 v
= SelectableInt(v
, info
.length
)
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
):
596 if isinstance(key
, int):
597 key
= spr_dict
[key
].SPR
598 key
= special_sprs
.get(key
, key
)
599 if key
== 'HSRR0': # HACK!
601 if key
== 'HSRR1': # HACK!
604 res
= dict.__getitem
__(self
, key
)
606 if isinstance(key
, int):
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
)
615 def __setitem__(self
, key
, value
):
616 if isinstance(key
, SelectableInt
):
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
)
629 def __call__(self
, ridx
):
632 def get_pdecode_idx_in(dec2
, name
):
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
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
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!
659 assert False, "RC does not exist yet"
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
670 def get_pdecode_cr_out(dec2
, name
):
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
687 if out_sel
== CROutSel
.CR0
.value
:
689 print ("get_pdecode_idx_out not found", name
)
693 def get_pdecode_idx_out(dec2
, name
):
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
702 if out_sel
== OutSel
.RA
.value
:
705 if out_sel
== OutSel
.RT
.value
:
707 print ("get_pdecode_idx_out not found", name
)
712 def get_pdecode_idx_out2(dec2
, name
):
714 print ("TODO: get_pdecode_idx_out2", name
)
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,
726 initial_insns
=None, respect_pc
=False,
732 self
.bigendian
= bigendian
734 self
.is_svp64_mode
= False
735 self
.respect_pc
= respect_pc
736 if initial_sprs
is None:
738 if initial_mem
is None:
740 if initial_insns
is None:
742 assert self
.respect_pc
== False, "instructions required to honor pc"
744 print("ISACaller insns", respect_pc
, initial_insns
, disassembly
)
745 print("ISACaller initial_msr", initial_msr
)
747 # "fake program counter" mode (for unit testing)
751 if isinstance(initial_mem
, tuple):
752 self
.fake_pc
= initial_mem
[0]
753 disasm_start
= self
.fake_pc
755 disasm_start
= initial_pc
757 # disassembly: we need this for now (not given from the decoder)
758 self
.disassembly
= {}
760 for i
, code
in enumerate(disassembly
):
761 self
.disassembly
[i
*4 + disasm_start
] = code
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
)
771 self
.mem
= RADIX(self
.mem
, self
)
772 self
.imem
= Mem(row_bytes
=4, initial_mem
=initial_insns
)
774 self
.spr
= SPR(decoder2
, initial_sprs
)
775 self
.msr
= SelectableInt(initial_msr
, 64) # underlying reg
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
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)
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)))
795 # "undefined", just set to variable-bit-width int (use exts "max")
796 #self.undefined = SelectableInt(0, 256) # TODO, not hard-code 256!
799 self
.namespace
.update(self
.spr
)
800 self
.namespace
.update({'GPR': self
.gpr
,
803 'memassign': self
.memassign
,
808 'undefined': undefined
,
809 'mode_is_64bit': True,
813 # update pc to requested start point
814 self
.set_pc(initial_pc
)
816 # field-selectable versions of Condition Register TODO check bitranges?
819 bits
= tuple(range(i
*4+32, (i
+1)*4+32)) # errr... maybe?
820 _cr
= FieldSelectableInt(self
.cr
, bits
)
822 self
.namespace
["CR%d" % i
] = _cr
824 self
.decoder
= decoder2
.dec
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
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
858 def memassign(self
, ea
, sz
, val
):
859 self
.mem
.memassign(ea
, sz
, val
)
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
865 # then "yield" fields only from op_fields rather than hard-coded
867 fields
= self
.decoder
.sigforms
[formname
]
868 for name
in op_fields
:
870 sig
= getattr(fields
, name
.upper())
872 sig
= getattr(fields
, name
)
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
880 self
.namespace
[name
] = SelectableInt(val
, sig
.width
)
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
886 def handle_carry_(self
, inputs
, outputs
, already_done
):
887 inv_a
= yield self
.dec2
.e
.do
.invert_in
889 inputs
[0] = ~inputs
[0]
891 imm_ok
= yield self
.dec2
.e
.do
.imm_data
.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):
903 print("gt input", x
, output
)
904 gt
= (gtu(x
, output
))
907 cy
= 1 if any(gts
) else 0
909 if not (1 & already_done
):
910 self
.spr
['XER'][XER_bits
['CA']] = cy
912 print("inputs", already_done
, inputs
)
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
920 b32
= (inputs
[1].value
& (1 << 32)) != 0
923 cy32
= res32 ^ a32 ^ b32
924 print("CA32 ADD", cy32
)
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)
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
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
942 inputs
[0] = ~inputs
[0]
944 imm_ok
= yield self
.dec2
.e
.do
.imm_data
.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:
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:
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
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
973 self
.spr
['XER'][XER_bits
['OV']] = ov
974 self
.spr
['XER'][XER_bits
['OV32']] = ov32
975 so
= self
.spr
['XER'][XER_bits
['SO']]
977 self
.spr
['XER'][XER_bits
['SO']] = so
979 def handle_comparison(self
, outputs
, cr_idx
=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
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
)
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
)
1003 def setup_one(self
):
1004 """set up one instruction
1007 pc
= self
.pc
.CIA
.value
1011 ins
= self
.imem
.ld(pc
, 4, False, True)
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
)
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
)
1024 # SVP64. first, check if the opcode is EXT001, and SVP64 id bits set
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
:
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
1050 def execute_one(self
):
1051 """execute one instruction
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
)
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
)
1063 # don't use this except in special circumstances
1064 if not self
.respect_pc
:
1067 print("execute one, CIA NIA", self
.pc
.CIA
.value
, self
.pc
.NIA
.value
)
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
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
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
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
]:
1099 if not asmop
.endswith("."): # don't add "." to "andis."
1102 if hasattr(self
.dec2
.e
.do
, "lk"):
1103 lk
= yield self
.dec2
.e
.do
.lk
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]
1112 spr_msb
= yield from self
.get_spr_msb()
1113 if int_op
== MicrOp
.OP_MFCR
.value
:
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
:
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]?
1131 def call(self
, name
):
1132 """call(opcode) - the primary execution point for instructions
1134 name
= name
.strip() # remove spaces if not already done so
1136 print("halted - not executing", name
)
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
)
1145 int_op
= yield self
.dec2
.dec
.op
.internal_op
1146 spr_msb
= yield from self
.get_spr_msb()
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
,
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
1160 print("is priv", instr_is_privileged
, hex(self
.msr
.value
),
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
)
1169 # check halted condition
1174 # check illegal instruction
1176 if name
not in ['mtcrf', 'mtocrf']:
1177 illegal
= name
!= asmop
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
))
1188 info
= self
.instrs
[name
]
1189 yield from self
.prep_namespace(info
.form
, info
.op_fields
)
1191 # preserve order of register names
1192 input_names
= create_args(list(info
.read_regs
) +
1193 list(info
.uninit_regs
))
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
)
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
)
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)
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'])
1215 # main input registers (RT, RA ...)
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
)
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
1228 # regnum += srcstep # TODO, elwidth overrides
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
)
1237 # "special" registers
1238 for special
in info
.special_regs
:
1239 if special
in special_sprs
:
1240 inputs
.append(self
.spr
[special
])
1242 inputs
.append(self
.namespace
[special
])
1244 # clear trap (trap) NIA
1245 self
.trap_nia
= None
1247 print("inputs", inputs
)
1248 results
= info
.func(self
, *inputs
)
1249 print("results", results
)
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
1256 print("after func", self
.namespace
['CIA'], self
.namespace
['NIA'])
1258 # detect if CA/CA32 already in outputs (sra*, basically)
1261 output_names
= create_args(info
.write_regs
)
1262 for name
in output_names
:
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
1274 yield from self
.handle_carry_(inputs
, results
, already_done
)
1276 # detect if overflow was in return result
1279 for name
, output
in zip(output_names
, results
):
1280 if name
== 'overflow':
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
1289 print("internal overflow", overflow
, ov_en
, ov_ok
)
1291 yield from self
.handle_overflow(inputs
, results
, overflow
)
1293 if hasattr(self
.dec2
.e
.do
, "rc"):
1294 rc_en
= yield self
.dec2
.e
.do
.rc
.rc
1298 regnum
, is_vec
= yield from get_pdecode_cr_out(self
.dec2
, "CR0")
1299 self
.handle_comparison(results
, regnum
)
1301 # any modified return results?
1303 for name
, output
in zip(output_names
, results
):
1304 if name
== 'overflow': # ignore, done already (above)
1306 if isinstance(output
, int):
1307 output
= SelectableInt(output
, 256)
1308 if name
in ['CA', 'CA32']:
1310 print("writing %s to XER" % name
, output
)
1311 self
.spr
['XER'][XER_bits
[name
]] = output
.value
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
1319 self
.namespace
[name
].eq(output
)
1321 print('msr written', hex(self
.msr
.value
))
1323 regnum
, is_vec
= yield from get_pdecode_idx_out(self
.dec2
,
1326 # temporary hack for not having 2nd output
1327 regnum
= yield getattr(self
.decoder
, name
)
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
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
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
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'])
1366 """Decorator factory.
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.
1374 "self.namespace['SI']" for example becomes accessible as just "SI" but
1375 *only* inside the function, when decorated.
1377 def variable_injector(func
):
1379 def decorator(*args
, **kwargs
):
1381 func_globals
= func
.__globals
__ # Python 2.6+
1382 except AttributeError:
1383 func_globals
= func
.func_globals
# Earlier versions.
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)
1396 # func_globals = saved_values # Undo changes.
1402 return variable_injector