blob: 2cdde5500954471b3c9d773b4660869417289acd [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"
Peter Collingbourne7c788882011-10-01 16:41:13 +000018#include "llvm/TableGen/Record.h"
James Molloy3015dfb2012-02-09 10:56:31 +000019#include "llvm/ADT/APInt.h"
Owen Andersond8c87882011-02-18 21:51:29 +000020#include "llvm/ADT/StringExtras.h"
Jakob Stoklund Olesen6f36fa92012-06-11 15:37:55 +000021#include "llvm/Support/DataTypes.h"
Owen Andersond8c87882011-02-18 21:51:29 +000022#include "llvm/Support/Debug.h"
23#include "llvm/Support/raw_ostream.h"
Jakob Stoklund Olesen6f36fa92012-06-11 15:37:55 +000024#include "llvm/TableGen/TableGenBackend.h"
Owen Andersond8c87882011-02-18 21:51:29 +000025
26#include <vector>
27#include <map>
28#include <string>
29
30using namespace llvm;
31
Jakob Stoklund Olesen6f36fa92012-06-11 15:37:55 +000032namespace {
33struct EncodingField {
34 unsigned Base, Width, Offset;
35 EncodingField(unsigned B, unsigned W, unsigned O)
36 : Base(B), Width(W), Offset(O) { }
37};
38} // End anonymous namespace
39
40namespace {
41struct OperandInfo {
42 std::vector<EncodingField> Fields;
43 std::string Decoder;
44
45 OperandInfo(std::string D)
46 : Decoder(D) { }
47
48 void addField(unsigned Base, unsigned Width, unsigned Offset) {
49 Fields.push_back(EncodingField(Base, Width, Offset));
50 }
51
52 unsigned numFields() const { return Fields.size(); }
53
54 typedef std::vector<EncodingField>::const_iterator const_iterator;
55
56 const_iterator begin() const { return Fields.begin(); }
57 const_iterator end() const { return Fields.end(); }
58};
59} // End anonymous namespace
60
61namespace {
62class FixedLenDecoderEmitter {
63public:
64
65 // Defaults preserved here for documentation, even though they aren't
66 // strictly necessary given the way that this is currently being called.
67 FixedLenDecoderEmitter(RecordKeeper &R,
68 std::string PredicateNamespace,
69 std::string GPrefix = "if (",
70 std::string GPostfix = " == MCDisassembler::Fail)"
71 " return MCDisassembler::Fail;",
72 std::string ROK = "MCDisassembler::Success",
73 std::string RFail = "MCDisassembler::Fail",
74 std::string L = "") :
75 Target(R),
76 PredicateNamespace(PredicateNamespace),
77 GuardPrefix(GPrefix), GuardPostfix(GPostfix),
78 ReturnOK(ROK), ReturnFail(RFail), Locals(L) {}
79
80 // run - Output the code emitter
81 void run(raw_ostream &o);
82
83private:
84 CodeGenTarget Target;
85public:
86 std::string PredicateNamespace;
87 std::string GuardPrefix, GuardPostfix;
88 std::string ReturnOK, ReturnFail;
89 std::string Locals;
90};
91} // End anonymous namespace
92
Owen Andersond8c87882011-02-18 21:51:29 +000093// The set (BIT_TRUE, BIT_FALSE, BIT_UNSET) represents a ternary logic system
94// for a bit value.
95//
96// BIT_UNFILTERED is used as the init value for a filter position. It is used
97// only for filter processings.
98typedef enum {
99 BIT_TRUE, // '1'
100 BIT_FALSE, // '0'
101 BIT_UNSET, // '?'
102 BIT_UNFILTERED // unfiltered
103} bit_value_t;
104
105static bool ValueSet(bit_value_t V) {
106 return (V == BIT_TRUE || V == BIT_FALSE);
107}
108static bool ValueNotSet(bit_value_t V) {
109 return (V == BIT_UNSET);
110}
111static int Value(bit_value_t V) {
112 return ValueNotSet(V) ? -1 : (V == BIT_FALSE ? 0 : 1);
113}
Craig Toppereb5cd612012-03-16 05:58:09 +0000114static bit_value_t bitFromBits(const BitsInit &bits, unsigned index) {
David Greene05bce0b2011-07-29 22:43:06 +0000115 if (BitInit *bit = dynamic_cast<BitInit*>(bits.getBit(index)))
Owen Andersond8c87882011-02-18 21:51:29 +0000116 return bit->getValue() ? BIT_TRUE : BIT_FALSE;
117
118 // The bit is uninitialized.
119 return BIT_UNSET;
120}
121// Prints the bit value for each position.
Craig Toppereb5cd612012-03-16 05:58:09 +0000122static void dumpBits(raw_ostream &o, const BitsInit &bits) {
Owen Andersond8c87882011-02-18 21:51:29 +0000123 unsigned index;
124
125 for (index = bits.getNumBits(); index > 0; index--) {
126 switch (bitFromBits(bits, index - 1)) {
127 case BIT_TRUE:
128 o << "1";
129 break;
130 case BIT_FALSE:
131 o << "0";
132 break;
133 case BIT_UNSET:
134 o << "_";
135 break;
136 default:
Craig Topper655b8de2012-02-05 07:21:30 +0000137 llvm_unreachable("unexpected return value from bitFromBits");
Owen Andersond8c87882011-02-18 21:51:29 +0000138 }
139 }
140}
141
David Greene05bce0b2011-07-29 22:43:06 +0000142static BitsInit &getBitsField(const Record &def, const char *str) {
143 BitsInit *bits = def.getValueAsBitsInit(str);
Owen Andersond8c87882011-02-18 21:51:29 +0000144 return *bits;
145}
146
147// Forward declaration.
Jakob Stoklund Olesen6f36fa92012-06-11 15:37:55 +0000148namespace {
Owen Andersond8c87882011-02-18 21:51:29 +0000149class FilterChooser;
Jakob Stoklund Olesen6f36fa92012-06-11 15:37:55 +0000150} // End anonymous namespace
Owen Andersond8c87882011-02-18 21:51:29 +0000151
Owen Andersond8c87882011-02-18 21:51:29 +0000152// Representation of the instruction to work on.
Owen Andersonf1a00902011-07-19 21:06:00 +0000153typedef std::vector<bit_value_t> insn_t;
Owen Andersond8c87882011-02-18 21:51:29 +0000154
155/// Filter - Filter works with FilterChooser to produce the decoding tree for
156/// the ISA.
157///
158/// It is useful to think of a Filter as governing the switch stmts of the
159/// decoding tree in a certain level. Each case stmt delegates to an inferior
160/// FilterChooser to decide what further decoding logic to employ, or in another
161/// words, what other remaining bits to look at. The FilterChooser eventually
162/// chooses a best Filter to do its job.
163///
164/// This recursive scheme ends when the number of Opcodes assigned to the
165/// FilterChooser becomes 1 or if there is a conflict. A conflict happens when
166/// the Filter/FilterChooser combo does not know how to distinguish among the
167/// Opcodes assigned.
168///
169/// An example of a conflict is
170///
171/// Conflict:
172/// 111101000.00........00010000....
173/// 111101000.00........0001........
174/// 1111010...00........0001........
175/// 1111010...00....................
176/// 1111010.........................
177/// 1111............................
178/// ................................
179/// VST4q8a 111101000_00________00010000____
180/// VST4q8b 111101000_00________00010000____
181///
182/// The Debug output shows the path that the decoding tree follows to reach the
183/// the conclusion that there is a conflict. VST4q8a is a vst4 to double-spaced
184/// even registers, while VST4q8b is a vst4 to double-spaced odd regsisters.
185///
186/// The encoding info in the .td files does not specify this meta information,
187/// which could have been used by the decoder to resolve the conflict. The
188/// decoder could try to decode the even/odd register numbering and assign to
189/// VST4q8a or VST4q8b, but for the time being, the decoder chooses the "a"
190/// version and return the Opcode since the two have the same Asm format string.
Jakob Stoklund Olesen6f36fa92012-06-11 15:37:55 +0000191namespace {
Owen Andersond8c87882011-02-18 21:51:29 +0000192class Filter {
193protected:
Craig Topper5a4c7902012-03-16 06:52:56 +0000194 const FilterChooser *Owner;// points to the FilterChooser who owns this filter
Owen Andersond8c87882011-02-18 21:51:29 +0000195 unsigned StartBit; // the starting bit position
196 unsigned NumBits; // number of bits to filter
197 bool Mixed; // a mixed region contains both set and unset bits
198
199 // Map of well-known segment value to the set of uid's with that value.
200 std::map<uint64_t, std::vector<unsigned> > FilteredInstructions;
201
202 // Set of uid's with non-constant segment values.
203 std::vector<unsigned> VariableInstructions;
204
205 // Map of well-known segment value to its delegate.
Craig Toppereb5cd612012-03-16 05:58:09 +0000206 std::map<unsigned, const FilterChooser*> FilterChooserMap;
Owen Andersond8c87882011-02-18 21:51:29 +0000207
208 // Number of instructions which fall under FilteredInstructions category.
209 unsigned NumFiltered;
210
211 // Keeps track of the last opcode in the filtered bucket.
212 unsigned LastOpcFiltered;
213
Owen Andersond8c87882011-02-18 21:51:29 +0000214public:
Craig Toppereb5cd612012-03-16 05:58:09 +0000215 unsigned getNumFiltered() const { return NumFiltered; }
216 unsigned getSingletonOpc() const {
Owen Andersond8c87882011-02-18 21:51:29 +0000217 assert(NumFiltered == 1);
218 return LastOpcFiltered;
219 }
220 // Return the filter chooser for the group of instructions without constant
221 // segment values.
Craig Toppereb5cd612012-03-16 05:58:09 +0000222 const FilterChooser &getVariableFC() const {
Owen Andersond8c87882011-02-18 21:51:29 +0000223 assert(NumFiltered == 1);
224 assert(FilterChooserMap.size() == 1);
225 return *(FilterChooserMap.find((unsigned)-1)->second);
226 }
227
228 Filter(const Filter &f);
229 Filter(FilterChooser &owner, unsigned startBit, unsigned numBits, bool mixed);
230
231 ~Filter();
232
233 // Divides the decoding task into sub tasks and delegates them to the
234 // inferior FilterChooser's.
235 //
236 // A special case arises when there's only one entry in the filtered
237 // instructions. In order to unambiguously decode the singleton, we need to
238 // match the remaining undecoded encoding bits against the singleton.
239 void recurse();
240
241 // Emit code to decode instructions given a segment or segments of bits.
Craig Toppereb5cd612012-03-16 05:58:09 +0000242 void emit(raw_ostream &o, unsigned &Indentation) const;
Owen Andersond8c87882011-02-18 21:51:29 +0000243
244 // Returns the number of fanout produced by the filter. More fanout implies
245 // the filter distinguishes more categories of instructions.
246 unsigned usefulness() const;
247}; // End of class Filter
Jakob Stoklund Olesen6f36fa92012-06-11 15:37:55 +0000248} // End anonymous namespace
Owen Andersond8c87882011-02-18 21:51:29 +0000249
250// These are states of our finite state machines used in FilterChooser's
251// filterProcessor() which produces the filter candidates to use.
252typedef enum {
253 ATTR_NONE,
254 ATTR_FILTERED,
255 ATTR_ALL_SET,
256 ATTR_ALL_UNSET,
257 ATTR_MIXED
258} bitAttr_t;
259
260/// FilterChooser - FilterChooser chooses the best filter among a set of Filters
261/// in order to perform the decoding of instructions at the current level.
262///
263/// Decoding proceeds from the top down. Based on the well-known encoding bits
264/// of instructions available, FilterChooser builds up the possible Filters that
265/// can further the task of decoding by distinguishing among the remaining
266/// candidate instructions.
267///
268/// Once a filter has been chosen, it is called upon to divide the decoding task
269/// into sub-tasks and delegates them to its inferior FilterChoosers for further
270/// processings.
271///
272/// It is useful to think of a Filter as governing the switch stmts of the
273/// decoding tree. And each case is delegated to an inferior FilterChooser to
274/// decide what further remaining bits to look at.
Jakob Stoklund Olesen6f36fa92012-06-11 15:37:55 +0000275namespace {
Owen Andersond8c87882011-02-18 21:51:29 +0000276class FilterChooser {
277protected:
278 friend class Filter;
279
280 // Vector of codegen instructions to choose our filter.
281 const std::vector<const CodeGenInstruction*> &AllInstructions;
282
283 // Vector of uid's for this filter chooser to work on.
Craig Topper5a4c7902012-03-16 06:52:56 +0000284 const std::vector<unsigned> &Opcodes;
Owen Andersond8c87882011-02-18 21:51:29 +0000285
286 // Lookup table for the operand decoding of instructions.
Craig Topper5a4c7902012-03-16 06:52:56 +0000287 const std::map<unsigned, std::vector<OperandInfo> > &Operands;
Owen Andersond8c87882011-02-18 21:51:29 +0000288
289 // Vector of candidate filters.
290 std::vector<Filter> Filters;
291
292 // Array of bit values passed down from our parent.
293 // Set to all BIT_UNFILTERED's for Parent == NULL.
Owen Andersonf1a00902011-07-19 21:06:00 +0000294 std::vector<bit_value_t> FilterBitValues;
Owen Andersond8c87882011-02-18 21:51:29 +0000295
296 // Links to the FilterChooser above us in the decoding tree.
Craig Topper5a4c7902012-03-16 06:52:56 +0000297 const FilterChooser *Parent;
Owen Andersond8c87882011-02-18 21:51:29 +0000298
299 // Index of the best filter from Filters.
300 int BestIndex;
301
Owen Andersonf1a00902011-07-19 21:06:00 +0000302 // Width of instructions
303 unsigned BitWidth;
304
Owen Anderson83e3f672011-08-17 17:44:15 +0000305 // Parent emitter
306 const FixedLenDecoderEmitter *Emitter;
307
Owen Andersond8c87882011-02-18 21:51:29 +0000308public:
Craig Topperd9360452012-03-16 01:19:24 +0000309 FilterChooser(const FilterChooser &FC)
310 : AllInstructions(FC.AllInstructions), Opcodes(FC.Opcodes),
Owen Andersonf1a00902011-07-19 21:06:00 +0000311 Operands(FC.Operands), Filters(FC.Filters),
312 FilterBitValues(FC.FilterBitValues), Parent(FC.Parent),
Craig Topperd9360452012-03-16 01:19:24 +0000313 BestIndex(FC.BestIndex), BitWidth(FC.BitWidth),
314 Emitter(FC.Emitter) { }
Owen Andersond8c87882011-02-18 21:51:29 +0000315
316 FilterChooser(const std::vector<const CodeGenInstruction*> &Insts,
317 const std::vector<unsigned> &IDs,
Craig Topper5a4c7902012-03-16 06:52:56 +0000318 const std::map<unsigned, std::vector<OperandInfo> > &Ops,
Owen Anderson83e3f672011-08-17 17:44:15 +0000319 unsigned BW,
Craig Topperd9360452012-03-16 01:19:24 +0000320 const FixedLenDecoderEmitter *E)
321 : AllInstructions(Insts), Opcodes(IDs), Operands(Ops), Filters(),
Owen Anderson83e3f672011-08-17 17:44:15 +0000322 Parent(NULL), BestIndex(-1), BitWidth(BW), Emitter(E) {
Owen Andersonf1a00902011-07-19 21:06:00 +0000323 for (unsigned i = 0; i < BitWidth; ++i)
324 FilterBitValues.push_back(BIT_UNFILTERED);
Owen Andersond8c87882011-02-18 21:51:29 +0000325
326 doFilter();
327 }
328
329 FilterChooser(const std::vector<const CodeGenInstruction*> &Insts,
330 const std::vector<unsigned> &IDs,
Craig Topper5a4c7902012-03-16 06:52:56 +0000331 const std::map<unsigned, std::vector<OperandInfo> > &Ops,
332 const std::vector<bit_value_t> &ParentFilterBitValues,
333 const FilterChooser &parent)
Craig Topperd9360452012-03-16 01:19:24 +0000334 : AllInstructions(Insts), Opcodes(IDs), Operands(Ops),
Owen Andersonf1a00902011-07-19 21:06:00 +0000335 Filters(), FilterBitValues(ParentFilterBitValues),
Owen Anderson83e3f672011-08-17 17:44:15 +0000336 Parent(&parent), BestIndex(-1), BitWidth(parent.BitWidth),
337 Emitter(parent.Emitter) {
Owen Andersond8c87882011-02-18 21:51:29 +0000338 doFilter();
339 }
340
341 // The top level filter chooser has NULL as its parent.
Craig Toppereb5cd612012-03-16 05:58:09 +0000342 bool isTopLevel() const { return Parent == NULL; }
Owen Andersond8c87882011-02-18 21:51:29 +0000343
344 // Emit the top level typedef and decodeInstruction() function.
Craig Toppereb5cd612012-03-16 05:58:09 +0000345 void emitTop(raw_ostream &o, unsigned Indentation,
346 const std::string &Namespace) const;
Owen Andersond8c87882011-02-18 21:51:29 +0000347
348protected:
349 // Populates the insn given the uid.
350 void insnWithID(insn_t &Insn, unsigned Opcode) const {
David Greene05bce0b2011-07-29 22:43:06 +0000351 BitsInit &Bits = getBitsField(*AllInstructions[Opcode]->TheDef, "Inst");
Owen Andersond8c87882011-02-18 21:51:29 +0000352
James Molloy3015dfb2012-02-09 10:56:31 +0000353 // We may have a SoftFail bitmask, which specifies a mask where an encoding
354 // may differ from the value in "Inst" and yet still be valid, but the
355 // disassembler should return SoftFail instead of Success.
356 //
357 // This is used for marking UNPREDICTABLE instructions in the ARM world.
Jim Grosbach9c826d22012-02-29 22:07:56 +0000358 BitsInit *SFBits =
359 AllInstructions[Opcode]->TheDef->getValueAsBitsInit("SoftFail");
James Molloy3015dfb2012-02-09 10:56:31 +0000360
361 for (unsigned i = 0; i < BitWidth; ++i) {
362 if (SFBits && bitFromBits(*SFBits, i) == BIT_TRUE)
363 Insn.push_back(BIT_UNSET);
364 else
365 Insn.push_back(bitFromBits(Bits, i));
366 }
Owen Andersond8c87882011-02-18 21:51:29 +0000367 }
368
369 // Returns the record name.
370 const std::string &nameWithID(unsigned Opcode) const {
371 return AllInstructions[Opcode]->TheDef->getName();
372 }
373
374 // Populates the field of the insn given the start position and the number of
375 // consecutive bits to scan for.
376 //
377 // Returns false if there exists any uninitialized bit value in the range.
378 // Returns true, otherwise.
379 bool fieldFromInsn(uint64_t &Field, insn_t &Insn, unsigned StartBit,
Craig Topperd9360452012-03-16 01:19:24 +0000380 unsigned NumBits) const;
Owen Andersond8c87882011-02-18 21:51:29 +0000381
382 /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
383 /// filter array as a series of chars.
Craig Toppereb5cd612012-03-16 05:58:09 +0000384 void dumpFilterArray(raw_ostream &o,
385 const std::vector<bit_value_t> & filter) const;
Owen Andersond8c87882011-02-18 21:51:29 +0000386
387 /// dumpStack - dumpStack traverses the filter chooser chain and calls
388 /// dumpFilterArray on each filter chooser up to the top level one.
Craig Toppereb5cd612012-03-16 05:58:09 +0000389 void dumpStack(raw_ostream &o, const char *prefix) const;
Owen Andersond8c87882011-02-18 21:51:29 +0000390
391 Filter &bestFilter() {
392 assert(BestIndex != -1 && "BestIndex not set");
393 return Filters[BestIndex];
394 }
395
396 // Called from Filter::recurse() when singleton exists. For debug purpose.
Craig Toppereb5cd612012-03-16 05:58:09 +0000397 void SingletonExists(unsigned Opc) const;
Owen Andersond8c87882011-02-18 21:51:29 +0000398
Craig Toppereb5cd612012-03-16 05:58:09 +0000399 bool PositionFiltered(unsigned i) const {
Owen Andersond8c87882011-02-18 21:51:29 +0000400 return ValueSet(FilterBitValues[i]);
401 }
402
403 // Calculates the island(s) needed to decode the instruction.
404 // This returns a lit of undecoded bits of an instructions, for example,
405 // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
406 // decoded bits in order to verify that the instruction matches the Opcode.
407 unsigned getIslands(std::vector<unsigned> &StartBits,
Craig Topperd9360452012-03-16 01:19:24 +0000408 std::vector<unsigned> &EndBits,
Craig Toppereb5cd612012-03-16 05:58:09 +0000409 std::vector<uint64_t> &FieldVals,
410 const insn_t &Insn) const;
Owen Andersond8c87882011-02-18 21:51:29 +0000411
James Molloya5d58562011-09-07 19:42:28 +0000412 // Emits code to check the Predicates member of an instruction are true.
413 // Returns true if predicate matches were emitted, false otherwise.
Craig Toppereb5cd612012-03-16 05:58:09 +0000414 bool emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
415 unsigned Opc) const;
James Molloya5d58562011-09-07 19:42:28 +0000416
Craig Toppereb5cd612012-03-16 05:58:09 +0000417 void emitSoftFailCheck(raw_ostream &o, unsigned Indentation,
418 unsigned Opc) const;
James Molloy3015dfb2012-02-09 10:56:31 +0000419
Owen Andersond8c87882011-02-18 21:51:29 +0000420 // Emits code to decode the singleton. Return true if we have matched all the
421 // well-known bits.
Craig Toppereb5cd612012-03-16 05:58:09 +0000422 bool emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,
423 unsigned Opc) const;
Owen Andersond8c87882011-02-18 21:51:29 +0000424
425 // Emits code to decode the singleton, and then to decode the rest.
Craig Toppereb5cd612012-03-16 05:58:09 +0000426 void emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,
427 const Filter &Best) const;
Owen Andersond8c87882011-02-18 21:51:29 +0000428
Owen Andersond1e38df2011-07-28 21:54:31 +0000429 void emitBinaryParser(raw_ostream &o , unsigned &Indentation,
Craig Toppereb5cd612012-03-16 05:58:09 +0000430 const OperandInfo &OpInfo) const;
Owen Andersond1e38df2011-07-28 21:54:31 +0000431
Owen Andersond8c87882011-02-18 21:51:29 +0000432 // Assign a single filter and run with it.
Craig Toppereb5cd612012-03-16 05:58:09 +0000433 void runSingleFilter(unsigned startBit, unsigned numBit, bool mixed);
Owen Andersond8c87882011-02-18 21:51:29 +0000434
435 // reportRegion is a helper function for filterProcessor to mark a region as
436 // eligible for use as a filter region.
437 void reportRegion(bitAttr_t RA, unsigned StartBit, unsigned BitIndex,
Craig Topperd9360452012-03-16 01:19:24 +0000438 bool AllowMixed);
Owen Andersond8c87882011-02-18 21:51:29 +0000439
440 // FilterProcessor scans the well-known encoding bits of the instructions and
441 // builds up a list of candidate filters. It chooses the best filter and
442 // recursively descends down the decoding tree.
443 bool filterProcessor(bool AllowMixed, bool Greedy = true);
444
445 // Decides on the best configuration of filter(s) to use in order to decode
446 // the instructions. A conflict of instructions may occur, in which case we
447 // dump the conflict set to the standard error.
448 void doFilter();
449
450 // Emits code to decode our share of instructions. Returns true if the
451 // emitted code causes a return, which occurs if we know how to decode
452 // the instruction at this level or the instruction is not decodeable.
Craig Toppereb5cd612012-03-16 05:58:09 +0000453 bool emit(raw_ostream &o, unsigned &Indentation) const;
Owen Andersond8c87882011-02-18 21:51:29 +0000454};
Jakob Stoklund Olesen6f36fa92012-06-11 15:37:55 +0000455} // End anonymous namespace
Owen Andersond8c87882011-02-18 21:51:29 +0000456
457///////////////////////////
458// //
Craig Topper797ba552012-03-16 00:56:01 +0000459// Filter Implementation //
Owen Andersond8c87882011-02-18 21:51:29 +0000460// //
461///////////////////////////
462
Craig Topperd9360452012-03-16 01:19:24 +0000463Filter::Filter(const Filter &f)
464 : Owner(f.Owner), StartBit(f.StartBit), NumBits(f.NumBits), Mixed(f.Mixed),
465 FilteredInstructions(f.FilteredInstructions),
466 VariableInstructions(f.VariableInstructions),
467 FilterChooserMap(f.FilterChooserMap), NumFiltered(f.NumFiltered),
468 LastOpcFiltered(f.LastOpcFiltered) {
Owen Andersond8c87882011-02-18 21:51:29 +0000469}
470
471Filter::Filter(FilterChooser &owner, unsigned startBit, unsigned numBits,
Craig Topperd9360452012-03-16 01:19:24 +0000472 bool mixed)
473 : Owner(&owner), StartBit(startBit), NumBits(numBits), Mixed(mixed) {
Owen Andersonf1a00902011-07-19 21:06:00 +0000474 assert(StartBit + NumBits - 1 < Owner->BitWidth);
Owen Andersond8c87882011-02-18 21:51:29 +0000475
476 NumFiltered = 0;
477 LastOpcFiltered = 0;
Owen Andersond8c87882011-02-18 21:51:29 +0000478
479 for (unsigned i = 0, e = Owner->Opcodes.size(); i != e; ++i) {
480 insn_t Insn;
481
482 // Populates the insn given the uid.
483 Owner->insnWithID(Insn, Owner->Opcodes[i]);
484
485 uint64_t Field;
486 // Scans the segment for possibly well-specified encoding bits.
487 bool ok = Owner->fieldFromInsn(Field, Insn, StartBit, NumBits);
488
489 if (ok) {
490 // The encoding bits are well-known. Lets add the uid of the
491 // instruction into the bucket keyed off the constant field value.
492 LastOpcFiltered = Owner->Opcodes[i];
493 FilteredInstructions[Field].push_back(LastOpcFiltered);
494 ++NumFiltered;
495 } else {
Craig Topper797ba552012-03-16 00:56:01 +0000496 // Some of the encoding bit(s) are unspecified. This contributes to
Owen Andersond8c87882011-02-18 21:51:29 +0000497 // one additional member of "Variable" instructions.
498 VariableInstructions.push_back(Owner->Opcodes[i]);
Owen Andersond8c87882011-02-18 21:51:29 +0000499 }
500 }
501
502 assert((FilteredInstructions.size() + VariableInstructions.size() > 0)
503 && "Filter returns no instruction categories");
504}
505
506Filter::~Filter() {
Craig Toppereb5cd612012-03-16 05:58:09 +0000507 std::map<unsigned, const FilterChooser*>::iterator filterIterator;
Owen Andersond8c87882011-02-18 21:51:29 +0000508 for (filterIterator = FilterChooserMap.begin();
509 filterIterator != FilterChooserMap.end();
510 filterIterator++) {
511 delete filterIterator->second;
512 }
513}
514
515// Divides the decoding task into sub tasks and delegates them to the
516// inferior FilterChooser's.
517//
518// A special case arises when there's only one entry in the filtered
519// instructions. In order to unambiguously decode the singleton, we need to
520// match the remaining undecoded encoding bits against the singleton.
521void Filter::recurse() {
522 std::map<uint64_t, std::vector<unsigned> >::const_iterator mapIterator;
523
Owen Andersond8c87882011-02-18 21:51:29 +0000524 // Starts by inheriting our parent filter chooser's filter bit values.
Owen Andersonf1a00902011-07-19 21:06:00 +0000525 std::vector<bit_value_t> BitValueArray(Owner->FilterBitValues);
Owen Andersond8c87882011-02-18 21:51:29 +0000526
527 unsigned bitIndex;
528
529 if (VariableInstructions.size()) {
530 // Conservatively marks each segment position as BIT_UNSET.
531 for (bitIndex = 0; bitIndex < NumBits; bitIndex++)
532 BitValueArray[StartBit + bitIndex] = BIT_UNSET;
533
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000534 // Delegates to an inferior filter chooser for further processing on this
Owen Andersond8c87882011-02-18 21:51:29 +0000535 // group of instructions whose segment values are variable.
Craig Toppereb5cd612012-03-16 05:58:09 +0000536 FilterChooserMap.insert(std::pair<unsigned, const FilterChooser*>(
Owen Andersond8c87882011-02-18 21:51:29 +0000537 (unsigned)-1,
538 new FilterChooser(Owner->AllInstructions,
539 VariableInstructions,
540 Owner->Operands,
541 BitValueArray,
542 *Owner)
543 ));
544 }
545
546 // No need to recurse for a singleton filtered instruction.
547 // See also Filter::emit().
548 if (getNumFiltered() == 1) {
549 //Owner->SingletonExists(LastOpcFiltered);
550 assert(FilterChooserMap.size() == 1);
551 return;
552 }
553
554 // Otherwise, create sub choosers.
555 for (mapIterator = FilteredInstructions.begin();
556 mapIterator != FilteredInstructions.end();
557 mapIterator++) {
558
559 // Marks all the segment positions with either BIT_TRUE or BIT_FALSE.
560 for (bitIndex = 0; bitIndex < NumBits; bitIndex++) {
561 if (mapIterator->first & (1ULL << bitIndex))
562 BitValueArray[StartBit + bitIndex] = BIT_TRUE;
563 else
564 BitValueArray[StartBit + bitIndex] = BIT_FALSE;
565 }
566
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000567 // Delegates to an inferior filter chooser for further processing on this
Owen Andersond8c87882011-02-18 21:51:29 +0000568 // category of instructions.
Craig Toppereb5cd612012-03-16 05:58:09 +0000569 FilterChooserMap.insert(std::pair<unsigned, const FilterChooser*>(
Owen Andersond8c87882011-02-18 21:51:29 +0000570 mapIterator->first,
571 new FilterChooser(Owner->AllInstructions,
572 mapIterator->second,
573 Owner->Operands,
574 BitValueArray,
575 *Owner)
576 ));
577 }
578}
579
580// Emit code to decode instructions given a segment or segments of bits.
Craig Toppereb5cd612012-03-16 05:58:09 +0000581void Filter::emit(raw_ostream &o, unsigned &Indentation) const {
Owen Andersond8c87882011-02-18 21:51:29 +0000582 o.indent(Indentation) << "// Check Inst{";
583
584 if (NumBits > 1)
585 o << (StartBit + NumBits - 1) << '-';
586
587 o << StartBit << "} ...\n";
588
Owen Andersonf1a00902011-07-19 21:06:00 +0000589 o.indent(Indentation) << "switch (fieldFromInstruction" << Owner->BitWidth
590 << "(insn, " << StartBit << ", "
591 << NumBits << ")) {\n";
Owen Andersond8c87882011-02-18 21:51:29 +0000592
Craig Toppereb5cd612012-03-16 05:58:09 +0000593 std::map<unsigned, const FilterChooser*>::const_iterator filterIterator;
Owen Andersond8c87882011-02-18 21:51:29 +0000594
595 bool DefaultCase = false;
596 for (filterIterator = FilterChooserMap.begin();
597 filterIterator != FilterChooserMap.end();
598 filterIterator++) {
599
600 // Field value -1 implies a non-empty set of variable instructions.
601 // See also recurse().
602 if (filterIterator->first == (unsigned)-1) {
603 DefaultCase = true;
604
605 o.indent(Indentation) << "default:\n";
606 o.indent(Indentation) << " break; // fallthrough\n";
607
608 // Closing curly brace for the switch statement.
609 // This is unconventional because we want the default processing to be
610 // performed for the fallthrough cases as well, i.e., when the "cases"
611 // did not prove a decoded instruction.
612 o.indent(Indentation) << "}\n";
613
614 } else
615 o.indent(Indentation) << "case " << filterIterator->first << ":\n";
616
617 // We arrive at a category of instructions with the same segment value.
618 // Now delegate to the sub filter chooser for further decodings.
619 // The case may fallthrough, which happens if the remaining well-known
620 // encoding bits do not match exactly.
621 if (!DefaultCase) { ++Indentation; ++Indentation; }
622
Silviu Baranga545b9622012-04-02 15:46:46 +0000623 filterIterator->second->emit(o, Indentation);
Owen Andersond8c87882011-02-18 21:51:29 +0000624 // For top level default case, there's no need for a break statement.
625 if (Owner->isTopLevel() && DefaultCase)
626 break;
Silviu Baranga545b9622012-04-02 15:46:46 +0000627
628 o.indent(Indentation) << "break;\n";
Owen Andersond8c87882011-02-18 21:51:29 +0000629
630 if (!DefaultCase) { --Indentation; --Indentation; }
631 }
632
633 // If there is no default case, we still need to supply a closing brace.
634 if (!DefaultCase) {
635 // Closing curly brace for the switch statement.
636 o.indent(Indentation) << "}\n";
637 }
638}
639
640// Returns the number of fanout produced by the filter. More fanout implies
641// the filter distinguishes more categories of instructions.
642unsigned Filter::usefulness() const {
643 if (VariableInstructions.size())
644 return FilteredInstructions.size();
645 else
646 return FilteredInstructions.size() + 1;
647}
648
649//////////////////////////////////
650// //
651// Filterchooser Implementation //
652// //
653//////////////////////////////////
654
655// Emit the top level typedef and decodeInstruction() function.
Owen Andersonf1a00902011-07-19 21:06:00 +0000656void FilterChooser::emitTop(raw_ostream &o, unsigned Indentation,
Craig Toppereb5cd612012-03-16 05:58:09 +0000657 const std::string &Namespace) const {
Owen Andersond8c87882011-02-18 21:51:29 +0000658 o.indent(Indentation) <<
Jim Grosbach9c826d22012-02-29 22:07:56 +0000659 "static MCDisassembler::DecodeStatus decode" << Namespace << "Instruction"
660 << BitWidth << "(MCInst &MI, uint" << BitWidth
661 << "_t insn, uint64_t Address, "
James Molloya5d58562011-09-07 19:42:28 +0000662 << "const void *Decoder, const MCSubtargetInfo &STI) {\n";
Owen Anderson684dfcf2011-10-17 16:56:47 +0000663 o.indent(Indentation) << " unsigned tmp = 0;\n";
664 o.indent(Indentation) << " (void)tmp;\n";
665 o.indent(Indentation) << Emitter->Locals << "\n";
Bob Wilson1cea66c2011-10-01 02:47:54 +0000666 o.indent(Indentation) << " uint64_t Bits = STI.getFeatureBits();\n";
Owen Anderson684dfcf2011-10-17 16:56:47 +0000667 o.indent(Indentation) << " (void)Bits;\n";
Owen Andersond8c87882011-02-18 21:51:29 +0000668
669 ++Indentation; ++Indentation;
670 // Emits code to decode the instructions.
671 emit(o, Indentation);
672
673 o << '\n';
Owen Anderson83e3f672011-08-17 17:44:15 +0000674 o.indent(Indentation) << "return " << Emitter->ReturnFail << ";\n";
Owen Andersond8c87882011-02-18 21:51:29 +0000675 --Indentation; --Indentation;
676
677 o.indent(Indentation) << "}\n";
678
679 o << '\n';
680}
681
682// Populates the field of the insn given the start position and the number of
683// consecutive bits to scan for.
684//
685// Returns false if and on the first uninitialized bit value encountered.
686// Returns true, otherwise.
687bool FilterChooser::fieldFromInsn(uint64_t &Field, insn_t &Insn,
Craig Toppereb5cd612012-03-16 05:58:09 +0000688 unsigned StartBit, unsigned NumBits) const {
Owen Andersond8c87882011-02-18 21:51:29 +0000689 Field = 0;
690
691 for (unsigned i = 0; i < NumBits; ++i) {
692 if (Insn[StartBit + i] == BIT_UNSET)
693 return false;
694
695 if (Insn[StartBit + i] == BIT_TRUE)
696 Field = Field | (1ULL << i);
697 }
698
699 return true;
700}
701
702/// dumpFilterArray - dumpFilterArray prints out debugging info for the given
703/// filter array as a series of chars.
704void FilterChooser::dumpFilterArray(raw_ostream &o,
Craig Toppereb5cd612012-03-16 05:58:09 +0000705 const std::vector<bit_value_t> &filter) const {
Owen Andersond8c87882011-02-18 21:51:29 +0000706 unsigned bitIndex;
707
Owen Andersonf1a00902011-07-19 21:06:00 +0000708 for (bitIndex = BitWidth; bitIndex > 0; bitIndex--) {
Owen Andersond8c87882011-02-18 21:51:29 +0000709 switch (filter[bitIndex - 1]) {
710 case BIT_UNFILTERED:
711 o << ".";
712 break;
713 case BIT_UNSET:
714 o << "_";
715 break;
716 case BIT_TRUE:
717 o << "1";
718 break;
719 case BIT_FALSE:
720 o << "0";
721 break;
722 }
723 }
724}
725
726/// dumpStack - dumpStack traverses the filter chooser chain and calls
727/// dumpFilterArray on each filter chooser up to the top level one.
Craig Toppereb5cd612012-03-16 05:58:09 +0000728void FilterChooser::dumpStack(raw_ostream &o, const char *prefix) const {
729 const FilterChooser *current = this;
Owen Andersond8c87882011-02-18 21:51:29 +0000730
731 while (current) {
732 o << prefix;
733 dumpFilterArray(o, current->FilterBitValues);
734 o << '\n';
735 current = current->Parent;
736 }
737}
738
739// Called from Filter::recurse() when singleton exists. For debug purpose.
Craig Toppereb5cd612012-03-16 05:58:09 +0000740void FilterChooser::SingletonExists(unsigned Opc) const {
Owen Andersond8c87882011-02-18 21:51:29 +0000741 insn_t Insn0;
742 insnWithID(Insn0, Opc);
743
744 errs() << "Singleton exists: " << nameWithID(Opc)
745 << " with its decoding dominating ";
746 for (unsigned i = 0; i < Opcodes.size(); ++i) {
747 if (Opcodes[i] == Opc) continue;
748 errs() << nameWithID(Opcodes[i]) << ' ';
749 }
750 errs() << '\n';
751
752 dumpStack(errs(), "\t\t");
Craig Topperd9360452012-03-16 01:19:24 +0000753 for (unsigned i = 0; i < Opcodes.size(); ++i) {
Owen Andersond8c87882011-02-18 21:51:29 +0000754 const std::string &Name = nameWithID(Opcodes[i]);
755
756 errs() << '\t' << Name << " ";
757 dumpBits(errs(),
758 getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
759 errs() << '\n';
760 }
761}
762
763// Calculates the island(s) needed to decode the instruction.
764// This returns a list of undecoded bits of an instructions, for example,
765// Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
766// decoded bits in order to verify that the instruction matches the Opcode.
767unsigned FilterChooser::getIslands(std::vector<unsigned> &StartBits,
Craig Topperd9360452012-03-16 01:19:24 +0000768 std::vector<unsigned> &EndBits,
769 std::vector<uint64_t> &FieldVals,
Craig Toppereb5cd612012-03-16 05:58:09 +0000770 const insn_t &Insn) const {
Owen Andersond8c87882011-02-18 21:51:29 +0000771 unsigned Num, BitNo;
772 Num = BitNo = 0;
773
774 uint64_t FieldVal = 0;
775
776 // 0: Init
777 // 1: Water (the bit value does not affect decoding)
778 // 2: Island (well-known bit value needed for decoding)
779 int State = 0;
780 int Val = -1;
781
Owen Andersonf1a00902011-07-19 21:06:00 +0000782 for (unsigned i = 0; i < BitWidth; ++i) {
Owen Andersond8c87882011-02-18 21:51:29 +0000783 Val = Value(Insn[i]);
784 bool Filtered = PositionFiltered(i);
785 switch (State) {
Craig Topper655b8de2012-02-05 07:21:30 +0000786 default: llvm_unreachable("Unreachable code!");
Owen Andersond8c87882011-02-18 21:51:29 +0000787 case 0:
788 case 1:
789 if (Filtered || Val == -1)
790 State = 1; // Still in Water
791 else {
792 State = 2; // Into the Island
793 BitNo = 0;
794 StartBits.push_back(i);
795 FieldVal = Val;
796 }
797 break;
798 case 2:
799 if (Filtered || Val == -1) {
800 State = 1; // Into the Water
801 EndBits.push_back(i - 1);
802 FieldVals.push_back(FieldVal);
803 ++Num;
804 } else {
805 State = 2; // Still in Island
806 ++BitNo;
807 FieldVal = FieldVal | Val << BitNo;
808 }
809 break;
810 }
811 }
812 // If we are still in Island after the loop, do some housekeeping.
813 if (State == 2) {
Owen Andersonf1a00902011-07-19 21:06:00 +0000814 EndBits.push_back(BitWidth - 1);
Owen Andersond8c87882011-02-18 21:51:29 +0000815 FieldVals.push_back(FieldVal);
816 ++Num;
817 }
818
819 assert(StartBits.size() == Num && EndBits.size() == Num &&
820 FieldVals.size() == Num);
821 return Num;
822}
823
Owen Andersond1e38df2011-07-28 21:54:31 +0000824void FilterChooser::emitBinaryParser(raw_ostream &o, unsigned &Indentation,
Craig Toppereb5cd612012-03-16 05:58:09 +0000825 const OperandInfo &OpInfo) const {
826 const std::string &Decoder = OpInfo.Decoder;
Owen Andersond1e38df2011-07-28 21:54:31 +0000827
828 if (OpInfo.numFields() == 1) {
Craig Toppereb5cd612012-03-16 05:58:09 +0000829 OperandInfo::const_iterator OI = OpInfo.begin();
Owen Andersond1e38df2011-07-28 21:54:31 +0000830 o.indent(Indentation) << " tmp = fieldFromInstruction" << BitWidth
831 << "(insn, " << OI->Base << ", " << OI->Width
832 << ");\n";
833 } else {
834 o.indent(Indentation) << " tmp = 0;\n";
Craig Toppereb5cd612012-03-16 05:58:09 +0000835 for (OperandInfo::const_iterator OI = OpInfo.begin(), OE = OpInfo.end();
Owen Andersond1e38df2011-07-28 21:54:31 +0000836 OI != OE; ++OI) {
837 o.indent(Indentation) << " tmp |= (fieldFromInstruction" << BitWidth
Andrew Tricked968a92011-09-08 05:23:14 +0000838 << "(insn, " << OI->Base << ", " << OI->Width
Owen Andersond1e38df2011-07-28 21:54:31 +0000839 << ") << " << OI->Offset << ");\n";
840 }
841 }
842
843 if (Decoder != "")
Owen Anderson83e3f672011-08-17 17:44:15 +0000844 o.indent(Indentation) << " " << Emitter->GuardPrefix << Decoder
Jim Grosbach9c826d22012-02-29 22:07:56 +0000845 << "(MI, tmp, Address, Decoder)"
846 << Emitter->GuardPostfix << "\n";
Owen Andersond1e38df2011-07-28 21:54:31 +0000847 else
848 o.indent(Indentation) << " MI.addOperand(MCOperand::CreateImm(tmp));\n";
849
850}
851
James Molloya5d58562011-09-07 19:42:28 +0000852static void emitSinglePredicateMatch(raw_ostream &o, StringRef str,
Craig Toppereb5cd612012-03-16 05:58:09 +0000853 const std::string &PredicateNamespace) {
Andrew Trick22b4c812011-09-08 05:25:49 +0000854 if (str[0] == '!')
855 o << "!(Bits & " << PredicateNamespace << "::"
856 << str.slice(1,str.size()) << ")";
James Molloya5d58562011-09-07 19:42:28 +0000857 else
Andrew Trick22b4c812011-09-08 05:25:49 +0000858 o << "(Bits & " << PredicateNamespace << "::" << str << ")";
James Molloya5d58562011-09-07 19:42:28 +0000859}
860
861bool FilterChooser::emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
Craig Toppereb5cd612012-03-16 05:58:09 +0000862 unsigned Opc) const {
Jim Grosbach9c826d22012-02-29 22:07:56 +0000863 ListInit *Predicates =
864 AllInstructions[Opc]->TheDef->getValueAsListInit("Predicates");
James Molloya5d58562011-09-07 19:42:28 +0000865 for (unsigned i = 0; i < Predicates->getSize(); ++i) {
866 Record *Pred = Predicates->getElementAsRecord(i);
867 if (!Pred->getValue("AssemblerMatcherPredicate"))
868 continue;
869
870 std::string P = Pred->getValueAsString("AssemblerCondString");
871
872 if (!P.length())
873 continue;
874
875 if (i != 0)
876 o << " && ";
877
878 StringRef SR(P);
879 std::pair<StringRef, StringRef> pairs = SR.split(',');
880 while (pairs.second.size()) {
881 emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
882 o << " && ";
883 pairs = pairs.second.split(',');
884 }
885 emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
886 }
887 return Predicates->getSize() > 0;
Andrew Tricked968a92011-09-08 05:23:14 +0000888}
James Molloya5d58562011-09-07 19:42:28 +0000889
Jim Grosbach9c826d22012-02-29 22:07:56 +0000890void FilterChooser::emitSoftFailCheck(raw_ostream &o, unsigned Indentation,
Craig Toppereb5cd612012-03-16 05:58:09 +0000891 unsigned Opc) const {
Jim Grosbach9c826d22012-02-29 22:07:56 +0000892 BitsInit *SFBits =
893 AllInstructions[Opc]->TheDef->getValueAsBitsInit("SoftFail");
James Molloy3015dfb2012-02-09 10:56:31 +0000894 if (!SFBits) return;
895 BitsInit *InstBits = AllInstructions[Opc]->TheDef->getValueAsBitsInit("Inst");
896
897 APInt PositiveMask(BitWidth, 0ULL);
898 APInt NegativeMask(BitWidth, 0ULL);
899 for (unsigned i = 0; i < BitWidth; ++i) {
900 bit_value_t B = bitFromBits(*SFBits, i);
901 bit_value_t IB = bitFromBits(*InstBits, i);
902
903 if (B != BIT_TRUE) continue;
904
905 switch (IB) {
906 case BIT_FALSE:
907 // The bit is meant to be false, so emit a check to see if it is true.
908 PositiveMask.setBit(i);
909 break;
910 case BIT_TRUE:
911 // The bit is meant to be true, so emit a check to see if it is false.
912 NegativeMask.setBit(i);
913 break;
914 default:
915 // The bit is not set; this must be an error!
916 StringRef Name = AllInstructions[Opc]->TheDef->getName();
917 errs() << "SoftFail Conflict: bit SoftFail{" << i << "} in "
918 << Name
919 << " is set but Inst{" << i <<"} is unset!\n"
920 << " - You can only mark a bit as SoftFail if it is fully defined"
921 << " (1/0 - not '?') in Inst\n";
922 o << "#error SoftFail Conflict, " << Name << "::SoftFail{" << i
923 << "} set but Inst{" << i << "} undefined!\n";
924 }
925 }
926
927 bool NeedPositiveMask = PositiveMask.getBoolValue();
928 bool NeedNegativeMask = NegativeMask.getBoolValue();
929
930 if (!NeedPositiveMask && !NeedNegativeMask)
931 return;
932
933 std::string PositiveMaskStr = PositiveMask.toString(16, /*signed=*/false);
934 std::string NegativeMaskStr = NegativeMask.toString(16, /*signed=*/false);
935 StringRef BitExt = "";
936 if (BitWidth > 32)
937 BitExt = "ULL";
938
939 o.indent(Indentation) << "if (";
940 if (NeedPositiveMask)
941 o << "insn & 0x" << PositiveMaskStr << BitExt;
942 if (NeedPositiveMask && NeedNegativeMask)
943 o << " || ";
944 if (NeedNegativeMask)
945 o << "~insn & 0x" << NegativeMaskStr << BitExt;
946 o << ")\n";
947 o.indent(Indentation+2) << "S = MCDisassembler::SoftFail;\n";
948}
949
Owen Andersond8c87882011-02-18 21:51:29 +0000950// Emits code to decode the singleton. Return true if we have matched all the
951// well-known bits.
952bool FilterChooser::emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,
Craig Toppereb5cd612012-03-16 05:58:09 +0000953 unsigned Opc) const {
Owen Andersond8c87882011-02-18 21:51:29 +0000954 std::vector<unsigned> StartBits;
955 std::vector<unsigned> EndBits;
956 std::vector<uint64_t> FieldVals;
957 insn_t Insn;
958 insnWithID(Insn, Opc);
959
960 // Look for islands of undecoded bits of the singleton.
961 getIslands(StartBits, EndBits, FieldVals, Insn);
962
963 unsigned Size = StartBits.size();
964 unsigned I, NumBits;
965
966 // If we have matched all the well-known bits, just issue a return.
967 if (Size == 0) {
James Molloya5d58562011-09-07 19:42:28 +0000968 o.indent(Indentation) << "if (";
Eli Friedman64a17b32011-09-08 21:00:31 +0000969 if (!emitPredicateMatch(o, Indentation, Opc))
970 o << "1";
James Molloya5d58562011-09-07 19:42:28 +0000971 o << ") {\n";
James Molloy3015dfb2012-02-09 10:56:31 +0000972 emitSoftFailCheck(o, Indentation+2, Opc);
Owen Andersond8c87882011-02-18 21:51:29 +0000973 o.indent(Indentation) << " MI.setOpcode(" << Opc << ");\n";
Craig Topper5a4c7902012-03-16 06:52:56 +0000974 std::map<unsigned, std::vector<OperandInfo> >::const_iterator OpIter =
975 Operands.find(Opc);
976 const std::vector<OperandInfo>& InsnOperands = OpIter->second;
977 for (std::vector<OperandInfo>::const_iterator
Owen Andersond8c87882011-02-18 21:51:29 +0000978 I = InsnOperands.begin(), E = InsnOperands.end(); I != E; ++I) {
979 // If a custom instruction decoder was specified, use that.
Owen Andersond1e38df2011-07-28 21:54:31 +0000980 if (I->numFields() == 0 && I->Decoder.size()) {
Owen Anderson83e3f672011-08-17 17:44:15 +0000981 o.indent(Indentation) << " " << Emitter->GuardPrefix << I->Decoder
Jim Grosbach9c826d22012-02-29 22:07:56 +0000982 << "(MI, insn, Address, Decoder)"
983 << Emitter->GuardPostfix << "\n";
Owen Andersond8c87882011-02-18 21:51:29 +0000984 break;
985 }
986
Owen Andersond1e38df2011-07-28 21:54:31 +0000987 emitBinaryParser(o, Indentation, *I);
Owen Andersond8c87882011-02-18 21:51:29 +0000988 }
989
Jim Grosbach9c826d22012-02-29 22:07:56 +0000990 o.indent(Indentation) << " return " << Emitter->ReturnOK << "; // "
991 << nameWithID(Opc) << '\n';
James Molloya5d58562011-09-07 19:42:28 +0000992 o.indent(Indentation) << "}\n"; // Closing predicate block.
Owen Andersond8c87882011-02-18 21:51:29 +0000993 return true;
994 }
995
996 // Otherwise, there are more decodings to be done!
997
998 // Emit code to match the island(s) for the singleton.
999 o.indent(Indentation) << "// Check ";
1000
1001 for (I = Size; I != 0; --I) {
1002 o << "Inst{" << EndBits[I-1] << '-' << StartBits[I-1] << "} ";
1003 if (I > 1)
James Molloya5d58562011-09-07 19:42:28 +00001004 o << " && ";
Owen Andersond8c87882011-02-18 21:51:29 +00001005 else
1006 o << "for singleton decoding...\n";
1007 }
1008
1009 o.indent(Indentation) << "if (";
James Molloy0d76b192011-09-08 08:12:01 +00001010 if (emitPredicateMatch(o, Indentation, Opc)) {
James Molloya5d58562011-09-07 19:42:28 +00001011 o << " &&\n";
1012 o.indent(Indentation+4);
1013 }
Owen Andersond8c87882011-02-18 21:51:29 +00001014
1015 for (I = Size; I != 0; --I) {
1016 NumBits = EndBits[I-1] - StartBits[I-1] + 1;
Owen Andersonf1a00902011-07-19 21:06:00 +00001017 o << "fieldFromInstruction" << BitWidth << "(insn, "
1018 << StartBits[I-1] << ", " << NumBits
Owen Andersond8c87882011-02-18 21:51:29 +00001019 << ") == " << FieldVals[I-1];
1020 if (I > 1)
1021 o << " && ";
1022 else
1023 o << ") {\n";
1024 }
James Molloy3015dfb2012-02-09 10:56:31 +00001025 emitSoftFailCheck(o, Indentation+2, Opc);
Owen Andersond8c87882011-02-18 21:51:29 +00001026 o.indent(Indentation) << " MI.setOpcode(" << Opc << ");\n";
Craig Topper5a4c7902012-03-16 06:52:56 +00001027 std::map<unsigned, std::vector<OperandInfo> >::const_iterator OpIter =
1028 Operands.find(Opc);
1029 const std::vector<OperandInfo>& InsnOperands = OpIter->second;
1030 for (std::vector<OperandInfo>::const_iterator
Owen Andersond8c87882011-02-18 21:51:29 +00001031 I = InsnOperands.begin(), E = InsnOperands.end(); I != E; ++I) {
1032 // If a custom instruction decoder was specified, use that.
Owen Andersond1e38df2011-07-28 21:54:31 +00001033 if (I->numFields() == 0 && I->Decoder.size()) {
Owen Anderson83e3f672011-08-17 17:44:15 +00001034 o.indent(Indentation) << " " << Emitter->GuardPrefix << I->Decoder
Jim Grosbach9c826d22012-02-29 22:07:56 +00001035 << "(MI, insn, Address, Decoder)"
1036 << Emitter->GuardPostfix << "\n";
Owen Andersond8c87882011-02-18 21:51:29 +00001037 break;
1038 }
1039
Owen Andersond1e38df2011-07-28 21:54:31 +00001040 emitBinaryParser(o, Indentation, *I);
Owen Andersond8c87882011-02-18 21:51:29 +00001041 }
Jim Grosbach9c826d22012-02-29 22:07:56 +00001042 o.indent(Indentation) << " return " << Emitter->ReturnOK << "; // "
1043 << nameWithID(Opc) << '\n';
Owen Andersond8c87882011-02-18 21:51:29 +00001044 o.indent(Indentation) << "}\n";
1045
1046 return false;
1047}
1048
1049// Emits code to decode the singleton, and then to decode the rest.
1050void FilterChooser::emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,
Craig Toppereb5cd612012-03-16 05:58:09 +00001051 const Filter &Best) const {
Owen Andersond8c87882011-02-18 21:51:29 +00001052
1053 unsigned Opc = Best.getSingletonOpc();
1054
1055 emitSingletonDecoder(o, Indentation, Opc);
1056
1057 // Emit code for the rest.
1058 o.indent(Indentation) << "else\n";
1059
1060 Indentation += 2;
1061 Best.getVariableFC().emit(o, Indentation);
1062 Indentation -= 2;
1063}
1064
1065// Assign a single filter and run with it. Top level API client can initialize
1066// with a single filter to start the filtering process.
Craig Toppereb5cd612012-03-16 05:58:09 +00001067void FilterChooser::runSingleFilter(unsigned startBit, unsigned numBit,
1068 bool mixed) {
Owen Andersond8c87882011-02-18 21:51:29 +00001069 Filters.clear();
1070 Filter F(*this, startBit, numBit, true);
1071 Filters.push_back(F);
1072 BestIndex = 0; // Sole Filter instance to choose from.
1073 bestFilter().recurse();
1074}
1075
1076// reportRegion is a helper function for filterProcessor to mark a region as
1077// eligible for use as a filter region.
1078void FilterChooser::reportRegion(bitAttr_t RA, unsigned StartBit,
Craig Topperd9360452012-03-16 01:19:24 +00001079 unsigned BitIndex, bool AllowMixed) {
Owen Andersond8c87882011-02-18 21:51:29 +00001080 if (RA == ATTR_MIXED && AllowMixed)
1081 Filters.push_back(Filter(*this, StartBit, BitIndex - StartBit, true));
1082 else if (RA == ATTR_ALL_SET && !AllowMixed)
1083 Filters.push_back(Filter(*this, StartBit, BitIndex - StartBit, false));
1084}
1085
1086// FilterProcessor scans the well-known encoding bits of the instructions and
1087// builds up a list of candidate filters. It chooses the best filter and
1088// recursively descends down the decoding tree.
1089bool FilterChooser::filterProcessor(bool AllowMixed, bool Greedy) {
1090 Filters.clear();
1091 BestIndex = -1;
1092 unsigned numInstructions = Opcodes.size();
1093
1094 assert(numInstructions && "Filter created with no instructions");
1095
1096 // No further filtering is necessary.
1097 if (numInstructions == 1)
1098 return true;
1099
1100 // Heuristics. See also doFilter()'s "Heuristics" comment when num of
1101 // instructions is 3.
1102 if (AllowMixed && !Greedy) {
1103 assert(numInstructions == 3);
1104
1105 for (unsigned i = 0; i < Opcodes.size(); ++i) {
1106 std::vector<unsigned> StartBits;
1107 std::vector<unsigned> EndBits;
1108 std::vector<uint64_t> FieldVals;
1109 insn_t Insn;
1110
1111 insnWithID(Insn, Opcodes[i]);
1112
1113 // Look for islands of undecoded bits of any instruction.
1114 if (getIslands(StartBits, EndBits, FieldVals, Insn) > 0) {
1115 // Found an instruction with island(s). Now just assign a filter.
Craig Toppereb5cd612012-03-16 05:58:09 +00001116 runSingleFilter(StartBits[0], EndBits[0] - StartBits[0] + 1, true);
Owen Andersond8c87882011-02-18 21:51:29 +00001117 return true;
1118 }
1119 }
1120 }
1121
1122 unsigned BitIndex, InsnIndex;
1123
1124 // We maintain BIT_WIDTH copies of the bitAttrs automaton.
1125 // The automaton consumes the corresponding bit from each
1126 // instruction.
1127 //
1128 // Input symbols: 0, 1, and _ (unset).
1129 // States: NONE, FILTERED, ALL_SET, ALL_UNSET, and MIXED.
1130 // Initial state: NONE.
1131 //
1132 // (NONE) ------- [01] -> (ALL_SET)
1133 // (NONE) ------- _ ----> (ALL_UNSET)
1134 // (ALL_SET) ---- [01] -> (ALL_SET)
1135 // (ALL_SET) ---- _ ----> (MIXED)
1136 // (ALL_UNSET) -- [01] -> (MIXED)
1137 // (ALL_UNSET) -- _ ----> (ALL_UNSET)
1138 // (MIXED) ------ . ----> (MIXED)
1139 // (FILTERED)---- . ----> (FILTERED)
1140
Owen Andersonf1a00902011-07-19 21:06:00 +00001141 std::vector<bitAttr_t> bitAttrs;
Owen Andersond8c87882011-02-18 21:51:29 +00001142
1143 // FILTERED bit positions provide no entropy and are not worthy of pursuing.
1144 // Filter::recurse() set either BIT_TRUE or BIT_FALSE for each position.
Owen Andersonf1a00902011-07-19 21:06:00 +00001145 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex)
Owen Andersond8c87882011-02-18 21:51:29 +00001146 if (FilterBitValues[BitIndex] == BIT_TRUE ||
1147 FilterBitValues[BitIndex] == BIT_FALSE)
Owen Andersonf1a00902011-07-19 21:06:00 +00001148 bitAttrs.push_back(ATTR_FILTERED);
Owen Andersond8c87882011-02-18 21:51:29 +00001149 else
Owen Andersonf1a00902011-07-19 21:06:00 +00001150 bitAttrs.push_back(ATTR_NONE);
Owen Andersond8c87882011-02-18 21:51:29 +00001151
1152 for (InsnIndex = 0; InsnIndex < numInstructions; ++InsnIndex) {
1153 insn_t insn;
1154
1155 insnWithID(insn, Opcodes[InsnIndex]);
1156
Owen Andersonf1a00902011-07-19 21:06:00 +00001157 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
Owen Andersond8c87882011-02-18 21:51:29 +00001158 switch (bitAttrs[BitIndex]) {
1159 case ATTR_NONE:
1160 if (insn[BitIndex] == BIT_UNSET)
1161 bitAttrs[BitIndex] = ATTR_ALL_UNSET;
1162 else
1163 bitAttrs[BitIndex] = ATTR_ALL_SET;
1164 break;
1165 case ATTR_ALL_SET:
1166 if (insn[BitIndex] == BIT_UNSET)
1167 bitAttrs[BitIndex] = ATTR_MIXED;
1168 break;
1169 case ATTR_ALL_UNSET:
1170 if (insn[BitIndex] != BIT_UNSET)
1171 bitAttrs[BitIndex] = ATTR_MIXED;
1172 break;
1173 case ATTR_MIXED:
1174 case ATTR_FILTERED:
1175 break;
1176 }
1177 }
1178 }
1179
1180 // The regionAttr automaton consumes the bitAttrs automatons' state,
1181 // lowest-to-highest.
1182 //
1183 // Input symbols: F(iltered), (all_)S(et), (all_)U(nset), M(ixed)
1184 // States: NONE, ALL_SET, MIXED
1185 // Initial state: NONE
1186 //
1187 // (NONE) ----- F --> (NONE)
1188 // (NONE) ----- S --> (ALL_SET) ; and set region start
1189 // (NONE) ----- U --> (NONE)
1190 // (NONE) ----- M --> (MIXED) ; and set region start
1191 // (ALL_SET) -- F --> (NONE) ; and report an ALL_SET region
1192 // (ALL_SET) -- S --> (ALL_SET)
1193 // (ALL_SET) -- U --> (NONE) ; and report an ALL_SET region
1194 // (ALL_SET) -- M --> (MIXED) ; and report an ALL_SET region
1195 // (MIXED) ---- F --> (NONE) ; and report a MIXED region
1196 // (MIXED) ---- S --> (ALL_SET) ; and report a MIXED region
1197 // (MIXED) ---- U --> (NONE) ; and report a MIXED region
1198 // (MIXED) ---- M --> (MIXED)
1199
1200 bitAttr_t RA = ATTR_NONE;
1201 unsigned StartBit = 0;
1202
Owen Andersonf1a00902011-07-19 21:06:00 +00001203 for (BitIndex = 0; BitIndex < BitWidth; BitIndex++) {
Owen Andersond8c87882011-02-18 21:51:29 +00001204 bitAttr_t bitAttr = bitAttrs[BitIndex];
1205
1206 assert(bitAttr != ATTR_NONE && "Bit without attributes");
1207
1208 switch (RA) {
1209 case ATTR_NONE:
1210 switch (bitAttr) {
1211 case ATTR_FILTERED:
1212 break;
1213 case ATTR_ALL_SET:
1214 StartBit = BitIndex;
1215 RA = ATTR_ALL_SET;
1216 break;
1217 case ATTR_ALL_UNSET:
1218 break;
1219 case ATTR_MIXED:
1220 StartBit = BitIndex;
1221 RA = ATTR_MIXED;
1222 break;
1223 default:
Craig Topper655b8de2012-02-05 07:21:30 +00001224 llvm_unreachable("Unexpected bitAttr!");
Owen Andersond8c87882011-02-18 21:51:29 +00001225 }
1226 break;
1227 case ATTR_ALL_SET:
1228 switch (bitAttr) {
1229 case ATTR_FILTERED:
1230 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1231 RA = ATTR_NONE;
1232 break;
1233 case ATTR_ALL_SET:
1234 break;
1235 case ATTR_ALL_UNSET:
1236 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1237 RA = ATTR_NONE;
1238 break;
1239 case ATTR_MIXED:
1240 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1241 StartBit = BitIndex;
1242 RA = ATTR_MIXED;
1243 break;
1244 default:
Craig Topper655b8de2012-02-05 07:21:30 +00001245 llvm_unreachable("Unexpected bitAttr!");
Owen Andersond8c87882011-02-18 21:51:29 +00001246 }
1247 break;
1248 case ATTR_MIXED:
1249 switch (bitAttr) {
1250 case ATTR_FILTERED:
1251 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1252 StartBit = BitIndex;
1253 RA = ATTR_NONE;
1254 break;
1255 case ATTR_ALL_SET:
1256 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1257 StartBit = BitIndex;
1258 RA = ATTR_ALL_SET;
1259 break;
1260 case ATTR_ALL_UNSET:
1261 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1262 RA = ATTR_NONE;
1263 break;
1264 case ATTR_MIXED:
1265 break;
1266 default:
Craig Topper655b8de2012-02-05 07:21:30 +00001267 llvm_unreachable("Unexpected bitAttr!");
Owen Andersond8c87882011-02-18 21:51:29 +00001268 }
1269 break;
1270 case ATTR_ALL_UNSET:
Craig Topper655b8de2012-02-05 07:21:30 +00001271 llvm_unreachable("regionAttr state machine has no ATTR_UNSET state");
Owen Andersond8c87882011-02-18 21:51:29 +00001272 case ATTR_FILTERED:
Craig Topper655b8de2012-02-05 07:21:30 +00001273 llvm_unreachable("regionAttr state machine has no ATTR_FILTERED state");
Owen Andersond8c87882011-02-18 21:51:29 +00001274 }
1275 }
1276
1277 // At the end, if we're still in ALL_SET or MIXED states, report a region
1278 switch (RA) {
1279 case ATTR_NONE:
1280 break;
1281 case ATTR_FILTERED:
1282 break;
1283 case ATTR_ALL_SET:
1284 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1285 break;
1286 case ATTR_ALL_UNSET:
1287 break;
1288 case ATTR_MIXED:
1289 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1290 break;
1291 }
1292
1293 // We have finished with the filter processings. Now it's time to choose
1294 // the best performing filter.
1295 BestIndex = 0;
1296 bool AllUseless = true;
1297 unsigned BestScore = 0;
1298
1299 for (unsigned i = 0, e = Filters.size(); i != e; ++i) {
1300 unsigned Usefulness = Filters[i].usefulness();
1301
1302 if (Usefulness)
1303 AllUseless = false;
1304
1305 if (Usefulness > BestScore) {
1306 BestIndex = i;
1307 BestScore = Usefulness;
1308 }
1309 }
1310
1311 if (!AllUseless)
1312 bestFilter().recurse();
1313
1314 return !AllUseless;
1315} // end of FilterChooser::filterProcessor(bool)
1316
1317// Decides on the best configuration of filter(s) to use in order to decode
1318// the instructions. A conflict of instructions may occur, in which case we
1319// dump the conflict set to the standard error.
1320void FilterChooser::doFilter() {
1321 unsigned Num = Opcodes.size();
1322 assert(Num && "FilterChooser created with no instructions");
1323
1324 // Try regions of consecutive known bit values first.
1325 if (filterProcessor(false))
1326 return;
1327
1328 // Then regions of mixed bits (both known and unitialized bit values allowed).
1329 if (filterProcessor(true))
1330 return;
1331
1332 // Heuristics to cope with conflict set {t2CMPrs, t2SUBSrr, t2SUBSrs} where
1333 // no single instruction for the maximum ATTR_MIXED region Inst{14-4} has a
1334 // well-known encoding pattern. In such case, we backtrack and scan for the
1335 // the very first consecutive ATTR_ALL_SET region and assign a filter to it.
1336 if (Num == 3 && filterProcessor(true, false))
1337 return;
1338
1339 // If we come to here, the instruction decoding has failed.
1340 // Set the BestIndex to -1 to indicate so.
1341 BestIndex = -1;
1342}
1343
1344// Emits code to decode our share of instructions. Returns true if the
1345// emitted code causes a return, which occurs if we know how to decode
1346// the instruction at this level or the instruction is not decodeable.
Craig Toppereb5cd612012-03-16 05:58:09 +00001347bool FilterChooser::emit(raw_ostream &o, unsigned &Indentation) const {
Owen Andersond8c87882011-02-18 21:51:29 +00001348 if (Opcodes.size() == 1)
1349 // There is only one instruction in the set, which is great!
1350 // Call emitSingletonDecoder() to see whether there are any remaining
1351 // encodings bits.
1352 return emitSingletonDecoder(o, Indentation, Opcodes[0]);
1353
1354 // Choose the best filter to do the decodings!
1355 if (BestIndex != -1) {
Craig Toppereb5cd612012-03-16 05:58:09 +00001356 const Filter &Best = Filters[BestIndex];
Owen Andersond8c87882011-02-18 21:51:29 +00001357 if (Best.getNumFiltered() == 1)
1358 emitSingletonDecoder(o, Indentation, Best);
1359 else
Craig Toppereb5cd612012-03-16 05:58:09 +00001360 Best.emit(o, Indentation);
Owen Andersond8c87882011-02-18 21:51:29 +00001361 return false;
1362 }
1363
1364 // We don't know how to decode these instructions! Return 0 and dump the
1365 // conflict set!
1366 o.indent(Indentation) << "return 0;" << " // Conflict set: ";
1367 for (int i = 0, N = Opcodes.size(); i < N; ++i) {
1368 o << nameWithID(Opcodes[i]);
1369 if (i < (N - 1))
1370 o << ", ";
1371 else
1372 o << '\n';
1373 }
1374
1375 // Print out useful conflict information for postmortem analysis.
1376 errs() << "Decoding Conflict:\n";
1377
1378 dumpStack(errs(), "\t\t");
1379
Craig Topperd9360452012-03-16 01:19:24 +00001380 for (unsigned i = 0; i < Opcodes.size(); ++i) {
Owen Andersond8c87882011-02-18 21:51:29 +00001381 const std::string &Name = nameWithID(Opcodes[i]);
1382
1383 errs() << '\t' << Name << " ";
1384 dumpBits(errs(),
1385 getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
1386 errs() << '\n';
1387 }
1388
1389 return true;
1390}
1391
Craig Topperd9360452012-03-16 01:19:24 +00001392static bool populateInstruction(const CodeGenInstruction &CGI, unsigned Opc,
1393 std::map<unsigned, std::vector<OperandInfo> > &Operands){
Owen Andersond8c87882011-02-18 21:51:29 +00001394 const Record &Def = *CGI.TheDef;
1395 // If all the bit positions are not specified; do not decode this instruction.
1396 // We are bound to fail! For proper disassembly, the well-known encoding bits
1397 // of the instruction must be fully specified.
1398 //
1399 // This also removes pseudo instructions from considerations of disassembly,
1400 // which is a better design and less fragile than the name matchings.
Owen Andersond8c87882011-02-18 21:51:29 +00001401 // Ignore "asm parser only" instructions.
Owen Anderson4dd27eb2011-03-14 20:58:49 +00001402 if (Def.getValueAsBit("isAsmParserOnly") ||
1403 Def.getValueAsBit("isCodeGenOnly"))
Owen Andersond8c87882011-02-18 21:51:29 +00001404 return false;
1405
David Greene05bce0b2011-07-29 22:43:06 +00001406 BitsInit &Bits = getBitsField(Def, "Inst");
Jim Grosbach806fcc02011-07-06 21:33:38 +00001407 if (Bits.allInComplete()) return false;
1408
Owen Andersond8c87882011-02-18 21:51:29 +00001409 std::vector<OperandInfo> InsnOperands;
1410
1411 // If the instruction has specified a custom decoding hook, use that instead
1412 // of trying to auto-generate the decoder.
1413 std::string InstDecoder = Def.getValueAsString("DecoderMethod");
1414 if (InstDecoder != "") {
Owen Andersond1e38df2011-07-28 21:54:31 +00001415 InsnOperands.push_back(OperandInfo(InstDecoder));
Owen Andersond8c87882011-02-18 21:51:29 +00001416 Operands[Opc] = InsnOperands;
1417 return true;
1418 }
1419
1420 // Generate a description of the operand of the instruction that we know
1421 // how to decode automatically.
1422 // FIXME: We'll need to have a way to manually override this as needed.
1423
1424 // Gather the outputs/inputs of the instruction, so we can find their
1425 // positions in the encoding. This assumes for now that they appear in the
1426 // MCInst in the order that they're listed.
David Greene05bce0b2011-07-29 22:43:06 +00001427 std::vector<std::pair<Init*, std::string> > InOutOperands;
1428 DagInit *Out = Def.getValueAsDag("OutOperandList");
1429 DagInit *In = Def.getValueAsDag("InOperandList");
Owen Andersond8c87882011-02-18 21:51:29 +00001430 for (unsigned i = 0; i < Out->getNumArgs(); ++i)
1431 InOutOperands.push_back(std::make_pair(Out->getArg(i), Out->getArgName(i)));
1432 for (unsigned i = 0; i < In->getNumArgs(); ++i)
1433 InOutOperands.push_back(std::make_pair(In->getArg(i), In->getArgName(i)));
1434
Owen Anderson00ef6e32011-07-28 23:56:20 +00001435 // Search for tied operands, so that we can correctly instantiate
1436 // operands that are not explicitly represented in the encoding.
Owen Andersonea242982011-07-29 18:28:52 +00001437 std::map<std::string, std::string> TiedNames;
Owen Anderson00ef6e32011-07-28 23:56:20 +00001438 for (unsigned i = 0; i < CGI.Operands.size(); ++i) {
1439 int tiedTo = CGI.Operands[i].getTiedRegister();
Owen Andersonea242982011-07-29 18:28:52 +00001440 if (tiedTo != -1) {
1441 TiedNames[InOutOperands[i].second] = InOutOperands[tiedTo].second;
1442 TiedNames[InOutOperands[tiedTo].second] = InOutOperands[i].second;
1443 }
Owen Anderson00ef6e32011-07-28 23:56:20 +00001444 }
1445
Owen Andersond8c87882011-02-18 21:51:29 +00001446 // For each operand, see if we can figure out where it is encoded.
Craig Topper5a4c7902012-03-16 06:52:56 +00001447 for (std::vector<std::pair<Init*, std::string> >::const_iterator
Owen Andersond8c87882011-02-18 21:51:29 +00001448 NI = InOutOperands.begin(), NE = InOutOperands.end(); NI != NE; ++NI) {
Owen Andersond8c87882011-02-18 21:51:29 +00001449 std::string Decoder = "";
1450
Owen Andersond1e38df2011-07-28 21:54:31 +00001451 // At this point, we can locate the field, but we need to know how to
1452 // interpret it. As a first step, require the target to provide callbacks
1453 // for decoding register classes.
1454 // FIXME: This need to be extended to handle instructions with custom
1455 // decoder methods, and operands with (simple) MIOperandInfo's.
David Greene05bce0b2011-07-29 22:43:06 +00001456 TypedInit *TI = dynamic_cast<TypedInit*>(NI->first);
Owen Andersond1e38df2011-07-28 21:54:31 +00001457 RecordRecTy *Type = dynamic_cast<RecordRecTy*>(TI->getType());
1458 Record *TypeRecord = Type->getRecord();
1459 bool isReg = false;
1460 if (TypeRecord->isSubClassOf("RegisterOperand"))
1461 TypeRecord = TypeRecord->getValueAsDef("RegClass");
1462 if (TypeRecord->isSubClassOf("RegisterClass")) {
1463 Decoder = "Decode" + TypeRecord->getName() + "RegisterClass";
1464 isReg = true;
1465 }
1466
1467 RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod");
David Greene05bce0b2011-07-29 22:43:06 +00001468 StringInit *String = DecoderString ?
1469 dynamic_cast<StringInit*>(DecoderString->getValue()) : 0;
Owen Andersond1e38df2011-07-28 21:54:31 +00001470 if (!isReg && String && String->getValue() != "")
1471 Decoder = String->getValue();
1472
1473 OperandInfo OpInfo(Decoder);
1474 unsigned Base = ~0U;
1475 unsigned Width = 0;
1476 unsigned Offset = 0;
1477
Owen Andersond8c87882011-02-18 21:51:29 +00001478 for (unsigned bi = 0; bi < Bits.getNumBits(); ++bi) {
Owen Andersoncf603952011-08-01 22:45:43 +00001479 VarInit *Var = 0;
David Greene05bce0b2011-07-29 22:43:06 +00001480 VarBitInit *BI = dynamic_cast<VarBitInit*>(Bits.getBit(bi));
Owen Andersoncf603952011-08-01 22:45:43 +00001481 if (BI)
1482 Var = dynamic_cast<VarInit*>(BI->getVariable());
1483 else
1484 Var = dynamic_cast<VarInit*>(Bits.getBit(bi));
1485
1486 if (!Var) {
Owen Andersond1e38df2011-07-28 21:54:31 +00001487 if (Base != ~0U) {
1488 OpInfo.addField(Base, Width, Offset);
1489 Base = ~0U;
1490 Width = 0;
1491 Offset = 0;
1492 }
1493 continue;
1494 }
Owen Andersond8c87882011-02-18 21:51:29 +00001495
Owen Anderson00ef6e32011-07-28 23:56:20 +00001496 if (Var->getName() != NI->second &&
Owen Andersonea242982011-07-29 18:28:52 +00001497 Var->getName() != TiedNames[NI->second]) {
Owen Andersond1e38df2011-07-28 21:54:31 +00001498 if (Base != ~0U) {
1499 OpInfo.addField(Base, Width, Offset);
1500 Base = ~0U;
1501 Width = 0;
1502 Offset = 0;
1503 }
1504 continue;
Owen Andersond8c87882011-02-18 21:51:29 +00001505 }
1506
Owen Andersond1e38df2011-07-28 21:54:31 +00001507 if (Base == ~0U) {
1508 Base = bi;
1509 Width = 1;
Owen Andersoncf603952011-08-01 22:45:43 +00001510 Offset = BI ? BI->getBitNum() : 0;
1511 } else if (BI && BI->getBitNum() != Offset + Width) {
Owen Andersoneb809f52011-07-29 23:01:18 +00001512 OpInfo.addField(Base, Width, Offset);
1513 Base = bi;
1514 Width = 1;
1515 Offset = BI->getBitNum();
Owen Andersond1e38df2011-07-28 21:54:31 +00001516 } else {
1517 ++Width;
Owen Andersond8c87882011-02-18 21:51:29 +00001518 }
Owen Andersond8c87882011-02-18 21:51:29 +00001519 }
1520
Owen Andersond1e38df2011-07-28 21:54:31 +00001521 if (Base != ~0U)
1522 OpInfo.addField(Base, Width, Offset);
1523
1524 if (OpInfo.numFields() > 0)
1525 InsnOperands.push_back(OpInfo);
Owen Andersond8c87882011-02-18 21:51:29 +00001526 }
1527
1528 Operands[Opc] = InsnOperands;
1529
1530
1531#if 0
1532 DEBUG({
1533 // Dumps the instruction encoding bits.
1534 dumpBits(errs(), Bits);
1535
1536 errs() << '\n';
1537
1538 // Dumps the list of operand info.
1539 for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) {
1540 const CGIOperandList::OperandInfo &Info = CGI.Operands[i];
1541 const std::string &OperandName = Info.Name;
1542 const Record &OperandDef = *Info.Rec;
1543
1544 errs() << "\t" << OperandName << " (" << OperandDef.getName() << ")\n";
1545 }
1546 });
1547#endif
1548
1549 return true;
1550}
1551
Owen Andersonf1a00902011-07-19 21:06:00 +00001552static void emitHelper(llvm::raw_ostream &o, unsigned BitWidth) {
1553 unsigned Indentation = 0;
1554 std::string WidthStr = "uint" + utostr(BitWidth) + "_t";
Owen Andersond8c87882011-02-18 21:51:29 +00001555
Owen Andersonf1a00902011-07-19 21:06:00 +00001556 o << '\n';
1557
1558 o.indent(Indentation) << "static " << WidthStr <<
1559 " fieldFromInstruction" << BitWidth <<
1560 "(" << WidthStr <<" insn, unsigned startBit, unsigned numBits)\n";
1561
1562 o.indent(Indentation) << "{\n";
1563
1564 ++Indentation; ++Indentation;
1565 o.indent(Indentation) << "assert(startBit + numBits <= " << BitWidth
1566 << " && \"Instruction field out of bounds!\");\n";
1567 o << '\n';
1568 o.indent(Indentation) << WidthStr << " fieldMask;\n";
1569 o << '\n';
1570 o.indent(Indentation) << "if (numBits == " << BitWidth << ")\n";
1571
1572 ++Indentation; ++Indentation;
1573 o.indent(Indentation) << "fieldMask = (" << WidthStr << ")-1;\n";
1574 --Indentation; --Indentation;
1575
1576 o.indent(Indentation) << "else\n";
1577
1578 ++Indentation; ++Indentation;
1579 o.indent(Indentation) << "fieldMask = ((1 << numBits) - 1) << startBit;\n";
1580 --Indentation; --Indentation;
1581
1582 o << '\n';
1583 o.indent(Indentation) << "return (insn & fieldMask) >> startBit;\n";
1584 --Indentation; --Indentation;
1585
1586 o.indent(Indentation) << "}\n";
1587
1588 o << '\n';
Owen Andersond8c87882011-02-18 21:51:29 +00001589}
1590
1591// Emits disassembler code for instruction decoding.
Craig Topperd9360452012-03-16 01:19:24 +00001592void FixedLenDecoderEmitter::run(raw_ostream &o) {
Owen Andersond8c87882011-02-18 21:51:29 +00001593 o << "#include \"llvm/MC/MCInst.h\"\n";
1594 o << "#include \"llvm/Support/DataTypes.h\"\n";
1595 o << "#include <assert.h>\n";
1596 o << '\n';
1597 o << "namespace llvm {\n\n";
1598
Owen Andersonf1a00902011-07-19 21:06:00 +00001599 // Parameterize the decoders based on namespace and instruction width.
Craig Toppereb5cd612012-03-16 05:58:09 +00001600 const std::vector<const CodeGenInstruction*> &NumberedInstructions =
Craig Topperc007ba82012-03-13 06:39:00 +00001601 Target.getInstructionsByEnumValue();
Owen Andersonf1a00902011-07-19 21:06:00 +00001602 std::map<std::pair<std::string, unsigned>,
1603 std::vector<unsigned> > OpcMap;
1604 std::map<unsigned, std::vector<OperandInfo> > Operands;
1605
1606 for (unsigned i = 0; i < NumberedInstructions.size(); ++i) {
1607 const CodeGenInstruction *Inst = NumberedInstructions[i];
Craig Toppereb5cd612012-03-16 05:58:09 +00001608 const Record *Def = Inst->TheDef;
Owen Andersonf1a00902011-07-19 21:06:00 +00001609 unsigned Size = Def->getValueAsInt("Size");
1610 if (Def->getValueAsString("Namespace") == "TargetOpcode" ||
1611 Def->getValueAsBit("isPseudo") ||
1612 Def->getValueAsBit("isAsmParserOnly") ||
1613 Def->getValueAsBit("isCodeGenOnly"))
1614 continue;
1615
1616 std::string DecoderNamespace = Def->getValueAsString("DecoderNamespace");
1617
1618 if (Size) {
1619 if (populateInstruction(*Inst, i, Operands)) {
1620 OpcMap[std::make_pair(DecoderNamespace, Size)].push_back(i);
1621 }
1622 }
1623 }
1624
1625 std::set<unsigned> Sizes;
1626 for (std::map<std::pair<std::string, unsigned>,
Craig Toppereb5cd612012-03-16 05:58:09 +00001627 std::vector<unsigned> >::const_iterator
Owen Andersonf1a00902011-07-19 21:06:00 +00001628 I = OpcMap.begin(), E = OpcMap.end(); I != E; ++I) {
1629 // If we haven't visited this instruction width before, emit the
1630 // helper method to extract fields.
1631 if (!Sizes.count(I->first.second)) {
1632 emitHelper(o, 8*I->first.second);
1633 Sizes.insert(I->first.second);
1634 }
1635
1636 // Emit the decoder for this namespace+width combination.
1637 FilterChooser FC(NumberedInstructions, I->second, Operands,
Owen Anderson83e3f672011-08-17 17:44:15 +00001638 8*I->first.second, this);
Owen Andersonf1a00902011-07-19 21:06:00 +00001639 FC.emitTop(o, 0, I->first.first);
1640 }
Owen Andersond8c87882011-02-18 21:51:29 +00001641
1642 o << "\n} // End llvm namespace \n";
1643}
Jakob Stoklund Olesen6f36fa92012-06-11 15:37:55 +00001644
1645namespace llvm {
1646
1647void EmitFixedLenDecoder(RecordKeeper &RK, raw_ostream &OS,
1648 std::string PredicateNamespace,
1649 std::string GPrefix,
1650 std::string GPostfix,
1651 std::string ROK,
1652 std::string RFail,
1653 std::string L) {
1654 FixedLenDecoderEmitter(RK, PredicateNamespace, GPrefix, GPostfix,
1655 ROK, RFail, L).run(OS);
1656}
1657
1658} // End llvm namespace