2e681bc7b2aa1b63443b19a02cab9b87827cf8e5
1 import collections
as _collections
3 import dataclasses
as _dataclasses
5 import functools
as _functools
7 import pathlib
as _pathlib
11 from functools
import cached_property
13 from cached_property
import cached_property
15 from openpower
.decoder
.power_enums
import (
16 Function
as _Function
,
23 CROutSel
as _CROutSel
,
25 LDSTMode
as _LDSTMode
,
34 SVExtraRegType
as _SVExtraRegType
,
35 SVExtraReg
as _SVExtraReg
,
37 from openpower
.decoder
.selectable_int
import (
38 SelectableInt
as _SelectableInt
,
39 selectconcat
as _selectconcat
,
41 from openpower
.decoder
.power_fields
import (
45 DecodeFields
as _DecodeFields
,
47 from openpower
.decoder
.pseudo
.pagereader
import ISA
as _ISA
50 def dataclass(cls
, record
, keymap
=None, typemap
=None):
54 typemap
= {field
.name
:field
.type for field
in _dataclasses
.fields(cls
)}
56 def transform(key_value
):
57 (key
, value
) = key_value
58 key
= keymap
.get(key
, key
)
59 hook
= typemap
.get(key
, lambda value
: value
)
60 if hook
is bool and value
in ("", "0"):
66 record
= dict(map(transform
, record
.items()))
67 for key
in frozenset(record
.keys()):
74 @_functools.total_ordering
75 @_dataclasses.dataclass(eq
=True, frozen
=True)
79 if self
.bit_length() <= 32:
80 return f
"0x{self:08x}"
82 return f
"0x{self:016x}"
86 if self
.bit_length() <= 32:
87 return f
"0x{self:08x}"
89 return f
"0x{self:016x}"
94 def __lt__(self
, other
):
95 if not isinstance(other
, Opcode
):
97 return ((self
.value
, self
.mask
) < (other
.value
, other
.mask
))
99 def __post_init__(self
):
100 (value
, mask
) = (self
.value
, self
.mask
)
102 if isinstance(value
, Opcode
):
104 raise ValueError(mask
)
105 (value
, mask
) = (value
.value
, value
.mask
)
106 elif isinstance(value
, str):
108 raise ValueError(mask
)
109 value
= int(value
, 0)
111 if not isinstance(value
, int):
112 raise ValueError(value
)
115 if not isinstance(mask
, int):
116 raise ValueError(mask
)
118 object.__setattr
__(self
, "value", self
.__class
__.Value(value
))
119 object.__setattr
__(self
, "mask", self
.__class
__.Mask(mask
))
122 class IntegerOpcode(Opcode
):
123 def __init__(self
, value
):
124 if isinstance(value
, str):
125 value
= int(value
, 0)
126 return super().__init
__(value
=value
, mask
=None)
129 class PatternOpcode(Opcode
):
130 def __init__(self
, value
):
131 (pattern
, value
, mask
) = (value
, 0, 0)
133 for symbol
in pattern
:
134 if symbol
not in {"0", "1", "-"}:
135 raise ValueError(pattern
)
136 value |
= (symbol
== "1")
137 mask |
= (symbol
!= "-")
143 return super().__init
__(value
=value
, mask
=mask
)
146 class FieldsOpcode(Opcode
):
147 def __init__(self
, fields
):
148 def field(opcode
, field
):
149 (value
, mask
) = opcode
150 (field
, bits
) = field
151 shifts
= map(lambda bit
: (31 - bit
), reversed(tuple(bits
)))
152 for (index
, shift
) in enumerate(shifts
):
153 bit
= ((field
& (1 << index
)) != 0)
154 value |
= (bit
<< shift
)
158 (value
, mask
) = _functools
.reduce(field
, fields
, (0, 0))
160 return super().__init
__(value
=value
, mask
=mask
)
163 @_dataclasses.dataclass(eq
=True, frozen
=True)
165 class FlagsMeta(type):
180 class Flags(frozenset, metaclass
=FlagsMeta
):
181 def __new__(cls
, flags
=frozenset()):
182 flags
= frozenset(flags
)
183 diff
= (flags
- frozenset(cls
))
185 raise ValueError(flags
)
186 return super().__new
__(cls
, flags
)
190 flags
: Flags
= Flags()
192 function
: _Function
= _Function
.NONE
193 intop
: _MicrOp
= _MicrOp
.OP_ILLEGAL
194 in1
: _In1Sel
= _In1Sel
.RA
195 in2
: _In2Sel
= _In2Sel
.NONE
196 in3
: _In3Sel
= _In3Sel
.NONE
197 out
: _OutSel
= _OutSel
.NONE
198 cr_in
: _CRInSel
= _CRInSel
.NONE
199 cr_out
: _CROutSel
= _CROutSel
.NONE
200 cry_in
: _CryIn
= _CryIn
.ZERO
201 ldst_len
: _LDSTLen
= _LDSTLen
.NONE
202 upd
: _LDSTMode
= _LDSTMode
.NONE
203 Rc
: _RCOE
= _RCOE
.NONE
204 form
: _Form
= _Form
.NONE
206 unofficial
: bool = False
210 "internal op": "intop",
214 "ldst len": "ldst_len",
216 "CONDITIONS": "conditions",
220 def CSV(cls
, record
, opcode_cls
=Opcode
):
221 typemap
= {field
.name
:field
.type for field
in _dataclasses
.fields(cls
)}
222 typemap
["opcode"] = opcode_cls
225 for flag
in frozenset(PPCRecord
.Flags
):
226 if bool(record
.pop(flag
, "")):
228 record
["flags"] = PPCRecord
.Flags(flags
)
230 return dataclass(cls
, record
, keymap
=PPCRecord
.__KEYMAP
, typemap
=typemap
)
234 return frozenset(self
.comment
.split("=")[-1].split("/"))
237 @_dataclasses.dataclass(eq
=True, frozen
=True)
239 class ExtraMap(tuple):
241 @_dataclasses.dataclass(eq
=True, frozen
=True)
243 regtype
: _SVExtraRegType
= _SVExtraRegType
.NONE
244 reg
: _SVExtraReg
= _SVExtraReg
.NONE
247 return f
"{self.regtype.value}:{self.reg.name}"
249 def __new__(cls
, value
="0"):
250 if isinstance(value
, str):
251 def transform(value
):
252 (regtype
, reg
) = value
.split(":")
253 regtype
= _SVExtraRegType(regtype
)
254 reg
= _SVExtraReg(reg
)
255 return cls
.Entry(regtype
=regtype
, reg
=reg
)
260 value
= map(transform
, value
.split(";"))
262 return super().__new
__(cls
, value
)
265 return repr(list(self
))
267 def __new__(cls
, value
=tuple()):
271 return super().__new
__(cls
, map(cls
.Extra
, value
))
274 return repr({index
:self
[index
] for index
in range(0, 4)})
277 ptype
: _SVPtype
= _SVPtype
.NONE
278 etype
: _SVEtype
= _SVEtype
.NONE
279 in1
: _In1Sel
= _In1Sel
.NONE
280 in2
: _In2Sel
= _In2Sel
.NONE
281 in3
: _In3Sel
= _In3Sel
.NONE
282 out
: _OutSel
= _OutSel
.NONE
283 out2
: _OutSel
= _OutSel
.NONE
284 cr_in
: _CRInSel
= _CRInSel
.NONE
285 cr_out
: _CROutSel
= _CROutSel
.NONE
286 extra
: ExtraMap
= ExtraMap()
289 mode
: _SVMode
= _SVMode
.NORMAL
293 "CONDITIONS": "conditions",
302 def CSV(cls
, record
):
303 for key
in ("in1", "in2", "in3", "out", "out2", "CR in", "CR out"):
308 record
["extra"] = cls
.ExtraMap(record
.pop(f
"{index}") for index
in range(0, 4))
310 return dataclass(cls
, record
, keymap
=cls
.__KEYMAP
)
314 def __init__(self
, value
=(0, 32)):
315 if isinstance(value
, str):
316 (start
, end
) = map(int, value
.split(":"))
319 if start
< 0 or end
< 0 or start
>= end
:
320 raise ValueError(value
)
325 return super().__init
__()
328 return f
"[{self.__start}:{self.__end}]"
331 yield from range(self
.start
, (self
.end
+ 1))
342 @_dataclasses.dataclass(eq
=True, frozen
=True)
344 class Mode(_enum
.Enum
):
345 INTEGER
= _enum
.auto()
346 PATTERN
= _enum
.auto()
349 def _missing_(cls
, value
):
350 if isinstance(value
, str):
351 return cls
[value
.upper()]
352 return super()._missing
_(value
)
355 def __new__(cls
, value
=None):
356 if isinstance(value
, str):
357 if value
.upper() == "NONE":
360 value
= int(value
, 0)
364 return super().__new
__(cls
, value
)
370 return (bin(self
) if self
else "None")
379 def CSV(cls
, record
):
380 return dataclass(cls
, record
)
384 def __init__(self
, items
):
385 if isinstance(items
, dict):
386 items
= items
.items()
389 (name
, bitrange
) = item
390 return (name
, tuple(bitrange
.values()))
392 self
.__mapping
= dict(map(transform
, items
))
394 return super().__init
__()
397 return repr(self
.__mapping
)
400 yield from self
.__mapping
.items()
402 def __contains__(self
, key
):
403 return self
.__mapping
.__contains
__(key
)
405 def __getitem__(self
, key
):
406 return self
.__mapping
.get(key
, None)
410 @_dataclasses.dataclass(eq
=True, frozen
=True)
414 def disassemble(self
, value
, record
):
415 raise NotImplementedError
417 @_dataclasses.dataclass(eq
=True, frozen
=True)
418 class DynamicOperand(Operand
):
419 def disassemble(self
, value
, record
):
420 return str(int(value
[record
.fields
[self
.name
]]))
422 @_dataclasses.dataclass(eq
=True, frozen
=True)
423 class StaticOperand(Operand
):
426 @_dataclasses.dataclass(eq
=True, frozen
=True)
427 class DynamicOperandIFormLI(DynamicOperand
):
428 def disassemble(self
, value
, record
):
429 return hex(int(_selectconcat(
430 value
[record
.fields
["LI"]],
431 _SelectableInt(value
=0b00, bits
=2))))
433 class DynamicOperandBFormBD(DynamicOperand
):
434 def disassemble(self
, value
, record
):
435 return hex(int(_selectconcat(
436 value
[record
.fields
["BD"]],
437 _SelectableInt(value
=0b00, bits
=2))))
439 @_dataclasses.dataclass(eq
=True, frozen
=True)
440 class DynamicOperandGPR(DynamicOperand
):
441 def disassemble(self
, value
, record
):
442 return f
"r{super().disassemble(value=value, record=record)}"
444 @_dataclasses.dataclass(eq
=True, frozen
=True)
445 class DynamicOperandFPR(DynamicOperand
):
446 def disassemble(self
, value
, record
):
447 return f
"f{super().disassemble(value=value, record=record)}"
449 def __init__(self
, insn
, iterable
):
451 "b": {"LI": self
.__class
__.DynamicOperandIFormLI
},
452 "ba": {"LI": self
.__class
__.DynamicOperandIFormLI
},
453 "bl": {"LI": self
.__class
__.DynamicOperandIFormLI
},
454 "bla": {"LI": self
.__class
__.DynamicOperandIFormLI
},
455 "bc": {"BD": self
.__class
__.DynamicOperandBFormBD
},
456 "bca": {"BD": self
.__class
__.DynamicOperandBFormBD
},
457 "bcl": {"BD": self
.__class
__.DynamicOperandBFormBD
},
458 "bcla": {"BD": self
.__class
__.DynamicOperandBFormBD
},
462 for operand
in iterable
:
463 dynamic_cls
= self
.__class
__.DynamicOperand
464 static_cls
= self
.__class
__.StaticOperand
467 (name
, value
) = operand
.split("=")
468 operand
= static_cls(name
=name
, value
=int(value
))
470 if insn
in branches
and operand
in branches
[insn
]:
471 dynamic_cls
= branches
[insn
][operand
]
473 if operand
in _RegType
.__members
__:
474 regtype
= _RegType
[operand
]
475 if regtype
is _RegType
.GPR
:
476 dynamic_cls
= self
.__class
__.DynamicOperandGPR
477 elif regtype
is _RegType
.FPR
:
478 dynamic_cls
= self
.__class
__.DynamicOperandFPR
480 operand
= dynamic_cls(name
=operand
)
482 operands
.append(operand
)
484 self
.__operands
= operands
486 return super().__init
__()
489 return self
.__operands
.__repr
__()
492 yield from self
.__operands
494 def __contains__(self
, key
):
495 return self
.__getitem
__(key
) is not None
497 def __getitem__(self
, key
):
498 for operand
in self
.__operands
:
499 if operand
.name
== key
:
507 if isinstance(operand
, self
.__class
__.DynamicOperand
):
513 if isinstance(operand
, self
.__class
__.StaticOperand
):
517 @_functools.total_ordering
518 @_dataclasses.dataclass(eq
=True, frozen
=True)
525 svp64
: SVP64Record
= None
534 def __lt__(self
, other
):
535 if not isinstance(other
, Record
):
536 return NotImplemented
537 return (self
.opcode
< other
.opcode
)
542 if self
.section
.opcode
:
543 fields
+= [(self
.section
.opcode
.value
, BitSel((0, 5)))]
544 fields
+= [(self
.ppc
.opcode
.value
, self
.section
.bitsel
)]
546 fields
+= [(self
.ppc
.opcode
.value
, self
.section
.bitsel
)]
548 for operand
in self
.operands
.static
:
549 fields
+= [(operand
.value
, self
.fields
[operand
.name
])]
551 return FieldsOpcode(fields
)
555 return self
.ppc
.function
575 if self
.svp64
is None:
581 return self
.ppc
.cr_in
585 return self
.ppc
.cr_out
587 def sv_extra(self
, key
):
588 if key
not in frozenset({
589 "in1", "in2", "in3", "cr_in",
590 "out", "out2", "cr_out",
594 sel
= getattr(self
.svp64
, key
)
595 if sel
is _CRInSel
.BA_BB
:
596 return _SVExtra
.Idx_1_2
597 reg
= _SVExtraReg(sel
)
598 if reg
is _SVExtraReg
.NONE
:
602 _SVExtraRegType
.SRC
: {},
603 _SVExtraRegType
.DST
: {},
605 for index
in range(0, 4):
606 for entry
in self
.svp64
.extra
[index
]:
607 extra_map
[entry
.regtype
][entry
.reg
] = Record
.__EXTRA
[index
]
609 for regtype
in (_SVExtraRegType
.SRC
, _SVExtraRegType
.DST
):
610 extra
= extra_map
[regtype
].get(reg
, _SVExtra
.NONE
)
611 if extra
is not _SVExtra
.NONE
:
616 sv_in1
= property(_functools
.partial(sv_extra
, key
="in1"))
617 sv_in2
= property(_functools
.partial(sv_extra
, key
="in2"))
618 sv_in3
= property(_functools
.partial(sv_extra
, key
="in3"))
619 sv_out
= property(_functools
.partial(sv_extra
, key
="out"))
620 sv_out2
= property(_functools
.partial(sv_extra
, key
="out2"))
621 sv_cr_in
= property(_functools
.partial(sv_extra
, key
="cr_in"))
622 sv_cr_out
= property(_functools
.partial(sv_extra
, key
="cr_out"))
626 if self
.svp64
is None:
628 return self
.svp64
.ptype
632 if self
.svp64
is None:
634 return self
.svp64
.etype
637 class Instruction(_Mapping
):
639 def integer(cls
, value
=0, bits
=None, byteorder
="little"):
640 if isinstance(value
, (int, bytes
)) and not isinstance(bits
, int):
641 raise ValueError(bits
)
643 if isinstance(value
, bytes
):
644 if ((len(value
) * 8) != bits
):
645 raise ValueError(f
"bit length mismatch")
646 value
= int.from_bytes(value
, byteorder
=byteorder
)
648 if isinstance(value
, int):
649 value
= _SelectableInt(value
=value
, bits
=bits
)
650 elif isinstance(value
, Instruction
):
651 value
= value
.storage
653 if not isinstance(value
, _SelectableInt
):
654 raise ValueError(value
)
657 if len(value
) != bits
:
658 raise ValueError(value
)
660 value
= _SelectableInt(value
=value
, bits
=bits
)
662 return cls(storage
=value
)
665 return hash(int(self
))
667 def disassemble(self
, db
, byteorder
="little"):
668 raise NotImplementedError
671 class WordInstruction(Instruction
):
672 _
: _Field
= range(0, 32)
673 po
: _Field
= range(0, 6)
676 def integer(cls
, value
, byteorder
="little"):
677 return super().integer(bits
=32, value
=value
, byteorder
=byteorder
)
679 def disassemble(self
, db
, byteorder
="little"):
681 blob
= integer
.to_bytes(length
=4, byteorder
=byteorder
)
682 blob
= " ".join(map(lambda byte
: f
"{byte:02x}", blob
))
686 yield f
"{blob} .long 0x{integer:08x}"
689 for operand
in record
.operands
.dynamic
:
690 operand
= operand
.disassemble(self
, record
)
691 operands
.append(operand
)
693 operands
= ",".join(operands
)
694 operands
= f
" {operands}"
697 yield f
"{blob} {record.name}{operands}"
699 class PrefixedInstruction(Instruction
):
700 class Prefix(WordInstruction
.remap(range(0, 32))):
703 class Suffix(WordInstruction
.remap(range(32, 64))):
706 _
: _Field
= range(64)
712 def integer(cls
, value
, byteorder
="little"):
713 return super().integer(bits
=64, value
=value
, byteorder
=byteorder
)
716 def pair(cls
, prefix
=0, suffix
=0, byteorder
="little"):
717 def transform(value
):
718 return WordInstruction
.integer(value
=value
,
719 byteorder
=byteorder
)[0:32]
721 (prefix
, suffix
) = map(transform
, (prefix
, suffix
))
722 value
= _selectconcat(prefix
, suffix
)
724 return super().integer(value
=value
)
727 class Mode(_Mapping
):
728 _
: _Field
= range(0, 5)
729 sel
: _Field
= range(0, 2)
732 class NormalMode(Mode
):
739 """scalar reduce mode (mapreduce), SUBVL=1"""
743 """parallel reduce mode (mapreduce), SUBVL=1"""
747 """subvector reduce mode, SUBVL>1"""
751 """Pack/Unpack mode, SUBVL>1"""
755 """Rc=1: ffirst CR sel"""
760 """Rc=0: ffirst z/nonz"""
766 """sat mode: N=0/1 u/s, SUBVL=1"""
772 """sat mode: N=0/1 u/s, SUBVL>1"""
779 """Pack/Unpack sat mode: N=0/1 u/s, SUBVL>1"""
786 """Rc=1: pred-result CR sel"""
791 """Rc=0: pred-result z/nonz"""
812 class LDSTImmMode(Mode
):
821 """Structured Pack/Unpack"""
828 """Rc=1: ffirst CR sel"""
833 """Rc=0: ffirst z/nonz"""
839 """sat mode: N=0/1 u/s"""
847 """Rc=1: pred-result CR sel"""
852 """Rc=0: pred-result z/nonz"""
866 class LDSTIdxMode(Mode
):
874 """strided (scalar only source)"""
880 """sat mode: N=0/1 u/s"""
886 """Rc=1: pred-result CR sel"""
891 """Rc=0: pred-result z/nonz"""
908 ldst_imm
: LDSTImmMode
909 ldst_idx
: LDSTIdxMode
911 _
: _Field
= range(24)
913 mask
: _Field
= range(1, 4)
914 elwidth
: _Field
= range(4, 6)
915 ewsrc
: _Field
= range(6, 8)
916 subvl
: _Field
= range(8, 10)
917 extra
: _Field
= range(10, 19)
918 mode
: Mode
.remap(range(19, 24))
919 extra2
: _Array
[4] = (
925 smask
: _Field
= range(16, 19)
926 extra3
: _Array
[3] = (
933 class SVP64Instruction(PrefixedInstruction
):
934 """SVP64 instruction: https://libre-soc.org/openpower/sv/svp64/"""
935 class Prefix(PrefixedInstruction
.Prefix
):
937 rm
: RM
.remap((6, 8) + tuple(range(10, 32)))
941 def disassemble(self
, db
, byteorder
="little"):
942 integer_prefix
= int(self
.prefix
)
943 blob_prefix
= integer_prefix
.to_bytes(length
=4, byteorder
=byteorder
)
944 blob_prefix
= " ".join(map(lambda byte
: f
"{byte:02x}", blob_prefix
))
946 integer_suffix
= int(self
.suffix
)
947 blob_suffix
= integer_suffix
.to_bytes(length
=4, byteorder
=byteorder
)
948 blob_suffix
= " ".join(map(lambda byte
: f
"{byte:02x}", blob_suffix
))
950 record
= db
[self
.suffix
]
951 if record
is None or record
.svp64
is None:
952 yield f
"{blob_prefix} .long 0x{int(self.prefix):08x}"
953 yield f
"{blob_suffix} .long 0x{int(self.suffix):08x}"
955 yield f
"{blob_prefix} sv.{record.name}"
956 yield f
"{blob_suffix}"
959 def parse(stream
, factory
):
960 lines
= filter(lambda line
: not line
.strip().startswith("#"), stream
)
961 entries
= _csv
.DictReader(lines
)
962 entries
= filter(lambda entry
: "TODO" not in frozenset(entry
.values()), entries
)
963 return tuple(map(factory
, entries
))
966 class MarkdownDatabase
:
969 for (name
, desc
) in _ISA():
972 (dynamic
, *static
) = desc
.regs
973 operands
.extend(dynamic
)
974 operands
.extend(static
)
975 db
[name
] = Operands(insn
=name
, iterable
=operands
)
977 return super().__init
__()
980 yield from self
.__db
.items()
982 def __getitem__(self
, key
):
983 return self
.__db
.__getitem
__(key
)
986 class FieldsDatabase
:
991 for (form
, fields
) in df
.instrs
.items():
992 if form
in {"DQE", "TX"}:
996 db
[_Form
[form
]] = Fields(fields
)
1000 return super().__init
__()
1002 def __getitem__(self
, key
):
1003 return self
.__db
.__getitem
__(key
)
1007 def __init__(self
, root
, mdwndb
, fieldsdb
):
1008 # The code below groups the instructions by section:identifier.
1009 # We use the comment as an identifier, there's nothing better.
1010 # The point is to capture different opcodes for the same instruction.
1011 dd
= _collections
.defaultdict
1012 records
= dd(lambda: dd(set))
1013 path
= (root
/ "insndb.csv")
1014 with
open(path
, "r", encoding
="UTF-8") as stream
:
1015 for section
in parse(stream
, Section
.CSV
):
1016 path
= (root
/ section
.path
)
1018 section
.Mode
.INTEGER
: IntegerOpcode
,
1019 section
.Mode
.PATTERN
: PatternOpcode
,
1021 factory
= _functools
.partial(PPCRecord
.CSV
, opcode_cls
=opcode_cls
)
1022 with
open(path
, "r", encoding
="UTF-8") as stream
:
1023 for insn
in parse(stream
, factory
):
1024 records
[section
][insn
.comment
].add(insn
)
1026 # Once we collected all instructions with the same identifier,
1027 # it's time to merge the different opcodes into the single pattern.
1028 # At this point, we only consider masks; the algorithm as follows:
1029 # 1. If any of two masks ignores the bit, it's ignored entirely.
1030 # 2. If the bit is not equal between masks, it's ignored.
1031 # 3. Otherwise the bits are equal and considered.
1032 def merge(lhs
, rhs
):
1035 lvalue
= lhs
.opcode
.value
1036 rvalue
= rhs
.opcode
.value
1037 lmask
= lhs
.opcode
.mask
1038 rmask
= rhs
.opcode
.mask
1039 bits
= max(lmask
.bit_length(), rmask
.bit_length())
1040 for bit
in range(bits
):
1041 lvstate
= ((lvalue
& (1 << bit
)) != 0)
1042 rvstate
= ((rvalue
& (1 << bit
)) != 0)
1043 lmstate
= ((lmask
& (1 << bit
)) != 0)
1044 rmstate
= ((rmask
& (1 << bit
)) != 0)
1047 if (not lmstate
or not rmstate
) or (lvstate
!= rvstate
):
1050 value |
= (vstate
<< bit
)
1051 mask |
= (mstate
<< bit
)
1052 return _dataclasses
.replace(lhs
, opcode
=Opcode(value
=value
, mask
=mask
))
1055 for (section
, group
) in records
.items():
1056 for records
in group
.values():
1057 db
[section
].add(_functools
.reduce(merge
, records
))
1060 self
.__mdwndb
= mdwndb
1061 self
.__fieldsdb
= fieldsdb
1063 return super().__init
__()
1065 def __getitem__(self
, key
):
1066 def exact_match(key
, record
):
1067 for name
in record
.names
:
1073 def Rc_match(key
, record
):
1074 if not key
.endswith("."):
1077 if not record
.Rc
is _RCOE
.RC
:
1080 return exact_match(key
[:-1], record
)
1082 def LK_match(key
, record
):
1083 if not key
.endswith("l"):
1086 if "lk" not in record
.flags
:
1089 return exact_match(key
[:-1], record
)
1091 def AA_match(key
, record
):
1092 if not key
.endswith("a"):
1095 if record
.intop
not in {_MicrOp
.OP_B
, _MicrOp
.OP_BC
}:
1098 if self
.__mdwndb
[key
]["AA"] is None:
1101 return (exact_match(key
[:-1], record
) or
1102 LK_match(key
[:-1], record
))
1104 for (section
, records
) in self
.__db
.items():
1105 for record
in records
:
1106 if (exact_match(key
, record
) or
1107 Rc_match(key
, record
) or
1108 LK_match(key
, record
) or
1109 AA_match(key
, record
)):
1110 return (section
, record
)
1115 class SVP64Database
:
1116 def __init__(self
, root
, ppcdb
):
1118 pattern
= _re
.compile(r
"^(?:LDST)?RM-(1P|2P)-.*?\.csv$")
1119 for (prefix
, _
, names
) in _os
.walk(root
):
1120 prefix
= _pathlib
.Path(prefix
)
1121 for name
in filter(lambda name
: pattern
.match(name
), names
):
1122 path
= (prefix
/ _pathlib
.Path(name
))
1123 with
open(path
, "r", encoding
="UTF-8") as stream
:
1124 db
.update(parse(stream
, SVP64Record
.CSV
))
1126 self
.__db
= {record
.name
:record
for record
in db
}
1127 self
.__ppcdb
= ppcdb
1129 return super().__init
__()
1131 def __getitem__(self
, key
):
1132 (_
, record
) = self
.__ppcdb
[key
]
1136 for name
in record
.names
:
1137 record
= self
.__db
.get(name
, None)
1138 if record
is not None:
1145 def __init__(self
, root
):
1146 root
= _pathlib
.Path(root
)
1148 mdwndb
= MarkdownDatabase()
1149 fieldsdb
= FieldsDatabase()
1150 ppcdb
= PPCDatabase(root
=root
, mdwndb
=mdwndb
, fieldsdb
=fieldsdb
)
1151 svp64db
= SVP64Database(root
=root
, ppcdb
=ppcdb
)
1154 for (name
, operands
) in mdwndb
:
1155 (section
, ppc
) = ppcdb
[name
]
1158 svp64
= svp64db
[name
]
1159 fields
= fieldsdb
[ppc
.form
]
1160 record
= Record(name
=name
,
1161 section
=section
, ppc
=ppc
, svp64
=svp64
,
1162 operands
=operands
, fields
=fields
)
1165 self
.__db
= tuple(sorted(db
))
1167 return super().__init
__()
1170 return repr(self
.__db
)
1173 yield from self
.__db
1175 @_functools.lru_cache(maxsize
=None)
1176 def __contains__(self
, key
):
1177 return self
.__getitem
__(key
) is not None
1179 @_functools.lru_cache(maxsize
=None)
1180 def __getitem__(self
, key
):
1181 if isinstance(key
, (int, Instruction
)):
1184 opcode
= record
.opcode
1185 if ((opcode
.value
& opcode
.mask
) ==
1186 (key
& opcode
.mask
)):
1189 elif isinstance(key
, Opcode
):
1191 if record
.opcode
== key
:
1193 elif isinstance(key
, str):
1195 if record
.name
== key
: