When doing Thumb disassembly, there's no need to consider t2ADDrSPi12/t2SUBrSPi12,
[oota-llvm.git] / utils / TableGen / ARMDecoderEmitter.cpp
1 //===------------ ARMDecoderEmitter.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 // This file is part of the ARM Disassembler.
11 // It contains the tablegen backend that emits the decoder functions for ARM and
12 // Thumb.  The disassembler core includes the auto-generated file, invokes the
13 // decoder functions, and builds up the MCInst based on the decoded Opcode.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #define DEBUG_TYPE "arm-decoder-emitter"
18
19 #include "ARMDecoderEmitter.h"
20 #include "CodeGenTarget.h"
21 #include "Record.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/raw_ostream.h"
25
26 #include <vector>
27 #include <map>
28 #include <string>
29
30 using namespace llvm;
31
32 /////////////////////////////////////////////////////
33 //                                                 //
34 //  Enums and Utilities for ARM Instruction Format //
35 //                                                 //
36 /////////////////////////////////////////////////////
37
38 #define ARM_FORMATS                   \
39   ENTRY(ARM_FORMAT_PSEUDO,         0) \
40   ENTRY(ARM_FORMAT_MULFRM,         1) \
41   ENTRY(ARM_FORMAT_BRFRM,          2) \
42   ENTRY(ARM_FORMAT_BRMISCFRM,      3) \
43   ENTRY(ARM_FORMAT_DPFRM,          4) \
44   ENTRY(ARM_FORMAT_DPSOREGFRM,     5) \
45   ENTRY(ARM_FORMAT_LDFRM,          6) \
46   ENTRY(ARM_FORMAT_STFRM,          7) \
47   ENTRY(ARM_FORMAT_LDMISCFRM,      8) \
48   ENTRY(ARM_FORMAT_STMISCFRM,      9) \
49   ENTRY(ARM_FORMAT_LDSTMULFRM,    10) \
50   ENTRY(ARM_FORMAT_LDSTEXFRM,     11) \
51   ENTRY(ARM_FORMAT_ARITHMISCFRM,  12) \
52   ENTRY(ARM_FORMAT_EXTFRM,        13) \
53   ENTRY(ARM_FORMAT_VFPUNARYFRM,   14) \
54   ENTRY(ARM_FORMAT_VFPBINARYFRM,  15) \
55   ENTRY(ARM_FORMAT_VFPCONV1FRM,   16) \
56   ENTRY(ARM_FORMAT_VFPCONV2FRM,   17) \
57   ENTRY(ARM_FORMAT_VFPCONV3FRM,   18) \
58   ENTRY(ARM_FORMAT_VFPCONV4FRM,   19) \
59   ENTRY(ARM_FORMAT_VFPCONV5FRM,   20) \
60   ENTRY(ARM_FORMAT_VFPLDSTFRM,    21) \
61   ENTRY(ARM_FORMAT_VFPLDSTMULFRM, 22) \
62   ENTRY(ARM_FORMAT_VFPMISCFRM,    23) \
63   ENTRY(ARM_FORMAT_THUMBFRM,      24) \
64   ENTRY(ARM_FORMAT_NEONFRM,       25) \
65   ENTRY(ARM_FORMAT_NEONGETLNFRM,  26) \
66   ENTRY(ARM_FORMAT_NEONSETLNFRM,  27) \
67   ENTRY(ARM_FORMAT_NEONDUPFRM,    28) \
68   ENTRY(ARM_FORMAT_MISCFRM,       29) \
69   ENTRY(ARM_FORMAT_THUMBMISCFRM,  30) \
70   ENTRY(ARM_FORMAT_NLdSt,         31) \
71   ENTRY(ARM_FORMAT_N1RegModImm,   32) \
72   ENTRY(ARM_FORMAT_N2Reg,         33) \
73   ENTRY(ARM_FORMAT_NVCVT,         34) \
74   ENTRY(ARM_FORMAT_NVecDupLn,     35) \
75   ENTRY(ARM_FORMAT_N2RegVecShL,   36) \
76   ENTRY(ARM_FORMAT_N2RegVecShR,   37) \
77   ENTRY(ARM_FORMAT_N3Reg,         38) \
78   ENTRY(ARM_FORMAT_N3RegVecSh,    39) \
79   ENTRY(ARM_FORMAT_NVecExtract,   40) \
80   ENTRY(ARM_FORMAT_NVecMulScalar, 41) \
81   ENTRY(ARM_FORMAT_NVTBL,         42)
82
83 // ARM instruction format specifies the encoding used by the instruction.
84 #define ENTRY(n, v) n = v,
85 typedef enum {
86   ARM_FORMATS
87   ARM_FORMAT_NA
88 } ARMFormat;
89 #undef ENTRY
90
91 // Converts enum to const char*.
92 static const char *stringForARMFormat(ARMFormat form) {
93 #define ENTRY(n, v) case n: return #n;
94   switch(form) {
95     ARM_FORMATS
96   case ARM_FORMAT_NA:
97   default:
98     return "";
99   }
100 #undef ENTRY
101 }
102
103 enum {
104   IndexModeNone = 0,
105   IndexModePre  = 1,
106   IndexModePost = 2,
107   IndexModeUpd  = 3
108 };
109
110 /////////////////////////
111 //                     //
112 //  Utility functions  //
113 //                     //
114 /////////////////////////
115
116 /// byteFromBitsInit - Return the byte value from a BitsInit.
117 /// Called from getByteField().
118 static uint8_t byteFromBitsInit(BitsInit &init) {
119   int width = init.getNumBits();
120
121   assert(width <= 8 && "Field is too large for uint8_t!");
122
123   int index;
124   uint8_t mask = 0x01;
125
126   uint8_t ret = 0;
127
128   for (index = 0; index < width; index++) {
129     if (static_cast<BitInit*>(init.getBit(index))->getValue())
130       ret |= mask;
131
132     mask <<= 1;
133   }
134
135   return ret;
136 }
137
138 static uint8_t getByteField(const Record &def, const char *str) {
139   BitsInit *bits = def.getValueAsBitsInit(str);
140   return byteFromBitsInit(*bits);
141 }
142
143 static BitsInit &getBitsField(const Record &def, const char *str) {
144   BitsInit *bits = def.getValueAsBitsInit(str);
145   return *bits;
146 }
147
148 /// sameStringExceptSuffix - Return true if the two strings differ only in RHS's
149 /// suffix.  ("VST4d8", "VST4d8_UPD", "_UPD") as input returns true.
150 static
151 bool sameStringExceptSuffix(const StringRef LHS, const StringRef RHS,
152                             const StringRef Suffix) {
153
154   if (RHS.startswith(LHS) && RHS.endswith(Suffix))
155     return RHS.size() == LHS.size() + Suffix.size();
156
157   return false;
158 }
159
160 /// thumbInstruction - Determine whether we have a Thumb instruction.
161 /// See also ARMInstrFormats.td.
162 static bool thumbInstruction(uint8_t Form) {
163   return Form == ARM_FORMAT_THUMBFRM;
164 }
165
166 // The set (BIT_TRUE, BIT_FALSE, BIT_UNSET) represents a ternary logic system
167 // for a bit value.
168 //
169 // BIT_UNFILTERED is used as the init value for a filter position.  It is used
170 // only for filter processings.
171 typedef enum {
172   BIT_TRUE,      // '1'
173   BIT_FALSE,     // '0'
174   BIT_UNSET,     // '?'
175   BIT_UNFILTERED // unfiltered
176 } bit_value_t;
177
178 static bool ValueSet(bit_value_t V) {
179   return (V == BIT_TRUE || V == BIT_FALSE);
180 }
181 static bool ValueNotSet(bit_value_t V) {
182   return (V == BIT_UNSET);
183 }
184 static int Value(bit_value_t V) {
185   return ValueNotSet(V) ? -1 : (V == BIT_FALSE ? 0 : 1);
186 }
187 static bit_value_t bitFromBits(BitsInit &bits, unsigned index) {
188   if (BitInit *bit = dynamic_cast<BitInit*>(bits.getBit(index)))
189     return bit->getValue() ? BIT_TRUE : BIT_FALSE;
190
191   // The bit is uninitialized.
192   return BIT_UNSET;
193 }
194 // Prints the bit value for each position.
195 static void dumpBits(raw_ostream &o, BitsInit &bits) {
196   unsigned index;
197
198   for (index = bits.getNumBits(); index > 0; index--) {
199     switch (bitFromBits(bits, index - 1)) {
200     case BIT_TRUE:
201       o << "1";
202       break;
203     case BIT_FALSE:
204       o << "0";
205       break;
206     case BIT_UNSET:
207       o << "_";
208       break;
209     default:
210       assert(0 && "unexpected return value from bitFromBits");
211     }
212   }
213 }
214
215 // Enums for the available target names.
216 typedef enum {
217   TARGET_ARM = 0,
218   TARGET_THUMB
219 } TARGET_NAME_t;
220
221 // FIXME: Possibly auto-detected?
222 #define BIT_WIDTH 32
223
224 // Forward declaration.
225 class FilterChooser;
226
227 // Representation of the instruction to work on.
228 typedef bit_value_t insn_t[BIT_WIDTH];
229
230 /// Filter - Filter works with FilterChooser to produce the decoding tree for
231 /// the ISA.
232 ///
233 /// It is useful to think of a Filter as governing the switch stmts of the
234 /// decoding tree in a certain level.  Each case stmt delegates to an inferior
235 /// FilterChooser to decide what further decoding logic to employ, or in another
236 /// words, what other remaining bits to look at.  The FilterChooser eventually
237 /// chooses a best Filter to do its job.
238 ///
239 /// This recursive scheme ends when the number of Opcodes assigned to the
240 /// FilterChooser becomes 1 or if there is a conflict.  A conflict happens when
241 /// the Filter/FilterChooser combo does not know how to distinguish among the
242 /// Opcodes assigned.
243 ///
244 /// An example of a conflcit is 
245 ///
246 /// Conflict:
247 ///                     111101000.00........00010000....
248 ///                     111101000.00........0001........
249 ///                     1111010...00........0001........
250 ///                     1111010...00....................
251 ///                     1111010.........................
252 ///                     1111............................
253 ///                     ................................
254 ///     VST4q8a         111101000_00________00010000____
255 ///     VST4q8b         111101000_00________00010000____
256 ///
257 /// The Debug output shows the path that the decoding tree follows to reach the
258 /// the conclusion that there is a conflict.  VST4q8a is a vst4 to double-spaced
259 /// even registers, while VST4q8b is a vst4 to double-spaced odd regsisters.
260 ///
261 /// The encoding info in the .td files does not specify this meta information,
262 /// which could have been used by the decoder to resolve the conflict.  The
263 /// decoder could try to decode the even/odd register numbering and assign to
264 /// VST4q8a or VST4q8b, but for the time being, the decoder chooses the "a"
265 /// version and return the Opcode since the two have the same Asm format string.
266 class Filter {
267 protected:
268   FilterChooser *Owner; // points to the FilterChooser who owns this filter
269   unsigned StartBit; // the starting bit position
270   unsigned NumBits; // number of bits to filter
271   bool Mixed; // a mixed region contains both set and unset bits
272
273   // Map of well-known segment value to the set of uid's with that value. 
274   std::map<uint64_t, std::vector<unsigned> > FilteredInstructions;
275
276   // Set of uid's with non-constant segment values.
277   std::vector<unsigned> VariableInstructions;
278
279   // Map of well-known segment value to its delegate.
280   std::map<unsigned, FilterChooser*> FilterChooserMap;
281
282   // Number of instructions which fall under FilteredInstructions category.
283   unsigned NumFiltered;
284
285   // Keeps track of the last opcode in the filtered bucket.
286   unsigned LastOpcFiltered;
287
288   // Number of instructions which fall under VariableInstructions category.
289   unsigned NumVariable;
290
291 public:
292   unsigned getNumFiltered() { return NumFiltered; }
293   unsigned getNumVariable() { return NumVariable; }
294   unsigned getSingletonOpc() {
295     assert(NumFiltered == 1);
296     return LastOpcFiltered;
297   }
298   // Return the filter chooser for the group of instructions without constant
299   // segment values.
300   FilterChooser &getVariableFC() {
301     assert(NumFiltered == 1);
302     assert(FilterChooserMap.size() == 1);
303     return *(FilterChooserMap.find((unsigned)-1)->second);
304   }
305
306   Filter(const Filter &f);
307   Filter(FilterChooser &owner, unsigned startBit, unsigned numBits, bool mixed);
308
309   ~Filter();
310
311   // Divides the decoding task into sub tasks and delegates them to the
312   // inferior FilterChooser's.
313   //
314   // A special case arises when there's only one entry in the filtered
315   // instructions.  In order to unambiguously decode the singleton, we need to
316   // match the remaining undecoded encoding bits against the singleton.
317   void recurse();
318
319   // Emit code to decode instructions given a segment or segments of bits.
320   void emit(raw_ostream &o, unsigned &Indentation);
321
322   // Returns the number of fanout produced by the filter.  More fanout implies
323   // the filter distinguishes more categories of instructions.
324   unsigned usefulness() const;
325 }; // End of class Filter
326
327 // These are states of our finite state machines used in FilterChooser's
328 // filterProcessor() which produces the filter candidates to use.
329 typedef enum {
330   ATTR_NONE,
331   ATTR_FILTERED,
332   ATTR_ALL_SET,
333   ATTR_ALL_UNSET,
334   ATTR_MIXED
335 } bitAttr_t;
336
337 /// FilterChooser - FilterChooser chooses the best filter among a set of Filters
338 /// in order to perform the decoding of instructions at the current level.
339 ///
340 /// Decoding proceeds from the top down.  Based on the well-known encoding bits
341 /// of instructions available, FilterChooser builds up the possible Filters that
342 /// can further the task of decoding by distinguishing among the remaining
343 /// candidate instructions.
344 ///
345 /// Once a filter has been chosen, it is called upon to divide the decoding task
346 /// into sub-tasks and delegates them to its inferior FilterChoosers for further
347 /// processings.
348 ///
349 /// It is useful to think of a Filter as governing the switch stmts of the
350 /// decoding tree.  And each case is delegated to an inferior FilterChooser to
351 /// decide what further remaining bits to look at.
352 class FilterChooser {
353   static TARGET_NAME_t TargetName;
354
355 protected:
356   friend class Filter;
357
358   // Vector of codegen instructions to choose our filter.
359   const std::vector<const CodeGenInstruction*> &AllInstructions;
360
361   // Vector of uid's for this filter chooser to work on.
362   const std::vector<unsigned> Opcodes;
363
364   // Vector of candidate filters.
365   std::vector<Filter> Filters;
366
367   // Array of bit values passed down from our parent.
368   // Set to all BIT_UNFILTERED's for Parent == NULL.
369   bit_value_t FilterBitValues[BIT_WIDTH];
370
371   // Links to the FilterChooser above us in the decoding tree.
372   FilterChooser *Parent;
373   
374   // Index of the best filter from Filters.
375   int BestIndex;
376
377 public:
378   static void setTargetName(TARGET_NAME_t tn) { TargetName = tn; }
379
380   FilterChooser(const FilterChooser &FC) :
381       AllInstructions(FC.AllInstructions), Opcodes(FC.Opcodes),
382       Filters(FC.Filters), Parent(FC.Parent), BestIndex(FC.BestIndex) {
383     memcpy(FilterBitValues, FC.FilterBitValues, sizeof(FilterBitValues));
384   }
385
386   FilterChooser(const std::vector<const CodeGenInstruction*> &Insts,
387                 const std::vector<unsigned> &IDs) :
388       AllInstructions(Insts), Opcodes(IDs), Filters(), Parent(NULL),
389       BestIndex(-1) {
390     for (unsigned i = 0; i < BIT_WIDTH; ++i)
391       FilterBitValues[i] = BIT_UNFILTERED;
392
393     doFilter();
394   }
395
396   FilterChooser(const std::vector<const CodeGenInstruction*> &Insts,
397                 const std::vector<unsigned> &IDs,
398                 bit_value_t (&ParentFilterBitValues)[BIT_WIDTH],
399                 FilterChooser &parent) :
400       AllInstructions(Insts), Opcodes(IDs), Filters(), Parent(&parent),
401       BestIndex(-1) {
402     for (unsigned i = 0; i < BIT_WIDTH; ++i)
403       FilterBitValues[i] = ParentFilterBitValues[i];
404
405     doFilter();
406   }
407
408   // The top level filter chooser has NULL as its parent.
409   bool isTopLevel() { return Parent == NULL; }
410
411   // This provides an opportunity for target specific code emission.
412   void emitTopHook(raw_ostream &o);
413
414   // Emit the top level typedef and decodeInstruction() function.
415   void emitTop(raw_ostream &o, unsigned &Indentation);
416
417   // This provides an opportunity for target specific code emission after
418   // emitTop().
419   void emitBot(raw_ostream &o, unsigned &Indentation);
420
421 protected:
422   // Populates the insn given the uid.
423   void insnWithID(insn_t &Insn, unsigned Opcode) const {
424     BitsInit &Bits = getBitsField(*AllInstructions[Opcode]->TheDef, "Inst");
425
426     for (unsigned i = 0; i < BIT_WIDTH; ++i)
427       Insn[i] = bitFromBits(Bits, i);
428
429     // Set Inst{21} to 1 (wback) when IndexModeBits == IndexModeUpd.
430     if (getByteField(*AllInstructions[Opcode]->TheDef, "IndexModeBits")
431         == IndexModeUpd)
432       Insn[21] = BIT_TRUE;
433   }
434
435   // Returns the record name.
436   const std::string &nameWithID(unsigned Opcode) const {
437     return AllInstructions[Opcode]->TheDef->getName();
438   }
439
440   // Populates the field of the insn given the start position and the number of
441   // consecutive bits to scan for.
442   //
443   // Returns false if there exists any uninitialized bit value in the range.
444   // Returns true, otherwise.
445   bool fieldFromInsn(uint64_t &Field, insn_t &Insn, unsigned StartBit,
446       unsigned NumBits) const;
447
448   /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
449   /// filter array as a series of chars.
450   void dumpFilterArray(raw_ostream &o, bit_value_t (&filter)[BIT_WIDTH]);
451
452   /// dumpStack - dumpStack traverses the filter chooser chain and calls
453   /// dumpFilterArray on each filter chooser up to the top level one.
454   void dumpStack(raw_ostream &o, const char *prefix);
455
456   Filter &bestFilter() {
457     assert(BestIndex != -1 && "BestIndex not set");
458     return Filters[BestIndex];
459   }
460
461   // Called from Filter::recurse() when singleton exists.  For debug purpose.
462   void SingletonExists(unsigned Opc);
463
464   bool PositionFiltered(unsigned i) {
465     return ValueSet(FilterBitValues[i]);
466   }
467
468   // Calculates the island(s) needed to decode the instruction.
469   // This returns a lit of undecoded bits of an instructions, for example,
470   // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
471   // decoded bits in order to verify that the instruction matches the Opcode.
472   unsigned getIslands(std::vector<unsigned> &StartBits,
473       std::vector<unsigned> &EndBits, std::vector<uint64_t> &FieldVals,
474       insn_t &Insn);
475
476   // The purpose of this function is for the API client to detect possible
477   // Load/Store Coprocessor instructions.  If the coprocessor number is of
478   // the instruction is either 10 or 11, the decoder should not report the
479   // instruction as LDC/LDC2/STC/STC2, but should match against Advanced SIMD or
480   // VFP instructions.
481   bool LdStCopEncoding1(unsigned Opc) {
482     const std::string &Name = nameWithID(Opc);
483     if (Name == "LDC_OFFSET" || Name == "LDC_OPTION" ||
484         Name == "LDC_POST" || Name == "LDC_PRE" ||
485         Name == "LDCL_OFFSET" || Name == "LDCL_OPTION" ||
486         Name == "LDCL_POST" || Name == "LDCL_PRE" ||
487         Name == "STC_OFFSET" || Name == "STC_OPTION" ||
488         Name == "STC_POST" || Name == "STC_PRE" ||
489         Name == "STCL_OFFSET" || Name == "STCL_OPTION" ||
490         Name == "STCL_POST" || Name == "STCL_PRE")
491       return true;
492     else
493       return false;
494   }
495
496   // Emits code to decode the singleton.  Return true if we have matched all the
497   // well-known bits.
498   bool emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,unsigned Opc);
499
500   // Emits code to decode the singleton, and then to decode the rest.
501   void emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,Filter &Best);
502
503   // Assign a single filter and run with it.
504   void runSingleFilter(FilterChooser &owner, unsigned startBit, unsigned numBit,
505       bool mixed);
506
507   // reportRegion is a helper function for filterProcessor to mark a region as
508   // eligible for use as a filter region.
509   void reportRegion(bitAttr_t RA, unsigned StartBit, unsigned BitIndex,
510       bool AllowMixed);
511
512   // FilterProcessor scans the well-known encoding bits of the instructions and
513   // builds up a list of candidate filters.  It chooses the best filter and
514   // recursively descends down the decoding tree.
515   bool filterProcessor(bool AllowMixed, bool Greedy = true);
516
517   // Decides on the best configuration of filter(s) to use in order to decode
518   // the instructions.  A conflict of instructions may occur, in which case we
519   // dump the conflict set to the standard error.
520   void doFilter();
521
522   // Emits code to decode our share of instructions.  Returns true if the
523   // emitted code causes a return, which occurs if we know how to decode
524   // the instruction at this level or the instruction is not decodeable.
525   bool emit(raw_ostream &o, unsigned &Indentation);
526 };
527
528 ///////////////////////////
529 //                       //
530 // Filter Implmenetation //
531 //                       //
532 ///////////////////////////
533
534 Filter::Filter(const Filter &f) :
535   Owner(f.Owner), StartBit(f.StartBit), NumBits(f.NumBits), Mixed(f.Mixed),
536   FilteredInstructions(f.FilteredInstructions),
537   VariableInstructions(f.VariableInstructions),
538   FilterChooserMap(f.FilterChooserMap), NumFiltered(f.NumFiltered),
539   LastOpcFiltered(f.LastOpcFiltered), NumVariable(f.NumVariable) {
540 }
541
542 Filter::Filter(FilterChooser &owner, unsigned startBit, unsigned numBits,
543     bool mixed) : Owner(&owner), StartBit(startBit), NumBits(numBits),
544                   Mixed(mixed) {
545   assert(StartBit + NumBits - 1 < BIT_WIDTH);
546
547   NumFiltered = 0;
548   LastOpcFiltered = 0;
549   NumVariable = 0;
550
551   for (unsigned i = 0, e = Owner->Opcodes.size(); i != e; ++i) {
552     insn_t Insn;
553
554     // Populates the insn given the uid.
555     Owner->insnWithID(Insn, Owner->Opcodes[i]);
556
557     uint64_t Field;
558     // Scans the segment for possibly well-specified encoding bits.
559     bool ok = Owner->fieldFromInsn(Field, Insn, StartBit, NumBits);
560
561     if (ok) {
562       // The encoding bits are well-known.  Lets add the uid of the
563       // instruction into the bucket keyed off the constant field value.
564       LastOpcFiltered = Owner->Opcodes[i];
565       FilteredInstructions[Field].push_back(LastOpcFiltered);
566       ++NumFiltered;
567     } else {
568       // Some of the encoding bit(s) are unspecfied.  This contributes to
569       // one additional member of "Variable" instructions.
570       VariableInstructions.push_back(Owner->Opcodes[i]);
571       ++NumVariable;
572     }
573   }
574
575   assert((FilteredInstructions.size() + VariableInstructions.size() > 0)
576          && "Filter returns no instruction categories");
577 }
578
579 Filter::~Filter() {
580   std::map<unsigned, FilterChooser*>::iterator filterIterator;
581   for (filterIterator = FilterChooserMap.begin();
582        filterIterator != FilterChooserMap.end();
583        filterIterator++) {
584     delete filterIterator->second;
585   }
586 }
587
588 // Divides the decoding task into sub tasks and delegates them to the
589 // inferior FilterChooser's.
590 //
591 // A special case arises when there's only one entry in the filtered
592 // instructions.  In order to unambiguously decode the singleton, we need to
593 // match the remaining undecoded encoding bits against the singleton.
594 void Filter::recurse() {
595   std::map<uint64_t, std::vector<unsigned> >::const_iterator mapIterator;
596
597   bit_value_t BitValueArray[BIT_WIDTH];
598   // Starts by inheriting our parent filter chooser's filter bit values.
599   memcpy(BitValueArray, Owner->FilterBitValues, sizeof(BitValueArray));
600
601   unsigned bitIndex;
602
603   if (VariableInstructions.size()) {
604     // Conservatively marks each segment position as BIT_UNSET.
605     for (bitIndex = 0; bitIndex < NumBits; bitIndex++)
606       BitValueArray[StartBit + bitIndex] = BIT_UNSET;
607
608     // Delegates to an inferior filter chooser for futher processing on this
609     // group of instructions whose segment values are variable.
610     FilterChooserMap.insert(std::pair<unsigned, FilterChooser*>(
611                               (unsigned)-1,
612                               new FilterChooser(Owner->AllInstructions,
613                                                 VariableInstructions,
614                                                 BitValueArray,
615                                                 *Owner)
616                               ));
617   }
618
619   // No need to recurse for a singleton filtered instruction.
620   // See also Filter::emit().
621   if (getNumFiltered() == 1) {
622     //Owner->SingletonExists(LastOpcFiltered);
623     assert(FilterChooserMap.size() == 1);
624     return;
625   }
626
627   // Otherwise, create sub choosers.
628   for (mapIterator = FilteredInstructions.begin();
629        mapIterator != FilteredInstructions.end();
630        mapIterator++) {
631
632     // Marks all the segment positions with either BIT_TRUE or BIT_FALSE.
633     for (bitIndex = 0; bitIndex < NumBits; bitIndex++) {
634       if (mapIterator->first & (1ULL << bitIndex))
635         BitValueArray[StartBit + bitIndex] = BIT_TRUE;
636       else
637         BitValueArray[StartBit + bitIndex] = BIT_FALSE;
638     }
639
640     // Delegates to an inferior filter chooser for futher processing on this
641     // category of instructions.
642     FilterChooserMap.insert(std::pair<unsigned, FilterChooser*>(
643                               mapIterator->first,
644                               new FilterChooser(Owner->AllInstructions,
645                                                 mapIterator->second,
646                                                 BitValueArray,
647                                                 *Owner)
648                               ));
649   }
650 }
651
652 // Emit code to decode instructions given a segment or segments of bits.
653 void Filter::emit(raw_ostream &o, unsigned &Indentation) {
654   o.indent(Indentation) << "// Check Inst{";
655
656   if (NumBits > 1)
657     o << (StartBit + NumBits - 1) << '-';
658
659   o << StartBit << "} ...\n";
660
661   o.indent(Indentation) << "switch (fieldFromInstruction(insn, "
662                         << StartBit << ", " << NumBits << ")) {\n";
663
664   std::map<unsigned, FilterChooser*>::iterator filterIterator;
665
666   bool DefaultCase = false;
667   for (filterIterator = FilterChooserMap.begin();
668        filterIterator != FilterChooserMap.end();
669        filterIterator++) {
670
671     // Field value -1 implies a non-empty set of variable instructions.
672     // See also recurse().
673     if (filterIterator->first == (unsigned)-1) {
674       DefaultCase = true;
675
676       o.indent(Indentation) << "default:\n";
677       o.indent(Indentation) << "  break; // fallthrough\n";
678
679       // Closing curly brace for the switch statement.
680       // This is unconventional because we want the default processing to be
681       // performed for the fallthrough cases as well, i.e., when the "cases"
682       // did not prove a decoded instruction.
683       o.indent(Indentation) << "}\n";
684
685     } else
686       o.indent(Indentation) << "case " << filterIterator->first << ":\n";
687
688     // We arrive at a category of instructions with the same segment value.
689     // Now delegate to the sub filter chooser for further decodings.
690     // The case may fallthrough, which happens if the remaining well-known
691     // encoding bits do not match exactly.
692     if (!DefaultCase) { ++Indentation; ++Indentation; }
693
694     bool finished = filterIterator->second->emit(o, Indentation);
695     // For top level default case, there's no need for a break statement.
696     if (Owner->isTopLevel() && DefaultCase)
697       break;
698     if (!finished)
699       o.indent(Indentation) << "break;\n";
700
701     if (!DefaultCase) { --Indentation; --Indentation; }
702   }
703
704   // If there is no default case, we still need to supply a closing brace.
705   if (!DefaultCase) {
706     // Closing curly brace for the switch statement.
707     o.indent(Indentation) << "}\n";
708   }
709 }
710
711 // Returns the number of fanout produced by the filter.  More fanout implies
712 // the filter distinguishes more categories of instructions.
713 unsigned Filter::usefulness() const {
714   if (VariableInstructions.size())
715     return FilteredInstructions.size();
716   else
717     return FilteredInstructions.size() + 1;
718 }
719
720 //////////////////////////////////
721 //                              //
722 // Filterchooser Implementation //
723 //                              //
724 //////////////////////////////////
725
726 // Define the symbol here.
727 TARGET_NAME_t FilterChooser::TargetName;
728
729 // This provides an opportunity for target specific code emission.
730 void FilterChooser::emitTopHook(raw_ostream &o) {
731   if (TargetName == TARGET_ARM) {
732     // Emit code that references the ARMFormat data type.
733     o << "static const ARMFormat ARMFormats[] = {\n";
734     for (unsigned i = 0, e = AllInstructions.size(); i != e; ++i) {
735       const Record &Def = *(AllInstructions[i]->TheDef);
736       const std::string &Name = Def.getName();
737       if (Def.isSubClassOf("InstARM") || Def.isSubClassOf("InstThumb"))
738         o.indent(2) << 
739           stringForARMFormat((ARMFormat)getByteField(Def, "Form"));
740       else
741         o << "  ARM_FORMAT_NA";
742
743       o << ",\t// Inst #" << i << " = " << Name << '\n';
744     }
745     o << "  ARM_FORMAT_NA\t// Unreachable.\n";
746     o << "};\n\n";
747   }
748 }
749
750 // Emit the top level typedef and decodeInstruction() function.
751 void FilterChooser::emitTop(raw_ostream &o, unsigned &Indentation) {
752   // Run the target specific emit hook.
753   emitTopHook(o);
754
755   switch (BIT_WIDTH) {
756   case 8:
757     o.indent(Indentation) << "typedef uint8_t field_t;\n";
758     break;
759   case 16:
760     o.indent(Indentation) << "typedef uint16_t field_t;\n";
761     break;
762   case 32:
763     o.indent(Indentation) << "typedef uint32_t field_t;\n";
764     break;
765   case 64:
766     o.indent(Indentation) << "typedef uint64_t field_t;\n";
767     break;
768   default:
769     assert(0 && "Unexpected instruction size!");
770   }
771
772   o << '\n';
773
774   o.indent(Indentation) << "static field_t " <<
775     "fieldFromInstruction(field_t insn, unsigned startBit, unsigned numBits)\n";
776
777   o.indent(Indentation) << "{\n";
778
779   ++Indentation; ++Indentation;
780   o.indent(Indentation) << "assert(startBit + numBits <= " << BIT_WIDTH
781                         << " && \"Instruction field out of bounds!\");\n";
782   o << '\n';
783   o.indent(Indentation) << "field_t fieldMask;\n";
784   o << '\n';
785   o.indent(Indentation) << "if (numBits == " << BIT_WIDTH << ")\n";
786
787   ++Indentation; ++Indentation;
788   o.indent(Indentation) << "fieldMask = (field_t)-1;\n";
789   --Indentation; --Indentation;
790
791   o.indent(Indentation) << "else\n";
792
793   ++Indentation; ++Indentation;
794   o.indent(Indentation) << "fieldMask = ((1 << numBits) - 1) << startBit;\n";
795   --Indentation; --Indentation;
796
797   o << '\n';
798   o.indent(Indentation) << "return (insn & fieldMask) >> startBit;\n";
799   --Indentation; --Indentation;
800
801   o.indent(Indentation) << "}\n";
802
803   o << '\n';
804
805   o.indent(Indentation) << "static uint16_t decodeInstruction(field_t insn) {\n";
806
807   ++Indentation; ++Indentation;
808   // Emits code to decode the instructions.
809   emit(o, Indentation);
810
811   o << '\n';
812   o.indent(Indentation) << "return 0;\n";
813   --Indentation; --Indentation;
814
815   o.indent(Indentation) << "}\n";
816
817   o << '\n';
818 }
819
820 // This provides an opportunity for target specific code emission after
821 // emitTop().
822 void FilterChooser::emitBot(raw_ostream &o, unsigned &Indentation) {
823   if (TargetName != TARGET_THUMB) return;
824
825   // Emit code that decodes the Thumb ISA.
826   o.indent(Indentation)
827     << "static uint16_t decodeThumbInstruction(field_t insn) {\n";
828
829   ++Indentation; ++Indentation;
830
831   // Emits code to decode the instructions.
832   emit(o, Indentation);
833
834   o << '\n';
835   o.indent(Indentation) << "return 0;\n";
836
837   --Indentation; --Indentation;
838
839   o.indent(Indentation) << "}\n";
840 }
841
842 // Populates the field of the insn given the start position and the number of
843 // consecutive bits to scan for.
844 //
845 // Returns false if and on the first uninitialized bit value encountered.
846 // Returns true, otherwise.
847 bool FilterChooser::fieldFromInsn(uint64_t &Field, insn_t &Insn,
848     unsigned StartBit, unsigned NumBits) const {
849   Field = 0;
850
851   for (unsigned i = 0; i < NumBits; ++i) {
852     if (Insn[StartBit + i] == BIT_UNSET)
853       return false;
854
855     if (Insn[StartBit + i] == BIT_TRUE)
856       Field = Field | (1ULL << i);
857   }
858
859   return true;
860 }
861
862 /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
863 /// filter array as a series of chars.
864 void FilterChooser::dumpFilterArray(raw_ostream &o,
865     bit_value_t (&filter)[BIT_WIDTH]) {
866   unsigned bitIndex;
867
868   for (bitIndex = BIT_WIDTH; bitIndex > 0; bitIndex--) {
869     switch (filter[bitIndex - 1]) {
870     case BIT_UNFILTERED:
871       o << ".";
872       break;
873     case BIT_UNSET:
874       o << "_";
875       break;
876     case BIT_TRUE:
877       o << "1";
878       break;
879     case BIT_FALSE:
880       o << "0";
881       break;
882     }
883   }
884 }
885
886 /// dumpStack - dumpStack traverses the filter chooser chain and calls
887 /// dumpFilterArray on each filter chooser up to the top level one.
888 void FilterChooser::dumpStack(raw_ostream &o, const char *prefix) {
889   FilterChooser *current = this;
890
891   while (current) {
892     o << prefix;
893     dumpFilterArray(o, current->FilterBitValues);
894     o << '\n';
895     current = current->Parent;
896   }
897 }
898
899 // Called from Filter::recurse() when singleton exists.  For debug purpose.
900 void FilterChooser::SingletonExists(unsigned Opc) {
901   insn_t Insn0;
902   insnWithID(Insn0, Opc);
903
904   errs() << "Singleton exists: " << nameWithID(Opc)
905          << " with its decoding dominating ";
906   for (unsigned i = 0; i < Opcodes.size(); ++i) {
907     if (Opcodes[i] == Opc) continue;
908     errs() << nameWithID(Opcodes[i]) << ' ';
909   }
910   errs() << '\n';
911
912   dumpStack(errs(), "\t\t");
913   for (unsigned i = 0; i < Opcodes.size(); i++) {
914     const std::string &Name = nameWithID(Opcodes[i]);
915
916     errs() << '\t' << Name << " ";
917     dumpBits(errs(),
918              getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
919     errs() << '\n';
920   }
921 }
922
923 // Calculates the island(s) needed to decode the instruction.
924 // This returns a list of undecoded bits of an instructions, for example,
925 // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
926 // decoded bits in order to verify that the instruction matches the Opcode.
927 unsigned FilterChooser::getIslands(std::vector<unsigned> &StartBits,
928     std::vector<unsigned> &EndBits, std::vector<uint64_t> &FieldVals,
929     insn_t &Insn) {
930   unsigned Num, BitNo;
931   Num = BitNo = 0;
932
933   uint64_t FieldVal = 0;
934
935   // 0: Init
936   // 1: Water (the bit value does not affect decoding)
937   // 2: Island (well-known bit value needed for decoding)
938   int State = 0;
939   int Val = -1;
940
941   for (unsigned i = 0; i < BIT_WIDTH; ++i) {
942     Val = Value(Insn[i]);
943     bool Filtered = PositionFiltered(i);
944     switch (State) {
945     default:
946       assert(0 && "Unreachable code!");
947       break;
948     case 0:
949     case 1:
950       if (Filtered || Val == -1)
951         State = 1; // Still in Water
952       else {
953         State = 2; // Into the Island
954         BitNo = 0;
955         StartBits.push_back(i);
956         FieldVal = Val;
957       }
958       break;
959     case 2:
960       if (Filtered || Val == -1) {
961         State = 1; // Into the Water
962         EndBits.push_back(i - 1);
963         FieldVals.push_back(FieldVal);
964         ++Num;
965       } else {
966         State = 2; // Still in Island
967         ++BitNo;
968         FieldVal = FieldVal | Val << BitNo;
969       }
970       break;
971     }
972   }
973   // If we are still in Island after the loop, do some housekeeping.
974   if (State == 2) {
975     EndBits.push_back(BIT_WIDTH - 1);
976     FieldVals.push_back(FieldVal);
977     ++Num;
978   }
979
980   assert(StartBits.size() == Num && EndBits.size() == Num &&
981          FieldVals.size() == Num);
982   return Num;
983 }
984
985 // Emits code to decode the singleton.  Return true if we have matched all the
986 // well-known bits.
987 bool FilterChooser::emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,
988                                          unsigned Opc) {
989   std::vector<unsigned> StartBits;
990   std::vector<unsigned> EndBits;
991   std::vector<uint64_t> FieldVals;
992   insn_t Insn;
993   insnWithID(Insn, Opc);
994
995   // This provides a good opportunity to check for possible Ld/St Coprocessor
996   // Opcode and escapes if the coproc # is either 10 or 11.  It is a NEON/VFP
997   // instruction is disguise.
998   if (TargetName == TARGET_ARM && LdStCopEncoding1(Opc)) {
999     o.indent(Indentation);
1000     // A8.6.51 & A8.6.188
1001     // If coproc = 0b101?, i.e, slice(insn, 11, 8) = 10 or 11, escape.
1002     o << "if (fieldFromInstruction(insn, 9, 3) == 5) break; // fallthrough\n";
1003   }
1004
1005   // Look for islands of undecoded bits of the singleton.
1006   getIslands(StartBits, EndBits, FieldVals, Insn);
1007
1008   unsigned Size = StartBits.size();
1009   unsigned I, NumBits;
1010
1011   // If we have matched all the well-known bits, just issue a return.
1012   if (Size == 0) {
1013     o.indent(Indentation) << "return " << Opc << "; // " << nameWithID(Opc)
1014                           << '\n';
1015     return true;
1016   }
1017
1018   // Otherwise, there are more decodings to be done!
1019
1020   // Emit code to match the island(s) for the singleton.
1021   o.indent(Indentation) << "// Check ";
1022
1023   for (I = Size; I != 0; --I) {
1024     o << "Inst{" << EndBits[I-1] << '-' << StartBits[I-1] << "} ";
1025     if (I > 1)
1026       o << "&& ";
1027     else
1028       o << "for singleton decoding...\n";
1029   }
1030
1031   o.indent(Indentation) << "if (";
1032
1033   for (I = Size; I != 0; --I) {
1034     NumBits = EndBits[I-1] - StartBits[I-1] + 1;
1035     o << "fieldFromInstruction(insn, " << StartBits[I-1] << ", " << NumBits
1036       << ") == " << FieldVals[I-1];
1037     if (I > 1)
1038       o << " && ";
1039     else
1040       o << ")\n";
1041   }
1042
1043   o.indent(Indentation) << "  return " << Opc << "; // " << nameWithID(Opc)
1044                         << '\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     Filter &Best) {
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(FilterChooser &owner, unsigned startBit,
1068     unsigned numBit, 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(*this, StartBits[0], EndBits[0] - StartBits[0] + 1,
1117                         true);
1118         return true;
1119       }
1120     }
1121   }
1122
1123   unsigned BitIndex, InsnIndex;
1124
1125   // We maintain BIT_WIDTH copies of the bitAttrs automaton.
1126   // The automaton consumes the corresponding bit from each
1127   // instruction.
1128   //
1129   //   Input symbols: 0, 1, and _ (unset).
1130   //   States:        NONE, FILTERED, ALL_SET, ALL_UNSET, and MIXED.
1131   //   Initial state: NONE.
1132   //
1133   // (NONE) ------- [01] -> (ALL_SET)
1134   // (NONE) ------- _ ----> (ALL_UNSET)
1135   // (ALL_SET) ---- [01] -> (ALL_SET)
1136   // (ALL_SET) ---- _ ----> (MIXED)
1137   // (ALL_UNSET) -- [01] -> (MIXED)
1138   // (ALL_UNSET) -- _ ----> (ALL_UNSET)
1139   // (MIXED) ------ . ----> (MIXED)
1140   // (FILTERED)---- . ----> (FILTERED)
1141
1142   bitAttr_t bitAttrs[BIT_WIDTH];
1143
1144   // FILTERED bit positions provide no entropy and are not worthy of pursuing.
1145   // Filter::recurse() set either BIT_TRUE or BIT_FALSE for each position.
1146   for (BitIndex = 0; BitIndex < BIT_WIDTH; ++BitIndex)
1147     if (FilterBitValues[BitIndex] == BIT_TRUE ||
1148         FilterBitValues[BitIndex] == BIT_FALSE)
1149       bitAttrs[BitIndex] = ATTR_FILTERED;
1150     else
1151       bitAttrs[BitIndex] = ATTR_NONE;
1152
1153   for (InsnIndex = 0; InsnIndex < numInstructions; ++InsnIndex) {
1154     insn_t insn;
1155
1156     insnWithID(insn, Opcodes[InsnIndex]);
1157
1158     for (BitIndex = 0; BitIndex < BIT_WIDTH; ++BitIndex) {
1159       switch (bitAttrs[BitIndex]) {
1160       case ATTR_NONE:
1161         if (insn[BitIndex] == BIT_UNSET)
1162           bitAttrs[BitIndex] = ATTR_ALL_UNSET;
1163         else
1164           bitAttrs[BitIndex] = ATTR_ALL_SET;
1165         break;
1166       case ATTR_ALL_SET:
1167         if (insn[BitIndex] == BIT_UNSET)
1168           bitAttrs[BitIndex] = ATTR_MIXED;
1169         break;
1170       case ATTR_ALL_UNSET:
1171         if (insn[BitIndex] != BIT_UNSET)
1172           bitAttrs[BitIndex] = ATTR_MIXED;
1173         break;
1174       case ATTR_MIXED:
1175       case ATTR_FILTERED:
1176         break;
1177       }
1178     }
1179   }
1180
1181   // The regionAttr automaton consumes the bitAttrs automatons' state,
1182   // lowest-to-highest.
1183   //
1184   //   Input symbols: F(iltered), (all_)S(et), (all_)U(nset), M(ixed)
1185   //   States:        NONE, ALL_SET, MIXED
1186   //   Initial state: NONE
1187   //
1188   // (NONE) ----- F --> (NONE)
1189   // (NONE) ----- S --> (ALL_SET)     ; and set region start
1190   // (NONE) ----- U --> (NONE)
1191   // (NONE) ----- M --> (MIXED)       ; and set region start
1192   // (ALL_SET) -- F --> (NONE)        ; and report an ALL_SET region
1193   // (ALL_SET) -- S --> (ALL_SET)
1194   // (ALL_SET) -- U --> (NONE)        ; and report an ALL_SET region
1195   // (ALL_SET) -- M --> (MIXED)       ; and report an ALL_SET region
1196   // (MIXED) ---- F --> (NONE)        ; and report a MIXED region
1197   // (MIXED) ---- S --> (ALL_SET)     ; and report a MIXED region
1198   // (MIXED) ---- U --> (NONE)        ; and report a MIXED region
1199   // (MIXED) ---- M --> (MIXED)
1200
1201   bitAttr_t RA = ATTR_NONE;
1202   unsigned StartBit = 0;
1203
1204   for (BitIndex = 0; BitIndex < BIT_WIDTH; BitIndex++) {
1205     bitAttr_t bitAttr = bitAttrs[BitIndex];
1206
1207     assert(bitAttr != ATTR_NONE && "Bit without attributes");
1208
1209     switch (RA) {
1210     case ATTR_NONE:
1211       switch (bitAttr) {
1212       case ATTR_FILTERED:
1213         break;
1214       case ATTR_ALL_SET:
1215         StartBit = BitIndex;
1216         RA = ATTR_ALL_SET;
1217         break;
1218       case ATTR_ALL_UNSET:
1219         break;
1220       case ATTR_MIXED:
1221         StartBit = BitIndex;
1222         RA = ATTR_MIXED;
1223         break;
1224       default:
1225         assert(0 && "Unexpected bitAttr!");
1226       }
1227       break;
1228     case ATTR_ALL_SET:
1229       switch (bitAttr) {
1230       case ATTR_FILTERED:
1231         reportRegion(RA, StartBit, BitIndex, AllowMixed);
1232         RA = ATTR_NONE;
1233         break;
1234       case ATTR_ALL_SET:
1235         break;
1236       case ATTR_ALL_UNSET:
1237         reportRegion(RA, StartBit, BitIndex, AllowMixed);
1238         RA = ATTR_NONE;
1239         break;
1240       case ATTR_MIXED:
1241         reportRegion(RA, StartBit, BitIndex, AllowMixed);
1242         StartBit = BitIndex;
1243         RA = ATTR_MIXED;
1244         break;
1245       default:
1246         assert(0 && "Unexpected bitAttr!");
1247       }
1248       break;
1249     case ATTR_MIXED:
1250       switch (bitAttr) {
1251       case ATTR_FILTERED:
1252         reportRegion(RA, StartBit, BitIndex, AllowMixed);
1253         StartBit = BitIndex;
1254         RA = ATTR_NONE;
1255         break;
1256       case ATTR_ALL_SET:
1257         reportRegion(RA, StartBit, BitIndex, AllowMixed);
1258         StartBit = BitIndex;
1259         RA = ATTR_ALL_SET;
1260         break;
1261       case ATTR_ALL_UNSET:
1262         reportRegion(RA, StartBit, BitIndex, AllowMixed);
1263         RA = ATTR_NONE;
1264         break;
1265       case ATTR_MIXED:
1266         break;
1267       default:
1268         assert(0 && "Unexpected bitAttr!");
1269       }
1270       break;
1271     case ATTR_ALL_UNSET:
1272       assert(0 && "regionAttr state machine has no ATTR_UNSET state");
1273     case ATTR_FILTERED:
1274       assert(0 && "regionAttr state machine has no ATTR_FILTERED state");
1275     }
1276   }
1277
1278   // At the end, if we're still in ALL_SET or MIXED states, report a region
1279   switch (RA) {
1280   case ATTR_NONE:
1281     break;
1282   case ATTR_FILTERED:
1283     break;
1284   case ATTR_ALL_SET:
1285     reportRegion(RA, StartBit, BitIndex, AllowMixed);
1286     break;
1287   case ATTR_ALL_UNSET:
1288     break;
1289   case ATTR_MIXED:
1290     reportRegion(RA, StartBit, BitIndex, AllowMixed);
1291     break;
1292   }
1293
1294   // We have finished with the filter processings.  Now it's time to choose
1295   // the best performing filter.
1296   BestIndex = 0;
1297   bool AllUseless = true;
1298   unsigned BestScore = 0;
1299
1300   for (unsigned i = 0, e = Filters.size(); i != e; ++i) {
1301     unsigned Usefulness = Filters[i].usefulness();
1302
1303     if (Usefulness)
1304       AllUseless = false;
1305
1306     if (Usefulness > BestScore) {
1307       BestIndex = i;
1308       BestScore = Usefulness;
1309     }
1310   }
1311
1312   if (!AllUseless)
1313     bestFilter().recurse();
1314
1315   return !AllUseless;
1316 } // end of FilterChooser::filterProcessor(bool)
1317
1318 // Decides on the best configuration of filter(s) to use in order to decode
1319 // the instructions.  A conflict of instructions may occur, in which case we
1320 // dump the conflict set to the standard error.
1321 void FilterChooser::doFilter() {
1322   unsigned Num = Opcodes.size();
1323   assert(Num && "FilterChooser created with no instructions");
1324
1325   // Heuristics: Use Inst{31-28} as the top level filter for ARM ISA.
1326   if (TargetName == TARGET_ARM && Parent == NULL) {
1327     runSingleFilter(*this, 28, 4, false);
1328     return;
1329   }
1330
1331   // Try regions of consecutive known bit values first. 
1332   if (filterProcessor(false))
1333     return;
1334
1335   // Then regions of mixed bits (both known and unitialized bit values allowed).
1336   if (filterProcessor(true))
1337     return;
1338
1339   // Heuristics to cope with conflict set {t2CMPrs, t2SUBSrr, t2SUBSrs} where
1340   // no single instruction for the maximum ATTR_MIXED region Inst{14-4} has a
1341   // well-known encoding pattern.  In such case, we backtrack and scan for the
1342   // the very first consecutive ATTR_ALL_SET region and assign a filter to it.
1343   if (Num == 3 && filterProcessor(true, false))
1344     return;
1345
1346   // If we come to here, the instruction decoding has failed.
1347   // Set the BestIndex to -1 to indicate so.
1348   BestIndex = -1;
1349 }
1350
1351 // Emits code to decode our share of instructions.  Returns true if the
1352 // emitted code causes a return, which occurs if we know how to decode
1353 // the instruction at this level or the instruction is not decodeable.
1354 bool FilterChooser::emit(raw_ostream &o, unsigned &Indentation) {
1355   if (Opcodes.size() == 1)
1356     // There is only one instruction in the set, which is great!
1357     // Call emitSingletonDecoder() to see whether there are any remaining
1358     // encodings bits.
1359     return emitSingletonDecoder(o, Indentation, Opcodes[0]);
1360
1361   // Choose the best filter to do the decodings!
1362   if (BestIndex != -1) {
1363     Filter &Best = bestFilter();
1364     if (Best.getNumFiltered() == 1)
1365       emitSingletonDecoder(o, Indentation, Best);
1366     else
1367       bestFilter().emit(o, Indentation);
1368     return false;
1369   }
1370
1371   // If we reach here, there is a conflict in decoding.  Let's resolve the known
1372   // conflicts!
1373   if ((TargetName == TARGET_ARM || TargetName == TARGET_THUMB) &&
1374       Opcodes.size() == 2) {
1375     // Resolve the known conflict sets:
1376     //
1377     // 1. source registers are identical => VMOVDneon; otherwise => VORRd
1378     // 2. source registers are identical => VMOVQ; otherwise => VORRq
1379     // 3. LDR, LDRcp => return LDR for now.
1380     // FIXME: How can we distinguish between LDR and LDRcp?  Do we need to?
1381     // 4. tLDM, tLDM_UPD => Rn = Inst{10-8}, reglist = Inst{7-0},
1382     //    wback = registers<Rn> = 0
1383     // NOTE: (tLDM, tLDM_UPD) resolution must come before Advanced SIMD
1384     //       addressing mode resolution!!!
1385     // 5. VLD[234]LN*/VST[234]LN* vs. VLD[234]LN*_UPD/VST[234]LN*_UPD conflicts
1386     //    are resolved returning the non-UPD versions of the instructions if the
1387     //    Rm field, i.e., Inst{3-0} is 0b1111.  This is specified in A7.7.1
1388     //    Advanced SIMD addressing mode.
1389     const std::string &name1 = nameWithID(Opcodes[0]);
1390     const std::string &name2 = nameWithID(Opcodes[1]);
1391     if ((name1 == "VMOVDneon" && name2 == "VORRd") ||
1392         (name1 == "VMOVQ" && name2 == "VORRq")) {
1393       // Inserting the opening curly brace for this case block.
1394       --Indentation; --Indentation;
1395       o.indent(Indentation) << "{\n";
1396       ++Indentation; ++Indentation;
1397
1398       o.indent(Indentation)
1399         << "field_t N = fieldFromInstruction(insn, 7, 1), "
1400         << "M = fieldFromInstruction(insn, 5, 1);\n";
1401       o.indent(Indentation)
1402         << "field_t Vn = fieldFromInstruction(insn, 16, 4), "
1403         << "Vm = fieldFromInstruction(insn, 0, 4);\n";
1404       o.indent(Indentation)
1405         << "return (N == M && Vn == Vm) ? "
1406         << Opcodes[0] << " /* " << name1 << " */ : "
1407         << Opcodes[1] << " /* " << name2 << " */ ;\n";
1408
1409       // Inserting the closing curly brace for this case block.
1410       --Indentation; --Indentation;
1411       o.indent(Indentation) << "}\n";
1412       ++Indentation; ++Indentation;
1413
1414       return true;
1415     }
1416     if (name1 == "LDR" && name2 == "LDRcp") {
1417       o.indent(Indentation)
1418         << "return " << Opcodes[0]
1419         << "; // Returning LDR for {LDR, LDRcp}\n";
1420       return true;
1421     }
1422     if (name1 == "tLDM" && name2 == "tLDM_UPD") {
1423       // Inserting the opening curly brace for this case block.
1424       --Indentation; --Indentation;
1425       o.indent(Indentation) << "{\n";
1426       ++Indentation; ++Indentation;
1427       
1428       o.indent(Indentation)
1429         << "unsigned Rn = fieldFromInstruction(insn, 8, 3), "
1430         << "list = fieldFromInstruction(insn, 0, 8);\n";
1431       o.indent(Indentation)
1432         << "return ((list >> Rn) & 1) == 0 ? "
1433         << Opcodes[1] << " /* " << name2 << " */ : "
1434         << Opcodes[0] << " /* " << name1 << " */ ;\n";
1435
1436       // Inserting the closing curly brace for this case block.
1437       --Indentation; --Indentation;
1438       o.indent(Indentation) << "}\n";
1439       ++Indentation; ++Indentation;
1440
1441       return true;
1442     }
1443     if (sameStringExceptSuffix(name1, name2, "_UPD")) {
1444       o.indent(Indentation)
1445         << "return fieldFromInstruction(insn, 0, 4) == 15 ? " << Opcodes[0]
1446         << " /* " << name1 << " */ : " << Opcodes[1] << "/* " << name2
1447         << " */ ; // Advanced SIMD addressing mode\n";
1448       return true;
1449     }
1450
1451     // Otherwise, it does not belong to the known conflict sets.
1452   }
1453
1454   // We don't know how to decode these instructions!  Return 0 and dump the
1455   // conflict set!
1456   o.indent(Indentation) << "return 0;" << " // Conflict set: ";
1457   for (int i = 0, N = Opcodes.size(); i < N; ++i) {
1458     o << nameWithID(Opcodes[i]);
1459     if (i < (N - 1))
1460       o << ", ";
1461     else
1462       o << '\n';
1463   }
1464
1465   // Print out useful conflict information for postmortem analysis.
1466   errs() << "Decoding Conflict:\n";
1467
1468   dumpStack(errs(), "\t\t");
1469
1470   for (unsigned i = 0; i < Opcodes.size(); i++) {
1471     const std::string &Name = nameWithID(Opcodes[i]);
1472
1473     errs() << '\t' << Name << " ";
1474     dumpBits(errs(),
1475              getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
1476     errs() << '\n';
1477   }
1478
1479   return true;
1480 }
1481
1482
1483 ////////////////////////////////////////////
1484 //                                        //
1485 //  ARMDEBackend                          //
1486 //  (Helper class for ARMDecoderEmitter)  //
1487 //                                        //
1488 ////////////////////////////////////////////
1489
1490 class ARMDecoderEmitter::ARMDEBackend {
1491 public:
1492   ARMDEBackend(ARMDecoderEmitter &frontend) :
1493     NumberedInstructions(),
1494     Opcodes(),
1495     Frontend(frontend),
1496     Target(),
1497     FC(NULL)
1498   {
1499     if (Target.getName() == "ARM")
1500       TargetName = TARGET_ARM;
1501     else {
1502       errs() << "Target name " << Target.getName() << " not recognized\n";
1503       assert(0 && "Unknown target");
1504     }
1505
1506     // Populate the instructions for our TargetName.
1507     populateInstructions();
1508   }
1509
1510   ~ARMDEBackend() {
1511     if (FC) {
1512       delete FC;
1513       FC = NULL;
1514     }
1515   }
1516
1517   void getInstructionsByEnumValue(std::vector<const CodeGenInstruction*>
1518                                                 &NumberedInstructions) {
1519     // We must emit the PHI opcode first...
1520     std::string Namespace = Target.getInstNamespace();
1521     assert(!Namespace.empty() && "No instructions defined.");
1522
1523     NumberedInstructions = Target.getInstructionsByEnumValue();
1524   }
1525
1526   bool populateInstruction(const CodeGenInstruction &CGI, TARGET_NAME_t TN);
1527
1528   void populateInstructions();
1529
1530   // Emits disassembler code for instruction decoding.  This delegates to the
1531   // FilterChooser instance to do the heavy lifting.
1532   void emit(raw_ostream &o);
1533
1534 protected:
1535   std::vector<const CodeGenInstruction*> NumberedInstructions;
1536   std::vector<unsigned> Opcodes;
1537   // Special case for the ARM chip, which supports ARM and Thumb ISAs.
1538   // Opcodes2 will be populated with the Thumb opcodes.
1539   std::vector<unsigned> Opcodes2;
1540   ARMDecoderEmitter &Frontend;
1541   CodeGenTarget Target;
1542   FilterChooser *FC;
1543
1544   TARGET_NAME_t TargetName;
1545 };
1546
1547 bool ARMDecoderEmitter::ARMDEBackend::populateInstruction(
1548     const CodeGenInstruction &CGI, TARGET_NAME_t TN) {
1549   const Record &Def = *CGI.TheDef;
1550   const StringRef Name = Def.getName();
1551   uint8_t Form = getByteField(Def, "Form");
1552
1553   BitsInit &Bits = getBitsField(Def, "Inst");
1554
1555   // If all the bit positions are not specified; do not decode this instruction.
1556   // We are bound to fail!  For proper disassembly, the well-known encoding bits
1557   // of the instruction must be fully specified.
1558   //
1559   // This also removes pseudo instructions from considerations of disassembly,
1560   // which is a better design and less fragile than the name matchings.
1561   if (Bits.allInComplete()) return false;
1562
1563   if (TN == TARGET_ARM) {
1564     // FIXME: what about Int_MemBarrierV6 and Int_SyncBarrierV6?
1565     if ((Name != "Int_MemBarrierV7" && Name != "Int_SyncBarrierV7") &&
1566         Form == ARM_FORMAT_PSEUDO)
1567       return false;
1568     if (thumbInstruction(Form))
1569       return false;
1570     if (Name.find("CMPz") != std::string::npos /* ||
1571         Name.find("CMNz") != std::string::npos */)
1572       return false;
1573
1574     // Ignore pseudo instructions.
1575     if (Name == "BXr9" || Name == "BMOVPCRX" || Name == "BMOVPCRXr9")
1576       return false;
1577
1578     // VLDMQ/VSTMQ can be hanlded with the more generic VLDMD/VSTMD.
1579     if (Name == "VLDMQ" || Name == "VLDMQ_UPD" ||
1580         Name == "VSTMQ" || Name == "VSTMQ_UPD")
1581       return false;
1582
1583     //
1584     // The following special cases are for conflict resolutions.
1585     //
1586
1587     // NEON NLdStFrm conflict resolutions:
1588     //
1589     // 1. Ignore suffix "odd" and "odd_UPD", prefer the "even" register-
1590     //    numbered ones which have the same Asm format string.
1591     // 2. Ignore VST2d64_UPD, which conflicts with VST1q64_UPD.
1592     // 3. Ignore VLD2d64_UPD, which conflicts with VLD1q64_UPD.
1593     // 4. Ignore VLD1q[_UPD], which conflicts with VLD1q64[_UPD].
1594     // 5. Ignore VST1q[_UPD], which conflicts with VST1q64[_UPD].
1595     if (Name.endswith("odd") || Name.endswith("odd_UPD") ||
1596         Name == "VST2d64_UPD" || Name == "VLD2d64_UPD" ||
1597         Name == "VLD1q" || Name == "VLD1q_UPD" ||
1598         Name == "VST1q" || Name == "VST1q_UPD")
1599       return false;
1600
1601     // RSCSri and RSCSrs set the 's' bit, but are not predicated.  We are
1602     // better off using the generic RSCri and RSCrs instructions.
1603     if (Name == "RSCSri" || Name == "RSCSrs") return false;
1604
1605     // MOVCCr, MOVCCs, MOVCCi, FCYPScc, FCYPDcc, FNEGScc, and FNEGDcc are used
1606     // in the compiler to implement conditional moves.  We can ignore them in
1607     // favor of their more generic versions of instructions.
1608     // See also SDNode *ARMDAGToDAGISel::Select(SDValue Op).
1609     if (Name == "MOVCCr" || Name == "MOVCCs" || Name == "MOVCCi" ||
1610         Name == "FCPYScc" || Name == "FCPYDcc" ||
1611         Name == "FNEGScc" || Name == "FNEGDcc")
1612       return false;
1613
1614     // Ditto for VMOVDcc, VMOVScc, VNEGDcc, and VNEGScc.
1615     if (Name == "VMOVDcc" || Name == "VMOVScc" || Name == "VNEGDcc" ||
1616         Name == "VNEGScc")
1617       return false;
1618
1619     // Ignore the *_sfp instructions when decoding.  They are used by the
1620     // compiler to implement scalar floating point operations using vector
1621     // operations in order to work around some performance issues.
1622     if (Name.find("_sfp") != std::string::npos) return false;
1623
1624     // LDM_RET is a special case of LDM (Load Multiple) where the registers
1625     // loaded include the PC, causing a branch to a loaded address.  Ignore
1626     // the LDM_RET instruction when decoding.
1627     if (Name == "LDM_RET") return false;
1628
1629     // Bcc is in a more generic form than B.  Ignore B when decoding.
1630     if (Name == "B") return false;
1631
1632     // Ignore the non-Darwin BL instructions and the TPsoft (TLS) instruction.
1633     if (Name == "BL" || Name == "BL_pred" || Name == "BLX" || Name == "BX" ||
1634         Name == "TPsoft")
1635       return false;
1636
1637     // Ignore VDUPf[d|q] instructions known to conflict with VDUP32[d-q] for
1638     // decoding.  The instruction duplicates an element from an ARM core
1639     // register into every element of the destination vector.  There is no
1640     // distinction between data types.
1641     if (Name == "VDUPfd" || Name == "VDUPfq") return false;
1642
1643     // A8-598: VEXT
1644     // Vector Extract extracts elements from the bottom end of the second
1645     // operand vector and the top end of the first, concatenates them and
1646     // places the result in the destination vector.  The elements of the
1647     // vectors are treated as being 8-bit bitfields.  There is no distinction
1648     // between data types.  The size of the operation can be specified in
1649     // assembler as vext.size.  If the value is 16, 32, or 64, the syntax is
1650     // a pseudo-instruction for a VEXT instruction specifying the equivalent
1651     // number of bytes.
1652     //
1653     // Variants VEXTd16, VEXTd32, VEXTd8, and VEXTdf are reduced to VEXTd8;
1654     // variants VEXTq16, VEXTq32, VEXTq8, and VEXTqf are reduced to VEXTq8.
1655     if (Name == "VEXTd16" || Name == "VEXTd32" || Name == "VEXTdf" ||
1656         Name == "VEXTq16" || Name == "VEXTq32" || Name == "VEXTqf")
1657       return false;
1658
1659     // Vector Reverse is similar to Vector Extract.  There is no distinction
1660     // between data types, other than size.
1661     //
1662     // VREV64df is equivalent to VREV64d32.
1663     // VREV64qf is equivalent to VREV64q32.
1664     if (Name == "VREV64df" || Name == "VREV64qf") return false;
1665
1666     // VDUPLNfd is equivalent to VDUPLN32d; VDUPfdf is specialized VDUPLN32d.
1667     // VDUPLNfq is equivalent to VDUPLN32q; VDUPfqf is specialized VDUPLN32q.
1668     // VLD1df is equivalent to VLD1d32.
1669     // VLD1qf is equivalent to VLD1q32.
1670     // VLD2d64 is equivalent to VLD1q64.
1671     // VST1df is equivalent to VST1d32.
1672     // VST1qf is equivalent to VST1q32.
1673     // VST2d64 is equivalent to VST1q64.
1674     if (Name == "VDUPLNfd" || Name == "VDUPfdf" ||
1675         Name == "VDUPLNfq" || Name == "VDUPfqf" ||
1676         Name == "VLD1df" || Name == "VLD1qf" || Name == "VLD2d64" ||
1677         Name == "VST1df" || Name == "VST1qf" || Name == "VST2d64")
1678       return false;
1679   } else if (TN == TARGET_THUMB) {
1680     if (!thumbInstruction(Form))
1681       return false;
1682
1683     // On Darwin R9 is call-clobbered.  Ignore the non-Darwin counterparts.
1684     if (Name == "tBL" || Name == "tBLXi" || Name == "tBLXr")
1685       return false;
1686
1687     // Ignore the TPsoft (TLS) instructions, which conflict with tBLr9.
1688     if (Name == "tTPsoft" || Name == "t2TPsoft")
1689       return false;
1690
1691     // Ignore tLEApcrel and tLEApcrelJT, prefer tADDrPCi.
1692     if (Name == "tLEApcrel" || Name == "tLEApcrelJT")
1693       return false;
1694
1695     // Ignore t2LEApcrel, prefer the generic t2ADD* for disassembly printing.
1696     if (Name == "t2LEApcrel")
1697       return false;
1698
1699     // Ignore tADDrSP, tADDspr, and tPICADD, prefer the generic tADDhirr.
1700     // Ignore t2SUBrSPs, prefer the t2SUB[S]r[r|s].
1701     // Ignore t2ADDrSPs, prefer the t2ADD[S]r[r|s].
1702     // Ignore t2ADDrSPi/t2SUBrSPi, which have more generic couterparts.
1703     // Ignore t2ADDrSPi12/t2SUBrSPi12, which have more generic couterparts
1704     if (Name == "tADDrSP" || Name == "tADDspr" || Name == "tPICADD" ||
1705         Name == "t2SUBrSPs" || Name == "t2ADDrSPs" ||
1706         Name == "t2ADDrSPi" || Name == "t2SUBrSPi" ||
1707         Name == "t2ADDrSPi12" || Name == "t2SUBrSPi12")
1708       return false;
1709
1710     // Ignore t2LDRDpci, prefer the generic t2LDRDi8, t2LDRD_PRE, t2LDRD_POST.
1711     if (Name == "t2LDRDpci")
1712       return false;
1713
1714     // Ignore t2TBB, t2TBH and prefer the generic t2TBBgen, t2TBHgen.
1715     if (Name == "t2TBB" || Name == "t2TBH")
1716       return false;
1717
1718     // Resolve conflicts:
1719     //
1720     //   tBfar conflicts with tBLr9
1721     //   tCMNz conflicts with tCMN (with assembly format strings being equal)
1722     //   tPOP_RET/t2LDM_RET conflict with tPOP/t2LDM (ditto)
1723     //   tMOVCCi conflicts with tMOVi8
1724     //   tMOVCCr conflicts with tMOVgpr2gpr
1725     //   tBR_JTr conflicts with tBRIND
1726     //   tSpill conflicts with tSTRspi
1727     //   tLDRcp conflicts with tLDRspi
1728     //   tRestore conflicts with tLDRspi
1729     //   t2LEApcrelJT conflicts with t2LEApcrel
1730     if (Name == "tBfar" ||
1731         /* Name == "tCMNz" || */ Name == "tCMPzi8" || Name == "tCMPzr" ||
1732         Name == "tCMPzhir" || /* Name == "t2CMNzrr" || Name == "t2CMNzrs" ||
1733         Name == "t2CMNzri" || */ Name == "t2CMPzrr" || Name == "t2CMPzrs" ||
1734         Name == "t2CMPzri" || Name == "tPOP_RET" || Name == "t2LDM_RET" ||
1735         Name == "tMOVCCi" || Name == "tMOVCCr" || Name == "tBR_JTr" ||
1736         Name == "tSpill" || Name == "tLDRcp" || Name == "tRestore" ||
1737         Name == "t2LEApcrelJT")
1738       return false;
1739   }
1740
1741   // Dumps the instruction encoding format.
1742   switch (TargetName) {
1743   case TARGET_ARM:
1744   case TARGET_THUMB:
1745     DEBUG(errs() << Name << " " << stringForARMFormat((ARMFormat)Form));
1746     break;
1747   }
1748
1749   DEBUG({
1750       errs() << " ";
1751
1752       // Dumps the instruction encoding bits.
1753       dumpBits(errs(), Bits);
1754
1755       errs() << '\n';
1756
1757       // Dumps the list of operand info.
1758       for (unsigned i = 0, e = CGI.OperandList.size(); i != e; ++i) {
1759         CodeGenInstruction::OperandInfo Info = CGI.OperandList[i];
1760         const std::string &OperandName = Info.Name;
1761         const Record &OperandDef = *Info.Rec;
1762
1763         errs() << "\t" << OperandName << " (" << OperandDef.getName() << ")\n";
1764       }
1765     });
1766
1767   return true;
1768 }
1769
1770 void ARMDecoderEmitter::ARMDEBackend::populateInstructions() {
1771   getInstructionsByEnumValue(NumberedInstructions);
1772
1773   uint16_t numUIDs = NumberedInstructions.size();
1774   uint16_t uid;
1775
1776   const char *instClass = NULL;
1777
1778   switch (TargetName) {
1779   case TARGET_ARM:
1780     instClass = "InstARM";
1781     break;
1782   default:
1783     assert(0 && "Unreachable code!");
1784   }
1785
1786   for (uid = 0; uid < numUIDs; uid++) {
1787     // filter out intrinsics
1788     if (!NumberedInstructions[uid]->TheDef->isSubClassOf(instClass))
1789       continue;
1790
1791     if (populateInstruction(*NumberedInstructions[uid], TargetName))
1792       Opcodes.push_back(uid);
1793   }
1794
1795   // Special handling for the ARM chip, which supports two modes of execution.
1796   // This branch handles the Thumb opcodes.
1797   if (TargetName == TARGET_ARM) {
1798     for (uid = 0; uid < numUIDs; uid++) {
1799       // filter out intrinsics
1800       if (!NumberedInstructions[uid]->TheDef->isSubClassOf("InstARM")
1801           && !NumberedInstructions[uid]->TheDef->isSubClassOf("InstThumb"))
1802         continue;
1803
1804       if (populateInstruction(*NumberedInstructions[uid], TARGET_THUMB))
1805         Opcodes2.push_back(uid);
1806     }
1807   }
1808 }
1809
1810 // Emits disassembler code for instruction decoding.  This delegates to the
1811 // FilterChooser instance to do the heavy lifting.
1812 void ARMDecoderEmitter::ARMDEBackend::emit(raw_ostream &o) {
1813   switch (TargetName) {
1814   case TARGET_ARM:
1815     Frontend.EmitSourceFileHeader("ARM/Thumb Decoders", o);
1816     break;
1817   default:
1818     assert(0 && "Unreachable code!");
1819   }
1820
1821   o << "#include \"llvm/System/DataTypes.h\"\n";
1822   o << "#include <assert.h>\n";
1823   o << '\n';
1824   o << "namespace llvm {\n\n";
1825
1826   FilterChooser::setTargetName(TargetName);
1827
1828   switch (TargetName) {
1829   case TARGET_ARM: {
1830     // Emit common utility and ARM ISA decoder.
1831     FC = new FilterChooser(NumberedInstructions, Opcodes);
1832     // Reset indentation level.
1833     unsigned Indentation = 0;
1834     FC->emitTop(o, Indentation);
1835     delete FC;
1836
1837     // Emit Thumb ISA decoder as well.
1838     FilterChooser::setTargetName(TARGET_THUMB);
1839     FC = new FilterChooser(NumberedInstructions, Opcodes2);
1840     // Reset indentation level.
1841     Indentation = 0;
1842     FC->emitBot(o, Indentation);
1843     break;
1844   }
1845   default:
1846     assert(0 && "Unreachable code!");
1847   }
1848
1849   o << "\n} // End llvm namespace \n";
1850 }
1851
1852 /////////////////////////
1853 //  Backend interface  //
1854 /////////////////////////
1855
1856 void ARMDecoderEmitter::initBackend()
1857 {
1858     Backend = new ARMDEBackend(*this);
1859 }
1860
1861 void ARMDecoderEmitter::run(raw_ostream &o)
1862 {
1863   Backend->emit(o);
1864 }
1865
1866 void ARMDecoderEmitter::shutdownBackend()
1867 {
1868   delete Backend;
1869   Backend = NULL;
1870 }