blob: 5cabcadabdbcb242cfc8fe2a8707f9340d1bbdf5 [file] [log] [blame]
Owen Andersond8c87882011-02-18 21:51:29 +00001//===------------ FixedLenDecoderEmitter.cpp - Decoder Generator ----------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// It contains the tablegen backend that emits the decoder functions for
11// targets with fixed length instruction set.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "decoder-emitter"
16
Owen Andersond8c87882011-02-18 21:51:29 +000017#include "CodeGenTarget.h"
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +000018#include "llvm/TableGen/Error.h"
Peter Collingbourne7c788882011-10-01 16:41:13 +000019#include "llvm/TableGen/Record.h"
James Molloy3015dfb2012-02-09 10:56:31 +000020#include "llvm/ADT/APInt.h"
Jim Grosbachfc1a1612012-08-14 19:06:05 +000021#include "llvm/ADT/SmallString.h"
Owen Andersond8c87882011-02-18 21:51:29 +000022#include "llvm/ADT/StringExtras.h"
Jim Grosbachfc1a1612012-08-14 19:06:05 +000023#include "llvm/ADT/StringRef.h"
24#include "llvm/ADT/Twine.h"
25#include "llvm/MC/MCFixedLenDisassembler.h"
Jakob Stoklund Olesen6f36fa92012-06-11 15:37:55 +000026#include "llvm/Support/DataTypes.h"
Owen Andersond8c87882011-02-18 21:51:29 +000027#include "llvm/Support/Debug.h"
Jim Grosbachfc1a1612012-08-14 19:06:05 +000028#include "llvm/Support/FormattedStream.h"
29#include "llvm/Support/LEB128.h"
Owen Andersond8c87882011-02-18 21:51:29 +000030#include "llvm/Support/raw_ostream.h"
Jakob Stoklund Olesen6f36fa92012-06-11 15:37:55 +000031#include "llvm/TableGen/TableGenBackend.h"
Owen Andersond8c87882011-02-18 21:51:29 +000032
33#include <vector>
34#include <map>
35#include <string>
36
37using namespace llvm;
38
Jakob Stoklund Olesen6f36fa92012-06-11 15:37:55 +000039namespace {
40struct EncodingField {
41 unsigned Base, Width, Offset;
42 EncodingField(unsigned B, unsigned W, unsigned O)
43 : Base(B), Width(W), Offset(O) { }
44};
Jakob Stoklund Olesen6f36fa92012-06-11 15:37:55 +000045
Jakob Stoklund Olesen6f36fa92012-06-11 15:37:55 +000046struct OperandInfo {
47 std::vector<EncodingField> Fields;
48 std::string Decoder;
49
50 OperandInfo(std::string D)
51 : Decoder(D) { }
52
53 void addField(unsigned Base, unsigned Width, unsigned Offset) {
54 Fields.push_back(EncodingField(Base, Width, Offset));
55 }
56
57 unsigned numFields() const { return Fields.size(); }
58
59 typedef std::vector<EncodingField>::const_iterator const_iterator;
60
61 const_iterator begin() const { return Fields.begin(); }
62 const_iterator end() const { return Fields.end(); }
63};
Jim Grosbachfc1a1612012-08-14 19:06:05 +000064
65typedef std::vector<uint8_t> DecoderTable;
66typedef uint32_t DecoderFixup;
67typedef std::vector<DecoderFixup> FixupList;
68typedef std::vector<FixupList> FixupScopeList;
69typedef SetVector<std::string> PredicateSet;
70typedef SetVector<std::string> DecoderSet;
71struct DecoderTableInfo {
72 DecoderTable Table;
73 FixupScopeList FixupStack;
74 PredicateSet Predicates;
75 DecoderSet Decoders;
76};
77
Jakob Stoklund Olesen6f36fa92012-06-11 15:37:55 +000078} // End anonymous namespace
79
80namespace {
81class FixedLenDecoderEmitter {
Jim Grosbachfc1a1612012-08-14 19:06:05 +000082 const std::vector<const CodeGenInstruction*> *NumberedInstructions;
Jakob Stoklund Olesen6f36fa92012-06-11 15:37:55 +000083public:
84
85 // Defaults preserved here for documentation, even though they aren't
86 // strictly necessary given the way that this is currently being called.
87 FixedLenDecoderEmitter(RecordKeeper &R,
88 std::string PredicateNamespace,
89 std::string GPrefix = "if (",
90 std::string GPostfix = " == MCDisassembler::Fail)"
91 " return MCDisassembler::Fail;",
92 std::string ROK = "MCDisassembler::Success",
93 std::string RFail = "MCDisassembler::Fail",
94 std::string L = "") :
95 Target(R),
96 PredicateNamespace(PredicateNamespace),
97 GuardPrefix(GPrefix), GuardPostfix(GPostfix),
98 ReturnOK(ROK), ReturnFail(RFail), Locals(L) {}
99
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000100 // Emit the decoder state machine table.
101 void emitTable(formatted_raw_ostream &o, DecoderTable &Table,
102 unsigned Indentation, unsigned BitWidth,
103 StringRef Namespace) const;
104 void emitPredicateFunction(formatted_raw_ostream &OS,
105 PredicateSet &Predicates,
106 unsigned Indentation) const;
107 void emitDecoderFunction(formatted_raw_ostream &OS,
108 DecoderSet &Decoders,
109 unsigned Indentation) const;
110
Jakob Stoklund Olesen6f36fa92012-06-11 15:37:55 +0000111 // run - Output the code emitter
112 void run(raw_ostream &o);
113
114private:
115 CodeGenTarget Target;
116public:
117 std::string PredicateNamespace;
118 std::string GuardPrefix, GuardPostfix;
119 std::string ReturnOK, ReturnFail;
120 std::string Locals;
121};
122} // End anonymous namespace
123
Owen Andersond8c87882011-02-18 21:51:29 +0000124// The set (BIT_TRUE, BIT_FALSE, BIT_UNSET) represents a ternary logic system
125// for a bit value.
126//
127// BIT_UNFILTERED is used as the init value for a filter position. It is used
128// only for filter processings.
129typedef enum {
130 BIT_TRUE, // '1'
131 BIT_FALSE, // '0'
132 BIT_UNSET, // '?'
133 BIT_UNFILTERED // unfiltered
134} bit_value_t;
135
136static bool ValueSet(bit_value_t V) {
137 return (V == BIT_TRUE || V == BIT_FALSE);
138}
139static bool ValueNotSet(bit_value_t V) {
140 return (V == BIT_UNSET);
141}
142static int Value(bit_value_t V) {
143 return ValueNotSet(V) ? -1 : (V == BIT_FALSE ? 0 : 1);
144}
Craig Toppereb5cd612012-03-16 05:58:09 +0000145static bit_value_t bitFromBits(const BitsInit &bits, unsigned index) {
Sean Silva6cfc8062012-10-10 20:24:43 +0000146 if (BitInit *bit = dyn_cast<BitInit>(bits.getBit(index)))
Owen Andersond8c87882011-02-18 21:51:29 +0000147 return bit->getValue() ? BIT_TRUE : BIT_FALSE;
148
149 // The bit is uninitialized.
150 return BIT_UNSET;
151}
152// Prints the bit value for each position.
Craig Toppereb5cd612012-03-16 05:58:09 +0000153static void dumpBits(raw_ostream &o, const BitsInit &bits) {
Craig Topper8cd9eae2012-08-17 05:42:16 +0000154 for (unsigned index = bits.getNumBits(); index > 0; --index) {
Owen Andersond8c87882011-02-18 21:51:29 +0000155 switch (bitFromBits(bits, index - 1)) {
156 case BIT_TRUE:
157 o << "1";
158 break;
159 case BIT_FALSE:
160 o << "0";
161 break;
162 case BIT_UNSET:
163 o << "_";
164 break;
165 default:
Craig Topper655b8de2012-02-05 07:21:30 +0000166 llvm_unreachable("unexpected return value from bitFromBits");
Owen Andersond8c87882011-02-18 21:51:29 +0000167 }
168 }
169}
170
David Greene05bce0b2011-07-29 22:43:06 +0000171static BitsInit &getBitsField(const Record &def, const char *str) {
172 BitsInit *bits = def.getValueAsBitsInit(str);
Owen Andersond8c87882011-02-18 21:51:29 +0000173 return *bits;
174}
175
176// Forward declaration.
Jakob Stoklund Olesen6f36fa92012-06-11 15:37:55 +0000177namespace {
Owen Andersond8c87882011-02-18 21:51:29 +0000178class FilterChooser;
Jakob Stoklund Olesen6f36fa92012-06-11 15:37:55 +0000179} // End anonymous namespace
Owen Andersond8c87882011-02-18 21:51:29 +0000180
Owen Andersond8c87882011-02-18 21:51:29 +0000181// Representation of the instruction to work on.
Owen Andersonf1a00902011-07-19 21:06:00 +0000182typedef std::vector<bit_value_t> insn_t;
Owen Andersond8c87882011-02-18 21:51:29 +0000183
184/// Filter - Filter works with FilterChooser to produce the decoding tree for
185/// the ISA.
186///
187/// It is useful to think of a Filter as governing the switch stmts of the
188/// decoding tree in a certain level. Each case stmt delegates to an inferior
189/// FilterChooser to decide what further decoding logic to employ, or in another
190/// words, what other remaining bits to look at. The FilterChooser eventually
191/// chooses a best Filter to do its job.
192///
193/// This recursive scheme ends when the number of Opcodes assigned to the
194/// FilterChooser becomes 1 or if there is a conflict. A conflict happens when
195/// the Filter/FilterChooser combo does not know how to distinguish among the
196/// Opcodes assigned.
197///
198/// An example of a conflict is
199///
200/// Conflict:
201/// 111101000.00........00010000....
202/// 111101000.00........0001........
203/// 1111010...00........0001........
204/// 1111010...00....................
205/// 1111010.........................
206/// 1111............................
207/// ................................
208/// VST4q8a 111101000_00________00010000____
209/// VST4q8b 111101000_00________00010000____
210///
211/// The Debug output shows the path that the decoding tree follows to reach the
212/// the conclusion that there is a conflict. VST4q8a is a vst4 to double-spaced
213/// even registers, while VST4q8b is a vst4 to double-spaced odd regsisters.
214///
215/// The encoding info in the .td files does not specify this meta information,
216/// which could have been used by the decoder to resolve the conflict. The
217/// decoder could try to decode the even/odd register numbering and assign to
218/// VST4q8a or VST4q8b, but for the time being, the decoder chooses the "a"
219/// version and return the Opcode since the two have the same Asm format string.
Jakob Stoklund Olesen6f36fa92012-06-11 15:37:55 +0000220namespace {
Owen Andersond8c87882011-02-18 21:51:29 +0000221class Filter {
222protected:
Craig Topper5a4c7902012-03-16 06:52:56 +0000223 const FilterChooser *Owner;// points to the FilterChooser who owns this filter
Owen Andersond8c87882011-02-18 21:51:29 +0000224 unsigned StartBit; // the starting bit position
225 unsigned NumBits; // number of bits to filter
226 bool Mixed; // a mixed region contains both set and unset bits
227
228 // Map of well-known segment value to the set of uid's with that value.
229 std::map<uint64_t, std::vector<unsigned> > FilteredInstructions;
230
231 // Set of uid's with non-constant segment values.
232 std::vector<unsigned> VariableInstructions;
233
234 // Map of well-known segment value to its delegate.
Craig Toppereb5cd612012-03-16 05:58:09 +0000235 std::map<unsigned, const FilterChooser*> FilterChooserMap;
Owen Andersond8c87882011-02-18 21:51:29 +0000236
237 // Number of instructions which fall under FilteredInstructions category.
238 unsigned NumFiltered;
239
240 // Keeps track of the last opcode in the filtered bucket.
241 unsigned LastOpcFiltered;
242
Owen Andersond8c87882011-02-18 21:51:29 +0000243public:
Craig Toppereb5cd612012-03-16 05:58:09 +0000244 unsigned getNumFiltered() const { return NumFiltered; }
245 unsigned getSingletonOpc() const {
Owen Andersond8c87882011-02-18 21:51:29 +0000246 assert(NumFiltered == 1);
247 return LastOpcFiltered;
248 }
249 // Return the filter chooser for the group of instructions without constant
250 // segment values.
Craig Toppereb5cd612012-03-16 05:58:09 +0000251 const FilterChooser &getVariableFC() const {
Owen Andersond8c87882011-02-18 21:51:29 +0000252 assert(NumFiltered == 1);
253 assert(FilterChooserMap.size() == 1);
254 return *(FilterChooserMap.find((unsigned)-1)->second);
255 }
256
257 Filter(const Filter &f);
258 Filter(FilterChooser &owner, unsigned startBit, unsigned numBits, bool mixed);
259
260 ~Filter();
261
262 // Divides the decoding task into sub tasks and delegates them to the
263 // inferior FilterChooser's.
264 //
265 // A special case arises when there's only one entry in the filtered
266 // instructions. In order to unambiguously decode the singleton, we need to
267 // match the remaining undecoded encoding bits against the singleton.
268 void recurse();
269
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000270 // Emit table entries to decode instructions given a segment or segments of
271 // bits.
272 void emitTableEntry(DecoderTableInfo &TableInfo) const;
Owen Andersond8c87882011-02-18 21:51:29 +0000273
274 // Returns the number of fanout produced by the filter. More fanout implies
275 // the filter distinguishes more categories of instructions.
276 unsigned usefulness() const;
277}; // End of class Filter
Jakob Stoklund Olesen6f36fa92012-06-11 15:37:55 +0000278} // End anonymous namespace
Owen Andersond8c87882011-02-18 21:51:29 +0000279
280// These are states of our finite state machines used in FilterChooser's
281// filterProcessor() which produces the filter candidates to use.
282typedef enum {
283 ATTR_NONE,
284 ATTR_FILTERED,
285 ATTR_ALL_SET,
286 ATTR_ALL_UNSET,
287 ATTR_MIXED
288} bitAttr_t;
289
290/// FilterChooser - FilterChooser chooses the best filter among a set of Filters
291/// in order to perform the decoding of instructions at the current level.
292///
293/// Decoding proceeds from the top down. Based on the well-known encoding bits
294/// of instructions available, FilterChooser builds up the possible Filters that
295/// can further the task of decoding by distinguishing among the remaining
296/// candidate instructions.
297///
298/// Once a filter has been chosen, it is called upon to divide the decoding task
299/// into sub-tasks and delegates them to its inferior FilterChoosers for further
300/// processings.
301///
302/// It is useful to think of a Filter as governing the switch stmts of the
303/// decoding tree. And each case is delegated to an inferior FilterChooser to
304/// decide what further remaining bits to look at.
Jakob Stoklund Olesen6f36fa92012-06-11 15:37:55 +0000305namespace {
Owen Andersond8c87882011-02-18 21:51:29 +0000306class FilterChooser {
307protected:
308 friend class Filter;
309
310 // Vector of codegen instructions to choose our filter.
311 const std::vector<const CodeGenInstruction*> &AllInstructions;
312
313 // Vector of uid's for this filter chooser to work on.
Craig Topper5a4c7902012-03-16 06:52:56 +0000314 const std::vector<unsigned> &Opcodes;
Owen Andersond8c87882011-02-18 21:51:29 +0000315
316 // Lookup table for the operand decoding of instructions.
Craig Topper5a4c7902012-03-16 06:52:56 +0000317 const std::map<unsigned, std::vector<OperandInfo> > &Operands;
Owen Andersond8c87882011-02-18 21:51:29 +0000318
319 // Vector of candidate filters.
320 std::vector<Filter> Filters;
321
322 // Array of bit values passed down from our parent.
323 // Set to all BIT_UNFILTERED's for Parent == NULL.
Owen Andersonf1a00902011-07-19 21:06:00 +0000324 std::vector<bit_value_t> FilterBitValues;
Owen Andersond8c87882011-02-18 21:51:29 +0000325
326 // Links to the FilterChooser above us in the decoding tree.
Craig Topper5a4c7902012-03-16 06:52:56 +0000327 const FilterChooser *Parent;
Owen Andersond8c87882011-02-18 21:51:29 +0000328
329 // Index of the best filter from Filters.
330 int BestIndex;
331
Owen Andersonf1a00902011-07-19 21:06:00 +0000332 // Width of instructions
333 unsigned BitWidth;
334
Owen Anderson83e3f672011-08-17 17:44:15 +0000335 // Parent emitter
336 const FixedLenDecoderEmitter *Emitter;
337
Owen Andersond8c87882011-02-18 21:51:29 +0000338public:
Craig Topperd9360452012-03-16 01:19:24 +0000339 FilterChooser(const FilterChooser &FC)
340 : AllInstructions(FC.AllInstructions), Opcodes(FC.Opcodes),
Owen Andersonf1a00902011-07-19 21:06:00 +0000341 Operands(FC.Operands), Filters(FC.Filters),
342 FilterBitValues(FC.FilterBitValues), Parent(FC.Parent),
Craig Topperd9360452012-03-16 01:19:24 +0000343 BestIndex(FC.BestIndex), BitWidth(FC.BitWidth),
344 Emitter(FC.Emitter) { }
Owen Andersond8c87882011-02-18 21:51:29 +0000345
346 FilterChooser(const std::vector<const CodeGenInstruction*> &Insts,
347 const std::vector<unsigned> &IDs,
Craig Topper5a4c7902012-03-16 06:52:56 +0000348 const std::map<unsigned, std::vector<OperandInfo> > &Ops,
Owen Anderson83e3f672011-08-17 17:44:15 +0000349 unsigned BW,
Craig Topperd9360452012-03-16 01:19:24 +0000350 const FixedLenDecoderEmitter *E)
351 : AllInstructions(Insts), Opcodes(IDs), Operands(Ops), Filters(),
Owen Anderson83e3f672011-08-17 17:44:15 +0000352 Parent(NULL), BestIndex(-1), BitWidth(BW), Emitter(E) {
Owen Andersonf1a00902011-07-19 21:06:00 +0000353 for (unsigned i = 0; i < BitWidth; ++i)
354 FilterBitValues.push_back(BIT_UNFILTERED);
Owen Andersond8c87882011-02-18 21:51:29 +0000355
356 doFilter();
357 }
358
359 FilterChooser(const std::vector<const CodeGenInstruction*> &Insts,
360 const std::vector<unsigned> &IDs,
Craig Topper5a4c7902012-03-16 06:52:56 +0000361 const std::map<unsigned, std::vector<OperandInfo> > &Ops,
362 const std::vector<bit_value_t> &ParentFilterBitValues,
363 const FilterChooser &parent)
Craig Topperd9360452012-03-16 01:19:24 +0000364 : AllInstructions(Insts), Opcodes(IDs), Operands(Ops),
Owen Andersonf1a00902011-07-19 21:06:00 +0000365 Filters(), FilterBitValues(ParentFilterBitValues),
Owen Anderson83e3f672011-08-17 17:44:15 +0000366 Parent(&parent), BestIndex(-1), BitWidth(parent.BitWidth),
367 Emitter(parent.Emitter) {
Owen Andersond8c87882011-02-18 21:51:29 +0000368 doFilter();
369 }
370
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000371 unsigned getBitWidth() const { return BitWidth; }
Owen Andersond8c87882011-02-18 21:51:29 +0000372
373protected:
374 // Populates the insn given the uid.
375 void insnWithID(insn_t &Insn, unsigned Opcode) const {
David Greene05bce0b2011-07-29 22:43:06 +0000376 BitsInit &Bits = getBitsField(*AllInstructions[Opcode]->TheDef, "Inst");
Owen Andersond8c87882011-02-18 21:51:29 +0000377
James Molloy3015dfb2012-02-09 10:56:31 +0000378 // We may have a SoftFail bitmask, which specifies a mask where an encoding
379 // may differ from the value in "Inst" and yet still be valid, but the
380 // disassembler should return SoftFail instead of Success.
381 //
382 // This is used for marking UNPREDICTABLE instructions in the ARM world.
Jim Grosbach9c826d22012-02-29 22:07:56 +0000383 BitsInit *SFBits =
384 AllInstructions[Opcode]->TheDef->getValueAsBitsInit("SoftFail");
James Molloy3015dfb2012-02-09 10:56:31 +0000385
386 for (unsigned i = 0; i < BitWidth; ++i) {
387 if (SFBits && bitFromBits(*SFBits, i) == BIT_TRUE)
388 Insn.push_back(BIT_UNSET);
389 else
390 Insn.push_back(bitFromBits(Bits, i));
391 }
Owen Andersond8c87882011-02-18 21:51:29 +0000392 }
393
394 // Returns the record name.
395 const std::string &nameWithID(unsigned Opcode) const {
396 return AllInstructions[Opcode]->TheDef->getName();
397 }
398
399 // Populates the field of the insn given the start position and the number of
400 // consecutive bits to scan for.
401 //
402 // Returns false if there exists any uninitialized bit value in the range.
403 // Returns true, otherwise.
404 bool fieldFromInsn(uint64_t &Field, insn_t &Insn, unsigned StartBit,
Craig Topperd9360452012-03-16 01:19:24 +0000405 unsigned NumBits) const;
Owen Andersond8c87882011-02-18 21:51:29 +0000406
407 /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
408 /// filter array as a series of chars.
Craig Toppereb5cd612012-03-16 05:58:09 +0000409 void dumpFilterArray(raw_ostream &o,
410 const std::vector<bit_value_t> & filter) const;
Owen Andersond8c87882011-02-18 21:51:29 +0000411
412 /// dumpStack - dumpStack traverses the filter chooser chain and calls
413 /// dumpFilterArray on each filter chooser up to the top level one.
Craig Toppereb5cd612012-03-16 05:58:09 +0000414 void dumpStack(raw_ostream &o, const char *prefix) const;
Owen Andersond8c87882011-02-18 21:51:29 +0000415
416 Filter &bestFilter() {
417 assert(BestIndex != -1 && "BestIndex not set");
418 return Filters[BestIndex];
419 }
420
421 // Called from Filter::recurse() when singleton exists. For debug purpose.
Craig Toppereb5cd612012-03-16 05:58:09 +0000422 void SingletonExists(unsigned Opc) const;
Owen Andersond8c87882011-02-18 21:51:29 +0000423
Craig Toppereb5cd612012-03-16 05:58:09 +0000424 bool PositionFiltered(unsigned i) const {
Owen Andersond8c87882011-02-18 21:51:29 +0000425 return ValueSet(FilterBitValues[i]);
426 }
427
428 // Calculates the island(s) needed to decode the instruction.
429 // This returns a lit of undecoded bits of an instructions, for example,
430 // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
431 // decoded bits in order to verify that the instruction matches the Opcode.
432 unsigned getIslands(std::vector<unsigned> &StartBits,
Craig Topperd9360452012-03-16 01:19:24 +0000433 std::vector<unsigned> &EndBits,
Craig Toppereb5cd612012-03-16 05:58:09 +0000434 std::vector<uint64_t> &FieldVals,
435 const insn_t &Insn) const;
Owen Andersond8c87882011-02-18 21:51:29 +0000436
James Molloya5d58562011-09-07 19:42:28 +0000437 // Emits code to check the Predicates member of an instruction are true.
438 // Returns true if predicate matches were emitted, false otherwise.
Craig Toppereb5cd612012-03-16 05:58:09 +0000439 bool emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
440 unsigned Opc) const;
James Molloya5d58562011-09-07 19:42:28 +0000441
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000442 bool doesOpcodeNeedPredicate(unsigned Opc) const;
443 unsigned getPredicateIndex(DecoderTableInfo &TableInfo, StringRef P) const;
444 void emitPredicateTableEntry(DecoderTableInfo &TableInfo,
445 unsigned Opc) const;
James Molloy3015dfb2012-02-09 10:56:31 +0000446
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000447 void emitSoftFailTableEntry(DecoderTableInfo &TableInfo,
448 unsigned Opc) const;
449
450 // Emits table entries to decode the singleton.
451 void emitSingletonTableEntry(DecoderTableInfo &TableInfo,
452 unsigned Opc) const;
Owen Andersond8c87882011-02-18 21:51:29 +0000453
454 // Emits code to decode the singleton, and then to decode the rest.
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000455 void emitSingletonTableEntry(DecoderTableInfo &TableInfo,
456 const Filter &Best) const;
Owen Andersond8c87882011-02-18 21:51:29 +0000457
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000458 void emitBinaryParser(raw_ostream &o, unsigned &Indentation,
Craig Toppereb5cd612012-03-16 05:58:09 +0000459 const OperandInfo &OpInfo) const;
Owen Andersond1e38df2011-07-28 21:54:31 +0000460
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000461 void emitDecoder(raw_ostream &OS, unsigned Indentation, unsigned Opc) const;
462 unsigned getDecoderIndex(DecoderSet &Decoders, unsigned Opc) const;
463
Owen Andersond8c87882011-02-18 21:51:29 +0000464 // Assign a single filter and run with it.
Craig Toppereb5cd612012-03-16 05:58:09 +0000465 void runSingleFilter(unsigned startBit, unsigned numBit, bool mixed);
Owen Andersond8c87882011-02-18 21:51:29 +0000466
467 // reportRegion is a helper function for filterProcessor to mark a region as
468 // eligible for use as a filter region.
469 void reportRegion(bitAttr_t RA, unsigned StartBit, unsigned BitIndex,
Craig Topperd9360452012-03-16 01:19:24 +0000470 bool AllowMixed);
Owen Andersond8c87882011-02-18 21:51:29 +0000471
472 // FilterProcessor scans the well-known encoding bits of the instructions and
473 // builds up a list of candidate filters. It chooses the best filter and
474 // recursively descends down the decoding tree.
475 bool filterProcessor(bool AllowMixed, bool Greedy = true);
476
477 // Decides on the best configuration of filter(s) to use in order to decode
478 // the instructions. A conflict of instructions may occur, in which case we
479 // dump the conflict set to the standard error.
480 void doFilter();
481
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000482public:
483 // emitTableEntries - Emit state machine entries to decode our share of
484 // instructions.
485 void emitTableEntries(DecoderTableInfo &TableInfo) const;
Owen Andersond8c87882011-02-18 21:51:29 +0000486};
Jakob Stoklund Olesen6f36fa92012-06-11 15:37:55 +0000487} // End anonymous namespace
Owen Andersond8c87882011-02-18 21:51:29 +0000488
489///////////////////////////
490// //
Craig Topper797ba552012-03-16 00:56:01 +0000491// Filter Implementation //
Owen Andersond8c87882011-02-18 21:51:29 +0000492// //
493///////////////////////////
494
Craig Topperd9360452012-03-16 01:19:24 +0000495Filter::Filter(const Filter &f)
496 : Owner(f.Owner), StartBit(f.StartBit), NumBits(f.NumBits), Mixed(f.Mixed),
497 FilteredInstructions(f.FilteredInstructions),
498 VariableInstructions(f.VariableInstructions),
499 FilterChooserMap(f.FilterChooserMap), NumFiltered(f.NumFiltered),
500 LastOpcFiltered(f.LastOpcFiltered) {
Owen Andersond8c87882011-02-18 21:51:29 +0000501}
502
503Filter::Filter(FilterChooser &owner, unsigned startBit, unsigned numBits,
Craig Topperd9360452012-03-16 01:19:24 +0000504 bool mixed)
505 : Owner(&owner), StartBit(startBit), NumBits(numBits), Mixed(mixed) {
Owen Andersonf1a00902011-07-19 21:06:00 +0000506 assert(StartBit + NumBits - 1 < Owner->BitWidth);
Owen Andersond8c87882011-02-18 21:51:29 +0000507
508 NumFiltered = 0;
509 LastOpcFiltered = 0;
Owen Andersond8c87882011-02-18 21:51:29 +0000510
511 for (unsigned i = 0, e = Owner->Opcodes.size(); i != e; ++i) {
512 insn_t Insn;
513
514 // Populates the insn given the uid.
515 Owner->insnWithID(Insn, Owner->Opcodes[i]);
516
517 uint64_t Field;
518 // Scans the segment for possibly well-specified encoding bits.
519 bool ok = Owner->fieldFromInsn(Field, Insn, StartBit, NumBits);
520
521 if (ok) {
522 // The encoding bits are well-known. Lets add the uid of the
523 // instruction into the bucket keyed off the constant field value.
524 LastOpcFiltered = Owner->Opcodes[i];
525 FilteredInstructions[Field].push_back(LastOpcFiltered);
526 ++NumFiltered;
527 } else {
Craig Topper797ba552012-03-16 00:56:01 +0000528 // Some of the encoding bit(s) are unspecified. This contributes to
Owen Andersond8c87882011-02-18 21:51:29 +0000529 // one additional member of "Variable" instructions.
530 VariableInstructions.push_back(Owner->Opcodes[i]);
Owen Andersond8c87882011-02-18 21:51:29 +0000531 }
532 }
533
534 assert((FilteredInstructions.size() + VariableInstructions.size() > 0)
535 && "Filter returns no instruction categories");
536}
537
538Filter::~Filter() {
Craig Toppereb5cd612012-03-16 05:58:09 +0000539 std::map<unsigned, const FilterChooser*>::iterator filterIterator;
Owen Andersond8c87882011-02-18 21:51:29 +0000540 for (filterIterator = FilterChooserMap.begin();
541 filterIterator != FilterChooserMap.end();
542 filterIterator++) {
543 delete filterIterator->second;
544 }
545}
546
547// Divides the decoding task into sub tasks and delegates them to the
548// inferior FilterChooser's.
549//
550// A special case arises when there's only one entry in the filtered
551// instructions. In order to unambiguously decode the singleton, we need to
552// match the remaining undecoded encoding bits against the singleton.
553void Filter::recurse() {
554 std::map<uint64_t, std::vector<unsigned> >::const_iterator mapIterator;
555
Owen Andersond8c87882011-02-18 21:51:29 +0000556 // Starts by inheriting our parent filter chooser's filter bit values.
Owen Andersonf1a00902011-07-19 21:06:00 +0000557 std::vector<bit_value_t> BitValueArray(Owner->FilterBitValues);
Owen Andersond8c87882011-02-18 21:51:29 +0000558
Owen Andersond8c87882011-02-18 21:51:29 +0000559 if (VariableInstructions.size()) {
560 // Conservatively marks each segment position as BIT_UNSET.
Craig Topper8cd9eae2012-08-17 05:42:16 +0000561 for (unsigned bitIndex = 0; bitIndex < NumBits; ++bitIndex)
Owen Andersond8c87882011-02-18 21:51:29 +0000562 BitValueArray[StartBit + bitIndex] = BIT_UNSET;
563
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000564 // Delegates to an inferior filter chooser for further processing on this
Owen Andersond8c87882011-02-18 21:51:29 +0000565 // group of instructions whose segment values are variable.
Craig Toppereb5cd612012-03-16 05:58:09 +0000566 FilterChooserMap.insert(std::pair<unsigned, const FilterChooser*>(
Owen Andersond8c87882011-02-18 21:51:29 +0000567 (unsigned)-1,
568 new FilterChooser(Owner->AllInstructions,
569 VariableInstructions,
570 Owner->Operands,
571 BitValueArray,
572 *Owner)
573 ));
574 }
575
576 // No need to recurse for a singleton filtered instruction.
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000577 // See also Filter::emit*().
Owen Andersond8c87882011-02-18 21:51:29 +0000578 if (getNumFiltered() == 1) {
579 //Owner->SingletonExists(LastOpcFiltered);
580 assert(FilterChooserMap.size() == 1);
581 return;
582 }
583
584 // Otherwise, create sub choosers.
585 for (mapIterator = FilteredInstructions.begin();
586 mapIterator != FilteredInstructions.end();
587 mapIterator++) {
588
589 // Marks all the segment positions with either BIT_TRUE or BIT_FALSE.
Craig Topper8cd9eae2012-08-17 05:42:16 +0000590 for (unsigned bitIndex = 0; bitIndex < NumBits; ++bitIndex) {
Owen Andersond8c87882011-02-18 21:51:29 +0000591 if (mapIterator->first & (1ULL << bitIndex))
592 BitValueArray[StartBit + bitIndex] = BIT_TRUE;
593 else
594 BitValueArray[StartBit + bitIndex] = BIT_FALSE;
595 }
596
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000597 // Delegates to an inferior filter chooser for further processing on this
Owen Andersond8c87882011-02-18 21:51:29 +0000598 // category of instructions.
Craig Toppereb5cd612012-03-16 05:58:09 +0000599 FilterChooserMap.insert(std::pair<unsigned, const FilterChooser*>(
Owen Andersond8c87882011-02-18 21:51:29 +0000600 mapIterator->first,
601 new FilterChooser(Owner->AllInstructions,
602 mapIterator->second,
603 Owner->Operands,
604 BitValueArray,
605 *Owner)
606 ));
607 }
608}
609
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000610static void resolveTableFixups(DecoderTable &Table, const FixupList &Fixups,
611 uint32_t DestIdx) {
612 // Any NumToSkip fixups in the current scope can resolve to the
613 // current location.
614 for (FixupList::const_reverse_iterator I = Fixups.rbegin(),
615 E = Fixups.rend();
616 I != E; ++I) {
617 // Calculate the distance from the byte following the fixup entry byte
618 // to the destination. The Target is calculated from after the 16-bit
619 // NumToSkip entry itself, so subtract two from the displacement here
620 // to account for that.
621 uint32_t FixupIdx = *I;
622 uint32_t Delta = DestIdx - FixupIdx - 2;
623 // Our NumToSkip entries are 16-bits. Make sure our table isn't too
624 // big.
625 assert(Delta < 65536U && "disassembler decoding table too large!");
626 Table[FixupIdx] = (uint8_t)Delta;
627 Table[FixupIdx + 1] = (uint8_t)(Delta >> 8);
628 }
629}
Owen Andersond8c87882011-02-18 21:51:29 +0000630
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000631// Emit table entries to decode instructions given a segment or segments
632// of bits.
633void Filter::emitTableEntry(DecoderTableInfo &TableInfo) const {
634 TableInfo.Table.push_back(MCD::OPC_ExtractField);
635 TableInfo.Table.push_back(StartBit);
636 TableInfo.Table.push_back(NumBits);
Owen Andersond8c87882011-02-18 21:51:29 +0000637
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000638 // A new filter entry begins a new scope for fixup resolution.
639 TableInfo.FixupStack.push_back(FixupList());
Owen Andersond8c87882011-02-18 21:51:29 +0000640
Craig Toppereb5cd612012-03-16 05:58:09 +0000641 std::map<unsigned, const FilterChooser*>::const_iterator filterIterator;
Owen Andersond8c87882011-02-18 21:51:29 +0000642
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000643 DecoderTable &Table = TableInfo.Table;
644
645 size_t PrevFilter = 0;
646 bool HasFallthrough = false;
Owen Andersond8c87882011-02-18 21:51:29 +0000647 for (filterIterator = FilterChooserMap.begin();
648 filterIterator != FilterChooserMap.end();
649 filterIterator++) {
Owen Andersond8c87882011-02-18 21:51:29 +0000650 // Field value -1 implies a non-empty set of variable instructions.
651 // See also recurse().
652 if (filterIterator->first == (unsigned)-1) {
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000653 HasFallthrough = true;
Owen Andersond8c87882011-02-18 21:51:29 +0000654
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000655 // Each scope should always have at least one filter value to check
656 // for.
657 assert(PrevFilter != 0 && "empty filter set!");
658 FixupList &CurScope = TableInfo.FixupStack.back();
659 // Resolve any NumToSkip fixups in the current scope.
660 resolveTableFixups(Table, CurScope, Table.size());
661 CurScope.clear();
662 PrevFilter = 0; // Don't re-process the filter's fallthrough.
663 } else {
664 Table.push_back(MCD::OPC_FilterValue);
665 // Encode and emit the value to filter against.
666 uint8_t Buffer[8];
667 unsigned Len = encodeULEB128(filterIterator->first, Buffer);
668 Table.insert(Table.end(), Buffer, Buffer + Len);
669 // Reserve space for the NumToSkip entry. We'll backpatch the value
670 // later.
671 PrevFilter = Table.size();
672 Table.push_back(0);
673 Table.push_back(0);
674 }
Owen Andersond8c87882011-02-18 21:51:29 +0000675
676 // We arrive at a category of instructions with the same segment value.
677 // Now delegate to the sub filter chooser for further decodings.
678 // The case may fallthrough, which happens if the remaining well-known
679 // encoding bits do not match exactly.
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000680 filterIterator->second->emitTableEntries(TableInfo);
Owen Andersond8c87882011-02-18 21:51:29 +0000681
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000682 // Now that we've emitted the body of the handler, update the NumToSkip
683 // of the filter itself to be able to skip forward when false. Subtract
684 // two as to account for the width of the NumToSkip field itself.
685 if (PrevFilter) {
686 uint32_t NumToSkip = Table.size() - PrevFilter - 2;
687 assert(NumToSkip < 65536U && "disassembler decoding table too large!");
688 Table[PrevFilter] = (uint8_t)NumToSkip;
689 Table[PrevFilter + 1] = (uint8_t)(NumToSkip >> 8);
690 }
Owen Andersond8c87882011-02-18 21:51:29 +0000691 }
692
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000693 // Any remaining unresolved fixups bubble up to the parent fixup scope.
694 assert(TableInfo.FixupStack.size() > 1 && "fixup stack underflow!");
695 FixupScopeList::iterator Source = TableInfo.FixupStack.end() - 1;
696 FixupScopeList::iterator Dest = Source - 1;
697 Dest->insert(Dest->end(), Source->begin(), Source->end());
698 TableInfo.FixupStack.pop_back();
699
700 // If there is no fallthrough, then the final filter should get fixed
701 // up according to the enclosing scope rather than the current position.
702 if (!HasFallthrough)
703 TableInfo.FixupStack.back().push_back(PrevFilter);
Owen Andersond8c87882011-02-18 21:51:29 +0000704}
705
706// Returns the number of fanout produced by the filter. More fanout implies
707// the filter distinguishes more categories of instructions.
708unsigned Filter::usefulness() const {
709 if (VariableInstructions.size())
710 return FilteredInstructions.size();
711 else
712 return FilteredInstructions.size() + 1;
713}
714
715//////////////////////////////////
716// //
717// Filterchooser Implementation //
718// //
719//////////////////////////////////
720
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000721// Emit the decoder state machine table.
722void FixedLenDecoderEmitter::emitTable(formatted_raw_ostream &OS,
723 DecoderTable &Table,
724 unsigned Indentation,
725 unsigned BitWidth,
726 StringRef Namespace) const {
727 OS.indent(Indentation) << "static const uint8_t DecoderTable" << Namespace
728 << BitWidth << "[] = {\n";
Owen Andersond8c87882011-02-18 21:51:29 +0000729
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000730 Indentation += 2;
Owen Andersond8c87882011-02-18 21:51:29 +0000731
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000732 // FIXME: We may be able to use the NumToSkip values to recover
733 // appropriate indentation levels.
734 DecoderTable::const_iterator I = Table.begin();
735 DecoderTable::const_iterator E = Table.end();
736 while (I != E) {
737 assert (I < E && "incomplete decode table entry!");
Owen Andersond8c87882011-02-18 21:51:29 +0000738
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000739 uint64_t Pos = I - Table.begin();
740 OS << "/* " << Pos << " */";
741 OS.PadToColumn(12);
Owen Andersond8c87882011-02-18 21:51:29 +0000742
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000743 switch (*I) {
744 default:
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000745 PrintFatalError("invalid decode table opcode");
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000746 case MCD::OPC_ExtractField: {
747 ++I;
748 unsigned Start = *I++;
749 unsigned Len = *I++;
750 OS.indent(Indentation) << "MCD::OPC_ExtractField, " << Start << ", "
751 << Len << ", // Inst{";
752 if (Len > 1)
753 OS << (Start + Len - 1) << "-";
754 OS << Start << "} ...\n";
755 break;
756 }
757 case MCD::OPC_FilterValue: {
758 ++I;
759 OS.indent(Indentation) << "MCD::OPC_FilterValue, ";
760 // The filter value is ULEB128 encoded.
761 while (*I >= 128)
762 OS << utostr(*I++) << ", ";
763 OS << utostr(*I++) << ", ";
764
765 // 16-bit numtoskip value.
766 uint8_t Byte = *I++;
767 uint32_t NumToSkip = Byte;
768 OS << utostr(Byte) << ", ";
769 Byte = *I++;
770 OS << utostr(Byte) << ", ";
771 NumToSkip |= Byte << 8;
772 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
773 break;
774 }
775 case MCD::OPC_CheckField: {
776 ++I;
777 unsigned Start = *I++;
778 unsigned Len = *I++;
779 OS.indent(Indentation) << "MCD::OPC_CheckField, " << Start << ", "
780 << Len << ", ";// << Val << ", " << NumToSkip << ",\n";
781 // ULEB128 encoded field value.
782 for (; *I >= 128; ++I)
783 OS << utostr(*I) << ", ";
784 OS << utostr(*I++) << ", ";
785 // 16-bit numtoskip value.
786 uint8_t Byte = *I++;
787 uint32_t NumToSkip = Byte;
788 OS << utostr(Byte) << ", ";
789 Byte = *I++;
790 OS << utostr(Byte) << ", ";
791 NumToSkip |= Byte << 8;
792 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
793 break;
794 }
795 case MCD::OPC_CheckPredicate: {
796 ++I;
797 OS.indent(Indentation) << "MCD::OPC_CheckPredicate, ";
798 for (; *I >= 128; ++I)
799 OS << utostr(*I) << ", ";
800 OS << utostr(*I++) << ", ";
801
802 // 16-bit numtoskip value.
803 uint8_t Byte = *I++;
804 uint32_t NumToSkip = Byte;
805 OS << utostr(Byte) << ", ";
806 Byte = *I++;
807 OS << utostr(Byte) << ", ";
808 NumToSkip |= Byte << 8;
809 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
810 break;
811 }
812 case MCD::OPC_Decode: {
813 ++I;
814 // Extract the ULEB128 encoded Opcode to a buffer.
815 uint8_t Buffer[8], *p = Buffer;
816 while ((*p++ = *I++) >= 128)
817 assert((p - Buffer) <= (ptrdiff_t)sizeof(Buffer)
818 && "ULEB128 value too large!");
819 // Decode the Opcode value.
820 unsigned Opc = decodeULEB128(Buffer);
821 OS.indent(Indentation) << "MCD::OPC_Decode, ";
822 for (p = Buffer; *p >= 128; ++p)
823 OS << utostr(*p) << ", ";
824 OS << utostr(*p) << ", ";
825
826 // Decoder index.
827 for (; *I >= 128; ++I)
828 OS << utostr(*I) << ", ";
829 OS << utostr(*I++) << ", ";
830
831 OS << "// Opcode: "
832 << NumberedInstructions->at(Opc)->TheDef->getName() << "\n";
833 break;
834 }
835 case MCD::OPC_SoftFail: {
836 ++I;
837 OS.indent(Indentation) << "MCD::OPC_SoftFail";
838 // Positive mask
839 uint64_t Value = 0;
840 unsigned Shift = 0;
841 do {
842 OS << ", " << utostr(*I);
843 Value += (*I & 0x7f) << Shift;
844 Shift += 7;
845 } while (*I++ >= 128);
846 if (Value > 127)
847 OS << " /* 0x" << utohexstr(Value) << " */";
848 // Negative mask
849 Value = 0;
850 Shift = 0;
851 do {
852 OS << ", " << utostr(*I);
853 Value += (*I & 0x7f) << Shift;
854 Shift += 7;
855 } while (*I++ >= 128);
856 if (Value > 127)
857 OS << " /* 0x" << utohexstr(Value) << " */";
858 OS << ",\n";
859 break;
860 }
861 case MCD::OPC_Fail: {
862 ++I;
863 OS.indent(Indentation) << "MCD::OPC_Fail,\n";
864 break;
865 }
866 }
867 }
868 OS.indent(Indentation) << "0\n";
869
870 Indentation -= 2;
871
872 OS.indent(Indentation) << "};\n\n";
873}
874
875void FixedLenDecoderEmitter::
876emitPredicateFunction(formatted_raw_ostream &OS, PredicateSet &Predicates,
877 unsigned Indentation) const {
878 // The predicate function is just a big switch statement based on the
879 // input predicate index.
880 OS.indent(Indentation) << "static bool checkDecoderPredicate(unsigned Idx, "
881 << "uint64_t Bits) {\n";
882 Indentation += 2;
883 OS.indent(Indentation) << "switch (Idx) {\n";
884 OS.indent(Indentation) << "default: llvm_unreachable(\"Invalid index!\");\n";
885 unsigned Index = 0;
886 for (PredicateSet::const_iterator I = Predicates.begin(), E = Predicates.end();
887 I != E; ++I, ++Index) {
888 OS.indent(Indentation) << "case " << Index << ":\n";
889 OS.indent(Indentation+2) << "return (" << *I << ");\n";
890 }
891 OS.indent(Indentation) << "}\n";
892 Indentation -= 2;
893 OS.indent(Indentation) << "}\n\n";
894}
895
896void FixedLenDecoderEmitter::
897emitDecoderFunction(formatted_raw_ostream &OS, DecoderSet &Decoders,
898 unsigned Indentation) const {
899 // The decoder function is just a big switch statement based on the
900 // input decoder index.
901 OS.indent(Indentation) << "template<typename InsnType>\n";
902 OS.indent(Indentation) << "static DecodeStatus decodeToMCInst(DecodeStatus S,"
903 << " unsigned Idx, InsnType insn, MCInst &MI,\n";
904 OS.indent(Indentation) << " uint64_t "
Benjamin Kramer95d235d2012-08-15 10:26:44 +0000905 << "Address, const void *Decoder) {\n";
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000906 Indentation += 2;
907 OS.indent(Indentation) << "InsnType tmp;\n";
908 OS.indent(Indentation) << "switch (Idx) {\n";
909 OS.indent(Indentation) << "default: llvm_unreachable(\"Invalid index!\");\n";
910 unsigned Index = 0;
911 for (DecoderSet::const_iterator I = Decoders.begin(), E = Decoders.end();
912 I != E; ++I, ++Index) {
913 OS.indent(Indentation) << "case " << Index << ":\n";
Craig Topperc0564832012-08-17 05:16:15 +0000914 OS << *I;
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000915 OS.indent(Indentation+2) << "return S;\n";
916 }
917 OS.indent(Indentation) << "}\n";
918 Indentation -= 2;
919 OS.indent(Indentation) << "}\n\n";
Owen Andersond8c87882011-02-18 21:51:29 +0000920}
921
922// Populates the field of the insn given the start position and the number of
923// consecutive bits to scan for.
924//
925// Returns false if and on the first uninitialized bit value encountered.
926// Returns true, otherwise.
927bool FilterChooser::fieldFromInsn(uint64_t &Field, insn_t &Insn,
Craig Toppereb5cd612012-03-16 05:58:09 +0000928 unsigned StartBit, unsigned NumBits) const {
Owen Andersond8c87882011-02-18 21:51:29 +0000929 Field = 0;
930
931 for (unsigned i = 0; i < NumBits; ++i) {
932 if (Insn[StartBit + i] == BIT_UNSET)
933 return false;
934
935 if (Insn[StartBit + i] == BIT_TRUE)
936 Field = Field | (1ULL << i);
937 }
938
939 return true;
940}
941
942/// dumpFilterArray - dumpFilterArray prints out debugging info for the given
943/// filter array as a series of chars.
944void FilterChooser::dumpFilterArray(raw_ostream &o,
Craig Toppereb5cd612012-03-16 05:58:09 +0000945 const std::vector<bit_value_t> &filter) const {
Craig Topper8cd9eae2012-08-17 05:42:16 +0000946 for (unsigned bitIndex = BitWidth; bitIndex > 0; bitIndex--) {
Owen Andersond8c87882011-02-18 21:51:29 +0000947 switch (filter[bitIndex - 1]) {
948 case BIT_UNFILTERED:
949 o << ".";
950 break;
951 case BIT_UNSET:
952 o << "_";
953 break;
954 case BIT_TRUE:
955 o << "1";
956 break;
957 case BIT_FALSE:
958 o << "0";
959 break;
960 }
961 }
962}
963
964/// dumpStack - dumpStack traverses the filter chooser chain and calls
965/// dumpFilterArray on each filter chooser up to the top level one.
Craig Toppereb5cd612012-03-16 05:58:09 +0000966void FilterChooser::dumpStack(raw_ostream &o, const char *prefix) const {
967 const FilterChooser *current = this;
Owen Andersond8c87882011-02-18 21:51:29 +0000968
969 while (current) {
970 o << prefix;
971 dumpFilterArray(o, current->FilterBitValues);
972 o << '\n';
973 current = current->Parent;
974 }
975}
976
977// Called from Filter::recurse() when singleton exists. For debug purpose.
Craig Toppereb5cd612012-03-16 05:58:09 +0000978void FilterChooser::SingletonExists(unsigned Opc) const {
Owen Andersond8c87882011-02-18 21:51:29 +0000979 insn_t Insn0;
980 insnWithID(Insn0, Opc);
981
982 errs() << "Singleton exists: " << nameWithID(Opc)
983 << " with its decoding dominating ";
984 for (unsigned i = 0; i < Opcodes.size(); ++i) {
985 if (Opcodes[i] == Opc) continue;
986 errs() << nameWithID(Opcodes[i]) << ' ';
987 }
988 errs() << '\n';
989
990 dumpStack(errs(), "\t\t");
Craig Topperd9360452012-03-16 01:19:24 +0000991 for (unsigned i = 0; i < Opcodes.size(); ++i) {
Owen Andersond8c87882011-02-18 21:51:29 +0000992 const std::string &Name = nameWithID(Opcodes[i]);
993
994 errs() << '\t' << Name << " ";
995 dumpBits(errs(),
996 getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
997 errs() << '\n';
998 }
999}
1000
1001// Calculates the island(s) needed to decode the instruction.
1002// This returns a list of undecoded bits of an instructions, for example,
1003// Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
1004// decoded bits in order to verify that the instruction matches the Opcode.
1005unsigned FilterChooser::getIslands(std::vector<unsigned> &StartBits,
Craig Topperd9360452012-03-16 01:19:24 +00001006 std::vector<unsigned> &EndBits,
1007 std::vector<uint64_t> &FieldVals,
Craig Toppereb5cd612012-03-16 05:58:09 +00001008 const insn_t &Insn) const {
Owen Andersond8c87882011-02-18 21:51:29 +00001009 unsigned Num, BitNo;
1010 Num = BitNo = 0;
1011
1012 uint64_t FieldVal = 0;
1013
1014 // 0: Init
1015 // 1: Water (the bit value does not affect decoding)
1016 // 2: Island (well-known bit value needed for decoding)
1017 int State = 0;
1018 int Val = -1;
1019
Owen Andersonf1a00902011-07-19 21:06:00 +00001020 for (unsigned i = 0; i < BitWidth; ++i) {
Owen Andersond8c87882011-02-18 21:51:29 +00001021 Val = Value(Insn[i]);
1022 bool Filtered = PositionFiltered(i);
1023 switch (State) {
Craig Topper655b8de2012-02-05 07:21:30 +00001024 default: llvm_unreachable("Unreachable code!");
Owen Andersond8c87882011-02-18 21:51:29 +00001025 case 0:
1026 case 1:
1027 if (Filtered || Val == -1)
1028 State = 1; // Still in Water
1029 else {
1030 State = 2; // Into the Island
1031 BitNo = 0;
1032 StartBits.push_back(i);
1033 FieldVal = Val;
1034 }
1035 break;
1036 case 2:
1037 if (Filtered || Val == -1) {
1038 State = 1; // Into the Water
1039 EndBits.push_back(i - 1);
1040 FieldVals.push_back(FieldVal);
1041 ++Num;
1042 } else {
1043 State = 2; // Still in Island
1044 ++BitNo;
1045 FieldVal = FieldVal | Val << BitNo;
1046 }
1047 break;
1048 }
1049 }
1050 // If we are still in Island after the loop, do some housekeeping.
1051 if (State == 2) {
Owen Andersonf1a00902011-07-19 21:06:00 +00001052 EndBits.push_back(BitWidth - 1);
Owen Andersond8c87882011-02-18 21:51:29 +00001053 FieldVals.push_back(FieldVal);
1054 ++Num;
1055 }
1056
1057 assert(StartBits.size() == Num && EndBits.size() == Num &&
1058 FieldVals.size() == Num);
1059 return Num;
1060}
1061
Owen Andersond1e38df2011-07-28 21:54:31 +00001062void FilterChooser::emitBinaryParser(raw_ostream &o, unsigned &Indentation,
Craig Toppereb5cd612012-03-16 05:58:09 +00001063 const OperandInfo &OpInfo) const {
1064 const std::string &Decoder = OpInfo.Decoder;
Owen Andersond1e38df2011-07-28 21:54:31 +00001065
1066 if (OpInfo.numFields() == 1) {
Craig Toppereb5cd612012-03-16 05:58:09 +00001067 OperandInfo::const_iterator OI = OpInfo.begin();
Craig Topperc0564832012-08-17 05:16:15 +00001068 o.indent(Indentation) << "tmp = fieldFromInstruction"
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001069 << "(insn, " << OI->Base << ", " << OI->Width
1070 << ");\n";
Owen Andersond1e38df2011-07-28 21:54:31 +00001071 } else {
Craig Topperc0564832012-08-17 05:16:15 +00001072 o.indent(Indentation) << "tmp = 0;\n";
Craig Toppereb5cd612012-03-16 05:58:09 +00001073 for (OperandInfo::const_iterator OI = OpInfo.begin(), OE = OpInfo.end();
Owen Andersond1e38df2011-07-28 21:54:31 +00001074 OI != OE; ++OI) {
Craig Topperc0564832012-08-17 05:16:15 +00001075 o.indent(Indentation) << "tmp |= (fieldFromInstruction"
Andrew Tricked968a92011-09-08 05:23:14 +00001076 << "(insn, " << OI->Base << ", " << OI->Width
Owen Andersond1e38df2011-07-28 21:54:31 +00001077 << ") << " << OI->Offset << ");\n";
1078 }
1079 }
1080
1081 if (Decoder != "")
Craig Topperc0564832012-08-17 05:16:15 +00001082 o.indent(Indentation) << Emitter->GuardPrefix << Decoder
Jim Grosbach9c826d22012-02-29 22:07:56 +00001083 << "(MI, tmp, Address, Decoder)"
1084 << Emitter->GuardPostfix << "\n";
Owen Andersond1e38df2011-07-28 21:54:31 +00001085 else
Craig Topperc0564832012-08-17 05:16:15 +00001086 o.indent(Indentation) << "MI.addOperand(MCOperand::CreateImm(tmp));\n";
Owen Andersond1e38df2011-07-28 21:54:31 +00001087
1088}
1089
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001090void FilterChooser::emitDecoder(raw_ostream &OS, unsigned Indentation,
1091 unsigned Opc) const {
1092 std::map<unsigned, std::vector<OperandInfo> >::const_iterator OpIter =
1093 Operands.find(Opc);
1094 const std::vector<OperandInfo>& InsnOperands = OpIter->second;
1095 for (std::vector<OperandInfo>::const_iterator
1096 I = InsnOperands.begin(), E = InsnOperands.end(); I != E; ++I) {
1097 // If a custom instruction decoder was specified, use that.
1098 if (I->numFields() == 0 && I->Decoder.size()) {
Craig Topperc0564832012-08-17 05:16:15 +00001099 OS.indent(Indentation) << Emitter->GuardPrefix << I->Decoder
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001100 << "(MI, insn, Address, Decoder)"
1101 << Emitter->GuardPostfix << "\n";
1102 break;
1103 }
1104
1105 emitBinaryParser(OS, Indentation, *I);
1106 }
1107}
1108
1109unsigned FilterChooser::getDecoderIndex(DecoderSet &Decoders,
1110 unsigned Opc) const {
1111 // Build up the predicate string.
1112 SmallString<256> Decoder;
1113 // FIXME: emitDecoder() function can take a buffer directly rather than
1114 // a stream.
1115 raw_svector_ostream S(Decoder);
Craig Topperc0564832012-08-17 05:16:15 +00001116 unsigned I = 4;
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001117 emitDecoder(S, I, Opc);
1118 S.flush();
1119
1120 // Using the full decoder string as the key value here is a bit
1121 // heavyweight, but is effective. If the string comparisons become a
1122 // performance concern, we can implement a mangling of the predicate
1123 // data easilly enough with a map back to the actual string. That's
1124 // overkill for now, though.
1125
1126 // Make sure the predicate is in the table.
1127 Decoders.insert(Decoder.str());
1128 // Now figure out the index for when we write out the table.
1129 DecoderSet::const_iterator P = std::find(Decoders.begin(),
1130 Decoders.end(),
1131 Decoder.str());
1132 return (unsigned)(P - Decoders.begin());
1133}
1134
James Molloya5d58562011-09-07 19:42:28 +00001135static void emitSinglePredicateMatch(raw_ostream &o, StringRef str,
Craig Toppereb5cd612012-03-16 05:58:09 +00001136 const std::string &PredicateNamespace) {
Andrew Trick22b4c812011-09-08 05:25:49 +00001137 if (str[0] == '!')
1138 o << "!(Bits & " << PredicateNamespace << "::"
1139 << str.slice(1,str.size()) << ")";
James Molloya5d58562011-09-07 19:42:28 +00001140 else
Andrew Trick22b4c812011-09-08 05:25:49 +00001141 o << "(Bits & " << PredicateNamespace << "::" << str << ")";
James Molloya5d58562011-09-07 19:42:28 +00001142}
1143
1144bool FilterChooser::emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
Craig Toppereb5cd612012-03-16 05:58:09 +00001145 unsigned Opc) const {
Jim Grosbach9c826d22012-02-29 22:07:56 +00001146 ListInit *Predicates =
1147 AllInstructions[Opc]->TheDef->getValueAsListInit("Predicates");
James Molloya5d58562011-09-07 19:42:28 +00001148 for (unsigned i = 0; i < Predicates->getSize(); ++i) {
1149 Record *Pred = Predicates->getElementAsRecord(i);
1150 if (!Pred->getValue("AssemblerMatcherPredicate"))
1151 continue;
1152
1153 std::string P = Pred->getValueAsString("AssemblerCondString");
1154
1155 if (!P.length())
1156 continue;
1157
1158 if (i != 0)
1159 o << " && ";
1160
1161 StringRef SR(P);
1162 std::pair<StringRef, StringRef> pairs = SR.split(',');
1163 while (pairs.second.size()) {
1164 emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
1165 o << " && ";
1166 pairs = pairs.second.split(',');
1167 }
1168 emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
1169 }
1170 return Predicates->getSize() > 0;
Andrew Tricked968a92011-09-08 05:23:14 +00001171}
James Molloya5d58562011-09-07 19:42:28 +00001172
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001173bool FilterChooser::doesOpcodeNeedPredicate(unsigned Opc) const {
1174 ListInit *Predicates =
1175 AllInstructions[Opc]->TheDef->getValueAsListInit("Predicates");
1176 for (unsigned i = 0; i < Predicates->getSize(); ++i) {
1177 Record *Pred = Predicates->getElementAsRecord(i);
1178 if (!Pred->getValue("AssemblerMatcherPredicate"))
1179 continue;
1180
1181 std::string P = Pred->getValueAsString("AssemblerCondString");
1182
1183 if (!P.length())
1184 continue;
1185
1186 return true;
1187 }
1188 return false;
1189}
1190
1191unsigned FilterChooser::getPredicateIndex(DecoderTableInfo &TableInfo,
1192 StringRef Predicate) const {
1193 // Using the full predicate string as the key value here is a bit
1194 // heavyweight, but is effective. If the string comparisons become a
1195 // performance concern, we can implement a mangling of the predicate
1196 // data easilly enough with a map back to the actual string. That's
1197 // overkill for now, though.
1198
1199 // Make sure the predicate is in the table.
1200 TableInfo.Predicates.insert(Predicate.str());
1201 // Now figure out the index for when we write out the table.
1202 PredicateSet::const_iterator P = std::find(TableInfo.Predicates.begin(),
1203 TableInfo.Predicates.end(),
1204 Predicate.str());
1205 return (unsigned)(P - TableInfo.Predicates.begin());
1206}
1207
1208void FilterChooser::emitPredicateTableEntry(DecoderTableInfo &TableInfo,
1209 unsigned Opc) const {
1210 if (!doesOpcodeNeedPredicate(Opc))
1211 return;
1212
1213 // Build up the predicate string.
1214 SmallString<256> Predicate;
1215 // FIXME: emitPredicateMatch() functions can take a buffer directly rather
1216 // than a stream.
1217 raw_svector_ostream PS(Predicate);
1218 unsigned I = 0;
1219 emitPredicateMatch(PS, I, Opc);
1220
1221 // Figure out the index into the predicate table for the predicate just
1222 // computed.
1223 unsigned PIdx = getPredicateIndex(TableInfo, PS.str());
1224 SmallString<16> PBytes;
1225 raw_svector_ostream S(PBytes);
1226 encodeULEB128(PIdx, S);
1227 S.flush();
1228
1229 TableInfo.Table.push_back(MCD::OPC_CheckPredicate);
1230 // Predicate index
Craig Topper8cd9eae2012-08-17 05:42:16 +00001231 for (unsigned i = 0, e = PBytes.size(); i != e; ++i)
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001232 TableInfo.Table.push_back(PBytes[i]);
1233 // Push location for NumToSkip backpatching.
1234 TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
1235 TableInfo.Table.push_back(0);
1236 TableInfo.Table.push_back(0);
1237}
1238
1239void FilterChooser::emitSoftFailTableEntry(DecoderTableInfo &TableInfo,
1240 unsigned Opc) const {
Jim Grosbach9c826d22012-02-29 22:07:56 +00001241 BitsInit *SFBits =
1242 AllInstructions[Opc]->TheDef->getValueAsBitsInit("SoftFail");
James Molloy3015dfb2012-02-09 10:56:31 +00001243 if (!SFBits) return;
1244 BitsInit *InstBits = AllInstructions[Opc]->TheDef->getValueAsBitsInit("Inst");
1245
1246 APInt PositiveMask(BitWidth, 0ULL);
1247 APInt NegativeMask(BitWidth, 0ULL);
1248 for (unsigned i = 0; i < BitWidth; ++i) {
1249 bit_value_t B = bitFromBits(*SFBits, i);
1250 bit_value_t IB = bitFromBits(*InstBits, i);
1251
1252 if (B != BIT_TRUE) continue;
1253
1254 switch (IB) {
1255 case BIT_FALSE:
1256 // The bit is meant to be false, so emit a check to see if it is true.
1257 PositiveMask.setBit(i);
1258 break;
1259 case BIT_TRUE:
1260 // The bit is meant to be true, so emit a check to see if it is false.
1261 NegativeMask.setBit(i);
1262 break;
1263 default:
1264 // The bit is not set; this must be an error!
1265 StringRef Name = AllInstructions[Opc]->TheDef->getName();
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001266 errs() << "SoftFail Conflict: bit SoftFail{" << i << "} in " << Name
1267 << " is set but Inst{" << i << "} is unset!\n"
James Molloy3015dfb2012-02-09 10:56:31 +00001268 << " - You can only mark a bit as SoftFail if it is fully defined"
1269 << " (1/0 - not '?') in Inst\n";
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001270 return;
James Molloy3015dfb2012-02-09 10:56:31 +00001271 }
1272 }
1273
1274 bool NeedPositiveMask = PositiveMask.getBoolValue();
1275 bool NeedNegativeMask = NegativeMask.getBoolValue();
1276
1277 if (!NeedPositiveMask && !NeedNegativeMask)
1278 return;
1279
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001280 TableInfo.Table.push_back(MCD::OPC_SoftFail);
James Molloy3015dfb2012-02-09 10:56:31 +00001281
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001282 SmallString<16> MaskBytes;
1283 raw_svector_ostream S(MaskBytes);
1284 if (NeedPositiveMask) {
1285 encodeULEB128(PositiveMask.getZExtValue(), S);
1286 S.flush();
Craig Topper8cd9eae2012-08-17 05:42:16 +00001287 for (unsigned i = 0, e = MaskBytes.size(); i != e; ++i)
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001288 TableInfo.Table.push_back(MaskBytes[i]);
1289 } else
1290 TableInfo.Table.push_back(0);
1291 if (NeedNegativeMask) {
1292 MaskBytes.clear();
1293 S.resync();
1294 encodeULEB128(NegativeMask.getZExtValue(), S);
1295 S.flush();
Craig Topper8cd9eae2012-08-17 05:42:16 +00001296 for (unsigned i = 0, e = MaskBytes.size(); i != e; ++i)
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001297 TableInfo.Table.push_back(MaskBytes[i]);
1298 } else
1299 TableInfo.Table.push_back(0);
James Molloy3015dfb2012-02-09 10:56:31 +00001300}
1301
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001302// Emits table entries to decode the singleton.
1303void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,
1304 unsigned Opc) const {
Owen Andersond8c87882011-02-18 21:51:29 +00001305 std::vector<unsigned> StartBits;
1306 std::vector<unsigned> EndBits;
1307 std::vector<uint64_t> FieldVals;
1308 insn_t Insn;
1309 insnWithID(Insn, Opc);
1310
1311 // Look for islands of undecoded bits of the singleton.
1312 getIslands(StartBits, EndBits, FieldVals, Insn);
1313
1314 unsigned Size = StartBits.size();
Owen Andersond8c87882011-02-18 21:51:29 +00001315
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001316 // Emit the predicate table entry if one is needed.
1317 emitPredicateTableEntry(TableInfo, Opc);
Owen Andersond8c87882011-02-18 21:51:29 +00001318
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001319 // Check any additional encoding fields needed.
Craig Topper8cd9eae2012-08-17 05:42:16 +00001320 for (unsigned I = Size; I != 0; --I) {
1321 unsigned NumBits = EndBits[I-1] - StartBits[I-1] + 1;
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001322 TableInfo.Table.push_back(MCD::OPC_CheckField);
1323 TableInfo.Table.push_back(StartBits[I-1]);
1324 TableInfo.Table.push_back(NumBits);
1325 uint8_t Buffer[8], *p;
1326 encodeULEB128(FieldVals[I-1], Buffer);
1327 for (p = Buffer; *p >= 128 ; ++p)
1328 TableInfo.Table.push_back(*p);
1329 TableInfo.Table.push_back(*p);
1330 // Push location for NumToSkip backpatching.
1331 TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
1332 // The fixup is always 16-bits, so go ahead and allocate the space
1333 // in the table so all our relative position calculations work OK even
1334 // before we fully resolve the real value here.
1335 TableInfo.Table.push_back(0);
1336 TableInfo.Table.push_back(0);
Owen Andersond8c87882011-02-18 21:51:29 +00001337 }
Owen Andersond8c87882011-02-18 21:51:29 +00001338
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001339 // Check for soft failure of the match.
1340 emitSoftFailTableEntry(TableInfo, Opc);
Owen Andersond8c87882011-02-18 21:51:29 +00001341
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001342 TableInfo.Table.push_back(MCD::OPC_Decode);
1343 uint8_t Buffer[8], *p;
1344 encodeULEB128(Opc, Buffer);
1345 for (p = Buffer; *p >= 128 ; ++p)
1346 TableInfo.Table.push_back(*p);
1347 TableInfo.Table.push_back(*p);
1348
1349 unsigned DIdx = getDecoderIndex(TableInfo.Decoders, Opc);
1350 SmallString<16> Bytes;
1351 raw_svector_ostream S(Bytes);
1352 encodeULEB128(DIdx, S);
1353 S.flush();
1354
1355 // Decoder index
Craig Topper8cd9eae2012-08-17 05:42:16 +00001356 for (unsigned i = 0, e = Bytes.size(); i != e; ++i)
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001357 TableInfo.Table.push_back(Bytes[i]);
Owen Andersond8c87882011-02-18 21:51:29 +00001358}
1359
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001360// Emits table entries to decode the singleton, and then to decode the rest.
1361void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,
1362 const Filter &Best) const {
Owen Andersond8c87882011-02-18 21:51:29 +00001363 unsigned Opc = Best.getSingletonOpc();
1364
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001365 // complex singletons need predicate checks from the first singleton
1366 // to refer forward to the variable filterchooser that follows.
1367 TableInfo.FixupStack.push_back(FixupList());
Owen Andersond8c87882011-02-18 21:51:29 +00001368
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001369 emitSingletonTableEntry(TableInfo, Opc);
Owen Andersond8c87882011-02-18 21:51:29 +00001370
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001371 resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),
1372 TableInfo.Table.size());
1373 TableInfo.FixupStack.pop_back();
1374
1375 Best.getVariableFC().emitTableEntries(TableInfo);
Owen Andersond8c87882011-02-18 21:51:29 +00001376}
1377
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001378
Owen Andersond8c87882011-02-18 21:51:29 +00001379// Assign a single filter and run with it. Top level API client can initialize
1380// with a single filter to start the filtering process.
Craig Toppereb5cd612012-03-16 05:58:09 +00001381void FilterChooser::runSingleFilter(unsigned startBit, unsigned numBit,
1382 bool mixed) {
Owen Andersond8c87882011-02-18 21:51:29 +00001383 Filters.clear();
1384 Filter F(*this, startBit, numBit, true);
1385 Filters.push_back(F);
1386 BestIndex = 0; // Sole Filter instance to choose from.
1387 bestFilter().recurse();
1388}
1389
1390// reportRegion is a helper function for filterProcessor to mark a region as
1391// eligible for use as a filter region.
1392void FilterChooser::reportRegion(bitAttr_t RA, unsigned StartBit,
Craig Topperd9360452012-03-16 01:19:24 +00001393 unsigned BitIndex, bool AllowMixed) {
Owen Andersond8c87882011-02-18 21:51:29 +00001394 if (RA == ATTR_MIXED && AllowMixed)
1395 Filters.push_back(Filter(*this, StartBit, BitIndex - StartBit, true));
1396 else if (RA == ATTR_ALL_SET && !AllowMixed)
1397 Filters.push_back(Filter(*this, StartBit, BitIndex - StartBit, false));
1398}
1399
1400// FilterProcessor scans the well-known encoding bits of the instructions and
1401// builds up a list of candidate filters. It chooses the best filter and
1402// recursively descends down the decoding tree.
1403bool FilterChooser::filterProcessor(bool AllowMixed, bool Greedy) {
1404 Filters.clear();
1405 BestIndex = -1;
1406 unsigned numInstructions = Opcodes.size();
1407
1408 assert(numInstructions && "Filter created with no instructions");
1409
1410 // No further filtering is necessary.
1411 if (numInstructions == 1)
1412 return true;
1413
1414 // Heuristics. See also doFilter()'s "Heuristics" comment when num of
1415 // instructions is 3.
1416 if (AllowMixed && !Greedy) {
1417 assert(numInstructions == 3);
1418
1419 for (unsigned i = 0; i < Opcodes.size(); ++i) {
1420 std::vector<unsigned> StartBits;
1421 std::vector<unsigned> EndBits;
1422 std::vector<uint64_t> FieldVals;
1423 insn_t Insn;
1424
1425 insnWithID(Insn, Opcodes[i]);
1426
1427 // Look for islands of undecoded bits of any instruction.
1428 if (getIslands(StartBits, EndBits, FieldVals, Insn) > 0) {
1429 // Found an instruction with island(s). Now just assign a filter.
Craig Toppereb5cd612012-03-16 05:58:09 +00001430 runSingleFilter(StartBits[0], EndBits[0] - StartBits[0] + 1, true);
Owen Andersond8c87882011-02-18 21:51:29 +00001431 return true;
1432 }
1433 }
1434 }
1435
Craig Topper8cd9eae2012-08-17 05:42:16 +00001436 unsigned BitIndex;
Owen Andersond8c87882011-02-18 21:51:29 +00001437
1438 // We maintain BIT_WIDTH copies of the bitAttrs automaton.
1439 // The automaton consumes the corresponding bit from each
1440 // instruction.
1441 //
1442 // Input symbols: 0, 1, and _ (unset).
1443 // States: NONE, FILTERED, ALL_SET, ALL_UNSET, and MIXED.
1444 // Initial state: NONE.
1445 //
1446 // (NONE) ------- [01] -> (ALL_SET)
1447 // (NONE) ------- _ ----> (ALL_UNSET)
1448 // (ALL_SET) ---- [01] -> (ALL_SET)
1449 // (ALL_SET) ---- _ ----> (MIXED)
1450 // (ALL_UNSET) -- [01] -> (MIXED)
1451 // (ALL_UNSET) -- _ ----> (ALL_UNSET)
1452 // (MIXED) ------ . ----> (MIXED)
1453 // (FILTERED)---- . ----> (FILTERED)
1454
Owen Andersonf1a00902011-07-19 21:06:00 +00001455 std::vector<bitAttr_t> bitAttrs;
Owen Andersond8c87882011-02-18 21:51:29 +00001456
1457 // FILTERED bit positions provide no entropy and are not worthy of pursuing.
1458 // Filter::recurse() set either BIT_TRUE or BIT_FALSE for each position.
Owen Andersonf1a00902011-07-19 21:06:00 +00001459 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex)
Owen Andersond8c87882011-02-18 21:51:29 +00001460 if (FilterBitValues[BitIndex] == BIT_TRUE ||
1461 FilterBitValues[BitIndex] == BIT_FALSE)
Owen Andersonf1a00902011-07-19 21:06:00 +00001462 bitAttrs.push_back(ATTR_FILTERED);
Owen Andersond8c87882011-02-18 21:51:29 +00001463 else
Owen Andersonf1a00902011-07-19 21:06:00 +00001464 bitAttrs.push_back(ATTR_NONE);
Owen Andersond8c87882011-02-18 21:51:29 +00001465
Craig Topper8cd9eae2012-08-17 05:42:16 +00001466 for (unsigned InsnIndex = 0; InsnIndex < numInstructions; ++InsnIndex) {
Owen Andersond8c87882011-02-18 21:51:29 +00001467 insn_t insn;
1468
1469 insnWithID(insn, Opcodes[InsnIndex]);
1470
Owen Andersonf1a00902011-07-19 21:06:00 +00001471 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
Owen Andersond8c87882011-02-18 21:51:29 +00001472 switch (bitAttrs[BitIndex]) {
1473 case ATTR_NONE:
1474 if (insn[BitIndex] == BIT_UNSET)
1475 bitAttrs[BitIndex] = ATTR_ALL_UNSET;
1476 else
1477 bitAttrs[BitIndex] = ATTR_ALL_SET;
1478 break;
1479 case ATTR_ALL_SET:
1480 if (insn[BitIndex] == BIT_UNSET)
1481 bitAttrs[BitIndex] = ATTR_MIXED;
1482 break;
1483 case ATTR_ALL_UNSET:
1484 if (insn[BitIndex] != BIT_UNSET)
1485 bitAttrs[BitIndex] = ATTR_MIXED;
1486 break;
1487 case ATTR_MIXED:
1488 case ATTR_FILTERED:
1489 break;
1490 }
1491 }
1492 }
1493
1494 // The regionAttr automaton consumes the bitAttrs automatons' state,
1495 // lowest-to-highest.
1496 //
1497 // Input symbols: F(iltered), (all_)S(et), (all_)U(nset), M(ixed)
1498 // States: NONE, ALL_SET, MIXED
1499 // Initial state: NONE
1500 //
1501 // (NONE) ----- F --> (NONE)
1502 // (NONE) ----- S --> (ALL_SET) ; and set region start
1503 // (NONE) ----- U --> (NONE)
1504 // (NONE) ----- M --> (MIXED) ; and set region start
1505 // (ALL_SET) -- F --> (NONE) ; and report an ALL_SET region
1506 // (ALL_SET) -- S --> (ALL_SET)
1507 // (ALL_SET) -- U --> (NONE) ; and report an ALL_SET region
1508 // (ALL_SET) -- M --> (MIXED) ; and report an ALL_SET region
1509 // (MIXED) ---- F --> (NONE) ; and report a MIXED region
1510 // (MIXED) ---- S --> (ALL_SET) ; and report a MIXED region
1511 // (MIXED) ---- U --> (NONE) ; and report a MIXED region
1512 // (MIXED) ---- M --> (MIXED)
1513
1514 bitAttr_t RA = ATTR_NONE;
1515 unsigned StartBit = 0;
1516
Craig Topper8cd9eae2012-08-17 05:42:16 +00001517 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
Owen Andersond8c87882011-02-18 21:51:29 +00001518 bitAttr_t bitAttr = bitAttrs[BitIndex];
1519
1520 assert(bitAttr != ATTR_NONE && "Bit without attributes");
1521
1522 switch (RA) {
1523 case ATTR_NONE:
1524 switch (bitAttr) {
1525 case ATTR_FILTERED:
1526 break;
1527 case ATTR_ALL_SET:
1528 StartBit = BitIndex;
1529 RA = ATTR_ALL_SET;
1530 break;
1531 case ATTR_ALL_UNSET:
1532 break;
1533 case ATTR_MIXED:
1534 StartBit = BitIndex;
1535 RA = ATTR_MIXED;
1536 break;
1537 default:
Craig Topper655b8de2012-02-05 07:21:30 +00001538 llvm_unreachable("Unexpected bitAttr!");
Owen Andersond8c87882011-02-18 21:51:29 +00001539 }
1540 break;
1541 case ATTR_ALL_SET:
1542 switch (bitAttr) {
1543 case ATTR_FILTERED:
1544 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1545 RA = ATTR_NONE;
1546 break;
1547 case ATTR_ALL_SET:
1548 break;
1549 case ATTR_ALL_UNSET:
1550 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1551 RA = ATTR_NONE;
1552 break;
1553 case ATTR_MIXED:
1554 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1555 StartBit = BitIndex;
1556 RA = ATTR_MIXED;
1557 break;
1558 default:
Craig Topper655b8de2012-02-05 07:21:30 +00001559 llvm_unreachable("Unexpected bitAttr!");
Owen Andersond8c87882011-02-18 21:51:29 +00001560 }
1561 break;
1562 case ATTR_MIXED:
1563 switch (bitAttr) {
1564 case ATTR_FILTERED:
1565 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1566 StartBit = BitIndex;
1567 RA = ATTR_NONE;
1568 break;
1569 case ATTR_ALL_SET:
1570 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1571 StartBit = BitIndex;
1572 RA = ATTR_ALL_SET;
1573 break;
1574 case ATTR_ALL_UNSET:
1575 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1576 RA = ATTR_NONE;
1577 break;
1578 case ATTR_MIXED:
1579 break;
1580 default:
Craig Topper655b8de2012-02-05 07:21:30 +00001581 llvm_unreachable("Unexpected bitAttr!");
Owen Andersond8c87882011-02-18 21:51:29 +00001582 }
1583 break;
1584 case ATTR_ALL_UNSET:
Craig Topper655b8de2012-02-05 07:21:30 +00001585 llvm_unreachable("regionAttr state machine has no ATTR_UNSET state");
Owen Andersond8c87882011-02-18 21:51:29 +00001586 case ATTR_FILTERED:
Craig Topper655b8de2012-02-05 07:21:30 +00001587 llvm_unreachable("regionAttr state machine has no ATTR_FILTERED state");
Owen Andersond8c87882011-02-18 21:51:29 +00001588 }
1589 }
1590
1591 // At the end, if we're still in ALL_SET or MIXED states, report a region
1592 switch (RA) {
1593 case ATTR_NONE:
1594 break;
1595 case ATTR_FILTERED:
1596 break;
1597 case ATTR_ALL_SET:
1598 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1599 break;
1600 case ATTR_ALL_UNSET:
1601 break;
1602 case ATTR_MIXED:
1603 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1604 break;
1605 }
1606
1607 // We have finished with the filter processings. Now it's time to choose
1608 // the best performing filter.
1609 BestIndex = 0;
1610 bool AllUseless = true;
1611 unsigned BestScore = 0;
1612
1613 for (unsigned i = 0, e = Filters.size(); i != e; ++i) {
1614 unsigned Usefulness = Filters[i].usefulness();
1615
1616 if (Usefulness)
1617 AllUseless = false;
1618
1619 if (Usefulness > BestScore) {
1620 BestIndex = i;
1621 BestScore = Usefulness;
1622 }
1623 }
1624
1625 if (!AllUseless)
1626 bestFilter().recurse();
1627
1628 return !AllUseless;
1629} // end of FilterChooser::filterProcessor(bool)
1630
1631// Decides on the best configuration of filter(s) to use in order to decode
1632// the instructions. A conflict of instructions may occur, in which case we
1633// dump the conflict set to the standard error.
1634void FilterChooser::doFilter() {
1635 unsigned Num = Opcodes.size();
1636 assert(Num && "FilterChooser created with no instructions");
1637
1638 // Try regions of consecutive known bit values first.
1639 if (filterProcessor(false))
1640 return;
1641
1642 // Then regions of mixed bits (both known and unitialized bit values allowed).
1643 if (filterProcessor(true))
1644 return;
1645
1646 // Heuristics to cope with conflict set {t2CMPrs, t2SUBSrr, t2SUBSrs} where
1647 // no single instruction for the maximum ATTR_MIXED region Inst{14-4} has a
1648 // well-known encoding pattern. In such case, we backtrack and scan for the
1649 // the very first consecutive ATTR_ALL_SET region and assign a filter to it.
1650 if (Num == 3 && filterProcessor(true, false))
1651 return;
1652
1653 // If we come to here, the instruction decoding has failed.
1654 // Set the BestIndex to -1 to indicate so.
1655 BestIndex = -1;
1656}
1657
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001658// emitTableEntries - Emit state machine entries to decode our share of
1659// instructions.
1660void FilterChooser::emitTableEntries(DecoderTableInfo &TableInfo) const {
1661 if (Opcodes.size() == 1) {
Owen Andersond8c87882011-02-18 21:51:29 +00001662 // There is only one instruction in the set, which is great!
1663 // Call emitSingletonDecoder() to see whether there are any remaining
1664 // encodings bits.
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001665 emitSingletonTableEntry(TableInfo, Opcodes[0]);
1666 return;
1667 }
Owen Andersond8c87882011-02-18 21:51:29 +00001668
1669 // Choose the best filter to do the decodings!
1670 if (BestIndex != -1) {
Craig Toppereb5cd612012-03-16 05:58:09 +00001671 const Filter &Best = Filters[BestIndex];
Owen Andersond8c87882011-02-18 21:51:29 +00001672 if (Best.getNumFiltered() == 1)
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001673 emitSingletonTableEntry(TableInfo, Best);
Owen Andersond8c87882011-02-18 21:51:29 +00001674 else
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001675 Best.emitTableEntry(TableInfo);
1676 return;
Owen Andersond8c87882011-02-18 21:51:29 +00001677 }
1678
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001679 // We don't know how to decode these instructions! Dump the
1680 // conflict set and bail.
Owen Andersond8c87882011-02-18 21:51:29 +00001681
1682 // Print out useful conflict information for postmortem analysis.
1683 errs() << "Decoding Conflict:\n";
1684
1685 dumpStack(errs(), "\t\t");
1686
Craig Topperd9360452012-03-16 01:19:24 +00001687 for (unsigned i = 0; i < Opcodes.size(); ++i) {
Owen Andersond8c87882011-02-18 21:51:29 +00001688 const std::string &Name = nameWithID(Opcodes[i]);
1689
1690 errs() << '\t' << Name << " ";
1691 dumpBits(errs(),
1692 getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
1693 errs() << '\n';
1694 }
Owen Andersond8c87882011-02-18 21:51:29 +00001695}
1696
Craig Topperd9360452012-03-16 01:19:24 +00001697static bool populateInstruction(const CodeGenInstruction &CGI, unsigned Opc,
1698 std::map<unsigned, std::vector<OperandInfo> > &Operands){
Owen Andersond8c87882011-02-18 21:51:29 +00001699 const Record &Def = *CGI.TheDef;
1700 // If all the bit positions are not specified; do not decode this instruction.
1701 // We are bound to fail! For proper disassembly, the well-known encoding bits
1702 // of the instruction must be fully specified.
1703 //
1704 // This also removes pseudo instructions from considerations of disassembly,
1705 // which is a better design and less fragile than the name matchings.
Owen Andersond8c87882011-02-18 21:51:29 +00001706 // Ignore "asm parser only" instructions.
Owen Anderson4dd27eb2011-03-14 20:58:49 +00001707 if (Def.getValueAsBit("isAsmParserOnly") ||
1708 Def.getValueAsBit("isCodeGenOnly"))
Owen Andersond8c87882011-02-18 21:51:29 +00001709 return false;
1710
David Greene05bce0b2011-07-29 22:43:06 +00001711 BitsInit &Bits = getBitsField(Def, "Inst");
Jim Grosbach806fcc02011-07-06 21:33:38 +00001712 if (Bits.allInComplete()) return false;
1713
Owen Andersond8c87882011-02-18 21:51:29 +00001714 std::vector<OperandInfo> InsnOperands;
1715
1716 // If the instruction has specified a custom decoding hook, use that instead
1717 // of trying to auto-generate the decoder.
1718 std::string InstDecoder = Def.getValueAsString("DecoderMethod");
1719 if (InstDecoder != "") {
Owen Andersond1e38df2011-07-28 21:54:31 +00001720 InsnOperands.push_back(OperandInfo(InstDecoder));
Owen Andersond8c87882011-02-18 21:51:29 +00001721 Operands[Opc] = InsnOperands;
1722 return true;
1723 }
1724
1725 // Generate a description of the operand of the instruction that we know
1726 // how to decode automatically.
1727 // FIXME: We'll need to have a way to manually override this as needed.
1728
1729 // Gather the outputs/inputs of the instruction, so we can find their
1730 // positions in the encoding. This assumes for now that they appear in the
1731 // MCInst in the order that they're listed.
David Greene05bce0b2011-07-29 22:43:06 +00001732 std::vector<std::pair<Init*, std::string> > InOutOperands;
1733 DagInit *Out = Def.getValueAsDag("OutOperandList");
1734 DagInit *In = Def.getValueAsDag("InOperandList");
Owen Andersond8c87882011-02-18 21:51:29 +00001735 for (unsigned i = 0; i < Out->getNumArgs(); ++i)
1736 InOutOperands.push_back(std::make_pair(Out->getArg(i), Out->getArgName(i)));
1737 for (unsigned i = 0; i < In->getNumArgs(); ++i)
1738 InOutOperands.push_back(std::make_pair(In->getArg(i), In->getArgName(i)));
1739
Owen Anderson00ef6e32011-07-28 23:56:20 +00001740 // Search for tied operands, so that we can correctly instantiate
1741 // operands that are not explicitly represented in the encoding.
Owen Andersonea242982011-07-29 18:28:52 +00001742 std::map<std::string, std::string> TiedNames;
Owen Anderson00ef6e32011-07-28 23:56:20 +00001743 for (unsigned i = 0; i < CGI.Operands.size(); ++i) {
1744 int tiedTo = CGI.Operands[i].getTiedRegister();
Owen Andersonea242982011-07-29 18:28:52 +00001745 if (tiedTo != -1) {
1746 TiedNames[InOutOperands[i].second] = InOutOperands[tiedTo].second;
1747 TiedNames[InOutOperands[tiedTo].second] = InOutOperands[i].second;
1748 }
Owen Anderson00ef6e32011-07-28 23:56:20 +00001749 }
1750
Owen Andersond8c87882011-02-18 21:51:29 +00001751 // For each operand, see if we can figure out where it is encoded.
Craig Topper5a4c7902012-03-16 06:52:56 +00001752 for (std::vector<std::pair<Init*, std::string> >::const_iterator
Owen Andersond8c87882011-02-18 21:51:29 +00001753 NI = InOutOperands.begin(), NE = InOutOperands.end(); NI != NE; ++NI) {
Owen Andersond8c87882011-02-18 21:51:29 +00001754 std::string Decoder = "";
1755
Owen Andersond1e38df2011-07-28 21:54:31 +00001756 // At this point, we can locate the field, but we need to know how to
1757 // interpret it. As a first step, require the target to provide callbacks
1758 // for decoding register classes.
1759 // FIXME: This need to be extended to handle instructions with custom
1760 // decoder methods, and operands with (simple) MIOperandInfo's.
Sean Silva3f7b7f82012-10-10 20:24:47 +00001761 TypedInit *TI = cast<TypedInit>(NI->first);
1762 RecordRecTy *Type = cast<RecordRecTy>(TI->getType());
Owen Andersond1e38df2011-07-28 21:54:31 +00001763 Record *TypeRecord = Type->getRecord();
1764 bool isReg = false;
1765 if (TypeRecord->isSubClassOf("RegisterOperand"))
1766 TypeRecord = TypeRecord->getValueAsDef("RegClass");
1767 if (TypeRecord->isSubClassOf("RegisterClass")) {
1768 Decoder = "Decode" + TypeRecord->getName() + "RegisterClass";
1769 isReg = true;
1770 }
1771
1772 RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod");
David Greene05bce0b2011-07-29 22:43:06 +00001773 StringInit *String = DecoderString ?
Sean Silva6cfc8062012-10-10 20:24:43 +00001774 dyn_cast<StringInit>(DecoderString->getValue()) : 0;
Owen Andersond1e38df2011-07-28 21:54:31 +00001775 if (!isReg && String && String->getValue() != "")
1776 Decoder = String->getValue();
1777
1778 OperandInfo OpInfo(Decoder);
1779 unsigned Base = ~0U;
1780 unsigned Width = 0;
1781 unsigned Offset = 0;
1782
Owen Andersond8c87882011-02-18 21:51:29 +00001783 for (unsigned bi = 0; bi < Bits.getNumBits(); ++bi) {
Owen Andersoncf603952011-08-01 22:45:43 +00001784 VarInit *Var = 0;
Sean Silva6cfc8062012-10-10 20:24:43 +00001785 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
Owen Andersoncf603952011-08-01 22:45:43 +00001786 if (BI)
Sean Silva6cfc8062012-10-10 20:24:43 +00001787 Var = dyn_cast<VarInit>(BI->getBitVar());
Owen Andersoncf603952011-08-01 22:45:43 +00001788 else
Sean Silva6cfc8062012-10-10 20:24:43 +00001789 Var = dyn_cast<VarInit>(Bits.getBit(bi));
Owen Andersoncf603952011-08-01 22:45:43 +00001790
1791 if (!Var) {
Owen Andersond1e38df2011-07-28 21:54:31 +00001792 if (Base != ~0U) {
1793 OpInfo.addField(Base, Width, Offset);
1794 Base = ~0U;
1795 Width = 0;
1796 Offset = 0;
1797 }
1798 continue;
1799 }
Owen Andersond8c87882011-02-18 21:51:29 +00001800
Owen Anderson00ef6e32011-07-28 23:56:20 +00001801 if (Var->getName() != NI->second &&
Owen Andersonea242982011-07-29 18:28:52 +00001802 Var->getName() != TiedNames[NI->second]) {
Owen Andersond1e38df2011-07-28 21:54:31 +00001803 if (Base != ~0U) {
1804 OpInfo.addField(Base, Width, Offset);
1805 Base = ~0U;
1806 Width = 0;
1807 Offset = 0;
1808 }
1809 continue;
Owen Andersond8c87882011-02-18 21:51:29 +00001810 }
1811
Owen Andersond1e38df2011-07-28 21:54:31 +00001812 if (Base == ~0U) {
1813 Base = bi;
1814 Width = 1;
Owen Andersoncf603952011-08-01 22:45:43 +00001815 Offset = BI ? BI->getBitNum() : 0;
1816 } else if (BI && BI->getBitNum() != Offset + Width) {
Owen Andersoneb809f52011-07-29 23:01:18 +00001817 OpInfo.addField(Base, Width, Offset);
1818 Base = bi;
1819 Width = 1;
1820 Offset = BI->getBitNum();
Owen Andersond1e38df2011-07-28 21:54:31 +00001821 } else {
1822 ++Width;
Owen Andersond8c87882011-02-18 21:51:29 +00001823 }
Owen Andersond8c87882011-02-18 21:51:29 +00001824 }
1825
Owen Andersond1e38df2011-07-28 21:54:31 +00001826 if (Base != ~0U)
1827 OpInfo.addField(Base, Width, Offset);
1828
1829 if (OpInfo.numFields() > 0)
1830 InsnOperands.push_back(OpInfo);
Owen Andersond8c87882011-02-18 21:51:29 +00001831 }
1832
1833 Operands[Opc] = InsnOperands;
1834
1835
1836#if 0
1837 DEBUG({
1838 // Dumps the instruction encoding bits.
1839 dumpBits(errs(), Bits);
1840
1841 errs() << '\n';
1842
1843 // Dumps the list of operand info.
1844 for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) {
1845 const CGIOperandList::OperandInfo &Info = CGI.Operands[i];
1846 const std::string &OperandName = Info.Name;
1847 const Record &OperandDef = *Info.Rec;
1848
1849 errs() << "\t" << OperandName << " (" << OperandDef.getName() << ")\n";
1850 }
1851 });
1852#endif
1853
1854 return true;
1855}
1856
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001857// emitFieldFromInstruction - Emit the templated helper function
1858// fieldFromInstruction().
1859static void emitFieldFromInstruction(formatted_raw_ostream &OS) {
1860 OS << "// Helper function for extracting fields from encoded instructions.\n"
1861 << "template<typename InsnType>\n"
1862 << "static InsnType fieldFromInstruction(InsnType insn, unsigned startBit,\n"
1863 << " unsigned numBits) {\n"
1864 << " assert(startBit + numBits <= (sizeof(InsnType)*8) &&\n"
1865 << " \"Instruction field out of bounds!\");\n"
1866 << " InsnType fieldMask;\n"
1867 << " if (numBits == sizeof(InsnType)*8)\n"
1868 << " fieldMask = (InsnType)(-1LL);\n"
1869 << " else\n"
1870 << " fieldMask = ((1 << numBits) - 1) << startBit;\n"
1871 << " return (insn & fieldMask) >> startBit;\n"
1872 << "}\n\n";
1873}
Owen Andersond8c87882011-02-18 21:51:29 +00001874
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001875// emitDecodeInstruction - Emit the templated helper function
1876// decodeInstruction().
1877static void emitDecodeInstruction(formatted_raw_ostream &OS) {
1878 OS << "template<typename InsnType>\n"
1879 << "static DecodeStatus decodeInstruction(const uint8_t DecodeTable[], MCInst &MI,\n"
1880 << " InsnType insn, uint64_t Address,\n"
1881 << " const void *DisAsm,\n"
1882 << " const MCSubtargetInfo &STI) {\n"
1883 << " uint64_t Bits = STI.getFeatureBits();\n"
1884 << "\n"
1885 << " const uint8_t *Ptr = DecodeTable;\n"
Jim Grosbach9bb938c2012-09-17 18:00:53 +00001886 << " uint32_t CurFieldValue = 0;\n"
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001887 << " DecodeStatus S = MCDisassembler::Success;\n"
1888 << " for (;;) {\n"
1889 << " ptrdiff_t Loc = Ptr - DecodeTable;\n"
1890 << " switch (*Ptr) {\n"
1891 << " default:\n"
1892 << " errs() << Loc << \": Unexpected decode table opcode!\\n\";\n"
1893 << " return MCDisassembler::Fail;\n"
1894 << " case MCD::OPC_ExtractField: {\n"
1895 << " unsigned Start = *++Ptr;\n"
1896 << " unsigned Len = *++Ptr;\n"
1897 << " ++Ptr;\n"
1898 << " CurFieldValue = fieldFromInstruction(insn, Start, Len);\n"
1899 << " DEBUG(dbgs() << Loc << \": OPC_ExtractField(\" << Start << \", \"\n"
1900 << " << Len << \"): \" << CurFieldValue << \"\\n\");\n"
1901 << " break;\n"
1902 << " }\n"
1903 << " case MCD::OPC_FilterValue: {\n"
1904 << " // Decode the field value.\n"
1905 << " unsigned Len;\n"
1906 << " InsnType Val = decodeULEB128(++Ptr, &Len);\n"
1907 << " Ptr += Len;\n"
1908 << " // NumToSkip is a plain 16-bit integer.\n"
1909 << " unsigned NumToSkip = *Ptr++;\n"
1910 << " NumToSkip |= (*Ptr++) << 8;\n"
1911 << "\n"
1912 << " // Perform the filter operation.\n"
1913 << " if (Val != CurFieldValue)\n"
1914 << " Ptr += NumToSkip;\n"
1915 << " DEBUG(dbgs() << Loc << \": OPC_FilterValue(\" << Val << \", \" << NumToSkip\n"
1916 << " << \"): \" << ((Val != CurFieldValue) ? \"FAIL:\" : \"PASS:\")\n"
1917 << " << \" continuing at \" << (Ptr - DecodeTable) << \"\\n\");\n"
1918 << "\n"
1919 << " break;\n"
1920 << " }\n"
1921 << " case MCD::OPC_CheckField: {\n"
1922 << " unsigned Start = *++Ptr;\n"
1923 << " unsigned Len = *++Ptr;\n"
1924 << " InsnType FieldValue = fieldFromInstruction(insn, Start, Len);\n"
1925 << " // Decode the field value.\n"
1926 << " uint32_t ExpectedValue = decodeULEB128(++Ptr, &Len);\n"
1927 << " Ptr += Len;\n"
1928 << " // NumToSkip is a plain 16-bit integer.\n"
1929 << " unsigned NumToSkip = *Ptr++;\n"
1930 << " NumToSkip |= (*Ptr++) << 8;\n"
1931 << "\n"
1932 << " // If the actual and expected values don't match, skip.\n"
1933 << " if (ExpectedValue != FieldValue)\n"
1934 << " Ptr += NumToSkip;\n"
1935 << " DEBUG(dbgs() << Loc << \": OPC_CheckField(\" << Start << \", \"\n"
1936 << " << Len << \", \" << ExpectedValue << \", \" << NumToSkip\n"
1937 << " << \"): FieldValue = \" << FieldValue << \", ExpectedValue = \"\n"
1938 << " << ExpectedValue << \": \"\n"
1939 << " << ((ExpectedValue == FieldValue) ? \"PASS\\n\" : \"FAIL\\n\"));\n"
1940 << " break;\n"
1941 << " }\n"
1942 << " case MCD::OPC_CheckPredicate: {\n"
1943 << " unsigned Len;\n"
1944 << " // Decode the Predicate Index value.\n"
1945 << " unsigned PIdx = decodeULEB128(++Ptr, &Len);\n"
1946 << " Ptr += Len;\n"
1947 << " // NumToSkip is a plain 16-bit integer.\n"
1948 << " unsigned NumToSkip = *Ptr++;\n"
1949 << " NumToSkip |= (*Ptr++) << 8;\n"
1950 << " // Check the predicate.\n"
1951 << " bool Pred;\n"
1952 << " if (!(Pred = checkDecoderPredicate(PIdx, Bits)))\n"
1953 << " Ptr += NumToSkip;\n"
1954 << " (void)Pred;\n"
1955 << " DEBUG(dbgs() << Loc << \": OPC_CheckPredicate(\" << PIdx << \"): \"\n"
1956 << " << (Pred ? \"PASS\\n\" : \"FAIL\\n\"));\n"
1957 << "\n"
1958 << " break;\n"
1959 << " }\n"
1960 << " case MCD::OPC_Decode: {\n"
1961 << " unsigned Len;\n"
1962 << " // Decode the Opcode value.\n"
1963 << " unsigned Opc = decodeULEB128(++Ptr, &Len);\n"
1964 << " Ptr += Len;\n"
1965 << " unsigned DecodeIdx = decodeULEB128(Ptr, &Len);\n"
1966 << " Ptr += Len;\n"
1967 << " DEBUG(dbgs() << Loc << \": OPC_Decode: opcode \" << Opc\n"
1968 << " << \", using decoder \" << DecodeIdx << \"\\n\" );\n"
1969 << " DEBUG(dbgs() << \"----- DECODE SUCCESSFUL -----\\n\");\n"
1970 << "\n"
1971 << " MI.setOpcode(Opc);\n"
Benjamin Kramer95d235d2012-08-15 10:26:44 +00001972 << " return decodeToMCInst(S, DecodeIdx, insn, MI, Address, DisAsm);\n"
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001973 << " }\n"
1974 << " case MCD::OPC_SoftFail: {\n"
1975 << " // Decode the mask values.\n"
1976 << " unsigned Len;\n"
1977 << " InsnType PositiveMask = decodeULEB128(++Ptr, &Len);\n"
1978 << " Ptr += Len;\n"
1979 << " InsnType NegativeMask = decodeULEB128(Ptr, &Len);\n"
1980 << " Ptr += Len;\n"
1981 << " bool Fail = (insn & PositiveMask) || (~insn & NegativeMask);\n"
1982 << " if (Fail)\n"
1983 << " S = MCDisassembler::SoftFail;\n"
1984 << " DEBUG(dbgs() << Loc << \": OPC_SoftFail: \" << (Fail ? \"FAIL\\n\":\"PASS\\n\"));\n"
1985 << " break;\n"
1986 << " }\n"
1987 << " case MCD::OPC_Fail: {\n"
1988 << " DEBUG(dbgs() << Loc << \": OPC_Fail\\n\");\n"
1989 << " return MCDisassembler::Fail;\n"
1990 << " }\n"
1991 << " }\n"
1992 << " }\n"
1993 << " llvm_unreachable(\"bogosity detected in disassembler state machine!\");\n"
1994 << "}\n\n";
Owen Andersond8c87882011-02-18 21:51:29 +00001995}
1996
1997// Emits disassembler code for instruction decoding.
Craig Topperd9360452012-03-16 01:19:24 +00001998void FixedLenDecoderEmitter::run(raw_ostream &o) {
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001999 formatted_raw_ostream OS(o);
2000 OS << "#include \"llvm/MC/MCInst.h\"\n";
2001 OS << "#include \"llvm/Support/Debug.h\"\n";
2002 OS << "#include \"llvm/Support/DataTypes.h\"\n";
2003 OS << "#include \"llvm/Support/LEB128.h\"\n";
2004 OS << "#include \"llvm/Support/raw_ostream.h\"\n";
2005 OS << "#include <assert.h>\n";
2006 OS << '\n';
2007 OS << "namespace llvm {\n\n";
2008
2009 emitFieldFromInstruction(OS);
Owen Andersond8c87882011-02-18 21:51:29 +00002010
Owen Andersonf1a00902011-07-19 21:06:00 +00002011 // Parameterize the decoders based on namespace and instruction width.
Jim Grosbachfc1a1612012-08-14 19:06:05 +00002012 NumberedInstructions = &Target.getInstructionsByEnumValue();
Owen Andersonf1a00902011-07-19 21:06:00 +00002013 std::map<std::pair<std::string, unsigned>,
2014 std::vector<unsigned> > OpcMap;
2015 std::map<unsigned, std::vector<OperandInfo> > Operands;
2016
Jim Grosbachfc1a1612012-08-14 19:06:05 +00002017 for (unsigned i = 0; i < NumberedInstructions->size(); ++i) {
2018 const CodeGenInstruction *Inst = NumberedInstructions->at(i);
Craig Toppereb5cd612012-03-16 05:58:09 +00002019 const Record *Def = Inst->TheDef;
Owen Andersonf1a00902011-07-19 21:06:00 +00002020 unsigned Size = Def->getValueAsInt("Size");
2021 if (Def->getValueAsString("Namespace") == "TargetOpcode" ||
2022 Def->getValueAsBit("isPseudo") ||
2023 Def->getValueAsBit("isAsmParserOnly") ||
2024 Def->getValueAsBit("isCodeGenOnly"))
2025 continue;
2026
2027 std::string DecoderNamespace = Def->getValueAsString("DecoderNamespace");
2028
2029 if (Size) {
2030 if (populateInstruction(*Inst, i, Operands)) {
2031 OpcMap[std::make_pair(DecoderNamespace, Size)].push_back(i);
2032 }
2033 }
2034 }
2035
Jim Grosbachfc1a1612012-08-14 19:06:05 +00002036 DecoderTableInfo TableInfo;
Owen Andersonf1a00902011-07-19 21:06:00 +00002037 std::set<unsigned> Sizes;
2038 for (std::map<std::pair<std::string, unsigned>,
Craig Toppereb5cd612012-03-16 05:58:09 +00002039 std::vector<unsigned> >::const_iterator
Owen Andersonf1a00902011-07-19 21:06:00 +00002040 I = OpcMap.begin(), E = OpcMap.end(); I != E; ++I) {
Owen Andersonf1a00902011-07-19 21:06:00 +00002041 // Emit the decoder for this namespace+width combination.
Jim Grosbachfc1a1612012-08-14 19:06:05 +00002042 FilterChooser FC(*NumberedInstructions, I->second, Operands,
Owen Anderson83e3f672011-08-17 17:44:15 +00002043 8*I->first.second, this);
Jim Grosbachfc1a1612012-08-14 19:06:05 +00002044
2045 // The decode table is cleared for each top level decoder function. The
2046 // predicates and decoders themselves, however, are shared across all
2047 // decoders to give more opportunities for uniqueing.
2048 TableInfo.Table.clear();
2049 TableInfo.FixupStack.clear();
2050 TableInfo.Table.reserve(16384);
2051 TableInfo.FixupStack.push_back(FixupList());
2052 FC.emitTableEntries(TableInfo);
2053 // Any NumToSkip fixups in the top level scope can resolve to the
2054 // OPC_Fail at the end of the table.
2055 assert(TableInfo.FixupStack.size() == 1 && "fixup stack phasing error!");
2056 // Resolve any NumToSkip fixups in the current scope.
2057 resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),
2058 TableInfo.Table.size());
2059 TableInfo.FixupStack.clear();
2060
2061 TableInfo.Table.push_back(MCD::OPC_Fail);
2062
2063 // Print the table to the output stream.
2064 emitTable(OS, TableInfo.Table, 0, FC.getBitWidth(), I->first.first);
2065 OS.flush();
Owen Andersonf1a00902011-07-19 21:06:00 +00002066 }
Owen Andersond8c87882011-02-18 21:51:29 +00002067
Jim Grosbachfc1a1612012-08-14 19:06:05 +00002068 // Emit the predicate function.
2069 emitPredicateFunction(OS, TableInfo.Predicates, 0);
2070
2071 // Emit the decoder function.
2072 emitDecoderFunction(OS, TableInfo.Decoders, 0);
2073
2074 // Emit the main entry point for the decoder, decodeInstruction().
2075 emitDecodeInstruction(OS);
2076
2077 OS << "\n} // End llvm namespace\n";
Owen Andersond8c87882011-02-18 21:51:29 +00002078}
Jakob Stoklund Olesen6f36fa92012-06-11 15:37:55 +00002079
2080namespace llvm {
2081
2082void EmitFixedLenDecoder(RecordKeeper &RK, raw_ostream &OS,
2083 std::string PredicateNamespace,
2084 std::string GPrefix,
2085 std::string GPostfix,
2086 std::string ROK,
2087 std::string RFail,
2088 std::string L) {
2089 FixedLenDecoderEmitter(RK, PredicateNamespace, GPrefix, GPostfix,
2090 ROK, RFail, L).run(OS);
2091}
2092
2093} // End llvm namespace