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 #define DEBUG_TYPE "decoder-emitter"
17 #include "CodeGenTarget.h"
18 #include "llvm/ADT/APInt.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/ADT/Twine.h"
23 #include "llvm/MC/MCFixedLenDisassembler.h"
24 #include "llvm/Support/DataTypes.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/FormattedStream.h"
27 #include "llvm/Support/LEB128.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/TableGen/Error.h"
30 #include "llvm/TableGen/Record.h"
38 struct EncodingField {
39 unsigned Base, Width, Offset;
40 EncodingField(unsigned B, unsigned W, unsigned O)
41 : Base(B), Width(W), Offset(O) { }
45 std::vector<EncodingField> Fields;
48 OperandInfo(std::string D)
51 void addField(unsigned Base, unsigned Width, unsigned Offset) {
52 Fields.push_back(EncodingField(Base, Width, Offset));
55 unsigned numFields() const { return Fields.size(); }
57 typedef std::vector<EncodingField>::const_iterator const_iterator;
59 const_iterator begin() const { return Fields.begin(); }
60 const_iterator end() const { return Fields.end(); }
63 typedef std::vector<uint8_t> DecoderTable;
64 typedef uint32_t DecoderFixup;
65 typedef std::vector<DecoderFixup> FixupList;
66 typedef std::vector<FixupList> FixupScopeList;
67 typedef SetVector<std::string> PredicateSet;
68 typedef SetVector<std::string> DecoderSet;
69 struct DecoderTableInfo {
71 FixupScopeList FixupStack;
72 PredicateSet Predicates;
76 } // End anonymous namespace
79 class FixedLenDecoderEmitter {
80 const std::vector<const CodeGenInstruction*> *NumberedInstructions;
83 // Defaults preserved here for documentation, even though they aren't
84 // strictly necessary given the way that this is currently being called.
85 FixedLenDecoderEmitter(RecordKeeper &R,
86 std::string PredicateNamespace,
87 std::string GPrefix = "if (",
88 std::string GPostfix = " == MCDisassembler::Fail)"
89 " return MCDisassembler::Fail;",
90 std::string ROK = "MCDisassembler::Success",
91 std::string RFail = "MCDisassembler::Fail",
94 PredicateNamespace(PredicateNamespace),
95 GuardPrefix(GPrefix), GuardPostfix(GPostfix),
96 ReturnOK(ROK), ReturnFail(RFail), Locals(L) {}
98 // Emit the decoder state machine table.
99 void emitTable(formatted_raw_ostream &o, DecoderTable &Table,
100 unsigned Indentation, unsigned BitWidth,
101 StringRef Namespace) const;
102 void emitPredicateFunction(formatted_raw_ostream &OS,
103 PredicateSet &Predicates,
104 unsigned Indentation) const;
105 void emitDecoderFunction(formatted_raw_ostream &OS,
106 DecoderSet &Decoders,
107 unsigned Indentation) const;
109 // run - Output the code emitter
110 void run(raw_ostream &o);
113 CodeGenTarget Target;
115 std::string PredicateNamespace;
116 std::string GuardPrefix, GuardPostfix;
117 std::string ReturnOK, ReturnFail;
120 } // End anonymous namespace
122 // The set (BIT_TRUE, BIT_FALSE, BIT_UNSET) represents a ternary logic system
125 // BIT_UNFILTERED is used as the init value for a filter position. It is used
126 // only for filter processings.
131 BIT_UNFILTERED // unfiltered
134 static bool ValueSet(bit_value_t V) {
135 return (V == BIT_TRUE || V == BIT_FALSE);
137 static bool ValueNotSet(bit_value_t V) {
138 return (V == BIT_UNSET);
140 static int Value(bit_value_t V) {
141 return ValueNotSet(V) ? -1 : (V == BIT_FALSE ? 0 : 1);
143 static bit_value_t bitFromBits(const BitsInit &bits, unsigned index) {
144 if (BitInit *bit = dyn_cast<BitInit>(bits.getBit(index)))
145 return bit->getValue() ? BIT_TRUE : BIT_FALSE;
147 // The bit is uninitialized.
150 // Prints the bit value for each position.
151 static void dumpBits(raw_ostream &o, const BitsInit &bits) {
152 for (unsigned index = bits.getNumBits(); index > 0; --index) {
153 switch (bitFromBits(bits, index - 1)) {
164 llvm_unreachable("unexpected return value from bitFromBits");
169 static BitsInit &getBitsField(const Record &def, const char *str) {
170 BitsInit *bits = def.getValueAsBitsInit(str);
174 // Forward declaration.
177 } // End anonymous namespace
179 // Representation of the instruction to work on.
180 typedef std::vector<bit_value_t> insn_t;
182 /// Filter - Filter works with FilterChooser to produce the decoding tree for
185 /// It is useful to think of a Filter as governing the switch stmts of the
186 /// decoding tree in a certain level. Each case stmt delegates to an inferior
187 /// FilterChooser to decide what further decoding logic to employ, or in another
188 /// words, what other remaining bits to look at. The FilterChooser eventually
189 /// chooses a best Filter to do its job.
191 /// This recursive scheme ends when the number of Opcodes assigned to the
192 /// FilterChooser becomes 1 or if there is a conflict. A conflict happens when
193 /// the Filter/FilterChooser combo does not know how to distinguish among the
194 /// Opcodes assigned.
196 /// An example of a conflict is
199 /// 111101000.00........00010000....
200 /// 111101000.00........0001........
201 /// 1111010...00........0001........
202 /// 1111010...00....................
203 /// 1111010.........................
204 /// 1111............................
205 /// ................................
206 /// VST4q8a 111101000_00________00010000____
207 /// VST4q8b 111101000_00________00010000____
209 /// The Debug output shows the path that the decoding tree follows to reach the
210 /// the conclusion that there is a conflict. VST4q8a is a vst4 to double-spaced
211 /// even registers, while VST4q8b is a vst4 to double-spaced odd regsisters.
213 /// The encoding info in the .td files does not specify this meta information,
214 /// which could have been used by the decoder to resolve the conflict. The
215 /// decoder could try to decode the even/odd register numbering and assign to
216 /// VST4q8a or VST4q8b, but for the time being, the decoder chooses the "a"
217 /// version and return the Opcode since the two have the same Asm format string.
221 const FilterChooser *Owner;// points to the FilterChooser who owns this filter
222 unsigned StartBit; // the starting bit position
223 unsigned NumBits; // number of bits to filter
224 bool Mixed; // a mixed region contains both set and unset bits
226 // Map of well-known segment value to the set of uid's with that value.
227 std::map<uint64_t, std::vector<unsigned> > FilteredInstructions;
229 // Set of uid's with non-constant segment values.
230 std::vector<unsigned> VariableInstructions;
232 // Map of well-known segment value to its delegate.
233 std::map<unsigned, const FilterChooser*> FilterChooserMap;
235 // Number of instructions which fall under FilteredInstructions category.
236 unsigned NumFiltered;
238 // Keeps track of the last opcode in the filtered bucket.
239 unsigned LastOpcFiltered;
242 unsigned getNumFiltered() const { return NumFiltered; }
243 unsigned getSingletonOpc() const {
244 assert(NumFiltered == 1);
245 return LastOpcFiltered;
247 // Return the filter chooser for the group of instructions without constant
249 const FilterChooser &getVariableFC() const {
250 assert(NumFiltered == 1);
251 assert(FilterChooserMap.size() == 1);
252 return *(FilterChooserMap.find((unsigned)-1)->second);
255 Filter(const Filter &f);
256 Filter(FilterChooser &owner, unsigned startBit, unsigned numBits, bool mixed);
260 // Divides the decoding task into sub tasks and delegates them to the
261 // inferior FilterChooser's.
263 // A special case arises when there's only one entry in the filtered
264 // instructions. In order to unambiguously decode the singleton, we need to
265 // match the remaining undecoded encoding bits against the singleton.
268 // Emit table entries to decode instructions given a segment or segments of
270 void emitTableEntry(DecoderTableInfo &TableInfo) const;
272 // Returns the number of fanout produced by the filter. More fanout implies
273 // the filter distinguishes more categories of instructions.
274 unsigned usefulness() const;
275 }; // End of class Filter
276 } // End anonymous namespace
278 // These are states of our finite state machines used in FilterChooser's
279 // filterProcessor() which produces the filter candidates to use.
288 /// FilterChooser - FilterChooser chooses the best filter among a set of Filters
289 /// in order to perform the decoding of instructions at the current level.
291 /// Decoding proceeds from the top down. Based on the well-known encoding bits
292 /// of instructions available, FilterChooser builds up the possible Filters that
293 /// can further the task of decoding by distinguishing among the remaining
294 /// candidate instructions.
296 /// Once a filter has been chosen, it is called upon to divide the decoding task
297 /// into sub-tasks and delegates them to its inferior FilterChoosers for further
300 /// It is useful to think of a Filter as governing the switch stmts of the
301 /// decoding tree. And each case is delegated to an inferior FilterChooser to
302 /// decide what further remaining bits to look at.
304 class FilterChooser {
308 // Vector of codegen instructions to choose our filter.
309 const std::vector<const CodeGenInstruction*> &AllInstructions;
311 // Vector of uid's for this filter chooser to work on.
312 const std::vector<unsigned> &Opcodes;
314 // Lookup table for the operand decoding of instructions.
315 const std::map<unsigned, std::vector<OperandInfo> > &Operands;
317 // Vector of candidate filters.
318 std::vector<Filter> Filters;
320 // Array of bit values passed down from our parent.
321 // Set to all BIT_UNFILTERED's for Parent == NULL.
322 std::vector<bit_value_t> FilterBitValues;
324 // Links to the FilterChooser above us in the decoding tree.
325 const FilterChooser *Parent;
327 // Index of the best filter from Filters.
330 // Width of instructions
334 const FixedLenDecoderEmitter *Emitter;
337 FilterChooser(const FilterChooser &FC)
338 : AllInstructions(FC.AllInstructions), Opcodes(FC.Opcodes),
339 Operands(FC.Operands), Filters(FC.Filters),
340 FilterBitValues(FC.FilterBitValues), Parent(FC.Parent),
341 BestIndex(FC.BestIndex), BitWidth(FC.BitWidth),
342 Emitter(FC.Emitter) { }
344 FilterChooser(const std::vector<const CodeGenInstruction*> &Insts,
345 const std::vector<unsigned> &IDs,
346 const std::map<unsigned, std::vector<OperandInfo> > &Ops,
348 const FixedLenDecoderEmitter *E)
349 : AllInstructions(Insts), Opcodes(IDs), Operands(Ops), Filters(),
350 Parent(NULL), BestIndex(-1), BitWidth(BW), Emitter(E) {
351 for (unsigned i = 0; i < BitWidth; ++i)
352 FilterBitValues.push_back(BIT_UNFILTERED);
357 FilterChooser(const std::vector<const CodeGenInstruction*> &Insts,
358 const std::vector<unsigned> &IDs,
359 const std::map<unsigned, std::vector<OperandInfo> > &Ops,
360 const std::vector<bit_value_t> &ParentFilterBitValues,
361 const FilterChooser &parent)
362 : AllInstructions(Insts), Opcodes(IDs), Operands(Ops),
363 Filters(), FilterBitValues(ParentFilterBitValues),
364 Parent(&parent), BestIndex(-1), BitWidth(parent.BitWidth),
365 Emitter(parent.Emitter) {
369 unsigned getBitWidth() const { return BitWidth; }
372 // Populates the insn given the uid.
373 void insnWithID(insn_t &Insn, unsigned Opcode) const {
374 BitsInit &Bits = getBitsField(*AllInstructions[Opcode]->TheDef, "Inst");
376 // We may have a SoftFail bitmask, which specifies a mask where an encoding
377 // may differ from the value in "Inst" and yet still be valid, but the
378 // disassembler should return SoftFail instead of Success.
380 // This is used for marking UNPREDICTABLE instructions in the ARM world.
382 AllInstructions[Opcode]->TheDef->getValueAsBitsInit("SoftFail");
384 for (unsigned i = 0; i < BitWidth; ++i) {
385 if (SFBits && bitFromBits(*SFBits, i) == BIT_TRUE)
386 Insn.push_back(BIT_UNSET);
388 Insn.push_back(bitFromBits(Bits, i));
392 // Returns the record name.
393 const std::string &nameWithID(unsigned Opcode) const {
394 return AllInstructions[Opcode]->TheDef->getName();
397 // Populates the field of the insn given the start position and the number of
398 // consecutive bits to scan for.
400 // Returns false if there exists any uninitialized bit value in the range.
401 // Returns true, otherwise.
402 bool fieldFromInsn(uint64_t &Field, insn_t &Insn, unsigned StartBit,
403 unsigned NumBits) const;
405 /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
406 /// filter array as a series of chars.
407 void dumpFilterArray(raw_ostream &o,
408 const std::vector<bit_value_t> & filter) const;
410 /// dumpStack - dumpStack traverses the filter chooser chain and calls
411 /// dumpFilterArray on each filter chooser up to the top level one.
412 void dumpStack(raw_ostream &o, const char *prefix) const;
414 Filter &bestFilter() {
415 assert(BestIndex != -1 && "BestIndex not set");
416 return Filters[BestIndex];
419 // Called from Filter::recurse() when singleton exists. For debug purpose.
420 void SingletonExists(unsigned Opc) const;
422 bool PositionFiltered(unsigned i) const {
423 return ValueSet(FilterBitValues[i]);
426 // Calculates the island(s) needed to decode the instruction.
427 // This returns a lit of undecoded bits of an instructions, for example,
428 // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
429 // decoded bits in order to verify that the instruction matches the Opcode.
430 unsigned getIslands(std::vector<unsigned> &StartBits,
431 std::vector<unsigned> &EndBits,
432 std::vector<uint64_t> &FieldVals,
433 const insn_t &Insn) const;
435 // Emits code to check the Predicates member of an instruction are true.
436 // Returns true if predicate matches were emitted, false otherwise.
437 bool emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
440 bool doesOpcodeNeedPredicate(unsigned Opc) const;
441 unsigned getPredicateIndex(DecoderTableInfo &TableInfo, StringRef P) const;
442 void emitPredicateTableEntry(DecoderTableInfo &TableInfo,
445 void emitSoftFailTableEntry(DecoderTableInfo &TableInfo,
448 // Emits table entries to decode the singleton.
449 void emitSingletonTableEntry(DecoderTableInfo &TableInfo,
452 // Emits code to decode the singleton, and then to decode the rest.
453 void emitSingletonTableEntry(DecoderTableInfo &TableInfo,
454 const Filter &Best) const;
456 void emitBinaryParser(raw_ostream &o, unsigned &Indentation,
457 const OperandInfo &OpInfo) const;
459 void emitDecoder(raw_ostream &OS, unsigned Indentation, unsigned Opc) const;
460 unsigned getDecoderIndex(DecoderSet &Decoders, unsigned Opc) const;
462 // Assign a single filter and run with it.
463 void runSingleFilter(unsigned startBit, unsigned numBit, bool mixed);
465 // reportRegion is a helper function for filterProcessor to mark a region as
466 // eligible for use as a filter region.
467 void reportRegion(bitAttr_t RA, unsigned StartBit, unsigned BitIndex,
470 // FilterProcessor scans the well-known encoding bits of the instructions and
471 // builds up a list of candidate filters. It chooses the best filter and
472 // recursively descends down the decoding tree.
473 bool filterProcessor(bool AllowMixed, bool Greedy = true);
475 // Decides on the best configuration of filter(s) to use in order to decode
476 // the instructions. A conflict of instructions may occur, in which case we
477 // dump the conflict set to the standard error.
481 // emitTableEntries - Emit state machine entries to decode our share of
483 void emitTableEntries(DecoderTableInfo &TableInfo) const;
485 } // End anonymous namespace
487 ///////////////////////////
489 // Filter Implementation //
491 ///////////////////////////
493 Filter::Filter(const Filter &f)
494 : Owner(f.Owner), StartBit(f.StartBit), NumBits(f.NumBits), Mixed(f.Mixed),
495 FilteredInstructions(f.FilteredInstructions),
496 VariableInstructions(f.VariableInstructions),
497 FilterChooserMap(f.FilterChooserMap), NumFiltered(f.NumFiltered),
498 LastOpcFiltered(f.LastOpcFiltered) {
501 Filter::Filter(FilterChooser &owner, unsigned startBit, unsigned numBits,
503 : Owner(&owner), StartBit(startBit), NumBits(numBits), Mixed(mixed) {
504 assert(StartBit + NumBits - 1 < Owner->BitWidth);
509 for (unsigned i = 0, e = Owner->Opcodes.size(); i != e; ++i) {
512 // Populates the insn given the uid.
513 Owner->insnWithID(Insn, Owner->Opcodes[i]);
516 // Scans the segment for possibly well-specified encoding bits.
517 bool ok = Owner->fieldFromInsn(Field, Insn, StartBit, NumBits);
520 // The encoding bits are well-known. Lets add the uid of the
521 // instruction into the bucket keyed off the constant field value.
522 LastOpcFiltered = Owner->Opcodes[i];
523 FilteredInstructions[Field].push_back(LastOpcFiltered);
526 // Some of the encoding bit(s) are unspecified. This contributes to
527 // one additional member of "Variable" instructions.
528 VariableInstructions.push_back(Owner->Opcodes[i]);
532 assert((FilteredInstructions.size() + VariableInstructions.size() > 0)
533 && "Filter returns no instruction categories");
537 std::map<unsigned, const FilterChooser*>::iterator filterIterator;
538 for (filterIterator = FilterChooserMap.begin();
539 filterIterator != FilterChooserMap.end();
541 delete filterIterator->second;
545 // Divides the decoding task into sub tasks and delegates them to the
546 // inferior FilterChooser's.
548 // A special case arises when there's only one entry in the filtered
549 // instructions. In order to unambiguously decode the singleton, we need to
550 // match the remaining undecoded encoding bits against the singleton.
551 void Filter::recurse() {
552 std::map<uint64_t, std::vector<unsigned> >::const_iterator mapIterator;
554 // Starts by inheriting our parent filter chooser's filter bit values.
555 std::vector<bit_value_t> BitValueArray(Owner->FilterBitValues);
557 if (VariableInstructions.size()) {
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(std::pair<unsigned, const FilterChooser*>(
566 new FilterChooser(Owner->AllInstructions,
567 VariableInstructions,
574 // No need to recurse for a singleton filtered instruction.
575 // See also Filter::emit*().
576 if (getNumFiltered() == 1) {
577 //Owner->SingletonExists(LastOpcFiltered);
578 assert(FilterChooserMap.size() == 1);
582 // Otherwise, create sub choosers.
583 for (mapIterator = FilteredInstructions.begin();
584 mapIterator != FilteredInstructions.end();
587 // Marks all the segment positions with either BIT_TRUE or BIT_FALSE.
588 for (unsigned bitIndex = 0; bitIndex < NumBits; ++bitIndex) {
589 if (mapIterator->first & (1ULL << bitIndex))
590 BitValueArray[StartBit + bitIndex] = BIT_TRUE;
592 BitValueArray[StartBit + bitIndex] = BIT_FALSE;
595 // Delegates to an inferior filter chooser for further processing on this
596 // category of instructions.
597 FilterChooserMap.insert(std::pair<unsigned, const FilterChooser*>(
599 new FilterChooser(Owner->AllInstructions,
608 static void resolveTableFixups(DecoderTable &Table, const FixupList &Fixups,
610 // Any NumToSkip fixups in the current scope can resolve to the
612 for (FixupList::const_reverse_iterator I = Fixups.rbegin(),
615 // Calculate the distance from the byte following the fixup entry byte
616 // to the destination. The Target is calculated from after the 16-bit
617 // NumToSkip entry itself, so subtract two from the displacement here
618 // to account for that.
619 uint32_t FixupIdx = *I;
620 uint32_t Delta = DestIdx - FixupIdx - 2;
621 // Our NumToSkip entries are 16-bits. Make sure our table isn't too
623 assert(Delta < 65536U && "disassembler decoding table too large!");
624 Table[FixupIdx] = (uint8_t)Delta;
625 Table[FixupIdx + 1] = (uint8_t)(Delta >> 8);
629 // Emit table entries to decode instructions given a segment or segments
631 void Filter::emitTableEntry(DecoderTableInfo &TableInfo) const {
632 TableInfo.Table.push_back(MCD::OPC_ExtractField);
633 TableInfo.Table.push_back(StartBit);
634 TableInfo.Table.push_back(NumBits);
636 // A new filter entry begins a new scope for fixup resolution.
637 TableInfo.FixupStack.push_back(FixupList());
639 std::map<unsigned, const FilterChooser*>::const_iterator filterIterator;
641 DecoderTable &Table = TableInfo.Table;
643 size_t PrevFilter = 0;
644 bool HasFallthrough = false;
645 for (filterIterator = FilterChooserMap.begin();
646 filterIterator != FilterChooserMap.end();
648 // Field value -1 implies a non-empty set of variable instructions.
649 // See also recurse().
650 if (filterIterator->first == (unsigned)-1) {
651 HasFallthrough = true;
653 // Each scope should always have at least one filter value to check
655 assert(PrevFilter != 0 && "empty filter set!");
656 FixupList &CurScope = TableInfo.FixupStack.back();
657 // Resolve any NumToSkip fixups in the current scope.
658 resolveTableFixups(Table, CurScope, Table.size());
660 PrevFilter = 0; // Don't re-process the filter's fallthrough.
662 Table.push_back(MCD::OPC_FilterValue);
663 // Encode and emit the value to filter against.
665 unsigned Len = encodeULEB128(filterIterator->first, Buffer);
666 Table.insert(Table.end(), Buffer, Buffer + Len);
667 // Reserve space for the NumToSkip entry. We'll backpatch the value
669 PrevFilter = Table.size();
674 // We arrive at a category of instructions with the same segment value.
675 // Now delegate to the sub filter chooser for further decodings.
676 // The case may fallthrough, which happens if the remaining well-known
677 // encoding bits do not match exactly.
678 filterIterator->second->emitTableEntries(TableInfo);
680 // Now that we've emitted the body of the handler, update the NumToSkip
681 // of the filter itself to be able to skip forward when false. Subtract
682 // two as to account for the width of the NumToSkip field itself.
684 uint32_t NumToSkip = Table.size() - PrevFilter - 2;
685 assert(NumToSkip < 65536U && "disassembler decoding table too large!");
686 Table[PrevFilter] = (uint8_t)NumToSkip;
687 Table[PrevFilter + 1] = (uint8_t)(NumToSkip >> 8);
691 // Any remaining unresolved fixups bubble up to the parent fixup scope.
692 assert(TableInfo.FixupStack.size() > 1 && "fixup stack underflow!");
693 FixupScopeList::iterator Source = TableInfo.FixupStack.end() - 1;
694 FixupScopeList::iterator Dest = Source - 1;
695 Dest->insert(Dest->end(), Source->begin(), Source->end());
696 TableInfo.FixupStack.pop_back();
698 // If there is no fallthrough, then the final filter should get fixed
699 // up according to the enclosing scope rather than the current position.
701 TableInfo.FixupStack.back().push_back(PrevFilter);
704 // Returns the number of fanout produced by the filter. More fanout implies
705 // the filter distinguishes more categories of instructions.
706 unsigned Filter::usefulness() const {
707 if (VariableInstructions.size())
708 return FilteredInstructions.size();
710 return FilteredInstructions.size() + 1;
713 //////////////////////////////////
715 // Filterchooser Implementation //
717 //////////////////////////////////
719 // Emit the decoder state machine table.
720 void FixedLenDecoderEmitter::emitTable(formatted_raw_ostream &OS,
722 unsigned Indentation,
724 StringRef Namespace) const {
725 OS.indent(Indentation) << "static const uint8_t DecoderTable" << Namespace
726 << BitWidth << "[] = {\n";
730 // FIXME: We may be able to use the NumToSkip values to recover
731 // appropriate indentation levels.
732 DecoderTable::const_iterator I = Table.begin();
733 DecoderTable::const_iterator E = Table.end();
735 assert (I < E && "incomplete decode table entry!");
737 uint64_t Pos = I - Table.begin();
738 OS << "/* " << Pos << " */";
743 PrintFatalError("invalid decode table opcode");
744 case MCD::OPC_ExtractField: {
746 unsigned Start = *I++;
748 OS.indent(Indentation) << "MCD::OPC_ExtractField, " << Start << ", "
749 << Len << ", // Inst{";
751 OS << (Start + Len - 1) << "-";
752 OS << Start << "} ...\n";
755 case MCD::OPC_FilterValue: {
757 OS.indent(Indentation) << "MCD::OPC_FilterValue, ";
758 // The filter value is ULEB128 encoded.
760 OS << utostr(*I++) << ", ";
761 OS << utostr(*I++) << ", ";
763 // 16-bit numtoskip value.
765 uint32_t NumToSkip = Byte;
766 OS << utostr(Byte) << ", ";
768 OS << utostr(Byte) << ", ";
769 NumToSkip |= Byte << 8;
770 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
773 case MCD::OPC_CheckField: {
775 unsigned Start = *I++;
777 OS.indent(Indentation) << "MCD::OPC_CheckField, " << Start << ", "
778 << Len << ", ";// << Val << ", " << NumToSkip << ",\n";
779 // ULEB128 encoded field value.
780 for (; *I >= 128; ++I)
781 OS << utostr(*I) << ", ";
782 OS << utostr(*I++) << ", ";
783 // 16-bit numtoskip value.
785 uint32_t NumToSkip = Byte;
786 OS << utostr(Byte) << ", ";
788 OS << utostr(Byte) << ", ";
789 NumToSkip |= Byte << 8;
790 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
793 case MCD::OPC_CheckPredicate: {
795 OS.indent(Indentation) << "MCD::OPC_CheckPredicate, ";
796 for (; *I >= 128; ++I)
797 OS << utostr(*I) << ", ";
798 OS << utostr(*I++) << ", ";
800 // 16-bit numtoskip value.
802 uint32_t NumToSkip = Byte;
803 OS << utostr(Byte) << ", ";
805 OS << utostr(Byte) << ", ";
806 NumToSkip |= Byte << 8;
807 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
810 case MCD::OPC_Decode: {
812 // Extract the ULEB128 encoded Opcode to a buffer.
813 uint8_t Buffer[8], *p = Buffer;
814 while ((*p++ = *I++) >= 128)
815 assert((p - Buffer) <= (ptrdiff_t)sizeof(Buffer)
816 && "ULEB128 value too large!");
817 // Decode the Opcode value.
818 unsigned Opc = decodeULEB128(Buffer);
819 OS.indent(Indentation) << "MCD::OPC_Decode, ";
820 for (p = Buffer; *p >= 128; ++p)
821 OS << utostr(*p) << ", ";
822 OS << utostr(*p) << ", ";
825 for (; *I >= 128; ++I)
826 OS << utostr(*I) << ", ";
827 OS << utostr(*I++) << ", ";
830 << NumberedInstructions->at(Opc)->TheDef->getName() << "\n";
833 case MCD::OPC_SoftFail: {
835 OS.indent(Indentation) << "MCD::OPC_SoftFail";
840 OS << ", " << utostr(*I);
841 Value += (*I & 0x7f) << Shift;
843 } while (*I++ >= 128);
845 OS << " /* 0x" << utohexstr(Value) << " */";
850 OS << ", " << utostr(*I);
851 Value += (*I & 0x7f) << Shift;
853 } while (*I++ >= 128);
855 OS << " /* 0x" << utohexstr(Value) << " */";
859 case MCD::OPC_Fail: {
861 OS.indent(Indentation) << "MCD::OPC_Fail,\n";
866 OS.indent(Indentation) << "0\n";
870 OS.indent(Indentation) << "};\n\n";
873 void FixedLenDecoderEmitter::
874 emitPredicateFunction(formatted_raw_ostream &OS, PredicateSet &Predicates,
875 unsigned Indentation) const {
876 // The predicate function is just a big switch statement based on the
877 // input predicate index.
878 OS.indent(Indentation) << "static bool checkDecoderPredicate(unsigned Idx, "
879 << "uint64_t Bits) {\n";
881 if (!Predicates.empty()) {
882 OS.indent(Indentation) << "switch (Idx) {\n";
883 OS.indent(Indentation) << "default: llvm_unreachable(\"Invalid index!\");\n";
885 for (PredicateSet::const_iterator I = Predicates.begin(), E = Predicates.end();
886 I != E; ++I, ++Index) {
887 OS.indent(Indentation) << "case " << Index << ":\n";
888 OS.indent(Indentation+2) << "return (" << *I << ");\n";
890 OS.indent(Indentation) << "}\n";
892 // No case statement to emit
893 OS.indent(Indentation) << "llvm_unreachable(\"Invalid index!\");\n";
896 OS.indent(Indentation) << "}\n\n";
899 void FixedLenDecoderEmitter::
900 emitDecoderFunction(formatted_raw_ostream &OS, DecoderSet &Decoders,
901 unsigned Indentation) const {
902 // The decoder function is just a big switch statement based on the
903 // input decoder index.
904 OS.indent(Indentation) << "template<typename InsnType>\n";
905 OS.indent(Indentation) << "static DecodeStatus decodeToMCInst(DecodeStatus S,"
906 << " unsigned Idx, InsnType insn, MCInst &MI,\n";
907 OS.indent(Indentation) << " uint64_t "
908 << "Address, const void *Decoder) {\n";
910 OS.indent(Indentation) << "InsnType tmp;\n";
911 OS.indent(Indentation) << "switch (Idx) {\n";
912 OS.indent(Indentation) << "default: llvm_unreachable(\"Invalid index!\");\n";
914 for (DecoderSet::const_iterator I = Decoders.begin(), E = Decoders.end();
915 I != E; ++I, ++Index) {
916 OS.indent(Indentation) << "case " << Index << ":\n";
918 OS.indent(Indentation+2) << "return S;\n";
920 OS.indent(Indentation) << "}\n";
922 OS.indent(Indentation) << "}\n\n";
925 // Populates the field of the insn given the start position and the number of
926 // consecutive bits to scan for.
928 // Returns false if and on the first uninitialized bit value encountered.
929 // Returns true, otherwise.
930 bool FilterChooser::fieldFromInsn(uint64_t &Field, insn_t &Insn,
931 unsigned StartBit, unsigned NumBits) const {
934 for (unsigned i = 0; i < NumBits; ++i) {
935 if (Insn[StartBit + i] == BIT_UNSET)
938 if (Insn[StartBit + i] == BIT_TRUE)
939 Field = Field | (1ULL << i);
945 /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
946 /// filter array as a series of chars.
947 void FilterChooser::dumpFilterArray(raw_ostream &o,
948 const std::vector<bit_value_t> &filter) const {
949 for (unsigned bitIndex = BitWidth; bitIndex > 0; bitIndex--) {
950 switch (filter[bitIndex - 1]) {
967 /// dumpStack - dumpStack traverses the filter chooser chain and calls
968 /// dumpFilterArray on each filter chooser up to the top level one.
969 void FilterChooser::dumpStack(raw_ostream &o, const char *prefix) const {
970 const FilterChooser *current = this;
974 dumpFilterArray(o, current->FilterBitValues);
976 current = current->Parent;
980 // Called from Filter::recurse() when singleton exists. For debug purpose.
981 void FilterChooser::SingletonExists(unsigned Opc) const {
983 insnWithID(Insn0, Opc);
985 errs() << "Singleton exists: " << nameWithID(Opc)
986 << " with its decoding dominating ";
987 for (unsigned i = 0; i < Opcodes.size(); ++i) {
988 if (Opcodes[i] == Opc) continue;
989 errs() << nameWithID(Opcodes[i]) << ' ';
993 dumpStack(errs(), "\t\t");
994 for (unsigned i = 0; i < Opcodes.size(); ++i) {
995 const std::string &Name = nameWithID(Opcodes[i]);
997 errs() << '\t' << Name << " ";
999 getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
1004 // Calculates the island(s) needed to decode the instruction.
1005 // This returns a list of undecoded bits of an instructions, for example,
1006 // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
1007 // decoded bits in order to verify that the instruction matches the Opcode.
1008 unsigned FilterChooser::getIslands(std::vector<unsigned> &StartBits,
1009 std::vector<unsigned> &EndBits,
1010 std::vector<uint64_t> &FieldVals,
1011 const insn_t &Insn) const {
1012 unsigned Num, BitNo;
1015 uint64_t FieldVal = 0;
1018 // 1: Water (the bit value does not affect decoding)
1019 // 2: Island (well-known bit value needed for decoding)
1023 for (unsigned i = 0; i < BitWidth; ++i) {
1024 Val = Value(Insn[i]);
1025 bool Filtered = PositionFiltered(i);
1027 default: llvm_unreachable("Unreachable code!");
1030 if (Filtered || Val == -1)
1031 State = 1; // Still in Water
1033 State = 2; // Into the Island
1035 StartBits.push_back(i);
1040 if (Filtered || Val == -1) {
1041 State = 1; // Into the Water
1042 EndBits.push_back(i - 1);
1043 FieldVals.push_back(FieldVal);
1046 State = 2; // Still in Island
1048 FieldVal = FieldVal | Val << BitNo;
1053 // If we are still in Island after the loop, do some housekeeping.
1055 EndBits.push_back(BitWidth - 1);
1056 FieldVals.push_back(FieldVal);
1060 assert(StartBits.size() == Num && EndBits.size() == Num &&
1061 FieldVals.size() == Num);
1065 void FilterChooser::emitBinaryParser(raw_ostream &o, unsigned &Indentation,
1066 const OperandInfo &OpInfo) const {
1067 const std::string &Decoder = OpInfo.Decoder;
1069 if (OpInfo.numFields() == 1) {
1070 OperandInfo::const_iterator OI = OpInfo.begin();
1071 o.indent(Indentation) << "tmp = fieldFromInstruction"
1072 << "(insn, " << OI->Base << ", " << OI->Width
1075 o.indent(Indentation) << "tmp = 0;\n";
1076 for (OperandInfo::const_iterator OI = OpInfo.begin(), OE = OpInfo.end();
1078 o.indent(Indentation) << "tmp |= (fieldFromInstruction"
1079 << "(insn, " << OI->Base << ", " << OI->Width
1080 << ") << " << OI->Offset << ");\n";
1085 o.indent(Indentation) << Emitter->GuardPrefix << Decoder
1086 << "(MI, tmp, Address, Decoder)"
1087 << Emitter->GuardPostfix << "\n";
1089 o.indent(Indentation) << "MI.addOperand(MCOperand::CreateImm(tmp));\n";
1093 void FilterChooser::emitDecoder(raw_ostream &OS, unsigned Indentation,
1094 unsigned Opc) const {
1095 std::map<unsigned, std::vector<OperandInfo> >::const_iterator OpIter =
1097 const std::vector<OperandInfo>& InsnOperands = OpIter->second;
1098 for (std::vector<OperandInfo>::const_iterator
1099 I = InsnOperands.begin(), E = InsnOperands.end(); I != E; ++I) {
1100 // If a custom instruction decoder was specified, use that.
1101 if (I->numFields() == 0 && I->Decoder.size()) {
1102 OS.indent(Indentation) << Emitter->GuardPrefix << I->Decoder
1103 << "(MI, insn, Address, Decoder)"
1104 << Emitter->GuardPostfix << "\n";
1108 emitBinaryParser(OS, Indentation, *I);
1112 unsigned FilterChooser::getDecoderIndex(DecoderSet &Decoders,
1113 unsigned Opc) const {
1114 // Build up the predicate string.
1115 SmallString<256> Decoder;
1116 // FIXME: emitDecoder() function can take a buffer directly rather than
1118 raw_svector_ostream S(Decoder);
1120 emitDecoder(S, I, Opc);
1123 // Using the full decoder string as the key value here is a bit
1124 // heavyweight, but is effective. If the string comparisons become a
1125 // performance concern, we can implement a mangling of the predicate
1126 // data easilly enough with a map back to the actual string. That's
1127 // overkill for now, though.
1129 // Make sure the predicate is in the table.
1130 Decoders.insert(Decoder.str());
1131 // Now figure out the index for when we write out the table.
1132 DecoderSet::const_iterator P = std::find(Decoders.begin(),
1135 return (unsigned)(P - Decoders.begin());
1138 static void emitSinglePredicateMatch(raw_ostream &o, StringRef str,
1139 const std::string &PredicateNamespace) {
1141 o << "!(Bits & " << PredicateNamespace << "::"
1142 << str.slice(1,str.size()) << ")";
1144 o << "(Bits & " << PredicateNamespace << "::" << str << ")";
1147 bool FilterChooser::emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
1148 unsigned Opc) const {
1149 ListInit *Predicates =
1150 AllInstructions[Opc]->TheDef->getValueAsListInit("Predicates");
1151 for (unsigned i = 0; i < Predicates->getSize(); ++i) {
1152 Record *Pred = Predicates->getElementAsRecord(i);
1153 if (!Pred->getValue("AssemblerMatcherPredicate"))
1156 std::string P = Pred->getValueAsString("AssemblerCondString");
1165 std::pair<StringRef, StringRef> pairs = SR.split(',');
1166 while (pairs.second.size()) {
1167 emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
1169 pairs = pairs.second.split(',');
1171 emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
1173 return Predicates->getSize() > 0;
1176 bool FilterChooser::doesOpcodeNeedPredicate(unsigned Opc) const {
1177 ListInit *Predicates =
1178 AllInstructions[Opc]->TheDef->getValueAsListInit("Predicates");
1179 for (unsigned i = 0; i < Predicates->getSize(); ++i) {
1180 Record *Pred = Predicates->getElementAsRecord(i);
1181 if (!Pred->getValue("AssemblerMatcherPredicate"))
1184 std::string P = Pred->getValueAsString("AssemblerCondString");
1194 unsigned FilterChooser::getPredicateIndex(DecoderTableInfo &TableInfo,
1195 StringRef Predicate) const {
1196 // Using the full predicate string as the key value here is a bit
1197 // heavyweight, but is effective. If the string comparisons become a
1198 // performance concern, we can implement a mangling of the predicate
1199 // data easilly enough with a map back to the actual string. That's
1200 // overkill for now, though.
1202 // Make sure the predicate is in the table.
1203 TableInfo.Predicates.insert(Predicate.str());
1204 // Now figure out the index for when we write out the table.
1205 PredicateSet::const_iterator P = std::find(TableInfo.Predicates.begin(),
1206 TableInfo.Predicates.end(),
1208 return (unsigned)(P - TableInfo.Predicates.begin());
1211 void FilterChooser::emitPredicateTableEntry(DecoderTableInfo &TableInfo,
1212 unsigned Opc) const {
1213 if (!doesOpcodeNeedPredicate(Opc))
1216 // Build up the predicate string.
1217 SmallString<256> Predicate;
1218 // FIXME: emitPredicateMatch() functions can take a buffer directly rather
1220 raw_svector_ostream PS(Predicate);
1222 emitPredicateMatch(PS, I, Opc);
1224 // Figure out the index into the predicate table for the predicate just
1226 unsigned PIdx = getPredicateIndex(TableInfo, PS.str());
1227 SmallString<16> PBytes;
1228 raw_svector_ostream S(PBytes);
1229 encodeULEB128(PIdx, S);
1232 TableInfo.Table.push_back(MCD::OPC_CheckPredicate);
1234 for (unsigned i = 0, e = PBytes.size(); i != e; ++i)
1235 TableInfo.Table.push_back(PBytes[i]);
1236 // Push location for NumToSkip backpatching.
1237 TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
1238 TableInfo.Table.push_back(0);
1239 TableInfo.Table.push_back(0);
1242 void FilterChooser::emitSoftFailTableEntry(DecoderTableInfo &TableInfo,
1243 unsigned Opc) const {
1245 AllInstructions[Opc]->TheDef->getValueAsBitsInit("SoftFail");
1246 if (!SFBits) return;
1247 BitsInit *InstBits = AllInstructions[Opc]->TheDef->getValueAsBitsInit("Inst");
1249 APInt PositiveMask(BitWidth, 0ULL);
1250 APInt NegativeMask(BitWidth, 0ULL);
1251 for (unsigned i = 0; i < BitWidth; ++i) {
1252 bit_value_t B = bitFromBits(*SFBits, i);
1253 bit_value_t IB = bitFromBits(*InstBits, i);
1255 if (B != BIT_TRUE) continue;
1259 // The bit is meant to be false, so emit a check to see if it is true.
1260 PositiveMask.setBit(i);
1263 // The bit is meant to be true, so emit a check to see if it is false.
1264 NegativeMask.setBit(i);
1267 // The bit is not set; this must be an error!
1268 StringRef Name = AllInstructions[Opc]->TheDef->getName();
1269 errs() << "SoftFail Conflict: bit SoftFail{" << i << "} in " << Name
1270 << " is set but Inst{" << i << "} is unset!\n"
1271 << " - You can only mark a bit as SoftFail if it is fully defined"
1272 << " (1/0 - not '?') in Inst\n";
1277 bool NeedPositiveMask = PositiveMask.getBoolValue();
1278 bool NeedNegativeMask = NegativeMask.getBoolValue();
1280 if (!NeedPositiveMask && !NeedNegativeMask)
1283 TableInfo.Table.push_back(MCD::OPC_SoftFail);
1285 SmallString<16> MaskBytes;
1286 raw_svector_ostream S(MaskBytes);
1287 if (NeedPositiveMask) {
1288 encodeULEB128(PositiveMask.getZExtValue(), S);
1290 for (unsigned i = 0, e = MaskBytes.size(); i != e; ++i)
1291 TableInfo.Table.push_back(MaskBytes[i]);
1293 TableInfo.Table.push_back(0);
1294 if (NeedNegativeMask) {
1297 encodeULEB128(NegativeMask.getZExtValue(), S);
1299 for (unsigned i = 0, e = MaskBytes.size(); i != e; ++i)
1300 TableInfo.Table.push_back(MaskBytes[i]);
1302 TableInfo.Table.push_back(0);
1305 // Emits table entries to decode the singleton.
1306 void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,
1307 unsigned Opc) const {
1308 std::vector<unsigned> StartBits;
1309 std::vector<unsigned> EndBits;
1310 std::vector<uint64_t> FieldVals;
1312 insnWithID(Insn, Opc);
1314 // Look for islands of undecoded bits of the singleton.
1315 getIslands(StartBits, EndBits, FieldVals, Insn);
1317 unsigned Size = StartBits.size();
1319 // Emit the predicate table entry if one is needed.
1320 emitPredicateTableEntry(TableInfo, Opc);
1322 // Check any additional encoding fields needed.
1323 for (unsigned I = Size; I != 0; --I) {
1324 unsigned NumBits = EndBits[I-1] - StartBits[I-1] + 1;
1325 TableInfo.Table.push_back(MCD::OPC_CheckField);
1326 TableInfo.Table.push_back(StartBits[I-1]);
1327 TableInfo.Table.push_back(NumBits);
1328 uint8_t Buffer[8], *p;
1329 encodeULEB128(FieldVals[I-1], Buffer);
1330 for (p = Buffer; *p >= 128 ; ++p)
1331 TableInfo.Table.push_back(*p);
1332 TableInfo.Table.push_back(*p);
1333 // Push location for NumToSkip backpatching.
1334 TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
1335 // The fixup is always 16-bits, so go ahead and allocate the space
1336 // in the table so all our relative position calculations work OK even
1337 // before we fully resolve the real value here.
1338 TableInfo.Table.push_back(0);
1339 TableInfo.Table.push_back(0);
1342 // Check for soft failure of the match.
1343 emitSoftFailTableEntry(TableInfo, Opc);
1345 TableInfo.Table.push_back(MCD::OPC_Decode);
1346 uint8_t Buffer[8], *p;
1347 encodeULEB128(Opc, Buffer);
1348 for (p = Buffer; *p >= 128 ; ++p)
1349 TableInfo.Table.push_back(*p);
1350 TableInfo.Table.push_back(*p);
1352 unsigned DIdx = getDecoderIndex(TableInfo.Decoders, Opc);
1353 SmallString<16> Bytes;
1354 raw_svector_ostream S(Bytes);
1355 encodeULEB128(DIdx, S);
1359 for (unsigned i = 0, e = Bytes.size(); i != e; ++i)
1360 TableInfo.Table.push_back(Bytes[i]);
1363 // Emits table entries to decode the singleton, and then to decode the rest.
1364 void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,
1365 const Filter &Best) const {
1366 unsigned Opc = Best.getSingletonOpc();
1368 // complex singletons need predicate checks from the first singleton
1369 // to refer forward to the variable filterchooser that follows.
1370 TableInfo.FixupStack.push_back(FixupList());
1372 emitSingletonTableEntry(TableInfo, Opc);
1374 resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),
1375 TableInfo.Table.size());
1376 TableInfo.FixupStack.pop_back();
1378 Best.getVariableFC().emitTableEntries(TableInfo);
1382 // Assign a single filter and run with it. Top level API client can initialize
1383 // with a single filter to start the filtering process.
1384 void FilterChooser::runSingleFilter(unsigned startBit, unsigned numBit,
1387 Filter F(*this, startBit, numBit, true);
1388 Filters.push_back(F);
1389 BestIndex = 0; // Sole Filter instance to choose from.
1390 bestFilter().recurse();
1393 // reportRegion is a helper function for filterProcessor to mark a region as
1394 // eligible for use as a filter region.
1395 void FilterChooser::reportRegion(bitAttr_t RA, unsigned StartBit,
1396 unsigned BitIndex, bool AllowMixed) {
1397 if (RA == ATTR_MIXED && AllowMixed)
1398 Filters.push_back(Filter(*this, StartBit, BitIndex - StartBit, true));
1399 else if (RA == ATTR_ALL_SET && !AllowMixed)
1400 Filters.push_back(Filter(*this, StartBit, BitIndex - StartBit, false));
1403 // FilterProcessor scans the well-known encoding bits of the instructions and
1404 // builds up a list of candidate filters. It chooses the best filter and
1405 // recursively descends down the decoding tree.
1406 bool FilterChooser::filterProcessor(bool AllowMixed, bool Greedy) {
1409 unsigned numInstructions = Opcodes.size();
1411 assert(numInstructions && "Filter created with no instructions");
1413 // No further filtering is necessary.
1414 if (numInstructions == 1)
1417 // Heuristics. See also doFilter()'s "Heuristics" comment when num of
1418 // instructions is 3.
1419 if (AllowMixed && !Greedy) {
1420 assert(numInstructions == 3);
1422 for (unsigned i = 0; i < Opcodes.size(); ++i) {
1423 std::vector<unsigned> StartBits;
1424 std::vector<unsigned> EndBits;
1425 std::vector<uint64_t> FieldVals;
1428 insnWithID(Insn, Opcodes[i]);
1430 // Look for islands of undecoded bits of any instruction.
1431 if (getIslands(StartBits, EndBits, FieldVals, Insn) > 0) {
1432 // Found an instruction with island(s). Now just assign a filter.
1433 runSingleFilter(StartBits[0], EndBits[0] - StartBits[0] + 1, true);
1441 // We maintain BIT_WIDTH copies of the bitAttrs automaton.
1442 // The automaton consumes the corresponding bit from each
1445 // Input symbols: 0, 1, and _ (unset).
1446 // States: NONE, FILTERED, ALL_SET, ALL_UNSET, and MIXED.
1447 // Initial state: NONE.
1449 // (NONE) ------- [01] -> (ALL_SET)
1450 // (NONE) ------- _ ----> (ALL_UNSET)
1451 // (ALL_SET) ---- [01] -> (ALL_SET)
1452 // (ALL_SET) ---- _ ----> (MIXED)
1453 // (ALL_UNSET) -- [01] -> (MIXED)
1454 // (ALL_UNSET) -- _ ----> (ALL_UNSET)
1455 // (MIXED) ------ . ----> (MIXED)
1456 // (FILTERED)---- . ----> (FILTERED)
1458 std::vector<bitAttr_t> bitAttrs;
1460 // FILTERED bit positions provide no entropy and are not worthy of pursuing.
1461 // Filter::recurse() set either BIT_TRUE or BIT_FALSE for each position.
1462 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex)
1463 if (FilterBitValues[BitIndex] == BIT_TRUE ||
1464 FilterBitValues[BitIndex] == BIT_FALSE)
1465 bitAttrs.push_back(ATTR_FILTERED);
1467 bitAttrs.push_back(ATTR_NONE);
1469 for (unsigned InsnIndex = 0; InsnIndex < numInstructions; ++InsnIndex) {
1472 insnWithID(insn, Opcodes[InsnIndex]);
1474 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
1475 switch (bitAttrs[BitIndex]) {
1477 if (insn[BitIndex] == BIT_UNSET)
1478 bitAttrs[BitIndex] = ATTR_ALL_UNSET;
1480 bitAttrs[BitIndex] = ATTR_ALL_SET;
1483 if (insn[BitIndex] == BIT_UNSET)
1484 bitAttrs[BitIndex] = ATTR_MIXED;
1486 case ATTR_ALL_UNSET:
1487 if (insn[BitIndex] != BIT_UNSET)
1488 bitAttrs[BitIndex] = ATTR_MIXED;
1497 // The regionAttr automaton consumes the bitAttrs automatons' state,
1498 // lowest-to-highest.
1500 // Input symbols: F(iltered), (all_)S(et), (all_)U(nset), M(ixed)
1501 // States: NONE, ALL_SET, MIXED
1502 // Initial state: NONE
1504 // (NONE) ----- F --> (NONE)
1505 // (NONE) ----- S --> (ALL_SET) ; and set region start
1506 // (NONE) ----- U --> (NONE)
1507 // (NONE) ----- M --> (MIXED) ; and set region start
1508 // (ALL_SET) -- F --> (NONE) ; and report an ALL_SET region
1509 // (ALL_SET) -- S --> (ALL_SET)
1510 // (ALL_SET) -- U --> (NONE) ; and report an ALL_SET region
1511 // (ALL_SET) -- M --> (MIXED) ; and report an ALL_SET region
1512 // (MIXED) ---- F --> (NONE) ; and report a MIXED region
1513 // (MIXED) ---- S --> (ALL_SET) ; and report a MIXED region
1514 // (MIXED) ---- U --> (NONE) ; and report a MIXED region
1515 // (MIXED) ---- M --> (MIXED)
1517 bitAttr_t RA = ATTR_NONE;
1518 unsigned StartBit = 0;
1520 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
1521 bitAttr_t bitAttr = bitAttrs[BitIndex];
1523 assert(bitAttr != ATTR_NONE && "Bit without attributes");
1531 StartBit = BitIndex;
1534 case ATTR_ALL_UNSET:
1537 StartBit = BitIndex;
1541 llvm_unreachable("Unexpected bitAttr!");
1547 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1552 case ATTR_ALL_UNSET:
1553 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1557 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1558 StartBit = BitIndex;
1562 llvm_unreachable("Unexpected bitAttr!");
1568 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1569 StartBit = BitIndex;
1573 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1574 StartBit = BitIndex;
1577 case ATTR_ALL_UNSET:
1578 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1584 llvm_unreachable("Unexpected bitAttr!");
1587 case ATTR_ALL_UNSET:
1588 llvm_unreachable("regionAttr state machine has no ATTR_UNSET state");
1590 llvm_unreachable("regionAttr state machine has no ATTR_FILTERED state");
1594 // At the end, if we're still in ALL_SET or MIXED states, report a region
1601 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1603 case ATTR_ALL_UNSET:
1606 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1610 // We have finished with the filter processings. Now it's time to choose
1611 // the best performing filter.
1613 bool AllUseless = true;
1614 unsigned BestScore = 0;
1616 for (unsigned i = 0, e = Filters.size(); i != e; ++i) {
1617 unsigned Usefulness = Filters[i].usefulness();
1622 if (Usefulness > BestScore) {
1624 BestScore = Usefulness;
1629 bestFilter().recurse();
1632 } // end of FilterChooser::filterProcessor(bool)
1634 // Decides on the best configuration of filter(s) to use in order to decode
1635 // the instructions. A conflict of instructions may occur, in which case we
1636 // dump the conflict set to the standard error.
1637 void FilterChooser::doFilter() {
1638 unsigned Num = Opcodes.size();
1639 assert(Num && "FilterChooser created with no instructions");
1641 // Try regions of consecutive known bit values first.
1642 if (filterProcessor(false))
1645 // Then regions of mixed bits (both known and unitialized bit values allowed).
1646 if (filterProcessor(true))
1649 // Heuristics to cope with conflict set {t2CMPrs, t2SUBSrr, t2SUBSrs} where
1650 // no single instruction for the maximum ATTR_MIXED region Inst{14-4} has a
1651 // well-known encoding pattern. In such case, we backtrack and scan for the
1652 // the very first consecutive ATTR_ALL_SET region and assign a filter to it.
1653 if (Num == 3 && filterProcessor(true, false))
1656 // If we come to here, the instruction decoding has failed.
1657 // Set the BestIndex to -1 to indicate so.
1661 // emitTableEntries - Emit state machine entries to decode our share of
1663 void FilterChooser::emitTableEntries(DecoderTableInfo &TableInfo) const {
1664 if (Opcodes.size() == 1) {
1665 // There is only one instruction in the set, which is great!
1666 // Call emitSingletonDecoder() to see whether there are any remaining
1668 emitSingletonTableEntry(TableInfo, Opcodes[0]);
1672 // Choose the best filter to do the decodings!
1673 if (BestIndex != -1) {
1674 const Filter &Best = Filters[BestIndex];
1675 if (Best.getNumFiltered() == 1)
1676 emitSingletonTableEntry(TableInfo, Best);
1678 Best.emitTableEntry(TableInfo);
1682 // We don't know how to decode these instructions! Dump the
1683 // conflict set and bail.
1685 // Print out useful conflict information for postmortem analysis.
1686 errs() << "Decoding Conflict:\n";
1688 dumpStack(errs(), "\t\t");
1690 for (unsigned i = 0; i < Opcodes.size(); ++i) {
1691 const std::string &Name = nameWithID(Opcodes[i]);
1693 errs() << '\t' << Name << " ";
1695 getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
1700 static bool populateInstruction(CodeGenTarget &Target,
1701 const CodeGenInstruction &CGI, unsigned Opc,
1702 std::map<unsigned, std::vector<OperandInfo> > &Operands){
1703 const Record &Def = *CGI.TheDef;
1704 // If all the bit positions are not specified; do not decode this instruction.
1705 // We are bound to fail! For proper disassembly, the well-known encoding bits
1706 // of the instruction must be fully specified.
1708 BitsInit &Bits = getBitsField(Def, "Inst");
1709 if (Bits.allInComplete()) return false;
1711 std::vector<OperandInfo> InsnOperands;
1713 // If the instruction has specified a custom decoding hook, use that instead
1714 // of trying to auto-generate the decoder.
1715 std::string InstDecoder = Def.getValueAsString("DecoderMethod");
1716 if (InstDecoder != "") {
1717 InsnOperands.push_back(OperandInfo(InstDecoder));
1718 Operands[Opc] = InsnOperands;
1722 // Generate a description of the operand of the instruction that we know
1723 // how to decode automatically.
1724 // FIXME: We'll need to have a way to manually override this as needed.
1726 // Gather the outputs/inputs of the instruction, so we can find their
1727 // positions in the encoding. This assumes for now that they appear in the
1728 // MCInst in the order that they're listed.
1729 std::vector<std::pair<Init*, std::string> > InOutOperands;
1730 DagInit *Out = Def.getValueAsDag("OutOperandList");
1731 DagInit *In = Def.getValueAsDag("InOperandList");
1732 for (unsigned i = 0; i < Out->getNumArgs(); ++i)
1733 InOutOperands.push_back(std::make_pair(Out->getArg(i), Out->getArgName(i)));
1734 for (unsigned i = 0; i < In->getNumArgs(); ++i)
1735 InOutOperands.push_back(std::make_pair(In->getArg(i), In->getArgName(i)));
1737 // Search for tied operands, so that we can correctly instantiate
1738 // operands that are not explicitly represented in the encoding.
1739 std::map<std::string, std::string> TiedNames;
1740 for (unsigned i = 0; i < CGI.Operands.size(); ++i) {
1741 int tiedTo = CGI.Operands[i].getTiedRegister();
1743 std::pair<unsigned, unsigned> SO =
1744 CGI.Operands.getSubOperandNumber(tiedTo);
1745 TiedNames[InOutOperands[i].second] = InOutOperands[SO.first].second;
1746 TiedNames[InOutOperands[SO.first].second] = InOutOperands[i].second;
1750 std::map<std::string, std::vector<OperandInfo> > NumberedInsnOperands;
1751 std::set<std::string> NumberedInsnOperandsNoTie;
1752 if (Target.getInstructionSet()->
1753 getValueAsBit("decodePositionallyEncodedOperands")) {
1754 const std::vector<RecordVal> &Vals = Def.getValues();
1755 unsigned NumberedOp = 0;
1757 std::set<unsigned> NamedOpIndices;
1758 if (Target.getInstructionSet()->
1759 getValueAsBit("noNamedPositionallyEncodedOperands"))
1760 // Collect the set of operand indices that might correspond to named
1761 // operand, and skip these when assigning operands based on position.
1762 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1764 if (!CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx))
1767 NamedOpIndices.insert(OpIdx);
1770 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1771 // Ignore fixed fields in the record, we're looking for values like:
1772 // bits<5> RST = { ?, ?, ?, ?, ? };
1773 if (Vals[i].getPrefix() || Vals[i].getValue()->isComplete())
1776 // Determine if Vals[i] actually contributes to the Inst encoding.
1778 for (; bi < Bits.getNumBits(); ++bi) {
1780 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
1782 Var = dyn_cast<VarInit>(BI->getBitVar());
1784 Var = dyn_cast<VarInit>(Bits.getBit(bi));
1786 if (Var && Var->getName() == Vals[i].getName())
1790 if (bi == Bits.getNumBits())
1793 // Skip variables that correspond to explicitly-named operands.
1795 if (CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx))
1798 // Get the bit range for this operand:
1799 unsigned bitStart = bi++, bitWidth = 1;
1800 for (; bi < Bits.getNumBits(); ++bi) {
1802 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
1804 Var = dyn_cast<VarInit>(BI->getBitVar());
1806 Var = dyn_cast<VarInit>(Bits.getBit(bi));
1811 if (Var->getName() != Vals[i].getName())
1817 unsigned NumberOps = CGI.Operands.size();
1818 while (NumberedOp < NumberOps &&
1819 (CGI.Operands.isFlatOperandNotEmitted(NumberedOp) ||
1820 (NamedOpIndices.size() && NamedOpIndices.count(
1821 CGI.Operands.getSubOperandNumber(NumberedOp).first))))
1824 OpIdx = NumberedOp++;
1826 // OpIdx now holds the ordered operand number of Vals[i].
1827 std::pair<unsigned, unsigned> SO =
1828 CGI.Operands.getSubOperandNumber(OpIdx);
1829 const std::string &Name = CGI.Operands[SO.first].Name;
1831 DEBUG(dbgs() << "Numbered operand mapping for " << Def.getName() << ": " <<
1832 Name << "(" << SO.first << ", " << SO.second << ") => " <<
1833 Vals[i].getName() << "\n");
1835 std::string Decoder = "";
1836 Record *TypeRecord = CGI.Operands[SO.first].Rec;
1838 RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod");
1839 StringInit *String = DecoderString ?
1840 dyn_cast<StringInit>(DecoderString->getValue()) : 0;
1841 if (String && String->getValue() != "")
1842 Decoder = String->getValue();
1844 if (Decoder == "" &&
1845 CGI.Operands[SO.first].MIOperandInfo &&
1846 CGI.Operands[SO.first].MIOperandInfo->getNumArgs()) {
1847 Init *Arg = CGI.Operands[SO.first].MIOperandInfo->
1849 if (TypedInit *TI = cast<TypedInit>(Arg)) {
1850 RecordRecTy *Type = cast<RecordRecTy>(TI->getType());
1851 TypeRecord = Type->getRecord();
1856 if (TypeRecord->isSubClassOf("RegisterOperand"))
1857 TypeRecord = TypeRecord->getValueAsDef("RegClass");
1858 if (TypeRecord->isSubClassOf("RegisterClass")) {
1859 Decoder = "Decode" + TypeRecord->getName() + "RegisterClass";
1861 } else if (TypeRecord->isSubClassOf("PointerLikeRegClass")) {
1862 Decoder = "DecodePointerLikeRegClass" +
1863 utostr(TypeRecord->getValueAsInt("RegClassKind"));
1867 DecoderString = TypeRecord->getValue("DecoderMethod");
1868 String = DecoderString ?
1869 dyn_cast<StringInit>(DecoderString->getValue()) : 0;
1870 if (!isReg && String && String->getValue() != "")
1871 Decoder = String->getValue();
1873 OperandInfo OpInfo(Decoder);
1874 OpInfo.addField(bitStart, bitWidth, 0);
1876 NumberedInsnOperands[Name].push_back(OpInfo);
1878 // FIXME: For complex operands with custom decoders we can't handle tied
1879 // sub-operands automatically. Skip those here and assume that this is
1880 // fixed up elsewhere.
1881 if (CGI.Operands[SO.first].MIOperandInfo &&
1882 CGI.Operands[SO.first].MIOperandInfo->getNumArgs() > 1 &&
1883 String && String->getValue() != "")
1884 NumberedInsnOperandsNoTie.insert(Name);
1888 // For each operand, see if we can figure out where it is encoded.
1889 for (std::vector<std::pair<Init*, std::string> >::const_iterator
1890 NI = InOutOperands.begin(), NE = InOutOperands.end(); NI != NE; ++NI) {
1891 if (!NumberedInsnOperands[NI->second].empty()) {
1892 InsnOperands.insert(InsnOperands.end(),
1893 NumberedInsnOperands[NI->second].begin(),
1894 NumberedInsnOperands[NI->second].end());
1896 } else if (!NumberedInsnOperands[TiedNames[NI->second]].empty()) {
1897 if (!NumberedInsnOperandsNoTie.count(TiedNames[NI->second])) {
1898 // Figure out to which (sub)operand we're tied.
1899 unsigned i = CGI.Operands.getOperandNamed(TiedNames[NI->second]);
1900 int tiedTo = CGI.Operands[i].getTiedRegister();
1902 i = CGI.Operands.getOperandNamed(NI->second);
1903 tiedTo = CGI.Operands[i].getTiedRegister();
1907 std::pair<unsigned, unsigned> SO =
1908 CGI.Operands.getSubOperandNumber(tiedTo);
1910 InsnOperands.push_back(NumberedInsnOperands[TiedNames[NI->second]]
1917 std::string Decoder = "";
1919 // At this point, we can locate the field, but we need to know how to
1920 // interpret it. As a first step, require the target to provide callbacks
1921 // for decoding register classes.
1922 // FIXME: This need to be extended to handle instructions with custom
1923 // decoder methods, and operands with (simple) MIOperandInfo's.
1924 TypedInit *TI = cast<TypedInit>(NI->first);
1925 RecordRecTy *Type = cast<RecordRecTy>(TI->getType());
1926 Record *TypeRecord = Type->getRecord();
1928 if (TypeRecord->isSubClassOf("RegisterOperand"))
1929 TypeRecord = TypeRecord->getValueAsDef("RegClass");
1930 if (TypeRecord->isSubClassOf("RegisterClass")) {
1931 Decoder = "Decode" + TypeRecord->getName() + "RegisterClass";
1933 } else if (TypeRecord->isSubClassOf("PointerLikeRegClass")) {
1934 Decoder = "DecodePointerLikeRegClass" +
1935 utostr(TypeRecord->getValueAsInt("RegClassKind"));
1939 RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod");
1940 StringInit *String = DecoderString ?
1941 dyn_cast<StringInit>(DecoderString->getValue()) : 0;
1942 if (!isReg && String && String->getValue() != "")
1943 Decoder = String->getValue();
1945 OperandInfo OpInfo(Decoder);
1946 unsigned Base = ~0U;
1948 unsigned Offset = 0;
1950 for (unsigned bi = 0; bi < Bits.getNumBits(); ++bi) {
1952 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
1954 Var = dyn_cast<VarInit>(BI->getBitVar());
1956 Var = dyn_cast<VarInit>(Bits.getBit(bi));
1960 OpInfo.addField(Base, Width, Offset);
1968 if (Var->getName() != NI->second &&
1969 Var->getName() != TiedNames[NI->second]) {
1971 OpInfo.addField(Base, Width, Offset);
1982 Offset = BI ? BI->getBitNum() : 0;
1983 } else if (BI && BI->getBitNum() != Offset + Width) {
1984 OpInfo.addField(Base, Width, Offset);
1987 Offset = BI->getBitNum();
1994 OpInfo.addField(Base, Width, Offset);
1996 if (OpInfo.numFields() > 0)
1997 InsnOperands.push_back(OpInfo);
2000 Operands[Opc] = InsnOperands;
2005 // Dumps the instruction encoding bits.
2006 dumpBits(errs(), Bits);
2010 // Dumps the list of operand info.
2011 for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) {
2012 const CGIOperandList::OperandInfo &Info = CGI.Operands[i];
2013 const std::string &OperandName = Info.Name;
2014 const Record &OperandDef = *Info.Rec;
2016 errs() << "\t" << OperandName << " (" << OperandDef.getName() << ")\n";
2024 // emitFieldFromInstruction - Emit the templated helper function
2025 // fieldFromInstruction().
2026 static void emitFieldFromInstruction(formatted_raw_ostream &OS) {
2027 OS << "// Helper function for extracting fields from encoded instructions.\n"
2028 << "template<typename InsnType>\n"
2029 << "static InsnType fieldFromInstruction(InsnType insn, unsigned startBit,\n"
2030 << " unsigned numBits) {\n"
2031 << " assert(startBit + numBits <= (sizeof(InsnType)*8) &&\n"
2032 << " \"Instruction field out of bounds!\");\n"
2033 << " InsnType fieldMask;\n"
2034 << " if (numBits == sizeof(InsnType)*8)\n"
2035 << " fieldMask = (InsnType)(-1LL);\n"
2037 << " fieldMask = (((InsnType)1 << numBits) - 1) << startBit;\n"
2038 << " return (insn & fieldMask) >> startBit;\n"
2042 // emitDecodeInstruction - Emit the templated helper function
2043 // decodeInstruction().
2044 static void emitDecodeInstruction(formatted_raw_ostream &OS) {
2045 OS << "template<typename InsnType>\n"
2046 << "static DecodeStatus decodeInstruction(const uint8_t DecodeTable[], MCInst &MI,\n"
2047 << " InsnType insn, uint64_t Address,\n"
2048 << " const void *DisAsm,\n"
2049 << " const MCSubtargetInfo &STI) {\n"
2050 << " uint64_t Bits = STI.getFeatureBits();\n"
2052 << " const uint8_t *Ptr = DecodeTable;\n"
2053 << " uint32_t CurFieldValue = 0;\n"
2054 << " DecodeStatus S = MCDisassembler::Success;\n"
2056 << " ptrdiff_t Loc = Ptr - DecodeTable;\n"
2057 << " switch (*Ptr) {\n"
2059 << " errs() << Loc << \": Unexpected decode table opcode!\\n\";\n"
2060 << " return MCDisassembler::Fail;\n"
2061 << " case MCD::OPC_ExtractField: {\n"
2062 << " unsigned Start = *++Ptr;\n"
2063 << " unsigned Len = *++Ptr;\n"
2065 << " CurFieldValue = fieldFromInstruction(insn, Start, Len);\n"
2066 << " DEBUG(dbgs() << Loc << \": OPC_ExtractField(\" << Start << \", \"\n"
2067 << " << Len << \"): \" << CurFieldValue << \"\\n\");\n"
2070 << " case MCD::OPC_FilterValue: {\n"
2071 << " // Decode the field value.\n"
2072 << " unsigned Len;\n"
2073 << " InsnType Val = decodeULEB128(++Ptr, &Len);\n"
2075 << " // NumToSkip is a plain 16-bit integer.\n"
2076 << " unsigned NumToSkip = *Ptr++;\n"
2077 << " NumToSkip |= (*Ptr++) << 8;\n"
2079 << " // Perform the filter operation.\n"
2080 << " if (Val != CurFieldValue)\n"
2081 << " Ptr += NumToSkip;\n"
2082 << " DEBUG(dbgs() << Loc << \": OPC_FilterValue(\" << Val << \", \" << NumToSkip\n"
2083 << " << \"): \" << ((Val != CurFieldValue) ? \"FAIL:\" : \"PASS:\")\n"
2084 << " << \" continuing at \" << (Ptr - DecodeTable) << \"\\n\");\n"
2088 << " case MCD::OPC_CheckField: {\n"
2089 << " unsigned Start = *++Ptr;\n"
2090 << " unsigned Len = *++Ptr;\n"
2091 << " InsnType FieldValue = fieldFromInstruction(insn, Start, Len);\n"
2092 << " // Decode the field value.\n"
2093 << " uint32_t ExpectedValue = decodeULEB128(++Ptr, &Len);\n"
2095 << " // NumToSkip is a plain 16-bit integer.\n"
2096 << " unsigned NumToSkip = *Ptr++;\n"
2097 << " NumToSkip |= (*Ptr++) << 8;\n"
2099 << " // If the actual and expected values don't match, skip.\n"
2100 << " if (ExpectedValue != FieldValue)\n"
2101 << " Ptr += NumToSkip;\n"
2102 << " DEBUG(dbgs() << Loc << \": OPC_CheckField(\" << Start << \", \"\n"
2103 << " << Len << \", \" << ExpectedValue << \", \" << NumToSkip\n"
2104 << " << \"): FieldValue = \" << FieldValue << \", ExpectedValue = \"\n"
2105 << " << ExpectedValue << \": \"\n"
2106 << " << ((ExpectedValue == FieldValue) ? \"PASS\\n\" : \"FAIL\\n\"));\n"
2109 << " case MCD::OPC_CheckPredicate: {\n"
2110 << " unsigned Len;\n"
2111 << " // Decode the Predicate Index value.\n"
2112 << " unsigned PIdx = decodeULEB128(++Ptr, &Len);\n"
2114 << " // NumToSkip is a plain 16-bit integer.\n"
2115 << " unsigned NumToSkip = *Ptr++;\n"
2116 << " NumToSkip |= (*Ptr++) << 8;\n"
2117 << " // Check the predicate.\n"
2119 << " if (!(Pred = checkDecoderPredicate(PIdx, Bits)))\n"
2120 << " Ptr += NumToSkip;\n"
2122 << " DEBUG(dbgs() << Loc << \": OPC_CheckPredicate(\" << PIdx << \"): \"\n"
2123 << " << (Pred ? \"PASS\\n\" : \"FAIL\\n\"));\n"
2127 << " case MCD::OPC_Decode: {\n"
2128 << " unsigned Len;\n"
2129 << " // Decode the Opcode value.\n"
2130 << " unsigned Opc = decodeULEB128(++Ptr, &Len);\n"
2132 << " unsigned DecodeIdx = decodeULEB128(Ptr, &Len);\n"
2134 << " DEBUG(dbgs() << Loc << \": OPC_Decode: opcode \" << Opc\n"
2135 << " << \", using decoder \" << DecodeIdx << \"\\n\" );\n"
2136 << " DEBUG(dbgs() << \"----- DECODE SUCCESSFUL -----\\n\");\n"
2138 << " MI.setOpcode(Opc);\n"
2139 << " return decodeToMCInst(S, DecodeIdx, insn, MI, Address, DisAsm);\n"
2141 << " case MCD::OPC_SoftFail: {\n"
2142 << " // Decode the mask values.\n"
2143 << " unsigned Len;\n"
2144 << " InsnType PositiveMask = decodeULEB128(++Ptr, &Len);\n"
2146 << " InsnType NegativeMask = decodeULEB128(Ptr, &Len);\n"
2148 << " bool Fail = (insn & PositiveMask) || (~insn & NegativeMask);\n"
2150 << " S = MCDisassembler::SoftFail;\n"
2151 << " DEBUG(dbgs() << Loc << \": OPC_SoftFail: \" << (Fail ? \"FAIL\\n\":\"PASS\\n\"));\n"
2154 << " case MCD::OPC_Fail: {\n"
2155 << " DEBUG(dbgs() << Loc << \": OPC_Fail\\n\");\n"
2156 << " return MCDisassembler::Fail;\n"
2160 << " llvm_unreachable(\"bogosity detected in disassembler state machine!\");\n"
2164 // Emits disassembler code for instruction decoding.
2165 void FixedLenDecoderEmitter::run(raw_ostream &o) {
2166 formatted_raw_ostream OS(o);
2167 OS << "#include \"llvm/MC/MCInst.h\"\n";
2168 OS << "#include \"llvm/Support/Debug.h\"\n";
2169 OS << "#include \"llvm/Support/DataTypes.h\"\n";
2170 OS << "#include \"llvm/Support/LEB128.h\"\n";
2171 OS << "#include \"llvm/Support/raw_ostream.h\"\n";
2172 OS << "#include <assert.h>\n";
2174 OS << "namespace llvm {\n\n";
2176 emitFieldFromInstruction(OS);
2178 Target.reverseBitsForLittleEndianEncoding();
2180 // Parameterize the decoders based on namespace and instruction width.
2181 NumberedInstructions = &Target.getInstructionsByEnumValue();
2182 std::map<std::pair<std::string, unsigned>,
2183 std::vector<unsigned> > OpcMap;
2184 std::map<unsigned, std::vector<OperandInfo> > Operands;
2186 for (unsigned i = 0; i < NumberedInstructions->size(); ++i) {
2187 const CodeGenInstruction *Inst = NumberedInstructions->at(i);
2188 const Record *Def = Inst->TheDef;
2189 unsigned Size = Def->getValueAsInt("Size");
2190 if (Def->getValueAsString("Namespace") == "TargetOpcode" ||
2191 Def->getValueAsBit("isPseudo") ||
2192 Def->getValueAsBit("isAsmParserOnly") ||
2193 Def->getValueAsBit("isCodeGenOnly"))
2196 std::string DecoderNamespace = Def->getValueAsString("DecoderNamespace");
2199 if (populateInstruction(Target, *Inst, i, Operands)) {
2200 OpcMap[std::make_pair(DecoderNamespace, Size)].push_back(i);
2205 DecoderTableInfo TableInfo;
2206 for (std::map<std::pair<std::string, unsigned>,
2207 std::vector<unsigned> >::const_iterator
2208 I = OpcMap.begin(), E = OpcMap.end(); I != E; ++I) {
2209 // Emit the decoder for this namespace+width combination.
2210 FilterChooser FC(*NumberedInstructions, I->second, Operands,
2211 8*I->first.second, this);
2213 // The decode table is cleared for each top level decoder function. The
2214 // predicates and decoders themselves, however, are shared across all
2215 // decoders to give more opportunities for uniqueing.
2216 TableInfo.Table.clear();
2217 TableInfo.FixupStack.clear();
2218 TableInfo.Table.reserve(16384);
2219 TableInfo.FixupStack.push_back(FixupList());
2220 FC.emitTableEntries(TableInfo);
2221 // Any NumToSkip fixups in the top level scope can resolve to the
2222 // OPC_Fail at the end of the table.
2223 assert(TableInfo.FixupStack.size() == 1 && "fixup stack phasing error!");
2224 // Resolve any NumToSkip fixups in the current scope.
2225 resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),
2226 TableInfo.Table.size());
2227 TableInfo.FixupStack.clear();
2229 TableInfo.Table.push_back(MCD::OPC_Fail);
2231 // Print the table to the output stream.
2232 emitTable(OS, TableInfo.Table, 0, FC.getBitWidth(), I->first.first);
2236 // Emit the predicate function.
2237 emitPredicateFunction(OS, TableInfo.Predicates, 0);
2239 // Emit the decoder function.
2240 emitDecoderFunction(OS, TableInfo.Decoders, 0);
2242 // Emit the main entry point for the decoder, decodeInstruction().
2243 emitDecodeInstruction(OS);
2245 OS << "\n} // End llvm namespace\n";
2250 void EmitFixedLenDecoder(RecordKeeper &RK, raw_ostream &OS,
2251 std::string PredicateNamespace,
2252 std::string GPrefix,
2253 std::string GPostfix,
2257 FixedLenDecoderEmitter(RK, PredicateNamespace, GPrefix, GPostfix,
2258 ROK, RFail, L).run(OS);
2261 } // End llvm namespace