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