1 //===------------ FixedLenDecoderEmitter.cpp - Decoder Generator ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // It contains the tablegen backend that emits the decoder functions for
11 // targets with fixed length instruction set.
13 //===----------------------------------------------------------------------===//
15 #include "CodeGenInstruction.h"
16 #include "CodeGenTarget.h"
17 #include "llvm/ADT/APInt.h"
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/CachedHashString.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/STLExtras.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 struct EncodingField {
52 unsigned Base, Width, Offset;
53 EncodingField(unsigned B, unsigned W, unsigned O)
54 : Base(B), Width(W), Offset(O) { }
58 std::vector<EncodingField> Fields;
60 bool HasCompleteDecoder;
62 OperandInfo(std::string D, bool HCD)
63 : Decoder(std::move(D)), HasCompleteDecoder(HCD) {}
65 void addField(unsigned Base, unsigned Width, unsigned Offset) {
66 Fields.push_back(EncodingField(Base, Width, Offset));
69 unsigned numFields() const { return Fields.size(); }
71 typedef std::vector<EncodingField>::const_iterator const_iterator;
73 const_iterator begin() const { return Fields.begin(); }
74 const_iterator end() const { return Fields.end(); }
77 typedef std::vector<uint8_t> DecoderTable;
78 typedef uint32_t DecoderFixup;
79 typedef std::vector<DecoderFixup> FixupList;
80 typedef std::vector<FixupList> FixupScopeList;
81 typedef SmallSetVector<CachedHashString, 16> PredicateSet;
82 typedef SmallSetVector<CachedHashString, 16> DecoderSet;
83 struct DecoderTableInfo {
85 FixupScopeList FixupStack;
86 PredicateSet Predicates;
90 class FixedLenDecoderEmitter {
91 ArrayRef<const CodeGenInstruction *> NumberedInstructions;
94 // Defaults preserved here for documentation, even though they aren't
95 // strictly necessary given the way that this is currently being called.
96 FixedLenDecoderEmitter(RecordKeeper &R, std::string PredicateNamespace,
97 std::string GPrefix = "if (",
98 std::string GPostfix = " == MCDisassembler::Fail)",
99 std::string ROK = "MCDisassembler::Success",
100 std::string RFail = "MCDisassembler::Fail",
102 : Target(R), PredicateNamespace(std::move(PredicateNamespace)),
103 GuardPrefix(std::move(GPrefix)), GuardPostfix(std::move(GPostfix)),
104 ReturnOK(std::move(ROK)), ReturnFail(std::move(RFail)),
105 Locals(std::move(L)) {}
107 // Emit the decoder state machine table.
108 void emitTable(formatted_raw_ostream &o, DecoderTable &Table,
109 unsigned Indentation, unsigned BitWidth,
110 StringRef Namespace) const;
111 void emitPredicateFunction(formatted_raw_ostream &OS,
112 PredicateSet &Predicates,
113 unsigned Indentation) const;
114 void emitDecoderFunction(formatted_raw_ostream &OS,
115 DecoderSet &Decoders,
116 unsigned Indentation) const;
118 // run - Output the code emitter
119 void run(raw_ostream &o);
122 CodeGenTarget Target;
125 std::string PredicateNamespace;
126 std::string GuardPrefix, GuardPostfix;
127 std::string ReturnOK, ReturnFail;
131 } // end anonymous namespace
133 // The set (BIT_TRUE, BIT_FALSE, BIT_UNSET) represents a ternary logic system
136 // BIT_UNFILTERED is used as the init value for a filter position. It is used
137 // only for filter processings.
142 BIT_UNFILTERED // unfiltered
145 static bool ValueSet(bit_value_t V) {
146 return (V == BIT_TRUE || V == BIT_FALSE);
149 static bool ValueNotSet(bit_value_t V) {
150 return (V == BIT_UNSET);
153 static int Value(bit_value_t V) {
154 return ValueNotSet(V) ? -1 : (V == BIT_FALSE ? 0 : 1);
157 static bit_value_t bitFromBits(const BitsInit &bits, unsigned index) {
158 if (BitInit *bit = dyn_cast<BitInit>(bits.getBit(index)))
159 return bit->getValue() ? BIT_TRUE : BIT_FALSE;
161 // The bit is uninitialized.
165 // Prints the bit value for each position.
166 static void dumpBits(raw_ostream &o, const BitsInit &bits) {
167 for (unsigned index = bits.getNumBits(); index > 0; --index) {
168 switch (bitFromBits(bits, index - 1)) {
179 llvm_unreachable("unexpected return value from bitFromBits");
184 static BitsInit &getBitsField(const Record &def, StringRef str) {
185 BitsInit *bits = def.getValueAsBitsInit(str);
189 // Representation of the instruction to work on.
190 typedef std::vector<bit_value_t> insn_t;
196 /// Filter - Filter works with FilterChooser to produce the decoding tree for
199 /// It is useful to think of a Filter as governing the switch stmts of the
200 /// decoding tree in a certain level. Each case stmt delegates to an inferior
201 /// FilterChooser to decide what further decoding logic to employ, or in another
202 /// words, what other remaining bits to look at. The FilterChooser eventually
203 /// chooses a best Filter to do its job.
205 /// This recursive scheme ends when the number of Opcodes assigned to the
206 /// FilterChooser becomes 1 or if there is a conflict. A conflict happens when
207 /// the Filter/FilterChooser combo does not know how to distinguish among the
208 /// Opcodes assigned.
210 /// An example of a conflict is
213 /// 111101000.00........00010000....
214 /// 111101000.00........0001........
215 /// 1111010...00........0001........
216 /// 1111010...00....................
217 /// 1111010.........................
218 /// 1111............................
219 /// ................................
220 /// VST4q8a 111101000_00________00010000____
221 /// VST4q8b 111101000_00________00010000____
223 /// The Debug output shows the path that the decoding tree follows to reach the
224 /// the conclusion that there is a conflict. VST4q8a is a vst4 to double-spaced
225 /// even registers, while VST4q8b is a vst4 to double-spaced odd registers.
227 /// The encoding info in the .td files does not specify this meta information,
228 /// which could have been used by the decoder to resolve the conflict. The
229 /// decoder could try to decode the even/odd register numbering and assign to
230 /// VST4q8a or VST4q8b, but for the time being, the decoder chooses the "a"
231 /// version and return the Opcode since the two have the same Asm format string.
234 const FilterChooser *Owner;// points to the FilterChooser who owns this filter
235 unsigned StartBit; // the starting bit position
236 unsigned NumBits; // number of bits to filter
237 bool Mixed; // a mixed region contains both set and unset bits
239 // Map of well-known segment value to the set of uid's with that value.
240 std::map<uint64_t, std::vector<unsigned>> FilteredInstructions;
242 // Set of uid's with non-constant segment values.
243 std::vector<unsigned> VariableInstructions;
245 // Map of well-known segment value to its delegate.
246 std::map<unsigned, std::unique_ptr<const FilterChooser>> FilterChooserMap;
248 // Number of instructions which fall under FilteredInstructions category.
249 unsigned NumFiltered;
251 // Keeps track of the last opcode in the filtered bucket.
252 unsigned LastOpcFiltered;
256 Filter(FilterChooser &owner, unsigned startBit, unsigned numBits, bool mixed);
260 unsigned getNumFiltered() const { return NumFiltered; }
262 unsigned getSingletonOpc() const {
263 assert(NumFiltered == 1);
264 return LastOpcFiltered;
267 // Return the filter chooser for the group of instructions without constant
269 const FilterChooser &getVariableFC() const {
270 assert(NumFiltered == 1);
271 assert(FilterChooserMap.size() == 1);
272 return *(FilterChooserMap.find((unsigned)-1)->second);
275 // Divides the decoding task into sub tasks and delegates them to the
276 // inferior FilterChooser's.
278 // A special case arises when there's only one entry in the filtered
279 // instructions. In order to unambiguously decode the singleton, we need to
280 // match the remaining undecoded encoding bits against the singleton.
283 // Emit table entries to decode instructions given a segment or segments of
285 void emitTableEntry(DecoderTableInfo &TableInfo) const;
287 // Returns the number of fanout produced by the filter. More fanout implies
288 // the filter distinguishes more categories of instructions.
289 unsigned usefulness() const;
290 }; // end class Filter
292 } // end anonymous namespace
294 // These are states of our finite state machines used in FilterChooser's
295 // filterProcessor() which produces the filter candidates to use.
304 /// FilterChooser - FilterChooser chooses the best filter among a set of Filters
305 /// in order to perform the decoding of instructions at the current level.
307 /// Decoding proceeds from the top down. Based on the well-known encoding bits
308 /// of instructions available, FilterChooser builds up the possible Filters that
309 /// can further the task of decoding by distinguishing among the remaining
310 /// candidate instructions.
312 /// Once a filter has been chosen, it is called upon to divide the decoding task
313 /// into sub-tasks and delegates them to its inferior FilterChoosers for further
316 /// It is useful to think of a Filter as governing the switch stmts of the
317 /// decoding tree. And each case is delegated to an inferior FilterChooser to
318 /// decide what further remaining bits to look at.
321 class FilterChooser {
325 // Vector of codegen instructions to choose our filter.
326 ArrayRef<const CodeGenInstruction *> AllInstructions;
328 // Vector of uid's for this filter chooser to work on.
329 const std::vector<unsigned> &Opcodes;
331 // Lookup table for the operand decoding of instructions.
332 const std::map<unsigned, std::vector<OperandInfo>> &Operands;
334 // Vector of candidate filters.
335 std::vector<Filter> Filters;
337 // Array of bit values passed down from our parent.
338 // Set to all BIT_UNFILTERED's for Parent == NULL.
339 std::vector<bit_value_t> FilterBitValues;
341 // Links to the FilterChooser above us in the decoding tree.
342 const FilterChooser *Parent;
344 // Index of the best filter from Filters.
347 // Width of instructions
351 const FixedLenDecoderEmitter *Emitter;
354 FilterChooser(ArrayRef<const CodeGenInstruction *> Insts,
355 const std::vector<unsigned> &IDs,
356 const std::map<unsigned, std::vector<OperandInfo>> &Ops,
358 const FixedLenDecoderEmitter *E)
359 : AllInstructions(Insts), Opcodes(IDs), Operands(Ops),
360 FilterBitValues(BW, BIT_UNFILTERED), Parent(nullptr), BestIndex(-1),
361 BitWidth(BW), Emitter(E) {
365 FilterChooser(ArrayRef<const CodeGenInstruction *> Insts,
366 const std::vector<unsigned> &IDs,
367 const std::map<unsigned, std::vector<OperandInfo>> &Ops,
368 const std::vector<bit_value_t> &ParentFilterBitValues,
369 const FilterChooser &parent)
370 : AllInstructions(Insts), Opcodes(IDs), Operands(Ops),
371 FilterBitValues(ParentFilterBitValues), Parent(&parent), BestIndex(-1),
372 BitWidth(parent.BitWidth), Emitter(parent.Emitter) {
376 FilterChooser(const FilterChooser &) = delete;
377 void operator=(const FilterChooser &) = delete;
379 unsigned getBitWidth() const { return BitWidth; }
382 // Populates the insn given the uid.
383 void insnWithID(insn_t &Insn, unsigned Opcode) const {
384 BitsInit &Bits = getBitsField(*AllInstructions[Opcode]->TheDef, "Inst");
386 // We may have a SoftFail bitmask, which specifies a mask where an encoding
387 // may differ from the value in "Inst" and yet still be valid, but the
388 // disassembler should return SoftFail instead of Success.
390 // This is used for marking UNPREDICTABLE instructions in the ARM world.
392 AllInstructions[Opcode]->TheDef->getValueAsBitsInit("SoftFail");
394 for (unsigned i = 0; i < BitWidth; ++i) {
395 if (SFBits && bitFromBits(*SFBits, i) == BIT_TRUE)
396 Insn.push_back(BIT_UNSET);
398 Insn.push_back(bitFromBits(Bits, i));
402 // Returns the record name.
403 const StringRef nameWithID(unsigned Opcode) const {
404 return AllInstructions[Opcode]->TheDef->getName();
407 // Populates the field of the insn given the start position and the number of
408 // consecutive bits to scan for.
410 // Returns false if there exists any uninitialized bit value in the range.
411 // Returns true, otherwise.
412 bool fieldFromInsn(uint64_t &Field, insn_t &Insn, unsigned StartBit,
413 unsigned NumBits) const;
415 /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
416 /// filter array as a series of chars.
417 void dumpFilterArray(raw_ostream &o,
418 const std::vector<bit_value_t> & filter) const;
420 /// dumpStack - dumpStack traverses the filter chooser chain and calls
421 /// dumpFilterArray on each filter chooser up to the top level one.
422 void dumpStack(raw_ostream &o, const char *prefix) const;
424 Filter &bestFilter() {
425 assert(BestIndex != -1 && "BestIndex not set");
426 return Filters[BestIndex];
429 bool PositionFiltered(unsigned i) const {
430 return ValueSet(FilterBitValues[i]);
433 // Calculates the island(s) needed to decode the instruction.
434 // This returns a lit of undecoded bits of an instructions, for example,
435 // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
436 // decoded bits in order to verify that the instruction matches the Opcode.
437 unsigned getIslands(std::vector<unsigned> &StartBits,
438 std::vector<unsigned> &EndBits,
439 std::vector<uint64_t> &FieldVals,
440 const insn_t &Insn) const;
442 // Emits code to check the Predicates member of an instruction are true.
443 // Returns true if predicate matches were emitted, false otherwise.
444 bool emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
447 bool doesOpcodeNeedPredicate(unsigned Opc) const;
448 unsigned getPredicateIndex(DecoderTableInfo &TableInfo, StringRef P) const;
449 void emitPredicateTableEntry(DecoderTableInfo &TableInfo,
452 void emitSoftFailTableEntry(DecoderTableInfo &TableInfo,
455 // Emits table entries to decode the singleton.
456 void emitSingletonTableEntry(DecoderTableInfo &TableInfo,
459 // Emits code to decode the singleton, and then to decode the rest.
460 void emitSingletonTableEntry(DecoderTableInfo &TableInfo,
461 const Filter &Best) const;
463 void emitBinaryParser(raw_ostream &o, unsigned &Indentation,
464 const OperandInfo &OpInfo,
465 bool &OpHasCompleteDecoder) const;
467 void emitDecoder(raw_ostream &OS, unsigned Indentation, unsigned Opc,
468 bool &HasCompleteDecoder) const;
469 unsigned getDecoderIndex(DecoderSet &Decoders, unsigned Opc,
470 bool &HasCompleteDecoder) const;
472 // Assign a single filter and run with it.
473 void runSingleFilter(unsigned startBit, unsigned numBit, bool mixed);
475 // reportRegion is a helper function for filterProcessor to mark a region as
476 // eligible for use as a filter region.
477 void reportRegion(bitAttr_t RA, unsigned StartBit, unsigned BitIndex,
480 // FilterProcessor scans the well-known encoding bits of the instructions and
481 // builds up a list of candidate filters. It chooses the best filter and
482 // recursively descends down the decoding tree.
483 bool filterProcessor(bool AllowMixed, bool Greedy = true);
485 // Decides on the best configuration of filter(s) to use in order to decode
486 // the instructions. A conflict of instructions may occur, in which case we
487 // dump the conflict set to the standard error.
491 // emitTableEntries - Emit state machine entries to decode our share of
493 void emitTableEntries(DecoderTableInfo &TableInfo) const;
496 } // end anonymous namespace
498 ///////////////////////////
500 // Filter Implementation //
502 ///////////////////////////
504 Filter::Filter(Filter &&f)
505 : Owner(f.Owner), StartBit(f.StartBit), NumBits(f.NumBits), Mixed(f.Mixed),
506 FilteredInstructions(std::move(f.FilteredInstructions)),
507 VariableInstructions(std::move(f.VariableInstructions)),
508 FilterChooserMap(std::move(f.FilterChooserMap)), NumFiltered(f.NumFiltered),
509 LastOpcFiltered(f.LastOpcFiltered) {
512 Filter::Filter(FilterChooser &owner, unsigned startBit, unsigned numBits,
514 : Owner(&owner), StartBit(startBit), NumBits(numBits), Mixed(mixed) {
515 assert(StartBit + NumBits - 1 < Owner->BitWidth);
520 for (unsigned i = 0, e = Owner->Opcodes.size(); i != e; ++i) {
523 // Populates the insn given the uid.
524 Owner->insnWithID(Insn, Owner->Opcodes[i]);
527 // Scans the segment for possibly well-specified encoding bits.
528 bool ok = Owner->fieldFromInsn(Field, Insn, StartBit, NumBits);
531 // The encoding bits are well-known. Lets add the uid of the
532 // instruction into the bucket keyed off the constant field value.
533 LastOpcFiltered = Owner->Opcodes[i];
534 FilteredInstructions[Field].push_back(LastOpcFiltered);
537 // Some of the encoding bit(s) are unspecified. This contributes to
538 // one additional member of "Variable" instructions.
539 VariableInstructions.push_back(Owner->Opcodes[i]);
543 assert((FilteredInstructions.size() + VariableInstructions.size() > 0)
544 && "Filter returns no instruction categories");
547 // Divides the decoding task into sub tasks and delegates them to the
548 // inferior FilterChooser's.
550 // A special case arises when there's only one entry in the filtered
551 // instructions. In order to unambiguously decode the singleton, we need to
552 // match the remaining undecoded encoding bits against the singleton.
553 void Filter::recurse() {
554 // Starts by inheriting our parent filter chooser's filter bit values.
555 std::vector<bit_value_t> BitValueArray(Owner->FilterBitValues);
557 if (!VariableInstructions.empty()) {
558 // Conservatively marks each segment position as BIT_UNSET.
559 for (unsigned bitIndex = 0; bitIndex < NumBits; ++bitIndex)
560 BitValueArray[StartBit + bitIndex] = BIT_UNSET;
562 // Delegates to an inferior filter chooser for further processing on this
563 // group of instructions whose segment values are variable.
564 FilterChooserMap.insert(
565 std::make_pair(-1U, llvm::make_unique<FilterChooser>(
566 Owner->AllInstructions, VariableInstructions,
567 Owner->Operands, BitValueArray, *Owner)));
570 // No need to recurse for a singleton filtered instruction.
571 // See also Filter::emit*().
572 if (getNumFiltered() == 1) {
573 assert(FilterChooserMap.size() == 1);
577 // Otherwise, create sub choosers.
578 for (const auto &Inst : FilteredInstructions) {
580 // Marks all the segment positions with either BIT_TRUE or BIT_FALSE.
581 for (unsigned bitIndex = 0; bitIndex < NumBits; ++bitIndex) {
582 if (Inst.first & (1ULL << bitIndex))
583 BitValueArray[StartBit + bitIndex] = BIT_TRUE;
585 BitValueArray[StartBit + bitIndex] = BIT_FALSE;
588 // Delegates to an inferior filter chooser for further processing on this
589 // category of instructions.
590 FilterChooserMap.insert(std::make_pair(
591 Inst.first, llvm::make_unique<FilterChooser>(
592 Owner->AllInstructions, Inst.second,
593 Owner->Operands, BitValueArray, *Owner)));
597 static void resolveTableFixups(DecoderTable &Table, const FixupList &Fixups,
599 // Any NumToSkip fixups in the current scope can resolve to the
601 for (FixupList::const_reverse_iterator I = Fixups.rbegin(),
604 // Calculate the distance from the byte following the fixup entry byte
605 // to the destination. The Target is calculated from after the 16-bit
606 // NumToSkip entry itself, so subtract two from the displacement here
607 // to account for that.
608 uint32_t FixupIdx = *I;
609 uint32_t Delta = DestIdx - FixupIdx - 2;
610 // Our NumToSkip entries are 16-bits. Make sure our table isn't too
612 assert(Delta < 65536U && "disassembler decoding table too large!");
613 Table[FixupIdx] = (uint8_t)Delta;
614 Table[FixupIdx + 1] = (uint8_t)(Delta >> 8);
618 // Emit table entries to decode instructions given a segment or segments
620 void Filter::emitTableEntry(DecoderTableInfo &TableInfo) const {
621 TableInfo.Table.push_back(MCD::OPC_ExtractField);
622 TableInfo.Table.push_back(StartBit);
623 TableInfo.Table.push_back(NumBits);
625 // A new filter entry begins a new scope for fixup resolution.
626 TableInfo.FixupStack.emplace_back();
628 DecoderTable &Table = TableInfo.Table;
630 size_t PrevFilter = 0;
631 bool HasFallthrough = false;
632 for (auto &Filter : FilterChooserMap) {
633 // Field value -1 implies a non-empty set of variable instructions.
634 // See also recurse().
635 if (Filter.first == (unsigned)-1) {
636 HasFallthrough = true;
638 // Each scope should always have at least one filter value to check
640 assert(PrevFilter != 0 && "empty filter set!");
641 FixupList &CurScope = TableInfo.FixupStack.back();
642 // Resolve any NumToSkip fixups in the current scope.
643 resolveTableFixups(Table, CurScope, Table.size());
645 PrevFilter = 0; // Don't re-process the filter's fallthrough.
647 Table.push_back(MCD::OPC_FilterValue);
648 // Encode and emit the value to filter against.
650 unsigned Len = encodeULEB128(Filter.first, Buffer);
651 Table.insert(Table.end(), Buffer, Buffer + Len);
652 // Reserve space for the NumToSkip entry. We'll backpatch the value
654 PrevFilter = Table.size();
659 // We arrive at a category of instructions with the same segment value.
660 // Now delegate to the sub filter chooser for further decodings.
661 // The case may fallthrough, which happens if the remaining well-known
662 // encoding bits do not match exactly.
663 Filter.second->emitTableEntries(TableInfo);
665 // Now that we've emitted the body of the handler, update the NumToSkip
666 // of the filter itself to be able to skip forward when false. Subtract
667 // two as to account for the width of the NumToSkip field itself.
669 uint32_t NumToSkip = Table.size() - PrevFilter - 2;
670 assert(NumToSkip < 65536U && "disassembler decoding table too large!");
671 Table[PrevFilter] = (uint8_t)NumToSkip;
672 Table[PrevFilter + 1] = (uint8_t)(NumToSkip >> 8);
676 // Any remaining unresolved fixups bubble up to the parent fixup scope.
677 assert(TableInfo.FixupStack.size() > 1 && "fixup stack underflow!");
678 FixupScopeList::iterator Source = TableInfo.FixupStack.end() - 1;
679 FixupScopeList::iterator Dest = Source - 1;
680 Dest->insert(Dest->end(), Source->begin(), Source->end());
681 TableInfo.FixupStack.pop_back();
683 // If there is no fallthrough, then the final filter should get fixed
684 // up according to the enclosing scope rather than the current position.
686 TableInfo.FixupStack.back().push_back(PrevFilter);
689 // Returns the number of fanout produced by the filter. More fanout implies
690 // the filter distinguishes more categories of instructions.
691 unsigned Filter::usefulness() const {
692 if (!VariableInstructions.empty())
693 return FilteredInstructions.size();
695 return FilteredInstructions.size() + 1;
698 //////////////////////////////////
700 // Filterchooser Implementation //
702 //////////////////////////////////
704 // Emit the decoder state machine table.
705 void FixedLenDecoderEmitter::emitTable(formatted_raw_ostream &OS,
707 unsigned Indentation,
709 StringRef Namespace) const {
710 OS.indent(Indentation) << "static const uint8_t DecoderTable" << Namespace
711 << BitWidth << "[] = {\n";
715 // FIXME: We may be able to use the NumToSkip values to recover
716 // appropriate indentation levels.
717 DecoderTable::const_iterator I = Table.begin();
718 DecoderTable::const_iterator E = Table.end();
720 assert (I < E && "incomplete decode table entry!");
722 uint64_t Pos = I - Table.begin();
723 OS << "/* " << Pos << " */";
728 PrintFatalError("invalid decode table opcode");
729 case MCD::OPC_ExtractField: {
731 unsigned Start = *I++;
733 OS.indent(Indentation) << "MCD::OPC_ExtractField, " << Start << ", "
734 << Len << ", // Inst{";
736 OS << (Start + Len - 1) << "-";
737 OS << Start << "} ...\n";
740 case MCD::OPC_FilterValue: {
742 OS.indent(Indentation) << "MCD::OPC_FilterValue, ";
743 // The filter value is ULEB128 encoded.
745 OS << (unsigned)*I++ << ", ";
746 OS << (unsigned)*I++ << ", ";
748 // 16-bit numtoskip value.
750 uint32_t NumToSkip = Byte;
751 OS << (unsigned)Byte << ", ";
753 OS << (unsigned)Byte << ", ";
754 NumToSkip |= Byte << 8;
755 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
758 case MCD::OPC_CheckField: {
760 unsigned Start = *I++;
762 OS.indent(Indentation) << "MCD::OPC_CheckField, " << Start << ", "
763 << Len << ", ";// << Val << ", " << NumToSkip << ",\n";
764 // ULEB128 encoded field value.
765 for (; *I >= 128; ++I)
766 OS << (unsigned)*I << ", ";
767 OS << (unsigned)*I++ << ", ";
768 // 16-bit numtoskip value.
770 uint32_t NumToSkip = Byte;
771 OS << (unsigned)Byte << ", ";
773 OS << (unsigned)Byte << ", ";
774 NumToSkip |= Byte << 8;
775 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
778 case MCD::OPC_CheckPredicate: {
780 OS.indent(Indentation) << "MCD::OPC_CheckPredicate, ";
781 for (; *I >= 128; ++I)
782 OS << (unsigned)*I << ", ";
783 OS << (unsigned)*I++ << ", ";
785 // 16-bit numtoskip value.
787 uint32_t NumToSkip = Byte;
788 OS << (unsigned)Byte << ", ";
790 OS << (unsigned)Byte << ", ";
791 NumToSkip |= Byte << 8;
792 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
795 case MCD::OPC_Decode:
796 case MCD::OPC_TryDecode: {
797 bool IsTry = *I == MCD::OPC_TryDecode;
799 // Extract the ULEB128 encoded Opcode to a buffer.
800 uint8_t Buffer[8], *p = Buffer;
801 while ((*p++ = *I++) >= 128)
802 assert((p - Buffer) <= (ptrdiff_t)sizeof(Buffer)
803 && "ULEB128 value too large!");
804 // Decode the Opcode value.
805 unsigned Opc = decodeULEB128(Buffer);
806 OS.indent(Indentation) << "MCD::OPC_" << (IsTry ? "Try" : "")
808 for (p = Buffer; *p >= 128; ++p)
809 OS << (unsigned)*p << ", ";
810 OS << (unsigned)*p << ", ";
813 for (; *I >= 128; ++I)
814 OS << (unsigned)*I << ", ";
815 OS << (unsigned)*I++ << ", ";
819 << NumberedInstructions[Opc]->TheDef->getName() << "\n";
823 // Fallthrough for OPC_TryDecode.
825 // 16-bit numtoskip value.
827 uint32_t NumToSkip = Byte;
828 OS << (unsigned)Byte << ", ";
830 OS << (unsigned)Byte << ", ";
831 NumToSkip |= Byte << 8;
834 << NumberedInstructions[Opc]->TheDef->getName()
835 << ", skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
838 case MCD::OPC_SoftFail: {
840 OS.indent(Indentation) << "MCD::OPC_SoftFail";
845 OS << ", " << (unsigned)*I;
846 Value += (*I & 0x7f) << Shift;
848 } while (*I++ >= 128);
858 OS << ", " << (unsigned)*I;
859 Value += (*I & 0x7f) << Shift;
861 } while (*I++ >= 128);
870 case MCD::OPC_Fail: {
872 OS.indent(Indentation) << "MCD::OPC_Fail,\n";
877 OS.indent(Indentation) << "0\n";
881 OS.indent(Indentation) << "};\n\n";
884 void FixedLenDecoderEmitter::
885 emitPredicateFunction(formatted_raw_ostream &OS, PredicateSet &Predicates,
886 unsigned Indentation) const {
887 // The predicate function is just a big switch statement based on the
888 // input predicate index.
889 OS.indent(Indentation) << "static bool checkDecoderPredicate(unsigned Idx, "
890 << "const FeatureBitset& Bits) {\n";
892 if (!Predicates.empty()) {
893 OS.indent(Indentation) << "switch (Idx) {\n";
894 OS.indent(Indentation) << "default: llvm_unreachable(\"Invalid index!\");\n";
896 for (const auto &Predicate : Predicates) {
897 OS.indent(Indentation) << "case " << Index++ << ":\n";
898 OS.indent(Indentation+2) << "return (" << Predicate << ");\n";
900 OS.indent(Indentation) << "}\n";
902 // No case statement to emit
903 OS.indent(Indentation) << "llvm_unreachable(\"Invalid index!\");\n";
906 OS.indent(Indentation) << "}\n\n";
909 void FixedLenDecoderEmitter::
910 emitDecoderFunction(formatted_raw_ostream &OS, DecoderSet &Decoders,
911 unsigned Indentation) const {
912 // The decoder function is just a big switch statement based on the
913 // input decoder index.
914 OS.indent(Indentation) << "template<typename InsnType>\n";
915 OS.indent(Indentation) << "static DecodeStatus decodeToMCInst(DecodeStatus S,"
916 << " unsigned Idx, InsnType insn, MCInst &MI,\n";
917 OS.indent(Indentation) << " uint64_t "
918 << "Address, const void *Decoder, bool &DecodeComplete) {\n";
920 OS.indent(Indentation) << "DecodeComplete = true;\n";
921 OS.indent(Indentation) << "InsnType tmp;\n";
922 OS.indent(Indentation) << "switch (Idx) {\n";
923 OS.indent(Indentation) << "default: llvm_unreachable(\"Invalid index!\");\n";
925 for (const auto &Decoder : Decoders) {
926 OS.indent(Indentation) << "case " << Index++ << ":\n";
928 OS.indent(Indentation+2) << "return S;\n";
930 OS.indent(Indentation) << "}\n";
932 OS.indent(Indentation) << "}\n\n";
935 // Populates the field of the insn given the start position and the number of
936 // consecutive bits to scan for.
938 // Returns false if and on the first uninitialized bit value encountered.
939 // Returns true, otherwise.
940 bool FilterChooser::fieldFromInsn(uint64_t &Field, insn_t &Insn,
941 unsigned StartBit, unsigned NumBits) const {
944 for (unsigned i = 0; i < NumBits; ++i) {
945 if (Insn[StartBit + i] == BIT_UNSET)
948 if (Insn[StartBit + i] == BIT_TRUE)
949 Field = Field | (1ULL << i);
955 /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
956 /// filter array as a series of chars.
957 void FilterChooser::dumpFilterArray(raw_ostream &o,
958 const std::vector<bit_value_t> &filter) const {
959 for (unsigned bitIndex = BitWidth; bitIndex > 0; bitIndex--) {
960 switch (filter[bitIndex - 1]) {
977 /// dumpStack - dumpStack traverses the filter chooser chain and calls
978 /// dumpFilterArray on each filter chooser up to the top level one.
979 void FilterChooser::dumpStack(raw_ostream &o, const char *prefix) const {
980 const FilterChooser *current = this;
984 dumpFilterArray(o, current->FilterBitValues);
986 current = current->Parent;
990 // Calculates the island(s) needed to decode the instruction.
991 // This returns a list of undecoded bits of an instructions, for example,
992 // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
993 // decoded bits in order to verify that the instruction matches the Opcode.
994 unsigned FilterChooser::getIslands(std::vector<unsigned> &StartBits,
995 std::vector<unsigned> &EndBits,
996 std::vector<uint64_t> &FieldVals,
997 const insn_t &Insn) const {
1001 uint64_t FieldVal = 0;
1004 // 1: Water (the bit value does not affect decoding)
1005 // 2: Island (well-known bit value needed for decoding)
1009 for (unsigned i = 0; i < BitWidth; ++i) {
1010 Val = Value(Insn[i]);
1011 bool Filtered = PositionFiltered(i);
1013 default: llvm_unreachable("Unreachable code!");
1016 if (Filtered || Val == -1)
1017 State = 1; // Still in Water
1019 State = 2; // Into the Island
1021 StartBits.push_back(i);
1026 if (Filtered || Val == -1) {
1027 State = 1; // Into the Water
1028 EndBits.push_back(i - 1);
1029 FieldVals.push_back(FieldVal);
1032 State = 2; // Still in Island
1034 FieldVal = FieldVal | Val << BitNo;
1039 // If we are still in Island after the loop, do some housekeeping.
1041 EndBits.push_back(BitWidth - 1);
1042 FieldVals.push_back(FieldVal);
1046 assert(StartBits.size() == Num && EndBits.size() == Num &&
1047 FieldVals.size() == Num);
1051 void FilterChooser::emitBinaryParser(raw_ostream &o, unsigned &Indentation,
1052 const OperandInfo &OpInfo,
1053 bool &OpHasCompleteDecoder) const {
1054 const std::string &Decoder = OpInfo.Decoder;
1056 if (OpInfo.numFields() != 1)
1057 o.indent(Indentation) << "tmp = 0;\n";
1059 for (const EncodingField &EF : OpInfo) {
1060 o.indent(Indentation) << "tmp ";
1061 if (OpInfo.numFields() != 1) o << '|';
1062 o << "= fieldFromInstruction"
1063 << "(insn, " << EF.Base << ", " << EF.Width << ')';
1064 if (OpInfo.numFields() != 1 || EF.Offset != 0)
1065 o << " << " << EF.Offset;
1069 if (Decoder != "") {
1070 OpHasCompleteDecoder = OpInfo.HasCompleteDecoder;
1071 o.indent(Indentation) << Emitter->GuardPrefix << Decoder
1072 << "(MI, tmp, Address, Decoder)"
1073 << Emitter->GuardPostfix
1074 << " { " << (OpHasCompleteDecoder ? "" : "DecodeComplete = false; ")
1075 << "return MCDisassembler::Fail; }\n";
1077 OpHasCompleteDecoder = true;
1078 o.indent(Indentation) << "MI.addOperand(MCOperand::createImm(tmp));\n";
1082 void FilterChooser::emitDecoder(raw_ostream &OS, unsigned Indentation,
1083 unsigned Opc, bool &HasCompleteDecoder) const {
1084 HasCompleteDecoder = true;
1086 for (const auto &Op : Operands.find(Opc)->second) {
1087 // If a custom instruction decoder was specified, use that.
1088 if (Op.numFields() == 0 && !Op.Decoder.empty()) {
1089 HasCompleteDecoder = Op.HasCompleteDecoder;
1090 OS.indent(Indentation) << Emitter->GuardPrefix << Op.Decoder
1091 << "(MI, insn, Address, Decoder)"
1092 << Emitter->GuardPostfix
1093 << " { " << (HasCompleteDecoder ? "" : "DecodeComplete = false; ")
1094 << "return MCDisassembler::Fail; }\n";
1098 bool OpHasCompleteDecoder;
1099 emitBinaryParser(OS, Indentation, Op, OpHasCompleteDecoder);
1100 if (!OpHasCompleteDecoder)
1101 HasCompleteDecoder = false;
1105 unsigned FilterChooser::getDecoderIndex(DecoderSet &Decoders,
1107 bool &HasCompleteDecoder) const {
1108 // Build up the predicate string.
1109 SmallString<256> Decoder;
1110 // FIXME: emitDecoder() function can take a buffer directly rather than
1112 raw_svector_ostream S(Decoder);
1114 emitDecoder(S, I, Opc, HasCompleteDecoder);
1116 // Using the full decoder string as the key value here is a bit
1117 // heavyweight, but is effective. If the string comparisons become a
1118 // performance concern, we can implement a mangling of the predicate
1119 // data easily enough with a map back to the actual string. That's
1120 // overkill for now, though.
1122 // Make sure the predicate is in the table.
1123 Decoders.insert(CachedHashString(Decoder));
1124 // Now figure out the index for when we write out the table.
1125 DecoderSet::const_iterator P = find(Decoders, Decoder.str());
1126 return (unsigned)(P - Decoders.begin());
1129 static void emitSinglePredicateMatch(raw_ostream &o, StringRef str,
1130 const std::string &PredicateNamespace) {
1132 o << "!Bits[" << PredicateNamespace << "::"
1133 << str.slice(1,str.size()) << "]";
1135 o << "Bits[" << PredicateNamespace << "::" << str << "]";
1138 bool FilterChooser::emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
1139 unsigned Opc) const {
1140 ListInit *Predicates =
1141 AllInstructions[Opc]->TheDef->getValueAsListInit("Predicates");
1142 bool IsFirstEmission = true;
1143 for (unsigned i = 0; i < Predicates->size(); ++i) {
1144 Record *Pred = Predicates->getElementAsRecord(i);
1145 if (!Pred->getValue("AssemblerMatcherPredicate"))
1148 StringRef P = Pred->getValueAsString("AssemblerCondString");
1153 if (!IsFirstEmission)
1156 std::pair<StringRef, StringRef> pairs = P.split(',');
1157 while (!pairs.second.empty()) {
1158 emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
1160 pairs = pairs.second.split(',');
1162 emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
1163 IsFirstEmission = false;
1165 return !Predicates->empty();
1168 bool FilterChooser::doesOpcodeNeedPredicate(unsigned Opc) const {
1169 ListInit *Predicates =
1170 AllInstructions[Opc]->TheDef->getValueAsListInit("Predicates");
1171 for (unsigned i = 0; i < Predicates->size(); ++i) {
1172 Record *Pred = Predicates->getElementAsRecord(i);
1173 if (!Pred->getValue("AssemblerMatcherPredicate"))
1176 StringRef P = Pred->getValueAsString("AssemblerCondString");
1186 unsigned FilterChooser::getPredicateIndex(DecoderTableInfo &TableInfo,
1187 StringRef Predicate) const {
1188 // Using the full predicate string as the key value here is a bit
1189 // heavyweight, but is effective. If the string comparisons become a
1190 // performance concern, we can implement a mangling of the predicate
1191 // data easily enough with a map back to the actual string. That's
1192 // overkill for now, though.
1194 // Make sure the predicate is in the table.
1195 TableInfo.Predicates.insert(CachedHashString(Predicate));
1196 // Now figure out the index for when we write out the table.
1197 PredicateSet::const_iterator P = find(TableInfo.Predicates, Predicate);
1198 return (unsigned)(P - TableInfo.Predicates.begin());
1201 void FilterChooser::emitPredicateTableEntry(DecoderTableInfo &TableInfo,
1202 unsigned Opc) const {
1203 if (!doesOpcodeNeedPredicate(Opc))
1206 // Build up the predicate string.
1207 SmallString<256> Predicate;
1208 // FIXME: emitPredicateMatch() functions can take a buffer directly rather
1210 raw_svector_ostream PS(Predicate);
1212 emitPredicateMatch(PS, I, Opc);
1214 // Figure out the index into the predicate table for the predicate just
1216 unsigned PIdx = getPredicateIndex(TableInfo, PS.str());
1217 SmallString<16> PBytes;
1218 raw_svector_ostream S(PBytes);
1219 encodeULEB128(PIdx, S);
1221 TableInfo.Table.push_back(MCD::OPC_CheckPredicate);
1223 for (unsigned i = 0, e = PBytes.size(); i != e; ++i)
1224 TableInfo.Table.push_back(PBytes[i]);
1225 // Push location for NumToSkip backpatching.
1226 TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
1227 TableInfo.Table.push_back(0);
1228 TableInfo.Table.push_back(0);
1231 void FilterChooser::emitSoftFailTableEntry(DecoderTableInfo &TableInfo,
1232 unsigned Opc) const {
1234 AllInstructions[Opc]->TheDef->getValueAsBitsInit("SoftFail");
1235 if (!SFBits) return;
1236 BitsInit *InstBits = AllInstructions[Opc]->TheDef->getValueAsBitsInit("Inst");
1238 APInt PositiveMask(BitWidth, 0ULL);
1239 APInt NegativeMask(BitWidth, 0ULL);
1240 for (unsigned i = 0; i < BitWidth; ++i) {
1241 bit_value_t B = bitFromBits(*SFBits, i);
1242 bit_value_t IB = bitFromBits(*InstBits, i);
1244 if (B != BIT_TRUE) continue;
1248 // The bit is meant to be false, so emit a check to see if it is true.
1249 PositiveMask.setBit(i);
1252 // The bit is meant to be true, so emit a check to see if it is false.
1253 NegativeMask.setBit(i);
1256 // The bit is not set; this must be an error!
1257 StringRef Name = AllInstructions[Opc]->TheDef->getName();
1258 errs() << "SoftFail Conflict: bit SoftFail{" << i << "} in " << Name
1259 << " is set but Inst{" << i << "} is unset!\n"
1260 << " - You can only mark a bit as SoftFail if it is fully defined"
1261 << " (1/0 - not '?') in Inst\n";
1266 bool NeedPositiveMask = PositiveMask.getBoolValue();
1267 bool NeedNegativeMask = NegativeMask.getBoolValue();
1269 if (!NeedPositiveMask && !NeedNegativeMask)
1272 TableInfo.Table.push_back(MCD::OPC_SoftFail);
1274 SmallString<16> MaskBytes;
1275 raw_svector_ostream S(MaskBytes);
1276 if (NeedPositiveMask) {
1277 encodeULEB128(PositiveMask.getZExtValue(), S);
1278 for (unsigned i = 0, e = MaskBytes.size(); i != e; ++i)
1279 TableInfo.Table.push_back(MaskBytes[i]);
1281 TableInfo.Table.push_back(0);
1282 if (NeedNegativeMask) {
1284 encodeULEB128(NegativeMask.getZExtValue(), S);
1285 for (unsigned i = 0, e = MaskBytes.size(); i != e; ++i)
1286 TableInfo.Table.push_back(MaskBytes[i]);
1288 TableInfo.Table.push_back(0);
1291 // Emits table entries to decode the singleton.
1292 void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,
1293 unsigned Opc) const {
1294 std::vector<unsigned> StartBits;
1295 std::vector<unsigned> EndBits;
1296 std::vector<uint64_t> FieldVals;
1298 insnWithID(Insn, Opc);
1300 // Look for islands of undecoded bits of the singleton.
1301 getIslands(StartBits, EndBits, FieldVals, Insn);
1303 unsigned Size = StartBits.size();
1305 // Emit the predicate table entry if one is needed.
1306 emitPredicateTableEntry(TableInfo, Opc);
1308 // Check any additional encoding fields needed.
1309 for (unsigned I = Size; I != 0; --I) {
1310 unsigned NumBits = EndBits[I-1] - StartBits[I-1] + 1;
1311 TableInfo.Table.push_back(MCD::OPC_CheckField);
1312 TableInfo.Table.push_back(StartBits[I-1]);
1313 TableInfo.Table.push_back(NumBits);
1314 uint8_t Buffer[8], *p;
1315 encodeULEB128(FieldVals[I-1], Buffer);
1316 for (p = Buffer; *p >= 128 ; ++p)
1317 TableInfo.Table.push_back(*p);
1318 TableInfo.Table.push_back(*p);
1319 // Push location for NumToSkip backpatching.
1320 TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
1321 // The fixup is always 16-bits, so go ahead and allocate the space
1322 // in the table so all our relative position calculations work OK even
1323 // before we fully resolve the real value here.
1324 TableInfo.Table.push_back(0);
1325 TableInfo.Table.push_back(0);
1328 // Check for soft failure of the match.
1329 emitSoftFailTableEntry(TableInfo, Opc);
1331 bool HasCompleteDecoder;
1332 unsigned DIdx = getDecoderIndex(TableInfo.Decoders, Opc, HasCompleteDecoder);
1334 // Produce OPC_Decode or OPC_TryDecode opcode based on the information
1335 // whether the instruction decoder is complete or not. If it is complete
1336 // then it handles all possible values of remaining variable/unfiltered bits
1337 // and for any value can determine if the bitpattern is a valid instruction
1338 // or not. This means OPC_Decode will be the final step in the decoding
1339 // process. If it is not complete, then the Fail return code from the
1340 // decoder method indicates that additional processing should be done to see
1341 // if there is any other instruction that also matches the bitpattern and
1343 TableInfo.Table.push_back(HasCompleteDecoder ? MCD::OPC_Decode :
1344 MCD::OPC_TryDecode);
1345 uint8_t Buffer[8], *p;
1346 encodeULEB128(Opc, Buffer);
1347 for (p = Buffer; *p >= 128 ; ++p)
1348 TableInfo.Table.push_back(*p);
1349 TableInfo.Table.push_back(*p);
1351 SmallString<16> Bytes;
1352 raw_svector_ostream S(Bytes);
1353 encodeULEB128(DIdx, S);
1356 for (unsigned i = 0, e = Bytes.size(); i != e; ++i)
1357 TableInfo.Table.push_back(Bytes[i]);
1359 if (!HasCompleteDecoder) {
1360 // Push location for NumToSkip backpatching.
1361 TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
1362 // Allocate the space for the fixup.
1363 TableInfo.Table.push_back(0);
1364 TableInfo.Table.push_back(0);
1368 // Emits table entries to decode the singleton, and then to decode the rest.
1369 void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,
1370 const Filter &Best) const {
1371 unsigned Opc = Best.getSingletonOpc();
1373 // complex singletons need predicate checks from the first singleton
1374 // to refer forward to the variable filterchooser that follows.
1375 TableInfo.FixupStack.emplace_back();
1377 emitSingletonTableEntry(TableInfo, Opc);
1379 resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),
1380 TableInfo.Table.size());
1381 TableInfo.FixupStack.pop_back();
1383 Best.getVariableFC().emitTableEntries(TableInfo);
1386 // Assign a single filter and run with it. Top level API client can initialize
1387 // with a single filter to start the filtering process.
1388 void FilterChooser::runSingleFilter(unsigned startBit, unsigned numBit,
1391 Filters.emplace_back(*this, startBit, numBit, true);
1392 BestIndex = 0; // Sole Filter instance to choose from.
1393 bestFilter().recurse();
1396 // reportRegion is a helper function for filterProcessor to mark a region as
1397 // eligible for use as a filter region.
1398 void FilterChooser::reportRegion(bitAttr_t RA, unsigned StartBit,
1399 unsigned BitIndex, bool AllowMixed) {
1400 if (RA == ATTR_MIXED && AllowMixed)
1401 Filters.emplace_back(*this, StartBit, BitIndex - StartBit, true);
1402 else if (RA == ATTR_ALL_SET && !AllowMixed)
1403 Filters.emplace_back(*this, StartBit, BitIndex - StartBit, false);
1406 // FilterProcessor scans the well-known encoding bits of the instructions and
1407 // builds up a list of candidate filters. It chooses the best filter and
1408 // recursively descends down the decoding tree.
1409 bool FilterChooser::filterProcessor(bool AllowMixed, bool Greedy) {
1412 unsigned numInstructions = Opcodes.size();
1414 assert(numInstructions && "Filter created with no instructions");
1416 // No further filtering is necessary.
1417 if (numInstructions == 1)
1420 // Heuristics. See also doFilter()'s "Heuristics" comment when num of
1421 // instructions is 3.
1422 if (AllowMixed && !Greedy) {
1423 assert(numInstructions == 3);
1425 for (unsigned i = 0; i < Opcodes.size(); ++i) {
1426 std::vector<unsigned> StartBits;
1427 std::vector<unsigned> EndBits;
1428 std::vector<uint64_t> FieldVals;
1431 insnWithID(Insn, Opcodes[i]);
1433 // Look for islands of undecoded bits of any instruction.
1434 if (getIslands(StartBits, EndBits, FieldVals, Insn) > 0) {
1435 // Found an instruction with island(s). Now just assign a filter.
1436 runSingleFilter(StartBits[0], EndBits[0] - StartBits[0] + 1, true);
1444 // We maintain BIT_WIDTH copies of the bitAttrs automaton.
1445 // The automaton consumes the corresponding bit from each
1448 // Input symbols: 0, 1, and _ (unset).
1449 // States: NONE, FILTERED, ALL_SET, ALL_UNSET, and MIXED.
1450 // Initial state: NONE.
1452 // (NONE) ------- [01] -> (ALL_SET)
1453 // (NONE) ------- _ ----> (ALL_UNSET)
1454 // (ALL_SET) ---- [01] -> (ALL_SET)
1455 // (ALL_SET) ---- _ ----> (MIXED)
1456 // (ALL_UNSET) -- [01] -> (MIXED)
1457 // (ALL_UNSET) -- _ ----> (ALL_UNSET)
1458 // (MIXED) ------ . ----> (MIXED)
1459 // (FILTERED)---- . ----> (FILTERED)
1461 std::vector<bitAttr_t> bitAttrs;
1463 // FILTERED bit positions provide no entropy and are not worthy of pursuing.
1464 // Filter::recurse() set either BIT_TRUE or BIT_FALSE for each position.
1465 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex)
1466 if (FilterBitValues[BitIndex] == BIT_TRUE ||
1467 FilterBitValues[BitIndex] == BIT_FALSE)
1468 bitAttrs.push_back(ATTR_FILTERED);
1470 bitAttrs.push_back(ATTR_NONE);
1472 for (unsigned InsnIndex = 0; InsnIndex < numInstructions; ++InsnIndex) {
1475 insnWithID(insn, Opcodes[InsnIndex]);
1477 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
1478 switch (bitAttrs[BitIndex]) {
1480 if (insn[BitIndex] == BIT_UNSET)
1481 bitAttrs[BitIndex] = ATTR_ALL_UNSET;
1483 bitAttrs[BitIndex] = ATTR_ALL_SET;
1486 if (insn[BitIndex] == BIT_UNSET)
1487 bitAttrs[BitIndex] = ATTR_MIXED;
1489 case ATTR_ALL_UNSET:
1490 if (insn[BitIndex] != BIT_UNSET)
1491 bitAttrs[BitIndex] = ATTR_MIXED;
1500 // The regionAttr automaton consumes the bitAttrs automatons' state,
1501 // lowest-to-highest.
1503 // Input symbols: F(iltered), (all_)S(et), (all_)U(nset), M(ixed)
1504 // States: NONE, ALL_SET, MIXED
1505 // Initial state: NONE
1507 // (NONE) ----- F --> (NONE)
1508 // (NONE) ----- S --> (ALL_SET) ; and set region start
1509 // (NONE) ----- U --> (NONE)
1510 // (NONE) ----- M --> (MIXED) ; and set region start
1511 // (ALL_SET) -- F --> (NONE) ; and report an ALL_SET region
1512 // (ALL_SET) -- S --> (ALL_SET)
1513 // (ALL_SET) -- U --> (NONE) ; and report an ALL_SET region
1514 // (ALL_SET) -- M --> (MIXED) ; and report an ALL_SET region
1515 // (MIXED) ---- F --> (NONE) ; and report a MIXED region
1516 // (MIXED) ---- S --> (ALL_SET) ; and report a MIXED region
1517 // (MIXED) ---- U --> (NONE) ; and report a MIXED region
1518 // (MIXED) ---- M --> (MIXED)
1520 bitAttr_t RA = ATTR_NONE;
1521 unsigned StartBit = 0;
1523 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
1524 bitAttr_t bitAttr = bitAttrs[BitIndex];
1526 assert(bitAttr != ATTR_NONE && "Bit without attributes");
1534 StartBit = BitIndex;
1537 case ATTR_ALL_UNSET:
1540 StartBit = BitIndex;
1544 llvm_unreachable("Unexpected bitAttr!");
1550 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1555 case ATTR_ALL_UNSET:
1556 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1560 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1561 StartBit = BitIndex;
1565 llvm_unreachable("Unexpected bitAttr!");
1571 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1572 StartBit = BitIndex;
1576 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1577 StartBit = BitIndex;
1580 case ATTR_ALL_UNSET:
1581 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1587 llvm_unreachable("Unexpected bitAttr!");
1590 case ATTR_ALL_UNSET:
1591 llvm_unreachable("regionAttr state machine has no ATTR_UNSET state");
1593 llvm_unreachable("regionAttr state machine has no ATTR_FILTERED state");
1597 // At the end, if we're still in ALL_SET or MIXED states, report a region
1604 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1606 case ATTR_ALL_UNSET:
1609 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1613 // We have finished with the filter processings. Now it's time to choose
1614 // the best performing filter.
1616 bool AllUseless = true;
1617 unsigned BestScore = 0;
1619 for (unsigned i = 0, e = Filters.size(); i != e; ++i) {
1620 unsigned Usefulness = Filters[i].usefulness();
1625 if (Usefulness > BestScore) {
1627 BestScore = Usefulness;
1632 bestFilter().recurse();
1635 } // end of FilterChooser::filterProcessor(bool)
1637 // Decides on the best configuration of filter(s) to use in order to decode
1638 // the instructions. A conflict of instructions may occur, in which case we
1639 // dump the conflict set to the standard error.
1640 void FilterChooser::doFilter() {
1641 unsigned Num = Opcodes.size();
1642 assert(Num && "FilterChooser created with no instructions");
1644 // Try regions of consecutive known bit values first.
1645 if (filterProcessor(false))
1648 // Then regions of mixed bits (both known and unitialized bit values allowed).
1649 if (filterProcessor(true))
1652 // Heuristics to cope with conflict set {t2CMPrs, t2SUBSrr, t2SUBSrs} where
1653 // no single instruction for the maximum ATTR_MIXED region Inst{14-4} has a
1654 // well-known encoding pattern. In such case, we backtrack and scan for the
1655 // the very first consecutive ATTR_ALL_SET region and assign a filter to it.
1656 if (Num == 3 && filterProcessor(true, false))
1659 // If we come to here, the instruction decoding has failed.
1660 // Set the BestIndex to -1 to indicate so.
1664 // emitTableEntries - Emit state machine entries to decode our share of
1666 void FilterChooser::emitTableEntries(DecoderTableInfo &TableInfo) const {
1667 if (Opcodes.size() == 1) {
1668 // There is only one instruction in the set, which is great!
1669 // Call emitSingletonDecoder() to see whether there are any remaining
1671 emitSingletonTableEntry(TableInfo, Opcodes[0]);
1675 // Choose the best filter to do the decodings!
1676 if (BestIndex != -1) {
1677 const Filter &Best = Filters[BestIndex];
1678 if (Best.getNumFiltered() == 1)
1679 emitSingletonTableEntry(TableInfo, Best);
1681 Best.emitTableEntry(TableInfo);
1685 // We don't know how to decode these instructions! Dump the
1686 // conflict set and bail.
1688 // Print out useful conflict information for postmortem analysis.
1689 errs() << "Decoding Conflict:\n";
1691 dumpStack(errs(), "\t\t");
1693 for (unsigned i = 0; i < Opcodes.size(); ++i) {
1694 const std::string &Name = nameWithID(Opcodes[i]);
1696 errs() << '\t' << Name << " ";
1698 getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
1703 static std::string findOperandDecoderMethod(TypedInit *TI) {
1704 std::string Decoder;
1706 RecordRecTy *Type = cast<RecordRecTy>(TI->getType());
1707 Record *TypeRecord = Type->getRecord();
1709 RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod");
1710 StringInit *String = DecoderString ?
1711 dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
1713 Decoder = String->getValue();
1714 if (!Decoder.empty())
1718 if (TypeRecord->isSubClassOf("RegisterOperand"))
1719 TypeRecord = TypeRecord->getValueAsDef("RegClass");
1721 if (TypeRecord->isSubClassOf("RegisterClass")) {
1722 Decoder = "Decode" + TypeRecord->getName().str() + "RegisterClass";
1723 } else if (TypeRecord->isSubClassOf("PointerLikeRegClass")) {
1724 Decoder = "DecodePointerLikeRegClass" +
1725 utostr(TypeRecord->getValueAsInt("RegClassKind"));
1731 static bool populateInstruction(CodeGenTarget &Target,
1732 const CodeGenInstruction &CGI, unsigned Opc,
1733 std::map<unsigned, std::vector<OperandInfo>> &Operands){
1734 const Record &Def = *CGI.TheDef;
1735 // If all the bit positions are not specified; do not decode this instruction.
1736 // We are bound to fail! For proper disassembly, the well-known encoding bits
1737 // of the instruction must be fully specified.
1739 BitsInit &Bits = getBitsField(Def, "Inst");
1740 if (Bits.allInComplete()) return false;
1742 std::vector<OperandInfo> InsnOperands;
1744 // If the instruction has specified a custom decoding hook, use that instead
1745 // of trying to auto-generate the decoder.
1746 StringRef InstDecoder = Def.getValueAsString("DecoderMethod");
1747 if (InstDecoder != "") {
1748 bool HasCompleteInstDecoder = Def.getValueAsBit("hasCompleteDecoder");
1749 InsnOperands.push_back(OperandInfo(InstDecoder, HasCompleteInstDecoder));
1750 Operands[Opc] = InsnOperands;
1754 // Generate a description of the operand of the instruction that we know
1755 // how to decode automatically.
1756 // FIXME: We'll need to have a way to manually override this as needed.
1758 // Gather the outputs/inputs of the instruction, so we can find their
1759 // positions in the encoding. This assumes for now that they appear in the
1760 // MCInst in the order that they're listed.
1761 std::vector<std::pair<Init*, StringRef>> InOutOperands;
1762 DagInit *Out = Def.getValueAsDag("OutOperandList");
1763 DagInit *In = Def.getValueAsDag("InOperandList");
1764 for (unsigned i = 0; i < Out->getNumArgs(); ++i)
1765 InOutOperands.push_back(std::make_pair(Out->getArg(i),
1766 Out->getArgNameStr(i)));
1767 for (unsigned i = 0; i < In->getNumArgs(); ++i)
1768 InOutOperands.push_back(std::make_pair(In->getArg(i),
1769 In->getArgNameStr(i)));
1771 // Search for tied operands, so that we can correctly instantiate
1772 // operands that are not explicitly represented in the encoding.
1773 std::map<std::string, std::string> TiedNames;
1774 for (unsigned i = 0; i < CGI.Operands.size(); ++i) {
1775 int tiedTo = CGI.Operands[i].getTiedRegister();
1777 std::pair<unsigned, unsigned> SO =
1778 CGI.Operands.getSubOperandNumber(tiedTo);
1779 TiedNames[InOutOperands[i].second] = InOutOperands[SO.first].second;
1780 TiedNames[InOutOperands[SO.first].second] = InOutOperands[i].second;
1784 std::map<std::string, std::vector<OperandInfo>> NumberedInsnOperands;
1785 std::set<std::string> NumberedInsnOperandsNoTie;
1786 if (Target.getInstructionSet()->
1787 getValueAsBit("decodePositionallyEncodedOperands")) {
1788 const std::vector<RecordVal> &Vals = Def.getValues();
1789 unsigned NumberedOp = 0;
1791 std::set<unsigned> NamedOpIndices;
1792 if (Target.getInstructionSet()->
1793 getValueAsBit("noNamedPositionallyEncodedOperands"))
1794 // Collect the set of operand indices that might correspond to named
1795 // operand, and skip these when assigning operands based on position.
1796 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1798 if (!CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx))
1801 NamedOpIndices.insert(OpIdx);
1804 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1805 // Ignore fixed fields in the record, we're looking for values like:
1806 // bits<5> RST = { ?, ?, ?, ?, ? };
1807 if (Vals[i].getPrefix() || Vals[i].getValue()->isComplete())
1810 // Determine if Vals[i] actually contributes to the Inst encoding.
1812 for (; bi < Bits.getNumBits(); ++bi) {
1813 VarInit *Var = nullptr;
1814 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
1816 Var = dyn_cast<VarInit>(BI->getBitVar());
1818 Var = dyn_cast<VarInit>(Bits.getBit(bi));
1820 if (Var && Var->getName() == Vals[i].getName())
1824 if (bi == Bits.getNumBits())
1827 // Skip variables that correspond to explicitly-named operands.
1829 if (CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx))
1832 // Get the bit range for this operand:
1833 unsigned bitStart = bi++, bitWidth = 1;
1834 for (; bi < Bits.getNumBits(); ++bi) {
1835 VarInit *Var = nullptr;
1836 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
1838 Var = dyn_cast<VarInit>(BI->getBitVar());
1840 Var = dyn_cast<VarInit>(Bits.getBit(bi));
1845 if (Var->getName() != Vals[i].getName())
1851 unsigned NumberOps = CGI.Operands.size();
1852 while (NumberedOp < NumberOps &&
1853 (CGI.Operands.isFlatOperandNotEmitted(NumberedOp) ||
1854 (!NamedOpIndices.empty() && NamedOpIndices.count(
1855 CGI.Operands.getSubOperandNumber(NumberedOp).first))))
1858 OpIdx = NumberedOp++;
1860 // OpIdx now holds the ordered operand number of Vals[i].
1861 std::pair<unsigned, unsigned> SO =
1862 CGI.Operands.getSubOperandNumber(OpIdx);
1863 const std::string &Name = CGI.Operands[SO.first].Name;
1865 DEBUG(dbgs() << "Numbered operand mapping for " << Def.getName() << ": " <<
1866 Name << "(" << SO.first << ", " << SO.second << ") => " <<
1867 Vals[i].getName() << "\n");
1869 std::string Decoder;
1870 Record *TypeRecord = CGI.Operands[SO.first].Rec;
1872 RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod");
1873 StringInit *String = DecoderString ?
1874 dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
1875 if (String && String->getValue() != "")
1876 Decoder = String->getValue();
1878 if (Decoder == "" &&
1879 CGI.Operands[SO.first].MIOperandInfo &&
1880 CGI.Operands[SO.first].MIOperandInfo->getNumArgs()) {
1881 Init *Arg = CGI.Operands[SO.first].MIOperandInfo->
1883 if (TypedInit *TI = cast<TypedInit>(Arg)) {
1884 RecordRecTy *Type = cast<RecordRecTy>(TI->getType());
1885 TypeRecord = Type->getRecord();
1890 if (TypeRecord->isSubClassOf("RegisterOperand"))
1891 TypeRecord = TypeRecord->getValueAsDef("RegClass");
1892 if (TypeRecord->isSubClassOf("RegisterClass")) {
1893 Decoder = "Decode" + TypeRecord->getName().str() + "RegisterClass";
1895 } else if (TypeRecord->isSubClassOf("PointerLikeRegClass")) {
1896 Decoder = "DecodePointerLikeRegClass" +
1897 utostr(TypeRecord->getValueAsInt("RegClassKind"));
1901 DecoderString = TypeRecord->getValue("DecoderMethod");
1902 String = DecoderString ?
1903 dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
1904 if (!isReg && String && String->getValue() != "")
1905 Decoder = String->getValue();
1907 RecordVal *HasCompleteDecoderVal =
1908 TypeRecord->getValue("hasCompleteDecoder");
1909 BitInit *HasCompleteDecoderBit = HasCompleteDecoderVal ?
1910 dyn_cast<BitInit>(HasCompleteDecoderVal->getValue()) : nullptr;
1911 bool HasCompleteDecoder = HasCompleteDecoderBit ?
1912 HasCompleteDecoderBit->getValue() : true;
1914 OperandInfo OpInfo(Decoder, HasCompleteDecoder);
1915 OpInfo.addField(bitStart, bitWidth, 0);
1917 NumberedInsnOperands[Name].push_back(OpInfo);
1919 // FIXME: For complex operands with custom decoders we can't handle tied
1920 // sub-operands automatically. Skip those here and assume that this is
1921 // fixed up elsewhere.
1922 if (CGI.Operands[SO.first].MIOperandInfo &&
1923 CGI.Operands[SO.first].MIOperandInfo->getNumArgs() > 1 &&
1924 String && String->getValue() != "")
1925 NumberedInsnOperandsNoTie.insert(Name);
1929 // For each operand, see if we can figure out where it is encoded.
1930 for (const auto &Op : InOutOperands) {
1931 if (!NumberedInsnOperands[Op.second].empty()) {
1932 InsnOperands.insert(InsnOperands.end(),
1933 NumberedInsnOperands[Op.second].begin(),
1934 NumberedInsnOperands[Op.second].end());
1937 if (!NumberedInsnOperands[TiedNames[Op.second]].empty()) {
1938 if (!NumberedInsnOperandsNoTie.count(TiedNames[Op.second])) {
1939 // Figure out to which (sub)operand we're tied.
1940 unsigned i = CGI.Operands.getOperandNamed(TiedNames[Op.second]);
1941 int tiedTo = CGI.Operands[i].getTiedRegister();
1943 i = CGI.Operands.getOperandNamed(Op.second);
1944 tiedTo = CGI.Operands[i].getTiedRegister();
1948 std::pair<unsigned, unsigned> SO =
1949 CGI.Operands.getSubOperandNumber(tiedTo);
1951 InsnOperands.push_back(NumberedInsnOperands[TiedNames[Op.second]]
1958 TypedInit *TI = cast<TypedInit>(Op.first);
1960 // At this point, we can locate the decoder field, but we need to know how
1961 // to interpret it. As a first step, require the target to provide
1962 // callbacks for decoding register classes.
1963 std::string Decoder = findOperandDecoderMethod(TI);
1964 Record *TypeRecord = cast<RecordRecTy>(TI->getType())->getRecord();
1966 RecordVal *HasCompleteDecoderVal =
1967 TypeRecord->getValue("hasCompleteDecoder");
1968 BitInit *HasCompleteDecoderBit = HasCompleteDecoderVal ?
1969 dyn_cast<BitInit>(HasCompleteDecoderVal->getValue()) : nullptr;
1970 bool HasCompleteDecoder = HasCompleteDecoderBit ?
1971 HasCompleteDecoderBit->getValue() : true;
1973 OperandInfo OpInfo(Decoder, HasCompleteDecoder);
1974 unsigned Base = ~0U;
1976 unsigned Offset = 0;
1978 for (unsigned bi = 0; bi < Bits.getNumBits(); ++bi) {
1979 VarInit *Var = nullptr;
1980 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
1982 Var = dyn_cast<VarInit>(BI->getBitVar());
1984 Var = dyn_cast<VarInit>(Bits.getBit(bi));
1988 OpInfo.addField(Base, Width, Offset);
1996 if (Var->getName() != Op.second &&
1997 Var->getName() != TiedNames[Op.second]) {
1999 OpInfo.addField(Base, Width, Offset);
2010 Offset = BI ? BI->getBitNum() : 0;
2011 } else if (BI && BI->getBitNum() != Offset + Width) {
2012 OpInfo.addField(Base, Width, Offset);
2015 Offset = BI->getBitNum();
2022 OpInfo.addField(Base, Width, Offset);
2024 if (OpInfo.numFields() > 0)
2025 InsnOperands.push_back(OpInfo);
2028 Operands[Opc] = InsnOperands;
2032 // Dumps the instruction encoding bits.
2033 dumpBits(errs(), Bits);
2037 // Dumps the list of operand info.
2038 for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) {
2039 const CGIOperandList::OperandInfo &Info = CGI.Operands[i];
2040 const std::string &OperandName = Info.Name;
2041 const Record &OperandDef = *Info.Rec;
2043 errs() << "\t" << OperandName << " (" << OperandDef.getName() << ")\n";
2051 // emitFieldFromInstruction - Emit the templated helper function
2052 // fieldFromInstruction().
2053 static void emitFieldFromInstruction(formatted_raw_ostream &OS) {
2054 OS << "// Helper function for extracting fields from encoded instructions.\n"
2055 << "template<typename InsnType>\n"
2056 << "static InsnType fieldFromInstruction(InsnType insn, unsigned startBit,\n"
2057 << " unsigned numBits) {\n"
2058 << " assert(startBit + numBits <= (sizeof(InsnType)*8) &&\n"
2059 << " \"Instruction field out of bounds!\");\n"
2060 << " InsnType fieldMask;\n"
2061 << " if (numBits == sizeof(InsnType)*8)\n"
2062 << " fieldMask = (InsnType)(-1LL);\n"
2064 << " fieldMask = (((InsnType)1 << numBits) - 1) << startBit;\n"
2065 << " return (insn & fieldMask) >> startBit;\n"
2069 // emitDecodeInstruction - Emit the templated helper function
2070 // decodeInstruction().
2071 static void emitDecodeInstruction(formatted_raw_ostream &OS) {
2072 OS << "template<typename InsnType>\n"
2073 << "static DecodeStatus decodeInstruction(const uint8_t DecodeTable[], MCInst &MI,\n"
2074 << " InsnType insn, uint64_t Address,\n"
2075 << " const void *DisAsm,\n"
2076 << " const MCSubtargetInfo &STI) {\n"
2077 << " const FeatureBitset& Bits = STI.getFeatureBits();\n"
2079 << " const uint8_t *Ptr = DecodeTable;\n"
2080 << " uint32_t CurFieldValue = 0;\n"
2081 << " DecodeStatus S = MCDisassembler::Success;\n"
2082 << " while (true) {\n"
2083 << " ptrdiff_t Loc = Ptr - DecodeTable;\n"
2084 << " switch (*Ptr) {\n"
2086 << " errs() << Loc << \": Unexpected decode table opcode!\\n\";\n"
2087 << " return MCDisassembler::Fail;\n"
2088 << " case MCD::OPC_ExtractField: {\n"
2089 << " unsigned Start = *++Ptr;\n"
2090 << " unsigned Len = *++Ptr;\n"
2092 << " CurFieldValue = fieldFromInstruction(insn, Start, Len);\n"
2093 << " DEBUG(dbgs() << Loc << \": OPC_ExtractField(\" << Start << \", \"\n"
2094 << " << Len << \"): \" << CurFieldValue << \"\\n\");\n"
2097 << " case MCD::OPC_FilterValue: {\n"
2098 << " // Decode the field value.\n"
2099 << " unsigned Len;\n"
2100 << " InsnType Val = decodeULEB128(++Ptr, &Len);\n"
2102 << " // NumToSkip is a plain 16-bit integer.\n"
2103 << " unsigned NumToSkip = *Ptr++;\n"
2104 << " NumToSkip |= (*Ptr++) << 8;\n"
2106 << " // Perform the filter operation.\n"
2107 << " if (Val != CurFieldValue)\n"
2108 << " Ptr += NumToSkip;\n"
2109 << " DEBUG(dbgs() << Loc << \": OPC_FilterValue(\" << Val << \", \" << NumToSkip\n"
2110 << " << \"): \" << ((Val != CurFieldValue) ? \"FAIL:\" : \"PASS:\")\n"
2111 << " << \" continuing at \" << (Ptr - DecodeTable) << \"\\n\");\n"
2115 << " case MCD::OPC_CheckField: {\n"
2116 << " unsigned Start = *++Ptr;\n"
2117 << " unsigned Len = *++Ptr;\n"
2118 << " InsnType FieldValue = fieldFromInstruction(insn, Start, Len);\n"
2119 << " // Decode the field value.\n"
2120 << " uint32_t ExpectedValue = decodeULEB128(++Ptr, &Len);\n"
2122 << " // NumToSkip is a plain 16-bit integer.\n"
2123 << " unsigned NumToSkip = *Ptr++;\n"
2124 << " NumToSkip |= (*Ptr++) << 8;\n"
2126 << " // If the actual and expected values don't match, skip.\n"
2127 << " if (ExpectedValue != FieldValue)\n"
2128 << " Ptr += NumToSkip;\n"
2129 << " DEBUG(dbgs() << Loc << \": OPC_CheckField(\" << Start << \", \"\n"
2130 << " << Len << \", \" << ExpectedValue << \", \" << NumToSkip\n"
2131 << " << \"): FieldValue = \" << FieldValue << \", ExpectedValue = \"\n"
2132 << " << ExpectedValue << \": \"\n"
2133 << " << ((ExpectedValue == FieldValue) ? \"PASS\\n\" : \"FAIL\\n\"));\n"
2136 << " case MCD::OPC_CheckPredicate: {\n"
2137 << " unsigned Len;\n"
2138 << " // Decode the Predicate Index value.\n"
2139 << " unsigned PIdx = decodeULEB128(++Ptr, &Len);\n"
2141 << " // NumToSkip is a plain 16-bit integer.\n"
2142 << " unsigned NumToSkip = *Ptr++;\n"
2143 << " NumToSkip |= (*Ptr++) << 8;\n"
2144 << " // Check the predicate.\n"
2146 << " if (!(Pred = checkDecoderPredicate(PIdx, Bits)))\n"
2147 << " Ptr += NumToSkip;\n"
2149 << " DEBUG(dbgs() << Loc << \": OPC_CheckPredicate(\" << PIdx << \"): \"\n"
2150 << " << (Pred ? \"PASS\\n\" : \"FAIL\\n\"));\n"
2154 << " case MCD::OPC_Decode: {\n"
2155 << " unsigned Len;\n"
2156 << " // Decode the Opcode value.\n"
2157 << " unsigned Opc = decodeULEB128(++Ptr, &Len);\n"
2159 << " unsigned DecodeIdx = decodeULEB128(Ptr, &Len);\n"
2163 << " MI.setOpcode(Opc);\n"
2164 << " bool DecodeComplete;\n"
2165 << " S = decodeToMCInst(S, DecodeIdx, insn, MI, Address, DisAsm, DecodeComplete);\n"
2166 << " assert(DecodeComplete);\n"
2168 << " DEBUG(dbgs() << Loc << \": OPC_Decode: opcode \" << Opc\n"
2169 << " << \", using decoder \" << DecodeIdx << \": \"\n"
2170 << " << (S != MCDisassembler::Fail ? \"PASS\" : \"FAIL\") << \"\\n\");\n"
2173 << " case MCD::OPC_TryDecode: {\n"
2174 << " unsigned Len;\n"
2175 << " // Decode the Opcode value.\n"
2176 << " unsigned Opc = decodeULEB128(++Ptr, &Len);\n"
2178 << " unsigned DecodeIdx = decodeULEB128(Ptr, &Len);\n"
2180 << " // NumToSkip is a plain 16-bit integer.\n"
2181 << " unsigned NumToSkip = *Ptr++;\n"
2182 << " NumToSkip |= (*Ptr++) << 8;\n"
2184 << " // Perform the decode operation.\n"
2185 << " MCInst TmpMI;\n"
2186 << " TmpMI.setOpcode(Opc);\n"
2187 << " bool DecodeComplete;\n"
2188 << " S = decodeToMCInst(S, DecodeIdx, insn, TmpMI, Address, DisAsm, DecodeComplete);\n"
2189 << " DEBUG(dbgs() << Loc << \": OPC_TryDecode: opcode \" << Opc\n"
2190 << " << \", using decoder \" << DecodeIdx << \": \");\n"
2192 << " if (DecodeComplete) {\n"
2193 << " // Decoding complete.\n"
2194 << " DEBUG(dbgs() << (S != MCDisassembler::Fail ? \"PASS\" : \"FAIL\") << \"\\n\");\n"
2198 << " assert(S == MCDisassembler::Fail);\n"
2199 << " // If the decoding was incomplete, skip.\n"
2200 << " Ptr += NumToSkip;\n"
2201 << " DEBUG(dbgs() << \"FAIL: continuing at \" << (Ptr - DecodeTable) << \"\\n\");\n"
2202 << " // Reset decode status. This also drops a SoftFail status that could be\n"
2203 << " // set before the decode attempt.\n"
2204 << " S = MCDisassembler::Success;\n"
2208 << " case MCD::OPC_SoftFail: {\n"
2209 << " // Decode the mask values.\n"
2210 << " unsigned Len;\n"
2211 << " InsnType PositiveMask = decodeULEB128(++Ptr, &Len);\n"
2213 << " InsnType NegativeMask = decodeULEB128(Ptr, &Len);\n"
2215 << " bool Fail = (insn & PositiveMask) || (~insn & NegativeMask);\n"
2217 << " S = MCDisassembler::SoftFail;\n"
2218 << " DEBUG(dbgs() << Loc << \": OPC_SoftFail: \" << (Fail ? \"FAIL\\n\":\"PASS\\n\"));\n"
2221 << " case MCD::OPC_Fail: {\n"
2222 << " DEBUG(dbgs() << Loc << \": OPC_Fail\\n\");\n"
2223 << " return MCDisassembler::Fail;\n"
2227 << " llvm_unreachable(\"bogosity detected in disassembler state machine!\");\n"
2231 // Emits disassembler code for instruction decoding.
2232 void FixedLenDecoderEmitter::run(raw_ostream &o) {
2233 formatted_raw_ostream OS(o);
2234 OS << "#include \"llvm/MC/MCInst.h\"\n";
2235 OS << "#include \"llvm/Support/Debug.h\"\n";
2236 OS << "#include \"llvm/Support/DataTypes.h\"\n";
2237 OS << "#include \"llvm/Support/LEB128.h\"\n";
2238 OS << "#include \"llvm/Support/raw_ostream.h\"\n";
2239 OS << "#include <assert.h>\n";
2241 OS << "namespace llvm {\n\n";
2243 emitFieldFromInstruction(OS);
2245 Target.reverseBitsForLittleEndianEncoding();
2247 // Parameterize the decoders based on namespace and instruction width.
2248 NumberedInstructions = Target.getInstructionsByEnumValue();
2249 std::map<std::pair<std::string, unsigned>,
2250 std::vector<unsigned>> OpcMap;
2251 std::map<unsigned, std::vector<OperandInfo>> Operands;
2253 for (unsigned i = 0; i < NumberedInstructions.size(); ++i) {
2254 const CodeGenInstruction *Inst = NumberedInstructions[i];
2255 const Record *Def = Inst->TheDef;
2256 unsigned Size = Def->getValueAsInt("Size");
2257 if (Def->getValueAsString("Namespace") == "TargetOpcode" ||
2258 Def->getValueAsBit("isPseudo") ||
2259 Def->getValueAsBit("isAsmParserOnly") ||
2260 Def->getValueAsBit("isCodeGenOnly"))
2263 StringRef DecoderNamespace = Def->getValueAsString("DecoderNamespace");
2266 if (populateInstruction(Target, *Inst, i, Operands)) {
2267 OpcMap[std::make_pair(DecoderNamespace, Size)].push_back(i);
2272 DecoderTableInfo TableInfo;
2273 for (const auto &Opc : OpcMap) {
2274 // Emit the decoder for this namespace+width combination.
2275 FilterChooser FC(NumberedInstructions, Opc.second, Operands,
2276 8*Opc.first.second, this);
2278 // The decode table is cleared for each top level decoder function. The
2279 // predicates and decoders themselves, however, are shared across all
2280 // decoders to give more opportunities for uniqueing.
2281 TableInfo.Table.clear();
2282 TableInfo.FixupStack.clear();
2283 TableInfo.Table.reserve(16384);
2284 TableInfo.FixupStack.emplace_back();
2285 FC.emitTableEntries(TableInfo);
2286 // Any NumToSkip fixups in the top level scope can resolve to the
2287 // OPC_Fail at the end of the table.
2288 assert(TableInfo.FixupStack.size() == 1 && "fixup stack phasing error!");
2289 // Resolve any NumToSkip fixups in the current scope.
2290 resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),
2291 TableInfo.Table.size());
2292 TableInfo.FixupStack.clear();
2294 TableInfo.Table.push_back(MCD::OPC_Fail);
2296 // Print the table to the output stream.
2297 emitTable(OS, TableInfo.Table, 0, FC.getBitWidth(), Opc.first.first);
2301 // Emit the predicate function.
2302 emitPredicateFunction(OS, TableInfo.Predicates, 0);
2304 // Emit the decoder function.
2305 emitDecoderFunction(OS, TableInfo.Decoders, 0);
2307 // Emit the main entry point for the decoder, decodeInstruction().
2308 emitDecodeInstruction(OS);
2310 OS << "\n} // End llvm namespace\n";
2315 void EmitFixedLenDecoder(RecordKeeper &RK, raw_ostream &OS,
2316 const std::string &PredicateNamespace,
2317 const std::string &GPrefix,
2318 const std::string &GPostfix, const std::string &ROK,
2319 const std::string &RFail, const std::string &L) {
2320 FixedLenDecoderEmitter(RK, PredicateNamespace, GPrefix, GPostfix,
2321 ROK, RFail, L).run(OS);
2324 } // end namespace llvm