1 //===------------ FixedLenDecoderEmitter.cpp - Decoder Generator ----------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // It contains the tablegen backend that emits the decoder functions for
10 // targets with fixed length instruction set.
12 //===----------------------------------------------------------------------===//
14 #include "CodeGenInstruction.h"
15 #include "CodeGenTarget.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/CachedHashString.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/StringRef.h"
25 #include "llvm/MC/MCFixedLenDisassembler.h"
26 #include "llvm/Support/Casting.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/FormattedStream.h"
30 #include "llvm/Support/LEB128.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/TableGen/Error.h"
33 #include "llvm/TableGen/Record.h"
47 #define DEBUG_TYPE "decoder-emitter"
51 STATISTIC(NumEncodings
, "Number of encodings considered");
52 STATISTIC(NumEncodingsLackingDisasm
, "Number of encodings without disassembler info");
53 STATISTIC(NumInstructions
, "Number of instructions considered");
54 STATISTIC(NumEncodingsSupported
, "Number of encodings supported");
55 STATISTIC(NumEncodingsOmitted
, "Number of encodings omitted");
57 struct EncodingField
{
58 unsigned Base
, Width
, Offset
;
59 EncodingField(unsigned B
, unsigned W
, unsigned O
)
60 : Base(B
), Width(W
), Offset(O
) { }
64 std::vector
<EncodingField
> Fields
;
66 bool HasCompleteDecoder
;
68 OperandInfo(std::string D
, bool HCD
)
69 : Decoder(std::move(D
)), HasCompleteDecoder(HCD
) {}
71 void addField(unsigned Base
, unsigned Width
, unsigned Offset
) {
72 Fields
.push_back(EncodingField(Base
, Width
, Offset
));
75 unsigned numFields() const { return Fields
.size(); }
77 typedef std::vector
<EncodingField
>::const_iterator const_iterator
;
79 const_iterator
begin() const { return Fields
.begin(); }
80 const_iterator
end() const { return Fields
.end(); }
83 typedef std::vector
<uint8_t> DecoderTable
;
84 typedef uint32_t DecoderFixup
;
85 typedef std::vector
<DecoderFixup
> FixupList
;
86 typedef std::vector
<FixupList
> FixupScopeList
;
87 typedef SmallSetVector
<CachedHashString
, 16> PredicateSet
;
88 typedef SmallSetVector
<CachedHashString
, 16> DecoderSet
;
89 struct DecoderTableInfo
{
91 FixupScopeList FixupStack
;
92 PredicateSet Predicates
;
96 struct EncodingAndInst
{
97 const Record
*EncodingDef
;
98 const CodeGenInstruction
*Inst
;
100 EncodingAndInst(const Record
*EncodingDef
, const CodeGenInstruction
*Inst
)
101 : EncodingDef(EncodingDef
), Inst(Inst
) {}
104 struct EncodingIDAndOpcode
{
108 EncodingIDAndOpcode() : EncodingID(0), Opcode(0) {}
109 EncodingIDAndOpcode(unsigned EncodingID
, unsigned Opcode
)
110 : EncodingID(EncodingID
), Opcode(Opcode
) {}
113 raw_ostream
&operator<<(raw_ostream
&OS
, const EncodingAndInst
&Value
) {
114 if (Value
.EncodingDef
!= Value
.Inst
->TheDef
)
115 OS
<< Value
.EncodingDef
->getName() << ":";
116 OS
<< Value
.Inst
->TheDef
->getName();
120 class FixedLenDecoderEmitter
{
122 std::vector
<EncodingAndInst
> NumberedEncodings
;
125 // Defaults preserved here for documentation, even though they aren't
126 // strictly necessary given the way that this is currently being called.
127 FixedLenDecoderEmitter(RecordKeeper
&R
, std::string PredicateNamespace
,
128 std::string GPrefix
= "if (",
129 std::string GPostfix
= " == MCDisassembler::Fail)",
130 std::string ROK
= "MCDisassembler::Success",
131 std::string RFail
= "MCDisassembler::Fail",
133 : RK(R
), Target(R
), PredicateNamespace(std::move(PredicateNamespace
)),
134 GuardPrefix(std::move(GPrefix
)), GuardPostfix(std::move(GPostfix
)),
135 ReturnOK(std::move(ROK
)), ReturnFail(std::move(RFail
)),
136 Locals(std::move(L
)) {}
138 // Emit the decoder state machine table.
139 void emitTable(formatted_raw_ostream
&o
, DecoderTable
&Table
,
140 unsigned Indentation
, unsigned BitWidth
,
141 StringRef Namespace
) const;
142 void emitPredicateFunction(formatted_raw_ostream
&OS
,
143 PredicateSet
&Predicates
,
144 unsigned Indentation
) const;
145 void emitDecoderFunction(formatted_raw_ostream
&OS
,
146 DecoderSet
&Decoders
,
147 unsigned Indentation
) const;
149 // run - Output the code emitter
150 void run(raw_ostream
&o
);
153 CodeGenTarget Target
;
156 std::string PredicateNamespace
;
157 std::string GuardPrefix
, GuardPostfix
;
158 std::string ReturnOK
, ReturnFail
;
162 } // end anonymous namespace
164 // The set (BIT_TRUE, BIT_FALSE, BIT_UNSET) represents a ternary logic system
167 // BIT_UNFILTERED is used as the init value for a filter position. It is used
168 // only for filter processings.
173 BIT_UNFILTERED
// unfiltered
176 static bool ValueSet(bit_value_t V
) {
177 return (V
== BIT_TRUE
|| V
== BIT_FALSE
);
180 static bool ValueNotSet(bit_value_t V
) {
181 return (V
== BIT_UNSET
);
184 static int Value(bit_value_t V
) {
185 return ValueNotSet(V
) ? -1 : (V
== BIT_FALSE
? 0 : 1);
188 static bit_value_t
bitFromBits(const BitsInit
&bits
, unsigned index
) {
189 if (BitInit
*bit
= dyn_cast
<BitInit
>(bits
.getBit(index
)))
190 return bit
->getValue() ? BIT_TRUE
: BIT_FALSE
;
192 // The bit is uninitialized.
196 // Prints the bit value for each position.
197 static void dumpBits(raw_ostream
&o
, const BitsInit
&bits
) {
198 for (unsigned index
= bits
.getNumBits(); index
> 0; --index
) {
199 switch (bitFromBits(bits
, index
- 1)) {
210 llvm_unreachable("unexpected return value from bitFromBits");
215 static BitsInit
&getBitsField(const Record
&def
, StringRef str
) {
216 BitsInit
*bits
= def
.getValueAsBitsInit(str
);
220 // Representation of the instruction to work on.
221 typedef std::vector
<bit_value_t
> insn_t
;
227 /// Filter - Filter works with FilterChooser to produce the decoding tree for
230 /// It is useful to think of a Filter as governing the switch stmts of the
231 /// decoding tree in a certain level. Each case stmt delegates to an inferior
232 /// FilterChooser to decide what further decoding logic to employ, or in another
233 /// words, what other remaining bits to look at. The FilterChooser eventually
234 /// chooses a best Filter to do its job.
236 /// This recursive scheme ends when the number of Opcodes assigned to the
237 /// FilterChooser becomes 1 or if there is a conflict. A conflict happens when
238 /// the Filter/FilterChooser combo does not know how to distinguish among the
239 /// Opcodes assigned.
241 /// An example of a conflict is
244 /// 111101000.00........00010000....
245 /// 111101000.00........0001........
246 /// 1111010...00........0001........
247 /// 1111010...00....................
248 /// 1111010.........................
249 /// 1111............................
250 /// ................................
251 /// VST4q8a 111101000_00________00010000____
252 /// VST4q8b 111101000_00________00010000____
254 /// The Debug output shows the path that the decoding tree follows to reach the
255 /// the conclusion that there is a conflict. VST4q8a is a vst4 to double-spaced
256 /// even registers, while VST4q8b is a vst4 to double-spaced odd registers.
258 /// The encoding info in the .td files does not specify this meta information,
259 /// which could have been used by the decoder to resolve the conflict. The
260 /// decoder could try to decode the even/odd register numbering and assign to
261 /// VST4q8a or VST4q8b, but for the time being, the decoder chooses the "a"
262 /// version and return the Opcode since the two have the same Asm format string.
265 const FilterChooser
*Owner
;// points to the FilterChooser who owns this filter
266 unsigned StartBit
; // the starting bit position
267 unsigned NumBits
; // number of bits to filter
268 bool Mixed
; // a mixed region contains both set and unset bits
270 // Map of well-known segment value to the set of uid's with that value.
271 std::map
<uint64_t, std::vector
<EncodingIDAndOpcode
>>
272 FilteredInstructions
;
274 // Set of uid's with non-constant segment values.
275 std::vector
<EncodingIDAndOpcode
> VariableInstructions
;
277 // Map of well-known segment value to its delegate.
278 std::map
<unsigned, std::unique_ptr
<const FilterChooser
>> FilterChooserMap
;
280 // Number of instructions which fall under FilteredInstructions category.
281 unsigned NumFiltered
;
283 // Keeps track of the last opcode in the filtered bucket.
284 EncodingIDAndOpcode LastOpcFiltered
;
288 Filter(FilterChooser
&owner
, unsigned startBit
, unsigned numBits
, bool mixed
);
292 unsigned getNumFiltered() const { return NumFiltered
; }
294 EncodingIDAndOpcode
getSingletonOpc() const {
295 assert(NumFiltered
== 1);
296 return LastOpcFiltered
;
299 // Return the filter chooser for the group of instructions without constant
301 const FilterChooser
&getVariableFC() const {
302 assert(NumFiltered
== 1);
303 assert(FilterChooserMap
.size() == 1);
304 return *(FilterChooserMap
.find((unsigned)-1)->second
);
307 // Divides the decoding task into sub tasks and delegates them to the
308 // inferior FilterChooser's.
310 // A special case arises when there's only one entry in the filtered
311 // instructions. In order to unambiguously decode the singleton, we need to
312 // match the remaining undecoded encoding bits against the singleton.
315 // Emit table entries to decode instructions given a segment or segments of
317 void emitTableEntry(DecoderTableInfo
&TableInfo
) const;
319 // Returns the number of fanout produced by the filter. More fanout implies
320 // the filter distinguishes more categories of instructions.
321 unsigned usefulness() const;
322 }; // end class Filter
324 } // end anonymous namespace
326 // These are states of our finite state machines used in FilterChooser's
327 // filterProcessor() which produces the filter candidates to use.
336 /// FilterChooser - FilterChooser chooses the best filter among a set of Filters
337 /// in order to perform the decoding of instructions at the current level.
339 /// Decoding proceeds from the top down. Based on the well-known encoding bits
340 /// of instructions available, FilterChooser builds up the possible Filters that
341 /// can further the task of decoding by distinguishing among the remaining
342 /// candidate instructions.
344 /// Once a filter has been chosen, it is called upon to divide the decoding task
345 /// into sub-tasks and delegates them to its inferior FilterChoosers for further
348 /// It is useful to think of a Filter as governing the switch stmts of the
349 /// decoding tree. And each case is delegated to an inferior FilterChooser to
350 /// decide what further remaining bits to look at.
353 class FilterChooser
{
357 // Vector of codegen instructions to choose our filter.
358 ArrayRef
<EncodingAndInst
> AllInstructions
;
360 // Vector of uid's for this filter chooser to work on.
361 // The first member of the pair is the opcode id being decoded, the second is
362 // the opcode id that should be emitted.
363 const std::vector
<EncodingIDAndOpcode
> &Opcodes
;
365 // Lookup table for the operand decoding of instructions.
366 const std::map
<unsigned, std::vector
<OperandInfo
>> &Operands
;
368 // Vector of candidate filters.
369 std::vector
<Filter
> Filters
;
371 // Array of bit values passed down from our parent.
372 // Set to all BIT_UNFILTERED's for Parent == NULL.
373 std::vector
<bit_value_t
> FilterBitValues
;
375 // Links to the FilterChooser above us in the decoding tree.
376 const FilterChooser
*Parent
;
378 // Index of the best filter from Filters.
381 // Width of instructions
385 const FixedLenDecoderEmitter
*Emitter
;
388 FilterChooser(ArrayRef
<EncodingAndInst
> Insts
,
389 const std::vector
<EncodingIDAndOpcode
> &IDs
,
390 const std::map
<unsigned, std::vector
<OperandInfo
>> &Ops
,
391 unsigned BW
, const FixedLenDecoderEmitter
*E
)
392 : AllInstructions(Insts
), Opcodes(IDs
), Operands(Ops
),
393 FilterBitValues(BW
, BIT_UNFILTERED
), Parent(nullptr), BestIndex(-1),
394 BitWidth(BW
), Emitter(E
) {
398 FilterChooser(ArrayRef
<EncodingAndInst
> Insts
,
399 const std::vector
<EncodingIDAndOpcode
> &IDs
,
400 const std::map
<unsigned, std::vector
<OperandInfo
>> &Ops
,
401 const std::vector
<bit_value_t
> &ParentFilterBitValues
,
402 const FilterChooser
&parent
)
403 : AllInstructions(Insts
), Opcodes(IDs
), Operands(Ops
),
404 FilterBitValues(ParentFilterBitValues
), Parent(&parent
), BestIndex(-1),
405 BitWidth(parent
.BitWidth
), Emitter(parent
.Emitter
) {
409 FilterChooser(const FilterChooser
&) = delete;
410 void operator=(const FilterChooser
&) = delete;
412 unsigned getBitWidth() const { return BitWidth
; }
415 // Populates the insn given the uid.
416 void insnWithID(insn_t
&Insn
, unsigned Opcode
) const {
417 BitsInit
&Bits
= getBitsField(*AllInstructions
[Opcode
].EncodingDef
, "Inst");
419 // We may have a SoftFail bitmask, which specifies a mask where an encoding
420 // may differ from the value in "Inst" and yet still be valid, but the
421 // disassembler should return SoftFail instead of Success.
423 // This is used for marking UNPREDICTABLE instructions in the ARM world.
425 AllInstructions
[Opcode
].EncodingDef
->getValueAsBitsInit("SoftFail");
427 for (unsigned i
= 0; i
< BitWidth
; ++i
) {
428 if (SFBits
&& bitFromBits(*SFBits
, i
) == BIT_TRUE
)
429 Insn
.push_back(BIT_UNSET
);
431 Insn
.push_back(bitFromBits(Bits
, i
));
435 // Emit the name of the encoding/instruction pair.
436 void emitNameWithID(raw_ostream
&OS
, unsigned Opcode
) const {
437 const Record
*EncodingDef
= AllInstructions
[Opcode
].EncodingDef
;
438 const Record
*InstDef
= AllInstructions
[Opcode
].Inst
->TheDef
;
439 if (EncodingDef
!= InstDef
)
440 OS
<< EncodingDef
->getName() << ":";
441 OS
<< InstDef
->getName();
444 // Populates the field of the insn given the start position and the number of
445 // consecutive bits to scan for.
447 // Returns false if there exists any uninitialized bit value in the range.
448 // Returns true, otherwise.
449 bool fieldFromInsn(uint64_t &Field
, insn_t
&Insn
, unsigned StartBit
,
450 unsigned NumBits
) const;
452 /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
453 /// filter array as a series of chars.
454 void dumpFilterArray(raw_ostream
&o
,
455 const std::vector
<bit_value_t
> & filter
) const;
457 /// dumpStack - dumpStack traverses the filter chooser chain and calls
458 /// dumpFilterArray on each filter chooser up to the top level one.
459 void dumpStack(raw_ostream
&o
, const char *prefix
) const;
461 Filter
&bestFilter() {
462 assert(BestIndex
!= -1 && "BestIndex not set");
463 return Filters
[BestIndex
];
466 bool PositionFiltered(unsigned i
) const {
467 return ValueSet(FilterBitValues
[i
]);
470 // Calculates the island(s) needed to decode the instruction.
471 // This returns a lit of undecoded bits of an instructions, for example,
472 // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
473 // decoded bits in order to verify that the instruction matches the Opcode.
474 unsigned getIslands(std::vector
<unsigned> &StartBits
,
475 std::vector
<unsigned> &EndBits
,
476 std::vector
<uint64_t> &FieldVals
,
477 const insn_t
&Insn
) const;
479 // Emits code to check the Predicates member of an instruction are true.
480 // Returns true if predicate matches were emitted, false otherwise.
481 bool emitPredicateMatch(raw_ostream
&o
, unsigned &Indentation
,
484 bool doesOpcodeNeedPredicate(unsigned Opc
) const;
485 unsigned getPredicateIndex(DecoderTableInfo
&TableInfo
, StringRef P
) const;
486 void emitPredicateTableEntry(DecoderTableInfo
&TableInfo
,
489 void emitSoftFailTableEntry(DecoderTableInfo
&TableInfo
,
492 // Emits table entries to decode the singleton.
493 void emitSingletonTableEntry(DecoderTableInfo
&TableInfo
,
494 EncodingIDAndOpcode Opc
) const;
496 // Emits code to decode the singleton, and then to decode the rest.
497 void emitSingletonTableEntry(DecoderTableInfo
&TableInfo
,
498 const Filter
&Best
) const;
500 void emitBinaryParser(raw_ostream
&o
, unsigned &Indentation
,
501 const OperandInfo
&OpInfo
,
502 bool &OpHasCompleteDecoder
) const;
504 void emitDecoder(raw_ostream
&OS
, unsigned Indentation
, unsigned Opc
,
505 bool &HasCompleteDecoder
) const;
506 unsigned getDecoderIndex(DecoderSet
&Decoders
, unsigned Opc
,
507 bool &HasCompleteDecoder
) const;
509 // Assign a single filter and run with it.
510 void runSingleFilter(unsigned startBit
, unsigned numBit
, bool mixed
);
512 // reportRegion is a helper function for filterProcessor to mark a region as
513 // eligible for use as a filter region.
514 void reportRegion(bitAttr_t RA
, unsigned StartBit
, unsigned BitIndex
,
517 // FilterProcessor scans the well-known encoding bits of the instructions and
518 // builds up a list of candidate filters. It chooses the best filter and
519 // recursively descends down the decoding tree.
520 bool filterProcessor(bool AllowMixed
, bool Greedy
= true);
522 // Decides on the best configuration of filter(s) to use in order to decode
523 // the instructions. A conflict of instructions may occur, in which case we
524 // dump the conflict set to the standard error.
528 // emitTableEntries - Emit state machine entries to decode our share of
530 void emitTableEntries(DecoderTableInfo
&TableInfo
) const;
533 } // end anonymous namespace
535 ///////////////////////////
537 // Filter Implementation //
539 ///////////////////////////
541 Filter::Filter(Filter
&&f
)
542 : Owner(f
.Owner
), StartBit(f
.StartBit
), NumBits(f
.NumBits
), Mixed(f
.Mixed
),
543 FilteredInstructions(std::move(f
.FilteredInstructions
)),
544 VariableInstructions(std::move(f
.VariableInstructions
)),
545 FilterChooserMap(std::move(f
.FilterChooserMap
)), NumFiltered(f
.NumFiltered
),
546 LastOpcFiltered(f
.LastOpcFiltered
) {
549 Filter::Filter(FilterChooser
&owner
, unsigned startBit
, unsigned numBits
,
551 : Owner(&owner
), StartBit(startBit
), NumBits(numBits
), Mixed(mixed
) {
552 assert(StartBit
+ NumBits
- 1 < Owner
->BitWidth
);
555 LastOpcFiltered
= {0, 0};
557 for (unsigned i
= 0, e
= Owner
->Opcodes
.size(); i
!= e
; ++i
) {
560 // Populates the insn given the uid.
561 Owner
->insnWithID(Insn
, Owner
->Opcodes
[i
].EncodingID
);
564 // Scans the segment for possibly well-specified encoding bits.
565 bool ok
= Owner
->fieldFromInsn(Field
, Insn
, StartBit
, NumBits
);
568 // The encoding bits are well-known. Lets add the uid of the
569 // instruction into the bucket keyed off the constant field value.
570 LastOpcFiltered
= Owner
->Opcodes
[i
];
571 FilteredInstructions
[Field
].push_back(LastOpcFiltered
);
574 // Some of the encoding bit(s) are unspecified. This contributes to
575 // one additional member of "Variable" instructions.
576 VariableInstructions
.push_back(Owner
->Opcodes
[i
]);
580 assert((FilteredInstructions
.size() + VariableInstructions
.size() > 0)
581 && "Filter returns no instruction categories");
584 // Divides the decoding task into sub tasks and delegates them to the
585 // inferior FilterChooser's.
587 // A special case arises when there's only one entry in the filtered
588 // instructions. In order to unambiguously decode the singleton, we need to
589 // match the remaining undecoded encoding bits against the singleton.
590 void Filter::recurse() {
591 // Starts by inheriting our parent filter chooser's filter bit values.
592 std::vector
<bit_value_t
> BitValueArray(Owner
->FilterBitValues
);
594 if (!VariableInstructions
.empty()) {
595 // Conservatively marks each segment position as BIT_UNSET.
596 for (unsigned bitIndex
= 0; bitIndex
< NumBits
; ++bitIndex
)
597 BitValueArray
[StartBit
+ bitIndex
] = BIT_UNSET
;
599 // Delegates to an inferior filter chooser for further processing on this
600 // group of instructions whose segment values are variable.
601 FilterChooserMap
.insert(
602 std::make_pair(-1U, llvm::make_unique
<FilterChooser
>(
603 Owner
->AllInstructions
, VariableInstructions
,
604 Owner
->Operands
, BitValueArray
, *Owner
)));
607 // No need to recurse for a singleton filtered instruction.
608 // See also Filter::emit*().
609 if (getNumFiltered() == 1) {
610 assert(FilterChooserMap
.size() == 1);
614 // Otherwise, create sub choosers.
615 for (const auto &Inst
: FilteredInstructions
) {
617 // Marks all the segment positions with either BIT_TRUE or BIT_FALSE.
618 for (unsigned bitIndex
= 0; bitIndex
< NumBits
; ++bitIndex
) {
619 if (Inst
.first
& (1ULL << bitIndex
))
620 BitValueArray
[StartBit
+ bitIndex
] = BIT_TRUE
;
622 BitValueArray
[StartBit
+ bitIndex
] = BIT_FALSE
;
625 // Delegates to an inferior filter chooser for further processing on this
626 // category of instructions.
627 FilterChooserMap
.insert(std::make_pair(
628 Inst
.first
, llvm::make_unique
<FilterChooser
>(
629 Owner
->AllInstructions
, Inst
.second
,
630 Owner
->Operands
, BitValueArray
, *Owner
)));
634 static void resolveTableFixups(DecoderTable
&Table
, const FixupList
&Fixups
,
636 // Any NumToSkip fixups in the current scope can resolve to the
638 for (FixupList::const_reverse_iterator I
= Fixups
.rbegin(),
641 // Calculate the distance from the byte following the fixup entry byte
642 // to the destination. The Target is calculated from after the 16-bit
643 // NumToSkip entry itself, so subtract two from the displacement here
644 // to account for that.
645 uint32_t FixupIdx
= *I
;
646 uint32_t Delta
= DestIdx
- FixupIdx
- 3;
647 // Our NumToSkip entries are 24-bits. Make sure our table isn't too
649 assert(Delta
< (1u << 24));
650 Table
[FixupIdx
] = (uint8_t)Delta
;
651 Table
[FixupIdx
+ 1] = (uint8_t)(Delta
>> 8);
652 Table
[FixupIdx
+ 2] = (uint8_t)(Delta
>> 16);
656 // Emit table entries to decode instructions given a segment or segments
658 void Filter::emitTableEntry(DecoderTableInfo
&TableInfo
) const {
659 TableInfo
.Table
.push_back(MCD::OPC_ExtractField
);
660 TableInfo
.Table
.push_back(StartBit
);
661 TableInfo
.Table
.push_back(NumBits
);
663 // A new filter entry begins a new scope for fixup resolution.
664 TableInfo
.FixupStack
.emplace_back();
666 DecoderTable
&Table
= TableInfo
.Table
;
668 size_t PrevFilter
= 0;
669 bool HasFallthrough
= false;
670 for (auto &Filter
: FilterChooserMap
) {
671 // Field value -1 implies a non-empty set of variable instructions.
672 // See also recurse().
673 if (Filter
.first
== (unsigned)-1) {
674 HasFallthrough
= true;
676 // Each scope should always have at least one filter value to check
678 assert(PrevFilter
!= 0 && "empty filter set!");
679 FixupList
&CurScope
= TableInfo
.FixupStack
.back();
680 // Resolve any NumToSkip fixups in the current scope.
681 resolveTableFixups(Table
, CurScope
, Table
.size());
683 PrevFilter
= 0; // Don't re-process the filter's fallthrough.
685 Table
.push_back(MCD::OPC_FilterValue
);
686 // Encode and emit the value to filter against.
688 unsigned Len
= encodeULEB128(Filter
.first
, Buffer
);
689 Table
.insert(Table
.end(), Buffer
, Buffer
+ Len
);
690 // Reserve space for the NumToSkip entry. We'll backpatch the value
692 PrevFilter
= Table
.size();
698 // We arrive at a category of instructions with the same segment value.
699 // Now delegate to the sub filter chooser for further decodings.
700 // The case may fallthrough, which happens if the remaining well-known
701 // encoding bits do not match exactly.
702 Filter
.second
->emitTableEntries(TableInfo
);
704 // Now that we've emitted the body of the handler, update the NumToSkip
705 // of the filter itself to be able to skip forward when false. Subtract
706 // two as to account for the width of the NumToSkip field itself.
708 uint32_t NumToSkip
= Table
.size() - PrevFilter
- 3;
709 assert(NumToSkip
< (1u << 24) && "disassembler decoding table too large!");
710 Table
[PrevFilter
] = (uint8_t)NumToSkip
;
711 Table
[PrevFilter
+ 1] = (uint8_t)(NumToSkip
>> 8);
712 Table
[PrevFilter
+ 2] = (uint8_t)(NumToSkip
>> 16);
716 // Any remaining unresolved fixups bubble up to the parent fixup scope.
717 assert(TableInfo
.FixupStack
.size() > 1 && "fixup stack underflow!");
718 FixupScopeList::iterator Source
= TableInfo
.FixupStack
.end() - 1;
719 FixupScopeList::iterator Dest
= Source
- 1;
720 Dest
->insert(Dest
->end(), Source
->begin(), Source
->end());
721 TableInfo
.FixupStack
.pop_back();
723 // If there is no fallthrough, then the final filter should get fixed
724 // up according to the enclosing scope rather than the current position.
726 TableInfo
.FixupStack
.back().push_back(PrevFilter
);
729 // Returns the number of fanout produced by the filter. More fanout implies
730 // the filter distinguishes more categories of instructions.
731 unsigned Filter::usefulness() const {
732 if (!VariableInstructions
.empty())
733 return FilteredInstructions
.size();
735 return FilteredInstructions
.size() + 1;
738 //////////////////////////////////
740 // Filterchooser Implementation //
742 //////////////////////////////////
744 // Emit the decoder state machine table.
745 void FixedLenDecoderEmitter::emitTable(formatted_raw_ostream
&OS
,
747 unsigned Indentation
,
749 StringRef Namespace
) const {
750 OS
.indent(Indentation
) << "static const uint8_t DecoderTable" << Namespace
751 << BitWidth
<< "[] = {\n";
755 // FIXME: We may be able to use the NumToSkip values to recover
756 // appropriate indentation levels.
757 DecoderTable::const_iterator I
= Table
.begin();
758 DecoderTable::const_iterator E
= Table
.end();
760 assert (I
< E
&& "incomplete decode table entry!");
762 uint64_t Pos
= I
- Table
.begin();
763 OS
<< "/* " << Pos
<< " */";
768 PrintFatalError("invalid decode table opcode");
769 case MCD::OPC_ExtractField
: {
771 unsigned Start
= *I
++;
773 OS
.indent(Indentation
) << "MCD::OPC_ExtractField, " << Start
<< ", "
774 << Len
<< ", // Inst{";
776 OS
<< (Start
+ Len
- 1) << "-";
777 OS
<< Start
<< "} ...\n";
780 case MCD::OPC_FilterValue
: {
782 OS
.indent(Indentation
) << "MCD::OPC_FilterValue, ";
783 // The filter value is ULEB128 encoded.
785 OS
<< (unsigned)*I
++ << ", ";
786 OS
<< (unsigned)*I
++ << ", ";
788 // 24-bit numtoskip value.
790 uint32_t NumToSkip
= Byte
;
791 OS
<< (unsigned)Byte
<< ", ";
793 OS
<< (unsigned)Byte
<< ", ";
794 NumToSkip
|= Byte
<< 8;
796 OS
<< utostr(Byte
) << ", ";
797 NumToSkip
|= Byte
<< 16;
798 OS
<< "// Skip to: " << ((I
- Table
.begin()) + NumToSkip
) << "\n";
801 case MCD::OPC_CheckField
: {
803 unsigned Start
= *I
++;
805 OS
.indent(Indentation
) << "MCD::OPC_CheckField, " << Start
<< ", "
806 << Len
<< ", ";// << Val << ", " << NumToSkip << ",\n";
807 // ULEB128 encoded field value.
808 for (; *I
>= 128; ++I
)
809 OS
<< (unsigned)*I
<< ", ";
810 OS
<< (unsigned)*I
++ << ", ";
811 // 24-bit numtoskip value.
813 uint32_t NumToSkip
= Byte
;
814 OS
<< (unsigned)Byte
<< ", ";
816 OS
<< (unsigned)Byte
<< ", ";
817 NumToSkip
|= Byte
<< 8;
819 OS
<< utostr(Byte
) << ", ";
820 NumToSkip
|= Byte
<< 16;
821 OS
<< "// Skip to: " << ((I
- Table
.begin()) + NumToSkip
) << "\n";
824 case MCD::OPC_CheckPredicate
: {
826 OS
.indent(Indentation
) << "MCD::OPC_CheckPredicate, ";
827 for (; *I
>= 128; ++I
)
828 OS
<< (unsigned)*I
<< ", ";
829 OS
<< (unsigned)*I
++ << ", ";
831 // 24-bit numtoskip value.
833 uint32_t NumToSkip
= Byte
;
834 OS
<< (unsigned)Byte
<< ", ";
836 OS
<< (unsigned)Byte
<< ", ";
837 NumToSkip
|= Byte
<< 8;
839 OS
<< utostr(Byte
) << ", ";
840 NumToSkip
|= Byte
<< 16;
841 OS
<< "// Skip to: " << ((I
- Table
.begin()) + NumToSkip
) << "\n";
844 case MCD::OPC_Decode
:
845 case MCD::OPC_TryDecode
: {
846 bool IsTry
= *I
== MCD::OPC_TryDecode
;
848 // Extract the ULEB128 encoded Opcode to a buffer.
849 uint8_t Buffer
[16], *p
= Buffer
;
850 while ((*p
++ = *I
++) >= 128)
851 assert((p
- Buffer
) <= (ptrdiff_t)sizeof(Buffer
)
852 && "ULEB128 value too large!");
853 // Decode the Opcode value.
854 unsigned Opc
= decodeULEB128(Buffer
);
855 OS
.indent(Indentation
) << "MCD::OPC_" << (IsTry
? "Try" : "")
857 for (p
= Buffer
; *p
>= 128; ++p
)
858 OS
<< (unsigned)*p
<< ", ";
859 OS
<< (unsigned)*p
<< ", ";
862 for (; *I
>= 128; ++I
)
863 OS
<< (unsigned)*I
<< ", ";
864 OS
<< (unsigned)*I
++ << ", ";
867 OS
<< "// Opcode: " << NumberedEncodings
[Opc
] << "\n";
871 // Fallthrough for OPC_TryDecode.
873 // 24-bit numtoskip value.
875 uint32_t NumToSkip
= Byte
;
876 OS
<< (unsigned)Byte
<< ", ";
878 OS
<< (unsigned)Byte
<< ", ";
879 NumToSkip
|= Byte
<< 8;
881 OS
<< utostr(Byte
) << ", ";
882 NumToSkip
|= Byte
<< 16;
884 OS
<< "// Opcode: " << NumberedEncodings
[Opc
]
885 << ", skip to: " << ((I
- Table
.begin()) + NumToSkip
) << "\n";
888 case MCD::OPC_SoftFail
: {
890 OS
.indent(Indentation
) << "MCD::OPC_SoftFail";
895 OS
<< ", " << (unsigned)*I
;
896 Value
+= (*I
& 0x7f) << Shift
;
898 } while (*I
++ >= 128);
908 OS
<< ", " << (unsigned)*I
;
909 Value
+= (*I
& 0x7f) << Shift
;
911 } while (*I
++ >= 128);
920 case MCD::OPC_Fail
: {
922 OS
.indent(Indentation
) << "MCD::OPC_Fail,\n";
927 OS
.indent(Indentation
) << "0\n";
931 OS
.indent(Indentation
) << "};\n\n";
934 void FixedLenDecoderEmitter::
935 emitPredicateFunction(formatted_raw_ostream
&OS
, PredicateSet
&Predicates
,
936 unsigned Indentation
) const {
937 // The predicate function is just a big switch statement based on the
938 // input predicate index.
939 OS
.indent(Indentation
) << "static bool checkDecoderPredicate(unsigned Idx, "
940 << "const FeatureBitset& Bits) {\n";
942 if (!Predicates
.empty()) {
943 OS
.indent(Indentation
) << "switch (Idx) {\n";
944 OS
.indent(Indentation
) << "default: llvm_unreachable(\"Invalid index!\");\n";
946 for (const auto &Predicate
: Predicates
) {
947 OS
.indent(Indentation
) << "case " << Index
++ << ":\n";
948 OS
.indent(Indentation
+2) << "return (" << Predicate
<< ");\n";
950 OS
.indent(Indentation
) << "}\n";
952 // No case statement to emit
953 OS
.indent(Indentation
) << "llvm_unreachable(\"Invalid index!\");\n";
956 OS
.indent(Indentation
) << "}\n\n";
959 void FixedLenDecoderEmitter::
960 emitDecoderFunction(formatted_raw_ostream
&OS
, DecoderSet
&Decoders
,
961 unsigned Indentation
) const {
962 // The decoder function is just a big switch statement based on the
963 // input decoder index.
964 OS
.indent(Indentation
) << "template<typename InsnType>\n";
965 OS
.indent(Indentation
) << "static DecodeStatus decodeToMCInst(DecodeStatus S,"
966 << " unsigned Idx, InsnType insn, MCInst &MI,\n";
967 OS
.indent(Indentation
) << " uint64_t "
968 << "Address, const void *Decoder, bool &DecodeComplete) {\n";
970 OS
.indent(Indentation
) << "DecodeComplete = true;\n";
971 OS
.indent(Indentation
) << "InsnType tmp;\n";
972 OS
.indent(Indentation
) << "switch (Idx) {\n";
973 OS
.indent(Indentation
) << "default: llvm_unreachable(\"Invalid index!\");\n";
975 for (const auto &Decoder
: Decoders
) {
976 OS
.indent(Indentation
) << "case " << Index
++ << ":\n";
978 OS
.indent(Indentation
+2) << "return S;\n";
980 OS
.indent(Indentation
) << "}\n";
982 OS
.indent(Indentation
) << "}\n\n";
985 // Populates the field of the insn given the start position and the number of
986 // consecutive bits to scan for.
988 // Returns false if and on the first uninitialized bit value encountered.
989 // Returns true, otherwise.
990 bool FilterChooser::fieldFromInsn(uint64_t &Field
, insn_t
&Insn
,
991 unsigned StartBit
, unsigned NumBits
) const {
994 for (unsigned i
= 0; i
< NumBits
; ++i
) {
995 if (Insn
[StartBit
+ i
] == BIT_UNSET
)
998 if (Insn
[StartBit
+ i
] == BIT_TRUE
)
999 Field
= Field
| (1ULL << i
);
1005 /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
1006 /// filter array as a series of chars.
1007 void FilterChooser::dumpFilterArray(raw_ostream
&o
,
1008 const std::vector
<bit_value_t
> &filter
) const {
1009 for (unsigned bitIndex
= BitWidth
; bitIndex
> 0; bitIndex
--) {
1010 switch (filter
[bitIndex
- 1]) {
1011 case BIT_UNFILTERED
:
1027 /// dumpStack - dumpStack traverses the filter chooser chain and calls
1028 /// dumpFilterArray on each filter chooser up to the top level one.
1029 void FilterChooser::dumpStack(raw_ostream
&o
, const char *prefix
) const {
1030 const FilterChooser
*current
= this;
1034 dumpFilterArray(o
, current
->FilterBitValues
);
1036 current
= current
->Parent
;
1040 // Calculates the island(s) needed to decode the instruction.
1041 // This returns a list of undecoded bits of an instructions, for example,
1042 // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
1043 // decoded bits in order to verify that the instruction matches the Opcode.
1044 unsigned FilterChooser::getIslands(std::vector
<unsigned> &StartBits
,
1045 std::vector
<unsigned> &EndBits
,
1046 std::vector
<uint64_t> &FieldVals
,
1047 const insn_t
&Insn
) const {
1048 unsigned Num
, BitNo
;
1051 uint64_t FieldVal
= 0;
1054 // 1: Water (the bit value does not affect decoding)
1055 // 2: Island (well-known bit value needed for decoding)
1059 for (unsigned i
= 0; i
< BitWidth
; ++i
) {
1060 Val
= Value(Insn
[i
]);
1061 bool Filtered
= PositionFiltered(i
);
1063 default: llvm_unreachable("Unreachable code!");
1066 if (Filtered
|| Val
== -1)
1067 State
= 1; // Still in Water
1069 State
= 2; // Into the Island
1071 StartBits
.push_back(i
);
1076 if (Filtered
|| Val
== -1) {
1077 State
= 1; // Into the Water
1078 EndBits
.push_back(i
- 1);
1079 FieldVals
.push_back(FieldVal
);
1082 State
= 2; // Still in Island
1084 FieldVal
= FieldVal
| Val
<< BitNo
;
1089 // If we are still in Island after the loop, do some housekeeping.
1091 EndBits
.push_back(BitWidth
- 1);
1092 FieldVals
.push_back(FieldVal
);
1096 assert(StartBits
.size() == Num
&& EndBits
.size() == Num
&&
1097 FieldVals
.size() == Num
);
1101 void FilterChooser::emitBinaryParser(raw_ostream
&o
, unsigned &Indentation
,
1102 const OperandInfo
&OpInfo
,
1103 bool &OpHasCompleteDecoder
) const {
1104 const std::string
&Decoder
= OpInfo
.Decoder
;
1106 if (OpInfo
.numFields() != 1)
1107 o
.indent(Indentation
) << "tmp = 0;\n";
1109 for (const EncodingField
&EF
: OpInfo
) {
1110 o
.indent(Indentation
) << "tmp ";
1111 if (OpInfo
.numFields() != 1) o
<< '|';
1112 o
<< "= fieldFromInstruction"
1113 << "(insn, " << EF
.Base
<< ", " << EF
.Width
<< ')';
1114 if (OpInfo
.numFields() != 1 || EF
.Offset
!= 0)
1115 o
<< " << " << EF
.Offset
;
1119 if (Decoder
!= "") {
1120 OpHasCompleteDecoder
= OpInfo
.HasCompleteDecoder
;
1121 o
.indent(Indentation
) << Emitter
->GuardPrefix
<< Decoder
1122 << "(MI, tmp, Address, Decoder)"
1123 << Emitter
->GuardPostfix
1124 << " { " << (OpHasCompleteDecoder
? "" : "DecodeComplete = false; ")
1125 << "return MCDisassembler::Fail; }\n";
1127 OpHasCompleteDecoder
= true;
1128 o
.indent(Indentation
) << "MI.addOperand(MCOperand::createImm(tmp));\n";
1132 void FilterChooser::emitDecoder(raw_ostream
&OS
, unsigned Indentation
,
1133 unsigned Opc
, bool &HasCompleteDecoder
) const {
1134 HasCompleteDecoder
= true;
1136 for (const auto &Op
: Operands
.find(Opc
)->second
) {
1137 // If a custom instruction decoder was specified, use that.
1138 if (Op
.numFields() == 0 && !Op
.Decoder
.empty()) {
1139 HasCompleteDecoder
= Op
.HasCompleteDecoder
;
1140 OS
.indent(Indentation
) << Emitter
->GuardPrefix
<< Op
.Decoder
1141 << "(MI, insn, Address, Decoder)"
1142 << Emitter
->GuardPostfix
1143 << " { " << (HasCompleteDecoder
? "" : "DecodeComplete = false; ")
1144 << "return MCDisassembler::Fail; }\n";
1148 bool OpHasCompleteDecoder
;
1149 emitBinaryParser(OS
, Indentation
, Op
, OpHasCompleteDecoder
);
1150 if (!OpHasCompleteDecoder
)
1151 HasCompleteDecoder
= false;
1155 unsigned FilterChooser::getDecoderIndex(DecoderSet
&Decoders
,
1157 bool &HasCompleteDecoder
) const {
1158 // Build up the predicate string.
1159 SmallString
<256> Decoder
;
1160 // FIXME: emitDecoder() function can take a buffer directly rather than
1162 raw_svector_ostream
S(Decoder
);
1164 emitDecoder(S
, I
, Opc
, HasCompleteDecoder
);
1166 // Using the full decoder string as the key value here is a bit
1167 // heavyweight, but is effective. If the string comparisons become a
1168 // performance concern, we can implement a mangling of the predicate
1169 // data easily enough with a map back to the actual string. That's
1170 // overkill for now, though.
1172 // Make sure the predicate is in the table.
1173 Decoders
.insert(CachedHashString(Decoder
));
1174 // Now figure out the index for when we write out the table.
1175 DecoderSet::const_iterator P
= find(Decoders
, Decoder
.str());
1176 return (unsigned)(P
- Decoders
.begin());
1179 static void emitSinglePredicateMatch(raw_ostream
&o
, StringRef str
,
1180 const std::string
&PredicateNamespace
) {
1182 o
<< "!Bits[" << PredicateNamespace
<< "::"
1183 << str
.slice(1,str
.size()) << "]";
1185 o
<< "Bits[" << PredicateNamespace
<< "::" << str
<< "]";
1188 bool FilterChooser::emitPredicateMatch(raw_ostream
&o
, unsigned &Indentation
,
1189 unsigned Opc
) const {
1190 ListInit
*Predicates
=
1191 AllInstructions
[Opc
].EncodingDef
->getValueAsListInit("Predicates");
1192 bool IsFirstEmission
= true;
1193 for (unsigned i
= 0; i
< Predicates
->size(); ++i
) {
1194 Record
*Pred
= Predicates
->getElementAsRecord(i
);
1195 if (!Pred
->getValue("AssemblerMatcherPredicate"))
1198 StringRef P
= Pred
->getValueAsString("AssemblerCondString");
1203 if (!IsFirstEmission
)
1206 std::pair
<StringRef
, StringRef
> pairs
= P
.split(',');
1207 while (!pairs
.second
.empty()) {
1208 emitSinglePredicateMatch(o
, pairs
.first
, Emitter
->PredicateNamespace
);
1210 pairs
= pairs
.second
.split(',');
1212 emitSinglePredicateMatch(o
, pairs
.first
, Emitter
->PredicateNamespace
);
1213 IsFirstEmission
= false;
1215 return !Predicates
->empty();
1218 bool FilterChooser::doesOpcodeNeedPredicate(unsigned Opc
) const {
1219 ListInit
*Predicates
=
1220 AllInstructions
[Opc
].EncodingDef
->getValueAsListInit("Predicates");
1221 for (unsigned i
= 0; i
< Predicates
->size(); ++i
) {
1222 Record
*Pred
= Predicates
->getElementAsRecord(i
);
1223 if (!Pred
->getValue("AssemblerMatcherPredicate"))
1226 StringRef P
= Pred
->getValueAsString("AssemblerCondString");
1236 unsigned FilterChooser::getPredicateIndex(DecoderTableInfo
&TableInfo
,
1237 StringRef Predicate
) const {
1238 // Using the full predicate string as the key value here is a bit
1239 // heavyweight, but is effective. If the string comparisons become a
1240 // performance concern, we can implement a mangling of the predicate
1241 // data easily enough with a map back to the actual string. That's
1242 // overkill for now, though.
1244 // Make sure the predicate is in the table.
1245 TableInfo
.Predicates
.insert(CachedHashString(Predicate
));
1246 // Now figure out the index for when we write out the table.
1247 PredicateSet::const_iterator P
= find(TableInfo
.Predicates
, Predicate
);
1248 return (unsigned)(P
- TableInfo
.Predicates
.begin());
1251 void FilterChooser::emitPredicateTableEntry(DecoderTableInfo
&TableInfo
,
1252 unsigned Opc
) const {
1253 if (!doesOpcodeNeedPredicate(Opc
))
1256 // Build up the predicate string.
1257 SmallString
<256> Predicate
;
1258 // FIXME: emitPredicateMatch() functions can take a buffer directly rather
1260 raw_svector_ostream
PS(Predicate
);
1262 emitPredicateMatch(PS
, I
, Opc
);
1264 // Figure out the index into the predicate table for the predicate just
1266 unsigned PIdx
= getPredicateIndex(TableInfo
, PS
.str());
1267 SmallString
<16> PBytes
;
1268 raw_svector_ostream
S(PBytes
);
1269 encodeULEB128(PIdx
, S
);
1271 TableInfo
.Table
.push_back(MCD::OPC_CheckPredicate
);
1273 for (unsigned i
= 0, e
= PBytes
.size(); i
!= e
; ++i
)
1274 TableInfo
.Table
.push_back(PBytes
[i
]);
1275 // Push location for NumToSkip backpatching.
1276 TableInfo
.FixupStack
.back().push_back(TableInfo
.Table
.size());
1277 TableInfo
.Table
.push_back(0);
1278 TableInfo
.Table
.push_back(0);
1279 TableInfo
.Table
.push_back(0);
1282 void FilterChooser::emitSoftFailTableEntry(DecoderTableInfo
&TableInfo
,
1283 unsigned Opc
) const {
1285 AllInstructions
[Opc
].EncodingDef
->getValueAsBitsInit("SoftFail");
1286 if (!SFBits
) return;
1287 BitsInit
*InstBits
=
1288 AllInstructions
[Opc
].EncodingDef
->getValueAsBitsInit("Inst");
1290 APInt
PositiveMask(BitWidth
, 0ULL);
1291 APInt
NegativeMask(BitWidth
, 0ULL);
1292 for (unsigned i
= 0; i
< BitWidth
; ++i
) {
1293 bit_value_t B
= bitFromBits(*SFBits
, i
);
1294 bit_value_t IB
= bitFromBits(*InstBits
, i
);
1296 if (B
!= BIT_TRUE
) continue;
1300 // The bit is meant to be false, so emit a check to see if it is true.
1301 PositiveMask
.setBit(i
);
1304 // The bit is meant to be true, so emit a check to see if it is false.
1305 NegativeMask
.setBit(i
);
1308 // The bit is not set; this must be an error!
1309 errs() << "SoftFail Conflict: bit SoftFail{" << i
<< "} in "
1310 << AllInstructions
[Opc
] << " is set but Inst{" << i
1312 << " - You can only mark a bit as SoftFail if it is fully defined"
1313 << " (1/0 - not '?') in Inst\n";
1318 bool NeedPositiveMask
= PositiveMask
.getBoolValue();
1319 bool NeedNegativeMask
= NegativeMask
.getBoolValue();
1321 if (!NeedPositiveMask
&& !NeedNegativeMask
)
1324 TableInfo
.Table
.push_back(MCD::OPC_SoftFail
);
1326 SmallString
<16> MaskBytes
;
1327 raw_svector_ostream
S(MaskBytes
);
1328 if (NeedPositiveMask
) {
1329 encodeULEB128(PositiveMask
.getZExtValue(), S
);
1330 for (unsigned i
= 0, e
= MaskBytes
.size(); i
!= e
; ++i
)
1331 TableInfo
.Table
.push_back(MaskBytes
[i
]);
1333 TableInfo
.Table
.push_back(0);
1334 if (NeedNegativeMask
) {
1336 encodeULEB128(NegativeMask
.getZExtValue(), S
);
1337 for (unsigned i
= 0, e
= MaskBytes
.size(); i
!= e
; ++i
)
1338 TableInfo
.Table
.push_back(MaskBytes
[i
]);
1340 TableInfo
.Table
.push_back(0);
1343 // Emits table entries to decode the singleton.
1344 void FilterChooser::emitSingletonTableEntry(DecoderTableInfo
&TableInfo
,
1345 EncodingIDAndOpcode Opc
) const {
1346 std::vector
<unsigned> StartBits
;
1347 std::vector
<unsigned> EndBits
;
1348 std::vector
<uint64_t> FieldVals
;
1350 insnWithID(Insn
, Opc
.EncodingID
);
1352 // Look for islands of undecoded bits of the singleton.
1353 getIslands(StartBits
, EndBits
, FieldVals
, Insn
);
1355 unsigned Size
= StartBits
.size();
1357 // Emit the predicate table entry if one is needed.
1358 emitPredicateTableEntry(TableInfo
, Opc
.EncodingID
);
1360 // Check any additional encoding fields needed.
1361 for (unsigned I
= Size
; I
!= 0; --I
) {
1362 unsigned NumBits
= EndBits
[I
-1] - StartBits
[I
-1] + 1;
1363 TableInfo
.Table
.push_back(MCD::OPC_CheckField
);
1364 TableInfo
.Table
.push_back(StartBits
[I
-1]);
1365 TableInfo
.Table
.push_back(NumBits
);
1366 uint8_t Buffer
[16], *p
;
1367 encodeULEB128(FieldVals
[I
-1], Buffer
);
1368 for (p
= Buffer
; *p
>= 128 ; ++p
)
1369 TableInfo
.Table
.push_back(*p
);
1370 TableInfo
.Table
.push_back(*p
);
1371 // Push location for NumToSkip backpatching.
1372 TableInfo
.FixupStack
.back().push_back(TableInfo
.Table
.size());
1373 // The fixup is always 24-bits, so go ahead and allocate the space
1374 // in the table so all our relative position calculations work OK even
1375 // before we fully resolve the real value here.
1376 TableInfo
.Table
.push_back(0);
1377 TableInfo
.Table
.push_back(0);
1378 TableInfo
.Table
.push_back(0);
1381 // Check for soft failure of the match.
1382 emitSoftFailTableEntry(TableInfo
, Opc
.EncodingID
);
1384 bool HasCompleteDecoder
;
1386 getDecoderIndex(TableInfo
.Decoders
, Opc
.EncodingID
, HasCompleteDecoder
);
1388 // Produce OPC_Decode or OPC_TryDecode opcode based on the information
1389 // whether the instruction decoder is complete or not. If it is complete
1390 // then it handles all possible values of remaining variable/unfiltered bits
1391 // and for any value can determine if the bitpattern is a valid instruction
1392 // or not. This means OPC_Decode will be the final step in the decoding
1393 // process. If it is not complete, then the Fail return code from the
1394 // decoder method indicates that additional processing should be done to see
1395 // if there is any other instruction that also matches the bitpattern and
1397 TableInfo
.Table
.push_back(HasCompleteDecoder
? MCD::OPC_Decode
:
1398 MCD::OPC_TryDecode
);
1399 NumEncodingsSupported
++;
1400 uint8_t Buffer
[16], *p
;
1401 encodeULEB128(Opc
.Opcode
, Buffer
);
1402 for (p
= Buffer
; *p
>= 128 ; ++p
)
1403 TableInfo
.Table
.push_back(*p
);
1404 TableInfo
.Table
.push_back(*p
);
1406 SmallString
<16> Bytes
;
1407 raw_svector_ostream
S(Bytes
);
1408 encodeULEB128(DIdx
, S
);
1411 for (unsigned i
= 0, e
= Bytes
.size(); i
!= e
; ++i
)
1412 TableInfo
.Table
.push_back(Bytes
[i
]);
1414 if (!HasCompleteDecoder
) {
1415 // Push location for NumToSkip backpatching.
1416 TableInfo
.FixupStack
.back().push_back(TableInfo
.Table
.size());
1417 // Allocate the space for the fixup.
1418 TableInfo
.Table
.push_back(0);
1419 TableInfo
.Table
.push_back(0);
1420 TableInfo
.Table
.push_back(0);
1424 // Emits table entries to decode the singleton, and then to decode the rest.
1425 void FilterChooser::emitSingletonTableEntry(DecoderTableInfo
&TableInfo
,
1426 const Filter
&Best
) const {
1427 EncodingIDAndOpcode Opc
= Best
.getSingletonOpc();
1429 // complex singletons need predicate checks from the first singleton
1430 // to refer forward to the variable filterchooser that follows.
1431 TableInfo
.FixupStack
.emplace_back();
1433 emitSingletonTableEntry(TableInfo
, Opc
);
1435 resolveTableFixups(TableInfo
.Table
, TableInfo
.FixupStack
.back(),
1436 TableInfo
.Table
.size());
1437 TableInfo
.FixupStack
.pop_back();
1439 Best
.getVariableFC().emitTableEntries(TableInfo
);
1442 // Assign a single filter and run with it. Top level API client can initialize
1443 // with a single filter to start the filtering process.
1444 void FilterChooser::runSingleFilter(unsigned startBit
, unsigned numBit
,
1447 Filters
.emplace_back(*this, startBit
, numBit
, true);
1448 BestIndex
= 0; // Sole Filter instance to choose from.
1449 bestFilter().recurse();
1452 // reportRegion is a helper function for filterProcessor to mark a region as
1453 // eligible for use as a filter region.
1454 void FilterChooser::reportRegion(bitAttr_t RA
, unsigned StartBit
,
1455 unsigned BitIndex
, bool AllowMixed
) {
1456 if (RA
== ATTR_MIXED
&& AllowMixed
)
1457 Filters
.emplace_back(*this, StartBit
, BitIndex
- StartBit
, true);
1458 else if (RA
== ATTR_ALL_SET
&& !AllowMixed
)
1459 Filters
.emplace_back(*this, StartBit
, BitIndex
- StartBit
, false);
1462 // FilterProcessor scans the well-known encoding bits of the instructions and
1463 // builds up a list of candidate filters. It chooses the best filter and
1464 // recursively descends down the decoding tree.
1465 bool FilterChooser::filterProcessor(bool AllowMixed
, bool Greedy
) {
1468 unsigned numInstructions
= Opcodes
.size();
1470 assert(numInstructions
&& "Filter created with no instructions");
1472 // No further filtering is necessary.
1473 if (numInstructions
== 1)
1476 // Heuristics. See also doFilter()'s "Heuristics" comment when num of
1477 // instructions is 3.
1478 if (AllowMixed
&& !Greedy
) {
1479 assert(numInstructions
== 3);
1481 for (unsigned i
= 0; i
< Opcodes
.size(); ++i
) {
1482 std::vector
<unsigned> StartBits
;
1483 std::vector
<unsigned> EndBits
;
1484 std::vector
<uint64_t> FieldVals
;
1487 insnWithID(Insn
, Opcodes
[i
].EncodingID
);
1489 // Look for islands of undecoded bits of any instruction.
1490 if (getIslands(StartBits
, EndBits
, FieldVals
, Insn
) > 0) {
1491 // Found an instruction with island(s). Now just assign a filter.
1492 runSingleFilter(StartBits
[0], EndBits
[0] - StartBits
[0] + 1, true);
1500 // We maintain BIT_WIDTH copies of the bitAttrs automaton.
1501 // The automaton consumes the corresponding bit from each
1504 // Input symbols: 0, 1, and _ (unset).
1505 // States: NONE, FILTERED, ALL_SET, ALL_UNSET, and MIXED.
1506 // Initial state: NONE.
1508 // (NONE) ------- [01] -> (ALL_SET)
1509 // (NONE) ------- _ ----> (ALL_UNSET)
1510 // (ALL_SET) ---- [01] -> (ALL_SET)
1511 // (ALL_SET) ---- _ ----> (MIXED)
1512 // (ALL_UNSET) -- [01] -> (MIXED)
1513 // (ALL_UNSET) -- _ ----> (ALL_UNSET)
1514 // (MIXED) ------ . ----> (MIXED)
1515 // (FILTERED)---- . ----> (FILTERED)
1517 std::vector
<bitAttr_t
> bitAttrs
;
1519 // FILTERED bit positions provide no entropy and are not worthy of pursuing.
1520 // Filter::recurse() set either BIT_TRUE or BIT_FALSE for each position.
1521 for (BitIndex
= 0; BitIndex
< BitWidth
; ++BitIndex
)
1522 if (FilterBitValues
[BitIndex
] == BIT_TRUE
||
1523 FilterBitValues
[BitIndex
] == BIT_FALSE
)
1524 bitAttrs
.push_back(ATTR_FILTERED
);
1526 bitAttrs
.push_back(ATTR_NONE
);
1528 for (unsigned InsnIndex
= 0; InsnIndex
< numInstructions
; ++InsnIndex
) {
1531 insnWithID(insn
, Opcodes
[InsnIndex
].EncodingID
);
1533 for (BitIndex
= 0; BitIndex
< BitWidth
; ++BitIndex
) {
1534 switch (bitAttrs
[BitIndex
]) {
1536 if (insn
[BitIndex
] == BIT_UNSET
)
1537 bitAttrs
[BitIndex
] = ATTR_ALL_UNSET
;
1539 bitAttrs
[BitIndex
] = ATTR_ALL_SET
;
1542 if (insn
[BitIndex
] == BIT_UNSET
)
1543 bitAttrs
[BitIndex
] = ATTR_MIXED
;
1545 case ATTR_ALL_UNSET
:
1546 if (insn
[BitIndex
] != BIT_UNSET
)
1547 bitAttrs
[BitIndex
] = ATTR_MIXED
;
1556 // The regionAttr automaton consumes the bitAttrs automatons' state,
1557 // lowest-to-highest.
1559 // Input symbols: F(iltered), (all_)S(et), (all_)U(nset), M(ixed)
1560 // States: NONE, ALL_SET, MIXED
1561 // Initial state: NONE
1563 // (NONE) ----- F --> (NONE)
1564 // (NONE) ----- S --> (ALL_SET) ; and set region start
1565 // (NONE) ----- U --> (NONE)
1566 // (NONE) ----- M --> (MIXED) ; and set region start
1567 // (ALL_SET) -- F --> (NONE) ; and report an ALL_SET region
1568 // (ALL_SET) -- S --> (ALL_SET)
1569 // (ALL_SET) -- U --> (NONE) ; and report an ALL_SET region
1570 // (ALL_SET) -- M --> (MIXED) ; and report an ALL_SET region
1571 // (MIXED) ---- F --> (NONE) ; and report a MIXED region
1572 // (MIXED) ---- S --> (ALL_SET) ; and report a MIXED region
1573 // (MIXED) ---- U --> (NONE) ; and report a MIXED region
1574 // (MIXED) ---- M --> (MIXED)
1576 bitAttr_t RA
= ATTR_NONE
;
1577 unsigned StartBit
= 0;
1579 for (BitIndex
= 0; BitIndex
< BitWidth
; ++BitIndex
) {
1580 bitAttr_t bitAttr
= bitAttrs
[BitIndex
];
1582 assert(bitAttr
!= ATTR_NONE
&& "Bit without attributes");
1590 StartBit
= BitIndex
;
1593 case ATTR_ALL_UNSET
:
1596 StartBit
= BitIndex
;
1600 llvm_unreachable("Unexpected bitAttr!");
1606 reportRegion(RA
, StartBit
, BitIndex
, AllowMixed
);
1611 case ATTR_ALL_UNSET
:
1612 reportRegion(RA
, StartBit
, BitIndex
, AllowMixed
);
1616 reportRegion(RA
, StartBit
, BitIndex
, AllowMixed
);
1617 StartBit
= BitIndex
;
1621 llvm_unreachable("Unexpected bitAttr!");
1627 reportRegion(RA
, StartBit
, BitIndex
, AllowMixed
);
1628 StartBit
= BitIndex
;
1632 reportRegion(RA
, StartBit
, BitIndex
, AllowMixed
);
1633 StartBit
= BitIndex
;
1636 case ATTR_ALL_UNSET
:
1637 reportRegion(RA
, StartBit
, BitIndex
, AllowMixed
);
1643 llvm_unreachable("Unexpected bitAttr!");
1646 case ATTR_ALL_UNSET
:
1647 llvm_unreachable("regionAttr state machine has no ATTR_UNSET state");
1649 llvm_unreachable("regionAttr state machine has no ATTR_FILTERED state");
1653 // At the end, if we're still in ALL_SET or MIXED states, report a region
1660 reportRegion(RA
, StartBit
, BitIndex
, AllowMixed
);
1662 case ATTR_ALL_UNSET
:
1665 reportRegion(RA
, StartBit
, BitIndex
, AllowMixed
);
1669 // We have finished with the filter processings. Now it's time to choose
1670 // the best performing filter.
1672 bool AllUseless
= true;
1673 unsigned BestScore
= 0;
1675 for (unsigned i
= 0, e
= Filters
.size(); i
!= e
; ++i
) {
1676 unsigned Usefulness
= Filters
[i
].usefulness();
1681 if (Usefulness
> BestScore
) {
1683 BestScore
= Usefulness
;
1688 bestFilter().recurse();
1691 } // end of FilterChooser::filterProcessor(bool)
1693 // Decides on the best configuration of filter(s) to use in order to decode
1694 // the instructions. A conflict of instructions may occur, in which case we
1695 // dump the conflict set to the standard error.
1696 void FilterChooser::doFilter() {
1697 unsigned Num
= Opcodes
.size();
1698 assert(Num
&& "FilterChooser created with no instructions");
1700 // Try regions of consecutive known bit values first.
1701 if (filterProcessor(false))
1704 // Then regions of mixed bits (both known and unitialized bit values allowed).
1705 if (filterProcessor(true))
1708 // Heuristics to cope with conflict set {t2CMPrs, t2SUBSrr, t2SUBSrs} where
1709 // no single instruction for the maximum ATTR_MIXED region Inst{14-4} has a
1710 // well-known encoding pattern. In such case, we backtrack and scan for the
1711 // the very first consecutive ATTR_ALL_SET region and assign a filter to it.
1712 if (Num
== 3 && filterProcessor(true, false))
1715 // If we come to here, the instruction decoding has failed.
1716 // Set the BestIndex to -1 to indicate so.
1720 // emitTableEntries - Emit state machine entries to decode our share of
1722 void FilterChooser::emitTableEntries(DecoderTableInfo
&TableInfo
) const {
1723 if (Opcodes
.size() == 1) {
1724 // There is only one instruction in the set, which is great!
1725 // Call emitSingletonDecoder() to see whether there are any remaining
1727 emitSingletonTableEntry(TableInfo
, Opcodes
[0]);
1731 // Choose the best filter to do the decodings!
1732 if (BestIndex
!= -1) {
1733 const Filter
&Best
= Filters
[BestIndex
];
1734 if (Best
.getNumFiltered() == 1)
1735 emitSingletonTableEntry(TableInfo
, Best
);
1737 Best
.emitTableEntry(TableInfo
);
1741 // We don't know how to decode these instructions! Dump the
1742 // conflict set and bail.
1744 // Print out useful conflict information for postmortem analysis.
1745 errs() << "Decoding Conflict:\n";
1747 dumpStack(errs(), "\t\t");
1749 for (unsigned i
= 0; i
< Opcodes
.size(); ++i
) {
1751 emitNameWithID(errs(), Opcodes
[i
].EncodingID
);
1755 getBitsField(*AllInstructions
[Opcodes
[i
].EncodingID
].EncodingDef
, "Inst"));
1760 static std::string
findOperandDecoderMethod(TypedInit
*TI
) {
1761 std::string Decoder
;
1763 Record
*Record
= cast
<DefInit
>(TI
)->getDef();
1765 RecordVal
*DecoderString
= Record
->getValue("DecoderMethod");
1766 StringInit
*String
= DecoderString
?
1767 dyn_cast
<StringInit
>(DecoderString
->getValue()) : nullptr;
1769 Decoder
= String
->getValue();
1770 if (!Decoder
.empty())
1774 if (Record
->isSubClassOf("RegisterOperand"))
1775 Record
= Record
->getValueAsDef("RegClass");
1777 if (Record
->isSubClassOf("RegisterClass")) {
1778 Decoder
= "Decode" + Record
->getName().str() + "RegisterClass";
1779 } else if (Record
->isSubClassOf("PointerLikeRegClass")) {
1780 Decoder
= "DecodePointerLikeRegClass" +
1781 utostr(Record
->getValueAsInt("RegClassKind"));
1788 populateInstruction(CodeGenTarget
&Target
, const Record
&EncodingDef
,
1789 const CodeGenInstruction
&CGI
, unsigned Opc
,
1790 std::map
<unsigned, std::vector
<OperandInfo
>> &Operands
) {
1791 const Record
&Def
= *CGI
.TheDef
;
1792 // If all the bit positions are not specified; do not decode this instruction.
1793 // We are bound to fail! For proper disassembly, the well-known encoding bits
1794 // of the instruction must be fully specified.
1796 BitsInit
&Bits
= getBitsField(EncodingDef
, "Inst");
1797 if (Bits
.allInComplete()) return false;
1799 std::vector
<OperandInfo
> InsnOperands
;
1801 // If the instruction has specified a custom decoding hook, use that instead
1802 // of trying to auto-generate the decoder.
1803 StringRef InstDecoder
= EncodingDef
.getValueAsString("DecoderMethod");
1804 if (InstDecoder
!= "") {
1805 bool HasCompleteInstDecoder
= EncodingDef
.getValueAsBit("hasCompleteDecoder");
1806 InsnOperands
.push_back(OperandInfo(InstDecoder
, HasCompleteInstDecoder
));
1807 Operands
[Opc
] = InsnOperands
;
1811 // Generate a description of the operand of the instruction that we know
1812 // how to decode automatically.
1813 // FIXME: We'll need to have a way to manually override this as needed.
1815 // Gather the outputs/inputs of the instruction, so we can find their
1816 // positions in the encoding. This assumes for now that they appear in the
1817 // MCInst in the order that they're listed.
1818 std::vector
<std::pair
<Init
*, StringRef
>> InOutOperands
;
1819 DagInit
*Out
= Def
.getValueAsDag("OutOperandList");
1820 DagInit
*In
= Def
.getValueAsDag("InOperandList");
1821 for (unsigned i
= 0; i
< Out
->getNumArgs(); ++i
)
1822 InOutOperands
.push_back(std::make_pair(Out
->getArg(i
),
1823 Out
->getArgNameStr(i
)));
1824 for (unsigned i
= 0; i
< In
->getNumArgs(); ++i
)
1825 InOutOperands
.push_back(std::make_pair(In
->getArg(i
),
1826 In
->getArgNameStr(i
)));
1828 // Search for tied operands, so that we can correctly instantiate
1829 // operands that are not explicitly represented in the encoding.
1830 std::map
<std::string
, std::string
> TiedNames
;
1831 for (unsigned i
= 0; i
< CGI
.Operands
.size(); ++i
) {
1832 int tiedTo
= CGI
.Operands
[i
].getTiedRegister();
1834 std::pair
<unsigned, unsigned> SO
=
1835 CGI
.Operands
.getSubOperandNumber(tiedTo
);
1836 TiedNames
[InOutOperands
[i
].second
] = InOutOperands
[SO
.first
].second
;
1837 TiedNames
[InOutOperands
[SO
.first
].second
] = InOutOperands
[i
].second
;
1841 std::map
<std::string
, std::vector
<OperandInfo
>> NumberedInsnOperands
;
1842 std::set
<std::string
> NumberedInsnOperandsNoTie
;
1843 if (Target
.getInstructionSet()->
1844 getValueAsBit("decodePositionallyEncodedOperands")) {
1845 const std::vector
<RecordVal
> &Vals
= Def
.getValues();
1846 unsigned NumberedOp
= 0;
1848 std::set
<unsigned> NamedOpIndices
;
1849 if (Target
.getInstructionSet()->
1850 getValueAsBit("noNamedPositionallyEncodedOperands"))
1851 // Collect the set of operand indices that might correspond to named
1852 // operand, and skip these when assigning operands based on position.
1853 for (unsigned i
= 0, e
= Vals
.size(); i
!= e
; ++i
) {
1855 if (!CGI
.Operands
.hasOperandNamed(Vals
[i
].getName(), OpIdx
))
1858 NamedOpIndices
.insert(OpIdx
);
1861 for (unsigned i
= 0, e
= Vals
.size(); i
!= e
; ++i
) {
1862 // Ignore fixed fields in the record, we're looking for values like:
1863 // bits<5> RST = { ?, ?, ?, ?, ? };
1864 if (Vals
[i
].getPrefix() || Vals
[i
].getValue()->isComplete())
1867 // Determine if Vals[i] actually contributes to the Inst encoding.
1869 for (; bi
< Bits
.getNumBits(); ++bi
) {
1870 VarInit
*Var
= nullptr;
1871 VarBitInit
*BI
= dyn_cast
<VarBitInit
>(Bits
.getBit(bi
));
1873 Var
= dyn_cast
<VarInit
>(BI
->getBitVar());
1875 Var
= dyn_cast
<VarInit
>(Bits
.getBit(bi
));
1877 if (Var
&& Var
->getName() == Vals
[i
].getName())
1881 if (bi
== Bits
.getNumBits())
1884 // Skip variables that correspond to explicitly-named operands.
1886 if (CGI
.Operands
.hasOperandNamed(Vals
[i
].getName(), OpIdx
))
1889 // Get the bit range for this operand:
1890 unsigned bitStart
= bi
++, bitWidth
= 1;
1891 for (; bi
< Bits
.getNumBits(); ++bi
) {
1892 VarInit
*Var
= nullptr;
1893 VarBitInit
*BI
= dyn_cast
<VarBitInit
>(Bits
.getBit(bi
));
1895 Var
= dyn_cast
<VarInit
>(BI
->getBitVar());
1897 Var
= dyn_cast
<VarInit
>(Bits
.getBit(bi
));
1902 if (Var
->getName() != Vals
[i
].getName())
1908 unsigned NumberOps
= CGI
.Operands
.size();
1909 while (NumberedOp
< NumberOps
&&
1910 (CGI
.Operands
.isFlatOperandNotEmitted(NumberedOp
) ||
1911 (!NamedOpIndices
.empty() && NamedOpIndices
.count(
1912 CGI
.Operands
.getSubOperandNumber(NumberedOp
).first
))))
1915 OpIdx
= NumberedOp
++;
1917 // OpIdx now holds the ordered operand number of Vals[i].
1918 std::pair
<unsigned, unsigned> SO
=
1919 CGI
.Operands
.getSubOperandNumber(OpIdx
);
1920 const std::string
&Name
= CGI
.Operands
[SO
.first
].Name
;
1922 LLVM_DEBUG(dbgs() << "Numbered operand mapping for " << Def
.getName()
1923 << ": " << Name
<< "(" << SO
.first
<< ", " << SO
.second
1924 << ") => " << Vals
[i
].getName() << "\n");
1926 std::string Decoder
;
1927 Record
*TypeRecord
= CGI
.Operands
[SO
.first
].Rec
;
1929 RecordVal
*DecoderString
= TypeRecord
->getValue("DecoderMethod");
1930 StringInit
*String
= DecoderString
?
1931 dyn_cast
<StringInit
>(DecoderString
->getValue()) : nullptr;
1932 if (String
&& String
->getValue() != "")
1933 Decoder
= String
->getValue();
1935 if (Decoder
== "" &&
1936 CGI
.Operands
[SO
.first
].MIOperandInfo
&&
1937 CGI
.Operands
[SO
.first
].MIOperandInfo
->getNumArgs()) {
1938 Init
*Arg
= CGI
.Operands
[SO
.first
].MIOperandInfo
->
1940 if (DefInit
*DI
= cast
<DefInit
>(Arg
))
1941 TypeRecord
= DI
->getDef();
1945 if (TypeRecord
->isSubClassOf("RegisterOperand"))
1946 TypeRecord
= TypeRecord
->getValueAsDef("RegClass");
1947 if (TypeRecord
->isSubClassOf("RegisterClass")) {
1948 Decoder
= "Decode" + TypeRecord
->getName().str() + "RegisterClass";
1950 } else if (TypeRecord
->isSubClassOf("PointerLikeRegClass")) {
1951 Decoder
= "DecodePointerLikeRegClass" +
1952 utostr(TypeRecord
->getValueAsInt("RegClassKind"));
1956 DecoderString
= TypeRecord
->getValue("DecoderMethod");
1957 String
= DecoderString
?
1958 dyn_cast
<StringInit
>(DecoderString
->getValue()) : nullptr;
1959 if (!isReg
&& String
&& String
->getValue() != "")
1960 Decoder
= String
->getValue();
1962 RecordVal
*HasCompleteDecoderVal
=
1963 TypeRecord
->getValue("hasCompleteDecoder");
1964 BitInit
*HasCompleteDecoderBit
= HasCompleteDecoderVal
?
1965 dyn_cast
<BitInit
>(HasCompleteDecoderVal
->getValue()) : nullptr;
1966 bool HasCompleteDecoder
= HasCompleteDecoderBit
?
1967 HasCompleteDecoderBit
->getValue() : true;
1969 OperandInfo
OpInfo(Decoder
, HasCompleteDecoder
);
1970 OpInfo
.addField(bitStart
, bitWidth
, 0);
1972 NumberedInsnOperands
[Name
].push_back(OpInfo
);
1974 // FIXME: For complex operands with custom decoders we can't handle tied
1975 // sub-operands automatically. Skip those here and assume that this is
1976 // fixed up elsewhere.
1977 if (CGI
.Operands
[SO
.first
].MIOperandInfo
&&
1978 CGI
.Operands
[SO
.first
].MIOperandInfo
->getNumArgs() > 1 &&
1979 String
&& String
->getValue() != "")
1980 NumberedInsnOperandsNoTie
.insert(Name
);
1984 // For each operand, see if we can figure out where it is encoded.
1985 for (const auto &Op
: InOutOperands
) {
1986 if (!NumberedInsnOperands
[Op
.second
].empty()) {
1987 InsnOperands
.insert(InsnOperands
.end(),
1988 NumberedInsnOperands
[Op
.second
].begin(),
1989 NumberedInsnOperands
[Op
.second
].end());
1992 if (!NumberedInsnOperands
[TiedNames
[Op
.second
]].empty()) {
1993 if (!NumberedInsnOperandsNoTie
.count(TiedNames
[Op
.second
])) {
1994 // Figure out to which (sub)operand we're tied.
1995 unsigned i
= CGI
.Operands
.getOperandNamed(TiedNames
[Op
.second
]);
1996 int tiedTo
= CGI
.Operands
[i
].getTiedRegister();
1998 i
= CGI
.Operands
.getOperandNamed(Op
.second
);
1999 tiedTo
= CGI
.Operands
[i
].getTiedRegister();
2003 std::pair
<unsigned, unsigned> SO
=
2004 CGI
.Operands
.getSubOperandNumber(tiedTo
);
2006 InsnOperands
.push_back(NumberedInsnOperands
[TiedNames
[Op
.second
]]
2013 TypedInit
*TI
= cast
<TypedInit
>(Op
.first
);
2015 // At this point, we can locate the decoder field, but we need to know how
2016 // to interpret it. As a first step, require the target to provide
2017 // callbacks for decoding register classes.
2018 std::string Decoder
= findOperandDecoderMethod(TI
);
2019 Record
*TypeRecord
= cast
<DefInit
>(TI
)->getDef();
2021 RecordVal
*HasCompleteDecoderVal
=
2022 TypeRecord
->getValue("hasCompleteDecoder");
2023 BitInit
*HasCompleteDecoderBit
= HasCompleteDecoderVal
?
2024 dyn_cast
<BitInit
>(HasCompleteDecoderVal
->getValue()) : nullptr;
2025 bool HasCompleteDecoder
= HasCompleteDecoderBit
?
2026 HasCompleteDecoderBit
->getValue() : true;
2028 OperandInfo
OpInfo(Decoder
, HasCompleteDecoder
);
2029 unsigned Base
= ~0U;
2031 unsigned Offset
= 0;
2033 for (unsigned bi
= 0; bi
< Bits
.getNumBits(); ++bi
) {
2034 VarInit
*Var
= nullptr;
2035 VarBitInit
*BI
= dyn_cast
<VarBitInit
>(Bits
.getBit(bi
));
2037 Var
= dyn_cast
<VarInit
>(BI
->getBitVar());
2039 Var
= dyn_cast
<VarInit
>(Bits
.getBit(bi
));
2043 OpInfo
.addField(Base
, Width
, Offset
);
2051 if (Var
->getName() != Op
.second
&&
2052 Var
->getName() != TiedNames
[Op
.second
]) {
2054 OpInfo
.addField(Base
, Width
, Offset
);
2065 Offset
= BI
? BI
->getBitNum() : 0;
2066 } else if (BI
&& BI
->getBitNum() != Offset
+ Width
) {
2067 OpInfo
.addField(Base
, Width
, Offset
);
2070 Offset
= BI
->getBitNum();
2077 OpInfo
.addField(Base
, Width
, Offset
);
2079 if (OpInfo
.numFields() > 0)
2080 InsnOperands
.push_back(OpInfo
);
2083 Operands
[Opc
] = InsnOperands
;
2087 // Dumps the instruction encoding bits.
2088 dumpBits(errs(), Bits
);
2092 // Dumps the list of operand info.
2093 for (unsigned i
= 0, e
= CGI
.Operands
.size(); i
!= e
; ++i
) {
2094 const CGIOperandList::OperandInfo
&Info
= CGI
.Operands
[i
];
2095 const std::string
&OperandName
= Info
.Name
;
2096 const Record
&OperandDef
= *Info
.Rec
;
2098 errs() << "\t" << OperandName
<< " (" << OperandDef
.getName() << ")\n";
2106 // emitFieldFromInstruction - Emit the templated helper function
2107 // fieldFromInstruction().
2108 // On Windows we make sure that this function is not inlined when
2109 // using the VS compiler. It has a bug which causes the function
2110 // to be optimized out in some circustances. See llvm.org/pr38292
2111 static void emitFieldFromInstruction(formatted_raw_ostream
&OS
) {
2112 OS
<< "// Helper functions for extracting fields from encoded instructions.\n"
2113 << "// InsnType must either be integral or an APInt-like object that "
2115 << "// * Have a static const max_size_in_bits equal to the number of bits "
2118 << "// * be default-constructible and copy-constructible\n"
2119 << "// * be constructible from a uint64_t\n"
2120 << "// * be constructible from an APInt (this can be private)\n"
2121 << "// * Support getBitsSet(loBit, hiBit)\n"
2122 << "// * be convertible to uint64_t\n"
2123 << "// * Support the ~, &, ==, !=, and |= operators with other objects of "
2125 << "// * Support shift (<<, >>) with signed and unsigned integers on the "
2127 << "// * Support put (<<) to raw_ostream&\n"
2128 << "template<typename InsnType>\n"
2129 << "#if defined(_MSC_VER) && !defined(__clang__)\n"
2130 << "__declspec(noinline)\n"
2132 << "static InsnType fieldFromInstruction(InsnType insn, unsigned "
2134 << " unsigned numBits, "
2135 "std::true_type) {\n"
2136 << " assert(startBit + numBits <= 64 && \"Cannot support >64-bit "
2137 "extractions!\");\n"
2138 << " assert(startBit + numBits <= (sizeof(InsnType) * 8) &&\n"
2139 << " \"Instruction field out of bounds!\");\n"
2140 << " InsnType fieldMask;\n"
2141 << " if (numBits == sizeof(InsnType) * 8)\n"
2142 << " fieldMask = (InsnType)(-1LL);\n"
2144 << " fieldMask = (((InsnType)1 << numBits) - 1) << startBit;\n"
2145 << " return (insn & fieldMask) >> startBit;\n"
2148 << "template<typename InsnType>\n"
2149 << "static InsnType fieldFromInstruction(InsnType insn, unsigned "
2151 << " unsigned numBits, "
2152 "std::false_type) {\n"
2153 << " assert(startBit + numBits <= InsnType::max_size_in_bits && "
2154 "\"Instruction field out of bounds!\");\n"
2155 << " InsnType fieldMask = InsnType::getBitsSet(0, numBits);\n"
2156 << " return (insn >> startBit) & fieldMask;\n"
2159 << "template<typename InsnType>\n"
2160 << "static InsnType fieldFromInstruction(InsnType insn, unsigned "
2162 << " unsigned numBits) {\n"
2163 << " return fieldFromInstruction(insn, startBit, numBits, "
2164 "std::is_integral<InsnType>());\n"
2168 // emitDecodeInstruction - Emit the templated helper function
2169 // decodeInstruction().
2170 static void emitDecodeInstruction(formatted_raw_ostream
&OS
) {
2171 OS
<< "template<typename InsnType>\n"
2172 << "static DecodeStatus decodeInstruction(const uint8_t DecodeTable[], "
2174 << " InsnType insn, uint64_t "
2176 << " const void *DisAsm,\n"
2177 << " const MCSubtargetInfo &STI) {\n"
2178 << " const FeatureBitset& Bits = STI.getFeatureBits();\n"
2180 << " const uint8_t *Ptr = DecodeTable;\n"
2181 << " InsnType CurFieldValue = 0;\n"
2182 << " DecodeStatus S = MCDisassembler::Success;\n"
2183 << " while (true) {\n"
2184 << " ptrdiff_t Loc = Ptr - DecodeTable;\n"
2185 << " switch (*Ptr) {\n"
2187 << " errs() << Loc << \": Unexpected decode table opcode!\\n\";\n"
2188 << " return MCDisassembler::Fail;\n"
2189 << " case MCD::OPC_ExtractField: {\n"
2190 << " unsigned Start = *++Ptr;\n"
2191 << " unsigned Len = *++Ptr;\n"
2193 << " CurFieldValue = fieldFromInstruction(insn, Start, Len);\n"
2194 << " LLVM_DEBUG(dbgs() << Loc << \": OPC_ExtractField(\" << Start << "
2196 << " << Len << \"): \" << CurFieldValue << \"\\n\");\n"
2199 << " case MCD::OPC_FilterValue: {\n"
2200 << " // Decode the field value.\n"
2201 << " unsigned Len;\n"
2202 << " InsnType Val = decodeULEB128(++Ptr, &Len);\n"
2204 << " // NumToSkip is a plain 24-bit integer.\n"
2205 << " unsigned NumToSkip = *Ptr++;\n"
2206 << " NumToSkip |= (*Ptr++) << 8;\n"
2207 << " NumToSkip |= (*Ptr++) << 16;\n"
2209 << " // Perform the filter operation.\n"
2210 << " if (Val != CurFieldValue)\n"
2211 << " Ptr += NumToSkip;\n"
2212 << " LLVM_DEBUG(dbgs() << Loc << \": OPC_FilterValue(\" << Val << "
2213 "\", \" << NumToSkip\n"
2214 << " << \"): \" << ((Val != CurFieldValue) ? \"FAIL:\" "
2216 << " << \" continuing at \" << (Ptr - DecodeTable) << "
2221 << " case MCD::OPC_CheckField: {\n"
2222 << " unsigned Start = *++Ptr;\n"
2223 << " unsigned Len = *++Ptr;\n"
2224 << " InsnType FieldValue = fieldFromInstruction(insn, Start, Len);\n"
2225 << " // Decode the field value.\n"
2226 << " InsnType ExpectedValue = decodeULEB128(++Ptr, &Len);\n"
2228 << " // NumToSkip is a plain 24-bit integer.\n"
2229 << " unsigned NumToSkip = *Ptr++;\n"
2230 << " NumToSkip |= (*Ptr++) << 8;\n"
2231 << " NumToSkip |= (*Ptr++) << 16;\n"
2233 << " // If the actual and expected values don't match, skip.\n"
2234 << " if (ExpectedValue != FieldValue)\n"
2235 << " Ptr += NumToSkip;\n"
2236 << " LLVM_DEBUG(dbgs() << Loc << \": OPC_CheckField(\" << Start << "
2238 << " << Len << \", \" << ExpectedValue << \", \" << "
2240 << " << \"): FieldValue = \" << FieldValue << \", "
2241 "ExpectedValue = \"\n"
2242 << " << ExpectedValue << \": \"\n"
2243 << " << ((ExpectedValue == FieldValue) ? \"PASS\\n\" : "
2247 << " case MCD::OPC_CheckPredicate: {\n"
2248 << " unsigned Len;\n"
2249 << " // Decode the Predicate Index value.\n"
2250 << " unsigned PIdx = decodeULEB128(++Ptr, &Len);\n"
2252 << " // NumToSkip is a plain 24-bit integer.\n"
2253 << " unsigned NumToSkip = *Ptr++;\n"
2254 << " NumToSkip |= (*Ptr++) << 8;\n"
2255 << " NumToSkip |= (*Ptr++) << 16;\n"
2256 << " // Check the predicate.\n"
2258 << " if (!(Pred = checkDecoderPredicate(PIdx, Bits)))\n"
2259 << " Ptr += NumToSkip;\n"
2261 << " LLVM_DEBUG(dbgs() << Loc << \": OPC_CheckPredicate(\" << PIdx "
2263 << " << (Pred ? \"PASS\\n\" : \"FAIL\\n\"));\n"
2267 << " case MCD::OPC_Decode: {\n"
2268 << " unsigned Len;\n"
2269 << " // Decode the Opcode value.\n"
2270 << " unsigned Opc = decodeULEB128(++Ptr, &Len);\n"
2272 << " unsigned DecodeIdx = decodeULEB128(Ptr, &Len);\n"
2276 << " MI.setOpcode(Opc);\n"
2277 << " bool DecodeComplete;\n"
2278 << " S = decodeToMCInst(S, DecodeIdx, insn, MI, Address, DisAsm, "
2279 "DecodeComplete);\n"
2280 << " assert(DecodeComplete);\n"
2282 << " LLVM_DEBUG(dbgs() << Loc << \": OPC_Decode: opcode \" << Opc\n"
2283 << " << \", using decoder \" << DecodeIdx << \": \"\n"
2284 << " << (S != MCDisassembler::Fail ? \"PASS\" : "
2285 "\"FAIL\") << \"\\n\");\n"
2288 << " case MCD::OPC_TryDecode: {\n"
2289 << " unsigned Len;\n"
2290 << " // Decode the Opcode value.\n"
2291 << " unsigned Opc = decodeULEB128(++Ptr, &Len);\n"
2293 << " unsigned DecodeIdx = decodeULEB128(Ptr, &Len);\n"
2295 << " // NumToSkip is a plain 24-bit integer.\n"
2296 << " unsigned NumToSkip = *Ptr++;\n"
2297 << " NumToSkip |= (*Ptr++) << 8;\n"
2298 << " NumToSkip |= (*Ptr++) << 16;\n"
2300 << " // Perform the decode operation.\n"
2301 << " MCInst TmpMI;\n"
2302 << " TmpMI.setOpcode(Opc);\n"
2303 << " bool DecodeComplete;\n"
2304 << " S = decodeToMCInst(S, DecodeIdx, insn, TmpMI, Address, DisAsm, "
2305 "DecodeComplete);\n"
2306 << " LLVM_DEBUG(dbgs() << Loc << \": OPC_TryDecode: opcode \" << "
2308 << " << \", using decoder \" << DecodeIdx << \": \");\n"
2310 << " if (DecodeComplete) {\n"
2311 << " // Decoding complete.\n"
2312 << " LLVM_DEBUG(dbgs() << (S != MCDisassembler::Fail ? \"PASS\" : "
2313 "\"FAIL\") << \"\\n\");\n"
2317 << " assert(S == MCDisassembler::Fail);\n"
2318 << " // If the decoding was incomplete, skip.\n"
2319 << " Ptr += NumToSkip;\n"
2320 << " LLVM_DEBUG(dbgs() << \"FAIL: continuing at \" << (Ptr - "
2321 "DecodeTable) << \"\\n\");\n"
2322 << " // Reset decode status. This also drops a SoftFail status "
2324 << " // set before the decode attempt.\n"
2325 << " S = MCDisassembler::Success;\n"
2329 << " case MCD::OPC_SoftFail: {\n"
2330 << " // Decode the mask values.\n"
2331 << " unsigned Len;\n"
2332 << " InsnType PositiveMask = decodeULEB128(++Ptr, &Len);\n"
2334 << " InsnType NegativeMask = decodeULEB128(Ptr, &Len);\n"
2336 << " bool Fail = (insn & PositiveMask) || (~insn & NegativeMask);\n"
2338 << " S = MCDisassembler::SoftFail;\n"
2339 << " LLVM_DEBUG(dbgs() << Loc << \": OPC_SoftFail: \" << (Fail ? "
2340 "\"FAIL\\n\":\"PASS\\n\"));\n"
2343 << " case MCD::OPC_Fail: {\n"
2344 << " LLVM_DEBUG(dbgs() << Loc << \": OPC_Fail\\n\");\n"
2345 << " return MCDisassembler::Fail;\n"
2349 << " llvm_unreachable(\"bogosity detected in disassembler state "
2354 // Emits disassembler code for instruction decoding.
2355 void FixedLenDecoderEmitter::run(raw_ostream
&o
) {
2356 formatted_raw_ostream
OS(o
);
2357 OS
<< "#include \"llvm/MC/MCInst.h\"\n";
2358 OS
<< "#include \"llvm/Support/Debug.h\"\n";
2359 OS
<< "#include \"llvm/Support/DataTypes.h\"\n";
2360 OS
<< "#include \"llvm/Support/LEB128.h\"\n";
2361 OS
<< "#include \"llvm/Support/raw_ostream.h\"\n";
2362 OS
<< "#include <assert.h>\n";
2364 OS
<< "namespace llvm {\n\n";
2366 emitFieldFromInstruction(OS
);
2368 Target
.reverseBitsForLittleEndianEncoding();
2370 // Parameterize the decoders based on namespace and instruction width.
2371 const auto &NumberedInstructions
= Target
.getInstructionsByEnumValue();
2372 NumberedEncodings
.reserve(NumberedInstructions
.size());
2373 DenseMap
<Record
*, unsigned> IndexOfInstruction
;
2374 for (const auto &NumberedInstruction
: NumberedInstructions
) {
2375 IndexOfInstruction
[NumberedInstruction
->TheDef
] = NumberedEncodings
.size();
2376 NumberedEncodings
.emplace_back(NumberedInstruction
->TheDef
, NumberedInstruction
);
2378 for (const auto &NumberedAlias
: RK
.getAllDerivedDefinitions("AdditionalEncoding"))
2379 NumberedEncodings
.emplace_back(
2381 &Target
.getInstruction(NumberedAlias
->getValueAsDef("AliasOf")));
2383 std::map
<std::pair
<std::string
, unsigned>, std::vector
<EncodingIDAndOpcode
>>
2385 std::map
<unsigned, std::vector
<OperandInfo
>> Operands
;
2387 for (unsigned i
= 0; i
< NumberedEncodings
.size(); ++i
) {
2388 const Record
*EncodingDef
= NumberedEncodings
[i
].EncodingDef
;
2389 const CodeGenInstruction
*Inst
= NumberedEncodings
[i
].Inst
;
2390 const Record
*Def
= Inst
->TheDef
;
2391 unsigned Size
= EncodingDef
->getValueAsInt("Size");
2392 if (Def
->getValueAsString("Namespace") == "TargetOpcode" ||
2393 Def
->getValueAsBit("isPseudo") ||
2394 Def
->getValueAsBit("isAsmParserOnly") ||
2395 Def
->getValueAsBit("isCodeGenOnly")) {
2396 NumEncodingsLackingDisasm
++;
2400 if (i
< NumberedInstructions
.size())
2404 StringRef DecoderNamespace
= EncodingDef
->getValueAsString("DecoderNamespace");
2407 if (populateInstruction(Target
, *EncodingDef
, *Inst
, i
, Operands
)) {
2408 OpcMap
[std::make_pair(DecoderNamespace
, Size
)].emplace_back(i
, IndexOfInstruction
.find(Def
)->second
);
2410 NumEncodingsOmitted
++;
2414 DecoderTableInfo TableInfo
;
2415 for (const auto &Opc
: OpcMap
) {
2416 // Emit the decoder for this namespace+width combination.
2417 ArrayRef
<EncodingAndInst
> NumberedEncodingsRef(
2418 NumberedEncodings
.data(), NumberedEncodings
.size());
2419 FilterChooser
FC(NumberedEncodingsRef
, Opc
.second
, Operands
,
2420 8 * Opc
.first
.second
, this);
2422 // The decode table is cleared for each top level decoder function. The
2423 // predicates and decoders themselves, however, are shared across all
2424 // decoders to give more opportunities for uniqueing.
2425 TableInfo
.Table
.clear();
2426 TableInfo
.FixupStack
.clear();
2427 TableInfo
.Table
.reserve(16384);
2428 TableInfo
.FixupStack
.emplace_back();
2429 FC
.emitTableEntries(TableInfo
);
2430 // Any NumToSkip fixups in the top level scope can resolve to the
2431 // OPC_Fail at the end of the table.
2432 assert(TableInfo
.FixupStack
.size() == 1 && "fixup stack phasing error!");
2433 // Resolve any NumToSkip fixups in the current scope.
2434 resolveTableFixups(TableInfo
.Table
, TableInfo
.FixupStack
.back(),
2435 TableInfo
.Table
.size());
2436 TableInfo
.FixupStack
.clear();
2438 TableInfo
.Table
.push_back(MCD::OPC_Fail
);
2440 // Print the table to the output stream.
2441 emitTable(OS
, TableInfo
.Table
, 0, FC
.getBitWidth(), Opc
.first
.first
);
2445 // Emit the predicate function.
2446 emitPredicateFunction(OS
, TableInfo
.Predicates
, 0);
2448 // Emit the decoder function.
2449 emitDecoderFunction(OS
, TableInfo
.Decoders
, 0);
2451 // Emit the main entry point for the decoder, decodeInstruction().
2452 emitDecodeInstruction(OS
);
2454 OS
<< "\n} // End llvm namespace\n";
2459 void EmitFixedLenDecoder(RecordKeeper
&RK
, raw_ostream
&OS
,
2460 const std::string
&PredicateNamespace
,
2461 const std::string
&GPrefix
,
2462 const std::string
&GPostfix
, const std::string
&ROK
,
2463 const std::string
&RFail
, const std::string
&L
) {
2464 FixedLenDecoderEmitter(RK
, PredicateNamespace
, GPrefix
, GPostfix
,
2465 ROK
, RFail
, L
).run(OS
);
2468 } // end namespace llvm