Fix ambiguous call to make_unique and clang-format.
[oota-llvm.git] / utils / TableGen / FixedLenDecoderEmitter.cpp
1 //===------------ FixedLenDecoderEmitter.cpp - Decoder Generator ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // It contains the tablegen backend that emits the decoder functions for
11 // targets with fixed length instruction set.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "CodeGenTarget.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/ADT/Twine.h"
21 #include "llvm/MC/MCFixedLenDisassembler.h"
22 #include "llvm/Support/DataTypes.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/FormattedStream.h"
25 #include "llvm/Support/LEB128.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/TableGen/Error.h"
28 #include "llvm/TableGen/Record.h"
29 #include <map>
30 #include <string>
31 #include <vector>
32
33 using namespace llvm;
34
35 #define DEBUG_TYPE "decoder-emitter"
36
37 namespace {
38 struct EncodingField {
39   unsigned Base, Width, Offset;
40   EncodingField(unsigned B, unsigned W, unsigned O)
41     : Base(B), Width(W), Offset(O) { }
42 };
43
44 struct OperandInfo {
45   std::vector<EncodingField> Fields;
46   std::string Decoder;
47
48   OperandInfo(std::string D)
49     : Decoder(D) { }
50
51   void addField(unsigned Base, unsigned Width, unsigned Offset) {
52     Fields.push_back(EncodingField(Base, Width, Offset));
53   }
54
55   unsigned numFields() const { return Fields.size(); }
56
57   typedef std::vector<EncodingField>::const_iterator const_iterator;
58
59   const_iterator begin() const { return Fields.begin(); }
60   const_iterator end() const   { return Fields.end();   }
61 };
62
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 {
70   DecoderTable Table;
71   FixupScopeList FixupStack;
72   PredicateSet Predicates;
73   DecoderSet Decoders;
74 };
75
76 } // End anonymous namespace
77
78 namespace {
79 class FixedLenDecoderEmitter {
80   const std::vector<const CodeGenInstruction*> *NumberedInstructions;
81 public:
82
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",
92                          std::string L        = "") :
93     Target(R),
94     PredicateNamespace(PredicateNamespace),
95     GuardPrefix(GPrefix), GuardPostfix(GPostfix),
96     ReturnOK(ROK), ReturnFail(RFail), Locals(L) {}
97
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;
108
109   // run - Output the code emitter
110   void run(raw_ostream &o);
111
112 private:
113   CodeGenTarget Target;
114 public:
115   std::string PredicateNamespace;
116   std::string GuardPrefix, GuardPostfix;
117   std::string ReturnOK, ReturnFail;
118   std::string Locals;
119 };
120 } // End anonymous namespace
121
122 // The set (BIT_TRUE, BIT_FALSE, BIT_UNSET) represents a ternary logic system
123 // for a bit value.
124 //
125 // BIT_UNFILTERED is used as the init value for a filter position.  It is used
126 // only for filter processings.
127 typedef enum {
128   BIT_TRUE,      // '1'
129   BIT_FALSE,     // '0'
130   BIT_UNSET,     // '?'
131   BIT_UNFILTERED // unfiltered
132 } bit_value_t;
133
134 static bool ValueSet(bit_value_t V) {
135   return (V == BIT_TRUE || V == BIT_FALSE);
136 }
137 static bool ValueNotSet(bit_value_t V) {
138   return (V == BIT_UNSET);
139 }
140 static int Value(bit_value_t V) {
141   return ValueNotSet(V) ? -1 : (V == BIT_FALSE ? 0 : 1);
142 }
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;
146
147   // The bit is uninitialized.
148   return BIT_UNSET;
149 }
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)) {
154     case BIT_TRUE:
155       o << "1";
156       break;
157     case BIT_FALSE:
158       o << "0";
159       break;
160     case BIT_UNSET:
161       o << "_";
162       break;
163     default:
164       llvm_unreachable("unexpected return value from bitFromBits");
165     }
166   }
167 }
168
169 static BitsInit &getBitsField(const Record &def, const char *str) {
170   BitsInit *bits = def.getValueAsBitsInit(str);
171   return *bits;
172 }
173
174 // Forward declaration.
175 namespace {
176 class FilterChooser;
177 } // End anonymous namespace
178
179 // Representation of the instruction to work on.
180 typedef std::vector<bit_value_t> insn_t;
181
182 /// Filter - Filter works with FilterChooser to produce the decoding tree for
183 /// the ISA.
184 ///
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.
190 ///
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.
195 ///
196 /// An example of a conflict is
197 ///
198 /// Conflict:
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____
208 ///
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.
212 ///
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.
218 namespace {
219 class Filter {
220 protected:
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
225
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;
228
229   // Set of uid's with non-constant segment values.
230   std::vector<unsigned> VariableInstructions;
231
232   // Map of well-known segment value to its delegate.
233   std::map<unsigned, std::unique_ptr<const FilterChooser>> FilterChooserMap;
234
235   // Number of instructions which fall under FilteredInstructions category.
236   unsigned NumFiltered;
237
238   // Keeps track of the last opcode in the filtered bucket.
239   unsigned LastOpcFiltered;
240
241 public:
242   unsigned getNumFiltered() const { return NumFiltered; }
243   unsigned getSingletonOpc() const {
244     assert(NumFiltered == 1);
245     return LastOpcFiltered;
246   }
247   // Return the filter chooser for the group of instructions without constant
248   // segment values.
249   const FilterChooser &getVariableFC() const {
250     assert(NumFiltered == 1);
251     assert(FilterChooserMap.size() == 1);
252     return *(FilterChooserMap.find((unsigned)-1)->second);
253   }
254
255   Filter(Filter &&f);
256   Filter(FilterChooser &owner, unsigned startBit, unsigned numBits, bool mixed);
257
258   ~Filter();
259
260   // Divides the decoding task into sub tasks and delegates them to the
261   // inferior FilterChooser's.
262   //
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.
266   void recurse();
267
268   // Emit table entries to decode instructions given a segment or segments of
269   // bits.
270   void emitTableEntry(DecoderTableInfo &TableInfo) const;
271
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
277
278 // These are states of our finite state machines used in FilterChooser's
279 // filterProcessor() which produces the filter candidates to use.
280 typedef enum {
281   ATTR_NONE,
282   ATTR_FILTERED,
283   ATTR_ALL_SET,
284   ATTR_ALL_UNSET,
285   ATTR_MIXED
286 } bitAttr_t;
287
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.
290 ///
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.
295 ///
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
298 /// processings.
299 ///
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.
303 namespace {
304 class FilterChooser {
305 protected:
306   friend class Filter;
307
308   // Vector of codegen instructions to choose our filter.
309   const std::vector<const CodeGenInstruction*> &AllInstructions;
310
311   // Vector of uid's for this filter chooser to work on.
312   const std::vector<unsigned> &Opcodes;
313
314   // Lookup table for the operand decoding of instructions.
315   const std::map<unsigned, std::vector<OperandInfo> > &Operands;
316
317   // Vector of candidate filters.
318   std::vector<Filter> Filters;
319
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;
323
324   // Links to the FilterChooser above us in the decoding tree.
325   const FilterChooser *Parent;
326
327   // Index of the best filter from Filters.
328   int BestIndex;
329
330   // Width of instructions
331   unsigned BitWidth;
332
333   // Parent emitter
334   const FixedLenDecoderEmitter *Emitter;
335
336   FilterChooser(const FilterChooser &) LLVM_DELETED_FUNCTION;
337   void operator=(const FilterChooser &) LLVM_DELETED_FUNCTION;
338 public:
339
340   FilterChooser(const std::vector<const CodeGenInstruction*> &Insts,
341                 const std::vector<unsigned> &IDs,
342                 const std::map<unsigned, std::vector<OperandInfo> > &Ops,
343                 unsigned BW,
344                 const FixedLenDecoderEmitter *E)
345     : AllInstructions(Insts), Opcodes(IDs), Operands(Ops), Filters(),
346       Parent(nullptr), BestIndex(-1), BitWidth(BW), Emitter(E) {
347     for (unsigned i = 0; i < BitWidth; ++i)
348       FilterBitValues.push_back(BIT_UNFILTERED);
349
350     doFilter();
351   }
352
353   FilterChooser(const std::vector<const CodeGenInstruction*> &Insts,
354                 const std::vector<unsigned> &IDs,
355                 const std::map<unsigned, std::vector<OperandInfo> > &Ops,
356                 const std::vector<bit_value_t> &ParentFilterBitValues,
357                 const FilterChooser &parent)
358     : AllInstructions(Insts), Opcodes(IDs), Operands(Ops),
359       Filters(), FilterBitValues(ParentFilterBitValues),
360       Parent(&parent), BestIndex(-1), BitWidth(parent.BitWidth),
361       Emitter(parent.Emitter) {
362     doFilter();
363   }
364
365   unsigned getBitWidth() const { return BitWidth; }
366
367 protected:
368   // Populates the insn given the uid.
369   void insnWithID(insn_t &Insn, unsigned Opcode) const {
370     BitsInit &Bits = getBitsField(*AllInstructions[Opcode]->TheDef, "Inst");
371
372     // We may have a SoftFail bitmask, which specifies a mask where an encoding
373     // may differ from the value in "Inst" and yet still be valid, but the
374     // disassembler should return SoftFail instead of Success.
375     //
376     // This is used for marking UNPREDICTABLE instructions in the ARM world.
377     BitsInit *SFBits =
378       AllInstructions[Opcode]->TheDef->getValueAsBitsInit("SoftFail");
379
380     for (unsigned i = 0; i < BitWidth; ++i) {
381       if (SFBits && bitFromBits(*SFBits, i) == BIT_TRUE)
382         Insn.push_back(BIT_UNSET);
383       else
384         Insn.push_back(bitFromBits(Bits, i));
385     }
386   }
387
388   // Returns the record name.
389   const std::string &nameWithID(unsigned Opcode) const {
390     return AllInstructions[Opcode]->TheDef->getName();
391   }
392
393   // Populates the field of the insn given the start position and the number of
394   // consecutive bits to scan for.
395   //
396   // Returns false if there exists any uninitialized bit value in the range.
397   // Returns true, otherwise.
398   bool fieldFromInsn(uint64_t &Field, insn_t &Insn, unsigned StartBit,
399                      unsigned NumBits) const;
400
401   /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
402   /// filter array as a series of chars.
403   void dumpFilterArray(raw_ostream &o,
404                        const std::vector<bit_value_t> & filter) const;
405
406   /// dumpStack - dumpStack traverses the filter chooser chain and calls
407   /// dumpFilterArray on each filter chooser up to the top level one.
408   void dumpStack(raw_ostream &o, const char *prefix) const;
409
410   Filter &bestFilter() {
411     assert(BestIndex != -1 && "BestIndex not set");
412     return Filters[BestIndex];
413   }
414
415   // Called from Filter::recurse() when singleton exists.  For debug purpose.
416   void SingletonExists(unsigned Opc) const;
417
418   bool PositionFiltered(unsigned i) const {
419     return ValueSet(FilterBitValues[i]);
420   }
421
422   // Calculates the island(s) needed to decode the instruction.
423   // This returns a lit of undecoded bits of an instructions, for example,
424   // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
425   // decoded bits in order to verify that the instruction matches the Opcode.
426   unsigned getIslands(std::vector<unsigned> &StartBits,
427                       std::vector<unsigned> &EndBits,
428                       std::vector<uint64_t> &FieldVals,
429                       const insn_t &Insn) const;
430
431   // Emits code to check the Predicates member of an instruction are true.
432   // Returns true if predicate matches were emitted, false otherwise.
433   bool emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
434                           unsigned Opc) const;
435
436   bool doesOpcodeNeedPredicate(unsigned Opc) const;
437   unsigned getPredicateIndex(DecoderTableInfo &TableInfo, StringRef P) const;
438   void emitPredicateTableEntry(DecoderTableInfo &TableInfo,
439                                unsigned Opc) const;
440
441   void emitSoftFailTableEntry(DecoderTableInfo &TableInfo,
442                               unsigned Opc) const;
443
444   // Emits table entries to decode the singleton.
445   void emitSingletonTableEntry(DecoderTableInfo &TableInfo,
446                                unsigned Opc) const;
447
448   // Emits code to decode the singleton, and then to decode the rest.
449   void emitSingletonTableEntry(DecoderTableInfo &TableInfo,
450                                const Filter &Best) const;
451
452   void emitBinaryParser(raw_ostream &o, unsigned &Indentation,
453                         const OperandInfo &OpInfo) const;
454
455   void emitDecoder(raw_ostream &OS, unsigned Indentation, unsigned Opc) const;
456   unsigned getDecoderIndex(DecoderSet &Decoders, unsigned Opc) const;
457
458   // Assign a single filter and run with it.
459   void runSingleFilter(unsigned startBit, unsigned numBit, bool mixed);
460
461   // reportRegion is a helper function for filterProcessor to mark a region as
462   // eligible for use as a filter region.
463   void reportRegion(bitAttr_t RA, unsigned StartBit, unsigned BitIndex,
464                     bool AllowMixed);
465
466   // FilterProcessor scans the well-known encoding bits of the instructions and
467   // builds up a list of candidate filters.  It chooses the best filter and
468   // recursively descends down the decoding tree.
469   bool filterProcessor(bool AllowMixed, bool Greedy = true);
470
471   // Decides on the best configuration of filter(s) to use in order to decode
472   // the instructions.  A conflict of instructions may occur, in which case we
473   // dump the conflict set to the standard error.
474   void doFilter();
475
476 public:
477   // emitTableEntries - Emit state machine entries to decode our share of
478   // instructions.
479   void emitTableEntries(DecoderTableInfo &TableInfo) const;
480 };
481 } // End anonymous namespace
482
483 ///////////////////////////
484 //                       //
485 // Filter Implementation //
486 //                       //
487 ///////////////////////////
488
489 Filter::Filter(Filter &&f)
490   : Owner(f.Owner), StartBit(f.StartBit), NumBits(f.NumBits), Mixed(f.Mixed),
491     FilteredInstructions(std::move(f.FilteredInstructions)),
492     VariableInstructions(std::move(f.VariableInstructions)),
493     FilterChooserMap(std::move(f.FilterChooserMap)), NumFiltered(f.NumFiltered),
494     LastOpcFiltered(f.LastOpcFiltered) {
495 }
496
497 Filter::Filter(FilterChooser &owner, unsigned startBit, unsigned numBits,
498                bool mixed)
499   : Owner(&owner), StartBit(startBit), NumBits(numBits), Mixed(mixed) {
500   assert(StartBit + NumBits - 1 < Owner->BitWidth);
501
502   NumFiltered = 0;
503   LastOpcFiltered = 0;
504
505   for (unsigned i = 0, e = Owner->Opcodes.size(); i != e; ++i) {
506     insn_t Insn;
507
508     // Populates the insn given the uid.
509     Owner->insnWithID(Insn, Owner->Opcodes[i]);
510
511     uint64_t Field;
512     // Scans the segment for possibly well-specified encoding bits.
513     bool ok = Owner->fieldFromInsn(Field, Insn, StartBit, NumBits);
514
515     if (ok) {
516       // The encoding bits are well-known.  Lets add the uid of the
517       // instruction into the bucket keyed off the constant field value.
518       LastOpcFiltered = Owner->Opcodes[i];
519       FilteredInstructions[Field].push_back(LastOpcFiltered);
520       ++NumFiltered;
521     } else {
522       // Some of the encoding bit(s) are unspecified.  This contributes to
523       // one additional member of "Variable" instructions.
524       VariableInstructions.push_back(Owner->Opcodes[i]);
525     }
526   }
527
528   assert((FilteredInstructions.size() + VariableInstructions.size() > 0)
529          && "Filter returns no instruction categories");
530 }
531
532 Filter::~Filter() {
533 }
534
535 // Divides the decoding task into sub tasks and delegates them to the
536 // inferior FilterChooser's.
537 //
538 // A special case arises when there's only one entry in the filtered
539 // instructions.  In order to unambiguously decode the singleton, we need to
540 // match the remaining undecoded encoding bits against the singleton.
541 void Filter::recurse() {
542   std::map<uint64_t, std::vector<unsigned> >::const_iterator mapIterator;
543
544   // Starts by inheriting our parent filter chooser's filter bit values.
545   std::vector<bit_value_t> BitValueArray(Owner->FilterBitValues);
546
547   if (VariableInstructions.size()) {
548     // Conservatively marks each segment position as BIT_UNSET.
549     for (unsigned bitIndex = 0; bitIndex < NumBits; ++bitIndex)
550       BitValueArray[StartBit + bitIndex] = BIT_UNSET;
551
552     // Delegates to an inferior filter chooser for further processing on this
553     // group of instructions whose segment values are variable.
554     FilterChooserMap.insert(
555         std::make_pair(-1U, llvm::make_unique<FilterChooser>(
556                                 Owner->AllInstructions, VariableInstructions,
557                                 Owner->Operands, BitValueArray, *Owner)));
558   }
559
560   // No need to recurse for a singleton filtered instruction.
561   // See also Filter::emit*().
562   if (getNumFiltered() == 1) {
563     //Owner->SingletonExists(LastOpcFiltered);
564     assert(FilterChooserMap.size() == 1);
565     return;
566   }
567
568   // Otherwise, create sub choosers.
569   for (mapIterator = FilteredInstructions.begin();
570        mapIterator != FilteredInstructions.end();
571        mapIterator++) {
572
573     // Marks all the segment positions with either BIT_TRUE or BIT_FALSE.
574     for (unsigned bitIndex = 0; bitIndex < NumBits; ++bitIndex) {
575       if (mapIterator->first & (1ULL << bitIndex))
576         BitValueArray[StartBit + bitIndex] = BIT_TRUE;
577       else
578         BitValueArray[StartBit + bitIndex] = BIT_FALSE;
579     }
580
581     // Delegates to an inferior filter chooser for further processing on this
582     // category of instructions.
583     FilterChooserMap.insert(std::make_pair(
584         mapIterator->first, llvm::make_unique<FilterChooser>(
585                                 Owner->AllInstructions, mapIterator->second,
586                                 Owner->Operands, BitValueArray, *Owner)));
587   }
588 }
589
590 static void resolveTableFixups(DecoderTable &Table, const FixupList &Fixups,
591                                uint32_t DestIdx) {
592   // Any NumToSkip fixups in the current scope can resolve to the
593   // current location.
594   for (FixupList::const_reverse_iterator I = Fixups.rbegin(),
595                                          E = Fixups.rend();
596        I != E; ++I) {
597     // Calculate the distance from the byte following the fixup entry byte
598     // to the destination. The Target is calculated from after the 16-bit
599     // NumToSkip entry itself, so subtract two  from the displacement here
600     // to account for that.
601     uint32_t FixupIdx = *I;
602     uint32_t Delta = DestIdx - FixupIdx - 2;
603     // Our NumToSkip entries are 16-bits. Make sure our table isn't too
604     // big.
605     assert(Delta < 65536U && "disassembler decoding table too large!");
606     Table[FixupIdx] = (uint8_t)Delta;
607     Table[FixupIdx + 1] = (uint8_t)(Delta >> 8);
608   }
609 }
610
611 // Emit table entries to decode instructions given a segment or segments
612 // of bits.
613 void Filter::emitTableEntry(DecoderTableInfo &TableInfo) const {
614   TableInfo.Table.push_back(MCD::OPC_ExtractField);
615   TableInfo.Table.push_back(StartBit);
616   TableInfo.Table.push_back(NumBits);
617
618   // A new filter entry begins a new scope for fixup resolution.
619   TableInfo.FixupStack.push_back(FixupList());
620
621   std::map<unsigned,
622            std::unique_ptr<const FilterChooser>>::const_iterator filterIterator;
623
624   DecoderTable &Table = TableInfo.Table;
625
626   size_t PrevFilter = 0;
627   bool HasFallthrough = false;
628   for (filterIterator = FilterChooserMap.begin();
629        filterIterator != FilterChooserMap.end();
630        filterIterator++) {
631     // Field value -1 implies a non-empty set of variable instructions.
632     // See also recurse().
633     if (filterIterator->first == (unsigned)-1) {
634       HasFallthrough = true;
635
636       // Each scope should always have at least one filter value to check
637       // for.
638       assert(PrevFilter != 0 && "empty filter set!");
639       FixupList &CurScope = TableInfo.FixupStack.back();
640       // Resolve any NumToSkip fixups in the current scope.
641       resolveTableFixups(Table, CurScope, Table.size());
642       CurScope.clear();
643       PrevFilter = 0;  // Don't re-process the filter's fallthrough.
644     } else {
645       Table.push_back(MCD::OPC_FilterValue);
646       // Encode and emit the value to filter against.
647       uint8_t Buffer[8];
648       unsigned Len = encodeULEB128(filterIterator->first, Buffer);
649       Table.insert(Table.end(), Buffer, Buffer + Len);
650       // Reserve space for the NumToSkip entry. We'll backpatch the value
651       // later.
652       PrevFilter = Table.size();
653       Table.push_back(0);
654       Table.push_back(0);
655     }
656
657     // We arrive at a category of instructions with the same segment value.
658     // Now delegate to the sub filter chooser for further decodings.
659     // The case may fallthrough, which happens if the remaining well-known
660     // encoding bits do not match exactly.
661     filterIterator->second->emitTableEntries(TableInfo);
662
663     // Now that we've emitted the body of the handler, update the NumToSkip
664     // of the filter itself to be able to skip forward when false. Subtract
665     // two as to account for the width of the NumToSkip field itself.
666     if (PrevFilter) {
667       uint32_t NumToSkip = Table.size() - PrevFilter - 2;
668       assert(NumToSkip < 65536U && "disassembler decoding table too large!");
669       Table[PrevFilter] = (uint8_t)NumToSkip;
670       Table[PrevFilter + 1] = (uint8_t)(NumToSkip >> 8);
671     }
672   }
673
674   // Any remaining unresolved fixups bubble up to the parent fixup scope.
675   assert(TableInfo.FixupStack.size() > 1 && "fixup stack underflow!");
676   FixupScopeList::iterator Source = TableInfo.FixupStack.end() - 1;
677   FixupScopeList::iterator Dest = Source - 1;
678   Dest->insert(Dest->end(), Source->begin(), Source->end());
679   TableInfo.FixupStack.pop_back();
680
681   // If there is no fallthrough, then the final filter should get fixed
682   // up according to the enclosing scope rather than the current position.
683   if (!HasFallthrough)
684     TableInfo.FixupStack.back().push_back(PrevFilter);
685 }
686
687 // Returns the number of fanout produced by the filter.  More fanout implies
688 // the filter distinguishes more categories of instructions.
689 unsigned Filter::usefulness() const {
690   if (VariableInstructions.size())
691     return FilteredInstructions.size();
692   else
693     return FilteredInstructions.size() + 1;
694 }
695
696 //////////////////////////////////
697 //                              //
698 // Filterchooser Implementation //
699 //                              //
700 //////////////////////////////////
701
702 // Emit the decoder state machine table.
703 void FixedLenDecoderEmitter::emitTable(formatted_raw_ostream &OS,
704                                        DecoderTable &Table,
705                                        unsigned Indentation,
706                                        unsigned BitWidth,
707                                        StringRef Namespace) const {
708   OS.indent(Indentation) << "static const uint8_t DecoderTable" << Namespace
709     << BitWidth << "[] = {\n";
710
711   Indentation += 2;
712
713   // FIXME: We may be able to use the NumToSkip values to recover
714   // appropriate indentation levels.
715   DecoderTable::const_iterator I = Table.begin();
716   DecoderTable::const_iterator E = Table.end();
717   while (I != E) {
718     assert (I < E && "incomplete decode table entry!");
719
720     uint64_t Pos = I - Table.begin();
721     OS << "/* " << Pos << " */";
722     OS.PadToColumn(12);
723
724     switch (*I) {
725     default:
726       PrintFatalError("invalid decode table opcode");
727     case MCD::OPC_ExtractField: {
728       ++I;
729       unsigned Start = *I++;
730       unsigned Len = *I++;
731       OS.indent(Indentation) << "MCD::OPC_ExtractField, " << Start << ", "
732         << Len << ",  // Inst{";
733       if (Len > 1)
734         OS << (Start + Len - 1) << "-";
735       OS << Start << "} ...\n";
736       break;
737     }
738     case MCD::OPC_FilterValue: {
739       ++I;
740       OS.indent(Indentation) << "MCD::OPC_FilterValue, ";
741       // The filter value is ULEB128 encoded.
742       while (*I >= 128)
743         OS << utostr(*I++) << ", ";
744       OS << utostr(*I++) << ", ";
745
746       // 16-bit numtoskip value.
747       uint8_t Byte = *I++;
748       uint32_t NumToSkip = Byte;
749       OS << utostr(Byte) << ", ";
750       Byte = *I++;
751       OS << utostr(Byte) << ", ";
752       NumToSkip |= Byte << 8;
753       OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
754       break;
755     }
756     case MCD::OPC_CheckField: {
757       ++I;
758       unsigned Start = *I++;
759       unsigned Len = *I++;
760       OS.indent(Indentation) << "MCD::OPC_CheckField, " << Start << ", "
761         << Len << ", ";// << Val << ", " << NumToSkip << ",\n";
762       // ULEB128 encoded field value.
763       for (; *I >= 128; ++I)
764         OS << utostr(*I) << ", ";
765       OS << utostr(*I++) << ", ";
766       // 16-bit numtoskip value.
767       uint8_t Byte = *I++;
768       uint32_t NumToSkip = Byte;
769       OS << utostr(Byte) << ", ";
770       Byte = *I++;
771       OS << utostr(Byte) << ", ";
772       NumToSkip |= Byte << 8;
773       OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
774       break;
775     }
776     case MCD::OPC_CheckPredicate: {
777       ++I;
778       OS.indent(Indentation) << "MCD::OPC_CheckPredicate, ";
779       for (; *I >= 128; ++I)
780         OS << utostr(*I) << ", ";
781       OS << utostr(*I++) << ", ";
782
783       // 16-bit numtoskip value.
784       uint8_t Byte = *I++;
785       uint32_t NumToSkip = Byte;
786       OS << utostr(Byte) << ", ";
787       Byte = *I++;
788       OS << utostr(Byte) << ", ";
789       NumToSkip |= Byte << 8;
790       OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
791       break;
792     }
793     case MCD::OPC_Decode: {
794       ++I;
795       // Extract the ULEB128 encoded Opcode to a buffer.
796       uint8_t Buffer[8], *p = Buffer;
797       while ((*p++ = *I++) >= 128)
798         assert((p - Buffer) <= (ptrdiff_t)sizeof(Buffer)
799                && "ULEB128 value too large!");
800       // Decode the Opcode value.
801       unsigned Opc = decodeULEB128(Buffer);
802       OS.indent(Indentation) << "MCD::OPC_Decode, ";
803       for (p = Buffer; *p >= 128; ++p)
804         OS << utostr(*p) << ", ";
805       OS << utostr(*p) << ", ";
806
807       // Decoder index.
808       for (; *I >= 128; ++I)
809         OS << utostr(*I) << ", ";
810       OS << utostr(*I++) << ", ";
811
812       OS << "// Opcode: "
813          << NumberedInstructions->at(Opc)->TheDef->getName() << "\n";
814       break;
815     }
816     case MCD::OPC_SoftFail: {
817       ++I;
818       OS.indent(Indentation) << "MCD::OPC_SoftFail";
819       // Positive mask
820       uint64_t Value = 0;
821       unsigned Shift = 0;
822       do {
823         OS << ", " << utostr(*I);
824         Value += (*I & 0x7f) << Shift;
825         Shift += 7;
826       } while (*I++ >= 128);
827       if (Value > 127)
828         OS << " /* 0x" << utohexstr(Value) << " */";
829       // Negative mask
830       Value = 0;
831       Shift = 0;
832       do {
833         OS << ", " << utostr(*I);
834         Value += (*I & 0x7f) << Shift;
835         Shift += 7;
836       } while (*I++ >= 128);
837       if (Value > 127)
838         OS << " /* 0x" << utohexstr(Value) << " */";
839       OS << ",\n";
840       break;
841     }
842     case MCD::OPC_Fail: {
843       ++I;
844       OS.indent(Indentation) << "MCD::OPC_Fail,\n";
845       break;
846     }
847     }
848   }
849   OS.indent(Indentation) << "0\n";
850
851   Indentation -= 2;
852
853   OS.indent(Indentation) << "};\n\n";
854 }
855
856 void FixedLenDecoderEmitter::
857 emitPredicateFunction(formatted_raw_ostream &OS, PredicateSet &Predicates,
858                       unsigned Indentation) const {
859   // The predicate function is just a big switch statement based on the
860   // input predicate index.
861   OS.indent(Indentation) << "static bool checkDecoderPredicate(unsigned Idx, "
862     << "uint64_t Bits) {\n";
863   Indentation += 2;
864   if (!Predicates.empty()) {
865     OS.indent(Indentation) << "switch (Idx) {\n";
866     OS.indent(Indentation) << "default: llvm_unreachable(\"Invalid index!\");\n";
867     unsigned Index = 0;
868     for (PredicateSet::const_iterator I = Predicates.begin(), E = Predicates.end();
869          I != E; ++I, ++Index) {
870       OS.indent(Indentation) << "case " << Index << ":\n";
871       OS.indent(Indentation+2) << "return (" << *I << ");\n";
872     }
873     OS.indent(Indentation) << "}\n";
874   } else {
875     // No case statement to emit
876     OS.indent(Indentation) << "llvm_unreachable(\"Invalid index!\");\n";
877   }
878   Indentation -= 2;
879   OS.indent(Indentation) << "}\n\n";
880 }
881
882 void FixedLenDecoderEmitter::
883 emitDecoderFunction(formatted_raw_ostream &OS, DecoderSet &Decoders,
884                     unsigned Indentation) const {
885   // The decoder function is just a big switch statement based on the
886   // input decoder index.
887   OS.indent(Indentation) << "template<typename InsnType>\n";
888   OS.indent(Indentation) << "static DecodeStatus decodeToMCInst(DecodeStatus S,"
889     << " unsigned Idx, InsnType insn, MCInst &MI,\n";
890   OS.indent(Indentation) << "                                   uint64_t "
891     << "Address, const void *Decoder) {\n";
892   Indentation += 2;
893   OS.indent(Indentation) << "InsnType tmp;\n";
894   OS.indent(Indentation) << "switch (Idx) {\n";
895   OS.indent(Indentation) << "default: llvm_unreachable(\"Invalid index!\");\n";
896   unsigned Index = 0;
897   for (DecoderSet::const_iterator I = Decoders.begin(), E = Decoders.end();
898        I != E; ++I, ++Index) {
899     OS.indent(Indentation) << "case " << Index << ":\n";
900     OS << *I;
901     OS.indent(Indentation+2) << "return S;\n";
902   }
903   OS.indent(Indentation) << "}\n";
904   Indentation -= 2;
905   OS.indent(Indentation) << "}\n\n";
906 }
907
908 // Populates the field of the insn given the start position and the number of
909 // consecutive bits to scan for.
910 //
911 // Returns false if and on the first uninitialized bit value encountered.
912 // Returns true, otherwise.
913 bool FilterChooser::fieldFromInsn(uint64_t &Field, insn_t &Insn,
914                                   unsigned StartBit, unsigned NumBits) const {
915   Field = 0;
916
917   for (unsigned i = 0; i < NumBits; ++i) {
918     if (Insn[StartBit + i] == BIT_UNSET)
919       return false;
920
921     if (Insn[StartBit + i] == BIT_TRUE)
922       Field = Field | (1ULL << i);
923   }
924
925   return true;
926 }
927
928 /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
929 /// filter array as a series of chars.
930 void FilterChooser::dumpFilterArray(raw_ostream &o,
931                                  const std::vector<bit_value_t> &filter) const {
932   for (unsigned bitIndex = BitWidth; bitIndex > 0; bitIndex--) {
933     switch (filter[bitIndex - 1]) {
934     case BIT_UNFILTERED:
935       o << ".";
936       break;
937     case BIT_UNSET:
938       o << "_";
939       break;
940     case BIT_TRUE:
941       o << "1";
942       break;
943     case BIT_FALSE:
944       o << "0";
945       break;
946     }
947   }
948 }
949
950 /// dumpStack - dumpStack traverses the filter chooser chain and calls
951 /// dumpFilterArray on each filter chooser up to the top level one.
952 void FilterChooser::dumpStack(raw_ostream &o, const char *prefix) const {
953   const FilterChooser *current = this;
954
955   while (current) {
956     o << prefix;
957     dumpFilterArray(o, current->FilterBitValues);
958     o << '\n';
959     current = current->Parent;
960   }
961 }
962
963 // Called from Filter::recurse() when singleton exists.  For debug purpose.
964 void FilterChooser::SingletonExists(unsigned Opc) const {
965   insn_t Insn0;
966   insnWithID(Insn0, Opc);
967
968   errs() << "Singleton exists: " << nameWithID(Opc)
969          << " with its decoding dominating ";
970   for (unsigned i = 0; i < Opcodes.size(); ++i) {
971     if (Opcodes[i] == Opc) continue;
972     errs() << nameWithID(Opcodes[i]) << ' ';
973   }
974   errs() << '\n';
975
976   dumpStack(errs(), "\t\t");
977   for (unsigned i = 0; i < Opcodes.size(); ++i) {
978     const std::string &Name = nameWithID(Opcodes[i]);
979
980     errs() << '\t' << Name << " ";
981     dumpBits(errs(),
982              getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
983     errs() << '\n';
984   }
985 }
986
987 // Calculates the island(s) needed to decode the instruction.
988 // This returns a list of undecoded bits of an instructions, for example,
989 // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
990 // decoded bits in order to verify that the instruction matches the Opcode.
991 unsigned FilterChooser::getIslands(std::vector<unsigned> &StartBits,
992                                    std::vector<unsigned> &EndBits,
993                                    std::vector<uint64_t> &FieldVals,
994                                    const insn_t &Insn) const {
995   unsigned Num, BitNo;
996   Num = BitNo = 0;
997
998   uint64_t FieldVal = 0;
999
1000   // 0: Init
1001   // 1: Water (the bit value does not affect decoding)
1002   // 2: Island (well-known bit value needed for decoding)
1003   int State = 0;
1004   int Val = -1;
1005
1006   for (unsigned i = 0; i < BitWidth; ++i) {
1007     Val = Value(Insn[i]);
1008     bool Filtered = PositionFiltered(i);
1009     switch (State) {
1010     default: llvm_unreachable("Unreachable code!");
1011     case 0:
1012     case 1:
1013       if (Filtered || Val == -1)
1014         State = 1; // Still in Water
1015       else {
1016         State = 2; // Into the Island
1017         BitNo = 0;
1018         StartBits.push_back(i);
1019         FieldVal = Val;
1020       }
1021       break;
1022     case 2:
1023       if (Filtered || Val == -1) {
1024         State = 1; // Into the Water
1025         EndBits.push_back(i - 1);
1026         FieldVals.push_back(FieldVal);
1027         ++Num;
1028       } else {
1029         State = 2; // Still in Island
1030         ++BitNo;
1031         FieldVal = FieldVal | Val << BitNo;
1032       }
1033       break;
1034     }
1035   }
1036   // If we are still in Island after the loop, do some housekeeping.
1037   if (State == 2) {
1038     EndBits.push_back(BitWidth - 1);
1039     FieldVals.push_back(FieldVal);
1040     ++Num;
1041   }
1042
1043   assert(StartBits.size() == Num && EndBits.size() == Num &&
1044          FieldVals.size() == Num);
1045   return Num;
1046 }
1047
1048 void FilterChooser::emitBinaryParser(raw_ostream &o, unsigned &Indentation,
1049                                      const OperandInfo &OpInfo) const {
1050   const std::string &Decoder = OpInfo.Decoder;
1051
1052   if (OpInfo.numFields() == 1) {
1053     OperandInfo::const_iterator OI = OpInfo.begin();
1054     o.indent(Indentation) << "tmp = fieldFromInstruction"
1055                           << "(insn, " << OI->Base << ", " << OI->Width
1056                           << ");\n";
1057   } else {
1058     o.indent(Indentation) << "tmp = 0;\n";
1059     for (OperandInfo::const_iterator OI = OpInfo.begin(), OE = OpInfo.end();
1060          OI != OE; ++OI) {
1061       o.indent(Indentation) << "tmp |= (fieldFromInstruction"
1062                             << "(insn, " << OI->Base << ", " << OI->Width
1063                             << ") << " << OI->Offset << ");\n";
1064     }
1065   }
1066
1067   if (Decoder != "")
1068     o.indent(Indentation) << Emitter->GuardPrefix << Decoder
1069                           << "(MI, tmp, Address, Decoder)"
1070                           << Emitter->GuardPostfix << "\n";
1071   else
1072     o.indent(Indentation) << "MI.addOperand(MCOperand::CreateImm(tmp));\n";
1073
1074 }
1075
1076 void FilterChooser::emitDecoder(raw_ostream &OS, unsigned Indentation,
1077                                 unsigned Opc) const {
1078   std::map<unsigned, std::vector<OperandInfo> >::const_iterator OpIter =
1079     Operands.find(Opc);
1080   const std::vector<OperandInfo>& InsnOperands = OpIter->second;
1081   for (std::vector<OperandInfo>::const_iterator
1082        I = InsnOperands.begin(), E = InsnOperands.end(); I != E; ++I) {
1083     // If a custom instruction decoder was specified, use that.
1084     if (I->numFields() == 0 && I->Decoder.size()) {
1085       OS.indent(Indentation) << Emitter->GuardPrefix << I->Decoder
1086         << "(MI, insn, Address, Decoder)"
1087         << Emitter->GuardPostfix << "\n";
1088       break;
1089     }
1090
1091     emitBinaryParser(OS, Indentation, *I);
1092   }
1093 }
1094
1095 unsigned FilterChooser::getDecoderIndex(DecoderSet &Decoders,
1096                                         unsigned Opc) const {
1097   // Build up the predicate string.
1098   SmallString<256> Decoder;
1099   // FIXME: emitDecoder() function can take a buffer directly rather than
1100   // a stream.
1101   raw_svector_ostream S(Decoder);
1102   unsigned I = 4;
1103   emitDecoder(S, I, Opc);
1104   S.flush();
1105
1106   // Using the full decoder string as the key value here is a bit
1107   // heavyweight, but is effective. If the string comparisons become a
1108   // performance concern, we can implement a mangling of the predicate
1109   // data easilly enough with a map back to the actual string. That's
1110   // overkill for now, though.
1111
1112   // Make sure the predicate is in the table.
1113   Decoders.insert(Decoder.str());
1114   // Now figure out the index for when we write out the table.
1115   DecoderSet::const_iterator P = std::find(Decoders.begin(),
1116                                            Decoders.end(),
1117                                            Decoder.str());
1118   return (unsigned)(P - Decoders.begin());
1119 }
1120
1121 static void emitSinglePredicateMatch(raw_ostream &o, StringRef str,
1122                                      const std::string &PredicateNamespace) {
1123   if (str[0] == '!')
1124     o << "!(Bits & " << PredicateNamespace << "::"
1125       << str.slice(1,str.size()) << ")";
1126   else
1127     o << "(Bits & " << PredicateNamespace << "::" << str << ")";
1128 }
1129
1130 bool FilterChooser::emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
1131                                        unsigned Opc) const {
1132   ListInit *Predicates =
1133     AllInstructions[Opc]->TheDef->getValueAsListInit("Predicates");
1134   for (unsigned i = 0; i < Predicates->getSize(); ++i) {
1135     Record *Pred = Predicates->getElementAsRecord(i);
1136     if (!Pred->getValue("AssemblerMatcherPredicate"))
1137       continue;
1138
1139     std::string P = Pred->getValueAsString("AssemblerCondString");
1140
1141     if (!P.length())
1142       continue;
1143
1144     if (i != 0)
1145       o << " && ";
1146
1147     StringRef SR(P);
1148     std::pair<StringRef, StringRef> pairs = SR.split(',');
1149     while (pairs.second.size()) {
1150       emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
1151       o << " && ";
1152       pairs = pairs.second.split(',');
1153     }
1154     emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
1155   }
1156   return Predicates->getSize() > 0;
1157 }
1158
1159 bool FilterChooser::doesOpcodeNeedPredicate(unsigned Opc) const {
1160   ListInit *Predicates =
1161     AllInstructions[Opc]->TheDef->getValueAsListInit("Predicates");
1162   for (unsigned i = 0; i < Predicates->getSize(); ++i) {
1163     Record *Pred = Predicates->getElementAsRecord(i);
1164     if (!Pred->getValue("AssemblerMatcherPredicate"))
1165       continue;
1166
1167     std::string P = Pred->getValueAsString("AssemblerCondString");
1168
1169     if (!P.length())
1170       continue;
1171
1172     return true;
1173   }
1174   return false;
1175 }
1176
1177 unsigned FilterChooser::getPredicateIndex(DecoderTableInfo &TableInfo,
1178                                           StringRef Predicate) const {
1179   // Using the full predicate string as the key value here is a bit
1180   // heavyweight, but is effective. If the string comparisons become a
1181   // performance concern, we can implement a mangling of the predicate
1182   // data easilly enough with a map back to the actual string. That's
1183   // overkill for now, though.
1184
1185   // Make sure the predicate is in the table.
1186   TableInfo.Predicates.insert(Predicate.str());
1187   // Now figure out the index for when we write out the table.
1188   PredicateSet::const_iterator P = std::find(TableInfo.Predicates.begin(),
1189                                              TableInfo.Predicates.end(),
1190                                              Predicate.str());
1191   return (unsigned)(P - TableInfo.Predicates.begin());
1192 }
1193
1194 void FilterChooser::emitPredicateTableEntry(DecoderTableInfo &TableInfo,
1195                                             unsigned Opc) const {
1196   if (!doesOpcodeNeedPredicate(Opc))
1197     return;
1198
1199   // Build up the predicate string.
1200   SmallString<256> Predicate;
1201   // FIXME: emitPredicateMatch() functions can take a buffer directly rather
1202   // than a stream.
1203   raw_svector_ostream PS(Predicate);
1204   unsigned I = 0;
1205   emitPredicateMatch(PS, I, Opc);
1206
1207   // Figure out the index into the predicate table for the predicate just
1208   // computed.
1209   unsigned PIdx = getPredicateIndex(TableInfo, PS.str());
1210   SmallString<16> PBytes;
1211   raw_svector_ostream S(PBytes);
1212   encodeULEB128(PIdx, S);
1213   S.flush();
1214
1215   TableInfo.Table.push_back(MCD::OPC_CheckPredicate);
1216   // Predicate index
1217   for (unsigned i = 0, e = PBytes.size(); i != e; ++i)
1218     TableInfo.Table.push_back(PBytes[i]);
1219   // Push location for NumToSkip backpatching.
1220   TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
1221   TableInfo.Table.push_back(0);
1222   TableInfo.Table.push_back(0);
1223 }
1224
1225 void FilterChooser::emitSoftFailTableEntry(DecoderTableInfo &TableInfo,
1226                                            unsigned Opc) const {
1227   BitsInit *SFBits =
1228     AllInstructions[Opc]->TheDef->getValueAsBitsInit("SoftFail");
1229   if (!SFBits) return;
1230   BitsInit *InstBits = AllInstructions[Opc]->TheDef->getValueAsBitsInit("Inst");
1231
1232   APInt PositiveMask(BitWidth, 0ULL);
1233   APInt NegativeMask(BitWidth, 0ULL);
1234   for (unsigned i = 0; i < BitWidth; ++i) {
1235     bit_value_t B = bitFromBits(*SFBits, i);
1236     bit_value_t IB = bitFromBits(*InstBits, i);
1237
1238     if (B != BIT_TRUE) continue;
1239
1240     switch (IB) {
1241     case BIT_FALSE:
1242       // The bit is meant to be false, so emit a check to see if it is true.
1243       PositiveMask.setBit(i);
1244       break;
1245     case BIT_TRUE:
1246       // The bit is meant to be true, so emit a check to see if it is false.
1247       NegativeMask.setBit(i);
1248       break;
1249     default:
1250       // The bit is not set; this must be an error!
1251       StringRef Name = AllInstructions[Opc]->TheDef->getName();
1252       errs() << "SoftFail Conflict: bit SoftFail{" << i << "} in " << Name
1253              << " is set but Inst{" << i << "} is unset!\n"
1254              << "  - You can only mark a bit as SoftFail if it is fully defined"
1255              << " (1/0 - not '?') in Inst\n";
1256       return;
1257     }
1258   }
1259
1260   bool NeedPositiveMask = PositiveMask.getBoolValue();
1261   bool NeedNegativeMask = NegativeMask.getBoolValue();
1262
1263   if (!NeedPositiveMask && !NeedNegativeMask)
1264     return;
1265
1266   TableInfo.Table.push_back(MCD::OPC_SoftFail);
1267
1268   SmallString<16> MaskBytes;
1269   raw_svector_ostream S(MaskBytes);
1270   if (NeedPositiveMask) {
1271     encodeULEB128(PositiveMask.getZExtValue(), S);
1272     S.flush();
1273     for (unsigned i = 0, e = MaskBytes.size(); i != e; ++i)
1274       TableInfo.Table.push_back(MaskBytes[i]);
1275   } else
1276     TableInfo.Table.push_back(0);
1277   if (NeedNegativeMask) {
1278     MaskBytes.clear();
1279     S.resync();
1280     encodeULEB128(NegativeMask.getZExtValue(), S);
1281     S.flush();
1282     for (unsigned i = 0, e = MaskBytes.size(); i != e; ++i)
1283       TableInfo.Table.push_back(MaskBytes[i]);
1284   } else
1285     TableInfo.Table.push_back(0);
1286 }
1287
1288 // Emits table entries to decode the singleton.
1289 void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,
1290                                             unsigned Opc) const {
1291   std::vector<unsigned> StartBits;
1292   std::vector<unsigned> EndBits;
1293   std::vector<uint64_t> FieldVals;
1294   insn_t Insn;
1295   insnWithID(Insn, Opc);
1296
1297   // Look for islands of undecoded bits of the singleton.
1298   getIslands(StartBits, EndBits, FieldVals, Insn);
1299
1300   unsigned Size = StartBits.size();
1301
1302   // Emit the predicate table entry if one is needed.
1303   emitPredicateTableEntry(TableInfo, Opc);
1304
1305   // Check any additional encoding fields needed.
1306   for (unsigned I = Size; I != 0; --I) {
1307     unsigned NumBits = EndBits[I-1] - StartBits[I-1] + 1;
1308     TableInfo.Table.push_back(MCD::OPC_CheckField);
1309     TableInfo.Table.push_back(StartBits[I-1]);
1310     TableInfo.Table.push_back(NumBits);
1311     uint8_t Buffer[8], *p;
1312     encodeULEB128(FieldVals[I-1], Buffer);
1313     for (p = Buffer; *p >= 128 ; ++p)
1314       TableInfo.Table.push_back(*p);
1315     TableInfo.Table.push_back(*p);
1316     // Push location for NumToSkip backpatching.
1317     TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
1318     // The fixup is always 16-bits, so go ahead and allocate the space
1319     // in the table so all our relative position calculations work OK even
1320     // before we fully resolve the real value here.
1321     TableInfo.Table.push_back(0);
1322     TableInfo.Table.push_back(0);
1323   }
1324
1325   // Check for soft failure of the match.
1326   emitSoftFailTableEntry(TableInfo, Opc);
1327
1328   TableInfo.Table.push_back(MCD::OPC_Decode);
1329   uint8_t Buffer[8], *p;
1330   encodeULEB128(Opc, Buffer);
1331   for (p = Buffer; *p >= 128 ; ++p)
1332     TableInfo.Table.push_back(*p);
1333   TableInfo.Table.push_back(*p);
1334
1335   unsigned DIdx = getDecoderIndex(TableInfo.Decoders, Opc);
1336   SmallString<16> Bytes;
1337   raw_svector_ostream S(Bytes);
1338   encodeULEB128(DIdx, S);
1339   S.flush();
1340
1341   // Decoder index
1342   for (unsigned i = 0, e = Bytes.size(); i != e; ++i)
1343     TableInfo.Table.push_back(Bytes[i]);
1344 }
1345
1346 // Emits table entries to decode the singleton, and then to decode the rest.
1347 void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,
1348                                             const Filter &Best) const {
1349   unsigned Opc = Best.getSingletonOpc();
1350
1351   // complex singletons need predicate checks from the first singleton
1352   // to refer forward to the variable filterchooser that follows.
1353   TableInfo.FixupStack.push_back(FixupList());
1354
1355   emitSingletonTableEntry(TableInfo, Opc);
1356
1357   resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),
1358                      TableInfo.Table.size());
1359   TableInfo.FixupStack.pop_back();
1360
1361   Best.getVariableFC().emitTableEntries(TableInfo);
1362 }
1363
1364
1365 // Assign a single filter and run with it.  Top level API client can initialize
1366 // with a single filter to start the filtering process.
1367 void FilterChooser::runSingleFilter(unsigned startBit, unsigned numBit,
1368                                     bool mixed) {
1369   Filters.clear();
1370   Filters.push_back(Filter(*this, startBit, numBit, true));
1371   BestIndex = 0; // Sole Filter instance to choose from.
1372   bestFilter().recurse();
1373 }
1374
1375 // reportRegion is a helper function for filterProcessor to mark a region as
1376 // eligible for use as a filter region.
1377 void FilterChooser::reportRegion(bitAttr_t RA, unsigned StartBit,
1378                                  unsigned BitIndex, bool AllowMixed) {
1379   if (RA == ATTR_MIXED && AllowMixed)
1380     Filters.push_back(Filter(*this, StartBit, BitIndex - StartBit, true));
1381   else if (RA == ATTR_ALL_SET && !AllowMixed)
1382     Filters.push_back(Filter(*this, StartBit, BitIndex - StartBit, false));
1383 }
1384
1385 // FilterProcessor scans the well-known encoding bits of the instructions and
1386 // builds up a list of candidate filters.  It chooses the best filter and
1387 // recursively descends down the decoding tree.
1388 bool FilterChooser::filterProcessor(bool AllowMixed, bool Greedy) {
1389   Filters.clear();
1390   BestIndex = -1;
1391   unsigned numInstructions = Opcodes.size();
1392
1393   assert(numInstructions && "Filter created with no instructions");
1394
1395   // No further filtering is necessary.
1396   if (numInstructions == 1)
1397     return true;
1398
1399   // Heuristics.  See also doFilter()'s "Heuristics" comment when num of
1400   // instructions is 3.
1401   if (AllowMixed && !Greedy) {
1402     assert(numInstructions == 3);
1403
1404     for (unsigned i = 0; i < Opcodes.size(); ++i) {
1405       std::vector<unsigned> StartBits;
1406       std::vector<unsigned> EndBits;
1407       std::vector<uint64_t> FieldVals;
1408       insn_t Insn;
1409
1410       insnWithID(Insn, Opcodes[i]);
1411
1412       // Look for islands of undecoded bits of any instruction.
1413       if (getIslands(StartBits, EndBits, FieldVals, Insn) > 0) {
1414         // Found an instruction with island(s).  Now just assign a filter.
1415         runSingleFilter(StartBits[0], EndBits[0] - StartBits[0] + 1, true);
1416         return true;
1417       }
1418     }
1419   }
1420
1421   unsigned BitIndex;
1422
1423   // We maintain BIT_WIDTH copies of the bitAttrs automaton.
1424   // The automaton consumes the corresponding bit from each
1425   // instruction.
1426   //
1427   //   Input symbols: 0, 1, and _ (unset).
1428   //   States:        NONE, FILTERED, ALL_SET, ALL_UNSET, and MIXED.
1429   //   Initial state: NONE.
1430   //
1431   // (NONE) ------- [01] -> (ALL_SET)
1432   // (NONE) ------- _ ----> (ALL_UNSET)
1433   // (ALL_SET) ---- [01] -> (ALL_SET)
1434   // (ALL_SET) ---- _ ----> (MIXED)
1435   // (ALL_UNSET) -- [01] -> (MIXED)
1436   // (ALL_UNSET) -- _ ----> (ALL_UNSET)
1437   // (MIXED) ------ . ----> (MIXED)
1438   // (FILTERED)---- . ----> (FILTERED)
1439
1440   std::vector<bitAttr_t> bitAttrs;
1441
1442   // FILTERED bit positions provide no entropy and are not worthy of pursuing.
1443   // Filter::recurse() set either BIT_TRUE or BIT_FALSE for each position.
1444   for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex)
1445     if (FilterBitValues[BitIndex] == BIT_TRUE ||
1446         FilterBitValues[BitIndex] == BIT_FALSE)
1447       bitAttrs.push_back(ATTR_FILTERED);
1448     else
1449       bitAttrs.push_back(ATTR_NONE);
1450
1451   for (unsigned InsnIndex = 0; InsnIndex < numInstructions; ++InsnIndex) {
1452     insn_t insn;
1453
1454     insnWithID(insn, Opcodes[InsnIndex]);
1455
1456     for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
1457       switch (bitAttrs[BitIndex]) {
1458       case ATTR_NONE:
1459         if (insn[BitIndex] == BIT_UNSET)
1460           bitAttrs[BitIndex] = ATTR_ALL_UNSET;
1461         else
1462           bitAttrs[BitIndex] = ATTR_ALL_SET;
1463         break;
1464       case ATTR_ALL_SET:
1465         if (insn[BitIndex] == BIT_UNSET)
1466           bitAttrs[BitIndex] = ATTR_MIXED;
1467         break;
1468       case ATTR_ALL_UNSET:
1469         if (insn[BitIndex] != BIT_UNSET)
1470           bitAttrs[BitIndex] = ATTR_MIXED;
1471         break;
1472       case ATTR_MIXED:
1473       case ATTR_FILTERED:
1474         break;
1475       }
1476     }
1477   }
1478
1479   // The regionAttr automaton consumes the bitAttrs automatons' state,
1480   // lowest-to-highest.
1481   //
1482   //   Input symbols: F(iltered), (all_)S(et), (all_)U(nset), M(ixed)
1483   //   States:        NONE, ALL_SET, MIXED
1484   //   Initial state: NONE
1485   //
1486   // (NONE) ----- F --> (NONE)
1487   // (NONE) ----- S --> (ALL_SET)     ; and set region start
1488   // (NONE) ----- U --> (NONE)
1489   // (NONE) ----- M --> (MIXED)       ; and set region start
1490   // (ALL_SET) -- F --> (NONE)        ; and report an ALL_SET region
1491   // (ALL_SET) -- S --> (ALL_SET)
1492   // (ALL_SET) -- U --> (NONE)        ; and report an ALL_SET region
1493   // (ALL_SET) -- M --> (MIXED)       ; and report an ALL_SET region
1494   // (MIXED) ---- F --> (NONE)        ; and report a MIXED region
1495   // (MIXED) ---- S --> (ALL_SET)     ; and report a MIXED region
1496   // (MIXED) ---- U --> (NONE)        ; and report a MIXED region
1497   // (MIXED) ---- M --> (MIXED)
1498
1499   bitAttr_t RA = ATTR_NONE;
1500   unsigned StartBit = 0;
1501
1502   for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
1503     bitAttr_t bitAttr = bitAttrs[BitIndex];
1504
1505     assert(bitAttr != ATTR_NONE && "Bit without attributes");
1506
1507     switch (RA) {
1508     case ATTR_NONE:
1509       switch (bitAttr) {
1510       case ATTR_FILTERED:
1511         break;
1512       case ATTR_ALL_SET:
1513         StartBit = BitIndex;
1514         RA = ATTR_ALL_SET;
1515         break;
1516       case ATTR_ALL_UNSET:
1517         break;
1518       case ATTR_MIXED:
1519         StartBit = BitIndex;
1520         RA = ATTR_MIXED;
1521         break;
1522       default:
1523         llvm_unreachable("Unexpected bitAttr!");
1524       }
1525       break;
1526     case ATTR_ALL_SET:
1527       switch (bitAttr) {
1528       case ATTR_FILTERED:
1529         reportRegion(RA, StartBit, BitIndex, AllowMixed);
1530         RA = ATTR_NONE;
1531         break;
1532       case ATTR_ALL_SET:
1533         break;
1534       case ATTR_ALL_UNSET:
1535         reportRegion(RA, StartBit, BitIndex, AllowMixed);
1536         RA = ATTR_NONE;
1537         break;
1538       case ATTR_MIXED:
1539         reportRegion(RA, StartBit, BitIndex, AllowMixed);
1540         StartBit = BitIndex;
1541         RA = ATTR_MIXED;
1542         break;
1543       default:
1544         llvm_unreachable("Unexpected bitAttr!");
1545       }
1546       break;
1547     case ATTR_MIXED:
1548       switch (bitAttr) {
1549       case ATTR_FILTERED:
1550         reportRegion(RA, StartBit, BitIndex, AllowMixed);
1551         StartBit = BitIndex;
1552         RA = ATTR_NONE;
1553         break;
1554       case ATTR_ALL_SET:
1555         reportRegion(RA, StartBit, BitIndex, AllowMixed);
1556         StartBit = BitIndex;
1557         RA = ATTR_ALL_SET;
1558         break;
1559       case ATTR_ALL_UNSET:
1560         reportRegion(RA, StartBit, BitIndex, AllowMixed);
1561         RA = ATTR_NONE;
1562         break;
1563       case ATTR_MIXED:
1564         break;
1565       default:
1566         llvm_unreachable("Unexpected bitAttr!");
1567       }
1568       break;
1569     case ATTR_ALL_UNSET:
1570       llvm_unreachable("regionAttr state machine has no ATTR_UNSET state");
1571     case ATTR_FILTERED:
1572       llvm_unreachable("regionAttr state machine has no ATTR_FILTERED state");
1573     }
1574   }
1575
1576   // At the end, if we're still in ALL_SET or MIXED states, report a region
1577   switch (RA) {
1578   case ATTR_NONE:
1579     break;
1580   case ATTR_FILTERED:
1581     break;
1582   case ATTR_ALL_SET:
1583     reportRegion(RA, StartBit, BitIndex, AllowMixed);
1584     break;
1585   case ATTR_ALL_UNSET:
1586     break;
1587   case ATTR_MIXED:
1588     reportRegion(RA, StartBit, BitIndex, AllowMixed);
1589     break;
1590   }
1591
1592   // We have finished with the filter processings.  Now it's time to choose
1593   // the best performing filter.
1594   BestIndex = 0;
1595   bool AllUseless = true;
1596   unsigned BestScore = 0;
1597
1598   for (unsigned i = 0, e = Filters.size(); i != e; ++i) {
1599     unsigned Usefulness = Filters[i].usefulness();
1600
1601     if (Usefulness)
1602       AllUseless = false;
1603
1604     if (Usefulness > BestScore) {
1605       BestIndex = i;
1606       BestScore = Usefulness;
1607     }
1608   }
1609
1610   if (!AllUseless)
1611     bestFilter().recurse();
1612
1613   return !AllUseless;
1614 } // end of FilterChooser::filterProcessor(bool)
1615
1616 // Decides on the best configuration of filter(s) to use in order to decode
1617 // the instructions.  A conflict of instructions may occur, in which case we
1618 // dump the conflict set to the standard error.
1619 void FilterChooser::doFilter() {
1620   unsigned Num = Opcodes.size();
1621   assert(Num && "FilterChooser created with no instructions");
1622
1623   // Try regions of consecutive known bit values first.
1624   if (filterProcessor(false))
1625     return;
1626
1627   // Then regions of mixed bits (both known and unitialized bit values allowed).
1628   if (filterProcessor(true))
1629     return;
1630
1631   // Heuristics to cope with conflict set {t2CMPrs, t2SUBSrr, t2SUBSrs} where
1632   // no single instruction for the maximum ATTR_MIXED region Inst{14-4} has a
1633   // well-known encoding pattern.  In such case, we backtrack and scan for the
1634   // the very first consecutive ATTR_ALL_SET region and assign a filter to it.
1635   if (Num == 3 && filterProcessor(true, false))
1636     return;
1637
1638   // If we come to here, the instruction decoding has failed.
1639   // Set the BestIndex to -1 to indicate so.
1640   BestIndex = -1;
1641 }
1642
1643 // emitTableEntries - Emit state machine entries to decode our share of
1644 // instructions.
1645 void FilterChooser::emitTableEntries(DecoderTableInfo &TableInfo) const {
1646   if (Opcodes.size() == 1) {
1647     // There is only one instruction in the set, which is great!
1648     // Call emitSingletonDecoder() to see whether there are any remaining
1649     // encodings bits.
1650     emitSingletonTableEntry(TableInfo, Opcodes[0]);
1651     return;
1652   }
1653
1654   // Choose the best filter to do the decodings!
1655   if (BestIndex != -1) {
1656     const Filter &Best = Filters[BestIndex];
1657     if (Best.getNumFiltered() == 1)
1658       emitSingletonTableEntry(TableInfo, Best);
1659     else
1660       Best.emitTableEntry(TableInfo);
1661     return;
1662   }
1663
1664   // We don't know how to decode these instructions!  Dump the
1665   // conflict set and bail.
1666
1667   // Print out useful conflict information for postmortem analysis.
1668   errs() << "Decoding Conflict:\n";
1669
1670   dumpStack(errs(), "\t\t");
1671
1672   for (unsigned i = 0; i < Opcodes.size(); ++i) {
1673     const std::string &Name = nameWithID(Opcodes[i]);
1674
1675     errs() << '\t' << Name << " ";
1676     dumpBits(errs(),
1677              getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
1678     errs() << '\n';
1679   }
1680 }
1681
1682 static bool populateInstruction(CodeGenTarget &Target,
1683                        const CodeGenInstruction &CGI, unsigned Opc,
1684                        std::map<unsigned, std::vector<OperandInfo> > &Operands){
1685   const Record &Def = *CGI.TheDef;
1686   // If all the bit positions are not specified; do not decode this instruction.
1687   // We are bound to fail!  For proper disassembly, the well-known encoding bits
1688   // of the instruction must be fully specified.
1689
1690   BitsInit &Bits = getBitsField(Def, "Inst");
1691   if (Bits.allInComplete()) return false;
1692
1693   std::vector<OperandInfo> InsnOperands;
1694
1695   // If the instruction has specified a custom decoding hook, use that instead
1696   // of trying to auto-generate the decoder.
1697   std::string InstDecoder = Def.getValueAsString("DecoderMethod");
1698   if (InstDecoder != "") {
1699     InsnOperands.push_back(OperandInfo(InstDecoder));
1700     Operands[Opc] = InsnOperands;
1701     return true;
1702   }
1703
1704   // Generate a description of the operand of the instruction that we know
1705   // how to decode automatically.
1706   // FIXME: We'll need to have a way to manually override this as needed.
1707
1708   // Gather the outputs/inputs of the instruction, so we can find their
1709   // positions in the encoding.  This assumes for now that they appear in the
1710   // MCInst in the order that they're listed.
1711   std::vector<std::pair<Init*, std::string> > InOutOperands;
1712   DagInit *Out  = Def.getValueAsDag("OutOperandList");
1713   DagInit *In  = Def.getValueAsDag("InOperandList");
1714   for (unsigned i = 0; i < Out->getNumArgs(); ++i)
1715     InOutOperands.push_back(std::make_pair(Out->getArg(i), Out->getArgName(i)));
1716   for (unsigned i = 0; i < In->getNumArgs(); ++i)
1717     InOutOperands.push_back(std::make_pair(In->getArg(i), In->getArgName(i)));
1718
1719   // Search for tied operands, so that we can correctly instantiate
1720   // operands that are not explicitly represented in the encoding.
1721   std::map<std::string, std::string> TiedNames;
1722   for (unsigned i = 0; i < CGI.Operands.size(); ++i) {
1723     int tiedTo = CGI.Operands[i].getTiedRegister();
1724     if (tiedTo != -1) {
1725       std::pair<unsigned, unsigned> SO =
1726         CGI.Operands.getSubOperandNumber(tiedTo);
1727       TiedNames[InOutOperands[i].second] = InOutOperands[SO.first].second;
1728       TiedNames[InOutOperands[SO.first].second] = InOutOperands[i].second;
1729     }
1730   }
1731
1732   std::map<std::string, std::vector<OperandInfo> > NumberedInsnOperands;
1733   std::set<std::string> NumberedInsnOperandsNoTie;
1734   if (Target.getInstructionSet()->
1735         getValueAsBit("decodePositionallyEncodedOperands")) {
1736     const std::vector<RecordVal> &Vals = Def.getValues();
1737     unsigned NumberedOp = 0;
1738
1739     std::set<unsigned> NamedOpIndices;
1740     if (Target.getInstructionSet()->
1741          getValueAsBit("noNamedPositionallyEncodedOperands"))
1742       // Collect the set of operand indices that might correspond to named
1743       // operand, and skip these when assigning operands based on position.
1744       for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1745         unsigned OpIdx;
1746         if (!CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx))
1747           continue;
1748
1749         NamedOpIndices.insert(OpIdx);
1750       }
1751
1752     for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1753       // Ignore fixed fields in the record, we're looking for values like:
1754       //    bits<5> RST = { ?, ?, ?, ?, ? };
1755       if (Vals[i].getPrefix() || Vals[i].getValue()->isComplete())
1756         continue;
1757
1758       // Determine if Vals[i] actually contributes to the Inst encoding.
1759       unsigned bi = 0;
1760       for (; bi < Bits.getNumBits(); ++bi) {
1761         VarInit *Var = nullptr;
1762         VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
1763         if (BI)
1764           Var = dyn_cast<VarInit>(BI->getBitVar());
1765         else
1766           Var = dyn_cast<VarInit>(Bits.getBit(bi));
1767
1768         if (Var && Var->getName() == Vals[i].getName())
1769           break;
1770       }
1771
1772       if (bi == Bits.getNumBits())
1773         continue;
1774
1775       // Skip variables that correspond to explicitly-named operands.
1776       unsigned OpIdx;
1777       if (CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx))
1778         continue;
1779
1780       // Get the bit range for this operand:
1781       unsigned bitStart = bi++, bitWidth = 1;
1782       for (; bi < Bits.getNumBits(); ++bi) {
1783         VarInit *Var = nullptr;
1784         VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
1785         if (BI)
1786           Var = dyn_cast<VarInit>(BI->getBitVar());
1787         else
1788           Var = dyn_cast<VarInit>(Bits.getBit(bi));
1789
1790         if (!Var)
1791           break;
1792
1793         if (Var->getName() != Vals[i].getName())
1794           break;
1795
1796         ++bitWidth;
1797       }
1798
1799       unsigned NumberOps = CGI.Operands.size();
1800       while (NumberedOp < NumberOps &&
1801              (CGI.Operands.isFlatOperandNotEmitted(NumberedOp) ||
1802               (NamedOpIndices.size() && NamedOpIndices.count(
1803                 CGI.Operands.getSubOperandNumber(NumberedOp).first))))
1804         ++NumberedOp;
1805
1806       OpIdx = NumberedOp++;
1807
1808       // OpIdx now holds the ordered operand number of Vals[i].
1809       std::pair<unsigned, unsigned> SO =
1810         CGI.Operands.getSubOperandNumber(OpIdx);
1811       const std::string &Name = CGI.Operands[SO.first].Name;
1812
1813       DEBUG(dbgs() << "Numbered operand mapping for " << Def.getName() << ": " <<
1814                       Name << "(" << SO.first << ", " << SO.second << ") => " <<
1815                       Vals[i].getName() << "\n");
1816
1817       std::string Decoder = "";
1818       Record *TypeRecord = CGI.Operands[SO.first].Rec;
1819
1820       RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod");
1821       StringInit *String = DecoderString ?
1822         dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
1823       if (String && String->getValue() != "")
1824         Decoder = String->getValue();
1825
1826       if (Decoder == "" &&
1827           CGI.Operands[SO.first].MIOperandInfo &&
1828           CGI.Operands[SO.first].MIOperandInfo->getNumArgs()) {
1829         Init *Arg = CGI.Operands[SO.first].MIOperandInfo->
1830                       getArg(SO.second);
1831         if (TypedInit *TI = cast<TypedInit>(Arg)) {
1832           RecordRecTy *Type = cast<RecordRecTy>(TI->getType());
1833           TypeRecord = Type->getRecord();
1834         }
1835       }
1836
1837       bool isReg = false;
1838       if (TypeRecord->isSubClassOf("RegisterOperand"))
1839         TypeRecord = TypeRecord->getValueAsDef("RegClass");
1840       if (TypeRecord->isSubClassOf("RegisterClass")) {
1841         Decoder = "Decode" + TypeRecord->getName() + "RegisterClass";
1842         isReg = true;
1843       } else if (TypeRecord->isSubClassOf("PointerLikeRegClass")) {
1844         Decoder = "DecodePointerLikeRegClass" +
1845                   utostr(TypeRecord->getValueAsInt("RegClassKind"));
1846         isReg = true;
1847       }
1848
1849       DecoderString = TypeRecord->getValue("DecoderMethod");
1850       String = DecoderString ?
1851         dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
1852       if (!isReg && String && String->getValue() != "")
1853         Decoder = String->getValue();
1854
1855       OperandInfo OpInfo(Decoder);
1856       OpInfo.addField(bitStart, bitWidth, 0);
1857
1858       NumberedInsnOperands[Name].push_back(OpInfo);
1859
1860       // FIXME: For complex operands with custom decoders we can't handle tied
1861       // sub-operands automatically. Skip those here and assume that this is
1862       // fixed up elsewhere.
1863       if (CGI.Operands[SO.first].MIOperandInfo &&
1864           CGI.Operands[SO.first].MIOperandInfo->getNumArgs() > 1 &&
1865           String && String->getValue() != "")
1866         NumberedInsnOperandsNoTie.insert(Name);
1867     }
1868   }
1869
1870   // For each operand, see if we can figure out where it is encoded.
1871   for (std::vector<std::pair<Init*, std::string> >::const_iterator
1872        NI = InOutOperands.begin(), NE = InOutOperands.end(); NI != NE; ++NI) {
1873     if (!NumberedInsnOperands[NI->second].empty()) {
1874       InsnOperands.insert(InsnOperands.end(),
1875                           NumberedInsnOperands[NI->second].begin(),
1876                           NumberedInsnOperands[NI->second].end());
1877       continue;
1878     } else if (!NumberedInsnOperands[TiedNames[NI->second]].empty()) {
1879       if (!NumberedInsnOperandsNoTie.count(TiedNames[NI->second])) {
1880         // Figure out to which (sub)operand we're tied.
1881         unsigned i = CGI.Operands.getOperandNamed(TiedNames[NI->second]);
1882         int tiedTo = CGI.Operands[i].getTiedRegister();
1883         if (tiedTo == -1) {
1884           i = CGI.Operands.getOperandNamed(NI->second);
1885           tiedTo = CGI.Operands[i].getTiedRegister();
1886         }
1887
1888         if (tiedTo != -1) {
1889           std::pair<unsigned, unsigned> SO =
1890             CGI.Operands.getSubOperandNumber(tiedTo);
1891
1892           InsnOperands.push_back(NumberedInsnOperands[TiedNames[NI->second]]
1893                                    [SO.second]);
1894         }
1895       }
1896       continue;
1897     }
1898
1899     std::string Decoder = "";
1900
1901     // At this point, we can locate the field, but we need to know how to
1902     // interpret it.  As a first step, require the target to provide callbacks
1903     // for decoding register classes.
1904     // FIXME: This need to be extended to handle instructions with custom
1905     // decoder methods, and operands with (simple) MIOperandInfo's.
1906     TypedInit *TI = cast<TypedInit>(NI->first);
1907     RecordRecTy *Type = cast<RecordRecTy>(TI->getType());
1908     Record *TypeRecord = Type->getRecord();
1909     bool isReg = false;
1910     if (TypeRecord->isSubClassOf("RegisterOperand"))
1911       TypeRecord = TypeRecord->getValueAsDef("RegClass");
1912     if (TypeRecord->isSubClassOf("RegisterClass")) {
1913       Decoder = "Decode" + TypeRecord->getName() + "RegisterClass";
1914       isReg = true;
1915     } else if (TypeRecord->isSubClassOf("PointerLikeRegClass")) {
1916       Decoder = "DecodePointerLikeRegClass" +
1917                 utostr(TypeRecord->getValueAsInt("RegClassKind"));
1918       isReg = true;
1919     }
1920
1921     RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod");
1922     StringInit *String = DecoderString ?
1923       dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
1924     if (!isReg && String && String->getValue() != "")
1925       Decoder = String->getValue();
1926
1927     OperandInfo OpInfo(Decoder);
1928     unsigned Base = ~0U;
1929     unsigned Width = 0;
1930     unsigned Offset = 0;
1931
1932     for (unsigned bi = 0; bi < Bits.getNumBits(); ++bi) {
1933       VarInit *Var = nullptr;
1934       VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
1935       if (BI)
1936         Var = dyn_cast<VarInit>(BI->getBitVar());
1937       else
1938         Var = dyn_cast<VarInit>(Bits.getBit(bi));
1939
1940       if (!Var) {
1941         if (Base != ~0U) {
1942           OpInfo.addField(Base, Width, Offset);
1943           Base = ~0U;
1944           Width = 0;
1945           Offset = 0;
1946         }
1947         continue;
1948       }
1949
1950       if (Var->getName() != NI->second &&
1951           Var->getName() != TiedNames[NI->second]) {
1952         if (Base != ~0U) {
1953           OpInfo.addField(Base, Width, Offset);
1954           Base = ~0U;
1955           Width = 0;
1956           Offset = 0;
1957         }
1958         continue;
1959       }
1960
1961       if (Base == ~0U) {
1962         Base = bi;
1963         Width = 1;
1964         Offset = BI ? BI->getBitNum() : 0;
1965       } else if (BI && BI->getBitNum() != Offset + Width) {
1966         OpInfo.addField(Base, Width, Offset);
1967         Base = bi;
1968         Width = 1;
1969         Offset = BI->getBitNum();
1970       } else {
1971         ++Width;
1972       }
1973     }
1974
1975     if (Base != ~0U)
1976       OpInfo.addField(Base, Width, Offset);
1977
1978     if (OpInfo.numFields() > 0)
1979       InsnOperands.push_back(OpInfo);
1980   }
1981
1982   Operands[Opc] = InsnOperands;
1983
1984
1985 #if 0
1986   DEBUG({
1987       // Dumps the instruction encoding bits.
1988       dumpBits(errs(), Bits);
1989
1990       errs() << '\n';
1991
1992       // Dumps the list of operand info.
1993       for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) {
1994         const CGIOperandList::OperandInfo &Info = CGI.Operands[i];
1995         const std::string &OperandName = Info.Name;
1996         const Record &OperandDef = *Info.Rec;
1997
1998         errs() << "\t" << OperandName << " (" << OperandDef.getName() << ")\n";
1999       }
2000     });
2001 #endif
2002
2003   return true;
2004 }
2005
2006 // emitFieldFromInstruction - Emit the templated helper function
2007 // fieldFromInstruction().
2008 static void emitFieldFromInstruction(formatted_raw_ostream &OS) {
2009   OS << "// Helper function for extracting fields from encoded instructions.\n"
2010      << "template<typename InsnType>\n"
2011    << "static InsnType fieldFromInstruction(InsnType insn, unsigned startBit,\n"
2012      << "                                     unsigned numBits) {\n"
2013      << "    assert(startBit + numBits <= (sizeof(InsnType)*8) &&\n"
2014      << "           \"Instruction field out of bounds!\");\n"
2015      << "    InsnType fieldMask;\n"
2016      << "    if (numBits == sizeof(InsnType)*8)\n"
2017      << "      fieldMask = (InsnType)(-1LL);\n"
2018      << "    else\n"
2019      << "      fieldMask = (((InsnType)1 << numBits) - 1) << startBit;\n"
2020      << "    return (insn & fieldMask) >> startBit;\n"
2021      << "}\n\n";
2022 }
2023
2024 // emitDecodeInstruction - Emit the templated helper function
2025 // decodeInstruction().
2026 static void emitDecodeInstruction(formatted_raw_ostream &OS) {
2027   OS << "template<typename InsnType>\n"
2028      << "static DecodeStatus decodeInstruction(const uint8_t DecodeTable[], MCInst &MI,\n"
2029      << "                                      InsnType insn, uint64_t Address,\n"
2030      << "                                      const void *DisAsm,\n"
2031      << "                                      const MCSubtargetInfo &STI) {\n"
2032      << "  uint64_t Bits = STI.getFeatureBits();\n"
2033      << "\n"
2034      << "  const uint8_t *Ptr = DecodeTable;\n"
2035      << "  uint32_t CurFieldValue = 0;\n"
2036      << "  DecodeStatus S = MCDisassembler::Success;\n"
2037      << "  for (;;) {\n"
2038      << "    ptrdiff_t Loc = Ptr - DecodeTable;\n"
2039      << "    switch (*Ptr) {\n"
2040      << "    default:\n"
2041      << "      errs() << Loc << \": Unexpected decode table opcode!\\n\";\n"
2042      << "      return MCDisassembler::Fail;\n"
2043      << "    case MCD::OPC_ExtractField: {\n"
2044      << "      unsigned Start = *++Ptr;\n"
2045      << "      unsigned Len = *++Ptr;\n"
2046      << "      ++Ptr;\n"
2047      << "      CurFieldValue = fieldFromInstruction(insn, Start, Len);\n"
2048      << "      DEBUG(dbgs() << Loc << \": OPC_ExtractField(\" << Start << \", \"\n"
2049      << "                   << Len << \"): \" << CurFieldValue << \"\\n\");\n"
2050      << "      break;\n"
2051      << "    }\n"
2052      << "    case MCD::OPC_FilterValue: {\n"
2053      << "      // Decode the field value.\n"
2054      << "      unsigned Len;\n"
2055      << "      InsnType Val = decodeULEB128(++Ptr, &Len);\n"
2056      << "      Ptr += Len;\n"
2057      << "      // NumToSkip is a plain 16-bit integer.\n"
2058      << "      unsigned NumToSkip = *Ptr++;\n"
2059      << "      NumToSkip |= (*Ptr++) << 8;\n"
2060      << "\n"
2061      << "      // Perform the filter operation.\n"
2062      << "      if (Val != CurFieldValue)\n"
2063      << "        Ptr += NumToSkip;\n"
2064      << "      DEBUG(dbgs() << Loc << \": OPC_FilterValue(\" << Val << \", \" << NumToSkip\n"
2065      << "                   << \"): \" << ((Val != CurFieldValue) ? \"FAIL:\" : \"PASS:\")\n"
2066      << "                   << \" continuing at \" << (Ptr - DecodeTable) << \"\\n\");\n"
2067      << "\n"
2068      << "      break;\n"
2069      << "    }\n"
2070      << "    case MCD::OPC_CheckField: {\n"
2071      << "      unsigned Start = *++Ptr;\n"
2072      << "      unsigned Len = *++Ptr;\n"
2073      << "      InsnType FieldValue = fieldFromInstruction(insn, Start, Len);\n"
2074      << "      // Decode the field value.\n"
2075      << "      uint32_t ExpectedValue = decodeULEB128(++Ptr, &Len);\n"
2076      << "      Ptr += Len;\n"
2077      << "      // NumToSkip is a plain 16-bit integer.\n"
2078      << "      unsigned NumToSkip = *Ptr++;\n"
2079      << "      NumToSkip |= (*Ptr++) << 8;\n"
2080      << "\n"
2081      << "      // If the actual and expected values don't match, skip.\n"
2082      << "      if (ExpectedValue != FieldValue)\n"
2083      << "        Ptr += NumToSkip;\n"
2084      << "      DEBUG(dbgs() << Loc << \": OPC_CheckField(\" << Start << \", \"\n"
2085      << "                   << Len << \", \" << ExpectedValue << \", \" << NumToSkip\n"
2086      << "                   << \"): FieldValue = \" << FieldValue << \", ExpectedValue = \"\n"
2087      << "                   << ExpectedValue << \": \"\n"
2088      << "                   << ((ExpectedValue == FieldValue) ? \"PASS\\n\" : \"FAIL\\n\"));\n"
2089      << "      break;\n"
2090      << "    }\n"
2091      << "    case MCD::OPC_CheckPredicate: {\n"
2092      << "      unsigned Len;\n"
2093      << "      // Decode the Predicate Index value.\n"
2094      << "      unsigned PIdx = decodeULEB128(++Ptr, &Len);\n"
2095      << "      Ptr += Len;\n"
2096      << "      // NumToSkip is a plain 16-bit integer.\n"
2097      << "      unsigned NumToSkip = *Ptr++;\n"
2098      << "      NumToSkip |= (*Ptr++) << 8;\n"
2099      << "      // Check the predicate.\n"
2100      << "      bool Pred;\n"
2101      << "      if (!(Pred = checkDecoderPredicate(PIdx, Bits)))\n"
2102      << "        Ptr += NumToSkip;\n"
2103      << "      (void)Pred;\n"
2104      << "      DEBUG(dbgs() << Loc << \": OPC_CheckPredicate(\" << PIdx << \"): \"\n"
2105      << "            << (Pred ? \"PASS\\n\" : \"FAIL\\n\"));\n"
2106      << "\n"
2107      << "      break;\n"
2108      << "    }\n"
2109      << "    case MCD::OPC_Decode: {\n"
2110      << "      unsigned Len;\n"
2111      << "      // Decode the Opcode value.\n"
2112      << "      unsigned Opc = decodeULEB128(++Ptr, &Len);\n"
2113      << "      Ptr += Len;\n"
2114      << "      unsigned DecodeIdx = decodeULEB128(Ptr, &Len);\n"
2115      << "      Ptr += Len;\n"
2116      << "      DEBUG(dbgs() << Loc << \": OPC_Decode: opcode \" << Opc\n"
2117      << "                   << \", using decoder \" << DecodeIdx << \"\\n\" );\n"
2118      << "      DEBUG(dbgs() << \"----- DECODE SUCCESSFUL -----\\n\");\n"
2119      << "\n"
2120      << "      MI.setOpcode(Opc);\n"
2121      << "      return decodeToMCInst(S, DecodeIdx, insn, MI, Address, DisAsm);\n"
2122      << "    }\n"
2123      << "    case MCD::OPC_SoftFail: {\n"
2124      << "      // Decode the mask values.\n"
2125      << "      unsigned Len;\n"
2126      << "      InsnType PositiveMask = decodeULEB128(++Ptr, &Len);\n"
2127      << "      Ptr += Len;\n"
2128      << "      InsnType NegativeMask = decodeULEB128(Ptr, &Len);\n"
2129      << "      Ptr += Len;\n"
2130      << "      bool Fail = (insn & PositiveMask) || (~insn & NegativeMask);\n"
2131      << "      if (Fail)\n"
2132      << "        S = MCDisassembler::SoftFail;\n"
2133      << "      DEBUG(dbgs() << Loc << \": OPC_SoftFail: \" << (Fail ? \"FAIL\\n\":\"PASS\\n\"));\n"
2134      << "      break;\n"
2135      << "    }\n"
2136      << "    case MCD::OPC_Fail: {\n"
2137      << "      DEBUG(dbgs() << Loc << \": OPC_Fail\\n\");\n"
2138      << "      return MCDisassembler::Fail;\n"
2139      << "    }\n"
2140      << "    }\n"
2141      << "  }\n"
2142      << "  llvm_unreachable(\"bogosity detected in disassembler state machine!\");\n"
2143      << "}\n\n";
2144 }
2145
2146 // Emits disassembler code for instruction decoding.
2147 void FixedLenDecoderEmitter::run(raw_ostream &o) {
2148   formatted_raw_ostream OS(o);
2149   OS << "#include \"llvm/MC/MCInst.h\"\n";
2150   OS << "#include \"llvm/Support/Debug.h\"\n";
2151   OS << "#include \"llvm/Support/DataTypes.h\"\n";
2152   OS << "#include \"llvm/Support/LEB128.h\"\n";
2153   OS << "#include \"llvm/Support/raw_ostream.h\"\n";
2154   OS << "#include <assert.h>\n";
2155   OS << '\n';
2156   OS << "namespace llvm {\n\n";
2157
2158   emitFieldFromInstruction(OS);
2159
2160   Target.reverseBitsForLittleEndianEncoding();
2161
2162   // Parameterize the decoders based on namespace and instruction width.
2163   NumberedInstructions = &Target.getInstructionsByEnumValue();
2164   std::map<std::pair<std::string, unsigned>,
2165            std::vector<unsigned> > OpcMap;
2166   std::map<unsigned, std::vector<OperandInfo> > Operands;
2167
2168   for (unsigned i = 0; i < NumberedInstructions->size(); ++i) {
2169     const CodeGenInstruction *Inst = NumberedInstructions->at(i);
2170     const Record *Def = Inst->TheDef;
2171     unsigned Size = Def->getValueAsInt("Size");
2172     if (Def->getValueAsString("Namespace") == "TargetOpcode" ||
2173         Def->getValueAsBit("isPseudo") ||
2174         Def->getValueAsBit("isAsmParserOnly") ||
2175         Def->getValueAsBit("isCodeGenOnly"))
2176       continue;
2177
2178     std::string DecoderNamespace = Def->getValueAsString("DecoderNamespace");
2179
2180     if (Size) {
2181       if (populateInstruction(Target, *Inst, i, Operands)) {
2182         OpcMap[std::make_pair(DecoderNamespace, Size)].push_back(i);
2183       }
2184     }
2185   }
2186
2187   DecoderTableInfo TableInfo;
2188   for (std::map<std::pair<std::string, unsigned>,
2189                 std::vector<unsigned> >::const_iterator
2190        I = OpcMap.begin(), E = OpcMap.end(); I != E; ++I) {
2191     // Emit the decoder for this namespace+width combination.
2192     FilterChooser FC(*NumberedInstructions, I->second, Operands,
2193                      8*I->first.second, this);
2194
2195     // The decode table is cleared for each top level decoder function. The
2196     // predicates and decoders themselves, however, are shared across all
2197     // decoders to give more opportunities for uniqueing.
2198     TableInfo.Table.clear();
2199     TableInfo.FixupStack.clear();
2200     TableInfo.Table.reserve(16384);
2201     TableInfo.FixupStack.push_back(FixupList());
2202     FC.emitTableEntries(TableInfo);
2203     // Any NumToSkip fixups in the top level scope can resolve to the
2204     // OPC_Fail at the end of the table.
2205     assert(TableInfo.FixupStack.size() == 1 && "fixup stack phasing error!");
2206     // Resolve any NumToSkip fixups in the current scope.
2207     resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),
2208                        TableInfo.Table.size());
2209     TableInfo.FixupStack.clear();
2210
2211     TableInfo.Table.push_back(MCD::OPC_Fail);
2212
2213     // Print the table to the output stream.
2214     emitTable(OS, TableInfo.Table, 0, FC.getBitWidth(), I->first.first);
2215     OS.flush();
2216   }
2217
2218   // Emit the predicate function.
2219   emitPredicateFunction(OS, TableInfo.Predicates, 0);
2220
2221   // Emit the decoder function.
2222   emitDecoderFunction(OS, TableInfo.Decoders, 0);
2223
2224   // Emit the main entry point for the decoder, decodeInstruction().
2225   emitDecodeInstruction(OS);
2226
2227   OS << "\n} // End llvm namespace\n";
2228 }
2229
2230 namespace llvm {
2231
2232 void EmitFixedLenDecoder(RecordKeeper &RK, raw_ostream &OS,
2233                          std::string PredicateNamespace,
2234                          std::string GPrefix,
2235                          std::string GPostfix,
2236                          std::string ROK,
2237                          std::string RFail,
2238                          std::string L) {
2239   FixedLenDecoderEmitter(RK, PredicateNamespace, GPrefix, GPostfix,
2240                          ROK, RFail, L).run(OS);
2241 }
2242
2243 } // End llvm namespace