Write llvm-tblgen backends as functions instead of sub-classes.
[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 #define DEBUG_TYPE "decoder-emitter"
16
17 #include "CodeGenTarget.h"
18 #include "llvm/TableGen/Record.h"
19 #include "llvm/ADT/APInt.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/Support/DataTypes.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include "llvm/TableGen/TableGenBackend.h"
25
26 #include <vector>
27 #include <map>
28 #include <string>
29
30 using namespace llvm;
31
32 namespace {
33 struct EncodingField {
34   unsigned Base, Width, Offset;
35   EncodingField(unsigned B, unsigned W, unsigned O)
36     : Base(B), Width(W), Offset(O) { }
37 };
38 } // End anonymous namespace
39
40 namespace {
41 struct OperandInfo {
42   std::vector<EncodingField> Fields;
43   std::string Decoder;
44
45   OperandInfo(std::string D)
46     : Decoder(D) { }
47
48   void addField(unsigned Base, unsigned Width, unsigned Offset) {
49     Fields.push_back(EncodingField(Base, Width, Offset));
50   }
51
52   unsigned numFields() const { return Fields.size(); }
53
54   typedef std::vector<EncodingField>::const_iterator const_iterator;
55
56   const_iterator begin() const { return Fields.begin(); }
57   const_iterator end() const   { return Fields.end();   }
58 };
59 } // End anonymous namespace
60
61 namespace {
62 class FixedLenDecoderEmitter {
63 public:
64
65   // Defaults preserved here for documentation, even though they aren't
66   // strictly necessary given the way that this is currently being called.
67   FixedLenDecoderEmitter(RecordKeeper &R,
68                          std::string PredicateNamespace,
69                          std::string GPrefix  = "if (",
70                          std::string GPostfix = " == MCDisassembler::Fail)"
71                          " return MCDisassembler::Fail;",
72                          std::string ROK      = "MCDisassembler::Success",
73                          std::string RFail    = "MCDisassembler::Fail",
74                          std::string L        = "") :
75     Target(R),
76     PredicateNamespace(PredicateNamespace),
77     GuardPrefix(GPrefix), GuardPostfix(GPostfix),
78     ReturnOK(ROK), ReturnFail(RFail), Locals(L) {}
79
80   // run - Output the code emitter
81   void run(raw_ostream &o);
82
83 private:
84   CodeGenTarget Target;
85 public:
86   std::string PredicateNamespace;
87   std::string GuardPrefix, GuardPostfix;
88   std::string ReturnOK, ReturnFail;
89   std::string Locals;
90 };
91 } // End anonymous namespace
92
93 // The set (BIT_TRUE, BIT_FALSE, BIT_UNSET) represents a ternary logic system
94 // for a bit value.
95 //
96 // BIT_UNFILTERED is used as the init value for a filter position.  It is used
97 // only for filter processings.
98 typedef enum {
99   BIT_TRUE,      // '1'
100   BIT_FALSE,     // '0'
101   BIT_UNSET,     // '?'
102   BIT_UNFILTERED // unfiltered
103 } bit_value_t;
104
105 static bool ValueSet(bit_value_t V) {
106   return (V == BIT_TRUE || V == BIT_FALSE);
107 }
108 static bool ValueNotSet(bit_value_t V) {
109   return (V == BIT_UNSET);
110 }
111 static int Value(bit_value_t V) {
112   return ValueNotSet(V) ? -1 : (V == BIT_FALSE ? 0 : 1);
113 }
114 static bit_value_t bitFromBits(const BitsInit &bits, unsigned index) {
115   if (BitInit *bit = dynamic_cast<BitInit*>(bits.getBit(index)))
116     return bit->getValue() ? BIT_TRUE : BIT_FALSE;
117
118   // The bit is uninitialized.
119   return BIT_UNSET;
120 }
121 // Prints the bit value for each position.
122 static void dumpBits(raw_ostream &o, const BitsInit &bits) {
123   unsigned index;
124
125   for (index = bits.getNumBits(); index > 0; index--) {
126     switch (bitFromBits(bits, index - 1)) {
127     case BIT_TRUE:
128       o << "1";
129       break;
130     case BIT_FALSE:
131       o << "0";
132       break;
133     case BIT_UNSET:
134       o << "_";
135       break;
136     default:
137       llvm_unreachable("unexpected return value from bitFromBits");
138     }
139   }
140 }
141
142 static BitsInit &getBitsField(const Record &def, const char *str) {
143   BitsInit *bits = def.getValueAsBitsInit(str);
144   return *bits;
145 }
146
147 // Forward declaration.
148 namespace {
149 class FilterChooser;
150 } // End anonymous namespace
151
152 // Representation of the instruction to work on.
153 typedef std::vector<bit_value_t> insn_t;
154
155 /// Filter - Filter works with FilterChooser to produce the decoding tree for
156 /// the ISA.
157 ///
158 /// It is useful to think of a Filter as governing the switch stmts of the
159 /// decoding tree in a certain level.  Each case stmt delegates to an inferior
160 /// FilterChooser to decide what further decoding logic to employ, or in another
161 /// words, what other remaining bits to look at.  The FilterChooser eventually
162 /// chooses a best Filter to do its job.
163 ///
164 /// This recursive scheme ends when the number of Opcodes assigned to the
165 /// FilterChooser becomes 1 or if there is a conflict.  A conflict happens when
166 /// the Filter/FilterChooser combo does not know how to distinguish among the
167 /// Opcodes assigned.
168 ///
169 /// An example of a conflict is
170 ///
171 /// Conflict:
172 ///                     111101000.00........00010000....
173 ///                     111101000.00........0001........
174 ///                     1111010...00........0001........
175 ///                     1111010...00....................
176 ///                     1111010.........................
177 ///                     1111............................
178 ///                     ................................
179 ///     VST4q8a         111101000_00________00010000____
180 ///     VST4q8b         111101000_00________00010000____
181 ///
182 /// The Debug output shows the path that the decoding tree follows to reach the
183 /// the conclusion that there is a conflict.  VST4q8a is a vst4 to double-spaced
184 /// even registers, while VST4q8b is a vst4 to double-spaced odd regsisters.
185 ///
186 /// The encoding info in the .td files does not specify this meta information,
187 /// which could have been used by the decoder to resolve the conflict.  The
188 /// decoder could try to decode the even/odd register numbering and assign to
189 /// VST4q8a or VST4q8b, but for the time being, the decoder chooses the "a"
190 /// version and return the Opcode since the two have the same Asm format string.
191 namespace {
192 class Filter {
193 protected:
194   const FilterChooser *Owner;// points to the FilterChooser who owns this filter
195   unsigned StartBit; // the starting bit position
196   unsigned NumBits; // number of bits to filter
197   bool Mixed; // a mixed region contains both set and unset bits
198
199   // Map of well-known segment value to the set of uid's with that value.
200   std::map<uint64_t, std::vector<unsigned> > FilteredInstructions;
201
202   // Set of uid's with non-constant segment values.
203   std::vector<unsigned> VariableInstructions;
204
205   // Map of well-known segment value to its delegate.
206   std::map<unsigned, const FilterChooser*> FilterChooserMap;
207
208   // Number of instructions which fall under FilteredInstructions category.
209   unsigned NumFiltered;
210
211   // Keeps track of the last opcode in the filtered bucket.
212   unsigned LastOpcFiltered;
213
214 public:
215   unsigned getNumFiltered() const { return NumFiltered; }
216   unsigned getSingletonOpc() const {
217     assert(NumFiltered == 1);
218     return LastOpcFiltered;
219   }
220   // Return the filter chooser for the group of instructions without constant
221   // segment values.
222   const FilterChooser &getVariableFC() const {
223     assert(NumFiltered == 1);
224     assert(FilterChooserMap.size() == 1);
225     return *(FilterChooserMap.find((unsigned)-1)->second);
226   }
227
228   Filter(const Filter &f);
229   Filter(FilterChooser &owner, unsigned startBit, unsigned numBits, bool mixed);
230
231   ~Filter();
232
233   // Divides the decoding task into sub tasks and delegates them to the
234   // inferior FilterChooser's.
235   //
236   // A special case arises when there's only one entry in the filtered
237   // instructions.  In order to unambiguously decode the singleton, we need to
238   // match the remaining undecoded encoding bits against the singleton.
239   void recurse();
240
241   // Emit code to decode instructions given a segment or segments of bits.
242   void emit(raw_ostream &o, unsigned &Indentation) const;
243
244   // Returns the number of fanout produced by the filter.  More fanout implies
245   // the filter distinguishes more categories of instructions.
246   unsigned usefulness() const;
247 }; // End of class Filter
248 } // End anonymous namespace
249
250 // These are states of our finite state machines used in FilterChooser's
251 // filterProcessor() which produces the filter candidates to use.
252 typedef enum {
253   ATTR_NONE,
254   ATTR_FILTERED,
255   ATTR_ALL_SET,
256   ATTR_ALL_UNSET,
257   ATTR_MIXED
258 } bitAttr_t;
259
260 /// FilterChooser - FilterChooser chooses the best filter among a set of Filters
261 /// in order to perform the decoding of instructions at the current level.
262 ///
263 /// Decoding proceeds from the top down.  Based on the well-known encoding bits
264 /// of instructions available, FilterChooser builds up the possible Filters that
265 /// can further the task of decoding by distinguishing among the remaining
266 /// candidate instructions.
267 ///
268 /// Once a filter has been chosen, it is called upon to divide the decoding task
269 /// into sub-tasks and delegates them to its inferior FilterChoosers for further
270 /// processings.
271 ///
272 /// It is useful to think of a Filter as governing the switch stmts of the
273 /// decoding tree.  And each case is delegated to an inferior FilterChooser to
274 /// decide what further remaining bits to look at.
275 namespace {
276 class FilterChooser {
277 protected:
278   friend class Filter;
279
280   // Vector of codegen instructions to choose our filter.
281   const std::vector<const CodeGenInstruction*> &AllInstructions;
282
283   // Vector of uid's for this filter chooser to work on.
284   const std::vector<unsigned> &Opcodes;
285
286   // Lookup table for the operand decoding of instructions.
287   const std::map<unsigned, std::vector<OperandInfo> > &Operands;
288
289   // Vector of candidate filters.
290   std::vector<Filter> Filters;
291
292   // Array of bit values passed down from our parent.
293   // Set to all BIT_UNFILTERED's for Parent == NULL.
294   std::vector<bit_value_t> FilterBitValues;
295
296   // Links to the FilterChooser above us in the decoding tree.
297   const FilterChooser *Parent;
298
299   // Index of the best filter from Filters.
300   int BestIndex;
301
302   // Width of instructions
303   unsigned BitWidth;
304
305   // Parent emitter
306   const FixedLenDecoderEmitter *Emitter;
307
308 public:
309   FilterChooser(const FilterChooser &FC)
310     : AllInstructions(FC.AllInstructions), Opcodes(FC.Opcodes),
311       Operands(FC.Operands), Filters(FC.Filters),
312       FilterBitValues(FC.FilterBitValues), Parent(FC.Parent),
313       BestIndex(FC.BestIndex), BitWidth(FC.BitWidth),
314       Emitter(FC.Emitter) { }
315
316   FilterChooser(const std::vector<const CodeGenInstruction*> &Insts,
317                 const std::vector<unsigned> &IDs,
318                 const std::map<unsigned, std::vector<OperandInfo> > &Ops,
319                 unsigned BW,
320                 const FixedLenDecoderEmitter *E)
321     : AllInstructions(Insts), Opcodes(IDs), Operands(Ops), Filters(),
322       Parent(NULL), BestIndex(-1), BitWidth(BW), Emitter(E) {
323     for (unsigned i = 0; i < BitWidth; ++i)
324       FilterBitValues.push_back(BIT_UNFILTERED);
325
326     doFilter();
327   }
328
329   FilterChooser(const std::vector<const CodeGenInstruction*> &Insts,
330                 const std::vector<unsigned> &IDs,
331                 const std::map<unsigned, std::vector<OperandInfo> > &Ops,
332                 const std::vector<bit_value_t> &ParentFilterBitValues,
333                 const FilterChooser &parent)
334     : AllInstructions(Insts), Opcodes(IDs), Operands(Ops),
335       Filters(), FilterBitValues(ParentFilterBitValues),
336       Parent(&parent), BestIndex(-1), BitWidth(parent.BitWidth),
337       Emitter(parent.Emitter) {
338     doFilter();
339   }
340
341   // The top level filter chooser has NULL as its parent.
342   bool isTopLevel() const { return Parent == NULL; }
343
344   // Emit the top level typedef and decodeInstruction() function.
345   void emitTop(raw_ostream &o, unsigned Indentation,
346                const std::string &Namespace) const;
347
348 protected:
349   // Populates the insn given the uid.
350   void insnWithID(insn_t &Insn, unsigned Opcode) const {
351     BitsInit &Bits = getBitsField(*AllInstructions[Opcode]->TheDef, "Inst");
352
353     // We may have a SoftFail bitmask, which specifies a mask where an encoding
354     // may differ from the value in "Inst" and yet still be valid, but the
355     // disassembler should return SoftFail instead of Success.
356     //
357     // This is used for marking UNPREDICTABLE instructions in the ARM world.
358     BitsInit *SFBits =
359       AllInstructions[Opcode]->TheDef->getValueAsBitsInit("SoftFail");
360
361     for (unsigned i = 0; i < BitWidth; ++i) {
362       if (SFBits && bitFromBits(*SFBits, i) == BIT_TRUE)
363         Insn.push_back(BIT_UNSET);
364       else
365         Insn.push_back(bitFromBits(Bits, i));
366     }
367   }
368
369   // Returns the record name.
370   const std::string &nameWithID(unsigned Opcode) const {
371     return AllInstructions[Opcode]->TheDef->getName();
372   }
373
374   // Populates the field of the insn given the start position and the number of
375   // consecutive bits to scan for.
376   //
377   // Returns false if there exists any uninitialized bit value in the range.
378   // Returns true, otherwise.
379   bool fieldFromInsn(uint64_t &Field, insn_t &Insn, unsigned StartBit,
380                      unsigned NumBits) const;
381
382   /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
383   /// filter array as a series of chars.
384   void dumpFilterArray(raw_ostream &o,
385                        const std::vector<bit_value_t> & filter) const;
386
387   /// dumpStack - dumpStack traverses the filter chooser chain and calls
388   /// dumpFilterArray on each filter chooser up to the top level one.
389   void dumpStack(raw_ostream &o, const char *prefix) const;
390
391   Filter &bestFilter() {
392     assert(BestIndex != -1 && "BestIndex not set");
393     return Filters[BestIndex];
394   }
395
396   // Called from Filter::recurse() when singleton exists.  For debug purpose.
397   void SingletonExists(unsigned Opc) const;
398
399   bool PositionFiltered(unsigned i) const {
400     return ValueSet(FilterBitValues[i]);
401   }
402
403   // Calculates the island(s) needed to decode the instruction.
404   // This returns a lit of undecoded bits of an instructions, for example,
405   // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
406   // decoded bits in order to verify that the instruction matches the Opcode.
407   unsigned getIslands(std::vector<unsigned> &StartBits,
408                       std::vector<unsigned> &EndBits,
409                       std::vector<uint64_t> &FieldVals,
410                       const insn_t &Insn) const;
411
412   // Emits code to check the Predicates member of an instruction are true.
413   // Returns true if predicate matches were emitted, false otherwise.
414   bool emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
415                           unsigned Opc) const;
416
417   void emitSoftFailCheck(raw_ostream &o, unsigned Indentation,
418                          unsigned Opc) const;
419
420   // Emits code to decode the singleton.  Return true if we have matched all the
421   // well-known bits.
422   bool emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,
423                             unsigned Opc) const;
424
425   // Emits code to decode the singleton, and then to decode the rest.
426   void emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,
427                             const Filter &Best) const;
428
429   void emitBinaryParser(raw_ostream &o , unsigned &Indentation,
430                         const OperandInfo &OpInfo) const;
431
432   // Assign a single filter and run with it.
433   void runSingleFilter(unsigned startBit, unsigned numBit, bool mixed);
434
435   // reportRegion is a helper function for filterProcessor to mark a region as
436   // eligible for use as a filter region.
437   void reportRegion(bitAttr_t RA, unsigned StartBit, unsigned BitIndex,
438                     bool AllowMixed);
439
440   // FilterProcessor scans the well-known encoding bits of the instructions and
441   // builds up a list of candidate filters.  It chooses the best filter and
442   // recursively descends down the decoding tree.
443   bool filterProcessor(bool AllowMixed, bool Greedy = true);
444
445   // Decides on the best configuration of filter(s) to use in order to decode
446   // the instructions.  A conflict of instructions may occur, in which case we
447   // dump the conflict set to the standard error.
448   void doFilter();
449
450   // Emits code to decode our share of instructions.  Returns true if the
451   // emitted code causes a return, which occurs if we know how to decode
452   // the instruction at this level or the instruction is not decodeable.
453   bool emit(raw_ostream &o, unsigned &Indentation) const;
454 };
455 } // End anonymous namespace
456
457 ///////////////////////////
458 //                       //
459 // Filter Implementation //
460 //                       //
461 ///////////////////////////
462
463 Filter::Filter(const Filter &f)
464   : Owner(f.Owner), StartBit(f.StartBit), NumBits(f.NumBits), Mixed(f.Mixed),
465     FilteredInstructions(f.FilteredInstructions),
466     VariableInstructions(f.VariableInstructions),
467     FilterChooserMap(f.FilterChooserMap), NumFiltered(f.NumFiltered),
468     LastOpcFiltered(f.LastOpcFiltered) {
469 }
470
471 Filter::Filter(FilterChooser &owner, unsigned startBit, unsigned numBits,
472                bool mixed)
473   : Owner(&owner), StartBit(startBit), NumBits(numBits), Mixed(mixed) {
474   assert(StartBit + NumBits - 1 < Owner->BitWidth);
475
476   NumFiltered = 0;
477   LastOpcFiltered = 0;
478
479   for (unsigned i = 0, e = Owner->Opcodes.size(); i != e; ++i) {
480     insn_t Insn;
481
482     // Populates the insn given the uid.
483     Owner->insnWithID(Insn, Owner->Opcodes[i]);
484
485     uint64_t Field;
486     // Scans the segment for possibly well-specified encoding bits.
487     bool ok = Owner->fieldFromInsn(Field, Insn, StartBit, NumBits);
488
489     if (ok) {
490       // The encoding bits are well-known.  Lets add the uid of the
491       // instruction into the bucket keyed off the constant field value.
492       LastOpcFiltered = Owner->Opcodes[i];
493       FilteredInstructions[Field].push_back(LastOpcFiltered);
494       ++NumFiltered;
495     } else {
496       // Some of the encoding bit(s) are unspecified.  This contributes to
497       // one additional member of "Variable" instructions.
498       VariableInstructions.push_back(Owner->Opcodes[i]);
499     }
500   }
501
502   assert((FilteredInstructions.size() + VariableInstructions.size() > 0)
503          && "Filter returns no instruction categories");
504 }
505
506 Filter::~Filter() {
507   std::map<unsigned, const FilterChooser*>::iterator filterIterator;
508   for (filterIterator = FilterChooserMap.begin();
509        filterIterator != FilterChooserMap.end();
510        filterIterator++) {
511     delete filterIterator->second;
512   }
513 }
514
515 // Divides the decoding task into sub tasks and delegates them to the
516 // inferior FilterChooser's.
517 //
518 // A special case arises when there's only one entry in the filtered
519 // instructions.  In order to unambiguously decode the singleton, we need to
520 // match the remaining undecoded encoding bits against the singleton.
521 void Filter::recurse() {
522   std::map<uint64_t, std::vector<unsigned> >::const_iterator mapIterator;
523
524   // Starts by inheriting our parent filter chooser's filter bit values.
525   std::vector<bit_value_t> BitValueArray(Owner->FilterBitValues);
526
527   unsigned bitIndex;
528
529   if (VariableInstructions.size()) {
530     // Conservatively marks each segment position as BIT_UNSET.
531     for (bitIndex = 0; bitIndex < NumBits; bitIndex++)
532       BitValueArray[StartBit + bitIndex] = BIT_UNSET;
533
534     // Delegates to an inferior filter chooser for further processing on this
535     // group of instructions whose segment values are variable.
536     FilterChooserMap.insert(std::pair<unsigned, const FilterChooser*>(
537                               (unsigned)-1,
538                               new FilterChooser(Owner->AllInstructions,
539                                                 VariableInstructions,
540                                                 Owner->Operands,
541                                                 BitValueArray,
542                                                 *Owner)
543                               ));
544   }
545
546   // No need to recurse for a singleton filtered instruction.
547   // See also Filter::emit().
548   if (getNumFiltered() == 1) {
549     //Owner->SingletonExists(LastOpcFiltered);
550     assert(FilterChooserMap.size() == 1);
551     return;
552   }
553
554   // Otherwise, create sub choosers.
555   for (mapIterator = FilteredInstructions.begin();
556        mapIterator != FilteredInstructions.end();
557        mapIterator++) {
558
559     // Marks all the segment positions with either BIT_TRUE or BIT_FALSE.
560     for (bitIndex = 0; bitIndex < NumBits; bitIndex++) {
561       if (mapIterator->first & (1ULL << bitIndex))
562         BitValueArray[StartBit + bitIndex] = BIT_TRUE;
563       else
564         BitValueArray[StartBit + bitIndex] = BIT_FALSE;
565     }
566
567     // Delegates to an inferior filter chooser for further processing on this
568     // category of instructions.
569     FilterChooserMap.insert(std::pair<unsigned, const FilterChooser*>(
570                               mapIterator->first,
571                               new FilterChooser(Owner->AllInstructions,
572                                                 mapIterator->second,
573                                                 Owner->Operands,
574                                                 BitValueArray,
575                                                 *Owner)
576                               ));
577   }
578 }
579
580 // Emit code to decode instructions given a segment or segments of bits.
581 void Filter::emit(raw_ostream &o, unsigned &Indentation) const {
582   o.indent(Indentation) << "// Check Inst{";
583
584   if (NumBits > 1)
585     o << (StartBit + NumBits - 1) << '-';
586
587   o << StartBit << "} ...\n";
588
589   o.indent(Indentation) << "switch (fieldFromInstruction" << Owner->BitWidth
590                         << "(insn, " << StartBit << ", "
591                         << NumBits << ")) {\n";
592
593   std::map<unsigned, const FilterChooser*>::const_iterator filterIterator;
594
595   bool DefaultCase = false;
596   for (filterIterator = FilterChooserMap.begin();
597        filterIterator != FilterChooserMap.end();
598        filterIterator++) {
599
600     // Field value -1 implies a non-empty set of variable instructions.
601     // See also recurse().
602     if (filterIterator->first == (unsigned)-1) {
603       DefaultCase = true;
604
605       o.indent(Indentation) << "default:\n";
606       o.indent(Indentation) << "  break; // fallthrough\n";
607
608       // Closing curly brace for the switch statement.
609       // This is unconventional because we want the default processing to be
610       // performed for the fallthrough cases as well, i.e., when the "cases"
611       // did not prove a decoded instruction.
612       o.indent(Indentation) << "}\n";
613
614     } else
615       o.indent(Indentation) << "case " << filterIterator->first << ":\n";
616
617     // We arrive at a category of instructions with the same segment value.
618     // Now delegate to the sub filter chooser for further decodings.
619     // The case may fallthrough, which happens if the remaining well-known
620     // encoding bits do not match exactly.
621     if (!DefaultCase) { ++Indentation; ++Indentation; }
622
623     filterIterator->second->emit(o, Indentation);
624     // For top level default case, there's no need for a break statement.
625     if (Owner->isTopLevel() && DefaultCase)
626       break;
627     
628     o.indent(Indentation) << "break;\n";
629
630     if (!DefaultCase) { --Indentation; --Indentation; }
631   }
632
633   // If there is no default case, we still need to supply a closing brace.
634   if (!DefaultCase) {
635     // Closing curly brace for the switch statement.
636     o.indent(Indentation) << "}\n";
637   }
638 }
639
640 // Returns the number of fanout produced by the filter.  More fanout implies
641 // the filter distinguishes more categories of instructions.
642 unsigned Filter::usefulness() const {
643   if (VariableInstructions.size())
644     return FilteredInstructions.size();
645   else
646     return FilteredInstructions.size() + 1;
647 }
648
649 //////////////////////////////////
650 //                              //
651 // Filterchooser Implementation //
652 //                              //
653 //////////////////////////////////
654
655 // Emit the top level typedef and decodeInstruction() function.
656 void FilterChooser::emitTop(raw_ostream &o, unsigned Indentation,
657                             const std::string &Namespace) const {
658   o.indent(Indentation) <<
659     "static MCDisassembler::DecodeStatus decode" << Namespace << "Instruction"
660     << BitWidth << "(MCInst &MI, uint" << BitWidth
661     << "_t insn, uint64_t Address, "
662     << "const void *Decoder, const MCSubtargetInfo &STI) {\n";
663   o.indent(Indentation) << "  unsigned tmp = 0;\n";
664   o.indent(Indentation) << "  (void)tmp;\n";
665   o.indent(Indentation) << Emitter->Locals << "\n";
666   o.indent(Indentation) << "  uint64_t Bits = STI.getFeatureBits();\n";
667   o.indent(Indentation) << "  (void)Bits;\n";
668
669   ++Indentation; ++Indentation;
670   // Emits code to decode the instructions.
671   emit(o, Indentation);
672
673   o << '\n';
674   o.indent(Indentation) << "return " << Emitter->ReturnFail << ";\n";
675   --Indentation; --Indentation;
676
677   o.indent(Indentation) << "}\n";
678
679   o << '\n';
680 }
681
682 // Populates the field of the insn given the start position and the number of
683 // consecutive bits to scan for.
684 //
685 // Returns false if and on the first uninitialized bit value encountered.
686 // Returns true, otherwise.
687 bool FilterChooser::fieldFromInsn(uint64_t &Field, insn_t &Insn,
688                                   unsigned StartBit, unsigned NumBits) const {
689   Field = 0;
690
691   for (unsigned i = 0; i < NumBits; ++i) {
692     if (Insn[StartBit + i] == BIT_UNSET)
693       return false;
694
695     if (Insn[StartBit + i] == BIT_TRUE)
696       Field = Field | (1ULL << i);
697   }
698
699   return true;
700 }
701
702 /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
703 /// filter array as a series of chars.
704 void FilterChooser::dumpFilterArray(raw_ostream &o,
705                                  const std::vector<bit_value_t> &filter) const {
706   unsigned bitIndex;
707
708   for (bitIndex = BitWidth; bitIndex > 0; bitIndex--) {
709     switch (filter[bitIndex - 1]) {
710     case BIT_UNFILTERED:
711       o << ".";
712       break;
713     case BIT_UNSET:
714       o << "_";
715       break;
716     case BIT_TRUE:
717       o << "1";
718       break;
719     case BIT_FALSE:
720       o << "0";
721       break;
722     }
723   }
724 }
725
726 /// dumpStack - dumpStack traverses the filter chooser chain and calls
727 /// dumpFilterArray on each filter chooser up to the top level one.
728 void FilterChooser::dumpStack(raw_ostream &o, const char *prefix) const {
729   const FilterChooser *current = this;
730
731   while (current) {
732     o << prefix;
733     dumpFilterArray(o, current->FilterBitValues);
734     o << '\n';
735     current = current->Parent;
736   }
737 }
738
739 // Called from Filter::recurse() when singleton exists.  For debug purpose.
740 void FilterChooser::SingletonExists(unsigned Opc) const {
741   insn_t Insn0;
742   insnWithID(Insn0, Opc);
743
744   errs() << "Singleton exists: " << nameWithID(Opc)
745          << " with its decoding dominating ";
746   for (unsigned i = 0; i < Opcodes.size(); ++i) {
747     if (Opcodes[i] == Opc) continue;
748     errs() << nameWithID(Opcodes[i]) << ' ';
749   }
750   errs() << '\n';
751
752   dumpStack(errs(), "\t\t");
753   for (unsigned i = 0; i < Opcodes.size(); ++i) {
754     const std::string &Name = nameWithID(Opcodes[i]);
755
756     errs() << '\t' << Name << " ";
757     dumpBits(errs(),
758              getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
759     errs() << '\n';
760   }
761 }
762
763 // Calculates the island(s) needed to decode the instruction.
764 // This returns a list of undecoded bits of an instructions, for example,
765 // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
766 // decoded bits in order to verify that the instruction matches the Opcode.
767 unsigned FilterChooser::getIslands(std::vector<unsigned> &StartBits,
768                                    std::vector<unsigned> &EndBits,
769                                    std::vector<uint64_t> &FieldVals,
770                                    const insn_t &Insn) const {
771   unsigned Num, BitNo;
772   Num = BitNo = 0;
773
774   uint64_t FieldVal = 0;
775
776   // 0: Init
777   // 1: Water (the bit value does not affect decoding)
778   // 2: Island (well-known bit value needed for decoding)
779   int State = 0;
780   int Val = -1;
781
782   for (unsigned i = 0; i < BitWidth; ++i) {
783     Val = Value(Insn[i]);
784     bool Filtered = PositionFiltered(i);
785     switch (State) {
786     default: llvm_unreachable("Unreachable code!");
787     case 0:
788     case 1:
789       if (Filtered || Val == -1)
790         State = 1; // Still in Water
791       else {
792         State = 2; // Into the Island
793         BitNo = 0;
794         StartBits.push_back(i);
795         FieldVal = Val;
796       }
797       break;
798     case 2:
799       if (Filtered || Val == -1) {
800         State = 1; // Into the Water
801         EndBits.push_back(i - 1);
802         FieldVals.push_back(FieldVal);
803         ++Num;
804       } else {
805         State = 2; // Still in Island
806         ++BitNo;
807         FieldVal = FieldVal | Val << BitNo;
808       }
809       break;
810     }
811   }
812   // If we are still in Island after the loop, do some housekeeping.
813   if (State == 2) {
814     EndBits.push_back(BitWidth - 1);
815     FieldVals.push_back(FieldVal);
816     ++Num;
817   }
818
819   assert(StartBits.size() == Num && EndBits.size() == Num &&
820          FieldVals.size() == Num);
821   return Num;
822 }
823
824 void FilterChooser::emitBinaryParser(raw_ostream &o, unsigned &Indentation,
825                                      const OperandInfo &OpInfo) const {
826   const std::string &Decoder = OpInfo.Decoder;
827
828   if (OpInfo.numFields() == 1) {
829     OperandInfo::const_iterator OI = OpInfo.begin();
830     o.indent(Indentation) << "  tmp = fieldFromInstruction" << BitWidth
831                             << "(insn, " << OI->Base << ", " << OI->Width
832                             << ");\n";
833   } else {
834     o.indent(Indentation) << "  tmp = 0;\n";
835     for (OperandInfo::const_iterator OI = OpInfo.begin(), OE = OpInfo.end();
836          OI != OE; ++OI) {
837       o.indent(Indentation) << "  tmp |= (fieldFromInstruction" << BitWidth
838                             << "(insn, " << OI->Base << ", " << OI->Width
839                             << ") << " << OI->Offset << ");\n";
840     }
841   }
842
843   if (Decoder != "")
844     o.indent(Indentation) << "  " << Emitter->GuardPrefix << Decoder
845                           << "(MI, tmp, Address, Decoder)"
846                           << Emitter->GuardPostfix << "\n";
847   else
848     o.indent(Indentation) << "  MI.addOperand(MCOperand::CreateImm(tmp));\n";
849
850 }
851
852 static void emitSinglePredicateMatch(raw_ostream &o, StringRef str,
853                                      const std::string &PredicateNamespace) {
854   if (str[0] == '!')
855     o << "!(Bits & " << PredicateNamespace << "::"
856       << str.slice(1,str.size()) << ")";
857   else
858     o << "(Bits & " << PredicateNamespace << "::" << str << ")";
859 }
860
861 bool FilterChooser::emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
862                                        unsigned Opc) const {
863   ListInit *Predicates =
864     AllInstructions[Opc]->TheDef->getValueAsListInit("Predicates");
865   for (unsigned i = 0; i < Predicates->getSize(); ++i) {
866     Record *Pred = Predicates->getElementAsRecord(i);
867     if (!Pred->getValue("AssemblerMatcherPredicate"))
868       continue;
869
870     std::string P = Pred->getValueAsString("AssemblerCondString");
871
872     if (!P.length())
873       continue;
874
875     if (i != 0)
876       o << " && ";
877
878     StringRef SR(P);
879     std::pair<StringRef, StringRef> pairs = SR.split(',');
880     while (pairs.second.size()) {
881       emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
882       o << " && ";
883       pairs = pairs.second.split(',');
884     }
885     emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
886   }
887   return Predicates->getSize() > 0;
888 }
889
890 void FilterChooser::emitSoftFailCheck(raw_ostream &o, unsigned Indentation,
891                                       unsigned Opc) const {
892   BitsInit *SFBits =
893     AllInstructions[Opc]->TheDef->getValueAsBitsInit("SoftFail");
894   if (!SFBits) return;
895   BitsInit *InstBits = AllInstructions[Opc]->TheDef->getValueAsBitsInit("Inst");
896
897   APInt PositiveMask(BitWidth, 0ULL);
898   APInt NegativeMask(BitWidth, 0ULL);
899   for (unsigned i = 0; i < BitWidth; ++i) {
900     bit_value_t B = bitFromBits(*SFBits, i);
901     bit_value_t IB = bitFromBits(*InstBits, i);
902
903     if (B != BIT_TRUE) continue;
904
905     switch (IB) {
906     case BIT_FALSE:
907       // The bit is meant to be false, so emit a check to see if it is true.
908       PositiveMask.setBit(i);
909       break;
910     case BIT_TRUE:
911       // The bit is meant to be true, so emit a check to see if it is false.
912       NegativeMask.setBit(i);
913       break;
914     default:
915       // The bit is not set; this must be an error!
916       StringRef Name = AllInstructions[Opc]->TheDef->getName();
917       errs() << "SoftFail Conflict: bit SoftFail{" << i << "} in "
918              << Name
919              << " is set but Inst{" << i <<"} is unset!\n"
920              << "  - You can only mark a bit as SoftFail if it is fully defined"
921              << " (1/0 - not '?') in Inst\n";
922       o << "#error SoftFail Conflict, " << Name << "::SoftFail{" << i 
923         << "} set but Inst{" << i << "} undefined!\n";
924     }
925   }
926
927   bool NeedPositiveMask = PositiveMask.getBoolValue();
928   bool NeedNegativeMask = NegativeMask.getBoolValue();
929
930   if (!NeedPositiveMask && !NeedNegativeMask)
931     return;
932
933   std::string PositiveMaskStr = PositiveMask.toString(16, /*signed=*/false);
934   std::string NegativeMaskStr = NegativeMask.toString(16, /*signed=*/false);
935   StringRef BitExt = "";
936   if (BitWidth > 32)
937     BitExt = "ULL";
938
939   o.indent(Indentation) << "if (";
940   if (NeedPositiveMask)
941     o << "insn & 0x" << PositiveMaskStr << BitExt;
942   if (NeedPositiveMask && NeedNegativeMask)
943     o << " || ";
944   if (NeedNegativeMask)
945     o << "~insn & 0x" << NegativeMaskStr << BitExt;
946   o << ")\n";
947   o.indent(Indentation+2) << "S = MCDisassembler::SoftFail;\n";
948 }
949
950 // Emits code to decode the singleton.  Return true if we have matched all the
951 // well-known bits.
952 bool FilterChooser::emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,
953                                          unsigned Opc) const {
954   std::vector<unsigned> StartBits;
955   std::vector<unsigned> EndBits;
956   std::vector<uint64_t> FieldVals;
957   insn_t Insn;
958   insnWithID(Insn, Opc);
959
960   // Look for islands of undecoded bits of the singleton.
961   getIslands(StartBits, EndBits, FieldVals, Insn);
962
963   unsigned Size = StartBits.size();
964   unsigned I, NumBits;
965
966   // If we have matched all the well-known bits, just issue a return.
967   if (Size == 0) {
968     o.indent(Indentation) << "if (";
969     if (!emitPredicateMatch(o, Indentation, Opc))
970       o << "1";
971     o << ") {\n";
972     emitSoftFailCheck(o, Indentation+2, Opc);
973     o.indent(Indentation) << "  MI.setOpcode(" << Opc << ");\n";
974     std::map<unsigned, std::vector<OperandInfo> >::const_iterator OpIter =
975       Operands.find(Opc);
976     const std::vector<OperandInfo>& InsnOperands = OpIter->second;
977     for (std::vector<OperandInfo>::const_iterator
978          I = InsnOperands.begin(), E = InsnOperands.end(); I != E; ++I) {
979       // If a custom instruction decoder was specified, use that.
980       if (I->numFields() == 0 && I->Decoder.size()) {
981         o.indent(Indentation) << "  " << Emitter->GuardPrefix << I->Decoder
982                               << "(MI, insn, Address, Decoder)"
983                               << Emitter->GuardPostfix << "\n";
984         break;
985       }
986
987       emitBinaryParser(o, Indentation, *I);
988     }
989
990     o.indent(Indentation) << "  return " << Emitter->ReturnOK << "; // "
991                           << nameWithID(Opc) << '\n';
992     o.indent(Indentation) << "}\n"; // Closing predicate block.
993     return true;
994   }
995
996   // Otherwise, there are more decodings to be done!
997
998   // Emit code to match the island(s) for the singleton.
999   o.indent(Indentation) << "// Check ";
1000
1001   for (I = Size; I != 0; --I) {
1002     o << "Inst{" << EndBits[I-1] << '-' << StartBits[I-1] << "} ";
1003     if (I > 1)
1004       o << " && ";
1005     else
1006       o << "for singleton decoding...\n";
1007   }
1008
1009   o.indent(Indentation) << "if (";
1010   if (emitPredicateMatch(o, Indentation, Opc)) {
1011     o << " &&\n";
1012     o.indent(Indentation+4);
1013   }
1014
1015   for (I = Size; I != 0; --I) {
1016     NumBits = EndBits[I-1] - StartBits[I-1] + 1;
1017     o << "fieldFromInstruction" << BitWidth << "(insn, "
1018       << StartBits[I-1] << ", " << NumBits
1019       << ") == " << FieldVals[I-1];
1020     if (I > 1)
1021       o << " && ";
1022     else
1023       o << ") {\n";
1024   }
1025   emitSoftFailCheck(o, Indentation+2, Opc);
1026   o.indent(Indentation) << "  MI.setOpcode(" << Opc << ");\n";
1027   std::map<unsigned, std::vector<OperandInfo> >::const_iterator OpIter =
1028     Operands.find(Opc);
1029   const std::vector<OperandInfo>& InsnOperands = OpIter->second;
1030   for (std::vector<OperandInfo>::const_iterator
1031        I = InsnOperands.begin(), E = InsnOperands.end(); I != E; ++I) {
1032     // If a custom instruction decoder was specified, use that.
1033     if (I->numFields() == 0 && I->Decoder.size()) {
1034       o.indent(Indentation) << "  " << Emitter->GuardPrefix << I->Decoder
1035                             << "(MI, insn, Address, Decoder)"
1036                             << Emitter->GuardPostfix << "\n";
1037       break;
1038     }
1039
1040     emitBinaryParser(o, Indentation, *I);
1041   }
1042   o.indent(Indentation) << "  return " << Emitter->ReturnOK << "; // "
1043                         << nameWithID(Opc) << '\n';
1044   o.indent(Indentation) << "}\n";
1045
1046   return false;
1047 }
1048
1049 // Emits code to decode the singleton, and then to decode the rest.
1050 void FilterChooser::emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,
1051                                          const Filter &Best) const {
1052
1053   unsigned Opc = Best.getSingletonOpc();
1054
1055   emitSingletonDecoder(o, Indentation, Opc);
1056
1057   // Emit code for the rest.
1058   o.indent(Indentation) << "else\n";
1059
1060   Indentation += 2;
1061   Best.getVariableFC().emit(o, Indentation);
1062   Indentation -= 2;
1063 }
1064
1065 // Assign a single filter and run with it.  Top level API client can initialize
1066 // with a single filter to start the filtering process.
1067 void FilterChooser::runSingleFilter(unsigned startBit, unsigned numBit,
1068                                     bool mixed) {
1069   Filters.clear();
1070   Filter F(*this, startBit, numBit, true);
1071   Filters.push_back(F);
1072   BestIndex = 0; // Sole Filter instance to choose from.
1073   bestFilter().recurse();
1074 }
1075
1076 // reportRegion is a helper function for filterProcessor to mark a region as
1077 // eligible for use as a filter region.
1078 void FilterChooser::reportRegion(bitAttr_t RA, unsigned StartBit,
1079                                  unsigned BitIndex, bool AllowMixed) {
1080   if (RA == ATTR_MIXED && AllowMixed)
1081     Filters.push_back(Filter(*this, StartBit, BitIndex - StartBit, true));
1082   else if (RA == ATTR_ALL_SET && !AllowMixed)
1083     Filters.push_back(Filter(*this, StartBit, BitIndex - StartBit, false));
1084 }
1085
1086 // FilterProcessor scans the well-known encoding bits of the instructions and
1087 // builds up a list of candidate filters.  It chooses the best filter and
1088 // recursively descends down the decoding tree.
1089 bool FilterChooser::filterProcessor(bool AllowMixed, bool Greedy) {
1090   Filters.clear();
1091   BestIndex = -1;
1092   unsigned numInstructions = Opcodes.size();
1093
1094   assert(numInstructions && "Filter created with no instructions");
1095
1096   // No further filtering is necessary.
1097   if (numInstructions == 1)
1098     return true;
1099
1100   // Heuristics.  See also doFilter()'s "Heuristics" comment when num of
1101   // instructions is 3.
1102   if (AllowMixed && !Greedy) {
1103     assert(numInstructions == 3);
1104
1105     for (unsigned i = 0; i < Opcodes.size(); ++i) {
1106       std::vector<unsigned> StartBits;
1107       std::vector<unsigned> EndBits;
1108       std::vector<uint64_t> FieldVals;
1109       insn_t Insn;
1110
1111       insnWithID(Insn, Opcodes[i]);
1112
1113       // Look for islands of undecoded bits of any instruction.
1114       if (getIslands(StartBits, EndBits, FieldVals, Insn) > 0) {
1115         // Found an instruction with island(s).  Now just assign a filter.
1116         runSingleFilter(StartBits[0], EndBits[0] - StartBits[0] + 1, true);
1117         return true;
1118       }
1119     }
1120   }
1121
1122   unsigned BitIndex, InsnIndex;
1123
1124   // We maintain BIT_WIDTH copies of the bitAttrs automaton.
1125   // The automaton consumes the corresponding bit from each
1126   // instruction.
1127   //
1128   //   Input symbols: 0, 1, and _ (unset).
1129   //   States:        NONE, FILTERED, ALL_SET, ALL_UNSET, and MIXED.
1130   //   Initial state: NONE.
1131   //
1132   // (NONE) ------- [01] -> (ALL_SET)
1133   // (NONE) ------- _ ----> (ALL_UNSET)
1134   // (ALL_SET) ---- [01] -> (ALL_SET)
1135   // (ALL_SET) ---- _ ----> (MIXED)
1136   // (ALL_UNSET) -- [01] -> (MIXED)
1137   // (ALL_UNSET) -- _ ----> (ALL_UNSET)
1138   // (MIXED) ------ . ----> (MIXED)
1139   // (FILTERED)---- . ----> (FILTERED)
1140
1141   std::vector<bitAttr_t> bitAttrs;
1142
1143   // FILTERED bit positions provide no entropy and are not worthy of pursuing.
1144   // Filter::recurse() set either BIT_TRUE or BIT_FALSE for each position.
1145   for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex)
1146     if (FilterBitValues[BitIndex] == BIT_TRUE ||
1147         FilterBitValues[BitIndex] == BIT_FALSE)
1148       bitAttrs.push_back(ATTR_FILTERED);
1149     else
1150       bitAttrs.push_back(ATTR_NONE);
1151
1152   for (InsnIndex = 0; InsnIndex < numInstructions; ++InsnIndex) {
1153     insn_t insn;
1154
1155     insnWithID(insn, Opcodes[InsnIndex]);
1156
1157     for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
1158       switch (bitAttrs[BitIndex]) {
1159       case ATTR_NONE:
1160         if (insn[BitIndex] == BIT_UNSET)
1161           bitAttrs[BitIndex] = ATTR_ALL_UNSET;
1162         else
1163           bitAttrs[BitIndex] = ATTR_ALL_SET;
1164         break;
1165       case ATTR_ALL_SET:
1166         if (insn[BitIndex] == BIT_UNSET)
1167           bitAttrs[BitIndex] = ATTR_MIXED;
1168         break;
1169       case ATTR_ALL_UNSET:
1170         if (insn[BitIndex] != BIT_UNSET)
1171           bitAttrs[BitIndex] = ATTR_MIXED;
1172         break;
1173       case ATTR_MIXED:
1174       case ATTR_FILTERED:
1175         break;
1176       }
1177     }
1178   }
1179
1180   // The regionAttr automaton consumes the bitAttrs automatons' state,
1181   // lowest-to-highest.
1182   //
1183   //   Input symbols: F(iltered), (all_)S(et), (all_)U(nset), M(ixed)
1184   //   States:        NONE, ALL_SET, MIXED
1185   //   Initial state: NONE
1186   //
1187   // (NONE) ----- F --> (NONE)
1188   // (NONE) ----- S --> (ALL_SET)     ; and set region start
1189   // (NONE) ----- U --> (NONE)
1190   // (NONE) ----- M --> (MIXED)       ; and set region start
1191   // (ALL_SET) -- F --> (NONE)        ; and report an ALL_SET region
1192   // (ALL_SET) -- S --> (ALL_SET)
1193   // (ALL_SET) -- U --> (NONE)        ; and report an ALL_SET region
1194   // (ALL_SET) -- M --> (MIXED)       ; and report an ALL_SET region
1195   // (MIXED) ---- F --> (NONE)        ; and report a MIXED region
1196   // (MIXED) ---- S --> (ALL_SET)     ; and report a MIXED region
1197   // (MIXED) ---- U --> (NONE)        ; and report a MIXED region
1198   // (MIXED) ---- M --> (MIXED)
1199
1200   bitAttr_t RA = ATTR_NONE;
1201   unsigned StartBit = 0;
1202
1203   for (BitIndex = 0; BitIndex < BitWidth; BitIndex++) {
1204     bitAttr_t bitAttr = bitAttrs[BitIndex];
1205
1206     assert(bitAttr != ATTR_NONE && "Bit without attributes");
1207
1208     switch (RA) {
1209     case ATTR_NONE:
1210       switch (bitAttr) {
1211       case ATTR_FILTERED:
1212         break;
1213       case ATTR_ALL_SET:
1214         StartBit = BitIndex;
1215         RA = ATTR_ALL_SET;
1216         break;
1217       case ATTR_ALL_UNSET:
1218         break;
1219       case ATTR_MIXED:
1220         StartBit = BitIndex;
1221         RA = ATTR_MIXED;
1222         break;
1223       default:
1224         llvm_unreachable("Unexpected bitAttr!");
1225       }
1226       break;
1227     case ATTR_ALL_SET:
1228       switch (bitAttr) {
1229       case ATTR_FILTERED:
1230         reportRegion(RA, StartBit, BitIndex, AllowMixed);
1231         RA = ATTR_NONE;
1232         break;
1233       case ATTR_ALL_SET:
1234         break;
1235       case ATTR_ALL_UNSET:
1236         reportRegion(RA, StartBit, BitIndex, AllowMixed);
1237         RA = ATTR_NONE;
1238         break;
1239       case ATTR_MIXED:
1240         reportRegion(RA, StartBit, BitIndex, AllowMixed);
1241         StartBit = BitIndex;
1242         RA = ATTR_MIXED;
1243         break;
1244       default:
1245         llvm_unreachable("Unexpected bitAttr!");
1246       }
1247       break;
1248     case ATTR_MIXED:
1249       switch (bitAttr) {
1250       case ATTR_FILTERED:
1251         reportRegion(RA, StartBit, BitIndex, AllowMixed);
1252         StartBit = BitIndex;
1253         RA = ATTR_NONE;
1254         break;
1255       case ATTR_ALL_SET:
1256         reportRegion(RA, StartBit, BitIndex, AllowMixed);
1257         StartBit = BitIndex;
1258         RA = ATTR_ALL_SET;
1259         break;
1260       case ATTR_ALL_UNSET:
1261         reportRegion(RA, StartBit, BitIndex, AllowMixed);
1262         RA = ATTR_NONE;
1263         break;
1264       case ATTR_MIXED:
1265         break;
1266       default:
1267         llvm_unreachable("Unexpected bitAttr!");
1268       }
1269       break;
1270     case ATTR_ALL_UNSET:
1271       llvm_unreachable("regionAttr state machine has no ATTR_UNSET state");
1272     case ATTR_FILTERED:
1273       llvm_unreachable("regionAttr state machine has no ATTR_FILTERED state");
1274     }
1275   }
1276
1277   // At the end, if we're still in ALL_SET or MIXED states, report a region
1278   switch (RA) {
1279   case ATTR_NONE:
1280     break;
1281   case ATTR_FILTERED:
1282     break;
1283   case ATTR_ALL_SET:
1284     reportRegion(RA, StartBit, BitIndex, AllowMixed);
1285     break;
1286   case ATTR_ALL_UNSET:
1287     break;
1288   case ATTR_MIXED:
1289     reportRegion(RA, StartBit, BitIndex, AllowMixed);
1290     break;
1291   }
1292
1293   // We have finished with the filter processings.  Now it's time to choose
1294   // the best performing filter.
1295   BestIndex = 0;
1296   bool AllUseless = true;
1297   unsigned BestScore = 0;
1298
1299   for (unsigned i = 0, e = Filters.size(); i != e; ++i) {
1300     unsigned Usefulness = Filters[i].usefulness();
1301
1302     if (Usefulness)
1303       AllUseless = false;
1304
1305     if (Usefulness > BestScore) {
1306       BestIndex = i;
1307       BestScore = Usefulness;
1308     }
1309   }
1310
1311   if (!AllUseless)
1312     bestFilter().recurse();
1313
1314   return !AllUseless;
1315 } // end of FilterChooser::filterProcessor(bool)
1316
1317 // Decides on the best configuration of filter(s) to use in order to decode
1318 // the instructions.  A conflict of instructions may occur, in which case we
1319 // dump the conflict set to the standard error.
1320 void FilterChooser::doFilter() {
1321   unsigned Num = Opcodes.size();
1322   assert(Num && "FilterChooser created with no instructions");
1323
1324   // Try regions of consecutive known bit values first.
1325   if (filterProcessor(false))
1326     return;
1327
1328   // Then regions of mixed bits (both known and unitialized bit values allowed).
1329   if (filterProcessor(true))
1330     return;
1331
1332   // Heuristics to cope with conflict set {t2CMPrs, t2SUBSrr, t2SUBSrs} where
1333   // no single instruction for the maximum ATTR_MIXED region Inst{14-4} has a
1334   // well-known encoding pattern.  In such case, we backtrack and scan for the
1335   // the very first consecutive ATTR_ALL_SET region and assign a filter to it.
1336   if (Num == 3 && filterProcessor(true, false))
1337     return;
1338
1339   // If we come to here, the instruction decoding has failed.
1340   // Set the BestIndex to -1 to indicate so.
1341   BestIndex = -1;
1342 }
1343
1344 // Emits code to decode our share of instructions.  Returns true if the
1345 // emitted code causes a return, which occurs if we know how to decode
1346 // the instruction at this level or the instruction is not decodeable.
1347 bool FilterChooser::emit(raw_ostream &o, unsigned &Indentation) const {
1348   if (Opcodes.size() == 1)
1349     // There is only one instruction in the set, which is great!
1350     // Call emitSingletonDecoder() to see whether there are any remaining
1351     // encodings bits.
1352     return emitSingletonDecoder(o, Indentation, Opcodes[0]);
1353
1354   // Choose the best filter to do the decodings!
1355   if (BestIndex != -1) {
1356     const Filter &Best = Filters[BestIndex];
1357     if (Best.getNumFiltered() == 1)
1358       emitSingletonDecoder(o, Indentation, Best);
1359     else
1360       Best.emit(o, Indentation);
1361     return false;
1362   }
1363
1364   // We don't know how to decode these instructions!  Return 0 and dump the
1365   // conflict set!
1366   o.indent(Indentation) << "return 0;" << " // Conflict set: ";
1367   for (int i = 0, N = Opcodes.size(); i < N; ++i) {
1368     o << nameWithID(Opcodes[i]);
1369     if (i < (N - 1))
1370       o << ", ";
1371     else
1372       o << '\n';
1373   }
1374
1375   // Print out useful conflict information for postmortem analysis.
1376   errs() << "Decoding Conflict:\n";
1377
1378   dumpStack(errs(), "\t\t");
1379
1380   for (unsigned i = 0; i < Opcodes.size(); ++i) {
1381     const std::string &Name = nameWithID(Opcodes[i]);
1382
1383     errs() << '\t' << Name << " ";
1384     dumpBits(errs(),
1385              getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
1386     errs() << '\n';
1387   }
1388
1389   return true;
1390 }
1391
1392 static bool populateInstruction(const CodeGenInstruction &CGI, unsigned Opc,
1393                        std::map<unsigned, std::vector<OperandInfo> > &Operands){
1394   const Record &Def = *CGI.TheDef;
1395   // If all the bit positions are not specified; do not decode this instruction.
1396   // We are bound to fail!  For proper disassembly, the well-known encoding bits
1397   // of the instruction must be fully specified.
1398   //
1399   // This also removes pseudo instructions from considerations of disassembly,
1400   // which is a better design and less fragile than the name matchings.
1401   // Ignore "asm parser only" instructions.
1402   if (Def.getValueAsBit("isAsmParserOnly") ||
1403       Def.getValueAsBit("isCodeGenOnly"))
1404     return false;
1405
1406   BitsInit &Bits = getBitsField(Def, "Inst");
1407   if (Bits.allInComplete()) return false;
1408
1409   std::vector<OperandInfo> InsnOperands;
1410
1411   // If the instruction has specified a custom decoding hook, use that instead
1412   // of trying to auto-generate the decoder.
1413   std::string InstDecoder = Def.getValueAsString("DecoderMethod");
1414   if (InstDecoder != "") {
1415     InsnOperands.push_back(OperandInfo(InstDecoder));
1416     Operands[Opc] = InsnOperands;
1417     return true;
1418   }
1419
1420   // Generate a description of the operand of the instruction that we know
1421   // how to decode automatically.
1422   // FIXME: We'll need to have a way to manually override this as needed.
1423
1424   // Gather the outputs/inputs of the instruction, so we can find their
1425   // positions in the encoding.  This assumes for now that they appear in the
1426   // MCInst in the order that they're listed.
1427   std::vector<std::pair<Init*, std::string> > InOutOperands;
1428   DagInit *Out  = Def.getValueAsDag("OutOperandList");
1429   DagInit *In  = Def.getValueAsDag("InOperandList");
1430   for (unsigned i = 0; i < Out->getNumArgs(); ++i)
1431     InOutOperands.push_back(std::make_pair(Out->getArg(i), Out->getArgName(i)));
1432   for (unsigned i = 0; i < In->getNumArgs(); ++i)
1433     InOutOperands.push_back(std::make_pair(In->getArg(i), In->getArgName(i)));
1434
1435   // Search for tied operands, so that we can correctly instantiate
1436   // operands that are not explicitly represented in the encoding.
1437   std::map<std::string, std::string> TiedNames;
1438   for (unsigned i = 0; i < CGI.Operands.size(); ++i) {
1439     int tiedTo = CGI.Operands[i].getTiedRegister();
1440     if (tiedTo != -1) {
1441       TiedNames[InOutOperands[i].second] = InOutOperands[tiedTo].second;
1442       TiedNames[InOutOperands[tiedTo].second] = InOutOperands[i].second;
1443     }
1444   }
1445
1446   // For each operand, see if we can figure out where it is encoded.
1447   for (std::vector<std::pair<Init*, std::string> >::const_iterator
1448        NI = InOutOperands.begin(), NE = InOutOperands.end(); NI != NE; ++NI) {
1449     std::string Decoder = "";
1450
1451     // At this point, we can locate the field, but we need to know how to
1452     // interpret it.  As a first step, require the target to provide callbacks
1453     // for decoding register classes.
1454     // FIXME: This need to be extended to handle instructions with custom
1455     // decoder methods, and operands with (simple) MIOperandInfo's.
1456     TypedInit *TI = dynamic_cast<TypedInit*>(NI->first);
1457     RecordRecTy *Type = dynamic_cast<RecordRecTy*>(TI->getType());
1458     Record *TypeRecord = Type->getRecord();
1459     bool isReg = false;
1460     if (TypeRecord->isSubClassOf("RegisterOperand"))
1461       TypeRecord = TypeRecord->getValueAsDef("RegClass");
1462     if (TypeRecord->isSubClassOf("RegisterClass")) {
1463       Decoder = "Decode" + TypeRecord->getName() + "RegisterClass";
1464       isReg = true;
1465     }
1466
1467     RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod");
1468     StringInit *String = DecoderString ?
1469       dynamic_cast<StringInit*>(DecoderString->getValue()) : 0;
1470     if (!isReg && String && String->getValue() != "")
1471       Decoder = String->getValue();
1472
1473     OperandInfo OpInfo(Decoder);
1474     unsigned Base = ~0U;
1475     unsigned Width = 0;
1476     unsigned Offset = 0;
1477
1478     for (unsigned bi = 0; bi < Bits.getNumBits(); ++bi) {
1479       VarInit *Var = 0;
1480       VarBitInit *BI = dynamic_cast<VarBitInit*>(Bits.getBit(bi));
1481       if (BI)
1482         Var = dynamic_cast<VarInit*>(BI->getVariable());
1483       else
1484         Var = dynamic_cast<VarInit*>(Bits.getBit(bi));
1485
1486       if (!Var) {
1487         if (Base != ~0U) {
1488           OpInfo.addField(Base, Width, Offset);
1489           Base = ~0U;
1490           Width = 0;
1491           Offset = 0;
1492         }
1493         continue;
1494       }
1495
1496       if (Var->getName() != NI->second &&
1497           Var->getName() != TiedNames[NI->second]) {
1498         if (Base != ~0U) {
1499           OpInfo.addField(Base, Width, Offset);
1500           Base = ~0U;
1501           Width = 0;
1502           Offset = 0;
1503         }
1504         continue;
1505       }
1506
1507       if (Base == ~0U) {
1508         Base = bi;
1509         Width = 1;
1510         Offset = BI ? BI->getBitNum() : 0;
1511       } else if (BI && BI->getBitNum() != Offset + Width) {
1512         OpInfo.addField(Base, Width, Offset);
1513         Base = bi;
1514         Width = 1;
1515         Offset = BI->getBitNum();
1516       } else {
1517         ++Width;
1518       }
1519     }
1520
1521     if (Base != ~0U)
1522       OpInfo.addField(Base, Width, Offset);
1523
1524     if (OpInfo.numFields() > 0)
1525       InsnOperands.push_back(OpInfo);
1526   }
1527
1528   Operands[Opc] = InsnOperands;
1529
1530
1531 #if 0
1532   DEBUG({
1533       // Dumps the instruction encoding bits.
1534       dumpBits(errs(), Bits);
1535
1536       errs() << '\n';
1537
1538       // Dumps the list of operand info.
1539       for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) {
1540         const CGIOperandList::OperandInfo &Info = CGI.Operands[i];
1541         const std::string &OperandName = Info.Name;
1542         const Record &OperandDef = *Info.Rec;
1543
1544         errs() << "\t" << OperandName << " (" << OperandDef.getName() << ")\n";
1545       }
1546     });
1547 #endif
1548
1549   return true;
1550 }
1551
1552 static void emitHelper(llvm::raw_ostream &o, unsigned BitWidth) {
1553   unsigned Indentation = 0;
1554   std::string WidthStr = "uint" + utostr(BitWidth) + "_t";
1555
1556   o << '\n';
1557
1558   o.indent(Indentation) << "static " << WidthStr <<
1559     " fieldFromInstruction" << BitWidth <<
1560     "(" << WidthStr <<" insn, unsigned startBit, unsigned numBits)\n";
1561
1562   o.indent(Indentation) << "{\n";
1563
1564   ++Indentation; ++Indentation;
1565   o.indent(Indentation) << "assert(startBit + numBits <= " << BitWidth
1566                         << " && \"Instruction field out of bounds!\");\n";
1567   o << '\n';
1568   o.indent(Indentation) << WidthStr << " fieldMask;\n";
1569   o << '\n';
1570   o.indent(Indentation) << "if (numBits == " << BitWidth << ")\n";
1571
1572   ++Indentation; ++Indentation;
1573   o.indent(Indentation) << "fieldMask = (" << WidthStr << ")-1;\n";
1574   --Indentation; --Indentation;
1575
1576   o.indent(Indentation) << "else\n";
1577
1578   ++Indentation; ++Indentation;
1579   o.indent(Indentation) << "fieldMask = ((1 << numBits) - 1) << startBit;\n";
1580   --Indentation; --Indentation;
1581
1582   o << '\n';
1583   o.indent(Indentation) << "return (insn & fieldMask) >> startBit;\n";
1584   --Indentation; --Indentation;
1585
1586   o.indent(Indentation) << "}\n";
1587
1588   o << '\n';
1589 }
1590
1591 // Emits disassembler code for instruction decoding.
1592 void FixedLenDecoderEmitter::run(raw_ostream &o) {
1593   o << "#include \"llvm/MC/MCInst.h\"\n";
1594   o << "#include \"llvm/Support/DataTypes.h\"\n";
1595   o << "#include <assert.h>\n";
1596   o << '\n';
1597   o << "namespace llvm {\n\n";
1598
1599   // Parameterize the decoders based on namespace and instruction width.
1600   const std::vector<const CodeGenInstruction*> &NumberedInstructions =
1601     Target.getInstructionsByEnumValue();
1602   std::map<std::pair<std::string, unsigned>,
1603            std::vector<unsigned> > OpcMap;
1604   std::map<unsigned, std::vector<OperandInfo> > Operands;
1605
1606   for (unsigned i = 0; i < NumberedInstructions.size(); ++i) {
1607     const CodeGenInstruction *Inst = NumberedInstructions[i];
1608     const Record *Def = Inst->TheDef;
1609     unsigned Size = Def->getValueAsInt("Size");
1610     if (Def->getValueAsString("Namespace") == "TargetOpcode" ||
1611         Def->getValueAsBit("isPseudo") ||
1612         Def->getValueAsBit("isAsmParserOnly") ||
1613         Def->getValueAsBit("isCodeGenOnly"))
1614       continue;
1615
1616     std::string DecoderNamespace = Def->getValueAsString("DecoderNamespace");
1617
1618     if (Size) {
1619       if (populateInstruction(*Inst, i, Operands)) {
1620         OpcMap[std::make_pair(DecoderNamespace, Size)].push_back(i);
1621       }
1622     }
1623   }
1624
1625   std::set<unsigned> Sizes;
1626   for (std::map<std::pair<std::string, unsigned>,
1627                 std::vector<unsigned> >::const_iterator
1628        I = OpcMap.begin(), E = OpcMap.end(); I != E; ++I) {
1629     // If we haven't visited this instruction width before, emit the
1630     // helper method to extract fields.
1631     if (!Sizes.count(I->first.second)) {
1632       emitHelper(o, 8*I->first.second);
1633       Sizes.insert(I->first.second);
1634     }
1635
1636     // Emit the decoder for this namespace+width combination.
1637     FilterChooser FC(NumberedInstructions, I->second, Operands,
1638                      8*I->first.second, this);
1639     FC.emitTop(o, 0, I->first.first);
1640   }
1641
1642   o << "\n} // End llvm namespace \n";
1643 }
1644
1645 namespace llvm {
1646
1647 void EmitFixedLenDecoder(RecordKeeper &RK, raw_ostream &OS,
1648                          std::string PredicateNamespace,
1649                          std::string GPrefix,
1650                          std::string GPostfix,
1651                          std::string ROK,
1652                          std::string RFail,
1653                          std::string L) {
1654   FixedLenDecoderEmitter(RK, PredicateNamespace, GPrefix, GPostfix,
1655                          ROK, RFail, L).run(OS);
1656 }
1657
1658 } // End llvm namespace