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