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 collections
import namedtuple
17 from copy
import deepcopy
18 from functools
import wraps
22 from nmigen
.sim
import Settle
23 import openpower
.syscalls
24 from openpower
.consts
import (MSRb
, PIb
, # big-endian (PowerISA versions)
25 SVP64CROffs
, SVP64MODEb
)
26 from openpower
.decoder
.helpers
import (ISACallerHelper
, ISAFPHelpers
, exts
,
27 gtu
, undefined
, copy_assign_rhs
)
28 from openpower
.decoder
.isa
.mem
import Mem
, MemMMap
, MemException
29 from openpower
.decoder
.isa
.radixmmu
import RADIX
30 from openpower
.decoder
.isa
.svshape
import SVSHAPE
31 from openpower
.decoder
.isa
.svstate
import SVP64State
32 from openpower
.decoder
.orderedset
import OrderedSet
33 from openpower
.decoder
.power_enums
import (FPTRANS_INSNS
, CRInSel
, CROutSel
,
34 In1Sel
, In2Sel
, In3Sel
, LDSTMode
,
35 MicrOp
, OutSel
, SVMode
,
36 SVP64LDSTmode
, SVP64PredCR
,
37 SVP64PredInt
, SVP64PredMode
,
38 SVP64RMMode
, SVPType
, XER_bits
,
39 insns
, spr_byname
, spr_dict
,
41 from openpower
.insndb
.core
import SVP64Instruction
42 from openpower
.decoder
.power_svp64
import SVP64RM
, decode_extra
43 from openpower
.decoder
.selectable_int
import (FieldSelectableInt
,
44 SelectableInt
, selectconcat
,
45 EFFECTIVELY_UNLIMITED
)
46 from openpower
.consts
import DEFAULT_MSR
47 from openpower
.fpscr
import FPSCRState
48 from openpower
.xer
import XERState
49 from openpower
.util
import LogType
, log
51 LDST_UPDATE_INSNS
= ['ldu', 'lwzu', 'lbzu', 'lhzu', 'lhau', 'lfsu', 'lfdu',
52 'stwu', 'stbu', 'sthu', 'stfsu', 'stfdu', 'stdu',
56 instruction_info
= namedtuple('instruction_info',
57 'func read_regs uninit_regs write_regs ' +
58 'special_regs op_fields form asmregs')
68 # rrright. this is here basically because the compiler pywriter returns
69 # results in a specific priority order. to make sure regs match up they
70 # need partial sorting. sigh.
72 # TODO (lkcl): adjust other registers that should be in a particular order
73 # probably CA, CA32, and CR
101 "overflow": 7, # should definitely be last
105 fregs
= ['FRA', 'FRB', 'FRC', 'FRS', 'FRT']
108 def get_masked_reg(regs
, base
, offs
, ew_bits
):
109 # rrrright. start by breaking down into row/col, based on elwidth
110 gpr_offs
= offs
// (64 // ew_bits
)
111 gpr_col
= offs
% (64 // ew_bits
)
112 # compute the mask based on ew_bits
113 mask
= (1 << ew_bits
) - 1
114 # now select the 64-bit register, but get its value (easier)
115 val
= regs
[base
+ gpr_offs
]
116 # shift down so element we want is at LSB
117 val
>>= gpr_col
* ew_bits
118 # mask so we only return the LSB element
122 def set_masked_reg(regs
, base
, offs
, ew_bits
, value
):
123 # rrrright. start by breaking down into row/col, based on elwidth
124 gpr_offs
= offs
// (64//ew_bits
)
125 gpr_col
= offs
% (64//ew_bits
)
126 # compute the mask based on ew_bits
127 mask
= (1 << ew_bits
)-1
128 # now select the 64-bit register, but get its value (easier)
129 val
= regs
[base
+gpr_offs
]
130 # now mask out the bit we don't want
131 val
= val
& ~
(mask
<< (gpr_col
*ew_bits
))
132 # then wipe the bit we don't want from the value
134 # OR the new value in, shifted up
135 val |
= value
<< (gpr_col
*ew_bits
)
136 regs
[base
+gpr_offs
] = val
139 def create_args(reglist
, extra
=None):
140 retval
= list(OrderedSet(reglist
))
141 retval
.sort(key
=lambda reg
: REG_SORT_ORDER
.get(reg
, 0))
142 if extra
is not None:
143 return [extra
] + retval
147 def create_full_args(*, read_regs
, special_regs
, uninit_regs
, write_regs
,
150 *read_regs
, *uninit_regs
, *write_regs
, *special_regs
], extra
=extra
)
154 def __init__(self
, decoder
, isacaller
, svstate
, regfile
):
157 self
.isacaller
= isacaller
158 self
.svstate
= svstate
159 for i
in range(len(regfile
)):
160 self
[i
] = SelectableInt(regfile
[i
], 64)
162 def __call__(self
, ridx
, is_vec
=False, offs
=0, elwidth
=64):
163 if isinstance(ridx
, SelectableInt
):
166 return self
[ridx
+offs
]
167 # rrrright. start by breaking down into row/col, based on elwidth
168 gpr_offs
= offs
// (64//elwidth
)
169 gpr_col
= offs
% (64//elwidth
)
170 # now select the 64-bit register, but get its value (easier)
171 val
= self
[ridx
+gpr_offs
].value
172 # now shift down and mask out
173 val
= val
>> (gpr_col
*elwidth
) & ((1 << elwidth
)-1)
174 # finally, return a SelectableInt at the required elwidth
175 log("GPR call", ridx
, "isvec", is_vec
, "offs", offs
,
176 "elwid", elwidth
, "offs/col", gpr_offs
, gpr_col
, "val", hex(val
))
177 return SelectableInt(val
, elwidth
)
179 def set_form(self
, form
):
182 def write(self
, rnum
, value
, is_vec
=False, elwidth
=64):
184 if isinstance(rnum
, SelectableInt
):
186 if isinstance(value
, SelectableInt
):
189 if isinstance(rnum
, tuple):
190 rnum
, base
, offs
= rnum
193 # rrrright. start by breaking down into row/col, based on elwidth
194 gpr_offs
= offs
// (64//elwidth
)
195 gpr_col
= offs
% (64//elwidth
)
196 # compute the mask based on elwidth
197 mask
= (1 << elwidth
)-1
198 # now select the 64-bit register, but get its value (easier)
199 val
= self
[base
+gpr_offs
].value
200 # now mask out the bit we don't want
201 val
= val
& ~
(mask
<< (gpr_col
*elwidth
))
202 # then wipe the bit we don't want from the value
204 # OR the new value in, shifted up
205 val |
= value
<< (gpr_col
*elwidth
)
206 # finally put the damn value into the regfile
207 log("GPR write", base
, "isvec", is_vec
, "offs", offs
,
208 "elwid", elwidth
, "offs/col", gpr_offs
, gpr_col
, "val", hex(val
),
210 dict.__setitem
__(self
, base
+gpr_offs
, SelectableInt(val
, 64))
212 def __setitem__(self
, rnum
, value
):
213 # rnum = rnum.value # only SelectableInt allowed
214 log("GPR setitem", rnum
, value
)
215 if isinstance(rnum
, SelectableInt
):
217 dict.__setitem
__(self
, rnum
, value
)
219 def getz(self
, rnum
):
220 # rnum = rnum.value # only SelectableInt allowed
221 log("GPR getzero?", rnum
)
223 return SelectableInt(0, 64)
226 def _get_regnum(self
, attr
):
227 getform
= self
.sd
.sigforms
[self
.form
]
228 rnum
= getattr(getform
, attr
)
231 def ___getitem__(self
, attr
):
232 """ XXX currently not used
234 rnum
= self
._get
_regnum
(attr
)
235 log("GPR getitem", attr
, rnum
)
236 return self
.regfile
[rnum
]
238 def dump(self
, printout
=True):
240 for i
in range(len(self
)):
241 res
.append(self
[i
].value
)
243 for i
in range(0, len(res
), 8):
246 s
.append("%08x" % res
[i
+j
])
248 print("reg", "%2d" % i
, s
)
253 def __init__(self
, dec2
, initial_sprs
={}):
256 for key
, v
in initial_sprs
.items():
257 if isinstance(key
, SelectableInt
):
259 key
= special_sprs
.get(key
, key
)
260 if isinstance(key
, int):
263 info
= spr_byname
[key
]
264 if not isinstance(v
, SelectableInt
):
265 v
= SelectableInt(v
, info
.length
)
268 def __getitem__(self
, key
):
270 #log("dict", self.items())
271 # if key in special_sprs get the special spr, otherwise return key
272 if isinstance(key
, SelectableInt
):
274 if isinstance(key
, int):
275 key
= spr_dict
[key
].SPR
276 key
= special_sprs
.get(key
, key
)
277 if key
== 'HSRR0': # HACK!
279 if key
== 'HSRR1': # HACK!
282 res
= dict.__getitem
__(self
, key
)
284 if isinstance(key
, int):
287 info
= spr_byname
[key
]
288 self
[key
] = SelectableInt(0, info
.length
)
289 res
= dict.__getitem
__(self
, key
)
290 #log("spr returning", key, res)
293 def __setitem__(self
, key
, value
):
294 if isinstance(key
, SelectableInt
):
296 if isinstance(key
, int):
297 key
= spr_dict
[key
].SPR
299 key
= special_sprs
.get(key
, key
)
300 if key
== 'HSRR0': # HACK!
301 self
.__setitem
__('SRR0', value
)
302 if key
== 'HSRR1': # HACK!
303 self
.__setitem
__('SRR1', value
)
305 value
= XERState(value
)
306 log("setting spr", key
, value
)
307 dict.__setitem
__(self
, key
, value
)
309 def __call__(self
, ridx
):
312 def dump(self
, printout
=True):
314 keys
= list(self
.keys())
317 sprname
= spr_dict
.get(k
, None)
321 sprname
= sprname
.SPR
322 res
.append((sprname
, self
[k
].value
))
324 for sprname
, value
in res
:
325 print(" ", sprname
, hex(value
))
330 def __init__(self
, pc_init
=0):
331 self
.CIA
= SelectableInt(pc_init
, 64)
332 self
.NIA
= self
.CIA
+ SelectableInt(4, 64) # only true for v3.0B!
334 def update_nia(self
, is_svp64
):
335 increment
= 8 if is_svp64
else 4
336 self
.NIA
= self
.CIA
+ SelectableInt(increment
, 64)
338 def update(self
, namespace
, is_svp64
):
339 """updates the program counter (PC) by 4 if v3.0B mode or 8 if SVP64
341 self
.CIA
= namespace
['NIA'].narrow(64)
342 self
.update_nia(is_svp64
)
343 namespace
['CIA'] = self
.CIA
344 namespace
['NIA'] = self
.NIA
348 # See PowerISA Version 3.0 B Book 1
349 # Section 2.3.1 Condition Register pages 30 - 31
351 LT
= FL
= 0 # negative, less than, floating-point less than
352 GT
= FG
= 1 # positive, greater than, floating-point greater than
353 EQ
= FE
= 2 # equal, floating-point equal
354 SO
= FU
= 3 # summary overflow, floating-point unordered
356 def __init__(self
, init
=0):
357 # rev_cr = int('{:016b}'.format(initial_cr)[::-1], 2)
358 # self.cr = FieldSelectableInt(self._cr, list(range(32, 64)))
359 self
.cr
= SelectableInt(init
, 64) # underlying reg
360 # field-selectable versions of Condition Register TODO check bitranges?
363 bits
= tuple(range(i
*4+32, (i
+1)*4+32))
364 _cr
= FieldSelectableInt(self
.cr
, bits
)
368 # decode SVP64 predicate integer to reg number and invert
369 def get_predint(gpr
, mask
):
373 log("get_predint", mask
, SVP64PredInt
.ALWAYS
.value
)
374 if mask
== SVP64PredInt
.ALWAYS
.value
:
375 return 0xffff_ffff_ffff_ffff # 64 bits of 1
376 if mask
== SVP64PredInt
.R3_UNARY
.value
:
377 return 1 << (r3
.value
& 0b111111)
378 if mask
== SVP64PredInt
.R3
.value
:
380 if mask
== SVP64PredInt
.R3_N
.value
:
382 if mask
== SVP64PredInt
.R10
.value
:
384 if mask
== SVP64PredInt
.R10_N
.value
:
386 if mask
== SVP64PredInt
.R30
.value
:
388 if mask
== SVP64PredInt
.R30_N
.value
:
392 # decode SVP64 predicate CR to reg number and invert status
393 def _get_predcr(mask
):
394 if mask
== SVP64PredCR
.LT
.value
:
396 if mask
== SVP64PredCR
.GE
.value
:
398 if mask
== SVP64PredCR
.GT
.value
:
400 if mask
== SVP64PredCR
.LE
.value
:
402 if mask
== SVP64PredCR
.EQ
.value
:
404 if mask
== SVP64PredCR
.NE
.value
:
406 if mask
== SVP64PredCR
.SO
.value
:
408 if mask
== SVP64PredCR
.NS
.value
:
412 # read individual CR fields (0..VL-1), extract the required bit
413 # and construct the mask
414 def get_predcr(crl
, mask
, vl
):
415 idx
, noninv
= _get_predcr(mask
)
418 cr
= crl
[i
+SVP64CROffs
.CRPred
]
419 if cr
[idx
].value
== noninv
:
424 # TODO, really should just be using PowerDecoder2
425 def get_idx_map(dec2
, name
):
427 in1_sel
= yield op
.in1_sel
428 in2_sel
= yield op
.in2_sel
429 in3_sel
= yield op
.in3_sel
430 in1
= yield dec2
.e
.read_reg1
.data
431 # identify which regnames map to in1/2/3
432 if name
== 'RA' or name
== 'RA_OR_ZERO':
433 if (in1_sel
== In1Sel
.RA
.value
or
434 (in1_sel
== In1Sel
.RA_OR_ZERO
.value
and in1
!= 0)):
436 if in1_sel
== In1Sel
.RA_OR_ZERO
.value
:
439 if in2_sel
== In2Sel
.RB
.value
:
441 if in3_sel
== In3Sel
.RB
.value
:
443 # XXX TODO, RC doesn't exist yet!
445 if in3_sel
== In3Sel
.RC
.value
:
447 elif name
in ['EA', 'RS']:
448 if in1_sel
== In1Sel
.RS
.value
:
450 if in2_sel
== In2Sel
.RS
.value
:
452 if in3_sel
== In3Sel
.RS
.value
:
455 if in1_sel
== In1Sel
.FRA
.value
:
457 if in3_sel
== In3Sel
.FRA
.value
:
460 if in2_sel
== In2Sel
.FRB
.value
:
463 if in3_sel
== In3Sel
.FRC
.value
:
466 if in1_sel
== In1Sel
.FRS
.value
:
468 if in3_sel
== In3Sel
.FRS
.value
:
471 if in1_sel
== In1Sel
.FRT
.value
:
474 if in1_sel
== In1Sel
.RT
.value
:
479 # TODO, really should just be using PowerDecoder2
480 def get_idx_in(dec2
, name
, ewmode
=False):
481 idx
= yield from get_idx_map(dec2
, name
)
485 in1_sel
= yield op
.in1_sel
486 in2_sel
= yield op
.in2_sel
487 in3_sel
= yield op
.in3_sel
488 # get the IN1/2/3 from the decoder (includes SVP64 remap and isvec)
489 in1
= yield dec2
.e
.read_reg1
.data
490 in2
= yield dec2
.e
.read_reg2
.data
491 in3
= yield dec2
.e
.read_reg3
.data
493 in1_base
= yield dec2
.e
.read_reg1
.base
494 in2_base
= yield dec2
.e
.read_reg2
.base
495 in3_base
= yield dec2
.e
.read_reg3
.base
496 in1_offs
= yield dec2
.e
.read_reg1
.offs
497 in2_offs
= yield dec2
.e
.read_reg2
.offs
498 in3_offs
= yield dec2
.e
.read_reg3
.offs
499 in1
= (in1
, in1_base
, in1_offs
)
500 in2
= (in2
, in2_base
, in2_offs
)
501 in3
= (in3
, in3_base
, in3_offs
)
503 in1_isvec
= yield dec2
.in1_isvec
504 in2_isvec
= yield dec2
.in2_isvec
505 in3_isvec
= yield dec2
.in3_isvec
506 log("get_idx_in in1", name
, in1_sel
, In1Sel
.RA
.value
,
508 log("get_idx_in in2", name
, in2_sel
, In2Sel
.RB
.value
,
510 log("get_idx_in in3", name
, in3_sel
, In3Sel
.RS
.value
,
512 log("get_idx_in FRS in3", name
, in3_sel
, In3Sel
.FRS
.value
,
514 log("get_idx_in FRB in2", name
, in2_sel
, In2Sel
.FRB
.value
,
516 log("get_idx_in FRC in3", name
, in3_sel
, In3Sel
.FRC
.value
,
519 return in1
, in1_isvec
521 return in2
, in2_isvec
523 return in3
, in3_isvec
527 # TODO, really should just be using PowerDecoder2
528 def get_cr_in(dec2
, name
):
530 in_sel
= yield op
.cr_in
531 in_bitfield
= yield dec2
.dec_cr_in
.cr_bitfield
.data
532 sv_cr_in
= yield op
.sv_cr_in
533 spec
= yield dec2
.crin_svdec
.spec
534 sv_override
= yield dec2
.dec_cr_in
.sv_override
535 # get the IN1/2/3 from the decoder (includes SVP64 remap and isvec)
536 in1
= yield dec2
.e
.read_cr1
.data
537 cr_isvec
= yield dec2
.cr_in_isvec
538 log("get_cr_in", in_sel
, CROutSel
.CR0
.value
, in1
, cr_isvec
)
539 log(" sv_cr_in", sv_cr_in
)
540 log(" cr_bf", in_bitfield
)
542 log(" override", sv_override
)
543 # identify which regnames map to in / o2
545 if in_sel
== CRInSel
.BI
.value
:
547 log("get_cr_in not found", name
)
551 # TODO, really should just be using PowerDecoder2
552 def get_cr_out(dec2
, name
):
554 out_sel
= yield op
.cr_out
555 out_bitfield
= yield dec2
.dec_cr_out
.cr_bitfield
.data
556 sv_cr_out
= yield op
.sv_cr_out
557 spec
= yield dec2
.crout_svdec
.spec
558 sv_override
= yield dec2
.dec_cr_out
.sv_override
559 # get the IN1/2/3 from the decoder (includes SVP64 remap and isvec)
560 out
= yield dec2
.e
.write_cr
.data
561 o_isvec
= yield dec2
.cr_out_isvec
562 log("get_cr_out", out_sel
, CROutSel
.CR0
.value
, out
, o_isvec
)
563 log(" sv_cr_out", sv_cr_out
)
564 log(" cr_bf", out_bitfield
)
566 log(" override", sv_override
)
567 # identify which regnames map to out / o2
569 if out_sel
== CROutSel
.BF
.value
:
572 if out_sel
== CROutSel
.CR0
.value
:
574 if name
== 'CR1': # these are not actually calculated correctly
575 if out_sel
== CROutSel
.CR1
.value
:
577 # check RC1 set? if so return implicit vector, this is a REAL bad hack
578 RC1
= yield dec2
.rm_dec
.RC1
580 log("get_cr_out RC1 mode")
582 return 0, True # XXX TODO: offset CR0 from SVSTATE SPR
584 return 1, True # XXX TODO: offset CR1 from SVSTATE SPR
586 log("get_cr_out not found", name
)
590 # TODO, really should just be using PowerDecoder2
591 def get_out_map(dec2
, name
):
593 out_sel
= yield op
.out_sel
594 # get the IN1/2/3 from the decoder (includes SVP64 remap and isvec)
595 out
= yield dec2
.e
.write_reg
.data
596 # identify which regnames map to out / o2
598 if out_sel
== OutSel
.RA
.value
:
601 if out_sel
== OutSel
.RT
.value
:
603 if out_sel
== OutSel
.RT_OR_ZERO
.value
and out
!= 0:
605 elif name
== 'RT_OR_ZERO':
606 if out_sel
== OutSel
.RT_OR_ZERO
.value
:
609 if out_sel
== OutSel
.FRA
.value
:
612 if out_sel
== OutSel
.FRS
.value
:
615 if out_sel
== OutSel
.FRT
.value
:
620 # TODO, really should just be using PowerDecoder2
621 def get_idx_out(dec2
, name
, ewmode
=False):
623 out_sel
= yield op
.out_sel
624 # get the IN1/2/3 from the decoder (includes SVP64 remap and isvec)
625 out
= yield dec2
.e
.write_reg
.data
626 o_isvec
= yield dec2
.o_isvec
628 offs
= yield dec2
.e
.write_reg
.offs
629 base
= yield dec2
.e
.write_reg
.base
630 out
= (out
, base
, offs
)
631 # identify which regnames map to out / o2
632 ismap
= yield from get_out_map(dec2
, name
)
634 log("get_idx_out", name
, out_sel
, out
, o_isvec
)
636 log("get_idx_out not found", name
, out_sel
, out
, o_isvec
)
640 # TODO, really should just be using PowerDecoder2
641 def get_out2_map(dec2
, name
):
642 # check first if register is activated for write
644 out_sel
= yield op
.out_sel
645 out
= yield dec2
.e
.write_ea
.data
646 out_ok
= yield dec2
.e
.write_ea
.ok
650 if name
in ['EA', 'RA']:
651 if hasattr(op
, "upd"):
652 # update mode LD/ST uses read-reg A also as an output
654 log("get_idx_out2", upd
, LDSTMode
.update
.value
,
655 out_sel
, OutSel
.RA
.value
,
657 if upd
== LDSTMode
.update
.value
:
660 fft_en
= yield dec2
.implicit_rs
662 log("get_idx_out2", out_sel
, OutSel
.RS
.value
,
666 fft_en
= yield dec2
.implicit_rs
668 log("get_idx_out2", out_sel
, OutSel
.FRS
.value
,
674 # TODO, really should just be using PowerDecoder2
675 def get_idx_out2(dec2
, name
, ewmode
=False):
676 # check first if register is activated for write
678 out_sel
= yield op
.out_sel
679 out
= yield dec2
.e
.write_ea
.data
681 offs
= yield dec2
.e
.write_ea
.offs
682 base
= yield dec2
.e
.write_ea
.base
683 out
= (out
, base
, offs
)
684 o_isvec
= yield dec2
.o2_isvec
685 ismap
= yield from get_out2_map(dec2
, name
)
687 log("get_idx_out2", name
, out_sel
, out
, o_isvec
)
693 """deals with svstate looping.
696 def __init__(self
, svstate
):
697 self
.svstate
= svstate
700 def new_iterators(self
):
701 self
.src_it
= self
.src_iterator()
702 self
.dst_it
= self
.dst_iterator()
706 self
.new_ssubstep
= 0
707 self
.new_dsubstep
= 0
708 self
.pred_dst_zero
= 0
709 self
.pred_src_zero
= 0
711 def src_iterator(self
):
712 """source-stepping iterator
714 pack
= self
.svstate
.pack
718 # pack advances subvl in *outer* loop
719 while True: # outer subvl loop
720 while True: # inner vl loop
723 srcmask
= self
.srcmask
724 srcstep
= self
.svstate
.srcstep
725 pred_src_zero
= ((1 << srcstep
) & srcmask
) != 0
726 if self
.pred_sz
or pred_src_zero
:
727 self
.pred_src_zero
= not pred_src_zero
728 log(" advance src", srcstep
, vl
,
729 self
.svstate
.ssubstep
, subvl
)
730 # yield actual substep/srcstep
731 yield (self
.svstate
.ssubstep
, srcstep
)
732 # the way yield works these could have been modified.
735 srcstep
= self
.svstate
.srcstep
736 log(" advance src check", srcstep
, vl
,
737 self
.svstate
.ssubstep
, subvl
, srcstep
== vl
-1,
738 self
.svstate
.ssubstep
== subvl
)
739 if srcstep
== vl
-1: # end-point
740 self
.svstate
.srcstep
= SelectableInt(0, 7) # reset
741 if self
.svstate
.ssubstep
== subvl
: # end-point
742 log(" advance pack stop")
744 break # exit inner loop
745 self
.svstate
.srcstep
+= SelectableInt(1, 7) # advance ss
747 if self
.svstate
.ssubstep
== subvl
: # end-point
748 self
.svstate
.ssubstep
= SelectableInt(0, 2) # reset
749 log(" advance pack stop")
751 self
.svstate
.ssubstep
+= SelectableInt(1, 2)
754 # these cannot be done as for-loops because SVSTATE may change
755 # (srcstep/substep may be modified, interrupted, subvl/vl change)
756 # but they *can* be done as while-loops as long as every SVSTATE
757 # "thing" is re-read every single time a yield gives indices
758 while True: # outer vl loop
759 while True: # inner subvl loop
762 srcmask
= self
.srcmask
763 srcstep
= self
.svstate
.srcstep
764 pred_src_zero
= ((1 << srcstep
) & srcmask
) != 0
765 if self
.pred_sz
or pred_src_zero
:
766 self
.pred_src_zero
= not pred_src_zero
767 log(" advance src", srcstep
, vl
,
768 self
.svstate
.ssubstep
, subvl
)
769 # yield actual substep/srcstep
770 yield (self
.svstate
.ssubstep
, srcstep
)
771 if self
.svstate
.ssubstep
== subvl
: # end-point
772 self
.svstate
.ssubstep
= SelectableInt(0, 2) # reset
773 break # exit inner loop
774 self
.svstate
.ssubstep
+= SelectableInt(1, 2)
776 if srcstep
== vl
-1: # end-point
777 self
.svstate
.srcstep
= SelectableInt(0, 7) # reset
780 self
.svstate
.srcstep
+= SelectableInt(1, 7) # advance srcstep
782 def dst_iterator(self
):
783 """dest-stepping iterator
785 unpack
= self
.svstate
.unpack
789 # pack advances subvl in *outer* loop
790 while True: # outer subvl loop
791 while True: # inner vl loop
794 dstmask
= self
.dstmask
795 dststep
= self
.svstate
.dststep
796 pred_dst_zero
= ((1 << dststep
) & dstmask
) != 0
797 if self
.pred_dz
or pred_dst_zero
:
798 self
.pred_dst_zero
= not pred_dst_zero
799 log(" advance dst", dststep
, vl
,
800 self
.svstate
.dsubstep
, subvl
)
801 # yield actual substep/dststep
802 yield (self
.svstate
.dsubstep
, dststep
)
803 # the way yield works these could have been modified.
805 dststep
= self
.svstate
.dststep
806 log(" advance dst check", dststep
, vl
,
807 self
.svstate
.ssubstep
, subvl
)
808 if dststep
== vl
-1: # end-point
809 self
.svstate
.dststep
= SelectableInt(0, 7) # reset
810 if self
.svstate
.dsubstep
== subvl
: # end-point
811 log(" advance unpack stop")
814 self
.svstate
.dststep
+= SelectableInt(1, 7) # advance ds
816 if self
.svstate
.dsubstep
== subvl
: # end-point
817 self
.svstate
.dsubstep
= SelectableInt(0, 2) # reset
818 log(" advance unpack stop")
820 self
.svstate
.dsubstep
+= SelectableInt(1, 2)
822 # these cannot be done as for-loops because SVSTATE may change
823 # (dststep/substep may be modified, interrupted, subvl/vl change)
824 # but they *can* be done as while-loops as long as every SVSTATE
825 # "thing" is re-read every single time a yield gives indices
826 while True: # outer vl loop
827 while True: # inner subvl loop
829 dstmask
= self
.dstmask
830 dststep
= self
.svstate
.dststep
831 pred_dst_zero
= ((1 << dststep
) & dstmask
) != 0
832 if self
.pred_dz
or pred_dst_zero
:
833 self
.pred_dst_zero
= not pred_dst_zero
834 log(" advance dst", dststep
, self
.svstate
.vl
,
835 self
.svstate
.dsubstep
, subvl
)
836 # yield actual substep/dststep
837 yield (self
.svstate
.dsubstep
, dststep
)
838 if self
.svstate
.dsubstep
== subvl
: # end-point
839 self
.svstate
.dsubstep
= SelectableInt(0, 2) # reset
841 self
.svstate
.dsubstep
+= SelectableInt(1, 2)
844 if dststep
== vl
-1: # end-point
845 self
.svstate
.dststep
= SelectableInt(0, 7) # reset
847 self
.svstate
.dststep
+= SelectableInt(1, 7) # advance dststep
849 def src_iterate(self
):
850 """source-stepping iterator
854 pack
= self
.svstate
.pack
855 unpack
= self
.svstate
.unpack
856 ssubstep
= self
.svstate
.ssubstep
857 end_ssub
= ssubstep
== subvl
858 end_src
= self
.svstate
.srcstep
== vl
-1
859 log(" pack/unpack/subvl", pack
, unpack
, subvl
,
863 srcstep
= self
.svstate
.srcstep
864 srcmask
= self
.srcmask
866 # pack advances subvl in *outer* loop
868 assert srcstep
<= vl
-1
869 end_src
= srcstep
== vl
-1
874 self
.svstate
.ssubstep
+= SelectableInt(1, 2)
878 srcstep
+= 1 # advance srcstep
879 if not self
.srcstep_skip
:
881 if ((1 << srcstep
) & srcmask
) != 0:
884 log(" sskip", bin(srcmask
), bin(1 << srcstep
))
886 # advance subvl in *inner* loop
889 assert srcstep
<= vl
-1
890 end_src
= srcstep
== vl
-1
891 if end_src
: # end-point
897 if not self
.srcstep_skip
:
899 if ((1 << srcstep
) & srcmask
) != 0:
902 log(" sskip", bin(srcmask
), bin(1 << srcstep
))
903 self
.svstate
.ssubstep
= SelectableInt(0, 2) # reset
906 self
.svstate
.ssubstep
+= SelectableInt(1, 2)
908 self
.svstate
.srcstep
= SelectableInt(srcstep
, 7)
909 log(" advance src", self
.svstate
.srcstep
, self
.svstate
.ssubstep
,
912 def dst_iterate(self
):
913 """dest step iterator
917 pack
= self
.svstate
.pack
918 unpack
= self
.svstate
.unpack
919 dsubstep
= self
.svstate
.dsubstep
920 end_dsub
= dsubstep
== subvl
921 dststep
= self
.svstate
.dststep
922 end_dst
= dststep
== vl
-1
923 dstmask
= self
.dstmask
924 log(" pack/unpack/subvl", pack
, unpack
, subvl
,
929 # unpack advances subvl in *outer* loop
931 assert dststep
<= vl
-1
932 end_dst
= dststep
== vl
-1
937 self
.svstate
.dsubstep
+= SelectableInt(1, 2)
941 dststep
+= 1 # advance dststep
942 if not self
.dststep_skip
:
944 if ((1 << dststep
) & dstmask
) != 0:
947 log(" dskip", bin(dstmask
), bin(1 << dststep
))
949 # advance subvl in *inner* loop
952 assert dststep
<= vl
-1
953 end_dst
= dststep
== vl
-1
954 if end_dst
: # end-point
960 if not self
.dststep_skip
:
962 if ((1 << dststep
) & dstmask
) != 0:
965 log(" dskip", bin(dstmask
), bin(1 << dststep
))
966 self
.svstate
.dsubstep
= SelectableInt(0, 2) # reset
969 self
.svstate
.dsubstep
+= SelectableInt(1, 2)
971 self
.svstate
.dststep
= SelectableInt(dststep
, 7)
972 log(" advance dst", self
.svstate
.dststep
, self
.svstate
.dsubstep
,
975 def at_loopend(self
):
976 """tells if this is the last possible element. uses the cached values
977 for src/dst-step and sub-steps
981 srcstep
, dststep
= self
.new_srcstep
, self
.new_dststep
982 ssubstep
, dsubstep
= self
.new_ssubstep
, self
.new_dsubstep
983 end_ssub
= ssubstep
== subvl
984 end_dsub
= dsubstep
== subvl
985 if srcstep
== vl
-1 and end_ssub
:
987 if dststep
== vl
-1 and end_dsub
:
991 def advance_svstate_steps(self
):
992 """ advance sub/steps. note that Pack/Unpack *INVERTS* the order.
993 TODO when Pack/Unpack is set, substep becomes the *outer* loop
995 self
.subvl
= yield self
.dec2
.rm_dec
.rm_in
.subvl
996 if self
.loopend
: # huhn??
1001 def read_src_mask(self
):
1002 """read/update pred_sz and src mask
1004 # get SVSTATE VL (oh and print out some debug stuff)
1005 vl
= self
.svstate
.vl
1006 srcstep
= self
.svstate
.srcstep
1007 ssubstep
= self
.svstate
.ssubstep
1009 # get predicate mask (all 64 bits)
1010 srcmask
= 0xffff_ffff_ffff_ffff
1012 pmode
= yield self
.dec2
.rm_dec
.predmode
1013 sv_ptype
= yield self
.dec2
.dec
.op
.SV_Ptype
1014 srcpred
= yield self
.dec2
.rm_dec
.srcpred
1015 dstpred
= yield self
.dec2
.rm_dec
.dstpred
1016 pred_sz
= yield self
.dec2
.rm_dec
.pred_sz
1017 if pmode
== SVP64PredMode
.INT
.value
:
1018 srcmask
= dstmask
= get_predint(self
.gpr
, dstpred
)
1019 if sv_ptype
== SVPType
.P2
.value
:
1020 srcmask
= get_predint(self
.gpr
, srcpred
)
1021 elif pmode
== SVP64PredMode
.CR
.value
:
1022 srcmask
= dstmask
= get_predcr(self
.crl
, dstpred
, vl
)
1023 if sv_ptype
== SVPType
.P2
.value
:
1024 srcmask
= get_predcr(self
.crl
, srcpred
, vl
)
1025 # work out if the ssubsteps are completed
1026 ssubstart
= ssubstep
== 0
1027 log(" pmode", pmode
)
1028 log(" ptype", sv_ptype
)
1029 log(" srcpred", bin(srcpred
))
1030 log(" srcmask", bin(srcmask
))
1031 log(" pred_sz", bin(pred_sz
))
1032 log(" ssubstart", ssubstart
)
1034 # store all that above
1035 self
.srcstep_skip
= False
1036 self
.srcmask
= srcmask
1037 self
.pred_sz
= pred_sz
1038 self
.new_ssubstep
= ssubstep
1039 log(" new ssubstep", ssubstep
)
1040 # until the predicate mask has a "1" bit... or we run out of VL
1041 # let srcstep==VL be the indicator to move to next instruction
1043 self
.srcstep_skip
= True
1045 def read_dst_mask(self
):
1046 """same as read_src_mask - check and record everything needed
1048 # get SVSTATE VL (oh and print out some debug stuff)
1049 # yield Delay(1e-10) # make changes visible
1050 vl
= self
.svstate
.vl
1051 dststep
= self
.svstate
.dststep
1052 dsubstep
= self
.svstate
.dsubstep
1054 # get predicate mask (all 64 bits)
1055 dstmask
= 0xffff_ffff_ffff_ffff
1057 pmode
= yield self
.dec2
.rm_dec
.predmode
1058 reverse_gear
= yield self
.dec2
.rm_dec
.reverse_gear
1059 sv_ptype
= yield self
.dec2
.dec
.op
.SV_Ptype
1060 dstpred
= yield self
.dec2
.rm_dec
.dstpred
1061 pred_dz
= yield self
.dec2
.rm_dec
.pred_dz
1062 if pmode
== SVP64PredMode
.INT
.value
:
1063 dstmask
= get_predint(self
.gpr
, dstpred
)
1064 elif pmode
== SVP64PredMode
.CR
.value
:
1065 dstmask
= get_predcr(self
.crl
, dstpred
, vl
)
1066 # work out if the ssubsteps are completed
1067 dsubstart
= dsubstep
== 0
1068 log(" pmode", pmode
)
1069 log(" ptype", sv_ptype
)
1070 log(" dstpred", bin(dstpred
))
1071 log(" dstmask", bin(dstmask
))
1072 log(" pred_dz", bin(pred_dz
))
1073 log(" dsubstart", dsubstart
)
1075 self
.dststep_skip
= False
1076 self
.dstmask
= dstmask
1077 self
.pred_dz
= pred_dz
1078 self
.new_dsubstep
= dsubstep
1079 log(" new dsubstep", dsubstep
)
1081 self
.dststep_skip
= True
1083 def svstate_pre_inc(self
):
1084 """check if srcstep/dststep need to skip over masked-out predicate bits
1085 note that this is not supposed to do anything to substep,
1086 it is purely for skipping masked-out bits
1089 self
.subvl
= yield self
.dec2
.rm_dec
.rm_in
.subvl
1090 yield from self
.read_src_mask()
1091 yield from self
.read_dst_mask()
1098 srcstep
= self
.svstate
.srcstep
1099 srcmask
= self
.srcmask
1100 pred_src_zero
= self
.pred_sz
1101 vl
= self
.svstate
.vl
1102 # srcstep-skipping opportunity identified
1103 if self
.srcstep_skip
:
1104 # cannot do this with sv.bc - XXX TODO
1107 while (((1 << srcstep
) & srcmask
) == 0) and (srcstep
!= vl
):
1108 log(" sskip", bin(1 << srcstep
))
1111 # now work out if the relevant mask bits require zeroing
1113 pred_src_zero
= ((1 << srcstep
) & srcmask
) == 0
1115 # store new srcstep / dststep
1116 self
.new_srcstep
= srcstep
1117 self
.pred_src_zero
= pred_src_zero
1118 log(" new srcstep", srcstep
)
1121 # dststep-skipping opportunity identified
1122 dststep
= self
.svstate
.dststep
1123 dstmask
= self
.dstmask
1124 pred_dst_zero
= self
.pred_dz
1125 vl
= self
.svstate
.vl
1126 if self
.dststep_skip
:
1127 # cannot do this with sv.bc - XXX TODO
1130 while (((1 << dststep
) & dstmask
) == 0) and (dststep
!= vl
):
1131 log(" dskip", bin(1 << dststep
))
1134 # now work out if the relevant mask bits require zeroing
1136 pred_dst_zero
= ((1 << dststep
) & dstmask
) == 0
1138 # store new srcstep / dststep
1139 self
.new_dststep
= dststep
1140 self
.pred_dst_zero
= pred_dst_zero
1141 log(" new dststep", dststep
)
1144 class SyscallEmulator(openpower
.syscalls
.Dispatcher
):
1145 def __init__(self
, isacaller
):
1146 self
.__isacaller
= isacaller
1148 host
= os
.uname().machine
1149 bits
= (64 if (sys
.maxsize
> (2**32)) else 32)
1150 host
= openpower
.syscalls
.architecture(arch
=host
, bits
=bits
)
1152 return super().__init
__(guest
="ppc64", host
=host
)
1154 def __call__(self
, identifier
, *arguments
):
1155 (identifier
, *arguments
) = map(int, (identifier
, *arguments
))
1156 return super().__call
__(identifier
, *arguments
)
1159 class ISACaller(ISACallerHelper
, ISAFPHelpers
, StepLoop
):
1160 # decoder2 - an instance of power_decoder2
1161 # regfile - a list of initial values for the registers
1162 # initial_{etc} - initial values for SPRs, Condition Register, Mem, MSR
1163 # respect_pc - tracks the program counter. requires initial_insns
1164 def __init__(self
, decoder2
, regfile
, initial_sprs
=None, initial_cr
=0,
1165 initial_mem
=None, initial_msr
=0,
1178 use_syscall_emu
=False):
1180 self
.syscall
= SyscallEmulator(isacaller
=self
)
1181 if not use_mmap_mem
:
1182 log("forcing use_mmap_mem due to use_syscall_emu active")
1187 # trace log file for model output. if None do nothing
1188 self
.insnlog
= insnlog
1189 self
.insnlog_is_file
= hasattr(insnlog
, "write")
1190 if not self
.insnlog_is_file
and self
.insnlog
:
1191 self
.insnlog
= open(self
.insnlog
, "w")
1193 self
.bigendian
= bigendian
1195 self
.is_svp64_mode
= False
1196 self
.respect_pc
= respect_pc
1197 if initial_sprs
is None:
1199 if initial_mem
is None:
1201 if fpregfile
is None:
1202 fpregfile
= [0] * 32
1203 if initial_insns
is None:
1205 assert self
.respect_pc
== False, "instructions required to honor pc"
1206 if initial_msr
is None:
1207 initial_msr
= DEFAULT_MSR
1209 log("ISACaller insns", respect_pc
, initial_insns
, disassembly
)
1210 log("ISACaller initial_msr", initial_msr
)
1212 # "fake program counter" mode (for unit testing)
1216 if isinstance(initial_mem
, tuple):
1217 self
.fake_pc
= initial_mem
[0]
1218 disasm_start
= self
.fake_pc
1220 disasm_start
= initial_pc
1222 # disassembly: we need this for now (not given from the decoder)
1223 self
.disassembly
= {}
1225 for i
, code
in enumerate(disassembly
):
1226 self
.disassembly
[i
*4 + disasm_start
] = code
1228 # set up registers, instruction memory, data memory, PC, SPRs, MSR, CR
1229 self
.svp64rm
= SVP64RM()
1230 if initial_svstate
is None:
1232 if isinstance(initial_svstate
, int):
1233 initial_svstate
= SVP64State(initial_svstate
)
1234 # SVSTATE, MSR and PC
1235 StepLoop
.__init
__(self
, initial_svstate
)
1236 self
.msr
= SelectableInt(initial_msr
, 64) # underlying reg
1238 # GPR FPR SPR registers
1239 initial_sprs
= deepcopy(initial_sprs
) # so as not to get modified
1240 self
.gpr
= GPR(decoder2
, self
, self
.svstate
, regfile
)
1241 self
.fpr
= GPR(decoder2
, self
, self
.svstate
, fpregfile
)
1242 self
.spr
= SPR(decoder2
, initial_sprs
) # initialise SPRs before MMU
1244 # set up 4 dummy SVSHAPEs if they aren't already set up
1246 sname
= 'SVSHAPE%d' % i
1247 val
= self
.spr
.get(sname
, 0)
1248 # make sure it's an SVSHAPE
1249 self
.spr
[sname
] = SVSHAPE(val
, self
.gpr
)
1250 self
.last_op_svshape
= False
1254 self
.mem
= MemMMap(row_bytes
=8,
1255 initial_mem
=initial_mem
,
1257 self
.imem
= self
.mem
1258 self
.mem
.initialize(row_bytes
=4, initial_mem
=initial_insns
)
1259 self
.mem
.log_fancy(kind
=LogType
.InstrInOuts
)
1261 self
.mem
= Mem(row_bytes
=8, initial_mem
=initial_mem
,
1263 self
.mem
.log_fancy(kind
=LogType
.InstrInOuts
)
1264 self
.imem
= Mem(row_bytes
=4, initial_mem
=initial_insns
)
1265 # MMU mode, redirect underlying Mem through RADIX
1267 self
.mem
= RADIX(self
.mem
, self
)
1269 self
.imem
= RADIX(self
.imem
, self
)
1271 # TODO, needed here:
1272 # FPR (same as GPR except for FP nums)
1273 # 4.2.2 p124 FPSCR (definitely "separate" - not in SPR)
1274 # note that mffs, mcrfs, mtfsf "manage" this FPSCR
1275 self
.fpscr
= FPSCRState(initial_fpscr
)
1277 # 2.3.1 CR (and sub-fields CR0..CR6 - CR0 SO comes from XER.SO)
1278 # note that mfocrf, mfcr, mtcr, mtocrf, mcrxrx "manage" CRs
1280 # 2.3.2 LR (actually SPR #8) -- Done
1281 # 2.3.3 CTR (actually SPR #9) -- Done
1282 # 2.3.4 TAR (actually SPR #815)
1283 # 3.2.2 p45 XER (actually SPR #1) -- Done
1284 # 3.2.3 p46 p232 VRSAVE (actually SPR #256)
1286 # create CR then allow portions of it to be "selectable" (below)
1287 self
.cr_fields
= CRFields(initial_cr
)
1288 self
.cr
= self
.cr_fields
.cr
1289 self
.cr_backup
= 0 # sigh, dreadful hack: for fail-first (VLi)
1291 # "undefined", just set to variable-bit-width int (use exts "max")
1292 # self.undefined = SelectableInt(0, EFFECTIVELY_UNLIMITED)
1295 self
.namespace
.update(self
.spr
)
1296 self
.namespace
.update({'GPR': self
.gpr
,
1300 'memassign': self
.memassign
,
1303 'SVSTATE': self
.svstate
,
1304 'SVSHAPE0': self
.spr
['SVSHAPE0'],
1305 'SVSHAPE1': self
.spr
['SVSHAPE1'],
1306 'SVSHAPE2': self
.spr
['SVSHAPE2'],
1307 'SVSHAPE3': self
.spr
['SVSHAPE3'],
1310 'FPSCR': self
.fpscr
,
1311 'undefined': undefined
,
1312 'mode_is_64bit': True,
1313 'SO': XER_bits
['SO'],
1314 'XLEN': 64 # elwidth overrides
1317 for name
in BFP_FLAG_NAMES
:
1318 setattr(self
, name
, 0)
1320 # update pc to requested start point
1321 self
.set_pc(initial_pc
)
1323 # field-selectable versions of Condition Register
1324 self
.crl
= self
.cr_fields
.crl
1326 self
.namespace
["CR%d" % i
] = self
.crl
[i
]
1328 self
.decoder
= decoder2
.dec
1329 self
.dec2
= decoder2
1331 super().__init
__(XLEN
=self
.namespace
["XLEN"], FPSCR
=self
.fpscr
)
1333 def trace(self
, out
):
1334 if self
.insnlog
is None:
1336 self
.insnlog
.write(out
)
1340 return self
.namespace
["XLEN"]
1346 def call_trap(self
, trap_addr
, trap_bit
):
1347 """calls TRAP and sets up NIA to the new execution location.
1348 next instruction will begin at trap_addr.
1350 self
.TRAP(trap_addr
, trap_bit
)
1351 self
.namespace
['NIA'] = self
.trap_nia
1352 self
.pc
.update(self
.namespace
, self
.is_svp64_mode
)
1354 def TRAP(self
, trap_addr
=0x700, trap_bit
=PIb
.TRAP
):
1355 """TRAP> saves PC, MSR (and TODO SVSTATE), and updates MSR
1357 TRAP function is callable from inside the pseudocode itself,
1358 hence the default arguments. when calling from inside ISACaller
1359 it is best to use call_trap()
1361 trap_addr: int | SelectableInt
1362 the address to go to (before any modifications from `KAIVB`)
1363 trap_bit: int | None
1364 the bit in `SRR1` to set, `None` means don't set any bits.
1366 if isinstance(trap_addr
, SelectableInt
):
1367 trap_addr
= trap_addr
.value
1368 # https://bugs.libre-soc.org/show_bug.cgi?id=859
1369 kaivb
= self
.spr
['KAIVB'].value
1370 msr
= self
.namespace
['MSR'].value
1371 log("TRAP:", hex(trap_addr
), hex(msr
), "kaivb", hex(kaivb
))
1372 # store CIA(+4?) in SRR0, set NIA to 0x700
1373 # store MSR in SRR1, set MSR to um errr something, have to check spec
1374 # store SVSTATE (if enabled) in SVSRR0
1375 self
.spr
['SRR0'].value
= self
.pc
.CIA
.value
1376 self
.spr
['SRR1'].value
= msr
1377 if self
.is_svp64_mode
:
1378 self
.spr
['SVSRR0'] = self
.namespace
['SVSTATE'].value
1379 self
.trap_nia
= SelectableInt(trap_addr |
(kaivb
& ~
0x1fff), 64)
1380 if trap_bit
is not None:
1381 self
.spr
['SRR1'][trap_bit
] = 1 # change *copy* of MSR in SRR1
1383 # set exception bits. TODO: this should, based on the address
1384 # in figure 66 p1065 V3.0B and the table figure 65 p1063 set these
1385 # bits appropriately. however it turns out that *for now* in all
1386 # cases (all trap_addrs) the exact same thing is needed.
1387 self
.msr
[MSRb
.IR
] = 0
1388 self
.msr
[MSRb
.DR
] = 0
1389 self
.msr
[MSRb
.FE0
] = 0
1390 self
.msr
[MSRb
.FE1
] = 0
1391 self
.msr
[MSRb
.EE
] = 0
1392 self
.msr
[MSRb
.RI
] = 0
1393 self
.msr
[MSRb
.SF
] = 1
1394 self
.msr
[MSRb
.TM
] = 0
1395 self
.msr
[MSRb
.VEC
] = 0
1396 self
.msr
[MSRb
.VSX
] = 0
1397 self
.msr
[MSRb
.PR
] = 0
1398 self
.msr
[MSRb
.FP
] = 0
1399 self
.msr
[MSRb
.PMM
] = 0
1400 self
.msr
[MSRb
.TEs
] = 0
1401 self
.msr
[MSRb
.TEe
] = 0
1402 self
.msr
[MSRb
.UND
] = 0
1403 self
.msr
[MSRb
.LE
] = 1
1405 def memassign(self
, ea
, sz
, val
):
1406 self
.mem
.memassign(ea
, sz
, val
)
1408 def prep_namespace(self
, insn_name
, formname
, op_fields
, xlen
):
1409 # TODO: get field names from form in decoder*1* (not decoder2)
1410 # decoder2 is hand-created, and decoder1.sigform is auto-generated
1412 # then "yield" fields only from op_fields rather than hard-coded
1414 fields
= self
.decoder
.sigforms
[formname
]
1415 log("prep_namespace", formname
, op_fields
, insn_name
)
1416 for name
in op_fields
:
1417 # CR immediates. deal with separately. needs modifying
1419 if self
.is_svp64_mode
and name
in ['BI']: # TODO, more CRs
1420 # BI is a 5-bit, must reconstruct the value
1421 regnum
, is_vec
= yield from get_cr_in(self
.dec2
, name
)
1422 sig
= getattr(fields
, name
)
1424 # low 2 LSBs (CR field selector) remain same, CR num extended
1425 assert regnum
<= 7, "sigh, TODO, 128 CR fields"
1426 val
= (val
& 0b11) |
(regnum
<< 2)
1427 elif self
.is_svp64_mode
and name
in ['BF']: # TODO, more CRs
1428 regnum
, is_vec
= yield from get_cr_out(self
.dec2
, "BF")
1429 log('hack %s' % name
, regnum
, is_vec
)
1432 sig
= getattr(fields
, name
)
1434 # these are all opcode fields involved in index-selection of CR,
1435 # and need to do "standard" arithmetic. CR[BA+32] for example
1436 # would, if using SelectableInt, only be 5-bit.
1437 if name
in ['BF', 'BFA', 'BC', 'BA', 'BB', 'BT', 'BI']:
1438 self
.namespace
[name
] = val
1440 self
.namespace
[name
] = SelectableInt(val
, sig
.width
)
1442 self
.namespace
['XER'] = self
.spr
['XER']
1443 self
.namespace
['CA'] = self
.spr
['XER'][XER_bits
['CA']].value
1444 self
.namespace
['CA32'] = self
.spr
['XER'][XER_bits
['CA32']].value
1445 self
.namespace
['OV'] = self
.spr
['XER'][XER_bits
['OV']].value
1446 self
.namespace
['OV32'] = self
.spr
['XER'][XER_bits
['OV32']].value
1447 self
.namespace
['XLEN'] = xlen
1449 # add some SVSTATE convenience variables
1450 vl
= self
.svstate
.vl
1451 srcstep
= self
.svstate
.srcstep
1452 self
.namespace
['VL'] = vl
1453 self
.namespace
['srcstep'] = srcstep
1455 # take a copy of the CR field value: if non-VLi fail-first fails
1456 # this is because the pseudocode writes *directly* to CR. sigh
1457 self
.cr_backup
= self
.cr
.value
1459 # sv.bc* need some extra fields
1460 if not self
.is_svp64_mode
or not insn_name
.startswith("sv.bc"):
1463 # blegh grab bits manually
1464 mode
= yield self
.dec2
.rm_dec
.rm_in
.mode
1465 # convert to SelectableInt before test
1466 mode
= SelectableInt(mode
, 5)
1467 bc_vlset
= mode
[SVP64MODEb
.BC_VLSET
] != 0
1468 bc_vli
= mode
[SVP64MODEb
.BC_VLI
] != 0
1469 bc_snz
= mode
[SVP64MODEb
.BC_SNZ
] != 0
1470 bc_vsb
= yield self
.dec2
.rm_dec
.bc_vsb
1471 bc_ctrtest
= yield self
.dec2
.rm_dec
.bc_ctrtest
1472 bc_lru
= yield self
.dec2
.rm_dec
.bc_lru
1473 bc_gate
= yield self
.dec2
.rm_dec
.bc_gate
1474 sz
= yield self
.dec2
.rm_dec
.pred_sz
1475 self
.namespace
['mode'] = SelectableInt(mode
, 5)
1476 self
.namespace
['ALL'] = SelectableInt(bc_gate
, 1)
1477 self
.namespace
['VSb'] = SelectableInt(bc_vsb
, 1)
1478 self
.namespace
['LRu'] = SelectableInt(bc_lru
, 1)
1479 self
.namespace
['CTRtest'] = SelectableInt(bc_ctrtest
, 1)
1480 self
.namespace
['VLSET'] = SelectableInt(bc_vlset
, 1)
1481 self
.namespace
['VLI'] = SelectableInt(bc_vli
, 1)
1482 self
.namespace
['sz'] = SelectableInt(sz
, 1)
1483 self
.namespace
['SNZ'] = SelectableInt(bc_snz
, 1)
1485 def get_kludged_op_add_ca_ov(self
, inputs
, inp_ca_ov
):
1486 """ this was not at all necessary to do. this function massively
1487 duplicates - in a laborious and complex fashion - the contents of
1488 the CSV files that were extracted two years ago from microwatt's
1489 source code. A-inversion is the "inv A" column, output inversion
1490 is the "inv out" column, carry-in equal to 0 or 1 or CA is the
1493 all of that information is available in
1494 self.instrs[ins_name].op_fields
1495 where info is usually assigned to self.instrs[ins_name]
1497 https://git.libre-soc.org/?p=openpower-isa.git;a=blob;f=openpower/isatables/minor_31.csv;hb=HEAD
1499 the immediate constants are *also* decoded correctly and placed
1500 usually by DecodeIn2Imm into operand2, as part of power_decoder2.py
1502 def ca(a
, b
, ca_in
, width
):
1503 mask
= (1 << width
) - 1
1504 y
= (a
& mask
) + (b
& mask
) + ca_in
1507 asmcode
= yield self
.dec2
.dec
.op
.asmcode
1508 insn
= insns
.get(asmcode
)
1509 SI
= yield self
.dec2
.dec
.SI
1512 inputs
= [i
.value
for i
in inputs
]
1515 if insn
in ("add", "addo", "addc", "addco"):
1519 elif insn
== "addic" or insn
== "addic.":
1523 elif insn
in ("subf", "subfo", "subfc", "subfco"):
1527 elif insn
== "subfic":
1531 elif insn
== "adde" or insn
== "addeo":
1535 elif insn
== "subfe" or insn
== "subfeo":
1539 elif insn
== "addme" or insn
== "addmeo":
1543 elif insn
== "addze" or insn
== "addzeo":
1547 elif insn
== "subfme" or insn
== "subfmeo":
1551 elif insn
== "subfze" or insn
== "subfzeo":
1555 elif insn
== "addex":
1556 # CA[32] aren't actually written, just generate so we have
1557 # something to return
1558 ca64
= ov64
= ca(inputs
[0], inputs
[1], OV
, 64)
1559 ca32
= ov32
= ca(inputs
[0], inputs
[1], OV
, 32)
1560 return ca64
, ca32
, ov64
, ov32
1561 elif insn
== "neg" or insn
== "nego":
1566 raise NotImplementedError(
1567 "op_add kludge unimplemented instruction: ", asmcode
, insn
)
1569 ca64
= ca(a
, b
, ca_in
, 64)
1570 ca32
= ca(a
, b
, ca_in
, 32)
1571 ov64
= ca64
!= ca(a
, b
, ca_in
, 63)
1572 ov32
= ca32
!= ca(a
, b
, ca_in
, 31)
1573 return ca64
, ca32
, ov64
, ov32
1575 def handle_carry_(self
, inputs
, output
, ca
, ca32
, inp_ca_ov
):
1576 if ca
is not None and ca32
is not None:
1578 op
= yield self
.dec2
.e
.do
.insn_type
1579 if op
== MicrOp
.OP_ADD
.value
and ca
is None and ca32
is None:
1580 retval
= yield from self
.get_kludged_op_add_ca_ov(
1582 ca
, ca32
, ov
, ov32
= retval
1583 asmcode
= yield self
.dec2
.dec
.op
.asmcode
1584 if insns
.get(asmcode
) == 'addex':
1585 # TODO: if 32-bit mode, set ov to ov32
1586 self
.spr
['XER'][XER_bits
['OV']] = ov
1587 self
.spr
['XER'][XER_bits
['OV32']] = ov32
1588 log(f
"write OV/OV32 OV={ov} OV32={ov32}",
1589 kind
=LogType
.InstrInOuts
)
1591 # TODO: if 32-bit mode, set ca to ca32
1592 self
.spr
['XER'][XER_bits
['CA']] = ca
1593 self
.spr
['XER'][XER_bits
['CA32']] = ca32
1594 log(f
"write CA/CA32 CA={ca} CA32={ca32}",
1595 kind
=LogType
.InstrInOuts
)
1597 inv_a
= yield self
.dec2
.e
.do
.invert_in
1599 inputs
[0] = ~inputs
[0]
1601 imm_ok
= yield self
.dec2
.e
.do
.imm_data
.ok
1603 imm
= yield self
.dec2
.e
.do
.imm_data
.data
1604 inputs
.append(SelectableInt(imm
, 64))
1607 log("gt input", x
, output
)
1608 gt
= (gtu(x
, output
))
1611 cy
= 1 if any(gts
) else 0
1613 if ca
is None: # already written
1614 self
.spr
['XER'][XER_bits
['CA']] = cy
1617 # ARGH... different for OP_ADD... *sigh*...
1618 op
= yield self
.dec2
.e
.do
.insn_type
1619 if op
== MicrOp
.OP_ADD
.value
:
1620 res32
= (output
.value
& (1 << 32)) != 0
1621 a32
= (inputs
[0].value
& (1 << 32)) != 0
1622 if len(inputs
) >= 2:
1623 b32
= (inputs
[1].value
& (1 << 32)) != 0
1626 cy32
= res32 ^ a32 ^ b32
1627 log("CA32 ADD", cy32
)
1631 log("input", x
, output
)
1632 log(" x[32:64]", x
, x
[32:64])
1633 log(" o[32:64]", output
, output
[32:64])
1634 gt
= (gtu(x
[32:64], output
[32:64])) == SelectableInt(1, 1)
1636 cy32
= 1 if any(gts
) else 0
1637 log("CA32", cy32
, gts
)
1638 if ca32
is None: # already written
1639 self
.spr
['XER'][XER_bits
['CA32']] = cy32
1641 def handle_overflow(self
, inputs
, output
, div_overflow
, inp_ca_ov
):
1642 op
= yield self
.dec2
.e
.do
.insn_type
1643 if op
== MicrOp
.OP_ADD
.value
:
1644 retval
= yield from self
.get_kludged_op_add_ca_ov(
1646 ca
, ca32
, ov
, ov32
= retval
1647 # TODO: if 32-bit mode, set ov to ov32
1648 self
.spr
['XER'][XER_bits
['OV']] = ov
1649 self
.spr
['XER'][XER_bits
['OV32']] = ov32
1650 self
.spr
['XER'][XER_bits
['SO']] |
= ov
1652 if hasattr(self
.dec2
.e
.do
, "invert_in"):
1653 inv_a
= yield self
.dec2
.e
.do
.invert_in
1655 inputs
[0] = ~inputs
[0]
1657 imm_ok
= yield self
.dec2
.e
.do
.imm_data
.ok
1659 imm
= yield self
.dec2
.e
.do
.imm_data
.data
1660 inputs
.append(SelectableInt(imm
, 64))
1661 log("handle_overflow", inputs
, output
, div_overflow
)
1662 if len(inputs
) < 2 and div_overflow
is None:
1665 # div overflow is different: it's returned by the pseudo-code
1666 # because it's more complex than can be done by analysing the output
1667 if div_overflow
is not None:
1668 ov
, ov32
= div_overflow
, div_overflow
1669 # arithmetic overflow can be done by analysing the input and output
1670 elif len(inputs
) >= 2:
1672 input_sgn
= [exts(x
.value
, x
.bits
) < 0 for x
in inputs
]
1673 output_sgn
= exts(output
.value
, output
.bits
) < 0
1674 ov
= 1 if input_sgn
[0] == input_sgn
[1] and \
1675 output_sgn
!= input_sgn
[0] else 0
1678 input32_sgn
= [exts(x
.value
, 32) < 0 for x
in inputs
]
1679 output32_sgn
= exts(output
.value
, 32) < 0
1680 ov32
= 1 if input32_sgn
[0] == input32_sgn
[1] and \
1681 output32_sgn
!= input32_sgn
[0] else 0
1683 # now update XER OV/OV32/SO
1684 so
= self
.spr
['XER'][XER_bits
['SO']]
1685 new_so
= so | ov
# sticky overflow ORs in old with new
1686 self
.spr
['XER'][XER_bits
['OV']] = ov
1687 self
.spr
['XER'][XER_bits
['OV32']] = ov32
1688 self
.spr
['XER'][XER_bits
['SO']] = new_so
1689 log(" set overflow", ov
, ov32
, so
, new_so
)
1691 def handle_comparison(self
, out
, cr_idx
=0, overflow
=None, no_so
=False):
1692 assert isinstance(out
, SelectableInt
), \
1693 "out zero not a SelectableInt %s" % repr(outputs
)
1694 log("handle_comparison", out
.bits
, hex(out
.value
))
1695 # TODO - XXX *processor* in 32-bit mode
1696 # https://bugs.libre-soc.org/show_bug.cgi?id=424
1698 # o32 = exts(out.value, 32)
1699 # print ("handle_comparison exts 32 bit", hex(o32))
1700 out
= exts(out
.value
, out
.bits
)
1701 log("handle_comparison exts", hex(out
))
1702 # create the three main CR flags, EQ GT LT
1703 zero
= SelectableInt(out
== 0, 1)
1704 positive
= SelectableInt(out
> 0, 1)
1705 negative
= SelectableInt(out
< 0, 1)
1706 # get (or not) XER.SO. for setvl this is important *not* to read SO
1708 SO
= SelectableInt(1, 0)
1710 SO
= self
.spr
['XER'][XER_bits
['SO']]
1711 log("handle_comparison SO", SO
.value
,
1712 "overflow", overflow
,
1714 "+ve", positive
.value
,
1715 "-ve", negative
.value
)
1716 # alternative overflow checking (setvl mainly at the moment)
1717 if overflow
is not None and overflow
== 1:
1718 SO
= SelectableInt(1, 1)
1719 # create the four CR field values and set the required CR field
1720 cr_field
= selectconcat(negative
, positive
, zero
, SO
)
1721 log("handle_comparison cr_field", self
.cr
, cr_idx
, cr_field
)
1722 self
.crl
[cr_idx
].eq(cr_field
)
1724 def set_pc(self
, pc_val
):
1725 self
.namespace
['NIA'] = SelectableInt(pc_val
, 64)
1726 self
.pc
.update(self
.namespace
, self
.is_svp64_mode
)
1728 def get_next_insn(self
):
1729 """check instruction
1732 pc
= self
.pc
.CIA
.value
1735 ins
= self
.imem
.ld(pc
, 4, False, True, instr_fetch
=True)
1737 raise KeyError("no instruction at 0x%x" % pc
)
1740 def setup_one(self
):
1741 """set up one instruction
1743 pc
, insn
= self
.get_next_insn()
1744 yield from self
.setup_next_insn(pc
, insn
)
1746 # cache since it's really slow to construct
1747 __PREFIX_CACHE
= SVP64Instruction
.Prefix(SelectableInt(value
=0, bits
=32))
1749 def __decode_prefix(self
, opcode
):
1750 pfx
= self
.__PREFIX
_CACHE
1751 pfx
.storage
.eq(opcode
)
1754 def setup_next_insn(self
, pc
, ins
):
1755 """set up next instruction
1758 log("setup: 0x%x 0x%x %s" % (pc
, ins
& 0xffffffff, bin(ins
)))
1759 log("CIA NIA", self
.respect_pc
, self
.pc
.CIA
.value
, self
.pc
.NIA
.value
)
1761 yield self
.dec2
.sv_rm
.eq(0)
1762 yield self
.dec2
.dec
.raw_opcode_in
.eq(ins
& 0xffffffff)
1763 yield self
.dec2
.dec
.bigendian
.eq(self
.bigendian
)
1764 yield self
.dec2
.state
.msr
.eq(self
.msr
.value
)
1765 yield self
.dec2
.state
.pc
.eq(pc
)
1766 if self
.svstate
is not None:
1767 yield self
.dec2
.state
.svstate
.eq(self
.svstate
.value
)
1769 # SVP64. first, check if the opcode is EXT001, and SVP64 id bits set
1771 opcode
= yield self
.dec2
.dec
.opcode_in
1772 opcode
= SelectableInt(value
=opcode
, bits
=32)
1773 pfx
= self
.__decode
_prefix
(opcode
)
1774 log("prefix test: opcode:", pfx
.PO
, bin(pfx
.PO
), pfx
.id)
1775 self
.is_svp64_mode
= bool((pfx
.PO
== 0b000001) and (pfx
.id == 0b11))
1776 self
.pc
.update_nia(self
.is_svp64_mode
)
1778 yield self
.dec2
.is_svp64_mode
.eq(self
.is_svp64_mode
)
1779 self
.namespace
['NIA'] = self
.pc
.NIA
1780 self
.namespace
['SVSTATE'] = self
.svstate
1781 if not self
.is_svp64_mode
:
1784 # in SVP64 mode. decode/print out svp64 prefix, get v3.0B instruction
1785 log("svp64.rm", bin(pfx
.rm
))
1786 log(" svstate.vl", self
.svstate
.vl
)
1787 log(" svstate.mvl", self
.svstate
.maxvl
)
1788 ins
= self
.imem
.ld(pc
+4, 4, False, True, instr_fetch
=True)
1789 log(" svsetup: 0x%x 0x%x %s" % (pc
+4, ins
& 0xffffffff, bin(ins
)))
1790 yield self
.dec2
.dec
.raw_opcode_in
.eq(ins
& 0xffffffff) # v3.0B suffix
1791 yield self
.dec2
.sv_rm
.eq(int(pfx
.rm
)) # svp64 prefix
1794 def execute_one(self
):
1795 """execute one instruction
1797 # get the disassembly code for this instruction
1798 if not self
.disassembly
:
1799 code
= yield from self
.get_assembly_name()
1802 if self
.is_svp64_mode
:
1803 offs
, dbg
= 4, "svp64 "
1804 code
= self
.disassembly
[self
._pc
+offs
]
1805 log(" %s sim-execute" % dbg
, hex(self
._pc
), code
)
1806 opname
= code
.split(' ')[0]
1808 yield from self
.call(opname
) # execute the instruction
1809 except MemException
as e
: # check for memory errors
1810 if e
.args
[0] == 'unaligned': # alignment error
1811 # run a Trap but set DAR first
1812 print("memory unaligned exception, DAR", e
.dar
, repr(e
))
1813 self
.spr
['DAR'] = SelectableInt(e
.dar
, 64)
1814 self
.call_trap(0x600, PIb
.PRIV
) # 0x600, privileged
1816 elif e
.args
[0] == 'invalid': # invalid
1817 # run a Trap but set DAR first
1818 log("RADIX MMU memory invalid error, mode %s" % e
.mode
)
1819 if e
.mode
== 'EXECUTE':
1820 # XXX TODO: must set a few bits in SRR1,
1821 # see microwatt loadstore1.vhdl
1822 # if m_in.segerr = '0' then
1823 # v.srr1(47 - 33) := m_in.invalid;
1824 # v.srr1(47 - 35) := m_in.perm_error; -- noexec fault
1825 # v.srr1(47 - 44) := m_in.badtree;
1826 # v.srr1(47 - 45) := m_in.rc_error;
1827 # v.intr_vec := 16#400#;
1829 # v.intr_vec := 16#480#;
1830 self
.call_trap(0x400, PIb
.PRIV
) # 0x400, privileged
1832 self
.call_trap(0x300, PIb
.PRIV
) # 0x300, privileged
1834 # not supported yet:
1835 raise e
# ... re-raise
1837 # append to the trace log file
1838 self
.trace(" # %s\n" % code
)
1840 log("gprs after code", code
)
1843 for i
in range(len(self
.crl
)):
1844 crs
.append(bin(self
.crl
[i
].asint()))
1845 log("crs", " ".join(crs
))
1846 log("vl,maxvl", self
.svstate
.vl
, self
.svstate
.maxvl
)
1848 # don't use this except in special circumstances
1849 if not self
.respect_pc
:
1852 log("execute one, CIA NIA", hex(self
.pc
.CIA
.value
),
1853 hex(self
.pc
.NIA
.value
))
1855 def get_assembly_name(self
):
1856 # TODO, asmregs is from the spec, e.g. add RT,RA,RB
1857 # see http://bugs.libre-riscv.org/show_bug.cgi?id=282
1858 dec_insn
= yield self
.dec2
.e
.do
.insn
1859 insn_1_11
= yield self
.dec2
.e
.do
.insn
[1:11]
1860 asmcode
= yield self
.dec2
.dec
.op
.asmcode
1861 int_op
= yield self
.dec2
.dec
.op
.internal_op
1862 log("get assembly name asmcode", asmcode
, int_op
,
1863 hex(dec_insn
), bin(insn_1_11
))
1864 asmop
= insns
.get(asmcode
, None)
1866 # sigh reconstruct the assembly instruction name
1867 if hasattr(self
.dec2
.e
.do
, "oe"):
1868 ov_en
= yield self
.dec2
.e
.do
.oe
.oe
1869 ov_ok
= yield self
.dec2
.e
.do
.oe
.ok
1873 if hasattr(self
.dec2
.e
.do
, "rc"):
1874 rc_en
= yield self
.dec2
.e
.do
.rc
.rc
1875 rc_ok
= yield self
.dec2
.e
.do
.rc
.ok
1879 # annoying: ignore rc_ok if RC1 is set (for creating *assembly name*)
1880 RC1
= yield self
.dec2
.rm_dec
.RC1
1884 # grrrr have to special-case MUL op (see DecodeOE)
1885 log("ov %d en %d rc %d en %d op %d" %
1886 (ov_ok
, ov_en
, rc_ok
, rc_en
, int_op
))
1887 if int_op
in [MicrOp
.OP_MUL_H64
.value
, MicrOp
.OP_MUL_H32
.value
]:
1892 if not asmop
.endswith("."): # don't add "." to "andis."
1895 if hasattr(self
.dec2
.e
.do
, "lk"):
1896 lk
= yield self
.dec2
.e
.do
.lk
1899 log("int_op", int_op
)
1900 if int_op
in [MicrOp
.OP_B
.value
, MicrOp
.OP_BC
.value
]:
1901 AA
= yield self
.dec2
.dec
.fields
.FormI
.AA
[0:-1]
1905 spr_msb
= yield from self
.get_spr_msb()
1906 if int_op
== MicrOp
.OP_MFCR
.value
:
1911 # XXX TODO: for whatever weird reason this doesn't work
1912 # https://bugs.libre-soc.org/show_bug.cgi?id=390
1913 if int_op
== MicrOp
.OP_MTCRF
.value
:
1920 def reset_remaps(self
):
1921 self
.remap_loopends
= [0] * 4
1922 self
.remap_idxs
= [0, 1, 2, 3]
1924 def get_remap_indices(self
):
1925 """WARNING, this function stores remap_idxs and remap_loopends
1926 in the class for later use. this to avoid problems with yield
1928 # go through all iterators in lock-step, advance to next remap_idx
1929 srcstep
, dststep
, ssubstep
, dsubstep
= self
.get_src_dststeps()
1930 # get four SVSHAPEs. here we are hard-coding
1932 SVSHAPE0
= self
.spr
['SVSHAPE0']
1933 SVSHAPE1
= self
.spr
['SVSHAPE1']
1934 SVSHAPE2
= self
.spr
['SVSHAPE2']
1935 SVSHAPE3
= self
.spr
['SVSHAPE3']
1936 # set up the iterators
1937 remaps
= [(SVSHAPE0
, SVSHAPE0
.get_iterator()),
1938 (SVSHAPE1
, SVSHAPE1
.get_iterator()),
1939 (SVSHAPE2
, SVSHAPE2
.get_iterator()),
1940 (SVSHAPE3
, SVSHAPE3
.get_iterator()),
1944 for i
, (shape
, remap
) in enumerate(remaps
):
1945 # zero is "disabled"
1946 if shape
.value
== 0x0:
1947 self
.remap_idxs
[i
] = 0
1948 # pick src or dststep depending on reg num (0-2=in, 3-4=out)
1949 step
= dststep
if (i
in [3, 4]) else srcstep
1950 # this is terrible. O(N^2) looking for the match. but hey.
1951 for idx
, (remap_idx
, loopends
) in enumerate(remap
):
1954 self
.remap_idxs
[i
] = remap_idx
1955 self
.remap_loopends
[i
] = loopends
1956 dbg
.append((i
, step
, remap_idx
, loopends
))
1957 for (i
, step
, remap_idx
, loopends
) in dbg
:
1958 log("SVSHAPE %d idx, end" % i
, step
, remap_idx
, bin(loopends
))
1961 def get_spr_msb(self
):
1962 dec_insn
= yield self
.dec2
.e
.do
.insn
1963 return dec_insn
& (1 << 20) != 0 # sigh - XFF.spr[-1]?
1965 def call(self
, name
, syscall_emu_active
=False):
1966 """call(opcode) - the primary execution point for instructions
1968 self
.last_st_addr
= None # reset the last known store address
1969 self
.last_ld_addr
= None # etc.
1971 ins_name
= name
.strip() # remove spaces if not already done so
1973 log("halted - not executing", ins_name
)
1976 # TODO, asmregs is from the spec, e.g. add RT,RA,RB
1977 # see http://bugs.libre-riscv.org/show_bug.cgi?id=282
1978 asmop
= yield from self
.get_assembly_name()
1979 log("call", ins_name
, asmop
,
1980 kind
=LogType
.InstrInOuts
)
1982 # sv.setvl is *not* a loop-function. sigh
1983 log("is_svp64_mode", self
.is_svp64_mode
, asmop
)
1986 int_op
= yield self
.dec2
.dec
.op
.internal_op
1987 spr_msb
= yield from self
.get_spr_msb()
1989 instr_is_privileged
= False
1990 if int_op
in [MicrOp
.OP_ATTN
.value
,
1991 MicrOp
.OP_MFMSR
.value
,
1992 MicrOp
.OP_MTMSR
.value
,
1993 MicrOp
.OP_MTMSRD
.value
,
1995 MicrOp
.OP_RFID
.value
]:
1996 instr_is_privileged
= True
1997 if int_op
in [MicrOp
.OP_MFSPR
.value
,
1998 MicrOp
.OP_MTSPR
.value
] and spr_msb
:
1999 instr_is_privileged
= True
2001 log("is priv", instr_is_privileged
, hex(self
.msr
.value
),
2003 # check MSR priv bit and whether op is privileged: if so, throw trap
2004 if instr_is_privileged
and self
.msr
[MSRb
.PR
] == 1:
2005 self
.call_trap(0x700, PIb
.PRIV
)
2008 # check halted condition
2009 if ins_name
== 'attn':
2013 # User mode system call emulation consists of several steps:
2014 # 1. Detect whether instruction is sc or scv.
2015 # 2. Call the HDL implementation which invokes trap.
2016 # 3. Reroute the guest system call to host system call.
2017 # 4. Force return from the interrupt as if we had guest OS.
2018 # "executing" rfid requires putting 0x4c000024 temporarily
2019 # into the program at the PC. TODO investigate and remove
2020 if ((asmop
in ("sc", "scv")) and
2021 (self
.syscall
is not None) and
2022 not syscall_emu_active
):
2023 # Memoize PC and trigger an interrupt
2025 pc
= self
.pc
.CIA
.value
2028 yield from self
.call(asmop
, syscall_emu_active
=True)
2030 # Reroute the syscall to host OS
2031 identifier
= self
.gpr(0)
2032 arguments
= map(self
.gpr
, range(3, 9))
2033 result
= self
.syscall(identifier
, *arguments
)
2034 self
.gpr
.write(3, result
, False, self
.namespace
["XLEN"])
2036 # Return from interrupt
2037 backup
= self
.imem
.ld(pc
, 4, False, True, instr_fetch
=True)
2038 self
.imem
.st(pc
, 0x4c000024, width
=4, swap
=True)
2039 yield from self
.call("rfid", syscall_emu_active
=True)
2040 self
.imem
.st(pc
, backup
, width
=4, swap
=True)
2041 elif ((name
in ("rfid", "hrfid")) and syscall_emu_active
):
2044 # check illegal instruction
2046 if ins_name
not in ['mtcrf', 'mtocrf']:
2047 illegal
= ins_name
!= asmop
2049 # list of instructions not being supported by binutils (.long)
2050 dotstrp
= asmop
[:-1] if asmop
[-1] == '.' else asmop
2051 if dotstrp
in [*FPTRANS_INSNS
,
2053 'ffmadds', 'fdmadds', 'ffadds',
2055 "brh", "brw", "brd",
2056 'setvl', 'svindex', 'svremap', 'svstep',
2057 'svshape', 'svshape2',
2058 'ternlogi', 'bmask', 'cprop',
2059 'absdu', 'absds', 'absdacs', 'absdacu', 'avgadd',
2060 'fmvis', 'fishmv', 'pcdec', "maddedu", "divmod2du",
2061 "dsld", "dsrd", "maddedus",
2062 "sadd", "saddw", "sadduw",
2067 "maddsubrs", "maddrs", "msubrs",
2068 "cfuged", "cntlzdm", "cnttzdm", "pdepd", "pextd",
2069 "setbc", "setbcr", "setnbc", "setnbcr",
2074 # branch-conditional redirects to sv.bc
2075 if asmop
.startswith('bc') and self
.is_svp64_mode
:
2076 ins_name
= 'sv.%s' % ins_name
2078 # ld-immediate-with-pi mode redirects to ld-with-postinc
2079 ldst_imm_postinc
= False
2080 if 'u' in ins_name
and self
.is_svp64_mode
:
2081 ldst_pi
= yield self
.dec2
.rm_dec
.ldst_postinc
2083 ins_name
= ins_name
.replace("u", "up")
2084 ldst_imm_postinc
= True
2085 log(" enable ld/st postinc", ins_name
)
2087 log(" post-processed name", dotstrp
, ins_name
, asmop
)
2089 # illegal instructions call TRAP at 0x700
2091 print("illegal", ins_name
, asmop
)
2092 self
.call_trap(0x700, PIb
.ILLEG
)
2093 print("name %s != %s - calling ILLEGAL trap, PC: %x" %
2094 (ins_name
, asmop
, self
.pc
.CIA
.value
))
2097 # this is for setvl "Vertical" mode: if set true,
2098 # srcstep/dststep is explicitly advanced. mode says which SVSTATE to
2099 # test for Rc=1 end condition. 3 bits of all 3 loops are put into CR0
2100 self
.allow_next_step_inc
= False
2101 self
.svstate_next_mode
= 0
2103 # nop has to be supported, we could let the actual op calculate
2104 # but PowerDecoder has a pattern for nop
2105 if ins_name
== 'nop':
2106 self
.update_pc_next()
2109 # get elwidths, defaults to 64
2113 if self
.is_svp64_mode
:
2114 ew_src
= yield self
.dec2
.rm_dec
.ew_src
2115 ew_dst
= yield self
.dec2
.rm_dec
.ew_dst
2116 ew_src
= 8 << (3-int(ew_src
)) # convert to bitlength
2117 ew_dst
= 8 << (3-int(ew_dst
)) # convert to bitlength
2118 xlen
= max(ew_src
, ew_dst
)
2119 log("elwdith", ew_src
, ew_dst
)
2120 log("XLEN:", self
.is_svp64_mode
, xlen
)
2122 # look up instruction in ISA.instrs, prepare namespace
2123 if ins_name
== 'pcdec': # grrrr yes there are others ("stbcx." etc.)
2124 info
= self
.instrs
[ins_name
+"."]
2125 elif asmop
[-1] == '.' and asmop
in self
.instrs
:
2126 info
= self
.instrs
[asmop
]
2128 info
= self
.instrs
[ins_name
]
2129 yield from self
.prep_namespace(ins_name
, info
.form
, info
.op_fields
,
2132 # dict retains order
2133 inputs
= dict.fromkeys(create_full_args(
2134 read_regs
=info
.read_regs
, special_regs
=info
.special_regs
,
2135 uninit_regs
=info
.uninit_regs
, write_regs
=info
.write_regs
))
2137 # preserve order of register names
2138 write_without_special_regs
= OrderedSet(info
.write_regs
)
2139 write_without_special_regs
-= OrderedSet(info
.special_regs
)
2140 input_names
= create_args([
2141 *info
.read_regs
, *info
.uninit_regs
, *write_without_special_regs
])
2142 log("input names", input_names
)
2144 # get SVP64 entry for the current instruction
2145 sv_rm
= self
.svp64rm
.instrs
.get(ins_name
)
2146 if sv_rm
is not None:
2147 dest_cr
, src_cr
, src_byname
, dest_byname
= decode_extra(sv_rm
)
2149 dest_cr
, src_cr
, src_byname
, dest_byname
= False, False, {}, {}
2150 log("sv rm", sv_rm
, dest_cr
, src_cr
, src_byname
, dest_byname
)
2152 # see if srcstep/dststep need skipping over masked-out predicate bits
2153 # svstep also needs advancement because it calls SVSTATE_NEXT.
2154 # bit the remaps get computed just after pre_inc moves them on
2155 # with remap_set_steps substituting for PowerDecider2 not doing it,
2156 # and SVSTATE_NEXT not being able to.use yield, the preinc on
2157 # svstep is necessary for now.
2159 if (self
.is_svp64_mode
or ins_name
in ['svstep']):
2160 yield from self
.svstate_pre_inc()
2161 if self
.is_svp64_mode
:
2162 pre
= yield from self
.update_new_svstate_steps()
2164 self
.svp64_reset_loop()
2166 self
.update_pc_next()
2168 srcstep
, dststep
, ssubstep
, dsubstep
= self
.get_src_dststeps()
2169 pred_dst_zero
= self
.pred_dst_zero
2170 pred_src_zero
= self
.pred_src_zero
2171 vl
= self
.svstate
.vl
2172 subvl
= yield self
.dec2
.rm_dec
.rm_in
.subvl
2174 # VL=0 in SVP64 mode means "do nothing: skip instruction"
2175 if self
.is_svp64_mode
and vl
== 0:
2176 self
.pc
.update(self
.namespace
, self
.is_svp64_mode
)
2177 log("SVP64: VL=0, end of call", self
.namespace
['CIA'],
2178 self
.namespace
['NIA'], kind
=LogType
.InstrInOuts
)
2181 # for when SVREMAP is active, using pre-arranged schedule.
2182 # note: modifying PowerDecoder2 needs to "settle"
2183 remap_en
= self
.svstate
.SVme
2184 persist
= self
.svstate
.RMpst
2185 active
= (persist
or self
.last_op_svshape
) and remap_en
!= 0
2186 if self
.is_svp64_mode
:
2187 yield self
.dec2
.remap_active
.eq(remap_en
if active
else 0)
2189 if persist
or self
.last_op_svshape
:
2190 remaps
= self
.get_remap_indices()
2191 if self
.is_svp64_mode
and (persist
or self
.last_op_svshape
):
2192 yield from self
.remap_set_steps(remaps
)
2193 # after that, settle down (combinatorial) to let Vector reg numbers
2194 # work themselves out
2196 if self
.is_svp64_mode
:
2197 remap_active
= yield self
.dec2
.remap_active
2199 remap_active
= False
2200 log("remap active", bin(remap_active
))
2202 # main input registers (RT, RA ...)
2203 for name
in input_names
:
2204 if name
== "overflow":
2205 inputs
[name
] = SelectableInt(0, 1)
2206 elif name
== "FPSCR":
2207 inputs
[name
] = self
.FPSCR
2208 elif name
in ("CA", "CA32", "OV", "OV32"):
2209 inputs
[name
] = self
.spr
['XER'][XER_bits
[name
]]
2211 inputs
[name
] = self
.crl
[0]
2212 elif name
in spr_byname
:
2213 inputs
[name
] = self
.spr
[name
]
2215 regval
= (yield from self
.get_input(name
, ew_src
))
2216 log("regval name", name
, regval
)
2217 inputs
[name
] = regval
2219 # arrrrgh, awful hack, to get _RT into namespace
2220 if ins_name
in ['setvl', 'svstep']:
2222 RT
= yield self
.dec2
.dec
.RT
2223 self
.namespace
[regname
] = SelectableInt(RT
, 5)
2225 self
.namespace
["RT"] = SelectableInt(0, 5)
2226 regnum
, is_vec
= yield from get_idx_out(self
.dec2
, "RT")
2227 log('hack input reg %s %s' % (name
, str(regnum
)), is_vec
)
2229 # in SVP64 mode for LD/ST work out immediate
2230 # XXX TODO: replace_ds for DS-Form rather than D-Form.
2231 # use info.form to detect
2232 if self
.is_svp64_mode
and not ldst_imm_postinc
:
2233 yield from self
.check_replace_d(info
, remap_active
)
2235 # "special" registers
2236 for special
in info
.special_regs
:
2237 if special
in special_sprs
:
2238 inputs
[special
] = self
.spr
[special
]
2240 inputs
[special
] = self
.namespace
[special
]
2242 # clear trap (trap) NIA
2243 self
.trap_nia
= None
2245 # check if this was an sv.bc* and create an indicator that
2246 # this is the last check to be made as a loop. combined with
2247 # the ALL/ANY mode we can early-exit. note that BI (to test)
2248 # is an input so there is no termination if BI is scalar
2249 # (because early-termination is for *output* scalars)
2250 if self
.is_svp64_mode
and ins_name
.startswith("sv.bc"):
2251 end_loop
= srcstep
== vl
-1 or dststep
== vl
-1
2252 self
.namespace
['end_loop'] = SelectableInt(end_loop
, 1)
2254 inp_ca_ov
= (self
.spr
['XER'][XER_bits
['CA']].value
,
2255 self
.spr
['XER'][XER_bits
['OV']].value
)
2257 for k
, v
in inputs
.items():
2259 v
= SelectableInt(0, self
.XLEN
)
2260 # prevent pseudo-code from modifying input registers
2261 v
= copy_assign_rhs(v
)
2262 if isinstance(v
, SelectableInt
):
2266 # execute actual instruction here (finally)
2267 log("inputs", inputs
)
2268 inputs
= list(inputs
.values())
2269 results
= info
.func(self
, *inputs
)
2270 output_names
= create_args(info
.write_regs
)
2272 # record .ok before anything after the pseudo-code can modify it
2274 for out
, n
in zip(results
or [], output_names
):
2277 if isinstance(out
, SelectableInt
):
2279 log("results", outs
)
2280 log("results ok", outs_ok
)
2282 # "inject" decorator takes namespace from function locals: we need to
2283 # overwrite NIA being overwritten (sigh)
2284 if self
.trap_nia
is not None:
2285 self
.namespace
['NIA'] = self
.trap_nia
2287 log("after func", self
.namespace
['CIA'], self
.namespace
['NIA'])
2289 # check if op was a LD/ST so that debugging can check the
2291 if int_op
in [MicrOp
.OP_STORE
.value
,
2293 self
.last_st_addr
= self
.mem
.last_st_addr
2294 if int_op
in [MicrOp
.OP_LOAD
.value
,
2296 self
.last_ld_addr
= self
.mem
.last_ld_addr
2297 log("op", int_op
, MicrOp
.OP_STORE
.value
, MicrOp
.OP_LOAD
.value
,
2298 self
.last_st_addr
, self
.last_ld_addr
)
2300 # detect if CA/CA32 already in outputs (sra*, basically)
2302 ca32
= outs
.get("CA32")
2304 log("carry already done?", ca
, ca32
, output_names
)
2305 # soc test_pipe_caller tests don't have output_carry
2306 has_output_carry
= hasattr(self
.dec2
.e
.do
, "output_carry")
2307 carry_en
= has_output_carry
and (yield self
.dec2
.e
.do
.output_carry
)
2309 yield from self
.handle_carry_(
2310 inputs
, results
[0], ca
, ca32
, inp_ca_ov
=inp_ca_ov
)
2312 # get output named "overflow" and "CR0"
2313 overflow
= outs
.get('overflow')
2314 cr0
= outs
.get('CR0')
2315 cr1
= outs
.get('CR1')
2317 # soc test_pipe_caller tests don't have oe
2318 has_oe
= hasattr(self
.dec2
.e
.do
, "oe")
2319 # yeah just no. not in parallel processing
2320 if has_oe
and not self
.is_svp64_mode
:
2321 # detect if overflow was in return result
2322 ov_en
= yield self
.dec2
.e
.do
.oe
.oe
2323 ov_ok
= yield self
.dec2
.e
.do
.oe
.ok
2324 log("internal overflow", ins_name
, overflow
, "en?", ov_en
, ov_ok
)
2326 yield from self
.handle_overflow(
2327 inputs
, results
[0], overflow
, inp_ca_ov
=inp_ca_ov
)
2329 # only do SVP64 dest predicated Rc=1 if dest-pred is not enabled
2331 if not self
.is_svp64_mode
or not pred_dst_zero
:
2332 if hasattr(self
.dec2
.e
.do
, "rc"):
2333 rc_en
= yield self
.dec2
.e
.do
.rc
.rc
2334 # don't do Rc=1 for svstep it is handled explicitly.
2335 # XXX TODO: now that CR0 is supported, sort out svstep's pseudocode
2336 # to write directly to CR0 instead of in ISACaller. hooyahh.
2337 if rc_en
and ins_name
not in ['svstep']:
2338 if outs_ok
.get('FPSCR', False):
2339 FPSCR
= outs
['FPSCR']
2342 yield from self
.do_rc_ov(
2343 ins_name
, results
[0], overflow
, cr0
, cr1
, FPSCR
)
2346 ffirst_hit
= False, False
2347 if self
.is_svp64_mode
:
2348 sv_mode
= yield self
.dec2
.rm_dec
.sv_mode
2349 is_cr
= sv_mode
== SVMode
.CROP
.value
2350 chk
= rc_en
or is_cr
2351 if outs_ok
.get('CR', False):
2352 # early write so check_ffirst can see value
2353 self
.namespace
['CR'].eq(outs
['CR'])
2354 ffirst_hit
= (yield from self
.check_ffirst(info
, chk
, srcstep
))
2356 # any modified return results?
2357 yield from self
.do_outregs(
2358 info
, outs
, carry_en
, ffirst_hit
, ew_dst
, outs_ok
)
2360 # check if a FP Exception occurred. TODO for DD-FFirst, check VLi
2361 # and raise the exception *after* if VLi=1 but if VLi=0 then
2362 # truncate and make the exception "disappear".
2363 if self
.FPSCR
.FEX
and (self
.msr
[MSRb
.FE0
] or self
.msr
[MSRb
.FE1
]):
2364 self
.call_trap(0x700, PIb
.FP
)
2367 yield from self
.do_nia(asmop
, ins_name
, rc_en
, ffirst_hit
)
2369 def check_ffirst(self
, info
, rc_en
, srcstep
):
2370 """fail-first mode: checks a bit of Rc Vector, truncates VL
2372 rm_mode
= yield self
.dec2
.rm_dec
.mode
2373 ff_inv
= yield self
.dec2
.rm_dec
.inv
2374 cr_bit
= yield self
.dec2
.rm_dec
.cr_sel
2375 RC1
= yield self
.dec2
.rm_dec
.RC1
2376 vli_
= yield self
.dec2
.rm_dec
.vli
# VL inclusive if truncated
2377 log(" ff rm_mode", rc_en
, rm_mode
, SVP64RMMode
.FFIRST
.value
)
2381 log(" cr_bit", cr_bit
)
2382 log(" rc_en", rc_en
)
2383 if not rc_en
or rm_mode
!= SVP64RMMode
.FFIRST
.value
:
2385 # get the CR vevtor, do BO-test
2387 log("asmregs", info
.asmregs
[0], info
.write_regs
)
2388 if 'CR' in info
.write_regs
and 'BF' in info
.asmregs
[0]:
2390 regnum
, is_vec
= yield from get_cr_out(self
.dec2
, crf
)
2391 crtest
= self
.crl
[regnum
]
2392 ffirst_hit
= crtest
[cr_bit
] != ff_inv
2393 log("cr test", crf
, regnum
, int(crtest
), crtest
, cr_bit
, ff_inv
)
2394 log("cr test?", ffirst_hit
)
2397 # Fail-first activated, truncate VL
2398 vli
= SelectableInt(int(vli_
), 7)
2399 self
.svstate
.vl
= srcstep
+ vli
2400 yield self
.dec2
.state
.svstate
.eq(self
.svstate
.value
)
2401 yield Settle() # let decoder update
2404 def do_rc_ov(self
, ins_name
, result
, overflow
, cr0
, cr1
, FPSCR
):
2405 cr_out
= yield self
.dec2
.op
.cr_out
2406 if cr_out
== CROutSel
.CR1
.value
:
2410 regnum
, is_vec
= yield from get_cr_out(self
.dec2
, rc_reg
)
2411 # hang on... for `setvl` actually you want to test SVSTATE.VL
2412 is_setvl
= ins_name
in ('svstep', 'setvl')
2414 result
= SelectableInt(result
.vl
, 64)
2416 # overflow = None # do not override overflow except in setvl
2420 cr1
= int(FPSCR
.FX
) << 3
2421 cr1 |
= int(FPSCR
.FEX
) << 2
2422 cr1 |
= int(FPSCR
.VX
) << 1
2423 cr1 |
= int(FPSCR
.OX
)
2424 log("default fp cr1", cr1
)
2426 log("explicit cr1", cr1
)
2427 self
.crl
[regnum
].eq(cr1
)
2429 # if there was not an explicit CR0 in the pseudocode,
2431 self
.handle_comparison(result
, regnum
, overflow
, no_so
=is_setvl
)
2433 # otherwise we just blat CR0 into the required regnum
2434 log("explicit rc0", cr0
)
2435 self
.crl
[regnum
].eq(cr0
)
2437 def do_outregs(self
, info
, outs
, ca_en
, ffirst_hit
, ew_dst
, outs_ok
):
2438 ffirst_hit
, vli
= ffirst_hit
2439 # write out any regs for this instruction, but only if fail-first is ok
2440 # XXX TODO: allow CR-vector to be written out even if ffirst fails
2441 if not ffirst_hit
or vli
:
2442 for name
, output
in outs
.items():
2443 if not outs_ok
[name
]:
2444 log("skipping writing output with .ok=False", name
, output
)
2446 yield from self
.check_write(info
, name
, output
, ca_en
, ew_dst
)
2447 # restore the CR value on non-VLI failfirst (from sv.cmp and others
2448 # which write directly to CR in the pseudocode (gah, what a mess)
2449 # if ffirst_hit and not vli:
2450 # self.cr.value = self.cr_backup
2452 def do_nia(self
, asmop
, ins_name
, rc_en
, ffirst_hit
):
2453 ffirst_hit
, vli
= ffirst_hit
2455 self
.svp64_reset_loop()
2458 # check advancement of src/dst/sub-steps and if PC needs updating
2459 nia_update
= (yield from self
.check_step_increment(
2460 rc_en
, asmop
, ins_name
))
2462 self
.update_pc_next()
2464 def check_replace_d(self
, info
, remap_active
):
2465 replace_d
= False # update / replace constant in pseudocode
2466 ldstmode
= yield self
.dec2
.rm_dec
.ldstmode
2467 vl
= self
.svstate
.vl
2468 subvl
= yield self
.dec2
.rm_dec
.rm_in
.subvl
2469 srcstep
, dststep
= self
.new_srcstep
, self
.new_dststep
2470 ssubstep
, dsubstep
= self
.new_ssubstep
, self
.new_dsubstep
2471 if info
.form
== 'DS':
2472 # DS-Form, multiply by 4 then knock 2 bits off after
2473 imm
= yield self
.dec2
.dec
.fields
.FormDS
.DS
[0:14] * 4
2475 imm
= yield self
.dec2
.dec
.fields
.FormD
.D
[0:16]
2476 imm
= exts(imm
, 16) # sign-extend to integer
2477 # get the right step. LD is from srcstep, ST is dststep
2478 op
= yield self
.dec2
.e
.do
.insn_type
2480 if op
== MicrOp
.OP_LOAD
.value
:
2482 offsmul
= yield self
.dec2
.in1_step
2483 log("D-field REMAP src", imm
, offsmul
, ldstmode
)
2485 offsmul
= (srcstep
* (subvl
+1)) + ssubstep
2486 log("D-field src", imm
, offsmul
, ldstmode
)
2487 elif op
== MicrOp
.OP_STORE
.value
:
2488 # XXX NOTE! no bit-reversed STORE! this should not ever be used
2489 offsmul
= (dststep
* (subvl
+1)) + dsubstep
2490 log("D-field dst", imm
, offsmul
, ldstmode
)
2491 # Unit-Strided LD/ST adds offset*width to immediate
2492 if ldstmode
== SVP64LDSTmode
.UNITSTRIDE
.value
:
2493 ldst_len
= yield self
.dec2
.e
.do
.data_len
2494 imm
= SelectableInt(imm
+ offsmul
* ldst_len
, 32)
2496 # Element-strided multiplies the immediate by element step
2497 elif ldstmode
== SVP64LDSTmode
.ELSTRIDE
.value
:
2498 imm
= SelectableInt(imm
* offsmul
, 32)
2501 ldst_ra_vec
= yield self
.dec2
.rm_dec
.ldst_ra_vec
2502 ldst_imz_in
= yield self
.dec2
.rm_dec
.ldst_imz_in
2503 log("LDSTmode", SVP64LDSTmode(ldstmode
),
2504 offsmul
, imm
, ldst_ra_vec
, ldst_imz_in
)
2505 # new replacement D... errr.. DS
2507 if info
.form
== 'DS':
2508 # TODO: assert 2 LSBs are zero?
2509 log("DS-Form, TODO, assert 2 LSBs zero?", bin(imm
.value
))
2510 imm
.value
= imm
.value
>> 2
2511 self
.namespace
['DS'] = imm
2513 self
.namespace
['D'] = imm
2515 def get_input(self
, name
, ew_src
):
2516 # using PowerDecoder2, first, find the decoder index.
2517 # (mapping name RA RB RC RS to in1, in2, in3)
2518 regnum
, is_vec
= yield from get_idx_in(self
.dec2
, name
, True)
2520 # doing this is not part of svp64, it's because output
2521 # registers, to be modified, need to be in the namespace.
2522 regnum
, is_vec
= yield from get_idx_out(self
.dec2
, name
, True)
2524 regnum
, is_vec
= yield from get_idx_out2(self
.dec2
, name
, True)
2526 if isinstance(regnum
, tuple):
2527 (regnum
, base
, offs
) = regnum
2529 base
, offs
= regnum
, 0 # temporary HACK
2531 # in case getting the register number is needed, _RA, _RB
2532 # (HACK: only in straight non-svp64-mode for now, or elwidth == 64)
2533 regname
= "_" + name
2534 if not self
.is_svp64_mode
or ew_src
== 64:
2535 self
.namespace
[regname
] = regnum
2536 elif regname
in self
.namespace
:
2537 del self
.namespace
[regname
]
2539 if not self
.is_svp64_mode
or not self
.pred_src_zero
:
2540 log('reading reg %s %s' % (name
, str(regnum
)), is_vec
)
2542 reg_val
= SelectableInt(self
.fpr(base
, is_vec
, offs
, ew_src
))
2543 log("read reg %d/%d: 0x%x" % (base
, offs
, reg_val
.value
),
2544 kind
=LogType
.InstrInOuts
)
2545 self
.trace("r:FPR:%d:%d:%d " % (base
, offs
, ew_src
))
2546 elif name
is not None:
2547 reg_val
= SelectableInt(self
.gpr(base
, is_vec
, offs
, ew_src
))
2548 self
.trace("r:GPR:%d:%d:%d " % (base
, offs
, ew_src
))
2549 log("read reg %d/%d: 0x%x" % (base
, offs
, reg_val
.value
),
2550 kind
=LogType
.InstrInOuts
)
2552 log('zero input reg %s %s' % (name
, str(regnum
)), is_vec
)
2553 reg_val
= SelectableInt(0, ew_src
)
2556 def remap_set_steps(self
, remaps
):
2557 """remap_set_steps sets up the in1/2/3 and out1/2 steps.
2558 they work in concert with PowerDecoder2 at the moment,
2559 there is no HDL implementation of REMAP. therefore this
2560 function, because ISACaller still uses PowerDecoder2,
2561 will *explicitly* write the dec2.XX_step values. this has
2564 # just some convenient debug info
2566 sname
= 'SVSHAPE%d' % i
2567 shape
= self
.spr
[sname
]
2568 log(sname
, bin(shape
.value
))
2569 log(" lims", shape
.lims
)
2570 log(" mode", shape
.mode
)
2571 log(" skip", shape
.skip
)
2573 # set up the list of steps to remap
2574 mi0
= self
.svstate
.mi0
2575 mi1
= self
.svstate
.mi1
2576 mi2
= self
.svstate
.mi2
2577 mo0
= self
.svstate
.mo0
2578 mo1
= self
.svstate
.mo1
2579 steps
= [[self
.dec2
.in1_step
, mi0
], # RA
2580 [self
.dec2
.in2_step
, mi1
], # RB
2581 [self
.dec2
.in3_step
, mi2
], # RC
2582 [self
.dec2
.o_step
, mo0
], # RT
2583 [self
.dec2
.o2_step
, mo1
], # EA
2586 rnames
= ['RA', 'RB', 'RC', 'RT', 'RS']
2587 for i
, reg
in enumerate(rnames
):
2588 idx
= yield from get_idx_map(self
.dec2
, reg
)
2590 idx
= yield from get_idx_map(self
.dec2
, "F"+reg
)
2592 steps
[i
][0] = self
.dec2
.in1_step
2594 steps
[i
][0] = self
.dec2
.in2_step
2596 steps
[i
][0] = self
.dec2
.in3_step
2597 log("remap step", i
, reg
, idx
, steps
[i
][1])
2598 remap_idxs
= self
.remap_idxs
2600 # now cross-index the required SHAPE for each of 3-in 2-out regs
2601 rnames
= ['RA', 'RB', 'RC', 'RT', 'EA']
2602 for i
, (dstep
, shape_idx
) in enumerate(steps
):
2603 (shape
, remap
) = remaps
[shape_idx
]
2604 remap_idx
= remap_idxs
[shape_idx
]
2605 # zero is "disabled"
2606 if shape
.value
== 0x0:
2608 # now set the actual requested step to the current index
2609 if dstep
is not None:
2610 yield dstep
.eq(remap_idx
)
2612 # debug printout info
2613 rremaps
.append((shape
.mode
, hex(shape
.value
), dstep
,
2614 i
, rnames
[i
], shape_idx
, remap_idx
))
2616 log("shape remap", x
)
2618 def check_write(self
, info
, name
, output
, carry_en
, ew_dst
):
2619 if name
== 'overflow': # ignore, done already (above)
2621 if name
== 'CR0': # ignore, done already (above)
2623 if isinstance(output
, int):
2624 output
= SelectableInt(output
, EFFECTIVELY_UNLIMITED
)
2626 if name
in ['FPSCR', ]:
2627 log("write FPSCR 0x%x" % (output
.value
))
2628 self
.FPSCR
.eq(output
)
2631 if name
in ['CA', 'CA32']:
2633 log("writing %s to XER" % name
, output
)
2634 log("write XER %s 0x%x" % (name
, output
.value
))
2635 self
.spr
['XER'][XER_bits
[name
]] = output
.value
2637 log("NOT writing %s to XER" % name
, output
)
2639 # write special SPRs
2640 if name
in info
.special_regs
:
2641 log('writing special %s' % name
, output
, special_sprs
)
2642 log("write reg %s 0x%x" % (name
, output
.value
),
2643 kind
=LogType
.InstrInOuts
)
2644 if name
in special_sprs
:
2645 self
.spr
[name
] = output
2647 self
.namespace
[name
].eq(output
)
2649 log('msr written', hex(self
.msr
.value
))
2651 # find out1/out2 PR/FPR
2652 regnum
, is_vec
= yield from get_idx_out(self
.dec2
, name
, True)
2654 regnum
, is_vec
= yield from get_idx_out2(self
.dec2
, name
, True)
2656 # temporary hack for not having 2nd output
2657 regnum
= yield getattr(self
.decoder
, name
)
2659 # convenient debug prefix
2664 # check zeroing due to predicate bit being zero
2665 if self
.is_svp64_mode
and self
.pred_dst_zero
:
2666 log('zeroing reg %s %s' % (str(regnum
), str(output
)), is_vec
)
2667 output
= SelectableInt(0, EFFECTIVELY_UNLIMITED
)
2668 log("write reg %s%s 0x%x ew %d" % (reg_prefix
, str(regnum
),
2669 output
.value
, ew_dst
),
2670 kind
=LogType
.InstrInOuts
)
2671 # zero-extend tov64 bit begore storing (should use EXT oh well)
2672 if output
.bits
> 64:
2673 output
= SelectableInt(output
.value
, 64)
2674 rnum
, base
, offset
= regnum
2676 self
.fpr
.write(regnum
, output
, is_vec
, ew_dst
)
2677 self
.trace("w:FPR:%d:%d:%d " % (rnum
, offset
, ew_dst
))
2679 self
.gpr
.write(regnum
, output
, is_vec
, ew_dst
)
2680 self
.trace("w:GPR:%d:%d:%d " % (rnum
, offset
, ew_dst
))
2682 def check_step_increment(self
, rc_en
, asmop
, ins_name
):
2683 # check if it is the SVSTATE.src/dest step that needs incrementing
2684 # this is our Sub-Program-Counter loop from 0 to VL-1
2685 if not self
.allow_next_step_inc
:
2686 if self
.is_svp64_mode
:
2687 return (yield from self
.svstate_post_inc(ins_name
))
2689 # XXX only in non-SVP64 mode!
2690 # record state of whether the current operation was an svshape,
2692 # to be able to know if it should apply in the next instruction.
2693 # also (if going to use this instruction) should disable ability
2694 # to interrupt in between. sigh.
2695 self
.last_op_svshape
= asmop
in ['svremap', 'svindex',
2702 log("SVSTATE_NEXT: inc requested, mode",
2703 self
.svstate_next_mode
, self
.allow_next_step_inc
)
2704 yield from self
.svstate_pre_inc()
2705 pre
= yield from self
.update_new_svstate_steps()
2707 # reset at end of loop including exit Vertical Mode
2708 log("SVSTATE_NEXT: end of loop, reset")
2709 self
.svp64_reset_loop()
2710 self
.svstate
.vfirst
= 0
2714 self
.handle_comparison(SelectableInt(0, 64)) # CR0
2716 if self
.allow_next_step_inc
== 2:
2717 log("SVSTATE_NEXT: read")
2718 nia_update
= (yield from self
.svstate_post_inc(ins_name
))
2720 log("SVSTATE_NEXT: post-inc")
2721 # use actual (cached) src/dst-step here to check end
2722 remaps
= self
.get_remap_indices()
2723 remap_idxs
= self
.remap_idxs
2724 vl
= self
.svstate
.vl
2725 subvl
= yield self
.dec2
.rm_dec
.rm_in
.subvl
2726 if self
.allow_next_step_inc
!= 2:
2727 yield from self
.advance_svstate_steps()
2728 #self.namespace['SVSTATE'] = self.svstate.spr
2729 # set CR0 (if Rc=1) based on end
2730 endtest
= 1 if self
.at_loopend() else 0
2732 #results = [SelectableInt(endtest, 64)]
2733 # self.handle_comparison(results) # CR0
2735 # see if svstep was requested, if so, which SVSTATE
2737 if self
.svstate_next_mode
> 0:
2738 shape_idx
= self
.svstate_next_mode
.value
-1
2739 endings
= self
.remap_loopends
[shape_idx
]
2740 cr_field
= SelectableInt((~endings
) << 1 | endtest
, 4)
2741 log("svstep Rc=1, CR0", cr_field
, endtest
)
2742 self
.crl
[0].eq(cr_field
) # CR0
2744 # reset at end of loop including exit Vertical Mode
2745 log("SVSTATE_NEXT: after increments, reset")
2746 self
.svp64_reset_loop()
2747 self
.svstate
.vfirst
= 0
2750 def SVSTATE_NEXT(self
, mode
, submode
):
2751 """explicitly moves srcstep/dststep on to next element, for
2752 "Vertical-First" mode. this function is called from
2753 setvl pseudo-code, as a pseudo-op "svstep"
2755 WARNING: this function uses information that was created EARLIER
2756 due to it being in the middle of a yield, but this function is
2757 *NOT* called from yield (it's called from compiled pseudocode).
2759 self
.allow_next_step_inc
= submode
.value
+ 1
2760 log("SVSTATE_NEXT mode", mode
, submode
, self
.allow_next_step_inc
)
2761 self
.svstate_next_mode
= mode
2762 if self
.svstate_next_mode
> 0 and self
.svstate_next_mode
< 5:
2763 shape_idx
= self
.svstate_next_mode
.value
-1
2764 return SelectableInt(self
.remap_idxs
[shape_idx
], 7)
2765 if self
.svstate_next_mode
== 5:
2766 self
.svstate_next_mode
= 0
2767 return SelectableInt(self
.svstate
.srcstep
, 7)
2768 if self
.svstate_next_mode
== 6:
2769 self
.svstate_next_mode
= 0
2770 return SelectableInt(self
.svstate
.dststep
, 7)
2771 if self
.svstate_next_mode
== 7:
2772 self
.svstate_next_mode
= 0
2773 return SelectableInt(self
.svstate
.ssubstep
, 7)
2774 if self
.svstate_next_mode
== 8:
2775 self
.svstate_next_mode
= 0
2776 return SelectableInt(self
.svstate
.dsubstep
, 7)
2777 return SelectableInt(0, 7)
2779 def get_src_dststeps(self
):
2780 """gets srcstep, dststep, and ssubstep, dsubstep
2782 return (self
.new_srcstep
, self
.new_dststep
,
2783 self
.new_ssubstep
, self
.new_dsubstep
)
2785 def update_svstate_namespace(self
, overwrite_svstate
=True):
2786 if overwrite_svstate
:
2787 # note, do not get the bit-reversed srcstep here!
2788 srcstep
, dststep
= self
.new_srcstep
, self
.new_dststep
2789 ssubstep
, dsubstep
= self
.new_ssubstep
, self
.new_dsubstep
2791 # update SVSTATE with new srcstep
2792 self
.svstate
.srcstep
= srcstep
2793 self
.svstate
.dststep
= dststep
2794 self
.svstate
.ssubstep
= ssubstep
2795 self
.svstate
.dsubstep
= dsubstep
2796 self
.namespace
['SVSTATE'] = self
.svstate
2797 yield self
.dec2
.state
.svstate
.eq(self
.svstate
.value
)
2798 yield Settle() # let decoder update
2800 def update_new_svstate_steps(self
, overwrite_svstate
=True):
2801 yield from self
.update_svstate_namespace(overwrite_svstate
)
2802 srcstep
= self
.svstate
.srcstep
2803 dststep
= self
.svstate
.dststep
2804 ssubstep
= self
.svstate
.ssubstep
2805 dsubstep
= self
.svstate
.dsubstep
2806 pack
= self
.svstate
.pack
2807 unpack
= self
.svstate
.unpack
2808 vl
= self
.svstate
.vl
2809 sv_mode
= yield self
.dec2
.rm_dec
.sv_mode
2810 subvl
= yield self
.dec2
.rm_dec
.rm_in
.subvl
2811 rm_mode
= yield self
.dec2
.rm_dec
.mode
2812 ff_inv
= yield self
.dec2
.rm_dec
.inv
2813 cr_bit
= yield self
.dec2
.rm_dec
.cr_sel
2814 log(" srcstep", srcstep
)
2815 log(" dststep", dststep
)
2817 log(" unpack", unpack
)
2818 log(" ssubstep", ssubstep
)
2819 log(" dsubstep", dsubstep
)
2821 log(" subvl", subvl
)
2822 log(" rm_mode", rm_mode
)
2823 log(" sv_mode", sv_mode
)
2825 log(" cr_bit", cr_bit
)
2827 # check if end reached (we let srcstep overrun, above)
2828 # nothing needs doing (TODO zeroing): just do next instruction
2831 return ((ssubstep
== subvl
and srcstep
== vl
) or
2832 (dsubstep
== subvl
and dststep
== vl
))
2834 def svstate_post_inc(self
, insn_name
, vf
=0):
2835 # check if SV "Vertical First" mode is enabled
2836 vfirst
= self
.svstate
.vfirst
2837 log(" SV Vertical First", vf
, vfirst
)
2838 if not vf
and vfirst
== 1:
2839 if insn_name
.startswith("sv.bc"):
2840 self
.update_pc_next()
2845 # check if it is the SVSTATE.src/dest step that needs incrementing
2846 # this is our Sub-Program-Counter loop from 0 to VL-1
2847 # XXX twin predication TODO
2848 vl
= self
.svstate
.vl
2849 subvl
= yield self
.dec2
.rm_dec
.rm_in
.subvl
2850 mvl
= self
.svstate
.maxvl
2851 srcstep
= self
.svstate
.srcstep
2852 dststep
= self
.svstate
.dststep
2853 ssubstep
= self
.svstate
.ssubstep
2854 dsubstep
= self
.svstate
.dsubstep
2855 pack
= self
.svstate
.pack
2856 unpack
= self
.svstate
.unpack
2857 rm_mode
= yield self
.dec2
.rm_dec
.mode
2858 reverse_gear
= yield self
.dec2
.rm_dec
.reverse_gear
2859 sv_ptype
= yield self
.dec2
.dec
.op
.SV_Ptype
2860 out_vec
= not (yield self
.dec2
.no_out_vec
)
2861 in_vec
= not (yield self
.dec2
.no_in_vec
)
2862 log(" svstate.vl", vl
)
2863 log(" svstate.mvl", mvl
)
2864 log(" rm.subvl", subvl
)
2865 log(" svstate.srcstep", srcstep
)
2866 log(" svstate.dststep", dststep
)
2867 log(" svstate.ssubstep", ssubstep
)
2868 log(" svstate.dsubstep", dsubstep
)
2869 log(" svstate.pack", pack
)
2870 log(" svstate.unpack", unpack
)
2871 log(" mode", rm_mode
)
2872 log(" reverse", reverse_gear
)
2873 log(" out_vec", out_vec
)
2874 log(" in_vec", in_vec
)
2875 log(" sv_ptype", sv_ptype
, sv_ptype
== SVPType
.P2
.value
)
2876 # check if this was an sv.bc* and if so did it succeed
2877 if self
.is_svp64_mode
and insn_name
.startswith("sv.bc"):
2878 end_loop
= self
.namespace
['end_loop']
2879 log("branch %s end_loop" % insn_name
, end_loop
)
2881 self
.svp64_reset_loop()
2882 self
.update_pc_next()
2884 # check if srcstep needs incrementing by one, stop PC advancing
2885 # but for 2-pred both src/dest have to be checked.
2886 # XXX this might not be true! it may just be LD/ST
2887 if sv_ptype
== SVPType
.P2
.value
:
2888 svp64_is_vector
= (out_vec
or in_vec
)
2890 svp64_is_vector
= out_vec
2891 # loops end at the first "hit" (source or dest)
2892 yield from self
.advance_svstate_steps()
2893 loopend
= self
.loopend
2894 log("loopend", svp64_is_vector
, loopend
)
2895 if not svp64_is_vector
or loopend
:
2896 # reset loop to zero and update NIA
2897 self
.svp64_reset_loop()
2902 # still looping, advance and update NIA
2903 self
.namespace
['SVSTATE'] = self
.svstate
2905 # not an SVP64 branch, so fix PC (NIA==CIA) for next loop
2906 # (by default, NIA is CIA+4 if v3.0B or CIA+8 if SVP64)
2907 # this way we keep repeating the same instruction (with new steps)
2908 self
.pc
.NIA
.eq(self
.pc
.CIA
)
2909 self
.namespace
['NIA'] = self
.pc
.NIA
2910 log("end of sub-pc call", self
.namespace
['CIA'], self
.namespace
['NIA'])
2911 return False # DO NOT allow PC update whilst Sub-PC loop running
2913 def update_pc_next(self
):
2914 # UPDATE program counter
2915 self
.pc
.update(self
.namespace
, self
.is_svp64_mode
)
2916 #self.svstate.spr = self.namespace['SVSTATE']
2917 log("end of call", self
.namespace
['CIA'],
2918 self
.namespace
['NIA'],
2919 self
.namespace
['SVSTATE'])
2921 def svp64_reset_loop(self
):
2922 self
.svstate
.srcstep
= 0
2923 self
.svstate
.dststep
= 0
2924 self
.svstate
.ssubstep
= 0
2925 self
.svstate
.dsubstep
= 0
2926 self
.loopend
= False
2927 log(" svstate.srcstep loop end (PC to update)")
2928 self
.namespace
['SVSTATE'] = self
.svstate
2930 def update_nia(self
):
2931 self
.pc
.update_nia(self
.is_svp64_mode
)
2932 self
.namespace
['NIA'] = self
.pc
.NIA
2936 """Decorator factory.
2938 this decorator will "inject" variables into the function's namespace,
2939 from the *dictionary* in self.namespace. it therefore becomes possible
2940 to make it look like a whole stack of variables which would otherwise
2941 need "self." inserted in front of them (*and* for those variables to be
2942 added to the instance) "appear" in the function.
2944 "self.namespace['SI']" for example becomes accessible as just "SI" but
2945 *only* inside the function, when decorated.
2947 def variable_injector(func
):
2949 def decorator(*args
, **kwargs
):
2951 func_globals
= func
.__globals
__ # Python 2.6+
2952 except AttributeError:
2953 func_globals
= func
.func_globals
# Earlier versions.
2955 context
= args
[0].namespace
# variables to be injected
2956 saved_values
= func_globals
.copy() # Shallow copy of dict.
2957 log("globals before", context
.keys())
2958 func_globals
.update(context
)
2959 result
= func(*args
, **kwargs
)
2960 log("globals after", func_globals
['CIA'], func_globals
['NIA'])
2961 log("args[0]", args
[0].namespace
['CIA'],
2962 args
[0].namespace
['NIA'],
2963 args
[0].namespace
['SVSTATE'])
2964 if 'end_loop' in func_globals
:
2965 log("args[0] end_loop", func_globals
['end_loop'])
2966 args
[0].namespace
= func_globals
2967 #exec (func.__code__, func_globals)
2970 # func_globals = saved_values # Undo changes.
2976 return variable_injector