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/TableGen/Record.h"
19 #include "llvm/ADT/APInt.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/ADT/Twine.h"
24 #include "llvm/MC/MCFixedLenDisassembler.h"
25 #include "llvm/Support/DataTypes.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/FormattedStream.h"
28 #include "llvm/Support/LEB128.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/TableGen/TableGenBackend.h"
39 struct EncodingField {
40 unsigned Base, Width, Offset;
41 EncodingField(unsigned B, unsigned W, unsigned O)
42 : Base(B), Width(W), Offset(O) { }
46 std::vector<EncodingField> Fields;
49 OperandInfo(std::string D)
52 void addField(unsigned Base, unsigned Width, unsigned Offset) {
53 Fields.push_back(EncodingField(Base, Width, Offset));
56 unsigned numFields() const { return Fields.size(); }
58 typedef std::vector<EncodingField>::const_iterator const_iterator;
60 const_iterator begin() const { return Fields.begin(); }
61 const_iterator end() const { return Fields.end(); }
64 typedef std::vector<uint8_t> DecoderTable;
65 typedef uint32_t DecoderFixup;
66 typedef std::vector<DecoderFixup> FixupList;
67 typedef std::vector<FixupList> FixupScopeList;
68 typedef SetVector<std::string> PredicateSet;
69 typedef SetVector<std::string> DecoderSet;
70 struct DecoderTableInfo {
72 FixupScopeList FixupStack;
73 PredicateSet Predicates;
77 } // End anonymous namespace
80 class FixedLenDecoderEmitter {
81 const std::vector<const CodeGenInstruction*> *NumberedInstructions;
84 // Defaults preserved here for documentation, even though they aren't
85 // strictly necessary given the way that this is currently being called.
86 FixedLenDecoderEmitter(RecordKeeper &R,
87 std::string PredicateNamespace,
88 std::string GPrefix = "if (",
89 std::string GPostfix = " == MCDisassembler::Fail)"
90 " return MCDisassembler::Fail;",
91 std::string ROK = "MCDisassembler::Success",
92 std::string RFail = "MCDisassembler::Fail",
95 PredicateNamespace(PredicateNamespace),
96 GuardPrefix(GPrefix), GuardPostfix(GPostfix),
97 ReturnOK(ROK), ReturnFail(RFail), Locals(L) {}
99 // Emit the decoder state machine table.
100 void emitTable(formatted_raw_ostream &o, DecoderTable &Table,
101 unsigned Indentation, unsigned BitWidth,
102 StringRef Namespace) const;
103 void emitPredicateFunction(formatted_raw_ostream &OS,
104 PredicateSet &Predicates,
105 unsigned Indentation) const;
106 void emitDecoderFunction(formatted_raw_ostream &OS,
107 DecoderSet &Decoders,
108 unsigned Indentation) const;
110 // run - Output the code emitter
111 void run(raw_ostream &o);
114 CodeGenTarget Target;
116 std::string PredicateNamespace;
117 std::string GuardPrefix, GuardPostfix;
118 std::string ReturnOK, ReturnFail;
121 } // End anonymous namespace
123 // The set (BIT_TRUE, BIT_FALSE, BIT_UNSET) represents a ternary logic system
126 // BIT_UNFILTERED is used as the init value for a filter position. It is used
127 // only for filter processings.
132 BIT_UNFILTERED // unfiltered
135 static bool ValueSet(bit_value_t V) {
136 return (V == BIT_TRUE || V == BIT_FALSE);
138 static bool ValueNotSet(bit_value_t V) {
139 return (V == BIT_UNSET);
141 static int Value(bit_value_t V) {
142 return ValueNotSet(V) ? -1 : (V == BIT_FALSE ? 0 : 1);
144 static bit_value_t bitFromBits(const BitsInit &bits, unsigned index) {
145 if (BitInit *bit = dynamic_cast<BitInit*>(bits.getBit(index)))
146 return bit->getValue() ? BIT_TRUE : BIT_FALSE;
148 // The bit is uninitialized.
151 // Prints the bit value for each position.
152 static void dumpBits(raw_ostream &o, const BitsInit &bits) {
155 for (index = bits.getNumBits(); index > 0; index--) {
156 switch (bitFromBits(bits, index - 1)) {
167 llvm_unreachable("unexpected return value from bitFromBits");
172 static BitsInit &getBitsField(const Record &def, const char *str) {
173 BitsInit *bits = def.getValueAsBitsInit(str);
177 // Forward declaration.
180 } // End anonymous namespace
182 // Representation of the instruction to work on.
183 typedef std::vector<bit_value_t> insn_t;
185 /// Filter - Filter works with FilterChooser to produce the decoding tree for
188 /// It is useful to think of a Filter as governing the switch stmts of the
189 /// decoding tree in a certain level. Each case stmt delegates to an inferior
190 /// FilterChooser to decide what further decoding logic to employ, or in another
191 /// words, what other remaining bits to look at. The FilterChooser eventually
192 /// chooses a best Filter to do its job.
194 /// This recursive scheme ends when the number of Opcodes assigned to the
195 /// FilterChooser becomes 1 or if there is a conflict. A conflict happens when
196 /// the Filter/FilterChooser combo does not know how to distinguish among the
197 /// Opcodes assigned.
199 /// An example of a conflict is
202 /// 111101000.00........00010000....
203 /// 111101000.00........0001........
204 /// 1111010...00........0001........
205 /// 1111010...00....................
206 /// 1111010.........................
207 /// 1111............................
208 /// ................................
209 /// VST4q8a 111101000_00________00010000____
210 /// VST4q8b 111101000_00________00010000____
212 /// The Debug output shows the path that the decoding tree follows to reach the
213 /// the conclusion that there is a conflict. VST4q8a is a vst4 to double-spaced
214 /// even registers, while VST4q8b is a vst4 to double-spaced odd regsisters.
216 /// The encoding info in the .td files does not specify this meta information,
217 /// which could have been used by the decoder to resolve the conflict. The
218 /// decoder could try to decode the even/odd register numbering and assign to
219 /// VST4q8a or VST4q8b, but for the time being, the decoder chooses the "a"
220 /// version and return the Opcode since the two have the same Asm format string.
224 const FilterChooser *Owner;// points to the FilterChooser who owns this filter
225 unsigned StartBit; // the starting bit position
226 unsigned NumBits; // number of bits to filter
227 bool Mixed; // a mixed region contains both set and unset bits
229 // Map of well-known segment value to the set of uid's with that value.
230 std::map<uint64_t, std::vector<unsigned> > FilteredInstructions;
232 // Set of uid's with non-constant segment values.
233 std::vector<unsigned> VariableInstructions;
235 // Map of well-known segment value to its delegate.
236 std::map<unsigned, const FilterChooser*> FilterChooserMap;
238 // Number of instructions which fall under FilteredInstructions category.
239 unsigned NumFiltered;
241 // Keeps track of the last opcode in the filtered bucket.
242 unsigned LastOpcFiltered;
245 unsigned getNumFiltered() const { return NumFiltered; }
246 unsigned getSingletonOpc() const {
247 assert(NumFiltered == 1);
248 return LastOpcFiltered;
250 // Return the filter chooser for the group of instructions without constant
252 const FilterChooser &getVariableFC() const {
253 assert(NumFiltered == 1);
254 assert(FilterChooserMap.size() == 1);
255 return *(FilterChooserMap.find((unsigned)-1)->second);
258 Filter(const Filter &f);
259 Filter(FilterChooser &owner, unsigned startBit, unsigned numBits, bool mixed);
263 // Divides the decoding task into sub tasks and delegates them to the
264 // inferior FilterChooser's.
266 // A special case arises when there's only one entry in the filtered
267 // instructions. In order to unambiguously decode the singleton, we need to
268 // match the remaining undecoded encoding bits against the singleton.
271 // Emit table entries to decode instructions given a segment or segments of
273 void emitTableEntry(DecoderTableInfo &TableInfo) const;
275 // Returns the number of fanout produced by the filter. More fanout implies
276 // the filter distinguishes more categories of instructions.
277 unsigned usefulness() const;
278 }; // End of class Filter
279 } // End anonymous namespace
281 // These are states of our finite state machines used in FilterChooser's
282 // filterProcessor() which produces the filter candidates to use.
291 /// FilterChooser - FilterChooser chooses the best filter among a set of Filters
292 /// in order to perform the decoding of instructions at the current level.
294 /// Decoding proceeds from the top down. Based on the well-known encoding bits
295 /// of instructions available, FilterChooser builds up the possible Filters that
296 /// can further the task of decoding by distinguishing among the remaining
297 /// candidate instructions.
299 /// Once a filter has been chosen, it is called upon to divide the decoding task
300 /// into sub-tasks and delegates them to its inferior FilterChoosers for further
303 /// It is useful to think of a Filter as governing the switch stmts of the
304 /// decoding tree. And each case is delegated to an inferior FilterChooser to
305 /// decide what further remaining bits to look at.
307 class FilterChooser {
311 // Vector of codegen instructions to choose our filter.
312 const std::vector<const CodeGenInstruction*> &AllInstructions;
314 // Vector of uid's for this filter chooser to work on.
315 const std::vector<unsigned> &Opcodes;
317 // Lookup table for the operand decoding of instructions.
318 const std::map<unsigned, std::vector<OperandInfo> > &Operands;
320 // Vector of candidate filters.
321 std::vector<Filter> Filters;
323 // Array of bit values passed down from our parent.
324 // Set to all BIT_UNFILTERED's for Parent == NULL.
325 std::vector<bit_value_t> FilterBitValues;
327 // Links to the FilterChooser above us in the decoding tree.
328 const FilterChooser *Parent;
330 // Index of the best filter from Filters.
333 // Width of instructions
337 const FixedLenDecoderEmitter *Emitter;
340 FilterChooser(const FilterChooser &FC)
341 : AllInstructions(FC.AllInstructions), Opcodes(FC.Opcodes),
342 Operands(FC.Operands), Filters(FC.Filters),
343 FilterBitValues(FC.FilterBitValues), Parent(FC.Parent),
344 BestIndex(FC.BestIndex), BitWidth(FC.BitWidth),
345 Emitter(FC.Emitter) { }
347 FilterChooser(const std::vector<const CodeGenInstruction*> &Insts,
348 const std::vector<unsigned> &IDs,
349 const std::map<unsigned, std::vector<OperandInfo> > &Ops,
351 const FixedLenDecoderEmitter *E)
352 : AllInstructions(Insts), Opcodes(IDs), Operands(Ops), Filters(),
353 Parent(NULL), BestIndex(-1), BitWidth(BW), Emitter(E) {
354 for (unsigned i = 0; i < BitWidth; ++i)
355 FilterBitValues.push_back(BIT_UNFILTERED);
360 FilterChooser(const std::vector<const CodeGenInstruction*> &Insts,
361 const std::vector<unsigned> &IDs,
362 const std::map<unsigned, std::vector<OperandInfo> > &Ops,
363 const std::vector<bit_value_t> &ParentFilterBitValues,
364 const FilterChooser &parent)
365 : AllInstructions(Insts), Opcodes(IDs), Operands(Ops),
366 Filters(), FilterBitValues(ParentFilterBitValues),
367 Parent(&parent), BestIndex(-1), BitWidth(parent.BitWidth),
368 Emitter(parent.Emitter) {
372 unsigned getBitWidth() const { return BitWidth; }
375 // Populates the insn given the uid.
376 void insnWithID(insn_t &Insn, unsigned Opcode) const {
377 BitsInit &Bits = getBitsField(*AllInstructions[Opcode]->TheDef, "Inst");
379 // We may have a SoftFail bitmask, which specifies a mask where an encoding
380 // may differ from the value in "Inst" and yet still be valid, but the
381 // disassembler should return SoftFail instead of Success.
383 // This is used for marking UNPREDICTABLE instructions in the ARM world.
385 AllInstructions[Opcode]->TheDef->getValueAsBitsInit("SoftFail");
387 for (unsigned i = 0; i < BitWidth; ++i) {
388 if (SFBits && bitFromBits(*SFBits, i) == BIT_TRUE)
389 Insn.push_back(BIT_UNSET);
391 Insn.push_back(bitFromBits(Bits, i));
395 // Returns the record name.
396 const std::string &nameWithID(unsigned Opcode) const {
397 return AllInstructions[Opcode]->TheDef->getName();
400 // Populates the field of the insn given the start position and the number of
401 // consecutive bits to scan for.
403 // Returns false if there exists any uninitialized bit value in the range.
404 // Returns true, otherwise.
405 bool fieldFromInsn(uint64_t &Field, insn_t &Insn, unsigned StartBit,
406 unsigned NumBits) const;
408 /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
409 /// filter array as a series of chars.
410 void dumpFilterArray(raw_ostream &o,
411 const std::vector<bit_value_t> & filter) const;
413 /// dumpStack - dumpStack traverses the filter chooser chain and calls
414 /// dumpFilterArray on each filter chooser up to the top level one.
415 void dumpStack(raw_ostream &o, const char *prefix) const;
417 Filter &bestFilter() {
418 assert(BestIndex != -1 && "BestIndex not set");
419 return Filters[BestIndex];
422 // Called from Filter::recurse() when singleton exists. For debug purpose.
423 void SingletonExists(unsigned Opc) const;
425 bool PositionFiltered(unsigned i) const {
426 return ValueSet(FilterBitValues[i]);
429 // Calculates the island(s) needed to decode the instruction.
430 // This returns a lit of undecoded bits of an instructions, for example,
431 // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
432 // decoded bits in order to verify that the instruction matches the Opcode.
433 unsigned getIslands(std::vector<unsigned> &StartBits,
434 std::vector<unsigned> &EndBits,
435 std::vector<uint64_t> &FieldVals,
436 const insn_t &Insn) const;
438 // Emits code to check the Predicates member of an instruction are true.
439 // Returns true if predicate matches were emitted, false otherwise.
440 bool emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
443 bool doesOpcodeNeedPredicate(unsigned Opc) const;
444 unsigned getPredicateIndex(DecoderTableInfo &TableInfo, StringRef P) const;
445 void emitPredicateTableEntry(DecoderTableInfo &TableInfo,
448 void emitSoftFailTableEntry(DecoderTableInfo &TableInfo,
451 // Emits table entries to decode the singleton.
452 void emitSingletonTableEntry(DecoderTableInfo &TableInfo,
455 // Emits code to decode the singleton, and then to decode the rest.
456 void emitSingletonTableEntry(DecoderTableInfo &TableInfo,
457 const Filter &Best) const;
459 void emitBinaryParser(raw_ostream &o, unsigned &Indentation,
460 const OperandInfo &OpInfo) const;
462 void emitDecoder(raw_ostream &OS, unsigned Indentation, unsigned Opc) const;
463 unsigned getDecoderIndex(DecoderSet &Decoders, unsigned Opc) const;
465 // Assign a single filter and run with it.
466 void runSingleFilter(unsigned startBit, unsigned numBit, bool mixed);
468 // reportRegion is a helper function for filterProcessor to mark a region as
469 // eligible for use as a filter region.
470 void reportRegion(bitAttr_t RA, unsigned StartBit, unsigned BitIndex,
473 // FilterProcessor scans the well-known encoding bits of the instructions and
474 // builds up a list of candidate filters. It chooses the best filter and
475 // recursively descends down the decoding tree.
476 bool filterProcessor(bool AllowMixed, bool Greedy = true);
478 // Decides on the best configuration of filter(s) to use in order to decode
479 // the instructions. A conflict of instructions may occur, in which case we
480 // dump the conflict set to the standard error.
484 // emitTableEntries - Emit state machine entries to decode our share of
486 void emitTableEntries(DecoderTableInfo &TableInfo) const;
488 } // End anonymous namespace
490 ///////////////////////////
492 // Filter Implementation //
494 ///////////////////////////
496 Filter::Filter(const Filter &f)
497 : Owner(f.Owner), StartBit(f.StartBit), NumBits(f.NumBits), Mixed(f.Mixed),
498 FilteredInstructions(f.FilteredInstructions),
499 VariableInstructions(f.VariableInstructions),
500 FilterChooserMap(f.FilterChooserMap), NumFiltered(f.NumFiltered),
501 LastOpcFiltered(f.LastOpcFiltered) {
504 Filter::Filter(FilterChooser &owner, unsigned startBit, unsigned numBits,
506 : Owner(&owner), StartBit(startBit), NumBits(numBits), Mixed(mixed) {
507 assert(StartBit + NumBits - 1 < Owner->BitWidth);
512 for (unsigned i = 0, e = Owner->Opcodes.size(); i != e; ++i) {
515 // Populates the insn given the uid.
516 Owner->insnWithID(Insn, Owner->Opcodes[i]);
519 // Scans the segment for possibly well-specified encoding bits.
520 bool ok = Owner->fieldFromInsn(Field, Insn, StartBit, NumBits);
523 // The encoding bits are well-known. Lets add the uid of the
524 // instruction into the bucket keyed off the constant field value.
525 LastOpcFiltered = Owner->Opcodes[i];
526 FilteredInstructions[Field].push_back(LastOpcFiltered);
529 // Some of the encoding bit(s) are unspecified. This contributes to
530 // one additional member of "Variable" instructions.
531 VariableInstructions.push_back(Owner->Opcodes[i]);
535 assert((FilteredInstructions.size() + VariableInstructions.size() > 0)
536 && "Filter returns no instruction categories");
540 std::map<unsigned, const FilterChooser*>::iterator filterIterator;
541 for (filterIterator = FilterChooserMap.begin();
542 filterIterator != FilterChooserMap.end();
544 delete filterIterator->second;
548 // Divides the decoding task into sub tasks and delegates them to the
549 // inferior FilterChooser's.
551 // A special case arises when there's only one entry in the filtered
552 // instructions. In order to unambiguously decode the singleton, we need to
553 // match the remaining undecoded encoding bits against the singleton.
554 void Filter::recurse() {
555 std::map<uint64_t, std::vector<unsigned> >::const_iterator mapIterator;
557 // Starts by inheriting our parent filter chooser's filter bit values.
558 std::vector<bit_value_t> BitValueArray(Owner->FilterBitValues);
562 if (VariableInstructions.size()) {
563 // Conservatively marks each segment position as BIT_UNSET.
564 for (bitIndex = 0; bitIndex < NumBits; bitIndex++)
565 BitValueArray[StartBit + bitIndex] = BIT_UNSET;
567 // Delegates to an inferior filter chooser for further processing on this
568 // group of instructions whose segment values are variable.
569 FilterChooserMap.insert(std::pair<unsigned, const FilterChooser*>(
571 new FilterChooser(Owner->AllInstructions,
572 VariableInstructions,
579 // No need to recurse for a singleton filtered instruction.
580 // See also Filter::emit*().
581 if (getNumFiltered() == 1) {
582 //Owner->SingletonExists(LastOpcFiltered);
583 assert(FilterChooserMap.size() == 1);
587 // Otherwise, create sub choosers.
588 for (mapIterator = FilteredInstructions.begin();
589 mapIterator != FilteredInstructions.end();
592 // Marks all the segment positions with either BIT_TRUE or BIT_FALSE.
593 for (bitIndex = 0; bitIndex < NumBits; bitIndex++) {
594 if (mapIterator->first & (1ULL << bitIndex))
595 BitValueArray[StartBit + bitIndex] = BIT_TRUE;
597 BitValueArray[StartBit + bitIndex] = BIT_FALSE;
600 // Delegates to an inferior filter chooser for further processing on this
601 // category of instructions.
602 FilterChooserMap.insert(std::pair<unsigned, const FilterChooser*>(
604 new FilterChooser(Owner->AllInstructions,
613 static void resolveTableFixups(DecoderTable &Table, const FixupList &Fixups,
615 // Any NumToSkip fixups in the current scope can resolve to the
617 for (FixupList::const_reverse_iterator I = Fixups.rbegin(),
620 // Calculate the distance from the byte following the fixup entry byte
621 // to the destination. The Target is calculated from after the 16-bit
622 // NumToSkip entry itself, so subtract two from the displacement here
623 // to account for that.
624 uint32_t FixupIdx = *I;
625 uint32_t Delta = DestIdx - FixupIdx - 2;
626 // Our NumToSkip entries are 16-bits. Make sure our table isn't too
628 assert(Delta < 65536U && "disassembler decoding table too large!");
629 Table[FixupIdx] = (uint8_t)Delta;
630 Table[FixupIdx + 1] = (uint8_t)(Delta >> 8);
634 // Emit table entries to decode instructions given a segment or segments
636 void Filter::emitTableEntry(DecoderTableInfo &TableInfo) const {
637 TableInfo.Table.push_back(MCD::OPC_ExtractField);
638 TableInfo.Table.push_back(StartBit);
639 TableInfo.Table.push_back(NumBits);
641 // A new filter entry begins a new scope for fixup resolution.
642 TableInfo.FixupStack.push_back(FixupList());
644 std::map<unsigned, const FilterChooser*>::const_iterator filterIterator;
646 DecoderTable &Table = TableInfo.Table;
648 size_t PrevFilter = 0;
649 bool HasFallthrough = false;
650 for (filterIterator = FilterChooserMap.begin();
651 filterIterator != FilterChooserMap.end();
653 // Field value -1 implies a non-empty set of variable instructions.
654 // See also recurse().
655 if (filterIterator->first == (unsigned)-1) {
656 HasFallthrough = true;
658 // Each scope should always have at least one filter value to check
660 assert(PrevFilter != 0 && "empty filter set!");
661 FixupList &CurScope = TableInfo.FixupStack.back();
662 // Resolve any NumToSkip fixups in the current scope.
663 resolveTableFixups(Table, CurScope, Table.size());
665 PrevFilter = 0; // Don't re-process the filter's fallthrough.
667 Table.push_back(MCD::OPC_FilterValue);
668 // Encode and emit the value to filter against.
670 unsigned Len = encodeULEB128(filterIterator->first, Buffer);
671 Table.insert(Table.end(), Buffer, Buffer + Len);
672 // Reserve space for the NumToSkip entry. We'll backpatch the value
674 PrevFilter = Table.size();
679 // We arrive at a category of instructions with the same segment value.
680 // Now delegate to the sub filter chooser for further decodings.
681 // The case may fallthrough, which happens if the remaining well-known
682 // encoding bits do not match exactly.
683 filterIterator->second->emitTableEntries(TableInfo);
685 // Now that we've emitted the body of the handler, update the NumToSkip
686 // of the filter itself to be able to skip forward when false. Subtract
687 // two as to account for the width of the NumToSkip field itself.
689 uint32_t NumToSkip = Table.size() - PrevFilter - 2;
690 assert(NumToSkip < 65536U && "disassembler decoding table too large!");
691 Table[PrevFilter] = (uint8_t)NumToSkip;
692 Table[PrevFilter + 1] = (uint8_t)(NumToSkip >> 8);
696 // Any remaining unresolved fixups bubble up to the parent fixup scope.
697 assert(TableInfo.FixupStack.size() > 1 && "fixup stack underflow!");
698 FixupScopeList::iterator Source = TableInfo.FixupStack.end() - 1;
699 FixupScopeList::iterator Dest = Source - 1;
700 Dest->insert(Dest->end(), Source->begin(), Source->end());
701 TableInfo.FixupStack.pop_back();
703 // If there is no fallthrough, then the final filter should get fixed
704 // up according to the enclosing scope rather than the current position.
706 TableInfo.FixupStack.back().push_back(PrevFilter);
709 // Returns the number of fanout produced by the filter. More fanout implies
710 // the filter distinguishes more categories of instructions.
711 unsigned Filter::usefulness() const {
712 if (VariableInstructions.size())
713 return FilteredInstructions.size();
715 return FilteredInstructions.size() + 1;
718 //////////////////////////////////
720 // Filterchooser Implementation //
722 //////////////////////////////////
724 // Emit the decoder state machine table.
725 void FixedLenDecoderEmitter::emitTable(formatted_raw_ostream &OS,
727 unsigned Indentation,
729 StringRef Namespace) const {
730 OS.indent(Indentation) << "static const uint8_t DecoderTable" << Namespace
731 << BitWidth << "[] = {\n";
735 // FIXME: We may be able to use the NumToSkip values to recover
736 // appropriate indentation levels.
737 DecoderTable::const_iterator I = Table.begin();
738 DecoderTable::const_iterator E = Table.end();
740 assert (I < E && "incomplete decode table entry!");
742 uint64_t Pos = I - Table.begin();
743 OS << "/* " << Pos << " */";
748 throw "invalid decode table opcode";
749 case MCD::OPC_ExtractField: {
751 unsigned Start = *I++;
753 OS.indent(Indentation) << "MCD::OPC_ExtractField, " << Start << ", "
754 << Len << ", // Inst{";
756 OS << (Start + Len - 1) << "-";
757 OS << Start << "} ...\n";
760 case MCD::OPC_FilterValue: {
762 OS.indent(Indentation) << "MCD::OPC_FilterValue, ";
763 // The filter value is ULEB128 encoded.
765 OS << utostr(*I++) << ", ";
766 OS << utostr(*I++) << ", ";
768 // 16-bit numtoskip value.
770 uint32_t NumToSkip = Byte;
771 OS << utostr(Byte) << ", ";
773 OS << utostr(Byte) << ", ";
774 NumToSkip |= Byte << 8;
775 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
778 case MCD::OPC_CheckField: {
780 unsigned Start = *I++;
782 OS.indent(Indentation) << "MCD::OPC_CheckField, " << Start << ", "
783 << Len << ", ";// << Val << ", " << NumToSkip << ",\n";
784 // ULEB128 encoded field value.
785 for (; *I >= 128; ++I)
786 OS << utostr(*I) << ", ";
787 OS << utostr(*I++) << ", ";
788 // 16-bit numtoskip value.
790 uint32_t NumToSkip = Byte;
791 OS << utostr(Byte) << ", ";
793 OS << utostr(Byte) << ", ";
794 NumToSkip |= Byte << 8;
795 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
798 case MCD::OPC_CheckPredicate: {
800 OS.indent(Indentation) << "MCD::OPC_CheckPredicate, ";
801 for (; *I >= 128; ++I)
802 OS << utostr(*I) << ", ";
803 OS << utostr(*I++) << ", ";
805 // 16-bit numtoskip value.
807 uint32_t NumToSkip = Byte;
808 OS << utostr(Byte) << ", ";
810 OS << utostr(Byte) << ", ";
811 NumToSkip |= Byte << 8;
812 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
815 case MCD::OPC_Decode: {
817 // Extract the ULEB128 encoded Opcode to a buffer.
818 uint8_t Buffer[8], *p = Buffer;
819 while ((*p++ = *I++) >= 128)
820 assert((p - Buffer) <= (ptrdiff_t)sizeof(Buffer)
821 && "ULEB128 value too large!");
822 // Decode the Opcode value.
823 unsigned Opc = decodeULEB128(Buffer);
824 OS.indent(Indentation) << "MCD::OPC_Decode, ";
825 for (p = Buffer; *p >= 128; ++p)
826 OS << utostr(*p) << ", ";
827 OS << utostr(*p) << ", ";
830 for (; *I >= 128; ++I)
831 OS << utostr(*I) << ", ";
832 OS << utostr(*I++) << ", ";
835 << NumberedInstructions->at(Opc)->TheDef->getName() << "\n";
838 case MCD::OPC_SoftFail: {
840 OS.indent(Indentation) << "MCD::OPC_SoftFail";
845 OS << ", " << utostr(*I);
846 Value += (*I & 0x7f) << Shift;
848 } while (*I++ >= 128);
850 OS << " /* 0x" << utohexstr(Value) << " */";
855 OS << ", " << utostr(*I);
856 Value += (*I & 0x7f) << Shift;
858 } while (*I++ >= 128);
860 OS << " /* 0x" << utohexstr(Value) << " */";
864 case MCD::OPC_Fail: {
866 OS.indent(Indentation) << "MCD::OPC_Fail,\n";
871 OS.indent(Indentation) << "0\n";
875 OS.indent(Indentation) << "};\n\n";
878 void FixedLenDecoderEmitter::
879 emitPredicateFunction(formatted_raw_ostream &OS, PredicateSet &Predicates,
880 unsigned Indentation) const {
881 // The predicate function is just a big switch statement based on the
882 // input predicate index.
883 OS.indent(Indentation) << "static bool checkDecoderPredicate(unsigned Idx, "
884 << "uint64_t Bits) {\n";
886 OS.indent(Indentation) << "switch (Idx) {\n";
887 OS.indent(Indentation) << "default: llvm_unreachable(\"Invalid index!\");\n";
889 for (PredicateSet::const_iterator I = Predicates.begin(), E = Predicates.end();
890 I != E; ++I, ++Index) {
891 OS.indent(Indentation) << "case " << Index << ":\n";
892 OS.indent(Indentation+2) << "return (" << *I << ");\n";
894 OS.indent(Indentation) << "}\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 {
951 for (bitIndex = BitWidth; bitIndex > 0; bitIndex--) {
952 switch (filter[bitIndex - 1]) {
969 /// dumpStack - dumpStack traverses the filter chooser chain and calls
970 /// dumpFilterArray on each filter chooser up to the top level one.
971 void FilterChooser::dumpStack(raw_ostream &o, const char *prefix) const {
972 const FilterChooser *current = this;
976 dumpFilterArray(o, current->FilterBitValues);
978 current = current->Parent;
982 // Called from Filter::recurse() when singleton exists. For debug purpose.
983 void FilterChooser::SingletonExists(unsigned Opc) const {
985 insnWithID(Insn0, Opc);
987 errs() << "Singleton exists: " << nameWithID(Opc)
988 << " with its decoding dominating ";
989 for (unsigned i = 0; i < Opcodes.size(); ++i) {
990 if (Opcodes[i] == Opc) continue;
991 errs() << nameWithID(Opcodes[i]) << ' ';
995 dumpStack(errs(), "\t\t");
996 for (unsigned i = 0; i < Opcodes.size(); ++i) {
997 const std::string &Name = nameWithID(Opcodes[i]);
999 errs() << '\t' << Name << " ";
1001 getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
1006 // Calculates the island(s) needed to decode the instruction.
1007 // This returns a list of undecoded bits of an instructions, for example,
1008 // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
1009 // decoded bits in order to verify that the instruction matches the Opcode.
1010 unsigned FilterChooser::getIslands(std::vector<unsigned> &StartBits,
1011 std::vector<unsigned> &EndBits,
1012 std::vector<uint64_t> &FieldVals,
1013 const insn_t &Insn) const {
1014 unsigned Num, BitNo;
1017 uint64_t FieldVal = 0;
1020 // 1: Water (the bit value does not affect decoding)
1021 // 2: Island (well-known bit value needed for decoding)
1025 for (unsigned i = 0; i < BitWidth; ++i) {
1026 Val = Value(Insn[i]);
1027 bool Filtered = PositionFiltered(i);
1029 default: llvm_unreachable("Unreachable code!");
1032 if (Filtered || Val == -1)
1033 State = 1; // Still in Water
1035 State = 2; // Into the Island
1037 StartBits.push_back(i);
1042 if (Filtered || Val == -1) {
1043 State = 1; // Into the Water
1044 EndBits.push_back(i - 1);
1045 FieldVals.push_back(FieldVal);
1048 State = 2; // Still in Island
1050 FieldVal = FieldVal | Val << BitNo;
1055 // If we are still in Island after the loop, do some housekeeping.
1057 EndBits.push_back(BitWidth - 1);
1058 FieldVals.push_back(FieldVal);
1062 assert(StartBits.size() == Num && EndBits.size() == Num &&
1063 FieldVals.size() == Num);
1067 void FilterChooser::emitBinaryParser(raw_ostream &o, unsigned &Indentation,
1068 const OperandInfo &OpInfo) const {
1069 const std::string &Decoder = OpInfo.Decoder;
1071 if (OpInfo.numFields() == 1) {
1072 OperandInfo::const_iterator OI = OpInfo.begin();
1073 o.indent(Indentation) << "tmp = fieldFromInstruction"
1074 << "(insn, " << OI->Base << ", " << OI->Width
1077 o.indent(Indentation) << "tmp = 0;\n";
1078 for (OperandInfo::const_iterator OI = OpInfo.begin(), OE = OpInfo.end();
1080 o.indent(Indentation) << "tmp |= (fieldFromInstruction"
1081 << "(insn, " << OI->Base << ", " << OI->Width
1082 << ") << " << OI->Offset << ");\n";
1087 o.indent(Indentation) << Emitter->GuardPrefix << Decoder
1088 << "(MI, tmp, Address, Decoder)"
1089 << Emitter->GuardPostfix << "\n";
1091 o.indent(Indentation) << "MI.addOperand(MCOperand::CreateImm(tmp));\n";
1095 void FilterChooser::emitDecoder(raw_ostream &OS, unsigned Indentation,
1096 unsigned Opc) const {
1097 std::map<unsigned, std::vector<OperandInfo> >::const_iterator OpIter =
1099 const std::vector<OperandInfo>& InsnOperands = OpIter->second;
1100 for (std::vector<OperandInfo>::const_iterator
1101 I = InsnOperands.begin(), E = InsnOperands.end(); I != E; ++I) {
1102 // If a custom instruction decoder was specified, use that.
1103 if (I->numFields() == 0 && I->Decoder.size()) {
1104 OS.indent(Indentation) << Emitter->GuardPrefix << I->Decoder
1105 << "(MI, insn, Address, Decoder)"
1106 << Emitter->GuardPostfix << "\n";
1110 emitBinaryParser(OS, Indentation, *I);
1114 unsigned FilterChooser::getDecoderIndex(DecoderSet &Decoders,
1115 unsigned Opc) const {
1116 // Build up the predicate string.
1117 SmallString<256> Decoder;
1118 // FIXME: emitDecoder() function can take a buffer directly rather than
1120 raw_svector_ostream S(Decoder);
1122 emitDecoder(S, I, Opc);
1125 // Using the full decoder string as the key value here is a bit
1126 // heavyweight, but is effective. If the string comparisons become a
1127 // performance concern, we can implement a mangling of the predicate
1128 // data easilly enough with a map back to the actual string. That's
1129 // overkill for now, though.
1131 // Make sure the predicate is in the table.
1132 Decoders.insert(Decoder.str());
1133 // Now figure out the index for when we write out the table.
1134 DecoderSet::const_iterator P = std::find(Decoders.begin(),
1137 return (unsigned)(P - Decoders.begin());
1140 static void emitSinglePredicateMatch(raw_ostream &o, StringRef str,
1141 const std::string &PredicateNamespace) {
1143 o << "!(Bits & " << PredicateNamespace << "::"
1144 << str.slice(1,str.size()) << ")";
1146 o << "(Bits & " << PredicateNamespace << "::" << str << ")";
1149 bool FilterChooser::emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
1150 unsigned Opc) const {
1151 ListInit *Predicates =
1152 AllInstructions[Opc]->TheDef->getValueAsListInit("Predicates");
1153 for (unsigned i = 0; i < Predicates->getSize(); ++i) {
1154 Record *Pred = Predicates->getElementAsRecord(i);
1155 if (!Pred->getValue("AssemblerMatcherPredicate"))
1158 std::string P = Pred->getValueAsString("AssemblerCondString");
1167 std::pair<StringRef, StringRef> pairs = SR.split(',');
1168 while (pairs.second.size()) {
1169 emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
1171 pairs = pairs.second.split(',');
1173 emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
1175 return Predicates->getSize() > 0;
1178 bool FilterChooser::doesOpcodeNeedPredicate(unsigned Opc) const {
1179 ListInit *Predicates =
1180 AllInstructions[Opc]->TheDef->getValueAsListInit("Predicates");
1181 for (unsigned i = 0; i < Predicates->getSize(); ++i) {
1182 Record *Pred = Predicates->getElementAsRecord(i);
1183 if (!Pred->getValue("AssemblerMatcherPredicate"))
1186 std::string P = Pred->getValueAsString("AssemblerCondString");
1196 unsigned FilterChooser::getPredicateIndex(DecoderTableInfo &TableInfo,
1197 StringRef Predicate) const {
1198 // Using the full predicate string as the key value here is a bit
1199 // heavyweight, but is effective. If the string comparisons become a
1200 // performance concern, we can implement a mangling of the predicate
1201 // data easilly enough with a map back to the actual string. That's
1202 // overkill for now, though.
1204 // Make sure the predicate is in the table.
1205 TableInfo.Predicates.insert(Predicate.str());
1206 // Now figure out the index for when we write out the table.
1207 PredicateSet::const_iterator P = std::find(TableInfo.Predicates.begin(),
1208 TableInfo.Predicates.end(),
1210 return (unsigned)(P - TableInfo.Predicates.begin());
1213 void FilterChooser::emitPredicateTableEntry(DecoderTableInfo &TableInfo,
1214 unsigned Opc) const {
1215 if (!doesOpcodeNeedPredicate(Opc))
1218 // Build up the predicate string.
1219 SmallString<256> Predicate;
1220 // FIXME: emitPredicateMatch() functions can take a buffer directly rather
1222 raw_svector_ostream PS(Predicate);
1224 emitPredicateMatch(PS, I, Opc);
1226 // Figure out the index into the predicate table for the predicate just
1228 unsigned PIdx = getPredicateIndex(TableInfo, PS.str());
1229 SmallString<16> PBytes;
1230 raw_svector_ostream S(PBytes);
1231 encodeULEB128(PIdx, S);
1234 TableInfo.Table.push_back(MCD::OPC_CheckPredicate);
1236 for (int i = 0, e = PBytes.size(); i != e; ++i)
1237 TableInfo.Table.push_back(PBytes[i]);
1238 // Push location for NumToSkip backpatching.
1239 TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
1240 TableInfo.Table.push_back(0);
1241 TableInfo.Table.push_back(0);
1244 void FilterChooser::emitSoftFailTableEntry(DecoderTableInfo &TableInfo,
1245 unsigned Opc) const {
1247 AllInstructions[Opc]->TheDef->getValueAsBitsInit("SoftFail");
1248 if (!SFBits) return;
1249 BitsInit *InstBits = AllInstructions[Opc]->TheDef->getValueAsBitsInit("Inst");
1251 APInt PositiveMask(BitWidth, 0ULL);
1252 APInt NegativeMask(BitWidth, 0ULL);
1253 for (unsigned i = 0; i < BitWidth; ++i) {
1254 bit_value_t B = bitFromBits(*SFBits, i);
1255 bit_value_t IB = bitFromBits(*InstBits, i);
1257 if (B != BIT_TRUE) continue;
1261 // The bit is meant to be false, so emit a check to see if it is true.
1262 PositiveMask.setBit(i);
1265 // The bit is meant to be true, so emit a check to see if it is false.
1266 NegativeMask.setBit(i);
1269 // The bit is not set; this must be an error!
1270 StringRef Name = AllInstructions[Opc]->TheDef->getName();
1271 errs() << "SoftFail Conflict: bit SoftFail{" << i << "} in " << Name
1272 << " is set but Inst{" << i << "} is unset!\n"
1273 << " - You can only mark a bit as SoftFail if it is fully defined"
1274 << " (1/0 - not '?') in Inst\n";
1279 bool NeedPositiveMask = PositiveMask.getBoolValue();
1280 bool NeedNegativeMask = NegativeMask.getBoolValue();
1282 if (!NeedPositiveMask && !NeedNegativeMask)
1285 TableInfo.Table.push_back(MCD::OPC_SoftFail);
1287 SmallString<16> MaskBytes;
1288 raw_svector_ostream S(MaskBytes);
1289 if (NeedPositiveMask) {
1290 encodeULEB128(PositiveMask.getZExtValue(), S);
1292 for (int i = 0, e = MaskBytes.size(); i != e; ++i)
1293 TableInfo.Table.push_back(MaskBytes[i]);
1295 TableInfo.Table.push_back(0);
1296 if (NeedNegativeMask) {
1299 encodeULEB128(NegativeMask.getZExtValue(), S);
1301 for (int i = 0, e = MaskBytes.size(); i != e; ++i)
1302 TableInfo.Table.push_back(MaskBytes[i]);
1304 TableInfo.Table.push_back(0);
1307 // Emits table entries to decode the singleton.
1308 void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,
1309 unsigned Opc) const {
1310 std::vector<unsigned> StartBits;
1311 std::vector<unsigned> EndBits;
1312 std::vector<uint64_t> FieldVals;
1314 insnWithID(Insn, Opc);
1316 // Look for islands of undecoded bits of the singleton.
1317 getIslands(StartBits, EndBits, FieldVals, Insn);
1319 unsigned Size = StartBits.size();
1320 unsigned I, NumBits;
1322 // Emit the predicate table entry if one is needed.
1323 emitPredicateTableEntry(TableInfo, Opc);
1325 // Check any additional encoding fields needed.
1326 for (I = Size; I != 0; --I) {
1327 NumBits = EndBits[I-1] - StartBits[I-1] + 1;
1328 TableInfo.Table.push_back(MCD::OPC_CheckField);
1329 TableInfo.Table.push_back(StartBits[I-1]);
1330 TableInfo.Table.push_back(NumBits);
1331 uint8_t Buffer[8], *p;
1332 encodeULEB128(FieldVals[I-1], Buffer);
1333 for (p = Buffer; *p >= 128 ; ++p)
1334 TableInfo.Table.push_back(*p);
1335 TableInfo.Table.push_back(*p);
1336 // Push location for NumToSkip backpatching.
1337 TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
1338 // The fixup is always 16-bits, so go ahead and allocate the space
1339 // in the table so all our relative position calculations work OK even
1340 // before we fully resolve the real value here.
1341 TableInfo.Table.push_back(0);
1342 TableInfo.Table.push_back(0);
1345 // Check for soft failure of the match.
1346 emitSoftFailTableEntry(TableInfo, Opc);
1348 TableInfo.Table.push_back(MCD::OPC_Decode);
1349 uint8_t Buffer[8], *p;
1350 encodeULEB128(Opc, Buffer);
1351 for (p = Buffer; *p >= 128 ; ++p)
1352 TableInfo.Table.push_back(*p);
1353 TableInfo.Table.push_back(*p);
1355 unsigned DIdx = getDecoderIndex(TableInfo.Decoders, Opc);
1356 SmallString<16> Bytes;
1357 raw_svector_ostream S(Bytes);
1358 encodeULEB128(DIdx, S);
1362 for (int i = 0, e = Bytes.size(); i != e; ++i)
1363 TableInfo.Table.push_back(Bytes[i]);
1366 // Emits table entries to decode the singleton, and then to decode the rest.
1367 void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,
1368 const Filter &Best) const {
1369 unsigned Opc = Best.getSingletonOpc();
1371 // complex singletons need predicate checks from the first singleton
1372 // to refer forward to the variable filterchooser that follows.
1373 TableInfo.FixupStack.push_back(FixupList());
1375 emitSingletonTableEntry(TableInfo, Opc);
1377 resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),
1378 TableInfo.Table.size());
1379 TableInfo.FixupStack.pop_back();
1381 Best.getVariableFC().emitTableEntries(TableInfo);
1385 // Assign a single filter and run with it. Top level API client can initialize
1386 // with a single filter to start the filtering process.
1387 void FilterChooser::runSingleFilter(unsigned startBit, unsigned numBit,
1390 Filter F(*this, startBit, numBit, true);
1391 Filters.push_back(F);
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.push_back(Filter(*this, StartBit, BitIndex - StartBit, true));
1402 else if (RA == ATTR_ALL_SET && !AllowMixed)
1403 Filters.push_back(Filter(*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);
1442 unsigned BitIndex, InsnIndex;
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 (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 bool populateInstruction(const CodeGenInstruction &CGI, unsigned Opc,
1704 std::map<unsigned, std::vector<OperandInfo> > &Operands){
1705 const Record &Def = *CGI.TheDef;
1706 // If all the bit positions are not specified; do not decode this instruction.
1707 // We are bound to fail! For proper disassembly, the well-known encoding bits
1708 // of the instruction must be fully specified.
1710 // This also removes pseudo instructions from considerations of disassembly,
1711 // which is a better design and less fragile than the name matchings.
1712 // Ignore "asm parser only" instructions.
1713 if (Def.getValueAsBit("isAsmParserOnly") ||
1714 Def.getValueAsBit("isCodeGenOnly"))
1717 BitsInit &Bits = getBitsField(Def, "Inst");
1718 if (Bits.allInComplete()) return false;
1720 std::vector<OperandInfo> InsnOperands;
1722 // If the instruction has specified a custom decoding hook, use that instead
1723 // of trying to auto-generate the decoder.
1724 std::string InstDecoder = Def.getValueAsString("DecoderMethod");
1725 if (InstDecoder != "") {
1726 InsnOperands.push_back(OperandInfo(InstDecoder));
1727 Operands[Opc] = InsnOperands;
1731 // Generate a description of the operand of the instruction that we know
1732 // how to decode automatically.
1733 // FIXME: We'll need to have a way to manually override this as needed.
1735 // Gather the outputs/inputs of the instruction, so we can find their
1736 // positions in the encoding. This assumes for now that they appear in the
1737 // MCInst in the order that they're listed.
1738 std::vector<std::pair<Init*, std::string> > InOutOperands;
1739 DagInit *Out = Def.getValueAsDag("OutOperandList");
1740 DagInit *In = Def.getValueAsDag("InOperandList");
1741 for (unsigned i = 0; i < Out->getNumArgs(); ++i)
1742 InOutOperands.push_back(std::make_pair(Out->getArg(i), Out->getArgName(i)));
1743 for (unsigned i = 0; i < In->getNumArgs(); ++i)
1744 InOutOperands.push_back(std::make_pair(In->getArg(i), In->getArgName(i)));
1746 // Search for tied operands, so that we can correctly instantiate
1747 // operands that are not explicitly represented in the encoding.
1748 std::map<std::string, std::string> TiedNames;
1749 for (unsigned i = 0; i < CGI.Operands.size(); ++i) {
1750 int tiedTo = CGI.Operands[i].getTiedRegister();
1752 TiedNames[InOutOperands[i].second] = InOutOperands[tiedTo].second;
1753 TiedNames[InOutOperands[tiedTo].second] = InOutOperands[i].second;
1757 // For each operand, see if we can figure out where it is encoded.
1758 for (std::vector<std::pair<Init*, std::string> >::const_iterator
1759 NI = InOutOperands.begin(), NE = InOutOperands.end(); NI != NE; ++NI) {
1760 std::string Decoder = "";
1762 // At this point, we can locate the field, but we need to know how to
1763 // interpret it. As a first step, require the target to provide callbacks
1764 // for decoding register classes.
1765 // FIXME: This need to be extended to handle instructions with custom
1766 // decoder methods, and operands with (simple) MIOperandInfo's.
1767 TypedInit *TI = dynamic_cast<TypedInit*>(NI->first);
1768 RecordRecTy *Type = dynamic_cast<RecordRecTy*>(TI->getType());
1769 Record *TypeRecord = Type->getRecord();
1771 if (TypeRecord->isSubClassOf("RegisterOperand"))
1772 TypeRecord = TypeRecord->getValueAsDef("RegClass");
1773 if (TypeRecord->isSubClassOf("RegisterClass")) {
1774 Decoder = "Decode" + TypeRecord->getName() + "RegisterClass";
1778 RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod");
1779 StringInit *String = DecoderString ?
1780 dynamic_cast<StringInit*>(DecoderString->getValue()) : 0;
1781 if (!isReg && String && String->getValue() != "")
1782 Decoder = String->getValue();
1784 OperandInfo OpInfo(Decoder);
1785 unsigned Base = ~0U;
1787 unsigned Offset = 0;
1789 for (unsigned bi = 0; bi < Bits.getNumBits(); ++bi) {
1791 VarBitInit *BI = dynamic_cast<VarBitInit*>(Bits.getBit(bi));
1793 Var = dynamic_cast<VarInit*>(BI->getVariable());
1795 Var = dynamic_cast<VarInit*>(Bits.getBit(bi));
1799 OpInfo.addField(Base, Width, Offset);
1807 if (Var->getName() != NI->second &&
1808 Var->getName() != TiedNames[NI->second]) {
1810 OpInfo.addField(Base, Width, Offset);
1821 Offset = BI ? BI->getBitNum() : 0;
1822 } else if (BI && BI->getBitNum() != Offset + Width) {
1823 OpInfo.addField(Base, Width, Offset);
1826 Offset = BI->getBitNum();
1833 OpInfo.addField(Base, Width, Offset);
1835 if (OpInfo.numFields() > 0)
1836 InsnOperands.push_back(OpInfo);
1839 Operands[Opc] = InsnOperands;
1844 // Dumps the instruction encoding bits.
1845 dumpBits(errs(), Bits);
1849 // Dumps the list of operand info.
1850 for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) {
1851 const CGIOperandList::OperandInfo &Info = CGI.Operands[i];
1852 const std::string &OperandName = Info.Name;
1853 const Record &OperandDef = *Info.Rec;
1855 errs() << "\t" << OperandName << " (" << OperandDef.getName() << ")\n";
1863 // emitFieldFromInstruction - Emit the templated helper function
1864 // fieldFromInstruction().
1865 static void emitFieldFromInstruction(formatted_raw_ostream &OS) {
1866 OS << "// Helper function for extracting fields from encoded instructions.\n"
1867 << "template<typename InsnType>\n"
1868 << "static InsnType fieldFromInstruction(InsnType insn, unsigned startBit,\n"
1869 << " unsigned numBits) {\n"
1870 << " assert(startBit + numBits <= (sizeof(InsnType)*8) &&\n"
1871 << " \"Instruction field out of bounds!\");\n"
1872 << " InsnType fieldMask;\n"
1873 << " if (numBits == sizeof(InsnType)*8)\n"
1874 << " fieldMask = (InsnType)(-1LL);\n"
1876 << " fieldMask = ((1 << numBits) - 1) << startBit;\n"
1877 << " return (insn & fieldMask) >> startBit;\n"
1881 // emitDecodeInstruction - Emit the templated helper function
1882 // decodeInstruction().
1883 static void emitDecodeInstruction(formatted_raw_ostream &OS) {
1884 OS << "template<typename InsnType>\n"
1885 << "static DecodeStatus decodeInstruction(const uint8_t DecodeTable[], MCInst &MI,\n"
1886 << " InsnType insn, uint64_t Address,\n"
1887 << " const void *DisAsm,\n"
1888 << " const MCSubtargetInfo &STI) {\n"
1889 << " uint64_t Bits = STI.getFeatureBits();\n"
1891 << " const uint8_t *Ptr = DecodeTable;\n"
1892 << " uint32_t CurFieldValue;\n"
1893 << " DecodeStatus S = MCDisassembler::Success;\n"
1895 << " ptrdiff_t Loc = Ptr - DecodeTable;\n"
1896 << " switch (*Ptr) {\n"
1898 << " errs() << Loc << \": Unexpected decode table opcode!\\n\";\n"
1899 << " return MCDisassembler::Fail;\n"
1900 << " case MCD::OPC_ExtractField: {\n"
1901 << " unsigned Start = *++Ptr;\n"
1902 << " unsigned Len = *++Ptr;\n"
1904 << " CurFieldValue = fieldFromInstruction(insn, Start, Len);\n"
1905 << " DEBUG(dbgs() << Loc << \": OPC_ExtractField(\" << Start << \", \"\n"
1906 << " << Len << \"): \" << CurFieldValue << \"\\n\");\n"
1909 << " case MCD::OPC_FilterValue: {\n"
1910 << " // Decode the field value.\n"
1911 << " unsigned Len;\n"
1912 << " InsnType Val = decodeULEB128(++Ptr, &Len);\n"
1914 << " // NumToSkip is a plain 16-bit integer.\n"
1915 << " unsigned NumToSkip = *Ptr++;\n"
1916 << " NumToSkip |= (*Ptr++) << 8;\n"
1918 << " // Perform the filter operation.\n"
1919 << " if (Val != CurFieldValue)\n"
1920 << " Ptr += NumToSkip;\n"
1921 << " DEBUG(dbgs() << Loc << \": OPC_FilterValue(\" << Val << \", \" << NumToSkip\n"
1922 << " << \"): \" << ((Val != CurFieldValue) ? \"FAIL:\" : \"PASS:\")\n"
1923 << " << \" continuing at \" << (Ptr - DecodeTable) << \"\\n\");\n"
1927 << " case MCD::OPC_CheckField: {\n"
1928 << " unsigned Start = *++Ptr;\n"
1929 << " unsigned Len = *++Ptr;\n"
1930 << " InsnType FieldValue = fieldFromInstruction(insn, Start, Len);\n"
1931 << " // Decode the field value.\n"
1932 << " uint32_t ExpectedValue = decodeULEB128(++Ptr, &Len);\n"
1934 << " // NumToSkip is a plain 16-bit integer.\n"
1935 << " unsigned NumToSkip = *Ptr++;\n"
1936 << " NumToSkip |= (*Ptr++) << 8;\n"
1938 << " // If the actual and expected values don't match, skip.\n"
1939 << " if (ExpectedValue != FieldValue)\n"
1940 << " Ptr += NumToSkip;\n"
1941 << " DEBUG(dbgs() << Loc << \": OPC_CheckField(\" << Start << \", \"\n"
1942 << " << Len << \", \" << ExpectedValue << \", \" << NumToSkip\n"
1943 << " << \"): FieldValue = \" << FieldValue << \", ExpectedValue = \"\n"
1944 << " << ExpectedValue << \": \"\n"
1945 << " << ((ExpectedValue == FieldValue) ? \"PASS\\n\" : \"FAIL\\n\"));\n"
1948 << " case MCD::OPC_CheckPredicate: {\n"
1949 << " unsigned Len;\n"
1950 << " // Decode the Predicate Index value.\n"
1951 << " unsigned PIdx = decodeULEB128(++Ptr, &Len);\n"
1953 << " // NumToSkip is a plain 16-bit integer.\n"
1954 << " unsigned NumToSkip = *Ptr++;\n"
1955 << " NumToSkip |= (*Ptr++) << 8;\n"
1956 << " // Check the predicate.\n"
1958 << " if (!(Pred = checkDecoderPredicate(PIdx, Bits)))\n"
1959 << " Ptr += NumToSkip;\n"
1961 << " DEBUG(dbgs() << Loc << \": OPC_CheckPredicate(\" << PIdx << \"): \"\n"
1962 << " << (Pred ? \"PASS\\n\" : \"FAIL\\n\"));\n"
1966 << " case MCD::OPC_Decode: {\n"
1967 << " unsigned Len;\n"
1968 << " // Decode the Opcode value.\n"
1969 << " unsigned Opc = decodeULEB128(++Ptr, &Len);\n"
1971 << " unsigned DecodeIdx = decodeULEB128(Ptr, &Len);\n"
1973 << " DEBUG(dbgs() << Loc << \": OPC_Decode: opcode \" << Opc\n"
1974 << " << \", using decoder \" << DecodeIdx << \"\\n\" );\n"
1975 << " DEBUG(dbgs() << \"----- DECODE SUCCESSFUL -----\\n\");\n"
1977 << " MI.setOpcode(Opc);\n"
1978 << " return decodeToMCInst(S, DecodeIdx, insn, MI, Address, DisAsm);\n"
1980 << " case MCD::OPC_SoftFail: {\n"
1981 << " // Decode the mask values.\n"
1982 << " unsigned Len;\n"
1983 << " InsnType PositiveMask = decodeULEB128(++Ptr, &Len);\n"
1985 << " InsnType NegativeMask = decodeULEB128(Ptr, &Len);\n"
1987 << " bool Fail = (insn & PositiveMask) || (~insn & NegativeMask);\n"
1989 << " S = MCDisassembler::SoftFail;\n"
1990 << " DEBUG(dbgs() << Loc << \": OPC_SoftFail: \" << (Fail ? \"FAIL\\n\":\"PASS\\n\"));\n"
1993 << " case MCD::OPC_Fail: {\n"
1994 << " DEBUG(dbgs() << Loc << \": OPC_Fail\\n\");\n"
1995 << " return MCDisassembler::Fail;\n"
1999 << " llvm_unreachable(\"bogosity detected in disassembler state machine!\");\n"
2003 // Emits disassembler code for instruction decoding.
2004 void FixedLenDecoderEmitter::run(raw_ostream &o) {
2005 formatted_raw_ostream OS(o);
2006 OS << "#include \"llvm/MC/MCInst.h\"\n";
2007 OS << "#include \"llvm/Support/Debug.h\"\n";
2008 OS << "#include \"llvm/Support/DataTypes.h\"\n";
2009 OS << "#include \"llvm/Support/LEB128.h\"\n";
2010 OS << "#include \"llvm/Support/raw_ostream.h\"\n";
2011 OS << "#include <assert.h>\n";
2013 OS << "namespace llvm {\n\n";
2015 emitFieldFromInstruction(OS);
2017 // Parameterize the decoders based on namespace and instruction width.
2018 NumberedInstructions = &Target.getInstructionsByEnumValue();
2019 std::map<std::pair<std::string, unsigned>,
2020 std::vector<unsigned> > OpcMap;
2021 std::map<unsigned, std::vector<OperandInfo> > Operands;
2023 for (unsigned i = 0; i < NumberedInstructions->size(); ++i) {
2024 const CodeGenInstruction *Inst = NumberedInstructions->at(i);
2025 const Record *Def = Inst->TheDef;
2026 unsigned Size = Def->getValueAsInt("Size");
2027 if (Def->getValueAsString("Namespace") == "TargetOpcode" ||
2028 Def->getValueAsBit("isPseudo") ||
2029 Def->getValueAsBit("isAsmParserOnly") ||
2030 Def->getValueAsBit("isCodeGenOnly"))
2033 std::string DecoderNamespace = Def->getValueAsString("DecoderNamespace");
2036 if (populateInstruction(*Inst, i, Operands)) {
2037 OpcMap[std::make_pair(DecoderNamespace, Size)].push_back(i);
2042 DecoderTableInfo TableInfo;
2043 std::set<unsigned> Sizes;
2044 for (std::map<std::pair<std::string, unsigned>,
2045 std::vector<unsigned> >::const_iterator
2046 I = OpcMap.begin(), E = OpcMap.end(); I != E; ++I) {
2047 // Emit the decoder for this namespace+width combination.
2048 FilterChooser FC(*NumberedInstructions, I->second, Operands,
2049 8*I->first.second, this);
2051 // The decode table is cleared for each top level decoder function. The
2052 // predicates and decoders themselves, however, are shared across all
2053 // decoders to give more opportunities for uniqueing.
2054 TableInfo.Table.clear();
2055 TableInfo.FixupStack.clear();
2056 TableInfo.Table.reserve(16384);
2057 TableInfo.FixupStack.push_back(FixupList());
2058 FC.emitTableEntries(TableInfo);
2059 // Any NumToSkip fixups in the top level scope can resolve to the
2060 // OPC_Fail at the end of the table.
2061 assert(TableInfo.FixupStack.size() == 1 && "fixup stack phasing error!");
2062 // Resolve any NumToSkip fixups in the current scope.
2063 resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),
2064 TableInfo.Table.size());
2065 TableInfo.FixupStack.clear();
2067 TableInfo.Table.push_back(MCD::OPC_Fail);
2069 // Print the table to the output stream.
2070 emitTable(OS, TableInfo.Table, 0, FC.getBitWidth(), I->first.first);
2074 // Emit the predicate function.
2075 emitPredicateFunction(OS, TableInfo.Predicates, 0);
2077 // Emit the decoder function.
2078 emitDecoderFunction(OS, TableInfo.Decoders, 0);
2080 // Emit the main entry point for the decoder, decodeInstruction().
2081 emitDecodeInstruction(OS);
2083 OS << "\n} // End llvm namespace\n";
2088 void EmitFixedLenDecoder(RecordKeeper &RK, raw_ostream &OS,
2089 std::string PredicateNamespace,
2090 std::string GPrefix,
2091 std::string GPostfix,
2095 FixedLenDecoderEmitter(RK, PredicateNamespace, GPrefix, GPostfix,
2096 ROK, RFail, L).run(OS);
2099 } // End llvm namespace