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