1f4a2713aSLionel Sambuc //===------------ FixedLenDecoderEmitter.cpp - Decoder Generator ----------===//
2f4a2713aSLionel Sambuc //
3f4a2713aSLionel Sambuc //                     The LLVM Compiler Infrastructure
4f4a2713aSLionel Sambuc //
5f4a2713aSLionel Sambuc // This file is distributed under the University of Illinois Open Source
6f4a2713aSLionel Sambuc // License. See LICENSE.TXT for details.
7f4a2713aSLionel Sambuc //
8f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
9f4a2713aSLionel Sambuc //
10f4a2713aSLionel Sambuc // It contains the tablegen backend that emits the decoder functions for
11f4a2713aSLionel Sambuc // targets with fixed length instruction set.
12f4a2713aSLionel Sambuc //
13f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
14f4a2713aSLionel Sambuc 
15f4a2713aSLionel Sambuc #include "CodeGenTarget.h"
16f4a2713aSLionel Sambuc #include "llvm/ADT/APInt.h"
17f4a2713aSLionel Sambuc #include "llvm/ADT/SmallString.h"
18f4a2713aSLionel Sambuc #include "llvm/ADT/StringExtras.h"
19f4a2713aSLionel Sambuc #include "llvm/ADT/StringRef.h"
20f4a2713aSLionel Sambuc #include "llvm/ADT/Twine.h"
21f4a2713aSLionel Sambuc #include "llvm/MC/MCFixedLenDisassembler.h"
22f4a2713aSLionel Sambuc #include "llvm/Support/DataTypes.h"
23f4a2713aSLionel Sambuc #include "llvm/Support/Debug.h"
24f4a2713aSLionel Sambuc #include "llvm/Support/FormattedStream.h"
25f4a2713aSLionel Sambuc #include "llvm/Support/LEB128.h"
26f4a2713aSLionel Sambuc #include "llvm/Support/raw_ostream.h"
27f4a2713aSLionel Sambuc #include "llvm/TableGen/Error.h"
28f4a2713aSLionel Sambuc #include "llvm/TableGen/Record.h"
29f4a2713aSLionel Sambuc #include <map>
30f4a2713aSLionel Sambuc #include <string>
31f4a2713aSLionel Sambuc #include <vector>
32f4a2713aSLionel Sambuc 
33f4a2713aSLionel Sambuc using namespace llvm;
34f4a2713aSLionel Sambuc 
35*0a6a1f1dSLionel Sambuc #define DEBUG_TYPE "decoder-emitter"
36*0a6a1f1dSLionel Sambuc 
37f4a2713aSLionel Sambuc namespace {
38f4a2713aSLionel Sambuc struct EncodingField {
39f4a2713aSLionel Sambuc   unsigned Base, Width, Offset;
EncodingField__anonc4ca6b850111::EncodingField40f4a2713aSLionel Sambuc   EncodingField(unsigned B, unsigned W, unsigned O)
41f4a2713aSLionel Sambuc     : Base(B), Width(W), Offset(O) { }
42f4a2713aSLionel Sambuc };
43f4a2713aSLionel Sambuc 
44f4a2713aSLionel Sambuc struct OperandInfo {
45f4a2713aSLionel Sambuc   std::vector<EncodingField> Fields;
46f4a2713aSLionel Sambuc   std::string Decoder;
47f4a2713aSLionel Sambuc 
OperandInfo__anonc4ca6b850111::OperandInfo48f4a2713aSLionel Sambuc   OperandInfo(std::string D)
49f4a2713aSLionel Sambuc     : Decoder(D) { }
50f4a2713aSLionel Sambuc 
addField__anonc4ca6b850111::OperandInfo51f4a2713aSLionel Sambuc   void addField(unsigned Base, unsigned Width, unsigned Offset) {
52f4a2713aSLionel Sambuc     Fields.push_back(EncodingField(Base, Width, Offset));
53f4a2713aSLionel Sambuc   }
54f4a2713aSLionel Sambuc 
numFields__anonc4ca6b850111::OperandInfo55f4a2713aSLionel Sambuc   unsigned numFields() const { return Fields.size(); }
56f4a2713aSLionel Sambuc 
57f4a2713aSLionel Sambuc   typedef std::vector<EncodingField>::const_iterator const_iterator;
58f4a2713aSLionel Sambuc 
begin__anonc4ca6b850111::OperandInfo59f4a2713aSLionel Sambuc   const_iterator begin() const { return Fields.begin(); }
end__anonc4ca6b850111::OperandInfo60f4a2713aSLionel Sambuc   const_iterator end() const   { return Fields.end();   }
61f4a2713aSLionel Sambuc };
62f4a2713aSLionel Sambuc 
63f4a2713aSLionel Sambuc typedef std::vector<uint8_t> DecoderTable;
64f4a2713aSLionel Sambuc typedef uint32_t DecoderFixup;
65f4a2713aSLionel Sambuc typedef std::vector<DecoderFixup> FixupList;
66f4a2713aSLionel Sambuc typedef std::vector<FixupList> FixupScopeList;
67f4a2713aSLionel Sambuc typedef SetVector<std::string> PredicateSet;
68f4a2713aSLionel Sambuc typedef SetVector<std::string> DecoderSet;
69f4a2713aSLionel Sambuc struct DecoderTableInfo {
70f4a2713aSLionel Sambuc   DecoderTable Table;
71f4a2713aSLionel Sambuc   FixupScopeList FixupStack;
72f4a2713aSLionel Sambuc   PredicateSet Predicates;
73f4a2713aSLionel Sambuc   DecoderSet Decoders;
74f4a2713aSLionel Sambuc };
75f4a2713aSLionel Sambuc 
76f4a2713aSLionel Sambuc } // End anonymous namespace
77f4a2713aSLionel Sambuc 
78f4a2713aSLionel Sambuc namespace {
79f4a2713aSLionel Sambuc class FixedLenDecoderEmitter {
80f4a2713aSLionel Sambuc   const std::vector<const CodeGenInstruction*> *NumberedInstructions;
81f4a2713aSLionel Sambuc public:
82f4a2713aSLionel Sambuc 
83f4a2713aSLionel Sambuc   // Defaults preserved here for documentation, even though they aren't
84f4a2713aSLionel Sambuc   // strictly necessary given the way that this is currently being called.
FixedLenDecoderEmitter(RecordKeeper & R,std::string PredicateNamespace,std::string GPrefix="if (",std::string GPostfix=" == MCDisassembler::Fail)"" return MCDisassembler::Fail;",std::string ROK="MCDisassembler::Success",std::string RFail="MCDisassembler::Fail",std::string L="")85f4a2713aSLionel Sambuc   FixedLenDecoderEmitter(RecordKeeper &R,
86f4a2713aSLionel Sambuc                          std::string PredicateNamespace,
87f4a2713aSLionel Sambuc                          std::string GPrefix  = "if (",
88f4a2713aSLionel Sambuc                          std::string GPostfix = " == MCDisassembler::Fail)"
89f4a2713aSLionel Sambuc                          " return MCDisassembler::Fail;",
90f4a2713aSLionel Sambuc                          std::string ROK      = "MCDisassembler::Success",
91f4a2713aSLionel Sambuc                          std::string RFail    = "MCDisassembler::Fail",
92f4a2713aSLionel Sambuc                          std::string L        = "") :
93f4a2713aSLionel Sambuc     Target(R),
94f4a2713aSLionel Sambuc     PredicateNamespace(PredicateNamespace),
95f4a2713aSLionel Sambuc     GuardPrefix(GPrefix), GuardPostfix(GPostfix),
96f4a2713aSLionel Sambuc     ReturnOK(ROK), ReturnFail(RFail), Locals(L) {}
97f4a2713aSLionel Sambuc 
98f4a2713aSLionel Sambuc   // Emit the decoder state machine table.
99f4a2713aSLionel Sambuc   void emitTable(formatted_raw_ostream &o, DecoderTable &Table,
100f4a2713aSLionel Sambuc                  unsigned Indentation, unsigned BitWidth,
101f4a2713aSLionel Sambuc                  StringRef Namespace) const;
102f4a2713aSLionel Sambuc   void emitPredicateFunction(formatted_raw_ostream &OS,
103f4a2713aSLionel Sambuc                              PredicateSet &Predicates,
104f4a2713aSLionel Sambuc                              unsigned Indentation) const;
105f4a2713aSLionel Sambuc   void emitDecoderFunction(formatted_raw_ostream &OS,
106f4a2713aSLionel Sambuc                            DecoderSet &Decoders,
107f4a2713aSLionel Sambuc                            unsigned Indentation) const;
108f4a2713aSLionel Sambuc 
109f4a2713aSLionel Sambuc   // run - Output the code emitter
110f4a2713aSLionel Sambuc   void run(raw_ostream &o);
111f4a2713aSLionel Sambuc 
112f4a2713aSLionel Sambuc private:
113f4a2713aSLionel Sambuc   CodeGenTarget Target;
114f4a2713aSLionel Sambuc public:
115f4a2713aSLionel Sambuc   std::string PredicateNamespace;
116f4a2713aSLionel Sambuc   std::string GuardPrefix, GuardPostfix;
117f4a2713aSLionel Sambuc   std::string ReturnOK, ReturnFail;
118f4a2713aSLionel Sambuc   std::string Locals;
119f4a2713aSLionel Sambuc };
120f4a2713aSLionel Sambuc } // End anonymous namespace
121f4a2713aSLionel Sambuc 
122f4a2713aSLionel Sambuc // The set (BIT_TRUE, BIT_FALSE, BIT_UNSET) represents a ternary logic system
123f4a2713aSLionel Sambuc // for a bit value.
124f4a2713aSLionel Sambuc //
125f4a2713aSLionel Sambuc // BIT_UNFILTERED is used as the init value for a filter position.  It is used
126f4a2713aSLionel Sambuc // only for filter processings.
127f4a2713aSLionel Sambuc typedef enum {
128f4a2713aSLionel Sambuc   BIT_TRUE,      // '1'
129f4a2713aSLionel Sambuc   BIT_FALSE,     // '0'
130f4a2713aSLionel Sambuc   BIT_UNSET,     // '?'
131f4a2713aSLionel Sambuc   BIT_UNFILTERED // unfiltered
132f4a2713aSLionel Sambuc } bit_value_t;
133f4a2713aSLionel Sambuc 
ValueSet(bit_value_t V)134f4a2713aSLionel Sambuc static bool ValueSet(bit_value_t V) {
135f4a2713aSLionel Sambuc   return (V == BIT_TRUE || V == BIT_FALSE);
136f4a2713aSLionel Sambuc }
ValueNotSet(bit_value_t V)137f4a2713aSLionel Sambuc static bool ValueNotSet(bit_value_t V) {
138f4a2713aSLionel Sambuc   return (V == BIT_UNSET);
139f4a2713aSLionel Sambuc }
Value(bit_value_t V)140f4a2713aSLionel Sambuc static int Value(bit_value_t V) {
141f4a2713aSLionel Sambuc   return ValueNotSet(V) ? -1 : (V == BIT_FALSE ? 0 : 1);
142f4a2713aSLionel Sambuc }
bitFromBits(const BitsInit & bits,unsigned index)143f4a2713aSLionel Sambuc static bit_value_t bitFromBits(const BitsInit &bits, unsigned index) {
144f4a2713aSLionel Sambuc   if (BitInit *bit = dyn_cast<BitInit>(bits.getBit(index)))
145f4a2713aSLionel Sambuc     return bit->getValue() ? BIT_TRUE : BIT_FALSE;
146f4a2713aSLionel Sambuc 
147f4a2713aSLionel Sambuc   // The bit is uninitialized.
148f4a2713aSLionel Sambuc   return BIT_UNSET;
149f4a2713aSLionel Sambuc }
150f4a2713aSLionel Sambuc // Prints the bit value for each position.
dumpBits(raw_ostream & o,const BitsInit & bits)151f4a2713aSLionel Sambuc static void dumpBits(raw_ostream &o, const BitsInit &bits) {
152f4a2713aSLionel Sambuc   for (unsigned index = bits.getNumBits(); index > 0; --index) {
153f4a2713aSLionel Sambuc     switch (bitFromBits(bits, index - 1)) {
154f4a2713aSLionel Sambuc     case BIT_TRUE:
155f4a2713aSLionel Sambuc       o << "1";
156f4a2713aSLionel Sambuc       break;
157f4a2713aSLionel Sambuc     case BIT_FALSE:
158f4a2713aSLionel Sambuc       o << "0";
159f4a2713aSLionel Sambuc       break;
160f4a2713aSLionel Sambuc     case BIT_UNSET:
161f4a2713aSLionel Sambuc       o << "_";
162f4a2713aSLionel Sambuc       break;
163f4a2713aSLionel Sambuc     default:
164f4a2713aSLionel Sambuc       llvm_unreachable("unexpected return value from bitFromBits");
165f4a2713aSLionel Sambuc     }
166f4a2713aSLionel Sambuc   }
167f4a2713aSLionel Sambuc }
168f4a2713aSLionel Sambuc 
getBitsField(const Record & def,const char * str)169f4a2713aSLionel Sambuc static BitsInit &getBitsField(const Record &def, const char *str) {
170f4a2713aSLionel Sambuc   BitsInit *bits = def.getValueAsBitsInit(str);
171f4a2713aSLionel Sambuc   return *bits;
172f4a2713aSLionel Sambuc }
173f4a2713aSLionel Sambuc 
174f4a2713aSLionel Sambuc // Forward declaration.
175f4a2713aSLionel Sambuc namespace {
176f4a2713aSLionel Sambuc class FilterChooser;
177f4a2713aSLionel Sambuc } // End anonymous namespace
178f4a2713aSLionel Sambuc 
179f4a2713aSLionel Sambuc // Representation of the instruction to work on.
180f4a2713aSLionel Sambuc typedef std::vector<bit_value_t> insn_t;
181f4a2713aSLionel Sambuc 
182f4a2713aSLionel Sambuc /// Filter - Filter works with FilterChooser to produce the decoding tree for
183f4a2713aSLionel Sambuc /// the ISA.
184f4a2713aSLionel Sambuc ///
185f4a2713aSLionel Sambuc /// It is useful to think of a Filter as governing the switch stmts of the
186f4a2713aSLionel Sambuc /// decoding tree in a certain level.  Each case stmt delegates to an inferior
187f4a2713aSLionel Sambuc /// FilterChooser to decide what further decoding logic to employ, or in another
188f4a2713aSLionel Sambuc /// words, what other remaining bits to look at.  The FilterChooser eventually
189f4a2713aSLionel Sambuc /// chooses a best Filter to do its job.
190f4a2713aSLionel Sambuc ///
191f4a2713aSLionel Sambuc /// This recursive scheme ends when the number of Opcodes assigned to the
192f4a2713aSLionel Sambuc /// FilterChooser becomes 1 or if there is a conflict.  A conflict happens when
193f4a2713aSLionel Sambuc /// the Filter/FilterChooser combo does not know how to distinguish among the
194f4a2713aSLionel Sambuc /// Opcodes assigned.
195f4a2713aSLionel Sambuc ///
196f4a2713aSLionel Sambuc /// An example of a conflict is
197f4a2713aSLionel Sambuc ///
198f4a2713aSLionel Sambuc /// Conflict:
199f4a2713aSLionel Sambuc ///                     111101000.00........00010000....
200f4a2713aSLionel Sambuc ///                     111101000.00........0001........
201f4a2713aSLionel Sambuc ///                     1111010...00........0001........
202f4a2713aSLionel Sambuc ///                     1111010...00....................
203f4a2713aSLionel Sambuc ///                     1111010.........................
204f4a2713aSLionel Sambuc ///                     1111............................
205f4a2713aSLionel Sambuc ///                     ................................
206f4a2713aSLionel Sambuc ///     VST4q8a         111101000_00________00010000____
207f4a2713aSLionel Sambuc ///     VST4q8b         111101000_00________00010000____
208f4a2713aSLionel Sambuc ///
209f4a2713aSLionel Sambuc /// The Debug output shows the path that the decoding tree follows to reach the
210f4a2713aSLionel Sambuc /// the conclusion that there is a conflict.  VST4q8a is a vst4 to double-spaced
211f4a2713aSLionel Sambuc /// even registers, while VST4q8b is a vst4 to double-spaced odd regsisters.
212f4a2713aSLionel Sambuc ///
213f4a2713aSLionel Sambuc /// The encoding info in the .td files does not specify this meta information,
214f4a2713aSLionel Sambuc /// which could have been used by the decoder to resolve the conflict.  The
215f4a2713aSLionel Sambuc /// decoder could try to decode the even/odd register numbering and assign to
216f4a2713aSLionel Sambuc /// VST4q8a or VST4q8b, but for the time being, the decoder chooses the "a"
217f4a2713aSLionel Sambuc /// version and return the Opcode since the two have the same Asm format string.
218f4a2713aSLionel Sambuc namespace {
219f4a2713aSLionel Sambuc class Filter {
220f4a2713aSLionel Sambuc protected:
221f4a2713aSLionel Sambuc   const FilterChooser *Owner;// points to the FilterChooser who owns this filter
222f4a2713aSLionel Sambuc   unsigned StartBit; // the starting bit position
223f4a2713aSLionel Sambuc   unsigned NumBits; // number of bits to filter
224f4a2713aSLionel Sambuc   bool Mixed; // a mixed region contains both set and unset bits
225f4a2713aSLionel Sambuc 
226f4a2713aSLionel Sambuc   // Map of well-known segment value to the set of uid's with that value.
227f4a2713aSLionel Sambuc   std::map<uint64_t, std::vector<unsigned> > FilteredInstructions;
228f4a2713aSLionel Sambuc 
229f4a2713aSLionel Sambuc   // Set of uid's with non-constant segment values.
230f4a2713aSLionel Sambuc   std::vector<unsigned> VariableInstructions;
231f4a2713aSLionel Sambuc 
232f4a2713aSLionel Sambuc   // Map of well-known segment value to its delegate.
233*0a6a1f1dSLionel Sambuc   std::map<unsigned, std::unique_ptr<const FilterChooser>> FilterChooserMap;
234f4a2713aSLionel Sambuc 
235f4a2713aSLionel Sambuc   // Number of instructions which fall under FilteredInstructions category.
236f4a2713aSLionel Sambuc   unsigned NumFiltered;
237f4a2713aSLionel Sambuc 
238f4a2713aSLionel Sambuc   // Keeps track of the last opcode in the filtered bucket.
239f4a2713aSLionel Sambuc   unsigned LastOpcFiltered;
240f4a2713aSLionel Sambuc 
241f4a2713aSLionel Sambuc public:
getNumFiltered() const242f4a2713aSLionel Sambuc   unsigned getNumFiltered() const { return NumFiltered; }
getSingletonOpc() const243f4a2713aSLionel Sambuc   unsigned getSingletonOpc() const {
244f4a2713aSLionel Sambuc     assert(NumFiltered == 1);
245f4a2713aSLionel Sambuc     return LastOpcFiltered;
246f4a2713aSLionel Sambuc   }
247f4a2713aSLionel Sambuc   // Return the filter chooser for the group of instructions without constant
248f4a2713aSLionel Sambuc   // segment values.
getVariableFC() const249f4a2713aSLionel Sambuc   const FilterChooser &getVariableFC() const {
250f4a2713aSLionel Sambuc     assert(NumFiltered == 1);
251f4a2713aSLionel Sambuc     assert(FilterChooserMap.size() == 1);
252f4a2713aSLionel Sambuc     return *(FilterChooserMap.find((unsigned)-1)->second);
253f4a2713aSLionel Sambuc   }
254f4a2713aSLionel Sambuc 
255*0a6a1f1dSLionel Sambuc   Filter(Filter &&f);
256f4a2713aSLionel Sambuc   Filter(FilterChooser &owner, unsigned startBit, unsigned numBits, bool mixed);
257f4a2713aSLionel Sambuc 
258f4a2713aSLionel Sambuc   ~Filter();
259f4a2713aSLionel Sambuc 
260f4a2713aSLionel Sambuc   // Divides the decoding task into sub tasks and delegates them to the
261f4a2713aSLionel Sambuc   // inferior FilterChooser's.
262f4a2713aSLionel Sambuc   //
263f4a2713aSLionel Sambuc   // A special case arises when there's only one entry in the filtered
264f4a2713aSLionel Sambuc   // instructions.  In order to unambiguously decode the singleton, we need to
265f4a2713aSLionel Sambuc   // match the remaining undecoded encoding bits against the singleton.
266f4a2713aSLionel Sambuc   void recurse();
267f4a2713aSLionel Sambuc 
268f4a2713aSLionel Sambuc   // Emit table entries to decode instructions given a segment or segments of
269f4a2713aSLionel Sambuc   // bits.
270f4a2713aSLionel Sambuc   void emitTableEntry(DecoderTableInfo &TableInfo) const;
271f4a2713aSLionel Sambuc 
272f4a2713aSLionel Sambuc   // Returns the number of fanout produced by the filter.  More fanout implies
273f4a2713aSLionel Sambuc   // the filter distinguishes more categories of instructions.
274f4a2713aSLionel Sambuc   unsigned usefulness() const;
275f4a2713aSLionel Sambuc }; // End of class Filter
276f4a2713aSLionel Sambuc } // End anonymous namespace
277f4a2713aSLionel Sambuc 
278f4a2713aSLionel Sambuc // These are states of our finite state machines used in FilterChooser's
279f4a2713aSLionel Sambuc // filterProcessor() which produces the filter candidates to use.
280f4a2713aSLionel Sambuc typedef enum {
281f4a2713aSLionel Sambuc   ATTR_NONE,
282f4a2713aSLionel Sambuc   ATTR_FILTERED,
283f4a2713aSLionel Sambuc   ATTR_ALL_SET,
284f4a2713aSLionel Sambuc   ATTR_ALL_UNSET,
285f4a2713aSLionel Sambuc   ATTR_MIXED
286f4a2713aSLionel Sambuc } bitAttr_t;
287f4a2713aSLionel Sambuc 
288f4a2713aSLionel Sambuc /// FilterChooser - FilterChooser chooses the best filter among a set of Filters
289f4a2713aSLionel Sambuc /// in order to perform the decoding of instructions at the current level.
290f4a2713aSLionel Sambuc ///
291f4a2713aSLionel Sambuc /// Decoding proceeds from the top down.  Based on the well-known encoding bits
292f4a2713aSLionel Sambuc /// of instructions available, FilterChooser builds up the possible Filters that
293f4a2713aSLionel Sambuc /// can further the task of decoding by distinguishing among the remaining
294f4a2713aSLionel Sambuc /// candidate instructions.
295f4a2713aSLionel Sambuc ///
296f4a2713aSLionel Sambuc /// Once a filter has been chosen, it is called upon to divide the decoding task
297f4a2713aSLionel Sambuc /// into sub-tasks and delegates them to its inferior FilterChoosers for further
298f4a2713aSLionel Sambuc /// processings.
299f4a2713aSLionel Sambuc ///
300f4a2713aSLionel Sambuc /// It is useful to think of a Filter as governing the switch stmts of the
301f4a2713aSLionel Sambuc /// decoding tree.  And each case is delegated to an inferior FilterChooser to
302f4a2713aSLionel Sambuc /// decide what further remaining bits to look at.
303f4a2713aSLionel Sambuc namespace {
304f4a2713aSLionel Sambuc class FilterChooser {
305f4a2713aSLionel Sambuc protected:
306f4a2713aSLionel Sambuc   friend class Filter;
307f4a2713aSLionel Sambuc 
308f4a2713aSLionel Sambuc   // Vector of codegen instructions to choose our filter.
309f4a2713aSLionel Sambuc   const std::vector<const CodeGenInstruction*> &AllInstructions;
310f4a2713aSLionel Sambuc 
311f4a2713aSLionel Sambuc   // Vector of uid's for this filter chooser to work on.
312f4a2713aSLionel Sambuc   const std::vector<unsigned> &Opcodes;
313f4a2713aSLionel Sambuc 
314f4a2713aSLionel Sambuc   // Lookup table for the operand decoding of instructions.
315f4a2713aSLionel Sambuc   const std::map<unsigned, std::vector<OperandInfo> > &Operands;
316f4a2713aSLionel Sambuc 
317f4a2713aSLionel Sambuc   // Vector of candidate filters.
318f4a2713aSLionel Sambuc   std::vector<Filter> Filters;
319f4a2713aSLionel Sambuc 
320f4a2713aSLionel Sambuc   // Array of bit values passed down from our parent.
321f4a2713aSLionel Sambuc   // Set to all BIT_UNFILTERED's for Parent == NULL.
322f4a2713aSLionel Sambuc   std::vector<bit_value_t> FilterBitValues;
323f4a2713aSLionel Sambuc 
324f4a2713aSLionel Sambuc   // Links to the FilterChooser above us in the decoding tree.
325f4a2713aSLionel Sambuc   const FilterChooser *Parent;
326f4a2713aSLionel Sambuc 
327f4a2713aSLionel Sambuc   // Index of the best filter from Filters.
328f4a2713aSLionel Sambuc   int BestIndex;
329f4a2713aSLionel Sambuc 
330f4a2713aSLionel Sambuc   // Width of instructions
331f4a2713aSLionel Sambuc   unsigned BitWidth;
332f4a2713aSLionel Sambuc 
333f4a2713aSLionel Sambuc   // Parent emitter
334f4a2713aSLionel Sambuc   const FixedLenDecoderEmitter *Emitter;
335f4a2713aSLionel Sambuc 
336*0a6a1f1dSLionel Sambuc   FilterChooser(const FilterChooser &) LLVM_DELETED_FUNCTION;
337*0a6a1f1dSLionel Sambuc   void operator=(const FilterChooser &) LLVM_DELETED_FUNCTION;
338f4a2713aSLionel Sambuc public:
339f4a2713aSLionel Sambuc 
FilterChooser(const std::vector<const CodeGenInstruction * > & Insts,const std::vector<unsigned> & IDs,const std::map<unsigned,std::vector<OperandInfo>> & Ops,unsigned BW,const FixedLenDecoderEmitter * E)340f4a2713aSLionel Sambuc   FilterChooser(const std::vector<const CodeGenInstruction*> &Insts,
341f4a2713aSLionel Sambuc                 const std::vector<unsigned> &IDs,
342f4a2713aSLionel Sambuc                 const std::map<unsigned, std::vector<OperandInfo> > &Ops,
343f4a2713aSLionel Sambuc                 unsigned BW,
344f4a2713aSLionel Sambuc                 const FixedLenDecoderEmitter *E)
345f4a2713aSLionel Sambuc     : AllInstructions(Insts), Opcodes(IDs), Operands(Ops), Filters(),
346*0a6a1f1dSLionel Sambuc       FilterBitValues(BW, BIT_UNFILTERED), Parent(nullptr), BestIndex(-1),
347*0a6a1f1dSLionel Sambuc       BitWidth(BW), Emitter(E) {
348f4a2713aSLionel Sambuc     doFilter();
349f4a2713aSLionel Sambuc   }
350f4a2713aSLionel Sambuc 
FilterChooser(const std::vector<const CodeGenInstruction * > & Insts,const std::vector<unsigned> & IDs,const std::map<unsigned,std::vector<OperandInfo>> & Ops,const std::vector<bit_value_t> & ParentFilterBitValues,const FilterChooser & parent)351f4a2713aSLionel Sambuc   FilterChooser(const std::vector<const CodeGenInstruction*> &Insts,
352f4a2713aSLionel Sambuc                 const std::vector<unsigned> &IDs,
353f4a2713aSLionel Sambuc                 const std::map<unsigned, std::vector<OperandInfo> > &Ops,
354f4a2713aSLionel Sambuc                 const std::vector<bit_value_t> &ParentFilterBitValues,
355f4a2713aSLionel Sambuc                 const FilterChooser &parent)
356f4a2713aSLionel Sambuc     : AllInstructions(Insts), Opcodes(IDs), Operands(Ops),
357f4a2713aSLionel Sambuc       Filters(), FilterBitValues(ParentFilterBitValues),
358f4a2713aSLionel Sambuc       Parent(&parent), BestIndex(-1), BitWidth(parent.BitWidth),
359f4a2713aSLionel Sambuc       Emitter(parent.Emitter) {
360f4a2713aSLionel Sambuc     doFilter();
361f4a2713aSLionel Sambuc   }
362f4a2713aSLionel Sambuc 
getBitWidth() const363f4a2713aSLionel Sambuc   unsigned getBitWidth() const { return BitWidth; }
364f4a2713aSLionel Sambuc 
365f4a2713aSLionel Sambuc protected:
366f4a2713aSLionel Sambuc   // Populates the insn given the uid.
insnWithID(insn_t & Insn,unsigned Opcode) const367f4a2713aSLionel Sambuc   void insnWithID(insn_t &Insn, unsigned Opcode) const {
368f4a2713aSLionel Sambuc     BitsInit &Bits = getBitsField(*AllInstructions[Opcode]->TheDef, "Inst");
369f4a2713aSLionel Sambuc 
370f4a2713aSLionel Sambuc     // We may have a SoftFail bitmask, which specifies a mask where an encoding
371f4a2713aSLionel Sambuc     // may differ from the value in "Inst" and yet still be valid, but the
372f4a2713aSLionel Sambuc     // disassembler should return SoftFail instead of Success.
373f4a2713aSLionel Sambuc     //
374f4a2713aSLionel Sambuc     // This is used for marking UNPREDICTABLE instructions in the ARM world.
375f4a2713aSLionel Sambuc     BitsInit *SFBits =
376f4a2713aSLionel Sambuc       AllInstructions[Opcode]->TheDef->getValueAsBitsInit("SoftFail");
377f4a2713aSLionel Sambuc 
378f4a2713aSLionel Sambuc     for (unsigned i = 0; i < BitWidth; ++i) {
379f4a2713aSLionel Sambuc       if (SFBits && bitFromBits(*SFBits, i) == BIT_TRUE)
380f4a2713aSLionel Sambuc         Insn.push_back(BIT_UNSET);
381f4a2713aSLionel Sambuc       else
382f4a2713aSLionel Sambuc         Insn.push_back(bitFromBits(Bits, i));
383f4a2713aSLionel Sambuc     }
384f4a2713aSLionel Sambuc   }
385f4a2713aSLionel Sambuc 
386f4a2713aSLionel Sambuc   // Returns the record name.
nameWithID(unsigned Opcode) const387f4a2713aSLionel Sambuc   const std::string &nameWithID(unsigned Opcode) const {
388f4a2713aSLionel Sambuc     return AllInstructions[Opcode]->TheDef->getName();
389f4a2713aSLionel Sambuc   }
390f4a2713aSLionel Sambuc 
391f4a2713aSLionel Sambuc   // Populates the field of the insn given the start position and the number of
392f4a2713aSLionel Sambuc   // consecutive bits to scan for.
393f4a2713aSLionel Sambuc   //
394f4a2713aSLionel Sambuc   // Returns false if there exists any uninitialized bit value in the range.
395f4a2713aSLionel Sambuc   // Returns true, otherwise.
396f4a2713aSLionel Sambuc   bool fieldFromInsn(uint64_t &Field, insn_t &Insn, unsigned StartBit,
397f4a2713aSLionel Sambuc                      unsigned NumBits) const;
398f4a2713aSLionel Sambuc 
399f4a2713aSLionel Sambuc   /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
400f4a2713aSLionel Sambuc   /// filter array as a series of chars.
401f4a2713aSLionel Sambuc   void dumpFilterArray(raw_ostream &o,
402f4a2713aSLionel Sambuc                        const std::vector<bit_value_t> & filter) const;
403f4a2713aSLionel Sambuc 
404f4a2713aSLionel Sambuc   /// dumpStack - dumpStack traverses the filter chooser chain and calls
405f4a2713aSLionel Sambuc   /// dumpFilterArray on each filter chooser up to the top level one.
406f4a2713aSLionel Sambuc   void dumpStack(raw_ostream &o, const char *prefix) const;
407f4a2713aSLionel Sambuc 
bestFilter()408f4a2713aSLionel Sambuc   Filter &bestFilter() {
409f4a2713aSLionel Sambuc     assert(BestIndex != -1 && "BestIndex not set");
410f4a2713aSLionel Sambuc     return Filters[BestIndex];
411f4a2713aSLionel Sambuc   }
412f4a2713aSLionel Sambuc 
413f4a2713aSLionel Sambuc   // Called from Filter::recurse() when singleton exists.  For debug purpose.
414f4a2713aSLionel Sambuc   void SingletonExists(unsigned Opc) const;
415f4a2713aSLionel Sambuc 
PositionFiltered(unsigned i) const416f4a2713aSLionel Sambuc   bool PositionFiltered(unsigned i) const {
417f4a2713aSLionel Sambuc     return ValueSet(FilterBitValues[i]);
418f4a2713aSLionel Sambuc   }
419f4a2713aSLionel Sambuc 
420f4a2713aSLionel Sambuc   // Calculates the island(s) needed to decode the instruction.
421f4a2713aSLionel Sambuc   // This returns a lit of undecoded bits of an instructions, for example,
422f4a2713aSLionel Sambuc   // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
423f4a2713aSLionel Sambuc   // decoded bits in order to verify that the instruction matches the Opcode.
424f4a2713aSLionel Sambuc   unsigned getIslands(std::vector<unsigned> &StartBits,
425f4a2713aSLionel Sambuc                       std::vector<unsigned> &EndBits,
426f4a2713aSLionel Sambuc                       std::vector<uint64_t> &FieldVals,
427f4a2713aSLionel Sambuc                       const insn_t &Insn) const;
428f4a2713aSLionel Sambuc 
429f4a2713aSLionel Sambuc   // Emits code to check the Predicates member of an instruction are true.
430f4a2713aSLionel Sambuc   // Returns true if predicate matches were emitted, false otherwise.
431f4a2713aSLionel Sambuc   bool emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
432f4a2713aSLionel Sambuc                           unsigned Opc) const;
433f4a2713aSLionel Sambuc 
434f4a2713aSLionel Sambuc   bool doesOpcodeNeedPredicate(unsigned Opc) const;
435f4a2713aSLionel Sambuc   unsigned getPredicateIndex(DecoderTableInfo &TableInfo, StringRef P) const;
436f4a2713aSLionel Sambuc   void emitPredicateTableEntry(DecoderTableInfo &TableInfo,
437f4a2713aSLionel Sambuc                                unsigned Opc) const;
438f4a2713aSLionel Sambuc 
439f4a2713aSLionel Sambuc   void emitSoftFailTableEntry(DecoderTableInfo &TableInfo,
440f4a2713aSLionel Sambuc                               unsigned Opc) const;
441f4a2713aSLionel Sambuc 
442f4a2713aSLionel Sambuc   // Emits table entries to decode the singleton.
443f4a2713aSLionel Sambuc   void emitSingletonTableEntry(DecoderTableInfo &TableInfo,
444f4a2713aSLionel Sambuc                                unsigned Opc) const;
445f4a2713aSLionel Sambuc 
446f4a2713aSLionel Sambuc   // Emits code to decode the singleton, and then to decode the rest.
447f4a2713aSLionel Sambuc   void emitSingletonTableEntry(DecoderTableInfo &TableInfo,
448f4a2713aSLionel Sambuc                                const Filter &Best) const;
449f4a2713aSLionel Sambuc 
450f4a2713aSLionel Sambuc   void emitBinaryParser(raw_ostream &o, unsigned &Indentation,
451f4a2713aSLionel Sambuc                         const OperandInfo &OpInfo) const;
452f4a2713aSLionel Sambuc 
453f4a2713aSLionel Sambuc   void emitDecoder(raw_ostream &OS, unsigned Indentation, unsigned Opc) const;
454f4a2713aSLionel Sambuc   unsigned getDecoderIndex(DecoderSet &Decoders, unsigned Opc) const;
455f4a2713aSLionel Sambuc 
456f4a2713aSLionel Sambuc   // Assign a single filter and run with it.
457f4a2713aSLionel Sambuc   void runSingleFilter(unsigned startBit, unsigned numBit, bool mixed);
458f4a2713aSLionel Sambuc 
459f4a2713aSLionel Sambuc   // reportRegion is a helper function for filterProcessor to mark a region as
460f4a2713aSLionel Sambuc   // eligible for use as a filter region.
461f4a2713aSLionel Sambuc   void reportRegion(bitAttr_t RA, unsigned StartBit, unsigned BitIndex,
462f4a2713aSLionel Sambuc                     bool AllowMixed);
463f4a2713aSLionel Sambuc 
464f4a2713aSLionel Sambuc   // FilterProcessor scans the well-known encoding bits of the instructions and
465f4a2713aSLionel Sambuc   // builds up a list of candidate filters.  It chooses the best filter and
466f4a2713aSLionel Sambuc   // recursively descends down the decoding tree.
467f4a2713aSLionel Sambuc   bool filterProcessor(bool AllowMixed, bool Greedy = true);
468f4a2713aSLionel Sambuc 
469f4a2713aSLionel Sambuc   // Decides on the best configuration of filter(s) to use in order to decode
470f4a2713aSLionel Sambuc   // the instructions.  A conflict of instructions may occur, in which case we
471f4a2713aSLionel Sambuc   // dump the conflict set to the standard error.
472f4a2713aSLionel Sambuc   void doFilter();
473f4a2713aSLionel Sambuc 
474f4a2713aSLionel Sambuc public:
475f4a2713aSLionel Sambuc   // emitTableEntries - Emit state machine entries to decode our share of
476f4a2713aSLionel Sambuc   // instructions.
477f4a2713aSLionel Sambuc   void emitTableEntries(DecoderTableInfo &TableInfo) const;
478f4a2713aSLionel Sambuc };
479f4a2713aSLionel Sambuc } // End anonymous namespace
480f4a2713aSLionel Sambuc 
481f4a2713aSLionel Sambuc ///////////////////////////
482f4a2713aSLionel Sambuc //                       //
483f4a2713aSLionel Sambuc // Filter Implementation //
484f4a2713aSLionel Sambuc //                       //
485f4a2713aSLionel Sambuc ///////////////////////////
486f4a2713aSLionel Sambuc 
Filter(Filter && f)487*0a6a1f1dSLionel Sambuc Filter::Filter(Filter &&f)
488f4a2713aSLionel Sambuc   : Owner(f.Owner), StartBit(f.StartBit), NumBits(f.NumBits), Mixed(f.Mixed),
489*0a6a1f1dSLionel Sambuc     FilteredInstructions(std::move(f.FilteredInstructions)),
490*0a6a1f1dSLionel Sambuc     VariableInstructions(std::move(f.VariableInstructions)),
491*0a6a1f1dSLionel Sambuc     FilterChooserMap(std::move(f.FilterChooserMap)), NumFiltered(f.NumFiltered),
492f4a2713aSLionel Sambuc     LastOpcFiltered(f.LastOpcFiltered) {
493f4a2713aSLionel Sambuc }
494f4a2713aSLionel Sambuc 
Filter(FilterChooser & owner,unsigned startBit,unsigned numBits,bool mixed)495f4a2713aSLionel Sambuc Filter::Filter(FilterChooser &owner, unsigned startBit, unsigned numBits,
496f4a2713aSLionel Sambuc                bool mixed)
497f4a2713aSLionel Sambuc   : Owner(&owner), StartBit(startBit), NumBits(numBits), Mixed(mixed) {
498f4a2713aSLionel Sambuc   assert(StartBit + NumBits - 1 < Owner->BitWidth);
499f4a2713aSLionel Sambuc 
500f4a2713aSLionel Sambuc   NumFiltered = 0;
501f4a2713aSLionel Sambuc   LastOpcFiltered = 0;
502f4a2713aSLionel Sambuc 
503f4a2713aSLionel Sambuc   for (unsigned i = 0, e = Owner->Opcodes.size(); i != e; ++i) {
504f4a2713aSLionel Sambuc     insn_t Insn;
505f4a2713aSLionel Sambuc 
506f4a2713aSLionel Sambuc     // Populates the insn given the uid.
507f4a2713aSLionel Sambuc     Owner->insnWithID(Insn, Owner->Opcodes[i]);
508f4a2713aSLionel Sambuc 
509f4a2713aSLionel Sambuc     uint64_t Field;
510f4a2713aSLionel Sambuc     // Scans the segment for possibly well-specified encoding bits.
511f4a2713aSLionel Sambuc     bool ok = Owner->fieldFromInsn(Field, Insn, StartBit, NumBits);
512f4a2713aSLionel Sambuc 
513f4a2713aSLionel Sambuc     if (ok) {
514f4a2713aSLionel Sambuc       // The encoding bits are well-known.  Lets add the uid of the
515f4a2713aSLionel Sambuc       // instruction into the bucket keyed off the constant field value.
516f4a2713aSLionel Sambuc       LastOpcFiltered = Owner->Opcodes[i];
517f4a2713aSLionel Sambuc       FilteredInstructions[Field].push_back(LastOpcFiltered);
518f4a2713aSLionel Sambuc       ++NumFiltered;
519f4a2713aSLionel Sambuc     } else {
520f4a2713aSLionel Sambuc       // Some of the encoding bit(s) are unspecified.  This contributes to
521f4a2713aSLionel Sambuc       // one additional member of "Variable" instructions.
522f4a2713aSLionel Sambuc       VariableInstructions.push_back(Owner->Opcodes[i]);
523f4a2713aSLionel Sambuc     }
524f4a2713aSLionel Sambuc   }
525f4a2713aSLionel Sambuc 
526f4a2713aSLionel Sambuc   assert((FilteredInstructions.size() + VariableInstructions.size() > 0)
527f4a2713aSLionel Sambuc          && "Filter returns no instruction categories");
528f4a2713aSLionel Sambuc }
529f4a2713aSLionel Sambuc 
~Filter()530f4a2713aSLionel Sambuc Filter::~Filter() {
531f4a2713aSLionel Sambuc }
532f4a2713aSLionel Sambuc 
533f4a2713aSLionel Sambuc // Divides the decoding task into sub tasks and delegates them to the
534f4a2713aSLionel Sambuc // inferior FilterChooser's.
535f4a2713aSLionel Sambuc //
536f4a2713aSLionel Sambuc // A special case arises when there's only one entry in the filtered
537f4a2713aSLionel Sambuc // instructions.  In order to unambiguously decode the singleton, we need to
538f4a2713aSLionel Sambuc // match the remaining undecoded encoding bits against the singleton.
recurse()539f4a2713aSLionel Sambuc void Filter::recurse() {
540f4a2713aSLionel Sambuc   // Starts by inheriting our parent filter chooser's filter bit values.
541f4a2713aSLionel Sambuc   std::vector<bit_value_t> BitValueArray(Owner->FilterBitValues);
542f4a2713aSLionel Sambuc 
543f4a2713aSLionel Sambuc   if (VariableInstructions.size()) {
544f4a2713aSLionel Sambuc     // Conservatively marks each segment position as BIT_UNSET.
545f4a2713aSLionel Sambuc     for (unsigned bitIndex = 0; bitIndex < NumBits; ++bitIndex)
546f4a2713aSLionel Sambuc       BitValueArray[StartBit + bitIndex] = BIT_UNSET;
547f4a2713aSLionel Sambuc 
548f4a2713aSLionel Sambuc     // Delegates to an inferior filter chooser for further processing on this
549f4a2713aSLionel Sambuc     // group of instructions whose segment values are variable.
550*0a6a1f1dSLionel Sambuc     FilterChooserMap.insert(
551*0a6a1f1dSLionel Sambuc         std::make_pair(-1U, llvm::make_unique<FilterChooser>(
552*0a6a1f1dSLionel Sambuc                                 Owner->AllInstructions, VariableInstructions,
553*0a6a1f1dSLionel Sambuc                                 Owner->Operands, BitValueArray, *Owner)));
554f4a2713aSLionel Sambuc   }
555f4a2713aSLionel Sambuc 
556f4a2713aSLionel Sambuc   // No need to recurse for a singleton filtered instruction.
557f4a2713aSLionel Sambuc   // See also Filter::emit*().
558f4a2713aSLionel Sambuc   if (getNumFiltered() == 1) {
559f4a2713aSLionel Sambuc     //Owner->SingletonExists(LastOpcFiltered);
560f4a2713aSLionel Sambuc     assert(FilterChooserMap.size() == 1);
561f4a2713aSLionel Sambuc     return;
562f4a2713aSLionel Sambuc   }
563f4a2713aSLionel Sambuc 
564f4a2713aSLionel Sambuc   // Otherwise, create sub choosers.
565*0a6a1f1dSLionel Sambuc   for (const auto &Inst : FilteredInstructions) {
566f4a2713aSLionel Sambuc 
567f4a2713aSLionel Sambuc     // Marks all the segment positions with either BIT_TRUE or BIT_FALSE.
568f4a2713aSLionel Sambuc     for (unsigned bitIndex = 0; bitIndex < NumBits; ++bitIndex) {
569*0a6a1f1dSLionel Sambuc       if (Inst.first & (1ULL << bitIndex))
570f4a2713aSLionel Sambuc         BitValueArray[StartBit + bitIndex] = BIT_TRUE;
571f4a2713aSLionel Sambuc       else
572f4a2713aSLionel Sambuc         BitValueArray[StartBit + bitIndex] = BIT_FALSE;
573f4a2713aSLionel Sambuc     }
574f4a2713aSLionel Sambuc 
575f4a2713aSLionel Sambuc     // Delegates to an inferior filter chooser for further processing on this
576f4a2713aSLionel Sambuc     // category of instructions.
577*0a6a1f1dSLionel Sambuc     FilterChooserMap.insert(std::make_pair(
578*0a6a1f1dSLionel Sambuc         Inst.first, llvm::make_unique<FilterChooser>(
579*0a6a1f1dSLionel Sambuc                                 Owner->AllInstructions, Inst.second,
580*0a6a1f1dSLionel Sambuc                                 Owner->Operands, BitValueArray, *Owner)));
581f4a2713aSLionel Sambuc   }
582f4a2713aSLionel Sambuc }
583f4a2713aSLionel Sambuc 
resolveTableFixups(DecoderTable & Table,const FixupList & Fixups,uint32_t DestIdx)584f4a2713aSLionel Sambuc static void resolveTableFixups(DecoderTable &Table, const FixupList &Fixups,
585f4a2713aSLionel Sambuc                                uint32_t DestIdx) {
586f4a2713aSLionel Sambuc   // Any NumToSkip fixups in the current scope can resolve to the
587f4a2713aSLionel Sambuc   // current location.
588f4a2713aSLionel Sambuc   for (FixupList::const_reverse_iterator I = Fixups.rbegin(),
589f4a2713aSLionel Sambuc                                          E = Fixups.rend();
590f4a2713aSLionel Sambuc        I != E; ++I) {
591f4a2713aSLionel Sambuc     // Calculate the distance from the byte following the fixup entry byte
592f4a2713aSLionel Sambuc     // to the destination. The Target is calculated from after the 16-bit
593f4a2713aSLionel Sambuc     // NumToSkip entry itself, so subtract two  from the displacement here
594f4a2713aSLionel Sambuc     // to account for that.
595f4a2713aSLionel Sambuc     uint32_t FixupIdx = *I;
596f4a2713aSLionel Sambuc     uint32_t Delta = DestIdx - FixupIdx - 2;
597f4a2713aSLionel Sambuc     // Our NumToSkip entries are 16-bits. Make sure our table isn't too
598f4a2713aSLionel Sambuc     // big.
599f4a2713aSLionel Sambuc     assert(Delta < 65536U && "disassembler decoding table too large!");
600f4a2713aSLionel Sambuc     Table[FixupIdx] = (uint8_t)Delta;
601f4a2713aSLionel Sambuc     Table[FixupIdx + 1] = (uint8_t)(Delta >> 8);
602f4a2713aSLionel Sambuc   }
603f4a2713aSLionel Sambuc }
604f4a2713aSLionel Sambuc 
605f4a2713aSLionel Sambuc // Emit table entries to decode instructions given a segment or segments
606f4a2713aSLionel Sambuc // of bits.
emitTableEntry(DecoderTableInfo & TableInfo) const607f4a2713aSLionel Sambuc void Filter::emitTableEntry(DecoderTableInfo &TableInfo) const {
608f4a2713aSLionel Sambuc   TableInfo.Table.push_back(MCD::OPC_ExtractField);
609f4a2713aSLionel Sambuc   TableInfo.Table.push_back(StartBit);
610f4a2713aSLionel Sambuc   TableInfo.Table.push_back(NumBits);
611f4a2713aSLionel Sambuc 
612f4a2713aSLionel Sambuc   // A new filter entry begins a new scope for fixup resolution.
613f4a2713aSLionel Sambuc   TableInfo.FixupStack.push_back(FixupList());
614f4a2713aSLionel Sambuc 
615f4a2713aSLionel Sambuc   DecoderTable &Table = TableInfo.Table;
616f4a2713aSLionel Sambuc 
617f4a2713aSLionel Sambuc   size_t PrevFilter = 0;
618f4a2713aSLionel Sambuc   bool HasFallthrough = false;
619*0a6a1f1dSLionel Sambuc   for (auto &Filter : FilterChooserMap) {
620f4a2713aSLionel Sambuc     // Field value -1 implies a non-empty set of variable instructions.
621f4a2713aSLionel Sambuc     // See also recurse().
622*0a6a1f1dSLionel Sambuc     if (Filter.first == (unsigned)-1) {
623f4a2713aSLionel Sambuc       HasFallthrough = true;
624f4a2713aSLionel Sambuc 
625f4a2713aSLionel Sambuc       // Each scope should always have at least one filter value to check
626f4a2713aSLionel Sambuc       // for.
627f4a2713aSLionel Sambuc       assert(PrevFilter != 0 && "empty filter set!");
628f4a2713aSLionel Sambuc       FixupList &CurScope = TableInfo.FixupStack.back();
629f4a2713aSLionel Sambuc       // Resolve any NumToSkip fixups in the current scope.
630f4a2713aSLionel Sambuc       resolveTableFixups(Table, CurScope, Table.size());
631f4a2713aSLionel Sambuc       CurScope.clear();
632f4a2713aSLionel Sambuc       PrevFilter = 0;  // Don't re-process the filter's fallthrough.
633f4a2713aSLionel Sambuc     } else {
634f4a2713aSLionel Sambuc       Table.push_back(MCD::OPC_FilterValue);
635f4a2713aSLionel Sambuc       // Encode and emit the value to filter against.
636f4a2713aSLionel Sambuc       uint8_t Buffer[8];
637*0a6a1f1dSLionel Sambuc       unsigned Len = encodeULEB128(Filter.first, Buffer);
638f4a2713aSLionel Sambuc       Table.insert(Table.end(), Buffer, Buffer + Len);
639f4a2713aSLionel Sambuc       // Reserve space for the NumToSkip entry. We'll backpatch the value
640f4a2713aSLionel Sambuc       // later.
641f4a2713aSLionel Sambuc       PrevFilter = Table.size();
642f4a2713aSLionel Sambuc       Table.push_back(0);
643f4a2713aSLionel Sambuc       Table.push_back(0);
644f4a2713aSLionel Sambuc     }
645f4a2713aSLionel Sambuc 
646f4a2713aSLionel Sambuc     // We arrive at a category of instructions with the same segment value.
647f4a2713aSLionel Sambuc     // Now delegate to the sub filter chooser for further decodings.
648f4a2713aSLionel Sambuc     // The case may fallthrough, which happens if the remaining well-known
649f4a2713aSLionel Sambuc     // encoding bits do not match exactly.
650*0a6a1f1dSLionel Sambuc     Filter.second->emitTableEntries(TableInfo);
651f4a2713aSLionel Sambuc 
652f4a2713aSLionel Sambuc     // Now that we've emitted the body of the handler, update the NumToSkip
653f4a2713aSLionel Sambuc     // of the filter itself to be able to skip forward when false. Subtract
654f4a2713aSLionel Sambuc     // two as to account for the width of the NumToSkip field itself.
655f4a2713aSLionel Sambuc     if (PrevFilter) {
656f4a2713aSLionel Sambuc       uint32_t NumToSkip = Table.size() - PrevFilter - 2;
657f4a2713aSLionel Sambuc       assert(NumToSkip < 65536U && "disassembler decoding table too large!");
658f4a2713aSLionel Sambuc       Table[PrevFilter] = (uint8_t)NumToSkip;
659f4a2713aSLionel Sambuc       Table[PrevFilter + 1] = (uint8_t)(NumToSkip >> 8);
660f4a2713aSLionel Sambuc     }
661f4a2713aSLionel Sambuc   }
662f4a2713aSLionel Sambuc 
663f4a2713aSLionel Sambuc   // Any remaining unresolved fixups bubble up to the parent fixup scope.
664f4a2713aSLionel Sambuc   assert(TableInfo.FixupStack.size() > 1 && "fixup stack underflow!");
665f4a2713aSLionel Sambuc   FixupScopeList::iterator Source = TableInfo.FixupStack.end() - 1;
666f4a2713aSLionel Sambuc   FixupScopeList::iterator Dest = Source - 1;
667f4a2713aSLionel Sambuc   Dest->insert(Dest->end(), Source->begin(), Source->end());
668f4a2713aSLionel Sambuc   TableInfo.FixupStack.pop_back();
669f4a2713aSLionel Sambuc 
670f4a2713aSLionel Sambuc   // If there is no fallthrough, then the final filter should get fixed
671f4a2713aSLionel Sambuc   // up according to the enclosing scope rather than the current position.
672f4a2713aSLionel Sambuc   if (!HasFallthrough)
673f4a2713aSLionel Sambuc     TableInfo.FixupStack.back().push_back(PrevFilter);
674f4a2713aSLionel Sambuc }
675f4a2713aSLionel Sambuc 
676f4a2713aSLionel Sambuc // Returns the number of fanout produced by the filter.  More fanout implies
677f4a2713aSLionel Sambuc // the filter distinguishes more categories of instructions.
usefulness() const678f4a2713aSLionel Sambuc unsigned Filter::usefulness() const {
679f4a2713aSLionel Sambuc   if (VariableInstructions.size())
680f4a2713aSLionel Sambuc     return FilteredInstructions.size();
681f4a2713aSLionel Sambuc   else
682f4a2713aSLionel Sambuc     return FilteredInstructions.size() + 1;
683f4a2713aSLionel Sambuc }
684f4a2713aSLionel Sambuc 
685f4a2713aSLionel Sambuc //////////////////////////////////
686f4a2713aSLionel Sambuc //                              //
687f4a2713aSLionel Sambuc // Filterchooser Implementation //
688f4a2713aSLionel Sambuc //                              //
689f4a2713aSLionel Sambuc //////////////////////////////////
690f4a2713aSLionel Sambuc 
691f4a2713aSLionel Sambuc // Emit the decoder state machine table.
emitTable(formatted_raw_ostream & OS,DecoderTable & Table,unsigned Indentation,unsigned BitWidth,StringRef Namespace) const692f4a2713aSLionel Sambuc void FixedLenDecoderEmitter::emitTable(formatted_raw_ostream &OS,
693f4a2713aSLionel Sambuc                                        DecoderTable &Table,
694f4a2713aSLionel Sambuc                                        unsigned Indentation,
695f4a2713aSLionel Sambuc                                        unsigned BitWidth,
696f4a2713aSLionel Sambuc                                        StringRef Namespace) const {
697f4a2713aSLionel Sambuc   OS.indent(Indentation) << "static const uint8_t DecoderTable" << Namespace
698f4a2713aSLionel Sambuc     << BitWidth << "[] = {\n";
699f4a2713aSLionel Sambuc 
700f4a2713aSLionel Sambuc   Indentation += 2;
701f4a2713aSLionel Sambuc 
702f4a2713aSLionel Sambuc   // FIXME: We may be able to use the NumToSkip values to recover
703f4a2713aSLionel Sambuc   // appropriate indentation levels.
704f4a2713aSLionel Sambuc   DecoderTable::const_iterator I = Table.begin();
705f4a2713aSLionel Sambuc   DecoderTable::const_iterator E = Table.end();
706f4a2713aSLionel Sambuc   while (I != E) {
707f4a2713aSLionel Sambuc     assert (I < E && "incomplete decode table entry!");
708f4a2713aSLionel Sambuc 
709f4a2713aSLionel Sambuc     uint64_t Pos = I - Table.begin();
710f4a2713aSLionel Sambuc     OS << "/* " << Pos << " */";
711f4a2713aSLionel Sambuc     OS.PadToColumn(12);
712f4a2713aSLionel Sambuc 
713f4a2713aSLionel Sambuc     switch (*I) {
714f4a2713aSLionel Sambuc     default:
715f4a2713aSLionel Sambuc       PrintFatalError("invalid decode table opcode");
716f4a2713aSLionel Sambuc     case MCD::OPC_ExtractField: {
717f4a2713aSLionel Sambuc       ++I;
718f4a2713aSLionel Sambuc       unsigned Start = *I++;
719f4a2713aSLionel Sambuc       unsigned Len = *I++;
720f4a2713aSLionel Sambuc       OS.indent(Indentation) << "MCD::OPC_ExtractField, " << Start << ", "
721f4a2713aSLionel Sambuc         << Len << ",  // Inst{";
722f4a2713aSLionel Sambuc       if (Len > 1)
723f4a2713aSLionel Sambuc         OS << (Start + Len - 1) << "-";
724f4a2713aSLionel Sambuc       OS << Start << "} ...\n";
725f4a2713aSLionel Sambuc       break;
726f4a2713aSLionel Sambuc     }
727f4a2713aSLionel Sambuc     case MCD::OPC_FilterValue: {
728f4a2713aSLionel Sambuc       ++I;
729f4a2713aSLionel Sambuc       OS.indent(Indentation) << "MCD::OPC_FilterValue, ";
730f4a2713aSLionel Sambuc       // The filter value is ULEB128 encoded.
731f4a2713aSLionel Sambuc       while (*I >= 128)
732f4a2713aSLionel Sambuc         OS << utostr(*I++) << ", ";
733f4a2713aSLionel Sambuc       OS << utostr(*I++) << ", ";
734f4a2713aSLionel Sambuc 
735f4a2713aSLionel Sambuc       // 16-bit numtoskip value.
736f4a2713aSLionel Sambuc       uint8_t Byte = *I++;
737f4a2713aSLionel Sambuc       uint32_t NumToSkip = Byte;
738f4a2713aSLionel Sambuc       OS << utostr(Byte) << ", ";
739f4a2713aSLionel Sambuc       Byte = *I++;
740f4a2713aSLionel Sambuc       OS << utostr(Byte) << ", ";
741f4a2713aSLionel Sambuc       NumToSkip |= Byte << 8;
742f4a2713aSLionel Sambuc       OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
743f4a2713aSLionel Sambuc       break;
744f4a2713aSLionel Sambuc     }
745f4a2713aSLionel Sambuc     case MCD::OPC_CheckField: {
746f4a2713aSLionel Sambuc       ++I;
747f4a2713aSLionel Sambuc       unsigned Start = *I++;
748f4a2713aSLionel Sambuc       unsigned Len = *I++;
749f4a2713aSLionel Sambuc       OS.indent(Indentation) << "MCD::OPC_CheckField, " << Start << ", "
750f4a2713aSLionel Sambuc         << Len << ", ";// << Val << ", " << NumToSkip << ",\n";
751f4a2713aSLionel Sambuc       // ULEB128 encoded field value.
752f4a2713aSLionel Sambuc       for (; *I >= 128; ++I)
753f4a2713aSLionel Sambuc         OS << utostr(*I) << ", ";
754f4a2713aSLionel Sambuc       OS << utostr(*I++) << ", ";
755f4a2713aSLionel Sambuc       // 16-bit numtoskip value.
756f4a2713aSLionel Sambuc       uint8_t Byte = *I++;
757f4a2713aSLionel Sambuc       uint32_t NumToSkip = Byte;
758f4a2713aSLionel Sambuc       OS << utostr(Byte) << ", ";
759f4a2713aSLionel Sambuc       Byte = *I++;
760f4a2713aSLionel Sambuc       OS << utostr(Byte) << ", ";
761f4a2713aSLionel Sambuc       NumToSkip |= Byte << 8;
762f4a2713aSLionel Sambuc       OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
763f4a2713aSLionel Sambuc       break;
764f4a2713aSLionel Sambuc     }
765f4a2713aSLionel Sambuc     case MCD::OPC_CheckPredicate: {
766f4a2713aSLionel Sambuc       ++I;
767f4a2713aSLionel Sambuc       OS.indent(Indentation) << "MCD::OPC_CheckPredicate, ";
768f4a2713aSLionel Sambuc       for (; *I >= 128; ++I)
769f4a2713aSLionel Sambuc         OS << utostr(*I) << ", ";
770f4a2713aSLionel Sambuc       OS << utostr(*I++) << ", ";
771f4a2713aSLionel Sambuc 
772f4a2713aSLionel Sambuc       // 16-bit numtoskip value.
773f4a2713aSLionel Sambuc       uint8_t Byte = *I++;
774f4a2713aSLionel Sambuc       uint32_t NumToSkip = Byte;
775f4a2713aSLionel Sambuc       OS << utostr(Byte) << ", ";
776f4a2713aSLionel Sambuc       Byte = *I++;
777f4a2713aSLionel Sambuc       OS << utostr(Byte) << ", ";
778f4a2713aSLionel Sambuc       NumToSkip |= Byte << 8;
779f4a2713aSLionel Sambuc       OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
780f4a2713aSLionel Sambuc       break;
781f4a2713aSLionel Sambuc     }
782f4a2713aSLionel Sambuc     case MCD::OPC_Decode: {
783f4a2713aSLionel Sambuc       ++I;
784f4a2713aSLionel Sambuc       // Extract the ULEB128 encoded Opcode to a buffer.
785f4a2713aSLionel Sambuc       uint8_t Buffer[8], *p = Buffer;
786f4a2713aSLionel Sambuc       while ((*p++ = *I++) >= 128)
787f4a2713aSLionel Sambuc         assert((p - Buffer) <= (ptrdiff_t)sizeof(Buffer)
788f4a2713aSLionel Sambuc                && "ULEB128 value too large!");
789f4a2713aSLionel Sambuc       // Decode the Opcode value.
790f4a2713aSLionel Sambuc       unsigned Opc = decodeULEB128(Buffer);
791f4a2713aSLionel Sambuc       OS.indent(Indentation) << "MCD::OPC_Decode, ";
792f4a2713aSLionel Sambuc       for (p = Buffer; *p >= 128; ++p)
793f4a2713aSLionel Sambuc         OS << utostr(*p) << ", ";
794f4a2713aSLionel Sambuc       OS << utostr(*p) << ", ";
795f4a2713aSLionel Sambuc 
796f4a2713aSLionel Sambuc       // Decoder index.
797f4a2713aSLionel Sambuc       for (; *I >= 128; ++I)
798f4a2713aSLionel Sambuc         OS << utostr(*I) << ", ";
799f4a2713aSLionel Sambuc       OS << utostr(*I++) << ", ";
800f4a2713aSLionel Sambuc 
801f4a2713aSLionel Sambuc       OS << "// Opcode: "
802f4a2713aSLionel Sambuc          << NumberedInstructions->at(Opc)->TheDef->getName() << "\n";
803f4a2713aSLionel Sambuc       break;
804f4a2713aSLionel Sambuc     }
805f4a2713aSLionel Sambuc     case MCD::OPC_SoftFail: {
806f4a2713aSLionel Sambuc       ++I;
807f4a2713aSLionel Sambuc       OS.indent(Indentation) << "MCD::OPC_SoftFail";
808f4a2713aSLionel Sambuc       // Positive mask
809f4a2713aSLionel Sambuc       uint64_t Value = 0;
810f4a2713aSLionel Sambuc       unsigned Shift = 0;
811f4a2713aSLionel Sambuc       do {
812f4a2713aSLionel Sambuc         OS << ", " << utostr(*I);
813f4a2713aSLionel Sambuc         Value += (*I & 0x7f) << Shift;
814f4a2713aSLionel Sambuc         Shift += 7;
815f4a2713aSLionel Sambuc       } while (*I++ >= 128);
816f4a2713aSLionel Sambuc       if (Value > 127)
817f4a2713aSLionel Sambuc         OS << " /* 0x" << utohexstr(Value) << " */";
818f4a2713aSLionel Sambuc       // Negative mask
819f4a2713aSLionel Sambuc       Value = 0;
820f4a2713aSLionel Sambuc       Shift = 0;
821f4a2713aSLionel Sambuc       do {
822f4a2713aSLionel Sambuc         OS << ", " << utostr(*I);
823f4a2713aSLionel Sambuc         Value += (*I & 0x7f) << Shift;
824f4a2713aSLionel Sambuc         Shift += 7;
825f4a2713aSLionel Sambuc       } while (*I++ >= 128);
826f4a2713aSLionel Sambuc       if (Value > 127)
827f4a2713aSLionel Sambuc         OS << " /* 0x" << utohexstr(Value) << " */";
828f4a2713aSLionel Sambuc       OS << ",\n";
829f4a2713aSLionel Sambuc       break;
830f4a2713aSLionel Sambuc     }
831f4a2713aSLionel Sambuc     case MCD::OPC_Fail: {
832f4a2713aSLionel Sambuc       ++I;
833f4a2713aSLionel Sambuc       OS.indent(Indentation) << "MCD::OPC_Fail,\n";
834f4a2713aSLionel Sambuc       break;
835f4a2713aSLionel Sambuc     }
836f4a2713aSLionel Sambuc     }
837f4a2713aSLionel Sambuc   }
838f4a2713aSLionel Sambuc   OS.indent(Indentation) << "0\n";
839f4a2713aSLionel Sambuc 
840f4a2713aSLionel Sambuc   Indentation -= 2;
841f4a2713aSLionel Sambuc 
842f4a2713aSLionel Sambuc   OS.indent(Indentation) << "};\n\n";
843f4a2713aSLionel Sambuc }
844f4a2713aSLionel Sambuc 
845f4a2713aSLionel Sambuc void FixedLenDecoderEmitter::
emitPredicateFunction(formatted_raw_ostream & OS,PredicateSet & Predicates,unsigned Indentation) const846f4a2713aSLionel Sambuc emitPredicateFunction(formatted_raw_ostream &OS, PredicateSet &Predicates,
847f4a2713aSLionel Sambuc                       unsigned Indentation) const {
848f4a2713aSLionel Sambuc   // The predicate function is just a big switch statement based on the
849f4a2713aSLionel Sambuc   // input predicate index.
850f4a2713aSLionel Sambuc   OS.indent(Indentation) << "static bool checkDecoderPredicate(unsigned Idx, "
851f4a2713aSLionel Sambuc     << "uint64_t Bits) {\n";
852f4a2713aSLionel Sambuc   Indentation += 2;
853f4a2713aSLionel Sambuc   if (!Predicates.empty()) {
854f4a2713aSLionel Sambuc     OS.indent(Indentation) << "switch (Idx) {\n";
855f4a2713aSLionel Sambuc     OS.indent(Indentation) << "default: llvm_unreachable(\"Invalid index!\");\n";
856f4a2713aSLionel Sambuc     unsigned Index = 0;
857*0a6a1f1dSLionel Sambuc     for (const auto &Predicate : Predicates) {
858*0a6a1f1dSLionel Sambuc       OS.indent(Indentation) << "case " << Index++ << ":\n";
859*0a6a1f1dSLionel Sambuc       OS.indent(Indentation+2) << "return (" << Predicate << ");\n";
860f4a2713aSLionel Sambuc     }
861f4a2713aSLionel Sambuc     OS.indent(Indentation) << "}\n";
862f4a2713aSLionel Sambuc   } else {
863f4a2713aSLionel Sambuc     // No case statement to emit
864f4a2713aSLionel Sambuc     OS.indent(Indentation) << "llvm_unreachable(\"Invalid index!\");\n";
865f4a2713aSLionel Sambuc   }
866f4a2713aSLionel Sambuc   Indentation -= 2;
867f4a2713aSLionel Sambuc   OS.indent(Indentation) << "}\n\n";
868f4a2713aSLionel Sambuc }
869f4a2713aSLionel Sambuc 
870f4a2713aSLionel Sambuc void FixedLenDecoderEmitter::
emitDecoderFunction(formatted_raw_ostream & OS,DecoderSet & Decoders,unsigned Indentation) const871f4a2713aSLionel Sambuc emitDecoderFunction(formatted_raw_ostream &OS, DecoderSet &Decoders,
872f4a2713aSLionel Sambuc                     unsigned Indentation) const {
873f4a2713aSLionel Sambuc   // The decoder function is just a big switch statement based on the
874f4a2713aSLionel Sambuc   // input decoder index.
875f4a2713aSLionel Sambuc   OS.indent(Indentation) << "template<typename InsnType>\n";
876f4a2713aSLionel Sambuc   OS.indent(Indentation) << "static DecodeStatus decodeToMCInst(DecodeStatus S,"
877f4a2713aSLionel Sambuc     << " unsigned Idx, InsnType insn, MCInst &MI,\n";
878f4a2713aSLionel Sambuc   OS.indent(Indentation) << "                                   uint64_t "
879f4a2713aSLionel Sambuc     << "Address, const void *Decoder) {\n";
880f4a2713aSLionel Sambuc   Indentation += 2;
881f4a2713aSLionel Sambuc   OS.indent(Indentation) << "InsnType tmp;\n";
882f4a2713aSLionel Sambuc   OS.indent(Indentation) << "switch (Idx) {\n";
883f4a2713aSLionel Sambuc   OS.indent(Indentation) << "default: llvm_unreachable(\"Invalid index!\");\n";
884f4a2713aSLionel Sambuc   unsigned Index = 0;
885*0a6a1f1dSLionel Sambuc   for (const auto &Decoder : Decoders) {
886*0a6a1f1dSLionel Sambuc     OS.indent(Indentation) << "case " << Index++ << ":\n";
887*0a6a1f1dSLionel Sambuc     OS << Decoder;
888f4a2713aSLionel Sambuc     OS.indent(Indentation+2) << "return S;\n";
889f4a2713aSLionel Sambuc   }
890f4a2713aSLionel Sambuc   OS.indent(Indentation) << "}\n";
891f4a2713aSLionel Sambuc   Indentation -= 2;
892f4a2713aSLionel Sambuc   OS.indent(Indentation) << "}\n\n";
893f4a2713aSLionel Sambuc }
894f4a2713aSLionel Sambuc 
895f4a2713aSLionel Sambuc // Populates the field of the insn given the start position and the number of
896f4a2713aSLionel Sambuc // consecutive bits to scan for.
897f4a2713aSLionel Sambuc //
898f4a2713aSLionel Sambuc // Returns false if and on the first uninitialized bit value encountered.
899f4a2713aSLionel Sambuc // Returns true, otherwise.
fieldFromInsn(uint64_t & Field,insn_t & Insn,unsigned StartBit,unsigned NumBits) const900f4a2713aSLionel Sambuc bool FilterChooser::fieldFromInsn(uint64_t &Field, insn_t &Insn,
901f4a2713aSLionel Sambuc                                   unsigned StartBit, unsigned NumBits) const {
902f4a2713aSLionel Sambuc   Field = 0;
903f4a2713aSLionel Sambuc 
904f4a2713aSLionel Sambuc   for (unsigned i = 0; i < NumBits; ++i) {
905f4a2713aSLionel Sambuc     if (Insn[StartBit + i] == BIT_UNSET)
906f4a2713aSLionel Sambuc       return false;
907f4a2713aSLionel Sambuc 
908f4a2713aSLionel Sambuc     if (Insn[StartBit + i] == BIT_TRUE)
909f4a2713aSLionel Sambuc       Field = Field | (1ULL << i);
910f4a2713aSLionel Sambuc   }
911f4a2713aSLionel Sambuc 
912f4a2713aSLionel Sambuc   return true;
913f4a2713aSLionel Sambuc }
914f4a2713aSLionel Sambuc 
915f4a2713aSLionel Sambuc /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
916f4a2713aSLionel Sambuc /// filter array as a series of chars.
dumpFilterArray(raw_ostream & o,const std::vector<bit_value_t> & filter) const917f4a2713aSLionel Sambuc void FilterChooser::dumpFilterArray(raw_ostream &o,
918f4a2713aSLionel Sambuc                                  const std::vector<bit_value_t> &filter) const {
919f4a2713aSLionel Sambuc   for (unsigned bitIndex = BitWidth; bitIndex > 0; bitIndex--) {
920f4a2713aSLionel Sambuc     switch (filter[bitIndex - 1]) {
921f4a2713aSLionel Sambuc     case BIT_UNFILTERED:
922f4a2713aSLionel Sambuc       o << ".";
923f4a2713aSLionel Sambuc       break;
924f4a2713aSLionel Sambuc     case BIT_UNSET:
925f4a2713aSLionel Sambuc       o << "_";
926f4a2713aSLionel Sambuc       break;
927f4a2713aSLionel Sambuc     case BIT_TRUE:
928f4a2713aSLionel Sambuc       o << "1";
929f4a2713aSLionel Sambuc       break;
930f4a2713aSLionel Sambuc     case BIT_FALSE:
931f4a2713aSLionel Sambuc       o << "0";
932f4a2713aSLionel Sambuc       break;
933f4a2713aSLionel Sambuc     }
934f4a2713aSLionel Sambuc   }
935f4a2713aSLionel Sambuc }
936f4a2713aSLionel Sambuc 
937f4a2713aSLionel Sambuc /// dumpStack - dumpStack traverses the filter chooser chain and calls
938f4a2713aSLionel Sambuc /// dumpFilterArray on each filter chooser up to the top level one.
dumpStack(raw_ostream & o,const char * prefix) const939f4a2713aSLionel Sambuc void FilterChooser::dumpStack(raw_ostream &o, const char *prefix) const {
940f4a2713aSLionel Sambuc   const FilterChooser *current = this;
941f4a2713aSLionel Sambuc 
942f4a2713aSLionel Sambuc   while (current) {
943f4a2713aSLionel Sambuc     o << prefix;
944f4a2713aSLionel Sambuc     dumpFilterArray(o, current->FilterBitValues);
945f4a2713aSLionel Sambuc     o << '\n';
946f4a2713aSLionel Sambuc     current = current->Parent;
947f4a2713aSLionel Sambuc   }
948f4a2713aSLionel Sambuc }
949f4a2713aSLionel Sambuc 
950f4a2713aSLionel Sambuc // Called from Filter::recurse() when singleton exists.  For debug purpose.
SingletonExists(unsigned Opc) const951f4a2713aSLionel Sambuc void FilterChooser::SingletonExists(unsigned Opc) const {
952f4a2713aSLionel Sambuc   insn_t Insn0;
953f4a2713aSLionel Sambuc   insnWithID(Insn0, Opc);
954f4a2713aSLionel Sambuc 
955f4a2713aSLionel Sambuc   errs() << "Singleton exists: " << nameWithID(Opc)
956f4a2713aSLionel Sambuc          << " with its decoding dominating ";
957f4a2713aSLionel Sambuc   for (unsigned i = 0; i < Opcodes.size(); ++i) {
958f4a2713aSLionel Sambuc     if (Opcodes[i] == Opc) continue;
959f4a2713aSLionel Sambuc     errs() << nameWithID(Opcodes[i]) << ' ';
960f4a2713aSLionel Sambuc   }
961f4a2713aSLionel Sambuc   errs() << '\n';
962f4a2713aSLionel Sambuc 
963f4a2713aSLionel Sambuc   dumpStack(errs(), "\t\t");
964f4a2713aSLionel Sambuc   for (unsigned i = 0; i < Opcodes.size(); ++i) {
965f4a2713aSLionel Sambuc     const std::string &Name = nameWithID(Opcodes[i]);
966f4a2713aSLionel Sambuc 
967f4a2713aSLionel Sambuc     errs() << '\t' << Name << " ";
968f4a2713aSLionel Sambuc     dumpBits(errs(),
969f4a2713aSLionel Sambuc              getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
970f4a2713aSLionel Sambuc     errs() << '\n';
971f4a2713aSLionel Sambuc   }
972f4a2713aSLionel Sambuc }
973f4a2713aSLionel Sambuc 
974f4a2713aSLionel Sambuc // Calculates the island(s) needed to decode the instruction.
975f4a2713aSLionel Sambuc // This returns a list of undecoded bits of an instructions, for example,
976f4a2713aSLionel Sambuc // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
977f4a2713aSLionel Sambuc // decoded bits in order to verify that the instruction matches the Opcode.
getIslands(std::vector<unsigned> & StartBits,std::vector<unsigned> & EndBits,std::vector<uint64_t> & FieldVals,const insn_t & Insn) const978f4a2713aSLionel Sambuc unsigned FilterChooser::getIslands(std::vector<unsigned> &StartBits,
979f4a2713aSLionel Sambuc                                    std::vector<unsigned> &EndBits,
980f4a2713aSLionel Sambuc                                    std::vector<uint64_t> &FieldVals,
981f4a2713aSLionel Sambuc                                    const insn_t &Insn) const {
982f4a2713aSLionel Sambuc   unsigned Num, BitNo;
983f4a2713aSLionel Sambuc   Num = BitNo = 0;
984f4a2713aSLionel Sambuc 
985f4a2713aSLionel Sambuc   uint64_t FieldVal = 0;
986f4a2713aSLionel Sambuc 
987f4a2713aSLionel Sambuc   // 0: Init
988f4a2713aSLionel Sambuc   // 1: Water (the bit value does not affect decoding)
989f4a2713aSLionel Sambuc   // 2: Island (well-known bit value needed for decoding)
990f4a2713aSLionel Sambuc   int State = 0;
991f4a2713aSLionel Sambuc   int Val = -1;
992f4a2713aSLionel Sambuc 
993f4a2713aSLionel Sambuc   for (unsigned i = 0; i < BitWidth; ++i) {
994f4a2713aSLionel Sambuc     Val = Value(Insn[i]);
995f4a2713aSLionel Sambuc     bool Filtered = PositionFiltered(i);
996f4a2713aSLionel Sambuc     switch (State) {
997f4a2713aSLionel Sambuc     default: llvm_unreachable("Unreachable code!");
998f4a2713aSLionel Sambuc     case 0:
999f4a2713aSLionel Sambuc     case 1:
1000f4a2713aSLionel Sambuc       if (Filtered || Val == -1)
1001f4a2713aSLionel Sambuc         State = 1; // Still in Water
1002f4a2713aSLionel Sambuc       else {
1003f4a2713aSLionel Sambuc         State = 2; // Into the Island
1004f4a2713aSLionel Sambuc         BitNo = 0;
1005f4a2713aSLionel Sambuc         StartBits.push_back(i);
1006f4a2713aSLionel Sambuc         FieldVal = Val;
1007f4a2713aSLionel Sambuc       }
1008f4a2713aSLionel Sambuc       break;
1009f4a2713aSLionel Sambuc     case 2:
1010f4a2713aSLionel Sambuc       if (Filtered || Val == -1) {
1011f4a2713aSLionel Sambuc         State = 1; // Into the Water
1012f4a2713aSLionel Sambuc         EndBits.push_back(i - 1);
1013f4a2713aSLionel Sambuc         FieldVals.push_back(FieldVal);
1014f4a2713aSLionel Sambuc         ++Num;
1015f4a2713aSLionel Sambuc       } else {
1016f4a2713aSLionel Sambuc         State = 2; // Still in Island
1017f4a2713aSLionel Sambuc         ++BitNo;
1018f4a2713aSLionel Sambuc         FieldVal = FieldVal | Val << BitNo;
1019f4a2713aSLionel Sambuc       }
1020f4a2713aSLionel Sambuc       break;
1021f4a2713aSLionel Sambuc     }
1022f4a2713aSLionel Sambuc   }
1023f4a2713aSLionel Sambuc   // If we are still in Island after the loop, do some housekeeping.
1024f4a2713aSLionel Sambuc   if (State == 2) {
1025f4a2713aSLionel Sambuc     EndBits.push_back(BitWidth - 1);
1026f4a2713aSLionel Sambuc     FieldVals.push_back(FieldVal);
1027f4a2713aSLionel Sambuc     ++Num;
1028f4a2713aSLionel Sambuc   }
1029f4a2713aSLionel Sambuc 
1030f4a2713aSLionel Sambuc   assert(StartBits.size() == Num && EndBits.size() == Num &&
1031f4a2713aSLionel Sambuc          FieldVals.size() == Num);
1032f4a2713aSLionel Sambuc   return Num;
1033f4a2713aSLionel Sambuc }
1034f4a2713aSLionel Sambuc 
emitBinaryParser(raw_ostream & o,unsigned & Indentation,const OperandInfo & OpInfo) const1035f4a2713aSLionel Sambuc void FilterChooser::emitBinaryParser(raw_ostream &o, unsigned &Indentation,
1036f4a2713aSLionel Sambuc                                      const OperandInfo &OpInfo) const {
1037f4a2713aSLionel Sambuc   const std::string &Decoder = OpInfo.Decoder;
1038f4a2713aSLionel Sambuc 
1039*0a6a1f1dSLionel Sambuc   if (OpInfo.numFields() != 1)
1040f4a2713aSLionel Sambuc     o.indent(Indentation) << "tmp = 0;\n";
1041*0a6a1f1dSLionel Sambuc 
1042*0a6a1f1dSLionel Sambuc   for (const EncodingField &EF : OpInfo) {
1043*0a6a1f1dSLionel Sambuc     o.indent(Indentation) << "tmp ";
1044*0a6a1f1dSLionel Sambuc     if (OpInfo.numFields() != 1) o << '|';
1045*0a6a1f1dSLionel Sambuc     o << "= fieldFromInstruction"
1046*0a6a1f1dSLionel Sambuc       << "(insn, " << EF.Base << ", " << EF.Width << ')';
1047*0a6a1f1dSLionel Sambuc     if (OpInfo.numFields() != 1 || EF.Offset != 0)
1048*0a6a1f1dSLionel Sambuc       o << " << " << EF.Offset;
1049*0a6a1f1dSLionel Sambuc     o << ";\n";
1050f4a2713aSLionel Sambuc   }
1051f4a2713aSLionel Sambuc 
1052f4a2713aSLionel Sambuc   if (Decoder != "")
1053f4a2713aSLionel Sambuc     o.indent(Indentation) << Emitter->GuardPrefix << Decoder
1054f4a2713aSLionel Sambuc                           << "(MI, tmp, Address, Decoder)"
1055f4a2713aSLionel Sambuc                           << Emitter->GuardPostfix << "\n";
1056f4a2713aSLionel Sambuc   else
1057f4a2713aSLionel Sambuc     o.indent(Indentation) << "MI.addOperand(MCOperand::CreateImm(tmp));\n";
1058f4a2713aSLionel Sambuc 
1059f4a2713aSLionel Sambuc }
1060f4a2713aSLionel Sambuc 
emitDecoder(raw_ostream & OS,unsigned Indentation,unsigned Opc) const1061f4a2713aSLionel Sambuc void FilterChooser::emitDecoder(raw_ostream &OS, unsigned Indentation,
1062f4a2713aSLionel Sambuc                                 unsigned Opc) const {
1063*0a6a1f1dSLionel Sambuc   for (const auto &Op : Operands.find(Opc)->second) {
1064f4a2713aSLionel Sambuc     // If a custom instruction decoder was specified, use that.
1065*0a6a1f1dSLionel Sambuc     if (Op.numFields() == 0 && Op.Decoder.size()) {
1066*0a6a1f1dSLionel Sambuc       OS.indent(Indentation) << Emitter->GuardPrefix << Op.Decoder
1067f4a2713aSLionel Sambuc         << "(MI, insn, Address, Decoder)"
1068f4a2713aSLionel Sambuc         << Emitter->GuardPostfix << "\n";
1069f4a2713aSLionel Sambuc       break;
1070f4a2713aSLionel Sambuc     }
1071f4a2713aSLionel Sambuc 
1072*0a6a1f1dSLionel Sambuc     emitBinaryParser(OS, Indentation, Op);
1073f4a2713aSLionel Sambuc   }
1074f4a2713aSLionel Sambuc }
1075f4a2713aSLionel Sambuc 
getDecoderIndex(DecoderSet & Decoders,unsigned Opc) const1076f4a2713aSLionel Sambuc unsigned FilterChooser::getDecoderIndex(DecoderSet &Decoders,
1077f4a2713aSLionel Sambuc                                         unsigned Opc) const {
1078f4a2713aSLionel Sambuc   // Build up the predicate string.
1079f4a2713aSLionel Sambuc   SmallString<256> Decoder;
1080f4a2713aSLionel Sambuc   // FIXME: emitDecoder() function can take a buffer directly rather than
1081f4a2713aSLionel Sambuc   // a stream.
1082f4a2713aSLionel Sambuc   raw_svector_ostream S(Decoder);
1083f4a2713aSLionel Sambuc   unsigned I = 4;
1084f4a2713aSLionel Sambuc   emitDecoder(S, I, Opc);
1085f4a2713aSLionel Sambuc   S.flush();
1086f4a2713aSLionel Sambuc 
1087f4a2713aSLionel Sambuc   // Using the full decoder string as the key value here is a bit
1088f4a2713aSLionel Sambuc   // heavyweight, but is effective. If the string comparisons become a
1089f4a2713aSLionel Sambuc   // performance concern, we can implement a mangling of the predicate
1090f4a2713aSLionel Sambuc   // data easilly enough with a map back to the actual string. That's
1091f4a2713aSLionel Sambuc   // overkill for now, though.
1092f4a2713aSLionel Sambuc 
1093f4a2713aSLionel Sambuc   // Make sure the predicate is in the table.
1094f4a2713aSLionel Sambuc   Decoders.insert(Decoder.str());
1095f4a2713aSLionel Sambuc   // Now figure out the index for when we write out the table.
1096f4a2713aSLionel Sambuc   DecoderSet::const_iterator P = std::find(Decoders.begin(),
1097f4a2713aSLionel Sambuc                                            Decoders.end(),
1098f4a2713aSLionel Sambuc                                            Decoder.str());
1099f4a2713aSLionel Sambuc   return (unsigned)(P - Decoders.begin());
1100f4a2713aSLionel Sambuc }
1101f4a2713aSLionel Sambuc 
emitSinglePredicateMatch(raw_ostream & o,StringRef str,const std::string & PredicateNamespace)1102f4a2713aSLionel Sambuc static void emitSinglePredicateMatch(raw_ostream &o, StringRef str,
1103f4a2713aSLionel Sambuc                                      const std::string &PredicateNamespace) {
1104f4a2713aSLionel Sambuc   if (str[0] == '!')
1105f4a2713aSLionel Sambuc     o << "!(Bits & " << PredicateNamespace << "::"
1106f4a2713aSLionel Sambuc       << str.slice(1,str.size()) << ")";
1107f4a2713aSLionel Sambuc   else
1108f4a2713aSLionel Sambuc     o << "(Bits & " << PredicateNamespace << "::" << str << ")";
1109f4a2713aSLionel Sambuc }
1110f4a2713aSLionel Sambuc 
emitPredicateMatch(raw_ostream & o,unsigned & Indentation,unsigned Opc) const1111f4a2713aSLionel Sambuc bool FilterChooser::emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
1112f4a2713aSLionel Sambuc                                        unsigned Opc) const {
1113f4a2713aSLionel Sambuc   ListInit *Predicates =
1114f4a2713aSLionel Sambuc     AllInstructions[Opc]->TheDef->getValueAsListInit("Predicates");
1115f4a2713aSLionel Sambuc   for (unsigned i = 0; i < Predicates->getSize(); ++i) {
1116f4a2713aSLionel Sambuc     Record *Pred = Predicates->getElementAsRecord(i);
1117f4a2713aSLionel Sambuc     if (!Pred->getValue("AssemblerMatcherPredicate"))
1118f4a2713aSLionel Sambuc       continue;
1119f4a2713aSLionel Sambuc 
1120f4a2713aSLionel Sambuc     std::string P = Pred->getValueAsString("AssemblerCondString");
1121f4a2713aSLionel Sambuc 
1122f4a2713aSLionel Sambuc     if (!P.length())
1123f4a2713aSLionel Sambuc       continue;
1124f4a2713aSLionel Sambuc 
1125f4a2713aSLionel Sambuc     if (i != 0)
1126f4a2713aSLionel Sambuc       o << " && ";
1127f4a2713aSLionel Sambuc 
1128f4a2713aSLionel Sambuc     StringRef SR(P);
1129f4a2713aSLionel Sambuc     std::pair<StringRef, StringRef> pairs = SR.split(',');
1130f4a2713aSLionel Sambuc     while (pairs.second.size()) {
1131f4a2713aSLionel Sambuc       emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
1132f4a2713aSLionel Sambuc       o << " && ";
1133f4a2713aSLionel Sambuc       pairs = pairs.second.split(',');
1134f4a2713aSLionel Sambuc     }
1135f4a2713aSLionel Sambuc     emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
1136f4a2713aSLionel Sambuc   }
1137f4a2713aSLionel Sambuc   return Predicates->getSize() > 0;
1138f4a2713aSLionel Sambuc }
1139f4a2713aSLionel Sambuc 
doesOpcodeNeedPredicate(unsigned Opc) const1140f4a2713aSLionel Sambuc bool FilterChooser::doesOpcodeNeedPredicate(unsigned Opc) const {
1141f4a2713aSLionel Sambuc   ListInit *Predicates =
1142f4a2713aSLionel Sambuc     AllInstructions[Opc]->TheDef->getValueAsListInit("Predicates");
1143f4a2713aSLionel Sambuc   for (unsigned i = 0; i < Predicates->getSize(); ++i) {
1144f4a2713aSLionel Sambuc     Record *Pred = Predicates->getElementAsRecord(i);
1145f4a2713aSLionel Sambuc     if (!Pred->getValue("AssemblerMatcherPredicate"))
1146f4a2713aSLionel Sambuc       continue;
1147f4a2713aSLionel Sambuc 
1148f4a2713aSLionel Sambuc     std::string P = Pred->getValueAsString("AssemblerCondString");
1149f4a2713aSLionel Sambuc 
1150f4a2713aSLionel Sambuc     if (!P.length())
1151f4a2713aSLionel Sambuc       continue;
1152f4a2713aSLionel Sambuc 
1153f4a2713aSLionel Sambuc     return true;
1154f4a2713aSLionel Sambuc   }
1155f4a2713aSLionel Sambuc   return false;
1156f4a2713aSLionel Sambuc }
1157f4a2713aSLionel Sambuc 
getPredicateIndex(DecoderTableInfo & TableInfo,StringRef Predicate) const1158f4a2713aSLionel Sambuc unsigned FilterChooser::getPredicateIndex(DecoderTableInfo &TableInfo,
1159f4a2713aSLionel Sambuc                                           StringRef Predicate) const {
1160f4a2713aSLionel Sambuc   // Using the full predicate string as the key value here is a bit
1161f4a2713aSLionel Sambuc   // heavyweight, but is effective. If the string comparisons become a
1162f4a2713aSLionel Sambuc   // performance concern, we can implement a mangling of the predicate
1163f4a2713aSLionel Sambuc   // data easilly enough with a map back to the actual string. That's
1164f4a2713aSLionel Sambuc   // overkill for now, though.
1165f4a2713aSLionel Sambuc 
1166f4a2713aSLionel Sambuc   // Make sure the predicate is in the table.
1167f4a2713aSLionel Sambuc   TableInfo.Predicates.insert(Predicate.str());
1168f4a2713aSLionel Sambuc   // Now figure out the index for when we write out the table.
1169f4a2713aSLionel Sambuc   PredicateSet::const_iterator P = std::find(TableInfo.Predicates.begin(),
1170f4a2713aSLionel Sambuc                                              TableInfo.Predicates.end(),
1171f4a2713aSLionel Sambuc                                              Predicate.str());
1172f4a2713aSLionel Sambuc   return (unsigned)(P - TableInfo.Predicates.begin());
1173f4a2713aSLionel Sambuc }
1174f4a2713aSLionel Sambuc 
emitPredicateTableEntry(DecoderTableInfo & TableInfo,unsigned Opc) const1175f4a2713aSLionel Sambuc void FilterChooser::emitPredicateTableEntry(DecoderTableInfo &TableInfo,
1176f4a2713aSLionel Sambuc                                             unsigned Opc) const {
1177f4a2713aSLionel Sambuc   if (!doesOpcodeNeedPredicate(Opc))
1178f4a2713aSLionel Sambuc     return;
1179f4a2713aSLionel Sambuc 
1180f4a2713aSLionel Sambuc   // Build up the predicate string.
1181f4a2713aSLionel Sambuc   SmallString<256> Predicate;
1182f4a2713aSLionel Sambuc   // FIXME: emitPredicateMatch() functions can take a buffer directly rather
1183f4a2713aSLionel Sambuc   // than a stream.
1184f4a2713aSLionel Sambuc   raw_svector_ostream PS(Predicate);
1185f4a2713aSLionel Sambuc   unsigned I = 0;
1186f4a2713aSLionel Sambuc   emitPredicateMatch(PS, I, Opc);
1187f4a2713aSLionel Sambuc 
1188f4a2713aSLionel Sambuc   // Figure out the index into the predicate table for the predicate just
1189f4a2713aSLionel Sambuc   // computed.
1190f4a2713aSLionel Sambuc   unsigned PIdx = getPredicateIndex(TableInfo, PS.str());
1191f4a2713aSLionel Sambuc   SmallString<16> PBytes;
1192f4a2713aSLionel Sambuc   raw_svector_ostream S(PBytes);
1193f4a2713aSLionel Sambuc   encodeULEB128(PIdx, S);
1194f4a2713aSLionel Sambuc   S.flush();
1195f4a2713aSLionel Sambuc 
1196f4a2713aSLionel Sambuc   TableInfo.Table.push_back(MCD::OPC_CheckPredicate);
1197f4a2713aSLionel Sambuc   // Predicate index
1198f4a2713aSLionel Sambuc   for (unsigned i = 0, e = PBytes.size(); i != e; ++i)
1199f4a2713aSLionel Sambuc     TableInfo.Table.push_back(PBytes[i]);
1200f4a2713aSLionel Sambuc   // Push location for NumToSkip backpatching.
1201f4a2713aSLionel Sambuc   TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
1202f4a2713aSLionel Sambuc   TableInfo.Table.push_back(0);
1203f4a2713aSLionel Sambuc   TableInfo.Table.push_back(0);
1204f4a2713aSLionel Sambuc }
1205f4a2713aSLionel Sambuc 
emitSoftFailTableEntry(DecoderTableInfo & TableInfo,unsigned Opc) const1206f4a2713aSLionel Sambuc void FilterChooser::emitSoftFailTableEntry(DecoderTableInfo &TableInfo,
1207f4a2713aSLionel Sambuc                                            unsigned Opc) const {
1208f4a2713aSLionel Sambuc   BitsInit *SFBits =
1209f4a2713aSLionel Sambuc     AllInstructions[Opc]->TheDef->getValueAsBitsInit("SoftFail");
1210f4a2713aSLionel Sambuc   if (!SFBits) return;
1211f4a2713aSLionel Sambuc   BitsInit *InstBits = AllInstructions[Opc]->TheDef->getValueAsBitsInit("Inst");
1212f4a2713aSLionel Sambuc 
1213f4a2713aSLionel Sambuc   APInt PositiveMask(BitWidth, 0ULL);
1214f4a2713aSLionel Sambuc   APInt NegativeMask(BitWidth, 0ULL);
1215f4a2713aSLionel Sambuc   for (unsigned i = 0; i < BitWidth; ++i) {
1216f4a2713aSLionel Sambuc     bit_value_t B = bitFromBits(*SFBits, i);
1217f4a2713aSLionel Sambuc     bit_value_t IB = bitFromBits(*InstBits, i);
1218f4a2713aSLionel Sambuc 
1219f4a2713aSLionel Sambuc     if (B != BIT_TRUE) continue;
1220f4a2713aSLionel Sambuc 
1221f4a2713aSLionel Sambuc     switch (IB) {
1222f4a2713aSLionel Sambuc     case BIT_FALSE:
1223f4a2713aSLionel Sambuc       // The bit is meant to be false, so emit a check to see if it is true.
1224f4a2713aSLionel Sambuc       PositiveMask.setBit(i);
1225f4a2713aSLionel Sambuc       break;
1226f4a2713aSLionel Sambuc     case BIT_TRUE:
1227f4a2713aSLionel Sambuc       // The bit is meant to be true, so emit a check to see if it is false.
1228f4a2713aSLionel Sambuc       NegativeMask.setBit(i);
1229f4a2713aSLionel Sambuc       break;
1230f4a2713aSLionel Sambuc     default:
1231f4a2713aSLionel Sambuc       // The bit is not set; this must be an error!
1232f4a2713aSLionel Sambuc       StringRef Name = AllInstructions[Opc]->TheDef->getName();
1233f4a2713aSLionel Sambuc       errs() << "SoftFail Conflict: bit SoftFail{" << i << "} in " << Name
1234f4a2713aSLionel Sambuc              << " is set but Inst{" << i << "} is unset!\n"
1235f4a2713aSLionel Sambuc              << "  - You can only mark a bit as SoftFail if it is fully defined"
1236f4a2713aSLionel Sambuc              << " (1/0 - not '?') in Inst\n";
1237f4a2713aSLionel Sambuc       return;
1238f4a2713aSLionel Sambuc     }
1239f4a2713aSLionel Sambuc   }
1240f4a2713aSLionel Sambuc 
1241f4a2713aSLionel Sambuc   bool NeedPositiveMask = PositiveMask.getBoolValue();
1242f4a2713aSLionel Sambuc   bool NeedNegativeMask = NegativeMask.getBoolValue();
1243f4a2713aSLionel Sambuc 
1244f4a2713aSLionel Sambuc   if (!NeedPositiveMask && !NeedNegativeMask)
1245f4a2713aSLionel Sambuc     return;
1246f4a2713aSLionel Sambuc 
1247f4a2713aSLionel Sambuc   TableInfo.Table.push_back(MCD::OPC_SoftFail);
1248f4a2713aSLionel Sambuc 
1249f4a2713aSLionel Sambuc   SmallString<16> MaskBytes;
1250f4a2713aSLionel Sambuc   raw_svector_ostream S(MaskBytes);
1251f4a2713aSLionel Sambuc   if (NeedPositiveMask) {
1252f4a2713aSLionel Sambuc     encodeULEB128(PositiveMask.getZExtValue(), S);
1253f4a2713aSLionel Sambuc     S.flush();
1254f4a2713aSLionel Sambuc     for (unsigned i = 0, e = MaskBytes.size(); i != e; ++i)
1255f4a2713aSLionel Sambuc       TableInfo.Table.push_back(MaskBytes[i]);
1256f4a2713aSLionel Sambuc   } else
1257f4a2713aSLionel Sambuc     TableInfo.Table.push_back(0);
1258f4a2713aSLionel Sambuc   if (NeedNegativeMask) {
1259f4a2713aSLionel Sambuc     MaskBytes.clear();
1260f4a2713aSLionel Sambuc     S.resync();
1261f4a2713aSLionel Sambuc     encodeULEB128(NegativeMask.getZExtValue(), S);
1262f4a2713aSLionel Sambuc     S.flush();
1263f4a2713aSLionel Sambuc     for (unsigned i = 0, e = MaskBytes.size(); i != e; ++i)
1264f4a2713aSLionel Sambuc       TableInfo.Table.push_back(MaskBytes[i]);
1265f4a2713aSLionel Sambuc   } else
1266f4a2713aSLionel Sambuc     TableInfo.Table.push_back(0);
1267f4a2713aSLionel Sambuc }
1268f4a2713aSLionel Sambuc 
1269f4a2713aSLionel Sambuc // Emits table entries to decode the singleton.
emitSingletonTableEntry(DecoderTableInfo & TableInfo,unsigned Opc) const1270f4a2713aSLionel Sambuc void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,
1271f4a2713aSLionel Sambuc                                             unsigned Opc) const {
1272f4a2713aSLionel Sambuc   std::vector<unsigned> StartBits;
1273f4a2713aSLionel Sambuc   std::vector<unsigned> EndBits;
1274f4a2713aSLionel Sambuc   std::vector<uint64_t> FieldVals;
1275f4a2713aSLionel Sambuc   insn_t Insn;
1276f4a2713aSLionel Sambuc   insnWithID(Insn, Opc);
1277f4a2713aSLionel Sambuc 
1278f4a2713aSLionel Sambuc   // Look for islands of undecoded bits of the singleton.
1279f4a2713aSLionel Sambuc   getIslands(StartBits, EndBits, FieldVals, Insn);
1280f4a2713aSLionel Sambuc 
1281f4a2713aSLionel Sambuc   unsigned Size = StartBits.size();
1282f4a2713aSLionel Sambuc 
1283f4a2713aSLionel Sambuc   // Emit the predicate table entry if one is needed.
1284f4a2713aSLionel Sambuc   emitPredicateTableEntry(TableInfo, Opc);
1285f4a2713aSLionel Sambuc 
1286f4a2713aSLionel Sambuc   // Check any additional encoding fields needed.
1287f4a2713aSLionel Sambuc   for (unsigned I = Size; I != 0; --I) {
1288f4a2713aSLionel Sambuc     unsigned NumBits = EndBits[I-1] - StartBits[I-1] + 1;
1289f4a2713aSLionel Sambuc     TableInfo.Table.push_back(MCD::OPC_CheckField);
1290f4a2713aSLionel Sambuc     TableInfo.Table.push_back(StartBits[I-1]);
1291f4a2713aSLionel Sambuc     TableInfo.Table.push_back(NumBits);
1292f4a2713aSLionel Sambuc     uint8_t Buffer[8], *p;
1293f4a2713aSLionel Sambuc     encodeULEB128(FieldVals[I-1], Buffer);
1294f4a2713aSLionel Sambuc     for (p = Buffer; *p >= 128 ; ++p)
1295f4a2713aSLionel Sambuc       TableInfo.Table.push_back(*p);
1296f4a2713aSLionel Sambuc     TableInfo.Table.push_back(*p);
1297f4a2713aSLionel Sambuc     // Push location for NumToSkip backpatching.
1298f4a2713aSLionel Sambuc     TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
1299f4a2713aSLionel Sambuc     // The fixup is always 16-bits, so go ahead and allocate the space
1300f4a2713aSLionel Sambuc     // in the table so all our relative position calculations work OK even
1301f4a2713aSLionel Sambuc     // before we fully resolve the real value here.
1302f4a2713aSLionel Sambuc     TableInfo.Table.push_back(0);
1303f4a2713aSLionel Sambuc     TableInfo.Table.push_back(0);
1304f4a2713aSLionel Sambuc   }
1305f4a2713aSLionel Sambuc 
1306f4a2713aSLionel Sambuc   // Check for soft failure of the match.
1307f4a2713aSLionel Sambuc   emitSoftFailTableEntry(TableInfo, Opc);
1308f4a2713aSLionel Sambuc 
1309f4a2713aSLionel Sambuc   TableInfo.Table.push_back(MCD::OPC_Decode);
1310f4a2713aSLionel Sambuc   uint8_t Buffer[8], *p;
1311f4a2713aSLionel Sambuc   encodeULEB128(Opc, Buffer);
1312f4a2713aSLionel Sambuc   for (p = Buffer; *p >= 128 ; ++p)
1313f4a2713aSLionel Sambuc     TableInfo.Table.push_back(*p);
1314f4a2713aSLionel Sambuc   TableInfo.Table.push_back(*p);
1315f4a2713aSLionel Sambuc 
1316f4a2713aSLionel Sambuc   unsigned DIdx = getDecoderIndex(TableInfo.Decoders, Opc);
1317f4a2713aSLionel Sambuc   SmallString<16> Bytes;
1318f4a2713aSLionel Sambuc   raw_svector_ostream S(Bytes);
1319f4a2713aSLionel Sambuc   encodeULEB128(DIdx, S);
1320f4a2713aSLionel Sambuc   S.flush();
1321f4a2713aSLionel Sambuc 
1322f4a2713aSLionel Sambuc   // Decoder index
1323f4a2713aSLionel Sambuc   for (unsigned i = 0, e = Bytes.size(); i != e; ++i)
1324f4a2713aSLionel Sambuc     TableInfo.Table.push_back(Bytes[i]);
1325f4a2713aSLionel Sambuc }
1326f4a2713aSLionel Sambuc 
1327f4a2713aSLionel Sambuc // Emits table entries to decode the singleton, and then to decode the rest.
emitSingletonTableEntry(DecoderTableInfo & TableInfo,const Filter & Best) const1328f4a2713aSLionel Sambuc void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,
1329f4a2713aSLionel Sambuc                                             const Filter &Best) const {
1330f4a2713aSLionel Sambuc   unsigned Opc = Best.getSingletonOpc();
1331f4a2713aSLionel Sambuc 
1332f4a2713aSLionel Sambuc   // complex singletons need predicate checks from the first singleton
1333f4a2713aSLionel Sambuc   // to refer forward to the variable filterchooser that follows.
1334f4a2713aSLionel Sambuc   TableInfo.FixupStack.push_back(FixupList());
1335f4a2713aSLionel Sambuc 
1336f4a2713aSLionel Sambuc   emitSingletonTableEntry(TableInfo, Opc);
1337f4a2713aSLionel Sambuc 
1338f4a2713aSLionel Sambuc   resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),
1339f4a2713aSLionel Sambuc                      TableInfo.Table.size());
1340f4a2713aSLionel Sambuc   TableInfo.FixupStack.pop_back();
1341f4a2713aSLionel Sambuc 
1342f4a2713aSLionel Sambuc   Best.getVariableFC().emitTableEntries(TableInfo);
1343f4a2713aSLionel Sambuc }
1344f4a2713aSLionel Sambuc 
1345f4a2713aSLionel Sambuc 
1346f4a2713aSLionel Sambuc // Assign a single filter and run with it.  Top level API client can initialize
1347f4a2713aSLionel Sambuc // with a single filter to start the filtering process.
runSingleFilter(unsigned startBit,unsigned numBit,bool mixed)1348f4a2713aSLionel Sambuc void FilterChooser::runSingleFilter(unsigned startBit, unsigned numBit,
1349f4a2713aSLionel Sambuc                                     bool mixed) {
1350f4a2713aSLionel Sambuc   Filters.clear();
1351*0a6a1f1dSLionel Sambuc   Filters.push_back(Filter(*this, startBit, numBit, true));
1352f4a2713aSLionel Sambuc   BestIndex = 0; // Sole Filter instance to choose from.
1353f4a2713aSLionel Sambuc   bestFilter().recurse();
1354f4a2713aSLionel Sambuc }
1355f4a2713aSLionel Sambuc 
1356f4a2713aSLionel Sambuc // reportRegion is a helper function for filterProcessor to mark a region as
1357f4a2713aSLionel Sambuc // eligible for use as a filter region.
reportRegion(bitAttr_t RA,unsigned StartBit,unsigned BitIndex,bool AllowMixed)1358f4a2713aSLionel Sambuc void FilterChooser::reportRegion(bitAttr_t RA, unsigned StartBit,
1359f4a2713aSLionel Sambuc                                  unsigned BitIndex, bool AllowMixed) {
1360f4a2713aSLionel Sambuc   if (RA == ATTR_MIXED && AllowMixed)
1361f4a2713aSLionel Sambuc     Filters.push_back(Filter(*this, StartBit, BitIndex - StartBit, true));
1362f4a2713aSLionel Sambuc   else if (RA == ATTR_ALL_SET && !AllowMixed)
1363f4a2713aSLionel Sambuc     Filters.push_back(Filter(*this, StartBit, BitIndex - StartBit, false));
1364f4a2713aSLionel Sambuc }
1365f4a2713aSLionel Sambuc 
1366f4a2713aSLionel Sambuc // FilterProcessor scans the well-known encoding bits of the instructions and
1367f4a2713aSLionel Sambuc // builds up a list of candidate filters.  It chooses the best filter and
1368f4a2713aSLionel Sambuc // recursively descends down the decoding tree.
filterProcessor(bool AllowMixed,bool Greedy)1369f4a2713aSLionel Sambuc bool FilterChooser::filterProcessor(bool AllowMixed, bool Greedy) {
1370f4a2713aSLionel Sambuc   Filters.clear();
1371f4a2713aSLionel Sambuc   BestIndex = -1;
1372f4a2713aSLionel Sambuc   unsigned numInstructions = Opcodes.size();
1373f4a2713aSLionel Sambuc 
1374f4a2713aSLionel Sambuc   assert(numInstructions && "Filter created with no instructions");
1375f4a2713aSLionel Sambuc 
1376f4a2713aSLionel Sambuc   // No further filtering is necessary.
1377f4a2713aSLionel Sambuc   if (numInstructions == 1)
1378f4a2713aSLionel Sambuc     return true;
1379f4a2713aSLionel Sambuc 
1380f4a2713aSLionel Sambuc   // Heuristics.  See also doFilter()'s "Heuristics" comment when num of
1381f4a2713aSLionel Sambuc   // instructions is 3.
1382f4a2713aSLionel Sambuc   if (AllowMixed && !Greedy) {
1383f4a2713aSLionel Sambuc     assert(numInstructions == 3);
1384f4a2713aSLionel Sambuc 
1385f4a2713aSLionel Sambuc     for (unsigned i = 0; i < Opcodes.size(); ++i) {
1386f4a2713aSLionel Sambuc       std::vector<unsigned> StartBits;
1387f4a2713aSLionel Sambuc       std::vector<unsigned> EndBits;
1388f4a2713aSLionel Sambuc       std::vector<uint64_t> FieldVals;
1389f4a2713aSLionel Sambuc       insn_t Insn;
1390f4a2713aSLionel Sambuc 
1391f4a2713aSLionel Sambuc       insnWithID(Insn, Opcodes[i]);
1392f4a2713aSLionel Sambuc 
1393f4a2713aSLionel Sambuc       // Look for islands of undecoded bits of any instruction.
1394f4a2713aSLionel Sambuc       if (getIslands(StartBits, EndBits, FieldVals, Insn) > 0) {
1395f4a2713aSLionel Sambuc         // Found an instruction with island(s).  Now just assign a filter.
1396f4a2713aSLionel Sambuc         runSingleFilter(StartBits[0], EndBits[0] - StartBits[0] + 1, true);
1397f4a2713aSLionel Sambuc         return true;
1398f4a2713aSLionel Sambuc       }
1399f4a2713aSLionel Sambuc     }
1400f4a2713aSLionel Sambuc   }
1401f4a2713aSLionel Sambuc 
1402f4a2713aSLionel Sambuc   unsigned BitIndex;
1403f4a2713aSLionel Sambuc 
1404f4a2713aSLionel Sambuc   // We maintain BIT_WIDTH copies of the bitAttrs automaton.
1405f4a2713aSLionel Sambuc   // The automaton consumes the corresponding bit from each
1406f4a2713aSLionel Sambuc   // instruction.
1407f4a2713aSLionel Sambuc   //
1408f4a2713aSLionel Sambuc   //   Input symbols: 0, 1, and _ (unset).
1409f4a2713aSLionel Sambuc   //   States:        NONE, FILTERED, ALL_SET, ALL_UNSET, and MIXED.
1410f4a2713aSLionel Sambuc   //   Initial state: NONE.
1411f4a2713aSLionel Sambuc   //
1412f4a2713aSLionel Sambuc   // (NONE) ------- [01] -> (ALL_SET)
1413f4a2713aSLionel Sambuc   // (NONE) ------- _ ----> (ALL_UNSET)
1414f4a2713aSLionel Sambuc   // (ALL_SET) ---- [01] -> (ALL_SET)
1415f4a2713aSLionel Sambuc   // (ALL_SET) ---- _ ----> (MIXED)
1416f4a2713aSLionel Sambuc   // (ALL_UNSET) -- [01] -> (MIXED)
1417f4a2713aSLionel Sambuc   // (ALL_UNSET) -- _ ----> (ALL_UNSET)
1418f4a2713aSLionel Sambuc   // (MIXED) ------ . ----> (MIXED)
1419f4a2713aSLionel Sambuc   // (FILTERED)---- . ----> (FILTERED)
1420f4a2713aSLionel Sambuc 
1421f4a2713aSLionel Sambuc   std::vector<bitAttr_t> bitAttrs;
1422f4a2713aSLionel Sambuc 
1423f4a2713aSLionel Sambuc   // FILTERED bit positions provide no entropy and are not worthy of pursuing.
1424f4a2713aSLionel Sambuc   // Filter::recurse() set either BIT_TRUE or BIT_FALSE for each position.
1425f4a2713aSLionel Sambuc   for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex)
1426f4a2713aSLionel Sambuc     if (FilterBitValues[BitIndex] == BIT_TRUE ||
1427f4a2713aSLionel Sambuc         FilterBitValues[BitIndex] == BIT_FALSE)
1428f4a2713aSLionel Sambuc       bitAttrs.push_back(ATTR_FILTERED);
1429f4a2713aSLionel Sambuc     else
1430f4a2713aSLionel Sambuc       bitAttrs.push_back(ATTR_NONE);
1431f4a2713aSLionel Sambuc 
1432f4a2713aSLionel Sambuc   for (unsigned InsnIndex = 0; InsnIndex < numInstructions; ++InsnIndex) {
1433f4a2713aSLionel Sambuc     insn_t insn;
1434f4a2713aSLionel Sambuc 
1435f4a2713aSLionel Sambuc     insnWithID(insn, Opcodes[InsnIndex]);
1436f4a2713aSLionel Sambuc 
1437f4a2713aSLionel Sambuc     for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
1438f4a2713aSLionel Sambuc       switch (bitAttrs[BitIndex]) {
1439f4a2713aSLionel Sambuc       case ATTR_NONE:
1440f4a2713aSLionel Sambuc         if (insn[BitIndex] == BIT_UNSET)
1441f4a2713aSLionel Sambuc           bitAttrs[BitIndex] = ATTR_ALL_UNSET;
1442f4a2713aSLionel Sambuc         else
1443f4a2713aSLionel Sambuc           bitAttrs[BitIndex] = ATTR_ALL_SET;
1444f4a2713aSLionel Sambuc         break;
1445f4a2713aSLionel Sambuc       case ATTR_ALL_SET:
1446f4a2713aSLionel Sambuc         if (insn[BitIndex] == BIT_UNSET)
1447f4a2713aSLionel Sambuc           bitAttrs[BitIndex] = ATTR_MIXED;
1448f4a2713aSLionel Sambuc         break;
1449f4a2713aSLionel Sambuc       case ATTR_ALL_UNSET:
1450f4a2713aSLionel Sambuc         if (insn[BitIndex] != BIT_UNSET)
1451f4a2713aSLionel Sambuc           bitAttrs[BitIndex] = ATTR_MIXED;
1452f4a2713aSLionel Sambuc         break;
1453f4a2713aSLionel Sambuc       case ATTR_MIXED:
1454f4a2713aSLionel Sambuc       case ATTR_FILTERED:
1455f4a2713aSLionel Sambuc         break;
1456f4a2713aSLionel Sambuc       }
1457f4a2713aSLionel Sambuc     }
1458f4a2713aSLionel Sambuc   }
1459f4a2713aSLionel Sambuc 
1460f4a2713aSLionel Sambuc   // The regionAttr automaton consumes the bitAttrs automatons' state,
1461f4a2713aSLionel Sambuc   // lowest-to-highest.
1462f4a2713aSLionel Sambuc   //
1463f4a2713aSLionel Sambuc   //   Input symbols: F(iltered), (all_)S(et), (all_)U(nset), M(ixed)
1464f4a2713aSLionel Sambuc   //   States:        NONE, ALL_SET, MIXED
1465f4a2713aSLionel Sambuc   //   Initial state: NONE
1466f4a2713aSLionel Sambuc   //
1467f4a2713aSLionel Sambuc   // (NONE) ----- F --> (NONE)
1468f4a2713aSLionel Sambuc   // (NONE) ----- S --> (ALL_SET)     ; and set region start
1469f4a2713aSLionel Sambuc   // (NONE) ----- U --> (NONE)
1470f4a2713aSLionel Sambuc   // (NONE) ----- M --> (MIXED)       ; and set region start
1471f4a2713aSLionel Sambuc   // (ALL_SET) -- F --> (NONE)        ; and report an ALL_SET region
1472f4a2713aSLionel Sambuc   // (ALL_SET) -- S --> (ALL_SET)
1473f4a2713aSLionel Sambuc   // (ALL_SET) -- U --> (NONE)        ; and report an ALL_SET region
1474f4a2713aSLionel Sambuc   // (ALL_SET) -- M --> (MIXED)       ; and report an ALL_SET region
1475f4a2713aSLionel Sambuc   // (MIXED) ---- F --> (NONE)        ; and report a MIXED region
1476f4a2713aSLionel Sambuc   // (MIXED) ---- S --> (ALL_SET)     ; and report a MIXED region
1477f4a2713aSLionel Sambuc   // (MIXED) ---- U --> (NONE)        ; and report a MIXED region
1478f4a2713aSLionel Sambuc   // (MIXED) ---- M --> (MIXED)
1479f4a2713aSLionel Sambuc 
1480f4a2713aSLionel Sambuc   bitAttr_t RA = ATTR_NONE;
1481f4a2713aSLionel Sambuc   unsigned StartBit = 0;
1482f4a2713aSLionel Sambuc 
1483f4a2713aSLionel Sambuc   for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
1484f4a2713aSLionel Sambuc     bitAttr_t bitAttr = bitAttrs[BitIndex];
1485f4a2713aSLionel Sambuc 
1486f4a2713aSLionel Sambuc     assert(bitAttr != ATTR_NONE && "Bit without attributes");
1487f4a2713aSLionel Sambuc 
1488f4a2713aSLionel Sambuc     switch (RA) {
1489f4a2713aSLionel Sambuc     case ATTR_NONE:
1490f4a2713aSLionel Sambuc       switch (bitAttr) {
1491f4a2713aSLionel Sambuc       case ATTR_FILTERED:
1492f4a2713aSLionel Sambuc         break;
1493f4a2713aSLionel Sambuc       case ATTR_ALL_SET:
1494f4a2713aSLionel Sambuc         StartBit = BitIndex;
1495f4a2713aSLionel Sambuc         RA = ATTR_ALL_SET;
1496f4a2713aSLionel Sambuc         break;
1497f4a2713aSLionel Sambuc       case ATTR_ALL_UNSET:
1498f4a2713aSLionel Sambuc         break;
1499f4a2713aSLionel Sambuc       case ATTR_MIXED:
1500f4a2713aSLionel Sambuc         StartBit = BitIndex;
1501f4a2713aSLionel Sambuc         RA = ATTR_MIXED;
1502f4a2713aSLionel Sambuc         break;
1503f4a2713aSLionel Sambuc       default:
1504f4a2713aSLionel Sambuc         llvm_unreachable("Unexpected bitAttr!");
1505f4a2713aSLionel Sambuc       }
1506f4a2713aSLionel Sambuc       break;
1507f4a2713aSLionel Sambuc     case ATTR_ALL_SET:
1508f4a2713aSLionel Sambuc       switch (bitAttr) {
1509f4a2713aSLionel Sambuc       case ATTR_FILTERED:
1510f4a2713aSLionel Sambuc         reportRegion(RA, StartBit, BitIndex, AllowMixed);
1511f4a2713aSLionel Sambuc         RA = ATTR_NONE;
1512f4a2713aSLionel Sambuc         break;
1513f4a2713aSLionel Sambuc       case ATTR_ALL_SET:
1514f4a2713aSLionel Sambuc         break;
1515f4a2713aSLionel Sambuc       case ATTR_ALL_UNSET:
1516f4a2713aSLionel Sambuc         reportRegion(RA, StartBit, BitIndex, AllowMixed);
1517f4a2713aSLionel Sambuc         RA = ATTR_NONE;
1518f4a2713aSLionel Sambuc         break;
1519f4a2713aSLionel Sambuc       case ATTR_MIXED:
1520f4a2713aSLionel Sambuc         reportRegion(RA, StartBit, BitIndex, AllowMixed);
1521f4a2713aSLionel Sambuc         StartBit = BitIndex;
1522f4a2713aSLionel Sambuc         RA = ATTR_MIXED;
1523f4a2713aSLionel Sambuc         break;
1524f4a2713aSLionel Sambuc       default:
1525f4a2713aSLionel Sambuc         llvm_unreachable("Unexpected bitAttr!");
1526f4a2713aSLionel Sambuc       }
1527f4a2713aSLionel Sambuc       break;
1528f4a2713aSLionel Sambuc     case ATTR_MIXED:
1529f4a2713aSLionel Sambuc       switch (bitAttr) {
1530f4a2713aSLionel Sambuc       case ATTR_FILTERED:
1531f4a2713aSLionel Sambuc         reportRegion(RA, StartBit, BitIndex, AllowMixed);
1532f4a2713aSLionel Sambuc         StartBit = BitIndex;
1533f4a2713aSLionel Sambuc         RA = ATTR_NONE;
1534f4a2713aSLionel Sambuc         break;
1535f4a2713aSLionel Sambuc       case ATTR_ALL_SET:
1536f4a2713aSLionel Sambuc         reportRegion(RA, StartBit, BitIndex, AllowMixed);
1537f4a2713aSLionel Sambuc         StartBit = BitIndex;
1538f4a2713aSLionel Sambuc         RA = ATTR_ALL_SET;
1539f4a2713aSLionel Sambuc         break;
1540f4a2713aSLionel Sambuc       case ATTR_ALL_UNSET:
1541f4a2713aSLionel Sambuc         reportRegion(RA, StartBit, BitIndex, AllowMixed);
1542f4a2713aSLionel Sambuc         RA = ATTR_NONE;
1543f4a2713aSLionel Sambuc         break;
1544f4a2713aSLionel Sambuc       case ATTR_MIXED:
1545f4a2713aSLionel Sambuc         break;
1546f4a2713aSLionel Sambuc       default:
1547f4a2713aSLionel Sambuc         llvm_unreachable("Unexpected bitAttr!");
1548f4a2713aSLionel Sambuc       }
1549f4a2713aSLionel Sambuc       break;
1550f4a2713aSLionel Sambuc     case ATTR_ALL_UNSET:
1551f4a2713aSLionel Sambuc       llvm_unreachable("regionAttr state machine has no ATTR_UNSET state");
1552f4a2713aSLionel Sambuc     case ATTR_FILTERED:
1553f4a2713aSLionel Sambuc       llvm_unreachable("regionAttr state machine has no ATTR_FILTERED state");
1554f4a2713aSLionel Sambuc     }
1555f4a2713aSLionel Sambuc   }
1556f4a2713aSLionel Sambuc 
1557f4a2713aSLionel Sambuc   // At the end, if we're still in ALL_SET or MIXED states, report a region
1558f4a2713aSLionel Sambuc   switch (RA) {
1559f4a2713aSLionel Sambuc   case ATTR_NONE:
1560f4a2713aSLionel Sambuc     break;
1561f4a2713aSLionel Sambuc   case ATTR_FILTERED:
1562f4a2713aSLionel Sambuc     break;
1563f4a2713aSLionel Sambuc   case ATTR_ALL_SET:
1564f4a2713aSLionel Sambuc     reportRegion(RA, StartBit, BitIndex, AllowMixed);
1565f4a2713aSLionel Sambuc     break;
1566f4a2713aSLionel Sambuc   case ATTR_ALL_UNSET:
1567f4a2713aSLionel Sambuc     break;
1568f4a2713aSLionel Sambuc   case ATTR_MIXED:
1569f4a2713aSLionel Sambuc     reportRegion(RA, StartBit, BitIndex, AllowMixed);
1570f4a2713aSLionel Sambuc     break;
1571f4a2713aSLionel Sambuc   }
1572f4a2713aSLionel Sambuc 
1573f4a2713aSLionel Sambuc   // We have finished with the filter processings.  Now it's time to choose
1574f4a2713aSLionel Sambuc   // the best performing filter.
1575f4a2713aSLionel Sambuc   BestIndex = 0;
1576f4a2713aSLionel Sambuc   bool AllUseless = true;
1577f4a2713aSLionel Sambuc   unsigned BestScore = 0;
1578f4a2713aSLionel Sambuc 
1579f4a2713aSLionel Sambuc   for (unsigned i = 0, e = Filters.size(); i != e; ++i) {
1580f4a2713aSLionel Sambuc     unsigned Usefulness = Filters[i].usefulness();
1581f4a2713aSLionel Sambuc 
1582f4a2713aSLionel Sambuc     if (Usefulness)
1583f4a2713aSLionel Sambuc       AllUseless = false;
1584f4a2713aSLionel Sambuc 
1585f4a2713aSLionel Sambuc     if (Usefulness > BestScore) {
1586f4a2713aSLionel Sambuc       BestIndex = i;
1587f4a2713aSLionel Sambuc       BestScore = Usefulness;
1588f4a2713aSLionel Sambuc     }
1589f4a2713aSLionel Sambuc   }
1590f4a2713aSLionel Sambuc 
1591f4a2713aSLionel Sambuc   if (!AllUseless)
1592f4a2713aSLionel Sambuc     bestFilter().recurse();
1593f4a2713aSLionel Sambuc 
1594f4a2713aSLionel Sambuc   return !AllUseless;
1595f4a2713aSLionel Sambuc } // end of FilterChooser::filterProcessor(bool)
1596f4a2713aSLionel Sambuc 
1597f4a2713aSLionel Sambuc // Decides on the best configuration of filter(s) to use in order to decode
1598f4a2713aSLionel Sambuc // the instructions.  A conflict of instructions may occur, in which case we
1599f4a2713aSLionel Sambuc // dump the conflict set to the standard error.
doFilter()1600f4a2713aSLionel Sambuc void FilterChooser::doFilter() {
1601f4a2713aSLionel Sambuc   unsigned Num = Opcodes.size();
1602f4a2713aSLionel Sambuc   assert(Num && "FilterChooser created with no instructions");
1603f4a2713aSLionel Sambuc 
1604f4a2713aSLionel Sambuc   // Try regions of consecutive known bit values first.
1605f4a2713aSLionel Sambuc   if (filterProcessor(false))
1606f4a2713aSLionel Sambuc     return;
1607f4a2713aSLionel Sambuc 
1608f4a2713aSLionel Sambuc   // Then regions of mixed bits (both known and unitialized bit values allowed).
1609f4a2713aSLionel Sambuc   if (filterProcessor(true))
1610f4a2713aSLionel Sambuc     return;
1611f4a2713aSLionel Sambuc 
1612f4a2713aSLionel Sambuc   // Heuristics to cope with conflict set {t2CMPrs, t2SUBSrr, t2SUBSrs} where
1613f4a2713aSLionel Sambuc   // no single instruction for the maximum ATTR_MIXED region Inst{14-4} has a
1614f4a2713aSLionel Sambuc   // well-known encoding pattern.  In such case, we backtrack and scan for the
1615f4a2713aSLionel Sambuc   // the very first consecutive ATTR_ALL_SET region and assign a filter to it.
1616f4a2713aSLionel Sambuc   if (Num == 3 && filterProcessor(true, false))
1617f4a2713aSLionel Sambuc     return;
1618f4a2713aSLionel Sambuc 
1619f4a2713aSLionel Sambuc   // If we come to here, the instruction decoding has failed.
1620f4a2713aSLionel Sambuc   // Set the BestIndex to -1 to indicate so.
1621f4a2713aSLionel Sambuc   BestIndex = -1;
1622f4a2713aSLionel Sambuc }
1623f4a2713aSLionel Sambuc 
1624f4a2713aSLionel Sambuc // emitTableEntries - Emit state machine entries to decode our share of
1625f4a2713aSLionel Sambuc // instructions.
emitTableEntries(DecoderTableInfo & TableInfo) const1626f4a2713aSLionel Sambuc void FilterChooser::emitTableEntries(DecoderTableInfo &TableInfo) const {
1627f4a2713aSLionel Sambuc   if (Opcodes.size() == 1) {
1628f4a2713aSLionel Sambuc     // There is only one instruction in the set, which is great!
1629f4a2713aSLionel Sambuc     // Call emitSingletonDecoder() to see whether there are any remaining
1630f4a2713aSLionel Sambuc     // encodings bits.
1631f4a2713aSLionel Sambuc     emitSingletonTableEntry(TableInfo, Opcodes[0]);
1632f4a2713aSLionel Sambuc     return;
1633f4a2713aSLionel Sambuc   }
1634f4a2713aSLionel Sambuc 
1635f4a2713aSLionel Sambuc   // Choose the best filter to do the decodings!
1636f4a2713aSLionel Sambuc   if (BestIndex != -1) {
1637f4a2713aSLionel Sambuc     const Filter &Best = Filters[BestIndex];
1638f4a2713aSLionel Sambuc     if (Best.getNumFiltered() == 1)
1639f4a2713aSLionel Sambuc       emitSingletonTableEntry(TableInfo, Best);
1640f4a2713aSLionel Sambuc     else
1641f4a2713aSLionel Sambuc       Best.emitTableEntry(TableInfo);
1642f4a2713aSLionel Sambuc     return;
1643f4a2713aSLionel Sambuc   }
1644f4a2713aSLionel Sambuc 
1645f4a2713aSLionel Sambuc   // We don't know how to decode these instructions!  Dump the
1646f4a2713aSLionel Sambuc   // conflict set and bail.
1647f4a2713aSLionel Sambuc 
1648f4a2713aSLionel Sambuc   // Print out useful conflict information for postmortem analysis.
1649f4a2713aSLionel Sambuc   errs() << "Decoding Conflict:\n";
1650f4a2713aSLionel Sambuc 
1651f4a2713aSLionel Sambuc   dumpStack(errs(), "\t\t");
1652f4a2713aSLionel Sambuc 
1653f4a2713aSLionel Sambuc   for (unsigned i = 0; i < Opcodes.size(); ++i) {
1654f4a2713aSLionel Sambuc     const std::string &Name = nameWithID(Opcodes[i]);
1655f4a2713aSLionel Sambuc 
1656f4a2713aSLionel Sambuc     errs() << '\t' << Name << " ";
1657f4a2713aSLionel Sambuc     dumpBits(errs(),
1658f4a2713aSLionel Sambuc              getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
1659f4a2713aSLionel Sambuc     errs() << '\n';
1660f4a2713aSLionel Sambuc   }
1661f4a2713aSLionel Sambuc }
1662f4a2713aSLionel Sambuc 
populateInstruction(CodeGenTarget & Target,const CodeGenInstruction & CGI,unsigned Opc,std::map<unsigned,std::vector<OperandInfo>> & Operands)1663*0a6a1f1dSLionel Sambuc static bool populateInstruction(CodeGenTarget &Target,
1664*0a6a1f1dSLionel Sambuc                        const CodeGenInstruction &CGI, unsigned Opc,
1665f4a2713aSLionel Sambuc                        std::map<unsigned, std::vector<OperandInfo> > &Operands){
1666f4a2713aSLionel Sambuc   const Record &Def = *CGI.TheDef;
1667f4a2713aSLionel Sambuc   // If all the bit positions are not specified; do not decode this instruction.
1668f4a2713aSLionel Sambuc   // We are bound to fail!  For proper disassembly, the well-known encoding bits
1669f4a2713aSLionel Sambuc   // of the instruction must be fully specified.
1670f4a2713aSLionel Sambuc 
1671f4a2713aSLionel Sambuc   BitsInit &Bits = getBitsField(Def, "Inst");
1672f4a2713aSLionel Sambuc   if (Bits.allInComplete()) return false;
1673f4a2713aSLionel Sambuc 
1674f4a2713aSLionel Sambuc   std::vector<OperandInfo> InsnOperands;
1675f4a2713aSLionel Sambuc 
1676f4a2713aSLionel Sambuc   // If the instruction has specified a custom decoding hook, use that instead
1677f4a2713aSLionel Sambuc   // of trying to auto-generate the decoder.
1678f4a2713aSLionel Sambuc   std::string InstDecoder = Def.getValueAsString("DecoderMethod");
1679f4a2713aSLionel Sambuc   if (InstDecoder != "") {
1680f4a2713aSLionel Sambuc     InsnOperands.push_back(OperandInfo(InstDecoder));
1681f4a2713aSLionel Sambuc     Operands[Opc] = InsnOperands;
1682f4a2713aSLionel Sambuc     return true;
1683f4a2713aSLionel Sambuc   }
1684f4a2713aSLionel Sambuc 
1685f4a2713aSLionel Sambuc   // Generate a description of the operand of the instruction that we know
1686f4a2713aSLionel Sambuc   // how to decode automatically.
1687f4a2713aSLionel Sambuc   // FIXME: We'll need to have a way to manually override this as needed.
1688f4a2713aSLionel Sambuc 
1689f4a2713aSLionel Sambuc   // Gather the outputs/inputs of the instruction, so we can find their
1690f4a2713aSLionel Sambuc   // positions in the encoding.  This assumes for now that they appear in the
1691f4a2713aSLionel Sambuc   // MCInst in the order that they're listed.
1692f4a2713aSLionel Sambuc   std::vector<std::pair<Init*, std::string> > InOutOperands;
1693f4a2713aSLionel Sambuc   DagInit *Out  = Def.getValueAsDag("OutOperandList");
1694f4a2713aSLionel Sambuc   DagInit *In  = Def.getValueAsDag("InOperandList");
1695f4a2713aSLionel Sambuc   for (unsigned i = 0; i < Out->getNumArgs(); ++i)
1696f4a2713aSLionel Sambuc     InOutOperands.push_back(std::make_pair(Out->getArg(i), Out->getArgName(i)));
1697f4a2713aSLionel Sambuc   for (unsigned i = 0; i < In->getNumArgs(); ++i)
1698f4a2713aSLionel Sambuc     InOutOperands.push_back(std::make_pair(In->getArg(i), In->getArgName(i)));
1699f4a2713aSLionel Sambuc 
1700f4a2713aSLionel Sambuc   // Search for tied operands, so that we can correctly instantiate
1701f4a2713aSLionel Sambuc   // operands that are not explicitly represented in the encoding.
1702f4a2713aSLionel Sambuc   std::map<std::string, std::string> TiedNames;
1703f4a2713aSLionel Sambuc   for (unsigned i = 0; i < CGI.Operands.size(); ++i) {
1704f4a2713aSLionel Sambuc     int tiedTo = CGI.Operands[i].getTiedRegister();
1705f4a2713aSLionel Sambuc     if (tiedTo != -1) {
1706*0a6a1f1dSLionel Sambuc       std::pair<unsigned, unsigned> SO =
1707*0a6a1f1dSLionel Sambuc         CGI.Operands.getSubOperandNumber(tiedTo);
1708*0a6a1f1dSLionel Sambuc       TiedNames[InOutOperands[i].second] = InOutOperands[SO.first].second;
1709*0a6a1f1dSLionel Sambuc       TiedNames[InOutOperands[SO.first].second] = InOutOperands[i].second;
1710*0a6a1f1dSLionel Sambuc     }
1711*0a6a1f1dSLionel Sambuc   }
1712*0a6a1f1dSLionel Sambuc 
1713*0a6a1f1dSLionel Sambuc   std::map<std::string, std::vector<OperandInfo> > NumberedInsnOperands;
1714*0a6a1f1dSLionel Sambuc   std::set<std::string> NumberedInsnOperandsNoTie;
1715*0a6a1f1dSLionel Sambuc   if (Target.getInstructionSet()->
1716*0a6a1f1dSLionel Sambuc         getValueAsBit("decodePositionallyEncodedOperands")) {
1717*0a6a1f1dSLionel Sambuc     const std::vector<RecordVal> &Vals = Def.getValues();
1718*0a6a1f1dSLionel Sambuc     unsigned NumberedOp = 0;
1719*0a6a1f1dSLionel Sambuc 
1720*0a6a1f1dSLionel Sambuc     std::set<unsigned> NamedOpIndices;
1721*0a6a1f1dSLionel Sambuc     if (Target.getInstructionSet()->
1722*0a6a1f1dSLionel Sambuc          getValueAsBit("noNamedPositionallyEncodedOperands"))
1723*0a6a1f1dSLionel Sambuc       // Collect the set of operand indices that might correspond to named
1724*0a6a1f1dSLionel Sambuc       // operand, and skip these when assigning operands based on position.
1725*0a6a1f1dSLionel Sambuc       for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1726*0a6a1f1dSLionel Sambuc         unsigned OpIdx;
1727*0a6a1f1dSLionel Sambuc         if (!CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx))
1728*0a6a1f1dSLionel Sambuc           continue;
1729*0a6a1f1dSLionel Sambuc 
1730*0a6a1f1dSLionel Sambuc         NamedOpIndices.insert(OpIdx);
1731*0a6a1f1dSLionel Sambuc       }
1732*0a6a1f1dSLionel Sambuc 
1733*0a6a1f1dSLionel Sambuc     for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1734*0a6a1f1dSLionel Sambuc       // Ignore fixed fields in the record, we're looking for values like:
1735*0a6a1f1dSLionel Sambuc       //    bits<5> RST = { ?, ?, ?, ?, ? };
1736*0a6a1f1dSLionel Sambuc       if (Vals[i].getPrefix() || Vals[i].getValue()->isComplete())
1737*0a6a1f1dSLionel Sambuc         continue;
1738*0a6a1f1dSLionel Sambuc 
1739*0a6a1f1dSLionel Sambuc       // Determine if Vals[i] actually contributes to the Inst encoding.
1740*0a6a1f1dSLionel Sambuc       unsigned bi = 0;
1741*0a6a1f1dSLionel Sambuc       for (; bi < Bits.getNumBits(); ++bi) {
1742*0a6a1f1dSLionel Sambuc         VarInit *Var = nullptr;
1743*0a6a1f1dSLionel Sambuc         VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
1744*0a6a1f1dSLionel Sambuc         if (BI)
1745*0a6a1f1dSLionel Sambuc           Var = dyn_cast<VarInit>(BI->getBitVar());
1746*0a6a1f1dSLionel Sambuc         else
1747*0a6a1f1dSLionel Sambuc           Var = dyn_cast<VarInit>(Bits.getBit(bi));
1748*0a6a1f1dSLionel Sambuc 
1749*0a6a1f1dSLionel Sambuc         if (Var && Var->getName() == Vals[i].getName())
1750*0a6a1f1dSLionel Sambuc           break;
1751*0a6a1f1dSLionel Sambuc       }
1752*0a6a1f1dSLionel Sambuc 
1753*0a6a1f1dSLionel Sambuc       if (bi == Bits.getNumBits())
1754*0a6a1f1dSLionel Sambuc         continue;
1755*0a6a1f1dSLionel Sambuc 
1756*0a6a1f1dSLionel Sambuc       // Skip variables that correspond to explicitly-named operands.
1757*0a6a1f1dSLionel Sambuc       unsigned OpIdx;
1758*0a6a1f1dSLionel Sambuc       if (CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx))
1759*0a6a1f1dSLionel Sambuc         continue;
1760*0a6a1f1dSLionel Sambuc 
1761*0a6a1f1dSLionel Sambuc       // Get the bit range for this operand:
1762*0a6a1f1dSLionel Sambuc       unsigned bitStart = bi++, bitWidth = 1;
1763*0a6a1f1dSLionel Sambuc       for (; bi < Bits.getNumBits(); ++bi) {
1764*0a6a1f1dSLionel Sambuc         VarInit *Var = nullptr;
1765*0a6a1f1dSLionel Sambuc         VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
1766*0a6a1f1dSLionel Sambuc         if (BI)
1767*0a6a1f1dSLionel Sambuc           Var = dyn_cast<VarInit>(BI->getBitVar());
1768*0a6a1f1dSLionel Sambuc         else
1769*0a6a1f1dSLionel Sambuc           Var = dyn_cast<VarInit>(Bits.getBit(bi));
1770*0a6a1f1dSLionel Sambuc 
1771*0a6a1f1dSLionel Sambuc         if (!Var)
1772*0a6a1f1dSLionel Sambuc           break;
1773*0a6a1f1dSLionel Sambuc 
1774*0a6a1f1dSLionel Sambuc         if (Var->getName() != Vals[i].getName())
1775*0a6a1f1dSLionel Sambuc           break;
1776*0a6a1f1dSLionel Sambuc 
1777*0a6a1f1dSLionel Sambuc         ++bitWidth;
1778*0a6a1f1dSLionel Sambuc       }
1779*0a6a1f1dSLionel Sambuc 
1780*0a6a1f1dSLionel Sambuc       unsigned NumberOps = CGI.Operands.size();
1781*0a6a1f1dSLionel Sambuc       while (NumberedOp < NumberOps &&
1782*0a6a1f1dSLionel Sambuc              (CGI.Operands.isFlatOperandNotEmitted(NumberedOp) ||
1783*0a6a1f1dSLionel Sambuc               (NamedOpIndices.size() && NamedOpIndices.count(
1784*0a6a1f1dSLionel Sambuc                 CGI.Operands.getSubOperandNumber(NumberedOp).first))))
1785*0a6a1f1dSLionel Sambuc         ++NumberedOp;
1786*0a6a1f1dSLionel Sambuc 
1787*0a6a1f1dSLionel Sambuc       OpIdx = NumberedOp++;
1788*0a6a1f1dSLionel Sambuc 
1789*0a6a1f1dSLionel Sambuc       // OpIdx now holds the ordered operand number of Vals[i].
1790*0a6a1f1dSLionel Sambuc       std::pair<unsigned, unsigned> SO =
1791*0a6a1f1dSLionel Sambuc         CGI.Operands.getSubOperandNumber(OpIdx);
1792*0a6a1f1dSLionel Sambuc       const std::string &Name = CGI.Operands[SO.first].Name;
1793*0a6a1f1dSLionel Sambuc 
1794*0a6a1f1dSLionel Sambuc       DEBUG(dbgs() << "Numbered operand mapping for " << Def.getName() << ": " <<
1795*0a6a1f1dSLionel Sambuc                       Name << "(" << SO.first << ", " << SO.second << ") => " <<
1796*0a6a1f1dSLionel Sambuc                       Vals[i].getName() << "\n");
1797*0a6a1f1dSLionel Sambuc 
1798*0a6a1f1dSLionel Sambuc       std::string Decoder = "";
1799*0a6a1f1dSLionel Sambuc       Record *TypeRecord = CGI.Operands[SO.first].Rec;
1800*0a6a1f1dSLionel Sambuc 
1801*0a6a1f1dSLionel Sambuc       RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod");
1802*0a6a1f1dSLionel Sambuc       StringInit *String = DecoderString ?
1803*0a6a1f1dSLionel Sambuc         dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
1804*0a6a1f1dSLionel Sambuc       if (String && String->getValue() != "")
1805*0a6a1f1dSLionel Sambuc         Decoder = String->getValue();
1806*0a6a1f1dSLionel Sambuc 
1807*0a6a1f1dSLionel Sambuc       if (Decoder == "" &&
1808*0a6a1f1dSLionel Sambuc           CGI.Operands[SO.first].MIOperandInfo &&
1809*0a6a1f1dSLionel Sambuc           CGI.Operands[SO.first].MIOperandInfo->getNumArgs()) {
1810*0a6a1f1dSLionel Sambuc         Init *Arg = CGI.Operands[SO.first].MIOperandInfo->
1811*0a6a1f1dSLionel Sambuc                       getArg(SO.second);
1812*0a6a1f1dSLionel Sambuc         if (TypedInit *TI = cast<TypedInit>(Arg)) {
1813*0a6a1f1dSLionel Sambuc           RecordRecTy *Type = cast<RecordRecTy>(TI->getType());
1814*0a6a1f1dSLionel Sambuc           TypeRecord = Type->getRecord();
1815*0a6a1f1dSLionel Sambuc         }
1816*0a6a1f1dSLionel Sambuc       }
1817*0a6a1f1dSLionel Sambuc 
1818*0a6a1f1dSLionel Sambuc       bool isReg = false;
1819*0a6a1f1dSLionel Sambuc       if (TypeRecord->isSubClassOf("RegisterOperand"))
1820*0a6a1f1dSLionel Sambuc         TypeRecord = TypeRecord->getValueAsDef("RegClass");
1821*0a6a1f1dSLionel Sambuc       if (TypeRecord->isSubClassOf("RegisterClass")) {
1822*0a6a1f1dSLionel Sambuc         Decoder = "Decode" + TypeRecord->getName() + "RegisterClass";
1823*0a6a1f1dSLionel Sambuc         isReg = true;
1824*0a6a1f1dSLionel Sambuc       } else if (TypeRecord->isSubClassOf("PointerLikeRegClass")) {
1825*0a6a1f1dSLionel Sambuc         Decoder = "DecodePointerLikeRegClass" +
1826*0a6a1f1dSLionel Sambuc                   utostr(TypeRecord->getValueAsInt("RegClassKind"));
1827*0a6a1f1dSLionel Sambuc         isReg = true;
1828*0a6a1f1dSLionel Sambuc       }
1829*0a6a1f1dSLionel Sambuc 
1830*0a6a1f1dSLionel Sambuc       DecoderString = TypeRecord->getValue("DecoderMethod");
1831*0a6a1f1dSLionel Sambuc       String = DecoderString ?
1832*0a6a1f1dSLionel Sambuc         dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
1833*0a6a1f1dSLionel Sambuc       if (!isReg && String && String->getValue() != "")
1834*0a6a1f1dSLionel Sambuc         Decoder = String->getValue();
1835*0a6a1f1dSLionel Sambuc 
1836*0a6a1f1dSLionel Sambuc       OperandInfo OpInfo(Decoder);
1837*0a6a1f1dSLionel Sambuc       OpInfo.addField(bitStart, bitWidth, 0);
1838*0a6a1f1dSLionel Sambuc 
1839*0a6a1f1dSLionel Sambuc       NumberedInsnOperands[Name].push_back(OpInfo);
1840*0a6a1f1dSLionel Sambuc 
1841*0a6a1f1dSLionel Sambuc       // FIXME: For complex operands with custom decoders we can't handle tied
1842*0a6a1f1dSLionel Sambuc       // sub-operands automatically. Skip those here and assume that this is
1843*0a6a1f1dSLionel Sambuc       // fixed up elsewhere.
1844*0a6a1f1dSLionel Sambuc       if (CGI.Operands[SO.first].MIOperandInfo &&
1845*0a6a1f1dSLionel Sambuc           CGI.Operands[SO.first].MIOperandInfo->getNumArgs() > 1 &&
1846*0a6a1f1dSLionel Sambuc           String && String->getValue() != "")
1847*0a6a1f1dSLionel Sambuc         NumberedInsnOperandsNoTie.insert(Name);
1848f4a2713aSLionel Sambuc     }
1849f4a2713aSLionel Sambuc   }
1850f4a2713aSLionel Sambuc 
1851f4a2713aSLionel Sambuc   // For each operand, see if we can figure out where it is encoded.
1852*0a6a1f1dSLionel Sambuc   for (const auto &Op : InOutOperands) {
1853*0a6a1f1dSLionel Sambuc     if (!NumberedInsnOperands[Op.second].empty()) {
1854*0a6a1f1dSLionel Sambuc       InsnOperands.insert(InsnOperands.end(),
1855*0a6a1f1dSLionel Sambuc                           NumberedInsnOperands[Op.second].begin(),
1856*0a6a1f1dSLionel Sambuc                           NumberedInsnOperands[Op.second].end());
1857*0a6a1f1dSLionel Sambuc       continue;
1858*0a6a1f1dSLionel Sambuc     }
1859*0a6a1f1dSLionel Sambuc     if (!NumberedInsnOperands[TiedNames[Op.second]].empty()) {
1860*0a6a1f1dSLionel Sambuc       if (!NumberedInsnOperandsNoTie.count(TiedNames[Op.second])) {
1861*0a6a1f1dSLionel Sambuc         // Figure out to which (sub)operand we're tied.
1862*0a6a1f1dSLionel Sambuc         unsigned i = CGI.Operands.getOperandNamed(TiedNames[Op.second]);
1863*0a6a1f1dSLionel Sambuc         int tiedTo = CGI.Operands[i].getTiedRegister();
1864*0a6a1f1dSLionel Sambuc         if (tiedTo == -1) {
1865*0a6a1f1dSLionel Sambuc           i = CGI.Operands.getOperandNamed(Op.second);
1866*0a6a1f1dSLionel Sambuc           tiedTo = CGI.Operands[i].getTiedRegister();
1867*0a6a1f1dSLionel Sambuc         }
1868*0a6a1f1dSLionel Sambuc 
1869*0a6a1f1dSLionel Sambuc         if (tiedTo != -1) {
1870*0a6a1f1dSLionel Sambuc           std::pair<unsigned, unsigned> SO =
1871*0a6a1f1dSLionel Sambuc             CGI.Operands.getSubOperandNumber(tiedTo);
1872*0a6a1f1dSLionel Sambuc 
1873*0a6a1f1dSLionel Sambuc           InsnOperands.push_back(NumberedInsnOperands[TiedNames[Op.second]]
1874*0a6a1f1dSLionel Sambuc                                    [SO.second]);
1875*0a6a1f1dSLionel Sambuc         }
1876*0a6a1f1dSLionel Sambuc       }
1877*0a6a1f1dSLionel Sambuc       continue;
1878*0a6a1f1dSLionel Sambuc     }
1879*0a6a1f1dSLionel Sambuc 
1880f4a2713aSLionel Sambuc     std::string Decoder = "";
1881f4a2713aSLionel Sambuc 
1882f4a2713aSLionel Sambuc     // At this point, we can locate the field, but we need to know how to
1883f4a2713aSLionel Sambuc     // interpret it.  As a first step, require the target to provide callbacks
1884f4a2713aSLionel Sambuc     // for decoding register classes.
1885f4a2713aSLionel Sambuc     // FIXME: This need to be extended to handle instructions with custom
1886f4a2713aSLionel Sambuc     // decoder methods, and operands with (simple) MIOperandInfo's.
1887*0a6a1f1dSLionel Sambuc     TypedInit *TI = cast<TypedInit>(Op.first);
1888f4a2713aSLionel Sambuc     RecordRecTy *Type = cast<RecordRecTy>(TI->getType());
1889f4a2713aSLionel Sambuc     Record *TypeRecord = Type->getRecord();
1890f4a2713aSLionel Sambuc     bool isReg = false;
1891f4a2713aSLionel Sambuc     if (TypeRecord->isSubClassOf("RegisterOperand"))
1892f4a2713aSLionel Sambuc       TypeRecord = TypeRecord->getValueAsDef("RegClass");
1893f4a2713aSLionel Sambuc     if (TypeRecord->isSubClassOf("RegisterClass")) {
1894f4a2713aSLionel Sambuc       Decoder = "Decode" + TypeRecord->getName() + "RegisterClass";
1895f4a2713aSLionel Sambuc       isReg = true;
1896*0a6a1f1dSLionel Sambuc     } else if (TypeRecord->isSubClassOf("PointerLikeRegClass")) {
1897*0a6a1f1dSLionel Sambuc       Decoder = "DecodePointerLikeRegClass" +
1898*0a6a1f1dSLionel Sambuc                 utostr(TypeRecord->getValueAsInt("RegClassKind"));
1899*0a6a1f1dSLionel Sambuc       isReg = true;
1900f4a2713aSLionel Sambuc     }
1901f4a2713aSLionel Sambuc 
1902f4a2713aSLionel Sambuc     RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod");
1903f4a2713aSLionel Sambuc     StringInit *String = DecoderString ?
1904*0a6a1f1dSLionel Sambuc       dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
1905f4a2713aSLionel Sambuc     if (!isReg && String && String->getValue() != "")
1906f4a2713aSLionel Sambuc       Decoder = String->getValue();
1907f4a2713aSLionel Sambuc 
1908f4a2713aSLionel Sambuc     OperandInfo OpInfo(Decoder);
1909f4a2713aSLionel Sambuc     unsigned Base = ~0U;
1910f4a2713aSLionel Sambuc     unsigned Width = 0;
1911f4a2713aSLionel Sambuc     unsigned Offset = 0;
1912f4a2713aSLionel Sambuc 
1913f4a2713aSLionel Sambuc     for (unsigned bi = 0; bi < Bits.getNumBits(); ++bi) {
1914*0a6a1f1dSLionel Sambuc       VarInit *Var = nullptr;
1915f4a2713aSLionel Sambuc       VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
1916f4a2713aSLionel Sambuc       if (BI)
1917f4a2713aSLionel Sambuc         Var = dyn_cast<VarInit>(BI->getBitVar());
1918f4a2713aSLionel Sambuc       else
1919f4a2713aSLionel Sambuc         Var = dyn_cast<VarInit>(Bits.getBit(bi));
1920f4a2713aSLionel Sambuc 
1921f4a2713aSLionel Sambuc       if (!Var) {
1922f4a2713aSLionel Sambuc         if (Base != ~0U) {
1923f4a2713aSLionel Sambuc           OpInfo.addField(Base, Width, Offset);
1924f4a2713aSLionel Sambuc           Base = ~0U;
1925f4a2713aSLionel Sambuc           Width = 0;
1926f4a2713aSLionel Sambuc           Offset = 0;
1927f4a2713aSLionel Sambuc         }
1928f4a2713aSLionel Sambuc         continue;
1929f4a2713aSLionel Sambuc       }
1930f4a2713aSLionel Sambuc 
1931*0a6a1f1dSLionel Sambuc       if (Var->getName() != Op.second &&
1932*0a6a1f1dSLionel Sambuc           Var->getName() != TiedNames[Op.second]) {
1933f4a2713aSLionel Sambuc         if (Base != ~0U) {
1934f4a2713aSLionel Sambuc           OpInfo.addField(Base, Width, Offset);
1935f4a2713aSLionel Sambuc           Base = ~0U;
1936f4a2713aSLionel Sambuc           Width = 0;
1937f4a2713aSLionel Sambuc           Offset = 0;
1938f4a2713aSLionel Sambuc         }
1939f4a2713aSLionel Sambuc         continue;
1940f4a2713aSLionel Sambuc       }
1941f4a2713aSLionel Sambuc 
1942f4a2713aSLionel Sambuc       if (Base == ~0U) {
1943f4a2713aSLionel Sambuc         Base = bi;
1944f4a2713aSLionel Sambuc         Width = 1;
1945f4a2713aSLionel Sambuc         Offset = BI ? BI->getBitNum() : 0;
1946f4a2713aSLionel Sambuc       } else if (BI && BI->getBitNum() != Offset + Width) {
1947f4a2713aSLionel Sambuc         OpInfo.addField(Base, Width, Offset);
1948f4a2713aSLionel Sambuc         Base = bi;
1949f4a2713aSLionel Sambuc         Width = 1;
1950f4a2713aSLionel Sambuc         Offset = BI->getBitNum();
1951f4a2713aSLionel Sambuc       } else {
1952f4a2713aSLionel Sambuc         ++Width;
1953f4a2713aSLionel Sambuc       }
1954f4a2713aSLionel Sambuc     }
1955f4a2713aSLionel Sambuc 
1956f4a2713aSLionel Sambuc     if (Base != ~0U)
1957f4a2713aSLionel Sambuc       OpInfo.addField(Base, Width, Offset);
1958f4a2713aSLionel Sambuc 
1959f4a2713aSLionel Sambuc     if (OpInfo.numFields() > 0)
1960f4a2713aSLionel Sambuc       InsnOperands.push_back(OpInfo);
1961f4a2713aSLionel Sambuc   }
1962f4a2713aSLionel Sambuc 
1963f4a2713aSLionel Sambuc   Operands[Opc] = InsnOperands;
1964f4a2713aSLionel Sambuc 
1965f4a2713aSLionel Sambuc 
1966f4a2713aSLionel Sambuc #if 0
1967f4a2713aSLionel Sambuc   DEBUG({
1968f4a2713aSLionel Sambuc       // Dumps the instruction encoding bits.
1969f4a2713aSLionel Sambuc       dumpBits(errs(), Bits);
1970f4a2713aSLionel Sambuc 
1971f4a2713aSLionel Sambuc       errs() << '\n';
1972f4a2713aSLionel Sambuc 
1973f4a2713aSLionel Sambuc       // Dumps the list of operand info.
1974f4a2713aSLionel Sambuc       for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) {
1975f4a2713aSLionel Sambuc         const CGIOperandList::OperandInfo &Info = CGI.Operands[i];
1976f4a2713aSLionel Sambuc         const std::string &OperandName = Info.Name;
1977f4a2713aSLionel Sambuc         const Record &OperandDef = *Info.Rec;
1978f4a2713aSLionel Sambuc 
1979f4a2713aSLionel Sambuc         errs() << "\t" << OperandName << " (" << OperandDef.getName() << ")\n";
1980f4a2713aSLionel Sambuc       }
1981f4a2713aSLionel Sambuc     });
1982f4a2713aSLionel Sambuc #endif
1983f4a2713aSLionel Sambuc 
1984f4a2713aSLionel Sambuc   return true;
1985f4a2713aSLionel Sambuc }
1986f4a2713aSLionel Sambuc 
1987f4a2713aSLionel Sambuc // emitFieldFromInstruction - Emit the templated helper function
1988f4a2713aSLionel Sambuc // fieldFromInstruction().
emitFieldFromInstruction(formatted_raw_ostream & OS)1989f4a2713aSLionel Sambuc static void emitFieldFromInstruction(formatted_raw_ostream &OS) {
1990f4a2713aSLionel Sambuc   OS << "// Helper function for extracting fields from encoded instructions.\n"
1991f4a2713aSLionel Sambuc      << "template<typename InsnType>\n"
1992f4a2713aSLionel Sambuc    << "static InsnType fieldFromInstruction(InsnType insn, unsigned startBit,\n"
1993f4a2713aSLionel Sambuc      << "                                     unsigned numBits) {\n"
1994f4a2713aSLionel Sambuc      << "    assert(startBit + numBits <= (sizeof(InsnType)*8) &&\n"
1995f4a2713aSLionel Sambuc      << "           \"Instruction field out of bounds!\");\n"
1996f4a2713aSLionel Sambuc      << "    InsnType fieldMask;\n"
1997f4a2713aSLionel Sambuc      << "    if (numBits == sizeof(InsnType)*8)\n"
1998f4a2713aSLionel Sambuc      << "      fieldMask = (InsnType)(-1LL);\n"
1999f4a2713aSLionel Sambuc      << "    else\n"
2000f4a2713aSLionel Sambuc      << "      fieldMask = (((InsnType)1 << numBits) - 1) << startBit;\n"
2001f4a2713aSLionel Sambuc      << "    return (insn & fieldMask) >> startBit;\n"
2002f4a2713aSLionel Sambuc      << "}\n\n";
2003f4a2713aSLionel Sambuc }
2004f4a2713aSLionel Sambuc 
2005f4a2713aSLionel Sambuc // emitDecodeInstruction - Emit the templated helper function
2006f4a2713aSLionel Sambuc // decodeInstruction().
emitDecodeInstruction(formatted_raw_ostream & OS)2007f4a2713aSLionel Sambuc static void emitDecodeInstruction(formatted_raw_ostream &OS) {
2008f4a2713aSLionel Sambuc   OS << "template<typename InsnType>\n"
2009f4a2713aSLionel Sambuc      << "static DecodeStatus decodeInstruction(const uint8_t DecodeTable[], MCInst &MI,\n"
2010f4a2713aSLionel Sambuc      << "                                      InsnType insn, uint64_t Address,\n"
2011f4a2713aSLionel Sambuc      << "                                      const void *DisAsm,\n"
2012f4a2713aSLionel Sambuc      << "                                      const MCSubtargetInfo &STI) {\n"
2013f4a2713aSLionel Sambuc      << "  uint64_t Bits = STI.getFeatureBits();\n"
2014f4a2713aSLionel Sambuc      << "\n"
2015f4a2713aSLionel Sambuc      << "  const uint8_t *Ptr = DecodeTable;\n"
2016f4a2713aSLionel Sambuc      << "  uint32_t CurFieldValue = 0;\n"
2017f4a2713aSLionel Sambuc      << "  DecodeStatus S = MCDisassembler::Success;\n"
2018f4a2713aSLionel Sambuc      << "  for (;;) {\n"
2019f4a2713aSLionel Sambuc      << "    ptrdiff_t Loc = Ptr - DecodeTable;\n"
2020f4a2713aSLionel Sambuc      << "    switch (*Ptr) {\n"
2021f4a2713aSLionel Sambuc      << "    default:\n"
2022f4a2713aSLionel Sambuc      << "      errs() << Loc << \": Unexpected decode table opcode!\\n\";\n"
2023f4a2713aSLionel Sambuc      << "      return MCDisassembler::Fail;\n"
2024f4a2713aSLionel Sambuc      << "    case MCD::OPC_ExtractField: {\n"
2025f4a2713aSLionel Sambuc      << "      unsigned Start = *++Ptr;\n"
2026f4a2713aSLionel Sambuc      << "      unsigned Len = *++Ptr;\n"
2027f4a2713aSLionel Sambuc      << "      ++Ptr;\n"
2028f4a2713aSLionel Sambuc      << "      CurFieldValue = fieldFromInstruction(insn, Start, Len);\n"
2029f4a2713aSLionel Sambuc      << "      DEBUG(dbgs() << Loc << \": OPC_ExtractField(\" << Start << \", \"\n"
2030f4a2713aSLionel Sambuc      << "                   << Len << \"): \" << CurFieldValue << \"\\n\");\n"
2031f4a2713aSLionel Sambuc      << "      break;\n"
2032f4a2713aSLionel Sambuc      << "    }\n"
2033f4a2713aSLionel Sambuc      << "    case MCD::OPC_FilterValue: {\n"
2034f4a2713aSLionel Sambuc      << "      // Decode the field value.\n"
2035f4a2713aSLionel Sambuc      << "      unsigned Len;\n"
2036f4a2713aSLionel Sambuc      << "      InsnType Val = decodeULEB128(++Ptr, &Len);\n"
2037f4a2713aSLionel Sambuc      << "      Ptr += Len;\n"
2038f4a2713aSLionel Sambuc      << "      // NumToSkip is a plain 16-bit integer.\n"
2039f4a2713aSLionel Sambuc      << "      unsigned NumToSkip = *Ptr++;\n"
2040f4a2713aSLionel Sambuc      << "      NumToSkip |= (*Ptr++) << 8;\n"
2041f4a2713aSLionel Sambuc      << "\n"
2042f4a2713aSLionel Sambuc      << "      // Perform the filter operation.\n"
2043f4a2713aSLionel Sambuc      << "      if (Val != CurFieldValue)\n"
2044f4a2713aSLionel Sambuc      << "        Ptr += NumToSkip;\n"
2045f4a2713aSLionel Sambuc      << "      DEBUG(dbgs() << Loc << \": OPC_FilterValue(\" << Val << \", \" << NumToSkip\n"
2046f4a2713aSLionel Sambuc      << "                   << \"): \" << ((Val != CurFieldValue) ? \"FAIL:\" : \"PASS:\")\n"
2047f4a2713aSLionel Sambuc      << "                   << \" continuing at \" << (Ptr - DecodeTable) << \"\\n\");\n"
2048f4a2713aSLionel Sambuc      << "\n"
2049f4a2713aSLionel Sambuc      << "      break;\n"
2050f4a2713aSLionel Sambuc      << "    }\n"
2051f4a2713aSLionel Sambuc      << "    case MCD::OPC_CheckField: {\n"
2052f4a2713aSLionel Sambuc      << "      unsigned Start = *++Ptr;\n"
2053f4a2713aSLionel Sambuc      << "      unsigned Len = *++Ptr;\n"
2054f4a2713aSLionel Sambuc      << "      InsnType FieldValue = fieldFromInstruction(insn, Start, Len);\n"
2055f4a2713aSLionel Sambuc      << "      // Decode the field value.\n"
2056f4a2713aSLionel Sambuc      << "      uint32_t ExpectedValue = decodeULEB128(++Ptr, &Len);\n"
2057f4a2713aSLionel Sambuc      << "      Ptr += Len;\n"
2058f4a2713aSLionel Sambuc      << "      // NumToSkip is a plain 16-bit integer.\n"
2059f4a2713aSLionel Sambuc      << "      unsigned NumToSkip = *Ptr++;\n"
2060f4a2713aSLionel Sambuc      << "      NumToSkip |= (*Ptr++) << 8;\n"
2061f4a2713aSLionel Sambuc      << "\n"
2062f4a2713aSLionel Sambuc      << "      // If the actual and expected values don't match, skip.\n"
2063f4a2713aSLionel Sambuc      << "      if (ExpectedValue != FieldValue)\n"
2064f4a2713aSLionel Sambuc      << "        Ptr += NumToSkip;\n"
2065f4a2713aSLionel Sambuc      << "      DEBUG(dbgs() << Loc << \": OPC_CheckField(\" << Start << \", \"\n"
2066f4a2713aSLionel Sambuc      << "                   << Len << \", \" << ExpectedValue << \", \" << NumToSkip\n"
2067f4a2713aSLionel Sambuc      << "                   << \"): FieldValue = \" << FieldValue << \", ExpectedValue = \"\n"
2068f4a2713aSLionel Sambuc      << "                   << ExpectedValue << \": \"\n"
2069f4a2713aSLionel Sambuc      << "                   << ((ExpectedValue == FieldValue) ? \"PASS\\n\" : \"FAIL\\n\"));\n"
2070f4a2713aSLionel Sambuc      << "      break;\n"
2071f4a2713aSLionel Sambuc      << "    }\n"
2072f4a2713aSLionel Sambuc      << "    case MCD::OPC_CheckPredicate: {\n"
2073f4a2713aSLionel Sambuc      << "      unsigned Len;\n"
2074f4a2713aSLionel Sambuc      << "      // Decode the Predicate Index value.\n"
2075f4a2713aSLionel Sambuc      << "      unsigned PIdx = decodeULEB128(++Ptr, &Len);\n"
2076f4a2713aSLionel Sambuc      << "      Ptr += Len;\n"
2077f4a2713aSLionel Sambuc      << "      // NumToSkip is a plain 16-bit integer.\n"
2078f4a2713aSLionel Sambuc      << "      unsigned NumToSkip = *Ptr++;\n"
2079f4a2713aSLionel Sambuc      << "      NumToSkip |= (*Ptr++) << 8;\n"
2080f4a2713aSLionel Sambuc      << "      // Check the predicate.\n"
2081f4a2713aSLionel Sambuc      << "      bool Pred;\n"
2082f4a2713aSLionel Sambuc      << "      if (!(Pred = checkDecoderPredicate(PIdx, Bits)))\n"
2083f4a2713aSLionel Sambuc      << "        Ptr += NumToSkip;\n"
2084f4a2713aSLionel Sambuc      << "      (void)Pred;\n"
2085f4a2713aSLionel Sambuc      << "      DEBUG(dbgs() << Loc << \": OPC_CheckPredicate(\" << PIdx << \"): \"\n"
2086f4a2713aSLionel Sambuc      << "            << (Pred ? \"PASS\\n\" : \"FAIL\\n\"));\n"
2087f4a2713aSLionel Sambuc      << "\n"
2088f4a2713aSLionel Sambuc      << "      break;\n"
2089f4a2713aSLionel Sambuc      << "    }\n"
2090f4a2713aSLionel Sambuc      << "    case MCD::OPC_Decode: {\n"
2091f4a2713aSLionel Sambuc      << "      unsigned Len;\n"
2092f4a2713aSLionel Sambuc      << "      // Decode the Opcode value.\n"
2093f4a2713aSLionel Sambuc      << "      unsigned Opc = decodeULEB128(++Ptr, &Len);\n"
2094f4a2713aSLionel Sambuc      << "      Ptr += Len;\n"
2095f4a2713aSLionel Sambuc      << "      unsigned DecodeIdx = decodeULEB128(Ptr, &Len);\n"
2096f4a2713aSLionel Sambuc      << "      Ptr += Len;\n"
2097f4a2713aSLionel Sambuc      << "      DEBUG(dbgs() << Loc << \": OPC_Decode: opcode \" << Opc\n"
2098f4a2713aSLionel Sambuc      << "                   << \", using decoder \" << DecodeIdx << \"\\n\" );\n"
2099f4a2713aSLionel Sambuc      << "      DEBUG(dbgs() << \"----- DECODE SUCCESSFUL -----\\n\");\n"
2100f4a2713aSLionel Sambuc      << "\n"
2101f4a2713aSLionel Sambuc      << "      MI.setOpcode(Opc);\n"
2102f4a2713aSLionel Sambuc      << "      return decodeToMCInst(S, DecodeIdx, insn, MI, Address, DisAsm);\n"
2103f4a2713aSLionel Sambuc      << "    }\n"
2104f4a2713aSLionel Sambuc      << "    case MCD::OPC_SoftFail: {\n"
2105f4a2713aSLionel Sambuc      << "      // Decode the mask values.\n"
2106f4a2713aSLionel Sambuc      << "      unsigned Len;\n"
2107f4a2713aSLionel Sambuc      << "      InsnType PositiveMask = decodeULEB128(++Ptr, &Len);\n"
2108f4a2713aSLionel Sambuc      << "      Ptr += Len;\n"
2109f4a2713aSLionel Sambuc      << "      InsnType NegativeMask = decodeULEB128(Ptr, &Len);\n"
2110f4a2713aSLionel Sambuc      << "      Ptr += Len;\n"
2111f4a2713aSLionel Sambuc      << "      bool Fail = (insn & PositiveMask) || (~insn & NegativeMask);\n"
2112f4a2713aSLionel Sambuc      << "      if (Fail)\n"
2113f4a2713aSLionel Sambuc      << "        S = MCDisassembler::SoftFail;\n"
2114f4a2713aSLionel Sambuc      << "      DEBUG(dbgs() << Loc << \": OPC_SoftFail: \" << (Fail ? \"FAIL\\n\":\"PASS\\n\"));\n"
2115f4a2713aSLionel Sambuc      << "      break;\n"
2116f4a2713aSLionel Sambuc      << "    }\n"
2117f4a2713aSLionel Sambuc      << "    case MCD::OPC_Fail: {\n"
2118f4a2713aSLionel Sambuc      << "      DEBUG(dbgs() << Loc << \": OPC_Fail\\n\");\n"
2119f4a2713aSLionel Sambuc      << "      return MCDisassembler::Fail;\n"
2120f4a2713aSLionel Sambuc      << "    }\n"
2121f4a2713aSLionel Sambuc      << "    }\n"
2122f4a2713aSLionel Sambuc      << "  }\n"
2123f4a2713aSLionel Sambuc      << "  llvm_unreachable(\"bogosity detected in disassembler state machine!\");\n"
2124f4a2713aSLionel Sambuc      << "}\n\n";
2125f4a2713aSLionel Sambuc }
2126f4a2713aSLionel Sambuc 
2127f4a2713aSLionel Sambuc // Emits disassembler code for instruction decoding.
run(raw_ostream & o)2128f4a2713aSLionel Sambuc void FixedLenDecoderEmitter::run(raw_ostream &o) {
2129f4a2713aSLionel Sambuc   formatted_raw_ostream OS(o);
2130f4a2713aSLionel Sambuc   OS << "#include \"llvm/MC/MCInst.h\"\n";
2131f4a2713aSLionel Sambuc   OS << "#include \"llvm/Support/Debug.h\"\n";
2132f4a2713aSLionel Sambuc   OS << "#include \"llvm/Support/DataTypes.h\"\n";
2133f4a2713aSLionel Sambuc   OS << "#include \"llvm/Support/LEB128.h\"\n";
2134f4a2713aSLionel Sambuc   OS << "#include \"llvm/Support/raw_ostream.h\"\n";
2135f4a2713aSLionel Sambuc   OS << "#include <assert.h>\n";
2136f4a2713aSLionel Sambuc   OS << '\n';
2137f4a2713aSLionel Sambuc   OS << "namespace llvm {\n\n";
2138f4a2713aSLionel Sambuc 
2139f4a2713aSLionel Sambuc   emitFieldFromInstruction(OS);
2140f4a2713aSLionel Sambuc 
2141*0a6a1f1dSLionel Sambuc   Target.reverseBitsForLittleEndianEncoding();
2142*0a6a1f1dSLionel Sambuc 
2143f4a2713aSLionel Sambuc   // Parameterize the decoders based on namespace and instruction width.
2144f4a2713aSLionel Sambuc   NumberedInstructions = &Target.getInstructionsByEnumValue();
2145f4a2713aSLionel Sambuc   std::map<std::pair<std::string, unsigned>,
2146f4a2713aSLionel Sambuc            std::vector<unsigned> > OpcMap;
2147f4a2713aSLionel Sambuc   std::map<unsigned, std::vector<OperandInfo> > Operands;
2148f4a2713aSLionel Sambuc 
2149f4a2713aSLionel Sambuc   for (unsigned i = 0; i < NumberedInstructions->size(); ++i) {
2150f4a2713aSLionel Sambuc     const CodeGenInstruction *Inst = NumberedInstructions->at(i);
2151f4a2713aSLionel Sambuc     const Record *Def = Inst->TheDef;
2152f4a2713aSLionel Sambuc     unsigned Size = Def->getValueAsInt("Size");
2153f4a2713aSLionel Sambuc     if (Def->getValueAsString("Namespace") == "TargetOpcode" ||
2154f4a2713aSLionel Sambuc         Def->getValueAsBit("isPseudo") ||
2155f4a2713aSLionel Sambuc         Def->getValueAsBit("isAsmParserOnly") ||
2156f4a2713aSLionel Sambuc         Def->getValueAsBit("isCodeGenOnly"))
2157f4a2713aSLionel Sambuc       continue;
2158f4a2713aSLionel Sambuc 
2159f4a2713aSLionel Sambuc     std::string DecoderNamespace = Def->getValueAsString("DecoderNamespace");
2160f4a2713aSLionel Sambuc 
2161f4a2713aSLionel Sambuc     if (Size) {
2162*0a6a1f1dSLionel Sambuc       if (populateInstruction(Target, *Inst, i, Operands)) {
2163f4a2713aSLionel Sambuc         OpcMap[std::make_pair(DecoderNamespace, Size)].push_back(i);
2164f4a2713aSLionel Sambuc       }
2165f4a2713aSLionel Sambuc     }
2166f4a2713aSLionel Sambuc   }
2167f4a2713aSLionel Sambuc 
2168f4a2713aSLionel Sambuc   DecoderTableInfo TableInfo;
2169*0a6a1f1dSLionel Sambuc   for (const auto &Opc : OpcMap) {
2170f4a2713aSLionel Sambuc     // Emit the decoder for this namespace+width combination.
2171*0a6a1f1dSLionel Sambuc     FilterChooser FC(*NumberedInstructions, Opc.second, Operands,
2172*0a6a1f1dSLionel Sambuc                      8*Opc.first.second, this);
2173f4a2713aSLionel Sambuc 
2174f4a2713aSLionel Sambuc     // The decode table is cleared for each top level decoder function. The
2175f4a2713aSLionel Sambuc     // predicates and decoders themselves, however, are shared across all
2176f4a2713aSLionel Sambuc     // decoders to give more opportunities for uniqueing.
2177f4a2713aSLionel Sambuc     TableInfo.Table.clear();
2178f4a2713aSLionel Sambuc     TableInfo.FixupStack.clear();
2179f4a2713aSLionel Sambuc     TableInfo.Table.reserve(16384);
2180f4a2713aSLionel Sambuc     TableInfo.FixupStack.push_back(FixupList());
2181f4a2713aSLionel Sambuc     FC.emitTableEntries(TableInfo);
2182f4a2713aSLionel Sambuc     // Any NumToSkip fixups in the top level scope can resolve to the
2183f4a2713aSLionel Sambuc     // OPC_Fail at the end of the table.
2184f4a2713aSLionel Sambuc     assert(TableInfo.FixupStack.size() == 1 && "fixup stack phasing error!");
2185f4a2713aSLionel Sambuc     // Resolve any NumToSkip fixups in the current scope.
2186f4a2713aSLionel Sambuc     resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),
2187f4a2713aSLionel Sambuc                        TableInfo.Table.size());
2188f4a2713aSLionel Sambuc     TableInfo.FixupStack.clear();
2189f4a2713aSLionel Sambuc 
2190f4a2713aSLionel Sambuc     TableInfo.Table.push_back(MCD::OPC_Fail);
2191f4a2713aSLionel Sambuc 
2192f4a2713aSLionel Sambuc     // Print the table to the output stream.
2193*0a6a1f1dSLionel Sambuc     emitTable(OS, TableInfo.Table, 0, FC.getBitWidth(), Opc.first.first);
2194f4a2713aSLionel Sambuc     OS.flush();
2195f4a2713aSLionel Sambuc   }
2196f4a2713aSLionel Sambuc 
2197f4a2713aSLionel Sambuc   // Emit the predicate function.
2198f4a2713aSLionel Sambuc   emitPredicateFunction(OS, TableInfo.Predicates, 0);
2199f4a2713aSLionel Sambuc 
2200f4a2713aSLionel Sambuc   // Emit the decoder function.
2201f4a2713aSLionel Sambuc   emitDecoderFunction(OS, TableInfo.Decoders, 0);
2202f4a2713aSLionel Sambuc 
2203f4a2713aSLionel Sambuc   // Emit the main entry point for the decoder, decodeInstruction().
2204f4a2713aSLionel Sambuc   emitDecodeInstruction(OS);
2205f4a2713aSLionel Sambuc 
2206f4a2713aSLionel Sambuc   OS << "\n} // End llvm namespace\n";
2207f4a2713aSLionel Sambuc }
2208f4a2713aSLionel Sambuc 
2209f4a2713aSLionel Sambuc namespace llvm {
2210f4a2713aSLionel Sambuc 
EmitFixedLenDecoder(RecordKeeper & RK,raw_ostream & OS,std::string PredicateNamespace,std::string GPrefix,std::string GPostfix,std::string ROK,std::string RFail,std::string L)2211f4a2713aSLionel Sambuc void EmitFixedLenDecoder(RecordKeeper &RK, raw_ostream &OS,
2212f4a2713aSLionel Sambuc                          std::string PredicateNamespace,
2213f4a2713aSLionel Sambuc                          std::string GPrefix,
2214f4a2713aSLionel Sambuc                          std::string GPostfix,
2215f4a2713aSLionel Sambuc                          std::string ROK,
2216f4a2713aSLionel Sambuc                          std::string RFail,
2217f4a2713aSLionel Sambuc                          std::string L) {
2218f4a2713aSLionel Sambuc   FixedLenDecoderEmitter(RK, PredicateNamespace, GPrefix, GPostfix,
2219f4a2713aSLionel Sambuc                          ROK, RFail, L).run(OS);
2220f4a2713aSLionel Sambuc }
2221f4a2713aSLionel Sambuc 
2222f4a2713aSLionel Sambuc } // End llvm namespace
2223