1 import collections
as _collections
3 import dataclasses
as _dataclasses
5 import functools
as _functools
6 import itertools
as _itertools
8 import operator
as _operator
9 import pathlib
as _pathlib
13 from functools
import cached_property
15 from cached_property
import cached_property
17 from openpower
.decoder
.power_enums
import (
18 Function
as _Function
,
25 CRIn2Sel
as _CRIn2Sel
,
26 CROutSel
as _CROutSel
,
28 LDSTMode
as _LDSTMode
,
33 SVmask_src
as _SVmask_src
,
38 SVExtraRegType
as _SVExtraRegType
,
39 SVExtraReg
as _SVExtraReg
,
41 from openpower
.decoder
.selectable_int
import (
42 SelectableInt
as _SelectableInt
,
43 selectconcat
as _selectconcat
,
45 from openpower
.decoder
.power_fields
import (
48 DecodeFields
as _DecodeFields
,
50 from openpower
.decoder
.pseudo
.pagereader
import ISA
as _ISA
53 @_functools.total_ordering
54 class Verbosity(_enum
.Enum
):
57 VERBOSE
= _enum
.auto()
59 def __lt__(self
, other
):
60 if not isinstance(other
, self
.__class
__):
62 return (self
.value
< other
.value
)
65 def dataclass(cls
, record
, keymap
=None, typemap
=None):
69 typemap
= {field
.name
:field
.type for field
in _dataclasses
.fields(cls
)}
71 def transform(key_value
):
72 (key
, value
) = key_value
73 key
= keymap
.get(key
, key
)
74 hook
= typemap
.get(key
, lambda value
: value
)
75 if hook
is bool and value
in ("", "0"):
81 record
= dict(map(transform
, record
.items()))
82 for key
in frozenset(record
.keys()):
89 @_functools.total_ordering
90 @_dataclasses.dataclass(eq
=True, frozen
=True)
93 def __new__(cls
, value
):
94 if isinstance(value
, str):
96 if not isinstance(value
, int):
97 raise ValueError(value
)
99 if value
.bit_length() > 64:
100 raise ValueError(value
)
102 return super().__new
__(cls
, value
)
105 return super().__repr
__()
108 return f
"{self:0{self.bit_length()}b}"
110 def bit_length(self
):
111 if super().bit_length() > 32:
115 class Value(Integer
):
124 def __lt__(self
, other
):
125 if not isinstance(other
, Opcode
):
126 return NotImplemented
127 return ((self
.value
, self
.mask
) < (other
.value
, other
.mask
))
129 def __post_init__(self
):
130 if self
.value
.bit_length() != self
.mask
.bit_length():
131 raise ValueError("bit length mismatch")
134 def pattern(value
, mask
, bit_length
):
135 for bit
in range(bit_length
):
136 if ((mask
& (1 << (bit_length
- bit
- 1))) == 0):
138 elif (value
& (1 << (bit_length
- bit
- 1))):
143 return "".join(pattern(self
.value
, self
.mask
, self
.value
.bit_length()))
146 class IntegerOpcode(Opcode
):
147 def __init__(self
, value
):
148 if value
.startswith("0b"):
149 mask
= int(("1" * len(value
[2:])), 2)
153 value
= Opcode
.Value(value
)
154 mask
= Opcode
.Mask(mask
)
156 return super().__init
__(value
=value
, mask
=mask
)
159 class PatternOpcode(Opcode
):
160 def __init__(self
, pattern
):
161 if not isinstance(pattern
, str):
162 raise ValueError(pattern
)
164 (value
, mask
) = (0, 0)
165 for symbol
in pattern
:
166 if symbol
not in {"0", "1", "-"}:
167 raise ValueError(pattern
)
168 value |
= (symbol
== "1")
169 mask |
= (symbol
!= "-")
175 value
= Opcode
.Value(value
)
176 mask
= Opcode
.Mask(mask
)
178 return super().__init
__(value
=value
, mask
=mask
)
181 @_dataclasses.dataclass(eq
=True, frozen
=True)
183 class FlagsMeta(type):
198 class Flags(frozenset, metaclass
=FlagsMeta
):
199 def __new__(cls
, flags
=frozenset()):
200 flags
= frozenset(flags
)
201 diff
= (flags
- frozenset(cls
))
203 raise ValueError(flags
)
204 return super().__new
__(cls
, flags
)
208 flags
: Flags
= Flags()
210 function
: _Function
= _Function
.NONE
211 intop
: _MicrOp
= _MicrOp
.OP_ILLEGAL
212 in1
: _In1Sel
= _In1Sel
.RA
213 in2
: _In2Sel
= _In2Sel
.NONE
214 in3
: _In3Sel
= _In3Sel
.NONE
215 out
: _OutSel
= _OutSel
.NONE
216 cr_in
: _CRInSel
= _CRInSel
.NONE
217 cr_in2
: _CRIn2Sel
= _CRIn2Sel
.NONE
218 cr_out
: _CROutSel
= _CROutSel
.NONE
219 cry_in
: _CryIn
= _CryIn
.ZERO
220 ldst_len
: _LDSTLen
= _LDSTLen
.NONE
221 upd
: _LDSTMode
= _LDSTMode
.NONE
222 Rc
: _RCOE
= _RCOE
.NONE
223 form
: _Form
= _Form
.NONE
225 unofficial
: bool = False
229 "internal op": "intop",
233 "ldst len": "ldst_len",
235 "CONDITIONS": "conditions",
238 def __lt__(self
, other
):
239 if not isinstance(other
, self
.__class
__):
240 return NotImplemented
241 lhs
= (self
.opcode
, self
.comment
)
242 rhs
= (other
.opcode
, other
.comment
)
246 def CSV(cls
, record
, opcode_cls
):
247 typemap
= {field
.name
:field
.type for field
in _dataclasses
.fields(cls
)}
248 typemap
["opcode"] = opcode_cls
250 if record
["CR in"] == "BA_BB":
251 record
["cr_in"] = "BA"
252 record
["cr_in2"] = "BB"
256 for flag
in frozenset(PPCRecord
.Flags
):
257 if bool(record
.pop(flag
, "")):
259 record
["flags"] = PPCRecord
.Flags(flags
)
261 return dataclass(cls
, record
,
262 keymap
=PPCRecord
.__KEYMAP
,
267 return frozenset(self
.comment
.split("=")[-1].split("/"))
270 class PPCMultiRecord(tuple):
271 def __getattr__(self
, attr
):
273 raise AttributeError(attr
)
274 return getattr(self
[0], attr
)
277 @_dataclasses.dataclass(eq
=True, frozen
=True)
279 class ExtraMap(tuple):
281 @_dataclasses.dataclass(eq
=True, frozen
=True)
283 regtype
: _SVExtraRegType
= _SVExtraRegType
.NONE
284 reg
: _SVExtraReg
= _SVExtraReg
.NONE
287 return f
"{self.regtype.value}:{self.reg.name}"
289 def __new__(cls
, value
="0"):
290 if isinstance(value
, str):
291 def transform(value
):
292 (regtype
, reg
) = value
.split(":")
293 regtype
= _SVExtraRegType(regtype
)
294 reg
= _SVExtraReg(reg
)
295 return cls
.Entry(regtype
=regtype
, reg
=reg
)
300 value
= map(transform
, value
.split(";"))
302 return super().__new
__(cls
, value
)
305 return repr(list(self
))
307 def __new__(cls
, value
=tuple()):
311 return super().__new
__(cls
, map(cls
.Extra
, value
))
314 return repr({index
:self
[index
] for index
in range(0, 4)})
317 ptype
: _SVPtype
= _SVPtype
.NONE
318 etype
: _SVEtype
= _SVEtype
.NONE
319 msrc
: _SVmask_src
= _SVmask_src
.NO
# MASK_SRC is active
320 in1
: _In1Sel
= _In1Sel
.NONE
321 in2
: _In2Sel
= _In2Sel
.NONE
322 in3
: _In3Sel
= _In3Sel
.NONE
323 out
: _OutSel
= _OutSel
.NONE
324 out2
: _OutSel
= _OutSel
.NONE
325 cr_in
: _CRInSel
= _CRInSel
.NONE
326 cr_in2
: _CRIn2Sel
= _CRIn2Sel
.NONE
327 cr_out
: _CROutSel
= _CROutSel
.NONE
328 extra
: ExtraMap
= ExtraMap()
330 mode
: _SVMode
= _SVMode
.NORMAL
334 "CONDITIONS": "conditions",
343 def CSV(cls
, record
):
344 for key
in frozenset({
345 "in1", "in2", "in3", "CR in",
346 "out", "out2", "CR out",
352 if record
["CR in"] == "BA_BB":
353 record
["cr_in"] = "BA"
354 record
["cr_in2"] = "BB"
358 for idx
in range(0, 4):
359 extra
.append(record
.pop(f
"{idx}"))
361 record
["extra"] = cls
.ExtraMap(extra
)
363 return dataclass(cls
, record
, keymap
=cls
.__KEYMAP
)
365 @_functools.lru_cache(maxsize
=None)
366 def extra_idx(self
, key
):
374 if key
not in frozenset({
375 "in1", "in2", "in3", "cr_in", "cr_in2",
376 "out", "out2", "cr_out",
380 sel
= getattr(self
, key
)
381 if sel
is _CRInSel
.BA_BB
:
382 return _SVExtra
.Idx_1_2
383 reg
= _SVExtraReg(sel
)
384 if reg
is _SVExtraReg
.NONE
:
388 _SVExtraRegType
.SRC
: {},
389 _SVExtraRegType
.DST
: {},
391 for index
in range(0, 4):
392 for entry
in self
.extra
[index
]:
393 extra_map
[entry
.regtype
][entry
.reg
] = extra_idx
[index
]
395 for regtype
in (_SVExtraRegType
.SRC
, _SVExtraRegType
.DST
):
396 extra
= extra_map
[regtype
].get(reg
, _SVExtra
.NONE
)
397 if extra
is not _SVExtra
.NONE
:
402 extra_idx_in1
= property(_functools
.partial(extra_idx
, key
="in1"))
403 extra_idx_in2
= property(_functools
.partial(extra_idx
, key
="in2"))
404 extra_idx_in3
= property(_functools
.partial(extra_idx
, key
="in3"))
405 extra_idx_out
= property(_functools
.partial(extra_idx
, key
="out"))
406 extra_idx_out2
= property(_functools
.partial(extra_idx
, key
="out2"))
407 extra_idx_cr_in
= property(_functools
.partial(extra_idx
, key
="cr_in"))
408 extra_idx_cr_in2
= property(_functools
.partial(extra_idx
, key
="cr_in2"))
409 extra_idx_cr_out
= property(_functools
.partial(extra_idx
, key
="cr_out"))
411 @_functools.lru_cache(maxsize
=None)
412 def extra_reg(self
, key
):
413 return _SVExtraReg(getattr(self
, key
))
415 extra_reg_in1
= property(_functools
.partial(extra_reg
, key
="in1"))
416 extra_reg_in2
= property(_functools
.partial(extra_reg
, key
="in2"))
417 extra_reg_in3
= property(_functools
.partial(extra_reg
, key
="in3"))
418 extra_reg_out
= property(_functools
.partial(extra_reg
, key
="out"))
419 extra_reg_out2
= property(_functools
.partial(extra_reg
, key
="out2"))
420 extra_reg_cr_in
= property(_functools
.partial(extra_reg
, key
="cr_in"))
421 extra_reg_cr_in2
= property(_functools
.partial(extra_reg
, key
="cr_in2"))
422 extra_reg_cr_out
= property(_functools
.partial(extra_reg
, key
="cr_out"))
426 def __init__(self
, value
=(0, 32)):
427 if isinstance(value
, str):
428 (start
, end
) = map(int, value
.split(":"))
431 if start
< 0 or end
< 0 or start
>= end
:
432 raise ValueError(value
)
437 return super().__init
__()
440 return f
"[{self.__start}:{self.__end}]"
443 yield from range(self
.start
, (self
.end
+ 1))
445 def __reversed__(self
):
446 return tuple(reversed(tuple(self
)))
457 @_dataclasses.dataclass(eq
=True, frozen
=True)
459 class Mode(_enum
.Enum
):
460 INTEGER
= _enum
.auto()
461 PATTERN
= _enum
.auto()
464 def _missing_(cls
, value
):
465 if isinstance(value
, str):
466 return cls
[value
.upper()]
467 return super()._missing
_(value
)
470 def __new__(cls
, value
=None):
471 if isinstance(value
, str):
472 if value
.upper() == "NONE":
475 value
= int(value
, 0)
479 return super().__new
__(cls
, value
)
485 return (bin(self
) if self
else "None")
491 opcode
: IntegerOpcode
= None
494 def CSV(cls
, record
):
495 typemap
= {field
.name
:field
.type for field
in _dataclasses
.fields(cls
)}
496 if record
["opcode"] == "NONE":
497 typemap
["opcode"] = lambda _
: None
499 return dataclass(cls
, record
, typemap
=typemap
)
503 def __init__(self
, items
):
504 if isinstance(items
, dict):
505 items
= items
.items()
508 (name
, bitrange
) = item
509 return (name
, tuple(bitrange
.values()))
511 self
.__mapping
= dict(map(transform
, items
))
513 return super().__init
__()
516 return repr(self
.__mapping
)
519 yield from self
.__mapping
.items()
521 def __contains__(self
, key
):
522 return self
.__mapping
.__contains
__(key
)
524 def __getitem__(self
, key
):
525 return self
.__mapping
.get(key
, None)
528 @_dataclasses.dataclass(eq
=True, frozen
=True)
532 def span(self
, record
):
533 return record
.fields
[self
.name
]
535 def disassemble(self
, insn
, record
,
536 verbosity
=Verbosity
.NORMAL
, indent
=""):
537 raise NotImplementedError
540 class DynamicOperand(Operand
):
541 def disassemble(self
, insn
, record
,
542 verbosity
=Verbosity
.NORMAL
, indent
=""):
543 span
= self
.span(record
=record
)
544 if isinstance(insn
, SVP64Instruction
):
545 span
= tuple(map(lambda bit
: (bit
+ 32), span
))
548 if verbosity
>= Verbosity
.VERBOSE
:
549 span
= map(str, span
)
550 yield f
"{indent}{self.name}"
551 yield f
"{indent}{indent}{int(value):0{value.bits}b}"
552 yield f
"{indent}{indent}{', '.join(span)}"
554 yield str(int(value
))
557 class SignedOperand(DynamicOperand
):
558 def disassemble(self
, insn
, record
,
559 verbosity
=Verbosity
.NORMAL
, indent
=""):
560 span
= self
.span(record
=record
)
561 if isinstance(insn
, SVP64Instruction
):
562 span
= tuple(map(lambda bit
: (bit
+ 32), span
))
565 if verbosity
>= Verbosity
.VERBOSE
:
566 span
= map(str, span
)
567 yield f
"{indent}{self.name}"
568 yield f
"{indent}{indent}{int(value):0{value.bits}b}"
569 yield f
"{indent}{indent}{', '.join(span)}"
571 yield str(value
.to_signed_int())
574 @_dataclasses.dataclass(eq
=True, frozen
=True)
575 class StaticOperand(Operand
):
578 def disassemble(self
, insn
, record
,
579 verbosity
=Verbosity
.NORMAL
, indent
=""):
580 span
= self
.span(record
=record
)
581 if isinstance(insn
, SVP64Instruction
):
582 span
= tuple(map(lambda bit
: (bit
+ 32), span
))
585 if verbosity
>= Verbosity
.VERBOSE
:
586 span
= map(str, span
)
587 yield f
"{indent}{self.name}"
588 yield f
"{indent}{indent}{int(value):0{value.bits}b}"
589 yield f
"{indent}{indent}{', '.join(span)}"
591 yield str(int(value
))
594 class ImmediateOperand(DynamicOperand
):
598 class NonZeroOperand(DynamicOperand
):
599 def disassemble(self
, insn
, record
,
600 verbosity
=Verbosity
.NORMAL
, indent
=""):
601 span
= self
.span(record
=record
)
602 if isinstance(insn
, SVP64Instruction
):
603 span
= tuple(map(lambda bit
: (bit
+ 32), span
))
606 if verbosity
>= Verbosity
.VERBOSE
:
607 span
= map(str, span
)
608 yield f
"{indent}{self.name}"
609 yield f
"{indent}{indent}{int(value):0{value.bits}b}"
610 yield f
"{indent}{indent}{', '.join(span)}"
612 yield str(int(value
) + 1)
615 class RegisterOperand(DynamicOperand
):
616 def sv_spec_enter(self
, value
, span
):
619 def sv_spec_leave(self
, value
, span
, origin_value
, origin_span
):
622 def spec(self
, insn
, record
):
624 span
= self
.span(record
=record
)
625 if isinstance(insn
, SVP64Instruction
):
626 span
= tuple(map(lambda bit
: (bit
+ 32), span
))
628 span
= tuple(map(str, span
))
630 if isinstance(insn
, SVP64Instruction
):
631 (origin_value
, origin_span
) = (value
, span
)
632 (value
, span
) = self
.sv_spec_enter(value
=value
, span
=span
)
634 extra_idx
= self
.extra_idx(record
=record
)
635 if extra_idx
is _SVExtra
.NONE
:
636 return (vector
, value
, span
)
638 if record
.etype
is _SVEtype
.EXTRA3
:
639 spec
= insn
.prefix
.rm
.extra3
[extra_idx
]
640 elif record
.etype
is _SVEtype
.EXTRA2
:
641 spec
= insn
.prefix
.rm
.extra2
[extra_idx
]
643 raise ValueError(record
.etype
)
646 vector
= bool(spec
[0])
647 spec_span
= spec
.__class
__
648 if record
.etype
is _SVEtype
.EXTRA3
:
649 spec_span
= tuple(map(str, spec_span
[1, 2]))
651 elif record
.etype
is _SVEtype
.EXTRA2
:
652 spec_span
= tuple(map(str, spec_span
[1,]))
653 spec
= _SelectableInt(value
=spec
[1].value
, bits
=2)
656 spec_span
= (spec_span
+ ("{0}",))
658 spec_span
= (("{0}",) + spec_span
)
660 raise ValueError(record
.etype
)
662 vector_shift
= (2 + (5 - value
.bits
))
663 scalar_shift
= value
.bits
664 spec_shift
= (5 - value
.bits
)
666 bits
= (len(span
) + len(spec_span
))
667 value
= _SelectableInt(value
=value
.value
, bits
=bits
)
668 spec
= _SelectableInt(value
=spec
.value
, bits
=bits
)
670 value
= ((value
<< vector_shift
) |
(spec
<< spec_shift
))
671 span
= (span
+ spec_span
+ ((spec_shift
* ("{0}",))))
673 value
= ((spec
<< scalar_shift
) | value
)
674 span
= ((spec_shift
* ("{0}",)) + spec_span
+ span
)
676 (value
, span
) = self
.sv_spec_leave(value
=value
, span
=span
,
677 origin_value
=origin_value
, origin_span
=origin_span
)
679 return (vector
, value
, span
)
683 return _SVExtraReg(self
.name
)
685 def extra_idx(self
, record
):
686 for key
in frozenset({
687 "in1", "in2", "in3", "cr_in", "cr_in2",
688 "out", "out2", "cr_out",
690 extra_reg
= record
.svp64
.extra_reg(key
=key
)
691 if extra_reg
is self
.extra_reg
:
692 return record
.extra_idx(key
=key
)
696 def disassemble(self
, insn
, record
,
697 verbosity
=Verbosity
.NORMAL
, prefix
="", indent
=""):
698 (vector
, value
, span
) = self
.spec(insn
=insn
, record
=record
)
700 if verbosity
>= Verbosity
.VERBOSE
:
701 mode
= "vector" if vector
else "scalar"
702 yield f
"{indent}{self.name} ({mode})"
703 yield f
"{indent}{indent}{int(value):0{value.bits}b}"
704 yield f
"{indent}{indent}{', '.join(span)}"
705 if isinstance(insn
, SVP64Instruction
):
706 extra_idx
= self
.extra_idx(record
)
707 if record
.etype
is _SVEtype
.NONE
:
708 yield f
"{indent}{indent}extra[none]"
710 etype
= repr(record
.etype
).lower()
711 yield f
"{indent}{indent}{etype}{extra_idx!r}"
713 vector
= "*" if vector
else ""
714 yield f
"{vector}{prefix}{int(value)}"
717 class GPROperand(RegisterOperand
):
718 def disassemble(self
, insn
, record
,
719 verbosity
=Verbosity
.NORMAL
, indent
=""):
720 prefix
= "" if (verbosity
<= Verbosity
.SHORT
) else "r"
721 yield from super().disassemble(prefix
=prefix
,
722 insn
=insn
, record
=record
,
723 verbosity
=verbosity
, indent
=indent
)
726 class FPROperand(RegisterOperand
):
727 def disassemble(self
, insn
, record
,
728 verbosity
=Verbosity
.NORMAL
, indent
=""):
729 prefix
= "" if (verbosity
<= Verbosity
.SHORT
) else "f"
730 yield from super().disassemble(prefix
=prefix
,
731 insn
=insn
, record
=record
,
732 verbosity
=verbosity
, indent
=indent
)
735 class CR3Operand(RegisterOperand
):
739 class CR5Operand(RegisterOperand
):
740 def sv_spec_enter(self
, value
, span
):
741 value
= _SelectableInt(value
=(value
.value
>> 2), bits
=3)
744 def sv_spec_leave(self
, value
, span
, origin_value
, origin_span
):
745 value
= _selectconcat(value
, origin_value
[3:5])
750 class TargetAddrOperand(RegisterOperand
):
751 def disassemble(self
, insn
, record
, field
,
752 verbosity
=Verbosity
.NORMAL
, indent
=""):
753 span
= self
.span(record
=record
)
754 if isinstance(insn
, SVP64Instruction
):
755 span
= tuple(map(lambda bit
: (bit
+ 32), span
))
758 if verbosity
>= Verbosity
.VERBOSE
:
759 span
= (tuple(map(str, span
)) + ("{0}", "{0}"))
760 yield f
"{indent}{self.name} = EXTS({field} || 0b00))"
761 yield f
"{indent}{indent}{field}"
762 yield f
"{indent}{indent}{indent}{int(value):0{value.bits}b}00"
763 yield f
"{indent}{indent}{indent}{', '.join(span)}"
765 yield hex(_selectconcat(value
,
766 _SelectableInt(value
=0b00, bits
=2)).to_signed_int())
769 class TargetAddrOperandLI(TargetAddrOperand
):
770 def span(self
, record
):
771 return record
.fields
["LI"]
773 def disassemble(self
, insn
, record
,
774 verbosity
=Verbosity
.NORMAL
, indent
=""):
775 return super().disassemble(field
="LI",
776 insn
=insn
, record
=record
,
777 verbosity
=verbosity
, indent
=indent
)
780 class TargetAddrOperandBD(TargetAddrOperand
):
781 def span(self
, record
):
782 return record
.fields
["BD"]
784 def disassemble(self
, insn
, record
,
785 verbosity
=Verbosity
.NORMAL
, indent
=""):
786 return super().disassemble(field
="BD",
787 insn
=insn
, record
=record
,
788 verbosity
=verbosity
, indent
=indent
)
791 class DOperandDX(SignedOperand
):
792 def span(self
, record
):
793 operands
= map(DynamicOperand
, ("d0", "d1", "d2"))
794 spans
= map(lambda operand
: operand
.span(record
=record
), operands
)
795 return sum(spans
, tuple())
797 def disassemble(self
, insn
, record
,
798 verbosity
=Verbosity
.NORMAL
, indent
=""):
799 span
= self
.span(record
=record
)
800 if isinstance(insn
, SVP64Instruction
):
801 span
= tuple(map(lambda bit
: (bit
+ 32), span
))
804 if verbosity
>= Verbosity
.VERBOSE
:
811 for (subname
, subspan
) in mapping
.items():
812 operand
= DynamicOperand(name
=subname
)
813 span
= operand
.span(record
=record
)
814 if isinstance(insn
, SVP64Instruction
):
815 span
= tuple(map(lambda bit
: (bit
+ 32), span
))
817 span
= map(str, span
)
818 yield f
"{indent}{indent}{operand.name} = D{subspan}"
819 yield f
"{indent}{indent}{indent}{int(value):0{value.bits}b}"
820 yield f
"{indent}{indent}{indent}{', '.join(span)}"
822 yield str(value
.to_signed_int())
825 class Operands(tuple):
826 def __new__(cls
, insn
, iterable
):
828 "b": {"target_addr": TargetAddrOperandLI
},
829 "ba": {"target_addr": TargetAddrOperandLI
},
830 "bl": {"target_addr": TargetAddrOperandLI
},
831 "bla": {"target_addr": TargetAddrOperandLI
},
832 "bc": {"target_addr": TargetAddrOperandBD
},
833 "bca": {"target_addr": TargetAddrOperandBD
},
834 "bcl": {"target_addr": TargetAddrOperandBD
},
835 "bcla": {"target_addr": TargetAddrOperandBD
},
836 "addpcis": {"D": DOperandDX
},
837 "fishmv": {"D": DOperandDX
},
838 "fmvis": {"D": DOperandDX
},
841 "SVi": NonZeroOperand
,
842 "SVd": NonZeroOperand
,
843 "SVxd": NonZeroOperand
,
844 "SVyd": NonZeroOperand
,
845 "SVzd": NonZeroOperand
,
853 "SIM": SignedOperand
,
854 "SVD": SignedOperand
,
855 "SVDS": SignedOperand
,
859 for operand
in iterable
:
860 dynamic_cls
= DynamicOperand
861 static_cls
= StaticOperand
864 (name
, value
) = operand
.split("=")
865 operand
= static_cls(name
=name
, value
=int(value
))
866 operands
.append(operand
)
868 if operand
.endswith(")"):
869 operand
= operand
.replace("(", " ").replace(")", "")
870 (immediate
, _
, operand
) = operand
.partition(" ")
874 if immediate
is not None:
875 operands
.append(ImmediateOperand(name
=immediate
))
877 if operand
in custom_fields
:
878 dynamic_cls
= custom_fields
[operand
]
879 if insn
in custom_insns
and operand
in custom_insns
[insn
]:
880 dynamic_cls
= custom_insns
[insn
][operand
]
882 if operand
in _RegType
.__members
__:
883 regtype
= _RegType
[operand
]
884 if regtype
is _RegType
.GPR
:
885 dynamic_cls
= GPROperand
886 elif regtype
is _RegType
.FPR
:
887 dynamic_cls
= FPROperand
888 if regtype
is _RegType
.CR_BIT
: # 5-bit
889 dynamic_cls
= CR5Operand
890 if regtype
is _RegType
.CR_REG
: # actually CR Field, 3-bit
891 dynamic_cls
= CR3Operand
893 operand
= dynamic_cls(name
=operand
)
894 operands
.append(operand
)
896 return super().__new
__(cls
, operands
)
898 def __contains__(self
, key
):
899 return self
.__getitem
__(key
) is not None
901 def __getitem__(self
, key
):
903 if operand
.name
== key
:
911 if isinstance(operand
, DynamicOperand
):
917 if isinstance(operand
, StaticOperand
):
922 def __init__(self
, iterable
):
923 self
.__pcode
= tuple(iterable
)
924 return super().__init
__()
927 yield from self
.__pcode
930 return self
.__pcode
.__repr
__()
933 @_dataclasses.dataclass(eq
=True, frozen
=True)
934 class MarkdownRecord
:
939 @_functools.total_ordering
940 @_dataclasses.dataclass(eq
=True, frozen
=True)
947 svp64
: SVP64Record
= None
949 def __lt__(self
, other
):
950 if not isinstance(other
, Record
):
951 return NotImplemented
952 lhs
= (min(self
.opcodes
), self
.name
)
953 rhs
= (min(other
.opcodes
), other
.name
)
962 PO
= self
.section
.opcode
964 for (src
, dst
) in enumerate(reversed(BitSel((0, 5)))):
965 value
[dst
] = int((PO
.value
& (1 << src
)) != 0)
966 mask
[dst
] = int((PO
.mask
& (1 << src
)) != 0)
969 for (src
, dst
) in enumerate(reversed(self
.section
.bitsel
)):
970 value
[dst
] = int((XO
.value
& (1 << src
)) != 0)
971 mask
[dst
] = int((XO
.mask
& (1 << src
)) != 0)
973 for operand
in self
.mdwn
.operands
.static
:
974 for (src
, dst
) in enumerate(reversed(operand
.span(record
=self
))):
975 value
[dst
] = int((operand
.value
& (1 << src
)) != 0)
978 value
= Opcode
.Value(int(("".join(map(str, value
))), 2))
979 mask
= Opcode
.Mask(int(("".join(map(str, mask
))), 2))
981 return Opcode(value
=value
, mask
=mask
)
983 return tuple(sorted(map(opcode
, self
.ppc
)))
985 def match(self
, key
):
986 for opcode
in self
.opcodes
:
987 if ((opcode
.value
& opcode
.mask
) ==
988 (key
& opcode
.mask
)):
994 return self
.svp64
.mode
1014 if self
.svp64
is None:
1020 return self
.ppc
.cr_in
1024 return self
.ppc
.cr_in2
1028 return self
.ppc
.cr_out
1030 ptype
= property(lambda self
: self
.svp64
.ptype
)
1031 etype
= property(lambda self
: self
.svp64
.etype
)
1033 def extra_idx(self
, key
):
1034 return self
.svp64
.extra_idx(key
)
1036 extra_idx_in1
= property(lambda self
: self
.svp64
.extra_idx_in1
)
1037 extra_idx_in2
= property(lambda self
: self
.svp64
.extra_idx_in2
)
1038 extra_idx_in3
= property(lambda self
: self
.svp64
.extra_idx_in3
)
1039 extra_idx_out
= property(lambda self
: self
.svp64
.extra_idx_out
)
1040 extra_idx_out2
= property(lambda self
: self
.svp64
.extra_idx_out2
)
1041 extra_idx_cr_in
= property(lambda self
: self
.svp64
.extra_idx_cr_in
)
1042 extra_idx_cr_in2
= property(lambda self
: self
.svp64
.extra_idx_cr_in2
)
1043 extra_idx_cr_out
= property(lambda self
: self
.svp64
.extra_idx_cr_out
)
1047 Rc
= self
.mdwn
.operands
["Rc"]
1050 return bool(Rc
.value
)
1052 class Instruction(_Mapping
):
1054 def integer(cls
, value
=0, bits
=None, byteorder
="little"):
1055 if isinstance(value
, (int, bytes
)) and not isinstance(bits
, int):
1056 raise ValueError(bits
)
1058 if isinstance(value
, bytes
):
1059 if ((len(value
) * 8) != bits
):
1060 raise ValueError(f
"bit length mismatch")
1061 value
= int.from_bytes(value
, byteorder
=byteorder
)
1063 if isinstance(value
, int):
1064 value
= _SelectableInt(value
=value
, bits
=bits
)
1065 elif isinstance(value
, Instruction
):
1066 value
= value
.storage
1068 if not isinstance(value
, _SelectableInt
):
1069 raise ValueError(value
)
1072 if len(value
) != bits
:
1073 raise ValueError(value
)
1075 value
= _SelectableInt(value
=value
, bits
=bits
)
1077 return cls(storage
=value
)
1080 return hash(int(self
))
1082 def __getitem__(self
, key
):
1083 return self
.storage
.__getitem
__(key
)
1085 def __setitem__(self
, key
, value
):
1086 return self
.storage
.__setitem
__(key
, value
)
1088 def bytes(self
, byteorder
="little"):
1089 nr_bytes
= (self
.storage
.bits
// 8)
1090 return int(self
).to_bytes(nr_bytes
, byteorder
=byteorder
)
1092 def record(self
, db
):
1095 raise KeyError(self
)
1098 def spec(self
, db
, prefix
):
1099 record
= self
.record(db
=db
)
1101 dynamic_operands
= tuple(map(_operator
.itemgetter(0),
1102 self
.dynamic_operands(db
=db
)))
1104 static_operands
= []
1105 for (name
, value
) in self
.static_operands(db
=db
):
1106 static_operands
.append(f
"{name}={value}")
1109 if dynamic_operands
:
1111 operands
+= ",".join(dynamic_operands
)
1114 operands
+= " ".join(static_operands
)
1116 return f
"{prefix}{record.name}{operands}"
1118 def dynamic_operands(self
, db
, verbosity
=Verbosity
.NORMAL
):
1119 record
= self
.record(db
=db
)
1124 for operand
in record
.mdwn
.operands
.dynamic
:
1126 dis
= operand
.disassemble(insn
=self
, record
=record
,
1127 verbosity
=min(verbosity
, Verbosity
.NORMAL
))
1128 value
= " ".join(dis
)
1130 name
= f
"{imm_name}({name})"
1131 value
= f
"{imm_value}({value})"
1133 if isinstance(operand
, ImmediateOperand
):
1140 def static_operands(self
, db
):
1141 record
= self
.record(db
=db
)
1142 for operand
in record
.mdwn
.operands
.static
:
1143 yield (operand
.name
, operand
.value
)
1145 def disassemble(self
, db
,
1147 verbosity
=Verbosity
.NORMAL
):
1148 raise NotImplementedError
1151 class WordInstruction(Instruction
):
1152 _
: _Field
= range(0, 32)
1153 po
: _Field
= range(0, 6)
1156 def integer(cls
, value
, byteorder
="little"):
1157 return super().integer(bits
=32, value
=value
, byteorder
=byteorder
)
1162 for idx
in range(32):
1163 bit
= int(self
[idx
])
1165 return "".join(map(str, bits
))
1167 def disassemble(self
, db
,
1169 verbosity
=Verbosity
.NORMAL
):
1171 if verbosity
<= Verbosity
.SHORT
:
1174 blob
= integer
.to_bytes(length
=4, byteorder
=byteorder
)
1175 blob
= " ".join(map(lambda byte
: f
"{byte:02x}", blob
))
1180 yield f
"{blob}.long 0x{integer:08x}"
1183 operands
= tuple(map(_operator
.itemgetter(1),
1184 self
.dynamic_operands(db
=db
, verbosity
=verbosity
)))
1186 operands
= ",".join(operands
)
1187 yield f
"{blob}{record.name} {operands}"
1189 yield f
"{blob}{record.name}"
1191 if verbosity
>= Verbosity
.VERBOSE
:
1193 binary
= self
.binary
1194 spec
= self
.spec(db
=db
, prefix
="")
1195 yield f
"{indent}spec"
1196 yield f
"{indent}{indent}{spec}"
1197 yield f
"{indent}pcode"
1198 for stmt
in record
.mdwn
.pcode
:
1199 yield f
"{indent}{indent}{stmt}"
1200 yield f
"{indent}binary"
1201 yield f
"{indent}{indent}[0:8] {binary[0:8]}"
1202 yield f
"{indent}{indent}[8:16] {binary[8:16]}"
1203 yield f
"{indent}{indent}[16:24] {binary[16:24]}"
1204 yield f
"{indent}{indent}[24:32] {binary[24:32]}"
1205 yield f
"{indent}opcodes"
1206 for opcode
in record
.opcodes
:
1207 yield f
"{indent}{indent}{opcode!r}"
1208 for operand
in record
.mdwn
.operands
:
1209 yield from operand
.disassemble(insn
=self
, record
=record
,
1210 verbosity
=verbosity
, indent
=indent
)
1214 class PrefixedInstruction(Instruction
):
1215 class Prefix(WordInstruction
.remap(range(0, 32))):
1218 class Suffix(WordInstruction
.remap(range(32, 64))):
1221 _
: _Field
= range(64)
1227 def integer(cls
, value
, byteorder
="little"):
1228 return super().integer(bits
=64, value
=value
, byteorder
=byteorder
)
1231 def pair(cls
, prefix
=0, suffix
=0, byteorder
="little"):
1232 def transform(value
):
1233 return WordInstruction
.integer(value
=value
,
1234 byteorder
=byteorder
)[0:32]
1236 (prefix
, suffix
) = map(transform
, (prefix
, suffix
))
1237 value
= _selectconcat(prefix
, suffix
)
1239 return super().integer(bits
=64, value
=value
)
1242 class Mode(_Mapping
):
1243 _
: _Field
= range(0, 5)
1246 class Extra(_Mapping
):
1247 _
: _Field
= range(0, 9)
1250 class Extra2(Extra
):
1251 idx0
: _Field
= range(0, 2)
1252 idx1
: _Field
= range(2, 4)
1253 idx2
: _Field
= range(4, 6)
1254 idx3
: _Field
= range(6, 8)
1256 def __getitem__(self
, key
):
1262 _SVExtra
.Idx0
: self
.idx0
,
1263 _SVExtra
.Idx1
: self
.idx1
,
1264 _SVExtra
.Idx2
: self
.idx2
,
1265 _SVExtra
.Idx3
: self
.idx3
,
1268 def __setitem__(self
, key
, value
):
1269 self
[key
].assign(value
)
1272 class Extra3(Extra
):
1273 idx0
: _Field
= range(0, 3)
1274 idx1
: _Field
= range(3, 6)
1275 idx2
: _Field
= range(6, 9)
1277 def __getitem__(self
, key
):
1282 _SVExtra
.Idx0
: self
.idx0
,
1283 _SVExtra
.Idx1
: self
.idx1
,
1284 _SVExtra
.Idx2
: self
.idx2
,
1287 def __setitem__(self
, key
, value
):
1288 self
[key
].assign(value
)
1291 class BaseRM(_Mapping
):
1292 _
: _Field
= range(24)
1293 mmode
: _Field
= (0,)
1294 mask
: _Field
= range(1, 4)
1295 elwidth
: _Field
= range(4, 6)
1296 ewsrc
: _Field
= range(6, 8)
1297 subvl
: _Field
= range(8, 10)
1298 mode
: Mode
.remap(range(19, 24))
1299 smask
: _Field
= range(16, 19)
1300 extra
: Extra
.remap(range(10, 19))
1301 extra2
: Extra2
.remap(range(10, 19))
1302 extra3
: Extra3
.remap(range(10, 19))
1304 def specifiers(self
, record
):
1305 subvl
= int(self
.subvl
)
1313 def disassemble(self
, verbosity
=Verbosity
.NORMAL
):
1314 if verbosity
>= Verbosity
.VERBOSE
:
1316 for (name
, span
) in self
.traverse(path
="RM"):
1317 value
= self
.storage
[span
]
1319 yield f
"{indent}{int(value):0{value.bits}b}"
1320 yield f
"{indent}{', '.join(map(str, span))}"
1323 class FFPRRc1BaseRM(BaseRM
):
1324 def specifiers(self
, record
, mode
):
1325 inv
= _SelectableInt(value
=int(self
.inv
), bits
=1)
1326 CR
= _SelectableInt(value
=int(self
.CR
), bits
=2)
1327 mask
= int(_selectconcat(CR
, inv
))
1328 predicate
= PredicateBaseRM
.predicate(True, mask
)
1329 yield f
"{mode}={predicate}"
1331 yield from super().specifiers(record
=record
)
1334 class FFPRRc0BaseRM(BaseRM
):
1335 def specifiers(self
, record
, mode
):
1337 inv
= "~" if self
.inv
else ""
1338 yield f
"{mode}={inv}RC1"
1340 yield from super().specifiers(record
=record
)
1343 class SatBaseRM(BaseRM
):
1344 def specifiers(self
, record
):
1350 yield from super().specifiers(record
=record
)
1353 class ZZBaseRM(BaseRM
):
1354 def specifiers(self
, record
):
1358 yield from super().specifiers(record
=record
)
1361 class DZBaseRM(BaseRM
):
1362 def specifiers(self
, record
):
1366 yield from super().specifiers(record
=record
)
1369 class SZBaseRM(BaseRM
):
1370 def specifiers(self
, record
):
1374 yield from super().specifiers(record
=record
)
1377 class MRBaseRM(BaseRM
):
1378 def specifiers(self
, record
):
1384 yield from super().specifiers(record
=record
)
1387 class ElsBaseRM(BaseRM
):
1388 def specifiers(self
, record
):
1392 yield from super().specifiers(record
=record
)
1395 class WidthBaseRM(BaseRM
):
1397 def width(FP
, width
):
1406 width
= ("fp" + width
)
1409 def specifiers(self
, record
):
1410 # elwidths: use "w=" if same otherwise dw/sw
1411 # FIXME this should consider FP instructions
1413 dw
= WidthBaseRM
.width(FP
, int(self
.elwidth
))
1414 sw
= WidthBaseRM
.width(FP
, int(self
.ewsrc
))
1423 yield from super().specifiers(record
=record
)
1426 class PredicateBaseRM(BaseRM
):
1428 def predicate(CR
, mask
):
1431 (False, 0b001): "1<<r3",
1432 (False, 0b010): "r3",
1433 (False, 0b011): "~r3",
1434 (False, 0b100): "r10",
1435 (False, 0b101): "~r10",
1436 (False, 0b110): "r30",
1437 (False, 0b111): "~r30",
1439 (True, 0b000): "lt",
1440 (True, 0b001): "ge",
1441 (True, 0b010): "gt",
1442 (True, 0b011): "le",
1443 (True, 0b100): "eq",
1444 (True, 0b101): "ne",
1445 (True, 0b110): "so",
1446 (True, 0b111): "ns",
1449 def specifiers(self
, record
):
1450 # predication - single and twin
1451 # use "m=" if same otherwise sm/dm
1452 CR
= (int(self
.mmode
) == 1)
1453 mask
= int(self
.mask
)
1454 sm
= dm
= PredicateBaseRM
.predicate(CR
, mask
)
1455 if record
.svp64
.ptype
is _SVPtype
.P2
:
1456 smask
= int(self
.smask
)
1457 sm
= PredicateBaseRM
.predicate(CR
, smask
)
1466 yield from super().specifiers(record
=record
)
1469 class PredicateWidthBaseRM(WidthBaseRM
, PredicateBaseRM
):
1473 class SEABaseRM(BaseRM
):
1474 def specifiers(self
, record
):
1478 yield from super().specifiers(record
=record
)
1481 class VLiBaseRM(BaseRM
):
1482 def specifiers(self
, record
):
1486 yield from super().specifiers(record
=record
)
1489 class NormalBaseRM(PredicateWidthBaseRM
):
1492 https://libre-soc.org/openpower/sv/normal/
1497 class NormalSimpleRM(DZBaseRM
, SZBaseRM
, NormalBaseRM
):
1498 """normal: simple mode"""
1502 def specifiers(self
, record
):
1503 yield from super().specifiers(record
=record
)
1506 class NormalMRRM(MRBaseRM
, NormalBaseRM
):
1507 """normal: scalar reduce mode (mapreduce), SUBVL=1"""
1511 class NormalFFRc1RM(FFPRRc1BaseRM
, NormalBaseRM
):
1512 """normal: Rc=1: ffirst CR sel"""
1514 CR
: BaseRM
.mode
[3, 4]
1516 def specifiers(self
, record
):
1517 yield from super().specifiers(record
=record
, mode
="ff")
1520 class NormalFFRc0RM(FFPRRc0BaseRM
, VLiBaseRM
, NormalBaseRM
):
1521 """normal: Rc=0: ffirst z/nonz"""
1526 def specifiers(self
, record
):
1527 yield from super().specifiers(record
=record
, mode
="ff")
1530 class NormalSatRM(SatBaseRM
, DZBaseRM
, SZBaseRM
, NormalBaseRM
):
1531 """normal: sat mode: N=0/1 u/s, SUBVL=1"""
1537 class NormalPRRc1RM(FFPRRc1BaseRM
, NormalBaseRM
):
1538 """normal: Rc=1: pred-result CR sel"""
1540 CR
: BaseRM
.mode
[3, 4]
1542 def specifiers(self
, record
):
1543 yield from super().specifiers(record
=record
, mode
="pr")
1546 class NormalPRRc0RM(FFPRRc0BaseRM
, ZZBaseRM
, NormalBaseRM
):
1547 """normal: Rc=0: pred-result z/nonz"""
1554 def specifiers(self
, record
):
1555 yield from super().specifiers(record
=record
, mode
="pr")
1558 class NormalRM(NormalBaseRM
):
1559 simple
: NormalSimpleRM
1561 ffrc1
: NormalFFRc1RM
1562 ffrc0
: NormalFFRc0RM
1564 prrc1
: NormalPRRc1RM
1565 prrc0
: NormalPRRc0RM
1568 class LDSTImmBaseRM(PredicateWidthBaseRM
):
1570 LD/ST Immediate mode
1571 https://libre-soc.org/openpower/sv/ldst/
1576 class LDSTImmSimpleRM(ElsBaseRM
, ZZBaseRM
, LDSTImmBaseRM
):
1577 """ld/st immediate: simple mode"""
1584 class LDSTImmRsvdRM(LDSTImmBaseRM
):
1585 """ld/st immediate: rsvd"""
1589 class LDSTImmFFRc1RM(FFPRRc1BaseRM
, LDSTImmBaseRM
):
1590 """ld/st immediate: Rc=1: ffirst CR sel"""
1592 CR
: BaseRM
.mode
[3, 4]
1594 def specifiers(self
, record
):
1595 yield from super().specifiers(record
=record
, mode
="ff")
1598 class LDSTImmFFRc0RM(FFPRRc0BaseRM
, ElsBaseRM
, LDSTImmBaseRM
):
1599 """ld/st immediate: Rc=0: ffirst z/nonz"""
1604 def specifiers(self
, record
):
1605 yield from super().specifiers(record
=record
, mode
="ff")
1608 class LDSTImmSatRM(ElsBaseRM
, SatBaseRM
, ZZBaseRM
, LDSTImmBaseRM
):
1609 """ld/st immediate: sat mode: N=0/1 u/s"""
1617 class LDSTImmPRRc1RM(FFPRRc1BaseRM
, LDSTImmBaseRM
):
1618 """ld/st immediate: Rc=1: pred-result CR sel"""
1620 CR
: BaseRM
.mode
[3, 4]
1622 def specifiers(self
, record
):
1623 yield from super().specifiers(record
=record
, mode
="pr")
1626 class LDSTImmPRRc0RM(FFPRRc0BaseRM
, ElsBaseRM
, LDSTImmBaseRM
):
1627 """ld/st immediate: Rc=0: pred-result z/nonz"""
1632 def specifiers(self
, record
):
1633 yield from super().specifiers(record
=record
, mode
="pr")
1636 class LDSTImmRM(LDSTImmBaseRM
):
1637 simple
: LDSTImmSimpleRM
1639 ffrc1
: LDSTImmFFRc1RM
1640 ffrc0
: LDSTImmFFRc0RM
1642 prrc1
: LDSTImmPRRc1RM
1643 prrc0
: LDSTImmPRRc0RM
1646 class LDSTIdxBaseRM(PredicateWidthBaseRM
):
1649 https://libre-soc.org/openpower/sv/ldst/
1654 class LDSTIdxSimpleRM(SEABaseRM
, DZBaseRM
, SZBaseRM
, LDSTIdxBaseRM
):
1655 """ld/st index: simple mode"""
1661 class LDSTIdxStrideRM(SEABaseRM
, DZBaseRM
, SZBaseRM
, LDSTIdxBaseRM
):
1662 """ld/st index: strided (scalar only source)"""
1667 def specifiers(self
, record
):
1670 yield from super().specifiers(record
=record
)
1673 class LDSTIdxSatRM(SatBaseRM
, DZBaseRM
, SZBaseRM
, LDSTIdxBaseRM
):
1674 """ld/st index: sat mode: N=0/1 u/s"""
1680 class LDSTIdxPRRc1RM(LDSTIdxBaseRM
):
1681 """ld/st index: Rc=1: pred-result CR sel"""
1683 CR
: BaseRM
.mode
[3, 4]
1685 def specifiers(self
, record
):
1686 yield from super().specifiers(record
=record
, mode
="pr")
1689 class LDSTIdxPRRc0RM(FFPRRc0BaseRM
, ZZBaseRM
, LDSTIdxBaseRM
):
1690 """ld/st index: Rc=0: pred-result z/nonz"""
1697 def specifiers(self
, record
):
1698 yield from super().specifiers(record
=record
, mode
="pr")
1701 class LDSTIdxRM(LDSTIdxBaseRM
):
1702 simple
: LDSTIdxSimpleRM
1703 stride
: LDSTIdxStrideRM
1705 prrc1
: LDSTIdxPRRc1RM
1706 prrc0
: LDSTIdxPRRc0RM
1710 class CROpBaseRM(BaseRM
):
1713 https://libre-soc.org/openpower/sv/cr_ops/
1718 class CROpSimpleRM(PredicateBaseRM
, DZBaseRM
, SZBaseRM
, CROpBaseRM
):
1719 """cr_op: simple mode"""
1724 def specifiers(self
, record
):
1726 yield "rg" # simple CR Mode reports /rg
1728 yield from super().specifiers(record
=record
)
1730 class CROpMRRM(MRBaseRM
, DZBaseRM
, SZBaseRM
, CROpBaseRM
):
1731 """cr_op: scalar reduce mode (mapreduce), SUBVL=1"""
1737 class CROpFF3RM(FFPRRc1BaseRM
, VLiBaseRM
, ZZBaseRM
, PredicateBaseRM
, CROpBaseRM
):
1738 """cr_op: ffirst 3-bit mode"""
1746 def specifiers(self
, record
):
1747 yield from super().specifiers(record
=record
, mode
="ff")
1750 class CROpFF5RM(FFPRRc0BaseRM
, PredicateBaseRM
,
1751 VLiBaseRM
, DZBaseRM
, SZBaseRM
, CROpBaseRM
):
1752 """cr_op: ffirst 5-bit mode"""
1755 RC1
: BaseRM
[19] # cheat: set RC=1 based on ffirst mode being set
1759 def specifiers(self
, record
):
1760 yield from super().specifiers(record
=record
, mode
="ff")
1763 class CROpRM(CROpBaseRM
):
1764 simple
: CROpSimpleRM
1770 # ********************
1772 # https://libre-soc.org/openpower/sv/branches/
1773 class BranchBaseRM(BaseRM
):
1783 def specifiers(self
, record
):
1795 raise ValueError(self
.sz
)
1807 # Branch modes lack source mask.
1808 # Therefore a custom code is needed.
1809 CR
= (int(self
.mmode
) == 1)
1810 mask
= int(self
.mask
)
1811 m
= PredicateBaseRM
.predicate(CR
, mask
)
1815 yield from super().specifiers(record
=record
)
1818 class BranchSimpleRM(BranchBaseRM
):
1819 """branch: simple mode"""
1823 class BranchVLSRM(BranchBaseRM
):
1824 """branch: VLSET mode"""
1828 def specifiers(self
, record
):
1834 }[int(self
.VSb
), int(self
.VLi
)]
1836 yield from super().specifiers(record
=record
)
1839 class BranchCTRRM(BranchBaseRM
):
1840 """branch: CTR-test mode"""
1843 def specifiers(self
, record
):
1849 yield from super().specifiers(record
=record
)
1852 class BranchCTRVLSRM(BranchVLSRM
, BranchCTRRM
):
1853 """branch: CTR-test+VLSET mode"""
1857 class BranchRM(BranchBaseRM
):
1858 simple
: BranchSimpleRM
1861 ctrvls
: BranchCTRVLSRM
1871 def select(self
, record
):
1875 # the idea behind these tables is that they are now literally
1876 # in identical format to insndb.csv and minor_xx.csv and can
1877 # be done precisely as that. the only thing to watch out for
1878 # is the insertion of Rc=1 as a "mask/value" bit and likewise
1879 # regtype detection (3-bit BF/BFA, 5-bit BA/BB/BT) also inserted
1882 if record
.svp64
.mode
is _SVMode
.NORMAL
:
1883 # concatenate mode 5-bit with Rc (LSB) then do a mask/map search
1884 # mode Rc mask Rc member
1886 (0b000000, 0b111000, "simple"), # simple (no Rc)
1887 (0b001000, 0b111000, "mr"), # mapreduce (no Rc)
1888 (0b010001, 0b110001, "ffrc1"), # ffirst, Rc=1
1889 (0b010000, 0b110001, "ffrc0"), # ffirst, Rc=0
1890 (0b100000, 0b110000, "sat"), # saturation (no Rc)
1891 (0b110000, 0b110001, "prrc0"), # predicate, Rc=0
1892 (0b110001, 0b110001, "prrc1"), # predicate, Rc=1
1895 search
= ((int(rm
.mode
) << 1) | Rc
)
1897 elif record
.svp64
.mode
is _SVMode
.LDST_IMM
:
1898 # concatenate mode 5-bit with Rc (LSB) then do a mask/map search
1899 # mode Rc mask Rc member
1900 # ironically/coincidentally this table is identical to NORMAL
1901 # mode except reserved in place of mr
1903 (0b000000, 0b111000, "simple"), # simple (no Rc)
1904 (0b001000, 0b111000, "rsvd"), # rsvd (no Rc)
1905 (0b010001, 0b110001, "ffrc1"), # ffirst, Rc=1
1906 (0b010000, 0b110001, "ffrc0"), # ffirst, Rc=0
1907 (0b100000, 0b110000, "sat"), # saturation (no Rc)
1908 (0b110001, 0b110001, "prrc1"), # predicate, Rc=1
1909 (0b110000, 0b110001, "prrc0"), # predicate, Rc=0
1912 search
= ((int(rm
.mode
) << 1) | Rc
)
1914 elif record
.svp64
.mode
is _SVMode
.LDST_IDX
:
1915 # concatenate mode 5-bit with Rc (LSB) then do a mask/map search
1916 # mode Rc mask Rc member
1918 (0b000000, 0b110000, "simple"), # simple (no Rc)
1919 (0b010000, 0b110000, "stride"), # strided, (no Rc)
1920 (0b100000, 0b110000, "sat"), # saturation (no Rc)
1921 (0b110001, 0b110001, "prrc1"), # predicate, Rc=1
1922 (0b110000, 0b110001, "prrc0"), # predicate, Rc=0
1925 search
= ((int(rm
.mode
) << 1) | Rc
)
1927 elif record
.svp64
.mode
is _SVMode
.CROP
:
1928 # concatenate mode 5-bit with regtype (LSB) then do mask/map search
1929 # mode 3b mask 3b member
1931 (0b000000, 0b111000, "simple"), # simple
1932 (0b001000, 0b111000, "mr"), # mapreduce
1933 (0b100001, 0b100001, "ff3"), # failfirst, 3-bit CR
1934 (0b100000, 0b100000, "ff5"), # failfirst, 5-bit CR
1936 # determine CR type, 5-bit (BA/BB/BT) or 3-bit Field (BF/BFA)
1938 for idx
in range(0, 4):
1939 for entry
in record
.svp64
.extra
[idx
]:
1940 if entry
.regtype
is _SVExtraRegType
.DST
:
1941 if regtype
is not None:
1942 raise ValueError(record
.svp64
)
1943 regtype
= _RegType(entry
.reg
)
1944 if regtype
is _RegType
.CR_REG
:
1946 elif regtype
is _RegType
.CR_BIT
:
1949 raise ValueError(record
.svp64
)
1950 # finally provide info for search
1952 search
= ((int(rm
.mode
) << 1) |
(regtype
or 0))
1954 elif record
.svp64
.mode
is _SVMode
.BRANCH
:
1958 (0b00, 0b11, "simple"), # simple
1959 (0b01, 0b11, "vls"), # VLset
1960 (0b10, 0b11, "ctr"), # CTR mode
1961 (0b11, 0b11, "ctrvls"), # CTR+VLset mode
1963 # slightly weird: doesn't have a 5-bit "mode" field like others
1965 search
= int(rm
.mode
[0, 1])
1968 if table
is not None:
1969 for (value
, mask
, member
) in table
:
1970 if ((value
& mask
) == (search
& mask
)):
1971 rm
= getattr(rm
, member
)
1974 if rm
.__class
__ is self
.__class
__:
1975 raise ValueError(self
)
1980 class SVP64Instruction(PrefixedInstruction
):
1981 """SVP64 instruction: https://libre-soc.org/openpower/sv/svp64/"""
1982 class Prefix(PrefixedInstruction
.Prefix
):
1984 rm
: RM
.remap((6, 8) + tuple(range(10, 32)))
1988 def record(self
, db
):
1989 record
= db
[self
.suffix
]
1991 raise KeyError(self
)
1997 for idx
in range(64):
1998 bit
= int(self
[idx
])
2000 return "".join(map(str, bits
))
2002 def disassemble(self
, db
,
2004 verbosity
=Verbosity
.NORMAL
):
2006 if verbosity
<= Verbosity
.SHORT
:
2009 blob
= integer
.to_bytes(length
=4, byteorder
=byteorder
)
2010 blob
= " ".join(map(lambda byte
: f
"{byte:02x}", blob
))
2013 record
= self
.record(db
=db
)
2014 blob_prefix
= blob(int(self
.prefix
))
2015 blob_suffix
= blob(int(self
.suffix
))
2016 if record
is None or record
.svp64
is None:
2017 yield f
"{blob_prefix}.long 0x{int(self.prefix):08x}"
2018 yield f
"{blob_suffix}.long 0x{int(self.suffix):08x}"
2021 name
= f
"sv.{record.name}"
2023 rm
= self
.prefix
.rm
.select(record
=record
)
2025 # convert specifiers to /x/y/z (sorted lexicographically)
2026 specifiers
= sorted(rm
.specifiers(record
=record
))
2027 if specifiers
: # if any add one extra to get the extra "/"
2028 specifiers
= ([""] + specifiers
)
2029 specifiers
= "/".join(specifiers
)
2031 # convert operands to " ,x,y,z"
2032 operands
= tuple(map(_operator
.itemgetter(1),
2033 self
.dynamic_operands(db
=db
, verbosity
=verbosity
)))
2034 operands
= ",".join(operands
)
2035 if len(operands
) > 0: # if any separate with a space
2036 operands
= (" " + operands
)
2038 yield f
"{blob_prefix}{name}{specifiers}{operands}"
2040 yield f
"{blob_suffix}"
2042 if verbosity
>= Verbosity
.VERBOSE
:
2044 binary
= self
.binary
2045 spec
= self
.spec(db
=db
, prefix
="sv.")
2047 yield f
"{indent}spec"
2048 yield f
"{indent}{indent}{spec}"
2049 yield f
"{indent}pcode"
2050 for stmt
in record
.mdwn
.pcode
:
2051 yield f
"{indent}{indent}{stmt}"
2052 yield f
"{indent}binary"
2053 yield f
"{indent}{indent}[0:8] {binary[0:8]}"
2054 yield f
"{indent}{indent}[8:16] {binary[8:16]}"
2055 yield f
"{indent}{indent}[16:24] {binary[16:24]}"
2056 yield f
"{indent}{indent}[24:32] {binary[24:32]}"
2057 yield f
"{indent}{indent}[32:40] {binary[32:40]}"
2058 yield f
"{indent}{indent}[40:48] {binary[40:48]}"
2059 yield f
"{indent}{indent}[48:56] {binary[48:56]}"
2060 yield f
"{indent}{indent}[56:64] {binary[56:64]}"
2061 yield f
"{indent}opcodes"
2062 for opcode
in record
.opcodes
:
2063 yield f
"{indent}{indent}{opcode!r}"
2064 for operand
in record
.mdwn
.operands
:
2065 yield from operand
.disassemble(insn
=self
, record
=record
,
2066 verbosity
=verbosity
, indent
=indent
)
2068 yield f
"{indent}{indent}{rm.__doc__}"
2069 for line
in rm
.disassemble(verbosity
=verbosity
):
2070 yield f
"{indent}{indent}{line}"
2074 def parse(stream
, factory
):
2076 return ("TODO" not in frozenset(entry
.values()))
2078 lines
= filter(lambda line
: not line
.strip().startswith("#"), stream
)
2079 entries
= _csv
.DictReader(lines
)
2080 entries
= filter(match
, entries
)
2081 return tuple(map(factory
, entries
))
2084 class MarkdownDatabase
:
2087 for (name
, desc
) in _ISA():
2090 (dynamic
, *static
) = desc
.regs
2091 operands
.extend(dynamic
)
2092 operands
.extend(static
)
2093 pcode
= PCode(iterable
=desc
.pcode
)
2094 operands
= Operands(insn
=name
, iterable
=operands
)
2095 db
[name
] = MarkdownRecord(pcode
=pcode
, operands
=operands
)
2097 self
.__db
= dict(sorted(db
.items()))
2099 return super().__init
__()
2102 yield from self
.__db
.items()
2104 def __contains__(self
, key
):
2105 return self
.__db
.__contains
__(key
)
2107 def __getitem__(self
, key
):
2108 return self
.__db
.__getitem
__(key
)
2111 class FieldsDatabase
:
2114 df
= _DecodeFields()
2116 for (form
, fields
) in df
.instrs
.items():
2117 if form
in {"DQE", "TX"}:
2121 db
[_Form
[form
]] = Fields(fields
)
2125 return super().__init
__()
2127 def __getitem__(self
, key
):
2128 return self
.__db
.__getitem
__(key
)
2132 def __init__(self
, root
, mdwndb
):
2133 # The code below groups the instructions by name:section.
2134 # There can be multiple names for the same instruction.
2135 # The point is to capture different opcodes for the same instruction.
2136 dd
= _collections
.defaultdict
2138 records
= _collections
.defaultdict(set)
2139 path
= (root
/ "insndb.csv")
2140 with
open(path
, "r", encoding
="UTF-8") as stream
:
2141 for section
in parse(stream
, Section
.CSV
):
2142 path
= (root
/ section
.path
)
2144 section
.Mode
.INTEGER
: IntegerOpcode
,
2145 section
.Mode
.PATTERN
: PatternOpcode
,
2147 factory
= _functools
.partial(
2148 PPCRecord
.CSV
, opcode_cls
=opcode_cls
)
2149 with
open(path
, "r", encoding
="UTF-8") as stream
:
2150 for insn
in parse(stream
, factory
):
2151 for name
in insn
.names
:
2152 records
[name
].add(insn
)
2153 sections
[name
] = section
2155 for (name
, multirecord
) in sorted(records
.items()):
2156 multirecord
= PPCMultiRecord(sorted(multirecord
))
2157 records
[name
] = multirecord
2159 def exact_match(name
):
2160 record
= records
.get(name
)
2166 if not name
.endswith("l"):
2168 alias
= exact_match(name
[:-1])
2171 record
= records
[alias
]
2172 if "lk" not in record
.flags
:
2173 raise ValueError(record
)
2177 if not name
.endswith("a"):
2179 alias
= LK_match(name
[:-1])
2182 record
= records
[alias
]
2183 if record
.intop
not in {_MicrOp
.OP_B
, _MicrOp
.OP_BC
}:
2184 raise ValueError(record
)
2185 operands
= mdwndb
[name
].operands
["AA"]
2186 if operands
is None:
2187 raise ValueError(record
)
2191 if not name
.endswith("."):
2193 alias
= exact_match(name
[:-1])
2196 record
= records
[alias
]
2197 if record
.Rc
is _RCOE
.NONE
:
2198 raise ValueError(record
)
2202 matches
= (exact_match
, LK_match
, AA_match
, Rc_match
)
2203 for (name
, _
) in mdwndb
:
2205 for match
in matches
:
2207 if alias
is not None:
2211 section
= sections
[alias
]
2212 record
= records
[alias
]
2213 db
[name
] = (section
, record
)
2215 self
.__db
= dict(sorted(db
.items()))
2217 return super().__init
__()
2219 @_functools.lru_cache(maxsize
=512, typed
=False)
2220 def __getitem__(self
, key
):
2221 return self
.__db
.get(key
, (None, None))
2224 class SVP64Database
:
2225 def __init__(self
, root
, ppcdb
):
2227 pattern
= _re
.compile(r
"^(?:LDST)?RM-(1P|2P)-.*?\.csv$")
2228 for (prefix
, _
, names
) in _os
.walk(root
):
2229 prefix
= _pathlib
.Path(prefix
)
2230 for name
in filter(lambda name
: pattern
.match(name
), names
):
2231 path
= (prefix
/ _pathlib
.Path(name
))
2232 with
open(path
, "r", encoding
="UTF-8") as stream
:
2233 db
.update(parse(stream
, SVP64Record
.CSV
))
2234 db
= {record
.name
:record
for record
in db
}
2236 self
.__db
= dict(sorted(db
.items()))
2237 self
.__ppcdb
= ppcdb
2239 return super().__init
__()
2241 def __getitem__(self
, key
):
2242 (_
, record
) = self
.__ppcdb
[key
]
2246 for name
in record
.names
:
2247 record
= self
.__db
.get(name
, None)
2248 if record
is not None:
2255 def __init__(self
, root
):
2256 root
= _pathlib
.Path(root
)
2257 mdwndb
= MarkdownDatabase()
2258 fieldsdb
= FieldsDatabase()
2259 ppcdb
= PPCDatabase(root
=root
, mdwndb
=mdwndb
)
2260 svp64db
= SVP64Database(root
=root
, ppcdb
=ppcdb
)
2264 opcodes
= _collections
.defaultdict(set)
2266 for (name
, mdwn
) in mdwndb
:
2267 (section
, ppc
) = ppcdb
[name
]
2270 svp64
= svp64db
[name
]
2271 fields
= fieldsdb
[ppc
.form
]
2272 record
= Record(name
=name
,
2273 section
=section
, ppc
=ppc
, svp64
=svp64
,
2274 mdwn
=mdwn
, fields
=fields
)
2276 names
[record
.name
] = record
2280 opcodes
[PO
.value
].add(record
)
2282 self
.__db
= sorted(db
)
2283 self
.__names
= dict(sorted(names
.items()))
2284 self
.__opcodes
= dict(sorted(opcodes
.items()))
2286 return super().__init
__()
2289 return repr(self
.__db
)
2292 yield from self
.__db
2294 @_functools.lru_cache(maxsize
=None)
2295 def __contains__(self
, key
):
2296 return self
.__getitem
__(key
) is not None
2298 @_functools.lru_cache(maxsize
=None)
2299 def __getitem__(self
, key
):
2300 if isinstance(key
, (int, Instruction
)):
2302 XO
= int(_SelectableInt(value
=int(key
), bits
=32)[0:6])
2303 for record
in self
.__opcodes
[XO
]:
2304 if record
.match(key
=key
):
2307 elif isinstance(key
, str):
2308 return self
.__names
[key
]