blob: d0c4e0fd2f9960e171e3fe9489ebfcaef2702057 [file] [log] [blame]
Owen Anderson4e818902011-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
Owen Anderson4e818902011-02-18 21:51:29 +000015#include "CodeGenTarget.h"
James Molloyd9ba4fd2012-02-09 10:56:31 +000016#include "llvm/ADT/APInt.h"
Jim Grosbachecaef492012-08-14 19:06:05 +000017#include "llvm/ADT/SmallString.h"
Owen Anderson4e818902011-02-18 21:51:29 +000018#include "llvm/ADT/StringExtras.h"
Jim Grosbachecaef492012-08-14 19:06:05 +000019#include "llvm/ADT/StringRef.h"
20#include "llvm/ADT/Twine.h"
21#include "llvm/MC/MCFixedLenDisassembler.h"
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000022#include "llvm/Support/DataTypes.h"
Owen Anderson4e818902011-02-18 21:51:29 +000023#include "llvm/Support/Debug.h"
Jim Grosbachecaef492012-08-14 19:06:05 +000024#include "llvm/Support/FormattedStream.h"
25#include "llvm/Support/LEB128.h"
Owen Anderson4e818902011-02-18 21:51:29 +000026#include "llvm/Support/raw_ostream.h"
Chandler Carruth91d19d82012-12-04 10:37:14 +000027#include "llvm/TableGen/Error.h"
28#include "llvm/TableGen/Record.h"
Owen Anderson4e818902011-02-18 21:51:29 +000029#include <map>
30#include <string>
Benjamin Kramer82de7d32016-05-27 14:27:24 +000031#include <utility>
Chandler Carruth91d19d82012-12-04 10:37:14 +000032#include <vector>
Owen Anderson4e818902011-02-18 21:51:29 +000033
34using namespace llvm;
35
Chandler Carruth97acce22014-04-22 03:06:00 +000036#define DEBUG_TYPE "decoder-emitter"
37
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000038namespace {
39struct EncodingField {
40 unsigned Base, Width, Offset;
41 EncodingField(unsigned B, unsigned W, unsigned O)
42 : Base(B), Width(W), Offset(O) { }
43};
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000044
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000045struct OperandInfo {
46 std::vector<EncodingField> Fields;
47 std::string Decoder;
Petr Pavlu182b0572015-07-15 08:04:27 +000048 bool HasCompleteDecoder;
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000049
Petr Pavlu182b0572015-07-15 08:04:27 +000050 OperandInfo(std::string D, bool HCD)
Benjamin Kramer82de7d32016-05-27 14:27:24 +000051 : Decoder(std::move(D)), HasCompleteDecoder(HCD) {}
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000052
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 Grosbachecaef492012-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;
Rafael Espindola55512f92015-11-18 06:52:18 +000069typedef SmallSetVector<std::string, 16> PredicateSet;
70typedef SmallSetVector<std::string, 16> DecoderSet;
Jim Grosbachecaef492012-08-14 19:06:05 +000071struct DecoderTableInfo {
72 DecoderTable Table;
73 FixupScopeList FixupStack;
74 PredicateSet Predicates;
75 DecoderSet Decoders;
76};
77
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000078} // End anonymous namespace
79
80namespace {
81class FixedLenDecoderEmitter {
Craig Topperf9265322016-01-17 20:38:14 +000082 ArrayRef<const CodeGenInstruction *> NumberedInstructions;
Jakob Stoklund Olesene6aed132012-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.
Benjamin Kramer82de7d32016-05-27 14:27:24 +000087 FixedLenDecoderEmitter(RecordKeeper &R, std::string PredicateNamespace,
88 std::string GPrefix = "if (",
Petr Pavlu182b0572015-07-15 08:04:27 +000089 std::string GPostfix = " == MCDisassembler::Fail)",
Benjamin Kramer82de7d32016-05-27 14:27:24 +000090 std::string ROK = "MCDisassembler::Success",
91 std::string RFail = "MCDisassembler::Fail",
92 std::string L = "")
93 : Target(R), PredicateNamespace(std::move(PredicateNamespace)),
94 GuardPrefix(std::move(GPrefix)), GuardPostfix(std::move(GPostfix)),
95 ReturnOK(std::move(ROK)), ReturnFail(std::move(RFail)),
96 Locals(std::move(L)) {}
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000097
Jim Grosbachecaef492012-08-14 19:06:05 +000098 // Emit the decoder state machine table.
99 void emitTable(formatted_raw_ostream &o, DecoderTable &Table,
100 unsigned Indentation, unsigned BitWidth,
101 StringRef Namespace) const;
102 void emitPredicateFunction(formatted_raw_ostream &OS,
103 PredicateSet &Predicates,
104 unsigned Indentation) const;
105 void emitDecoderFunction(formatted_raw_ostream &OS,
106 DecoderSet &Decoders,
107 unsigned Indentation) const;
108
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +0000109 // run - Output the code emitter
110 void run(raw_ostream &o);
111
112private:
113 CodeGenTarget Target;
114public:
115 std::string PredicateNamespace;
116 std::string GuardPrefix, GuardPostfix;
117 std::string ReturnOK, ReturnFail;
118 std::string Locals;
119};
120} // End anonymous namespace
121
Owen Anderson4e818902011-02-18 21:51:29 +0000122// The set (BIT_TRUE, BIT_FALSE, BIT_UNSET) represents a ternary logic system
123// for a bit value.
124//
125// BIT_UNFILTERED is used as the init value for a filter position. It is used
126// only for filter processings.
127typedef enum {
128 BIT_TRUE, // '1'
129 BIT_FALSE, // '0'
130 BIT_UNSET, // '?'
131 BIT_UNFILTERED // unfiltered
132} bit_value_t;
133
134static bool ValueSet(bit_value_t V) {
135 return (V == BIT_TRUE || V == BIT_FALSE);
136}
137static bool ValueNotSet(bit_value_t V) {
138 return (V == BIT_UNSET);
139}
140static int Value(bit_value_t V) {
141 return ValueNotSet(V) ? -1 : (V == BIT_FALSE ? 0 : 1);
142}
Craig Topper48c112b2012-03-16 05:58:09 +0000143static bit_value_t bitFromBits(const BitsInit &bits, unsigned index) {
Sean Silvafb509ed2012-10-10 20:24:43 +0000144 if (BitInit *bit = dyn_cast<BitInit>(bits.getBit(index)))
Owen Anderson4e818902011-02-18 21:51:29 +0000145 return bit->getValue() ? BIT_TRUE : BIT_FALSE;
146
147 // The bit is uninitialized.
148 return BIT_UNSET;
149}
150// Prints the bit value for each position.
Craig Topper48c112b2012-03-16 05:58:09 +0000151static void dumpBits(raw_ostream &o, const BitsInit &bits) {
Craig Topper29688ab2012-08-17 05:42:16 +0000152 for (unsigned index = bits.getNumBits(); index > 0; --index) {
Owen Anderson4e818902011-02-18 21:51:29 +0000153 switch (bitFromBits(bits, index - 1)) {
154 case BIT_TRUE:
155 o << "1";
156 break;
157 case BIT_FALSE:
158 o << "0";
159 break;
160 case BIT_UNSET:
161 o << "_";
162 break;
163 default:
Craig Topperc4965bc2012-02-05 07:21:30 +0000164 llvm_unreachable("unexpected return value from bitFromBits");
Owen Anderson4e818902011-02-18 21:51:29 +0000165 }
166 }
167}
168
Mehdi Amini32986ed2016-10-04 23:47:33 +0000169static BitsInit &getBitsField(const Record &def, StringRef str) {
David Greeneaf8ee2c2011-07-29 22:43:06 +0000170 BitsInit *bits = def.getValueAsBitsInit(str);
Owen Anderson4e818902011-02-18 21:51:29 +0000171 return *bits;
172}
173
174// Forward declaration.
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +0000175namespace {
Owen Anderson4e818902011-02-18 21:51:29 +0000176class FilterChooser;
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +0000177} // End anonymous namespace
Owen Anderson4e818902011-02-18 21:51:29 +0000178
Owen Anderson4e818902011-02-18 21:51:29 +0000179// Representation of the instruction to work on.
Owen Andersonc78e03c2011-07-19 21:06:00 +0000180typedef std::vector<bit_value_t> insn_t;
Owen Anderson4e818902011-02-18 21:51:29 +0000181
182/// Filter - Filter works with FilterChooser to produce the decoding tree for
183/// the ISA.
184///
185/// It is useful to think of a Filter as governing the switch stmts of the
186/// decoding tree in a certain level. Each case stmt delegates to an inferior
187/// FilterChooser to decide what further decoding logic to employ, or in another
188/// words, what other remaining bits to look at. The FilterChooser eventually
189/// chooses a best Filter to do its job.
190///
191/// This recursive scheme ends when the number of Opcodes assigned to the
192/// FilterChooser becomes 1 or if there is a conflict. A conflict happens when
193/// the Filter/FilterChooser combo does not know how to distinguish among the
194/// Opcodes assigned.
195///
196/// An example of a conflict is
197///
198/// Conflict:
199/// 111101000.00........00010000....
200/// 111101000.00........0001........
201/// 1111010...00........0001........
202/// 1111010...00....................
203/// 1111010.........................
204/// 1111............................
205/// ................................
206/// VST4q8a 111101000_00________00010000____
207/// VST4q8b 111101000_00________00010000____
208///
209/// The Debug output shows the path that the decoding tree follows to reach the
210/// the conclusion that there is a conflict. VST4q8a is a vst4 to double-spaced
Petr Pavlu21894652015-07-14 08:00:34 +0000211/// even registers, while VST4q8b is a vst4 to double-spaced odd registers.
Owen Anderson4e818902011-02-18 21:51:29 +0000212///
213/// The encoding info in the .td files does not specify this meta information,
214/// which could have been used by the decoder to resolve the conflict. The
215/// decoder could try to decode the even/odd register numbering and assign to
216/// VST4q8a or VST4q8b, but for the time being, the decoder chooses the "a"
217/// version and return the Opcode since the two have the same Asm format string.
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +0000218namespace {
Owen Anderson4e818902011-02-18 21:51:29 +0000219class Filter {
220protected:
Craig Topper501d95c2012-03-16 06:52:56 +0000221 const FilterChooser *Owner;// points to the FilterChooser who owns this filter
Owen Anderson4e818902011-02-18 21:51:29 +0000222 unsigned StartBit; // the starting bit position
223 unsigned NumBits; // number of bits to filter
224 bool Mixed; // a mixed region contains both set and unset bits
225
226 // Map of well-known segment value to the set of uid's with that value.
227 std::map<uint64_t, std::vector<unsigned> > FilteredInstructions;
228
229 // Set of uid's with non-constant segment values.
230 std::vector<unsigned> VariableInstructions;
231
232 // Map of well-known segment value to its delegate.
Craig Toppercf05f912014-09-03 06:07:54 +0000233 std::map<unsigned, std::unique_ptr<const FilterChooser>> FilterChooserMap;
Owen Anderson4e818902011-02-18 21:51:29 +0000234
235 // Number of instructions which fall under FilteredInstructions category.
236 unsigned NumFiltered;
237
238 // Keeps track of the last opcode in the filtered bucket.
239 unsigned LastOpcFiltered;
240
Owen Anderson4e818902011-02-18 21:51:29 +0000241public:
Craig Topper48c112b2012-03-16 05:58:09 +0000242 unsigned getNumFiltered() const { return NumFiltered; }
243 unsigned getSingletonOpc() const {
Owen Anderson4e818902011-02-18 21:51:29 +0000244 assert(NumFiltered == 1);
245 return LastOpcFiltered;
246 }
247 // Return the filter chooser for the group of instructions without constant
248 // segment values.
Craig Topper48c112b2012-03-16 05:58:09 +0000249 const FilterChooser &getVariableFC() const {
Owen Anderson4e818902011-02-18 21:51:29 +0000250 assert(NumFiltered == 1);
251 assert(FilterChooserMap.size() == 1);
252 return *(FilterChooserMap.find((unsigned)-1)->second);
253 }
254
Craig Topper5c2b4ac2014-09-03 05:49:07 +0000255 Filter(Filter &&f);
Owen Anderson4e818902011-02-18 21:51:29 +0000256 Filter(FilterChooser &owner, unsigned startBit, unsigned numBits, bool mixed);
257
258 ~Filter();
259
260 // Divides the decoding task into sub tasks and delegates them to the
261 // inferior FilterChooser's.
262 //
263 // A special case arises when there's only one entry in the filtered
264 // instructions. In order to unambiguously decode the singleton, we need to
265 // match the remaining undecoded encoding bits against the singleton.
266 void recurse();
267
Jim Grosbachecaef492012-08-14 19:06:05 +0000268 // Emit table entries to decode instructions given a segment or segments of
269 // bits.
270 void emitTableEntry(DecoderTableInfo &TableInfo) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000271
272 // Returns the number of fanout produced by the filter. More fanout implies
273 // the filter distinguishes more categories of instructions.
274 unsigned usefulness() const;
275}; // End of class Filter
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +0000276} // End anonymous namespace
Owen Anderson4e818902011-02-18 21:51:29 +0000277
278// These are states of our finite state machines used in FilterChooser's
279// filterProcessor() which produces the filter candidates to use.
280typedef enum {
281 ATTR_NONE,
282 ATTR_FILTERED,
283 ATTR_ALL_SET,
284 ATTR_ALL_UNSET,
285 ATTR_MIXED
286} bitAttr_t;
287
288/// FilterChooser - FilterChooser chooses the best filter among a set of Filters
289/// in order to perform the decoding of instructions at the current level.
290///
291/// Decoding proceeds from the top down. Based on the well-known encoding bits
292/// of instructions available, FilterChooser builds up the possible Filters that
293/// can further the task of decoding by distinguishing among the remaining
294/// candidate instructions.
295///
296/// Once a filter has been chosen, it is called upon to divide the decoding task
297/// into sub-tasks and delegates them to its inferior FilterChoosers for further
298/// processings.
299///
300/// It is useful to think of a Filter as governing the switch stmts of the
301/// decoding tree. And each case is delegated to an inferior FilterChooser to
302/// decide what further remaining bits to look at.
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +0000303namespace {
Owen Anderson4e818902011-02-18 21:51:29 +0000304class FilterChooser {
305protected:
306 friend class Filter;
307
308 // Vector of codegen instructions to choose our filter.
Craig Topperf9265322016-01-17 20:38:14 +0000309 ArrayRef<const CodeGenInstruction *> AllInstructions;
Owen Anderson4e818902011-02-18 21:51:29 +0000310
311 // Vector of uid's for this filter chooser to work on.
Craig Topper501d95c2012-03-16 06:52:56 +0000312 const std::vector<unsigned> &Opcodes;
Owen Anderson4e818902011-02-18 21:51:29 +0000313
314 // Lookup table for the operand decoding of instructions.
Craig Topper501d95c2012-03-16 06:52:56 +0000315 const std::map<unsigned, std::vector<OperandInfo> > &Operands;
Owen Anderson4e818902011-02-18 21:51:29 +0000316
317 // Vector of candidate filters.
318 std::vector<Filter> Filters;
319
320 // Array of bit values passed down from our parent.
321 // Set to all BIT_UNFILTERED's for Parent == NULL.
Owen Andersonc78e03c2011-07-19 21:06:00 +0000322 std::vector<bit_value_t> FilterBitValues;
Owen Anderson4e818902011-02-18 21:51:29 +0000323
324 // Links to the FilterChooser above us in the decoding tree.
Craig Topper501d95c2012-03-16 06:52:56 +0000325 const FilterChooser *Parent;
Owen Anderson4e818902011-02-18 21:51:29 +0000326
327 // Index of the best filter from Filters.
328 int BestIndex;
329
Owen Andersonc78e03c2011-07-19 21:06:00 +0000330 // Width of instructions
331 unsigned BitWidth;
332
Owen Andersona4043c42011-08-17 17:44:15 +0000333 // Parent emitter
334 const FixedLenDecoderEmitter *Emitter;
335
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000336 FilterChooser(const FilterChooser &) = delete;
337 void operator=(const FilterChooser &) = delete;
Owen Anderson4e818902011-02-18 21:51:29 +0000338public:
Owen Anderson4e818902011-02-18 21:51:29 +0000339
Craig Topperf9265322016-01-17 20:38:14 +0000340 FilterChooser(ArrayRef<const CodeGenInstruction *> Insts,
Owen Anderson4e818902011-02-18 21:51:29 +0000341 const std::vector<unsigned> &IDs,
Craig Topper501d95c2012-03-16 06:52:56 +0000342 const std::map<unsigned, std::vector<OperandInfo> > &Ops,
Owen Andersona4043c42011-08-17 17:44:15 +0000343 unsigned BW,
Craig Topper82d0d5f2012-03-16 01:19:24 +0000344 const FixedLenDecoderEmitter *E)
345 : AllInstructions(Insts), Opcodes(IDs), Operands(Ops), Filters(),
Craig Topper1ddc2882014-09-04 04:49:03 +0000346 FilterBitValues(BW, BIT_UNFILTERED), Parent(nullptr), BestIndex(-1),
347 BitWidth(BW), Emitter(E) {
Owen Anderson4e818902011-02-18 21:51:29 +0000348 doFilter();
349 }
350
Craig Topperf9265322016-01-17 20:38:14 +0000351 FilterChooser(ArrayRef<const CodeGenInstruction *> Insts,
Owen Anderson4e818902011-02-18 21:51:29 +0000352 const std::vector<unsigned> &IDs,
Craig Topper501d95c2012-03-16 06:52:56 +0000353 const std::map<unsigned, std::vector<OperandInfo> > &Ops,
354 const std::vector<bit_value_t> &ParentFilterBitValues,
355 const FilterChooser &parent)
Craig Topper82d0d5f2012-03-16 01:19:24 +0000356 : AllInstructions(Insts), Opcodes(IDs), Operands(Ops),
Owen Andersonc78e03c2011-07-19 21:06:00 +0000357 Filters(), FilterBitValues(ParentFilterBitValues),
Owen Andersona4043c42011-08-17 17:44:15 +0000358 Parent(&parent), BestIndex(-1), BitWidth(parent.BitWidth),
359 Emitter(parent.Emitter) {
Owen Anderson4e818902011-02-18 21:51:29 +0000360 doFilter();
361 }
362
Jim Grosbachecaef492012-08-14 19:06:05 +0000363 unsigned getBitWidth() const { return BitWidth; }
Owen Anderson4e818902011-02-18 21:51:29 +0000364
365protected:
366 // Populates the insn given the uid.
367 void insnWithID(insn_t &Insn, unsigned Opcode) const {
David Greeneaf8ee2c2011-07-29 22:43:06 +0000368 BitsInit &Bits = getBitsField(*AllInstructions[Opcode]->TheDef, "Inst");
Owen Anderson4e818902011-02-18 21:51:29 +0000369
James Molloyd9ba4fd2012-02-09 10:56:31 +0000370 // We may have a SoftFail bitmask, which specifies a mask where an encoding
371 // may differ from the value in "Inst" and yet still be valid, but the
372 // disassembler should return SoftFail instead of Success.
373 //
374 // This is used for marking UNPREDICTABLE instructions in the ARM world.
Jim Grosbach3f4b2392012-02-29 22:07:56 +0000375 BitsInit *SFBits =
376 AllInstructions[Opcode]->TheDef->getValueAsBitsInit("SoftFail");
James Molloyd9ba4fd2012-02-09 10:56:31 +0000377
378 for (unsigned i = 0; i < BitWidth; ++i) {
379 if (SFBits && bitFromBits(*SFBits, i) == BIT_TRUE)
380 Insn.push_back(BIT_UNSET);
381 else
382 Insn.push_back(bitFromBits(Bits, i));
383 }
Owen Anderson4e818902011-02-18 21:51:29 +0000384 }
385
386 // Returns the record name.
387 const std::string &nameWithID(unsigned Opcode) const {
388 return AllInstructions[Opcode]->TheDef->getName();
389 }
390
391 // Populates the field of the insn given the start position and the number of
392 // consecutive bits to scan for.
393 //
394 // Returns false if there exists any uninitialized bit value in the range.
395 // Returns true, otherwise.
396 bool fieldFromInsn(uint64_t &Field, insn_t &Insn, unsigned StartBit,
Craig Topper82d0d5f2012-03-16 01:19:24 +0000397 unsigned NumBits) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000398
399 /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
400 /// filter array as a series of chars.
Craig Topper48c112b2012-03-16 05:58:09 +0000401 void dumpFilterArray(raw_ostream &o,
402 const std::vector<bit_value_t> & filter) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000403
404 /// dumpStack - dumpStack traverses the filter chooser chain and calls
405 /// dumpFilterArray on each filter chooser up to the top level one.
Craig Topper48c112b2012-03-16 05:58:09 +0000406 void dumpStack(raw_ostream &o, const char *prefix) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000407
408 Filter &bestFilter() {
409 assert(BestIndex != -1 && "BestIndex not set");
410 return Filters[BestIndex];
411 }
412
Craig Topper48c112b2012-03-16 05:58:09 +0000413 bool PositionFiltered(unsigned i) const {
Owen Anderson4e818902011-02-18 21:51:29 +0000414 return ValueSet(FilterBitValues[i]);
415 }
416
417 // Calculates the island(s) needed to decode the instruction.
418 // This returns a lit of undecoded bits of an instructions, for example,
419 // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
420 // decoded bits in order to verify that the instruction matches the Opcode.
421 unsigned getIslands(std::vector<unsigned> &StartBits,
Craig Topper82d0d5f2012-03-16 01:19:24 +0000422 std::vector<unsigned> &EndBits,
Craig Topper48c112b2012-03-16 05:58:09 +0000423 std::vector<uint64_t> &FieldVals,
424 const insn_t &Insn) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000425
James Molloy8067df92011-09-07 19:42:28 +0000426 // Emits code to check the Predicates member of an instruction are true.
427 // Returns true if predicate matches were emitted, false otherwise.
Craig Topper48c112b2012-03-16 05:58:09 +0000428 bool emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
429 unsigned Opc) const;
James Molloy8067df92011-09-07 19:42:28 +0000430
Jim Grosbachecaef492012-08-14 19:06:05 +0000431 bool doesOpcodeNeedPredicate(unsigned Opc) const;
432 unsigned getPredicateIndex(DecoderTableInfo &TableInfo, StringRef P) const;
433 void emitPredicateTableEntry(DecoderTableInfo &TableInfo,
434 unsigned Opc) const;
James Molloyd9ba4fd2012-02-09 10:56:31 +0000435
Jim Grosbachecaef492012-08-14 19:06:05 +0000436 void emitSoftFailTableEntry(DecoderTableInfo &TableInfo,
437 unsigned Opc) const;
438
439 // Emits table entries to decode the singleton.
440 void emitSingletonTableEntry(DecoderTableInfo &TableInfo,
441 unsigned Opc) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000442
443 // Emits code to decode the singleton, and then to decode the rest.
Jim Grosbachecaef492012-08-14 19:06:05 +0000444 void emitSingletonTableEntry(DecoderTableInfo &TableInfo,
445 const Filter &Best) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000446
Jim Grosbachecaef492012-08-14 19:06:05 +0000447 void emitBinaryParser(raw_ostream &o, unsigned &Indentation,
Petr Pavlu182b0572015-07-15 08:04:27 +0000448 const OperandInfo &OpInfo,
449 bool &OpHasCompleteDecoder) const;
Owen Andersone3591652011-07-28 21:54:31 +0000450
Petr Pavlu182b0572015-07-15 08:04:27 +0000451 void emitDecoder(raw_ostream &OS, unsigned Indentation, unsigned Opc,
452 bool &HasCompleteDecoder) const;
453 unsigned getDecoderIndex(DecoderSet &Decoders, unsigned Opc,
454 bool &HasCompleteDecoder) const;
Jim Grosbachecaef492012-08-14 19:06:05 +0000455
Owen Anderson4e818902011-02-18 21:51:29 +0000456 // Assign a single filter and run with it.
Craig Topper48c112b2012-03-16 05:58:09 +0000457 void runSingleFilter(unsigned startBit, unsigned numBit, bool mixed);
Owen Anderson4e818902011-02-18 21:51:29 +0000458
459 // reportRegion is a helper function for filterProcessor to mark a region as
460 // eligible for use as a filter region.
461 void reportRegion(bitAttr_t RA, unsigned StartBit, unsigned BitIndex,
Craig Topper82d0d5f2012-03-16 01:19:24 +0000462 bool AllowMixed);
Owen Anderson4e818902011-02-18 21:51:29 +0000463
464 // FilterProcessor scans the well-known encoding bits of the instructions and
465 // builds up a list of candidate filters. It chooses the best filter and
466 // recursively descends down the decoding tree.
467 bool filterProcessor(bool AllowMixed, bool Greedy = true);
468
469 // Decides on the best configuration of filter(s) to use in order to decode
470 // the instructions. A conflict of instructions may occur, in which case we
471 // dump the conflict set to the standard error.
472 void doFilter();
473
Jim Grosbachecaef492012-08-14 19:06:05 +0000474public:
475 // emitTableEntries - Emit state machine entries to decode our share of
476 // instructions.
477 void emitTableEntries(DecoderTableInfo &TableInfo) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000478};
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +0000479} // End anonymous namespace
Owen Anderson4e818902011-02-18 21:51:29 +0000480
481///////////////////////////
482// //
Craig Topper93e64342012-03-16 00:56:01 +0000483// Filter Implementation //
Owen Anderson4e818902011-02-18 21:51:29 +0000484// //
485///////////////////////////
486
Craig Topper5c2b4ac2014-09-03 05:49:07 +0000487Filter::Filter(Filter &&f)
Craig Topper82d0d5f2012-03-16 01:19:24 +0000488 : Owner(f.Owner), StartBit(f.StartBit), NumBits(f.NumBits), Mixed(f.Mixed),
Craig Topper5c2b4ac2014-09-03 05:49:07 +0000489 FilteredInstructions(std::move(f.FilteredInstructions)),
490 VariableInstructions(std::move(f.VariableInstructions)),
491 FilterChooserMap(std::move(f.FilterChooserMap)), NumFiltered(f.NumFiltered),
Craig Topper82d0d5f2012-03-16 01:19:24 +0000492 LastOpcFiltered(f.LastOpcFiltered) {
Owen Anderson4e818902011-02-18 21:51:29 +0000493}
494
495Filter::Filter(FilterChooser &owner, unsigned startBit, unsigned numBits,
Craig Topper82d0d5f2012-03-16 01:19:24 +0000496 bool mixed)
497 : Owner(&owner), StartBit(startBit), NumBits(numBits), Mixed(mixed) {
Owen Andersonc78e03c2011-07-19 21:06:00 +0000498 assert(StartBit + NumBits - 1 < Owner->BitWidth);
Owen Anderson4e818902011-02-18 21:51:29 +0000499
500 NumFiltered = 0;
501 LastOpcFiltered = 0;
Owen Anderson4e818902011-02-18 21:51:29 +0000502
503 for (unsigned i = 0, e = Owner->Opcodes.size(); i != e; ++i) {
504 insn_t Insn;
505
506 // Populates the insn given the uid.
507 Owner->insnWithID(Insn, Owner->Opcodes[i]);
508
509 uint64_t Field;
510 // Scans the segment for possibly well-specified encoding bits.
511 bool ok = Owner->fieldFromInsn(Field, Insn, StartBit, NumBits);
512
513 if (ok) {
514 // The encoding bits are well-known. Lets add the uid of the
515 // instruction into the bucket keyed off the constant field value.
516 LastOpcFiltered = Owner->Opcodes[i];
517 FilteredInstructions[Field].push_back(LastOpcFiltered);
518 ++NumFiltered;
519 } else {
Craig Topper93e64342012-03-16 00:56:01 +0000520 // Some of the encoding bit(s) are unspecified. This contributes to
Owen Anderson4e818902011-02-18 21:51:29 +0000521 // one additional member of "Variable" instructions.
522 VariableInstructions.push_back(Owner->Opcodes[i]);
Owen Anderson4e818902011-02-18 21:51:29 +0000523 }
524 }
525
526 assert((FilteredInstructions.size() + VariableInstructions.size() > 0)
527 && "Filter returns no instruction categories");
528}
529
530Filter::~Filter() {
Owen Anderson4e818902011-02-18 21:51:29 +0000531}
532
533// Divides the decoding task into sub tasks and delegates them to the
534// inferior FilterChooser's.
535//
536// A special case arises when there's only one entry in the filtered
537// instructions. In order to unambiguously decode the singleton, we need to
538// match the remaining undecoded encoding bits against the singleton.
539void Filter::recurse() {
Owen Anderson4e818902011-02-18 21:51:29 +0000540 // Starts by inheriting our parent filter chooser's filter bit values.
Owen Andersonc78e03c2011-07-19 21:06:00 +0000541 std::vector<bit_value_t> BitValueArray(Owner->FilterBitValues);
Owen Anderson4e818902011-02-18 21:51:29 +0000542
Alexander Kornienko8c0809c2015-01-15 11:41:30 +0000543 if (!VariableInstructions.empty()) {
Owen Anderson4e818902011-02-18 21:51:29 +0000544 // Conservatively marks each segment position as BIT_UNSET.
Craig Topper29688ab2012-08-17 05:42:16 +0000545 for (unsigned bitIndex = 0; bitIndex < NumBits; ++bitIndex)
Owen Anderson4e818902011-02-18 21:51:29 +0000546 BitValueArray[StartBit + bitIndex] = BIT_UNSET;
547
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000548 // Delegates to an inferior filter chooser for further processing on this
Owen Anderson4e818902011-02-18 21:51:29 +0000549 // group of instructions whose segment values are variable.
Yaron Kerene499db02014-09-03 08:22:30 +0000550 FilterChooserMap.insert(
551 std::make_pair(-1U, llvm::make_unique<FilterChooser>(
552 Owner->AllInstructions, VariableInstructions,
553 Owner->Operands, BitValueArray, *Owner)));
Owen Anderson4e818902011-02-18 21:51:29 +0000554 }
555
556 // No need to recurse for a singleton filtered instruction.
Jim Grosbachecaef492012-08-14 19:06:05 +0000557 // See also Filter::emit*().
Owen Anderson4e818902011-02-18 21:51:29 +0000558 if (getNumFiltered() == 1) {
Owen Anderson4e818902011-02-18 21:51:29 +0000559 assert(FilterChooserMap.size() == 1);
560 return;
561 }
562
563 // Otherwise, create sub choosers.
Craig Topper1f7604d2014-12-13 05:12:19 +0000564 for (const auto &Inst : FilteredInstructions) {
Owen Anderson4e818902011-02-18 21:51:29 +0000565
566 // Marks all the segment positions with either BIT_TRUE or BIT_FALSE.
Craig Topper29688ab2012-08-17 05:42:16 +0000567 for (unsigned bitIndex = 0; bitIndex < NumBits; ++bitIndex) {
Craig Topper1f7604d2014-12-13 05:12:19 +0000568 if (Inst.first & (1ULL << bitIndex))
Owen Anderson4e818902011-02-18 21:51:29 +0000569 BitValueArray[StartBit + bitIndex] = BIT_TRUE;
570 else
571 BitValueArray[StartBit + bitIndex] = BIT_FALSE;
572 }
573
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000574 // Delegates to an inferior filter chooser for further processing on this
Owen Anderson4e818902011-02-18 21:51:29 +0000575 // category of instructions.
Craig Toppercf05f912014-09-03 06:07:54 +0000576 FilterChooserMap.insert(std::make_pair(
Craig Topper1f7604d2014-12-13 05:12:19 +0000577 Inst.first, llvm::make_unique<FilterChooser>(
578 Owner->AllInstructions, Inst.second,
Yaron Kerene499db02014-09-03 08:22:30 +0000579 Owner->Operands, BitValueArray, *Owner)));
Owen Anderson4e818902011-02-18 21:51:29 +0000580 }
581}
582
Jim Grosbachecaef492012-08-14 19:06:05 +0000583static void resolveTableFixups(DecoderTable &Table, const FixupList &Fixups,
584 uint32_t DestIdx) {
585 // Any NumToSkip fixups in the current scope can resolve to the
586 // current location.
587 for (FixupList::const_reverse_iterator I = Fixups.rbegin(),
588 E = Fixups.rend();
589 I != E; ++I) {
590 // Calculate the distance from the byte following the fixup entry byte
591 // to the destination. The Target is calculated from after the 16-bit
592 // NumToSkip entry itself, so subtract two from the displacement here
593 // to account for that.
594 uint32_t FixupIdx = *I;
595 uint32_t Delta = DestIdx - FixupIdx - 2;
596 // Our NumToSkip entries are 16-bits. Make sure our table isn't too
597 // big.
598 assert(Delta < 65536U && "disassembler decoding table too large!");
599 Table[FixupIdx] = (uint8_t)Delta;
600 Table[FixupIdx + 1] = (uint8_t)(Delta >> 8);
601 }
602}
Owen Anderson4e818902011-02-18 21:51:29 +0000603
Jim Grosbachecaef492012-08-14 19:06:05 +0000604// Emit table entries to decode instructions given a segment or segments
605// of bits.
606void Filter::emitTableEntry(DecoderTableInfo &TableInfo) const {
607 TableInfo.Table.push_back(MCD::OPC_ExtractField);
608 TableInfo.Table.push_back(StartBit);
609 TableInfo.Table.push_back(NumBits);
Owen Anderson4e818902011-02-18 21:51:29 +0000610
Jim Grosbachecaef492012-08-14 19:06:05 +0000611 // A new filter entry begins a new scope for fixup resolution.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000612 TableInfo.FixupStack.emplace_back();
Owen Anderson4e818902011-02-18 21:51:29 +0000613
Jim Grosbachecaef492012-08-14 19:06:05 +0000614 DecoderTable &Table = TableInfo.Table;
615
616 size_t PrevFilter = 0;
617 bool HasFallthrough = false;
Craig Topper1f7604d2014-12-13 05:12:19 +0000618 for (auto &Filter : FilterChooserMap) {
Owen Anderson4e818902011-02-18 21:51:29 +0000619 // Field value -1 implies a non-empty set of variable instructions.
620 // See also recurse().
Craig Topper1f7604d2014-12-13 05:12:19 +0000621 if (Filter.first == (unsigned)-1) {
Jim Grosbachecaef492012-08-14 19:06:05 +0000622 HasFallthrough = true;
Owen Anderson4e818902011-02-18 21:51:29 +0000623
Jim Grosbachecaef492012-08-14 19:06:05 +0000624 // Each scope should always have at least one filter value to check
625 // for.
626 assert(PrevFilter != 0 && "empty filter set!");
627 FixupList &CurScope = TableInfo.FixupStack.back();
628 // Resolve any NumToSkip fixups in the current scope.
629 resolveTableFixups(Table, CurScope, Table.size());
630 CurScope.clear();
631 PrevFilter = 0; // Don't re-process the filter's fallthrough.
632 } else {
633 Table.push_back(MCD::OPC_FilterValue);
634 // Encode and emit the value to filter against.
635 uint8_t Buffer[8];
Craig Topper1f7604d2014-12-13 05:12:19 +0000636 unsigned Len = encodeULEB128(Filter.first, Buffer);
Jim Grosbachecaef492012-08-14 19:06:05 +0000637 Table.insert(Table.end(), Buffer, Buffer + Len);
638 // Reserve space for the NumToSkip entry. We'll backpatch the value
639 // later.
640 PrevFilter = Table.size();
641 Table.push_back(0);
642 Table.push_back(0);
643 }
Owen Anderson4e818902011-02-18 21:51:29 +0000644
645 // We arrive at a category of instructions with the same segment value.
646 // Now delegate to the sub filter chooser for further decodings.
647 // The case may fallthrough, which happens if the remaining well-known
648 // encoding bits do not match exactly.
Craig Topper1f7604d2014-12-13 05:12:19 +0000649 Filter.second->emitTableEntries(TableInfo);
Owen Anderson4e818902011-02-18 21:51:29 +0000650
Jim Grosbachecaef492012-08-14 19:06:05 +0000651 // Now that we've emitted the body of the handler, update the NumToSkip
652 // of the filter itself to be able to skip forward when false. Subtract
653 // two as to account for the width of the NumToSkip field itself.
654 if (PrevFilter) {
655 uint32_t NumToSkip = Table.size() - PrevFilter - 2;
656 assert(NumToSkip < 65536U && "disassembler decoding table too large!");
657 Table[PrevFilter] = (uint8_t)NumToSkip;
658 Table[PrevFilter + 1] = (uint8_t)(NumToSkip >> 8);
659 }
Owen Anderson4e818902011-02-18 21:51:29 +0000660 }
661
Jim Grosbachecaef492012-08-14 19:06:05 +0000662 // Any remaining unresolved fixups bubble up to the parent fixup scope.
663 assert(TableInfo.FixupStack.size() > 1 && "fixup stack underflow!");
664 FixupScopeList::iterator Source = TableInfo.FixupStack.end() - 1;
665 FixupScopeList::iterator Dest = Source - 1;
666 Dest->insert(Dest->end(), Source->begin(), Source->end());
667 TableInfo.FixupStack.pop_back();
668
669 // If there is no fallthrough, then the final filter should get fixed
670 // up according to the enclosing scope rather than the current position.
671 if (!HasFallthrough)
672 TableInfo.FixupStack.back().push_back(PrevFilter);
Owen Anderson4e818902011-02-18 21:51:29 +0000673}
674
675// Returns the number of fanout produced by the filter. More fanout implies
676// the filter distinguishes more categories of instructions.
677unsigned Filter::usefulness() const {
Alexander Kornienko8c0809c2015-01-15 11:41:30 +0000678 if (!VariableInstructions.empty())
Owen Anderson4e818902011-02-18 21:51:29 +0000679 return FilteredInstructions.size();
680 else
681 return FilteredInstructions.size() + 1;
682}
683
684//////////////////////////////////
685// //
686// Filterchooser Implementation //
687// //
688//////////////////////////////////
689
Jim Grosbachecaef492012-08-14 19:06:05 +0000690// Emit the decoder state machine table.
691void FixedLenDecoderEmitter::emitTable(formatted_raw_ostream &OS,
692 DecoderTable &Table,
693 unsigned Indentation,
694 unsigned BitWidth,
695 StringRef Namespace) const {
696 OS.indent(Indentation) << "static const uint8_t DecoderTable" << Namespace
697 << BitWidth << "[] = {\n";
Owen Anderson4e818902011-02-18 21:51:29 +0000698
Jim Grosbachecaef492012-08-14 19:06:05 +0000699 Indentation += 2;
Owen Anderson4e818902011-02-18 21:51:29 +0000700
Jim Grosbachecaef492012-08-14 19:06:05 +0000701 // FIXME: We may be able to use the NumToSkip values to recover
702 // appropriate indentation levels.
703 DecoderTable::const_iterator I = Table.begin();
704 DecoderTable::const_iterator E = Table.end();
705 while (I != E) {
706 assert (I < E && "incomplete decode table entry!");
Owen Anderson4e818902011-02-18 21:51:29 +0000707
Jim Grosbachecaef492012-08-14 19:06:05 +0000708 uint64_t Pos = I - Table.begin();
709 OS << "/* " << Pos << " */";
710 OS.PadToColumn(12);
Owen Anderson4e818902011-02-18 21:51:29 +0000711
Jim Grosbachecaef492012-08-14 19:06:05 +0000712 switch (*I) {
713 default:
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000714 PrintFatalError("invalid decode table opcode");
Jim Grosbachecaef492012-08-14 19:06:05 +0000715 case MCD::OPC_ExtractField: {
716 ++I;
717 unsigned Start = *I++;
718 unsigned Len = *I++;
719 OS.indent(Indentation) << "MCD::OPC_ExtractField, " << Start << ", "
720 << Len << ", // Inst{";
721 if (Len > 1)
722 OS << (Start + Len - 1) << "-";
723 OS << Start << "} ...\n";
724 break;
725 }
726 case MCD::OPC_FilterValue: {
727 ++I;
728 OS.indent(Indentation) << "MCD::OPC_FilterValue, ";
729 // The filter value is ULEB128 encoded.
730 while (*I >= 128)
Craig Topper429093a2016-01-31 01:55:15 +0000731 OS << (unsigned)*I++ << ", ";
732 OS << (unsigned)*I++ << ", ";
Jim Grosbachecaef492012-08-14 19:06:05 +0000733
734 // 16-bit numtoskip value.
735 uint8_t Byte = *I++;
736 uint32_t NumToSkip = Byte;
Craig Topper429093a2016-01-31 01:55:15 +0000737 OS << (unsigned)Byte << ", ";
Jim Grosbachecaef492012-08-14 19:06:05 +0000738 Byte = *I++;
Craig Topper429093a2016-01-31 01:55:15 +0000739 OS << (unsigned)Byte << ", ";
Jim Grosbachecaef492012-08-14 19:06:05 +0000740 NumToSkip |= Byte << 8;
741 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
742 break;
743 }
744 case MCD::OPC_CheckField: {
745 ++I;
746 unsigned Start = *I++;
747 unsigned Len = *I++;
748 OS.indent(Indentation) << "MCD::OPC_CheckField, " << Start << ", "
749 << Len << ", ";// << Val << ", " << NumToSkip << ",\n";
750 // ULEB128 encoded field value.
751 for (; *I >= 128; ++I)
Craig Topper429093a2016-01-31 01:55:15 +0000752 OS << (unsigned)*I << ", ";
753 OS << (unsigned)*I++ << ", ";
Jim Grosbachecaef492012-08-14 19:06:05 +0000754 // 16-bit numtoskip value.
755 uint8_t Byte = *I++;
756 uint32_t NumToSkip = Byte;
Craig Topper429093a2016-01-31 01:55:15 +0000757 OS << (unsigned)Byte << ", ";
Jim Grosbachecaef492012-08-14 19:06:05 +0000758 Byte = *I++;
Craig Topper429093a2016-01-31 01:55:15 +0000759 OS << (unsigned)Byte << ", ";
Jim Grosbachecaef492012-08-14 19:06:05 +0000760 NumToSkip |= Byte << 8;
761 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
762 break;
763 }
764 case MCD::OPC_CheckPredicate: {
765 ++I;
766 OS.indent(Indentation) << "MCD::OPC_CheckPredicate, ";
767 for (; *I >= 128; ++I)
Craig Topper429093a2016-01-31 01:55:15 +0000768 OS << (unsigned)*I << ", ";
769 OS << (unsigned)*I++ << ", ";
Jim Grosbachecaef492012-08-14 19:06:05 +0000770
771 // 16-bit numtoskip value.
772 uint8_t Byte = *I++;
773 uint32_t NumToSkip = Byte;
Craig Topper429093a2016-01-31 01:55:15 +0000774 OS << (unsigned)Byte << ", ";
Jim Grosbachecaef492012-08-14 19:06:05 +0000775 Byte = *I++;
Craig Topper429093a2016-01-31 01:55:15 +0000776 OS << (unsigned)Byte << ", ";
Jim Grosbachecaef492012-08-14 19:06:05 +0000777 NumToSkip |= Byte << 8;
778 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
779 break;
780 }
Petr Pavlu182b0572015-07-15 08:04:27 +0000781 case MCD::OPC_Decode:
782 case MCD::OPC_TryDecode: {
783 bool IsTry = *I == MCD::OPC_TryDecode;
Jim Grosbachecaef492012-08-14 19:06:05 +0000784 ++I;
785 // Extract the ULEB128 encoded Opcode to a buffer.
786 uint8_t Buffer[8], *p = Buffer;
787 while ((*p++ = *I++) >= 128)
788 assert((p - Buffer) <= (ptrdiff_t)sizeof(Buffer)
789 && "ULEB128 value too large!");
790 // Decode the Opcode value.
791 unsigned Opc = decodeULEB128(Buffer);
Petr Pavlu182b0572015-07-15 08:04:27 +0000792 OS.indent(Indentation) << "MCD::OPC_" << (IsTry ? "Try" : "")
793 << "Decode, ";
Jim Grosbachecaef492012-08-14 19:06:05 +0000794 for (p = Buffer; *p >= 128; ++p)
Craig Topper429093a2016-01-31 01:55:15 +0000795 OS << (unsigned)*p << ", ";
796 OS << (unsigned)*p << ", ";
Jim Grosbachecaef492012-08-14 19:06:05 +0000797
798 // Decoder index.
799 for (; *I >= 128; ++I)
Craig Topper429093a2016-01-31 01:55:15 +0000800 OS << (unsigned)*I << ", ";
801 OS << (unsigned)*I++ << ", ";
Jim Grosbachecaef492012-08-14 19:06:05 +0000802
Petr Pavlu182b0572015-07-15 08:04:27 +0000803 if (!IsTry) {
804 OS << "// Opcode: "
Craig Topperf9265322016-01-17 20:38:14 +0000805 << NumberedInstructions[Opc]->TheDef->getName() << "\n";
Petr Pavlu182b0572015-07-15 08:04:27 +0000806 break;
807 }
808
809 // Fallthrough for OPC_TryDecode.
810
811 // 16-bit numtoskip value.
812 uint8_t Byte = *I++;
813 uint32_t NumToSkip = Byte;
Craig Topper429093a2016-01-31 01:55:15 +0000814 OS << (unsigned)Byte << ", ";
Petr Pavlu182b0572015-07-15 08:04:27 +0000815 Byte = *I++;
Craig Topper429093a2016-01-31 01:55:15 +0000816 OS << (unsigned)Byte << ", ";
Petr Pavlu182b0572015-07-15 08:04:27 +0000817 NumToSkip |= Byte << 8;
818
Jim Grosbachecaef492012-08-14 19:06:05 +0000819 OS << "// Opcode: "
Craig Topperf9265322016-01-17 20:38:14 +0000820 << NumberedInstructions[Opc]->TheDef->getName()
Petr Pavlu182b0572015-07-15 08:04:27 +0000821 << ", skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
Jim Grosbachecaef492012-08-14 19:06:05 +0000822 break;
823 }
824 case MCD::OPC_SoftFail: {
825 ++I;
826 OS.indent(Indentation) << "MCD::OPC_SoftFail";
827 // Positive mask
828 uint64_t Value = 0;
829 unsigned Shift = 0;
830 do {
Craig Topper429093a2016-01-31 01:55:15 +0000831 OS << ", " << (unsigned)*I;
Jim Grosbachecaef492012-08-14 19:06:05 +0000832 Value += (*I & 0x7f) << Shift;
833 Shift += 7;
834 } while (*I++ >= 128);
Craig Topper429093a2016-01-31 01:55:15 +0000835 if (Value > 127) {
836 OS << " /* 0x";
837 OS.write_hex(Value);
838 OS << " */";
839 }
Jim Grosbachecaef492012-08-14 19:06:05 +0000840 // Negative mask
841 Value = 0;
842 Shift = 0;
843 do {
Craig Topper429093a2016-01-31 01:55:15 +0000844 OS << ", " << (unsigned)*I;
Jim Grosbachecaef492012-08-14 19:06:05 +0000845 Value += (*I & 0x7f) << Shift;
846 Shift += 7;
847 } while (*I++ >= 128);
Craig Topper429093a2016-01-31 01:55:15 +0000848 if (Value > 127) {
849 OS << " /* 0x";
850 OS.write_hex(Value);
851 OS << " */";
852 }
Jim Grosbachecaef492012-08-14 19:06:05 +0000853 OS << ",\n";
854 break;
855 }
856 case MCD::OPC_Fail: {
857 ++I;
858 OS.indent(Indentation) << "MCD::OPC_Fail,\n";
859 break;
860 }
861 }
862 }
863 OS.indent(Indentation) << "0\n";
864
865 Indentation -= 2;
866
867 OS.indent(Indentation) << "};\n\n";
868}
869
870void FixedLenDecoderEmitter::
871emitPredicateFunction(formatted_raw_ostream &OS, PredicateSet &Predicates,
872 unsigned Indentation) const {
873 // The predicate function is just a big switch statement based on the
874 // input predicate index.
875 OS.indent(Indentation) << "static bool checkDecoderPredicate(unsigned Idx, "
Michael Kupersteindb0712f2015-05-26 10:47:10 +0000876 << "const FeatureBitset& Bits) {\n";
Jim Grosbachecaef492012-08-14 19:06:05 +0000877 Indentation += 2;
Aaron Ballmane59e3582013-07-15 16:53:32 +0000878 if (!Predicates.empty()) {
879 OS.indent(Indentation) << "switch (Idx) {\n";
880 OS.indent(Indentation) << "default: llvm_unreachable(\"Invalid index!\");\n";
881 unsigned Index = 0;
Craig Topper1f7604d2014-12-13 05:12:19 +0000882 for (const auto &Predicate : Predicates) {
883 OS.indent(Indentation) << "case " << Index++ << ":\n";
884 OS.indent(Indentation+2) << "return (" << Predicate << ");\n";
Aaron Ballmane59e3582013-07-15 16:53:32 +0000885 }
886 OS.indent(Indentation) << "}\n";
887 } else {
888 // No case statement to emit
889 OS.indent(Indentation) << "llvm_unreachable(\"Invalid index!\");\n";
Jim Grosbachecaef492012-08-14 19:06:05 +0000890 }
Jim Grosbachecaef492012-08-14 19:06:05 +0000891 Indentation -= 2;
892 OS.indent(Indentation) << "}\n\n";
893}
894
895void FixedLenDecoderEmitter::
896emitDecoderFunction(formatted_raw_ostream &OS, DecoderSet &Decoders,
897 unsigned Indentation) const {
898 // The decoder function is just a big switch statement based on the
899 // input decoder index.
900 OS.indent(Indentation) << "template<typename InsnType>\n";
901 OS.indent(Indentation) << "static DecodeStatus decodeToMCInst(DecodeStatus S,"
902 << " unsigned Idx, InsnType insn, MCInst &MI,\n";
903 OS.indent(Indentation) << " uint64_t "
Petr Pavlu182b0572015-07-15 08:04:27 +0000904 << "Address, const void *Decoder, bool &DecodeComplete) {\n";
Jim Grosbachecaef492012-08-14 19:06:05 +0000905 Indentation += 2;
Petr Pavlu182b0572015-07-15 08:04:27 +0000906 OS.indent(Indentation) << "DecodeComplete = true;\n";
Jim Grosbachecaef492012-08-14 19:06:05 +0000907 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;
Craig Topper1f7604d2014-12-13 05:12:19 +0000911 for (const auto &Decoder : Decoders) {
912 OS.indent(Indentation) << "case " << Index++ << ":\n";
913 OS << Decoder;
Jim Grosbachecaef492012-08-14 19:06:05 +0000914 OS.indent(Indentation+2) << "return S;\n";
915 }
916 OS.indent(Indentation) << "}\n";
917 Indentation -= 2;
918 OS.indent(Indentation) << "}\n\n";
Owen Anderson4e818902011-02-18 21:51:29 +0000919}
920
921// Populates the field of the insn given the start position and the number of
922// consecutive bits to scan for.
923//
924// Returns false if and on the first uninitialized bit value encountered.
925// Returns true, otherwise.
926bool FilterChooser::fieldFromInsn(uint64_t &Field, insn_t &Insn,
Craig Topper48c112b2012-03-16 05:58:09 +0000927 unsigned StartBit, unsigned NumBits) const {
Owen Anderson4e818902011-02-18 21:51:29 +0000928 Field = 0;
929
930 for (unsigned i = 0; i < NumBits; ++i) {
931 if (Insn[StartBit + i] == BIT_UNSET)
932 return false;
933
934 if (Insn[StartBit + i] == BIT_TRUE)
935 Field = Field | (1ULL << i);
936 }
937
938 return true;
939}
940
941/// dumpFilterArray - dumpFilterArray prints out debugging info for the given
942/// filter array as a series of chars.
943void FilterChooser::dumpFilterArray(raw_ostream &o,
Craig Topper48c112b2012-03-16 05:58:09 +0000944 const std::vector<bit_value_t> &filter) const {
Craig Topper29688ab2012-08-17 05:42:16 +0000945 for (unsigned bitIndex = BitWidth; bitIndex > 0; bitIndex--) {
Owen Anderson4e818902011-02-18 21:51:29 +0000946 switch (filter[bitIndex - 1]) {
947 case BIT_UNFILTERED:
948 o << ".";
949 break;
950 case BIT_UNSET:
951 o << "_";
952 break;
953 case BIT_TRUE:
954 o << "1";
955 break;
956 case BIT_FALSE:
957 o << "0";
958 break;
959 }
960 }
961}
962
963/// dumpStack - dumpStack traverses the filter chooser chain and calls
964/// dumpFilterArray on each filter chooser up to the top level one.
Craig Topper48c112b2012-03-16 05:58:09 +0000965void FilterChooser::dumpStack(raw_ostream &o, const char *prefix) const {
966 const FilterChooser *current = this;
Owen Anderson4e818902011-02-18 21:51:29 +0000967
968 while (current) {
969 o << prefix;
970 dumpFilterArray(o, current->FilterBitValues);
971 o << '\n';
972 current = current->Parent;
973 }
974}
975
Owen Anderson4e818902011-02-18 21:51:29 +0000976// Calculates the island(s) needed to decode the instruction.
977// This returns a list of undecoded bits of an instructions, for example,
978// Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
979// decoded bits in order to verify that the instruction matches the Opcode.
980unsigned FilterChooser::getIslands(std::vector<unsigned> &StartBits,
Craig Topper82d0d5f2012-03-16 01:19:24 +0000981 std::vector<unsigned> &EndBits,
982 std::vector<uint64_t> &FieldVals,
Craig Topper48c112b2012-03-16 05:58:09 +0000983 const insn_t &Insn) const {
Owen Anderson4e818902011-02-18 21:51:29 +0000984 unsigned Num, BitNo;
985 Num = BitNo = 0;
986
987 uint64_t FieldVal = 0;
988
989 // 0: Init
990 // 1: Water (the bit value does not affect decoding)
991 // 2: Island (well-known bit value needed for decoding)
992 int State = 0;
993 int Val = -1;
994
Owen Andersonc78e03c2011-07-19 21:06:00 +0000995 for (unsigned i = 0; i < BitWidth; ++i) {
Owen Anderson4e818902011-02-18 21:51:29 +0000996 Val = Value(Insn[i]);
997 bool Filtered = PositionFiltered(i);
998 switch (State) {
Craig Topperc4965bc2012-02-05 07:21:30 +0000999 default: llvm_unreachable("Unreachable code!");
Owen Anderson4e818902011-02-18 21:51:29 +00001000 case 0:
1001 case 1:
1002 if (Filtered || Val == -1)
1003 State = 1; // Still in Water
1004 else {
1005 State = 2; // Into the Island
1006 BitNo = 0;
1007 StartBits.push_back(i);
1008 FieldVal = Val;
1009 }
1010 break;
1011 case 2:
1012 if (Filtered || Val == -1) {
1013 State = 1; // Into the Water
1014 EndBits.push_back(i - 1);
1015 FieldVals.push_back(FieldVal);
1016 ++Num;
1017 } else {
1018 State = 2; // Still in Island
1019 ++BitNo;
1020 FieldVal = FieldVal | Val << BitNo;
1021 }
1022 break;
1023 }
1024 }
1025 // If we are still in Island after the loop, do some housekeeping.
1026 if (State == 2) {
Owen Andersonc78e03c2011-07-19 21:06:00 +00001027 EndBits.push_back(BitWidth - 1);
Owen Anderson4e818902011-02-18 21:51:29 +00001028 FieldVals.push_back(FieldVal);
1029 ++Num;
1030 }
1031
1032 assert(StartBits.size() == Num && EndBits.size() == Num &&
1033 FieldVals.size() == Num);
1034 return Num;
1035}
1036
Owen Andersone3591652011-07-28 21:54:31 +00001037void FilterChooser::emitBinaryParser(raw_ostream &o, unsigned &Indentation,
Petr Pavlu182b0572015-07-15 08:04:27 +00001038 const OperandInfo &OpInfo,
1039 bool &OpHasCompleteDecoder) const {
Craig Topper48c112b2012-03-16 05:58:09 +00001040 const std::string &Decoder = OpInfo.Decoder;
Owen Andersone3591652011-07-28 21:54:31 +00001041
Craig Topper5546f8c2014-09-27 05:26:42 +00001042 if (OpInfo.numFields() != 1)
Craig Topperebc3aa22012-08-17 05:16:15 +00001043 o.indent(Indentation) << "tmp = 0;\n";
Craig Topper5546f8c2014-09-27 05:26:42 +00001044
1045 for (const EncodingField &EF : OpInfo) {
1046 o.indent(Indentation) << "tmp ";
1047 if (OpInfo.numFields() != 1) o << '|';
1048 o << "= fieldFromInstruction"
1049 << "(insn, " << EF.Base << ", " << EF.Width << ')';
1050 if (OpInfo.numFields() != 1 || EF.Offset != 0)
1051 o << " << " << EF.Offset;
1052 o << ";\n";
Owen Andersone3591652011-07-28 21:54:31 +00001053 }
1054
Petr Pavlu182b0572015-07-15 08:04:27 +00001055 if (Decoder != "") {
1056 OpHasCompleteDecoder = OpInfo.HasCompleteDecoder;
Craig Topperebc3aa22012-08-17 05:16:15 +00001057 o.indent(Indentation) << Emitter->GuardPrefix << Decoder
Petr Pavlu182b0572015-07-15 08:04:27 +00001058 << "(MI, tmp, Address, Decoder)"
1059 << Emitter->GuardPostfix
1060 << " { " << (OpHasCompleteDecoder ? "" : "DecodeComplete = false; ")
1061 << "return MCDisassembler::Fail; }\n";
1062 } else {
1063 OpHasCompleteDecoder = true;
Jim Grosbache9119e42015-05-13 18:37:00 +00001064 o.indent(Indentation) << "MI.addOperand(MCOperand::createImm(tmp));\n";
Petr Pavlu182b0572015-07-15 08:04:27 +00001065 }
Owen Andersone3591652011-07-28 21:54:31 +00001066}
1067
Jim Grosbachecaef492012-08-14 19:06:05 +00001068void FilterChooser::emitDecoder(raw_ostream &OS, unsigned Indentation,
Petr Pavlu182b0572015-07-15 08:04:27 +00001069 unsigned Opc, bool &HasCompleteDecoder) const {
1070 HasCompleteDecoder = true;
1071
Craig Topper1f7604d2014-12-13 05:12:19 +00001072 for (const auto &Op : Operands.find(Opc)->second) {
Jim Grosbachecaef492012-08-14 19:06:05 +00001073 // If a custom instruction decoder was specified, use that.
Craig Topper1f7604d2014-12-13 05:12:19 +00001074 if (Op.numFields() == 0 && Op.Decoder.size()) {
Petr Pavlu182b0572015-07-15 08:04:27 +00001075 HasCompleteDecoder = Op.HasCompleteDecoder;
Craig Topper1f7604d2014-12-13 05:12:19 +00001076 OS.indent(Indentation) << Emitter->GuardPrefix << Op.Decoder
Jim Grosbachecaef492012-08-14 19:06:05 +00001077 << "(MI, insn, Address, Decoder)"
Petr Pavlu182b0572015-07-15 08:04:27 +00001078 << Emitter->GuardPostfix
1079 << " { " << (HasCompleteDecoder ? "" : "DecodeComplete = false; ")
1080 << "return MCDisassembler::Fail; }\n";
Jim Grosbachecaef492012-08-14 19:06:05 +00001081 break;
1082 }
1083
Petr Pavlu182b0572015-07-15 08:04:27 +00001084 bool OpHasCompleteDecoder;
1085 emitBinaryParser(OS, Indentation, Op, OpHasCompleteDecoder);
1086 if (!OpHasCompleteDecoder)
1087 HasCompleteDecoder = false;
Jim Grosbachecaef492012-08-14 19:06:05 +00001088 }
1089}
1090
1091unsigned FilterChooser::getDecoderIndex(DecoderSet &Decoders,
Petr Pavlu182b0572015-07-15 08:04:27 +00001092 unsigned Opc,
1093 bool &HasCompleteDecoder) const {
Jim Grosbachecaef492012-08-14 19:06:05 +00001094 // Build up the predicate string.
1095 SmallString<256> Decoder;
1096 // FIXME: emitDecoder() function can take a buffer directly rather than
1097 // a stream.
1098 raw_svector_ostream S(Decoder);
Craig Topperebc3aa22012-08-17 05:16:15 +00001099 unsigned I = 4;
Petr Pavlu182b0572015-07-15 08:04:27 +00001100 emitDecoder(S, I, Opc, HasCompleteDecoder);
Jim Grosbachecaef492012-08-14 19:06:05 +00001101
1102 // Using the full decoder string as the key value here is a bit
1103 // heavyweight, but is effective. If the string comparisons become a
1104 // performance concern, we can implement a mangling of the predicate
Nick Lewycky06b0ea22015-08-18 22:41:58 +00001105 // data easily enough with a map back to the actual string. That's
Jim Grosbachecaef492012-08-14 19:06:05 +00001106 // overkill for now, though.
1107
1108 // Make sure the predicate is in the table.
Yaron Keren92e1b622015-03-18 10:17:07 +00001109 Decoders.insert(StringRef(Decoder));
Jim Grosbachecaef492012-08-14 19:06:05 +00001110 // Now figure out the index for when we write out the table.
David Majnemer42531262016-08-12 03:55:06 +00001111 DecoderSet::const_iterator P = find(Decoders, Decoder.str());
Jim Grosbachecaef492012-08-14 19:06:05 +00001112 return (unsigned)(P - Decoders.begin());
1113}
1114
James Molloy8067df92011-09-07 19:42:28 +00001115static void emitSinglePredicateMatch(raw_ostream &o, StringRef str,
Craig Topper48c112b2012-03-16 05:58:09 +00001116 const std::string &PredicateNamespace) {
Andrew Trick43674ad2011-09-08 05:25:49 +00001117 if (str[0] == '!')
Michael Kupersteindb0712f2015-05-26 10:47:10 +00001118 o << "!Bits[" << PredicateNamespace << "::"
1119 << str.slice(1,str.size()) << "]";
James Molloy8067df92011-09-07 19:42:28 +00001120 else
Michael Kupersteindb0712f2015-05-26 10:47:10 +00001121 o << "Bits[" << PredicateNamespace << "::" << str << "]";
James Molloy8067df92011-09-07 19:42:28 +00001122}
1123
1124bool FilterChooser::emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
Craig Topper48c112b2012-03-16 05:58:09 +00001125 unsigned Opc) const {
Jim Grosbach3f4b2392012-02-29 22:07:56 +00001126 ListInit *Predicates =
1127 AllInstructions[Opc]->TheDef->getValueAsListInit("Predicates");
Toma Tabacu3d5ce492015-04-07 12:10:11 +00001128 bool IsFirstEmission = true;
Craig Topper664f6a02015-06-02 04:15:57 +00001129 for (unsigned i = 0; i < Predicates->size(); ++i) {
James Molloy8067df92011-09-07 19:42:28 +00001130 Record *Pred = Predicates->getElementAsRecord(i);
1131 if (!Pred->getValue("AssemblerMatcherPredicate"))
1132 continue;
1133
1134 std::string P = Pred->getValueAsString("AssemblerCondString");
1135
1136 if (!P.length())
1137 continue;
1138
Toma Tabacu3d5ce492015-04-07 12:10:11 +00001139 if (!IsFirstEmission)
James Molloy8067df92011-09-07 19:42:28 +00001140 o << " && ";
1141
1142 StringRef SR(P);
1143 std::pair<StringRef, StringRef> pairs = SR.split(',');
1144 while (pairs.second.size()) {
1145 emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
1146 o << " && ";
1147 pairs = pairs.second.split(',');
1148 }
1149 emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
Toma Tabacu3d5ce492015-04-07 12:10:11 +00001150 IsFirstEmission = false;
James Molloy8067df92011-09-07 19:42:28 +00001151 }
Craig Topper664f6a02015-06-02 04:15:57 +00001152 return !Predicates->empty();
Andrew Trick61abca62011-09-08 05:23:14 +00001153}
James Molloy8067df92011-09-07 19:42:28 +00001154
Jim Grosbachecaef492012-08-14 19:06:05 +00001155bool FilterChooser::doesOpcodeNeedPredicate(unsigned Opc) const {
1156 ListInit *Predicates =
1157 AllInstructions[Opc]->TheDef->getValueAsListInit("Predicates");
Craig Topper664f6a02015-06-02 04:15:57 +00001158 for (unsigned i = 0; i < Predicates->size(); ++i) {
Jim Grosbachecaef492012-08-14 19:06:05 +00001159 Record *Pred = Predicates->getElementAsRecord(i);
1160 if (!Pred->getValue("AssemblerMatcherPredicate"))
1161 continue;
1162
1163 std::string P = Pred->getValueAsString("AssemblerCondString");
1164
1165 if (!P.length())
1166 continue;
1167
1168 return true;
1169 }
1170 return false;
1171}
1172
1173unsigned FilterChooser::getPredicateIndex(DecoderTableInfo &TableInfo,
1174 StringRef Predicate) const {
1175 // Using the full predicate string as the key value here is a bit
1176 // heavyweight, but is effective. If the string comparisons become a
1177 // performance concern, we can implement a mangling of the predicate
Nick Lewycky06b0ea22015-08-18 22:41:58 +00001178 // data easily enough with a map back to the actual string. That's
Jim Grosbachecaef492012-08-14 19:06:05 +00001179 // overkill for now, though.
1180
1181 // Make sure the predicate is in the table.
1182 TableInfo.Predicates.insert(Predicate.str());
1183 // Now figure out the index for when we write out the table.
David Majnemer42531262016-08-12 03:55:06 +00001184 PredicateSet::const_iterator P = find(TableInfo.Predicates, Predicate.str());
Jim Grosbachecaef492012-08-14 19:06:05 +00001185 return (unsigned)(P - TableInfo.Predicates.begin());
1186}
1187
1188void FilterChooser::emitPredicateTableEntry(DecoderTableInfo &TableInfo,
1189 unsigned Opc) const {
1190 if (!doesOpcodeNeedPredicate(Opc))
1191 return;
1192
1193 // Build up the predicate string.
1194 SmallString<256> Predicate;
1195 // FIXME: emitPredicateMatch() functions can take a buffer directly rather
1196 // than a stream.
1197 raw_svector_ostream PS(Predicate);
1198 unsigned I = 0;
1199 emitPredicateMatch(PS, I, Opc);
1200
1201 // Figure out the index into the predicate table for the predicate just
1202 // computed.
1203 unsigned PIdx = getPredicateIndex(TableInfo, PS.str());
1204 SmallString<16> PBytes;
1205 raw_svector_ostream S(PBytes);
1206 encodeULEB128(PIdx, S);
Jim Grosbachecaef492012-08-14 19:06:05 +00001207
1208 TableInfo.Table.push_back(MCD::OPC_CheckPredicate);
1209 // Predicate index
Craig Topper29688ab2012-08-17 05:42:16 +00001210 for (unsigned i = 0, e = PBytes.size(); i != e; ++i)
Jim Grosbachecaef492012-08-14 19:06:05 +00001211 TableInfo.Table.push_back(PBytes[i]);
1212 // Push location for NumToSkip backpatching.
1213 TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
1214 TableInfo.Table.push_back(0);
1215 TableInfo.Table.push_back(0);
1216}
1217
1218void FilterChooser::emitSoftFailTableEntry(DecoderTableInfo &TableInfo,
1219 unsigned Opc) const {
Jim Grosbach3f4b2392012-02-29 22:07:56 +00001220 BitsInit *SFBits =
1221 AllInstructions[Opc]->TheDef->getValueAsBitsInit("SoftFail");
James Molloyd9ba4fd2012-02-09 10:56:31 +00001222 if (!SFBits) return;
1223 BitsInit *InstBits = AllInstructions[Opc]->TheDef->getValueAsBitsInit("Inst");
1224
1225 APInt PositiveMask(BitWidth, 0ULL);
1226 APInt NegativeMask(BitWidth, 0ULL);
1227 for (unsigned i = 0; i < BitWidth; ++i) {
1228 bit_value_t B = bitFromBits(*SFBits, i);
1229 bit_value_t IB = bitFromBits(*InstBits, i);
1230
1231 if (B != BIT_TRUE) continue;
1232
1233 switch (IB) {
1234 case BIT_FALSE:
1235 // The bit is meant to be false, so emit a check to see if it is true.
1236 PositiveMask.setBit(i);
1237 break;
1238 case BIT_TRUE:
1239 // The bit is meant to be true, so emit a check to see if it is false.
1240 NegativeMask.setBit(i);
1241 break;
1242 default:
1243 // The bit is not set; this must be an error!
1244 StringRef Name = AllInstructions[Opc]->TheDef->getName();
Jim Grosbachecaef492012-08-14 19:06:05 +00001245 errs() << "SoftFail Conflict: bit SoftFail{" << i << "} in " << Name
1246 << " is set but Inst{" << i << "} is unset!\n"
James Molloyd9ba4fd2012-02-09 10:56:31 +00001247 << " - You can only mark a bit as SoftFail if it is fully defined"
1248 << " (1/0 - not '?') in Inst\n";
Jim Grosbachecaef492012-08-14 19:06:05 +00001249 return;
James Molloyd9ba4fd2012-02-09 10:56:31 +00001250 }
1251 }
1252
1253 bool NeedPositiveMask = PositiveMask.getBoolValue();
1254 bool NeedNegativeMask = NegativeMask.getBoolValue();
1255
1256 if (!NeedPositiveMask && !NeedNegativeMask)
1257 return;
1258
Jim Grosbachecaef492012-08-14 19:06:05 +00001259 TableInfo.Table.push_back(MCD::OPC_SoftFail);
James Molloyd9ba4fd2012-02-09 10:56:31 +00001260
Jim Grosbachecaef492012-08-14 19:06:05 +00001261 SmallString<16> MaskBytes;
1262 raw_svector_ostream S(MaskBytes);
1263 if (NeedPositiveMask) {
1264 encodeULEB128(PositiveMask.getZExtValue(), S);
Craig Topper29688ab2012-08-17 05:42:16 +00001265 for (unsigned i = 0, e = MaskBytes.size(); i != e; ++i)
Jim Grosbachecaef492012-08-14 19:06:05 +00001266 TableInfo.Table.push_back(MaskBytes[i]);
1267 } else
1268 TableInfo.Table.push_back(0);
1269 if (NeedNegativeMask) {
1270 MaskBytes.clear();
Jim Grosbachecaef492012-08-14 19:06:05 +00001271 encodeULEB128(NegativeMask.getZExtValue(), S);
Craig Topper29688ab2012-08-17 05:42:16 +00001272 for (unsigned i = 0, e = MaskBytes.size(); i != e; ++i)
Jim Grosbachecaef492012-08-14 19:06:05 +00001273 TableInfo.Table.push_back(MaskBytes[i]);
1274 } else
1275 TableInfo.Table.push_back(0);
James Molloyd9ba4fd2012-02-09 10:56:31 +00001276}
1277
Jim Grosbachecaef492012-08-14 19:06:05 +00001278// Emits table entries to decode the singleton.
1279void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,
1280 unsigned Opc) const {
Owen Anderson4e818902011-02-18 21:51:29 +00001281 std::vector<unsigned> StartBits;
1282 std::vector<unsigned> EndBits;
1283 std::vector<uint64_t> FieldVals;
1284 insn_t Insn;
1285 insnWithID(Insn, Opc);
1286
1287 // Look for islands of undecoded bits of the singleton.
1288 getIslands(StartBits, EndBits, FieldVals, Insn);
1289
1290 unsigned Size = StartBits.size();
Owen Anderson4e818902011-02-18 21:51:29 +00001291
Jim Grosbachecaef492012-08-14 19:06:05 +00001292 // Emit the predicate table entry if one is needed.
1293 emitPredicateTableEntry(TableInfo, Opc);
Owen Anderson4e818902011-02-18 21:51:29 +00001294
Jim Grosbachecaef492012-08-14 19:06:05 +00001295 // Check any additional encoding fields needed.
Craig Topper29688ab2012-08-17 05:42:16 +00001296 for (unsigned I = Size; I != 0; --I) {
1297 unsigned NumBits = EndBits[I-1] - StartBits[I-1] + 1;
Jim Grosbachecaef492012-08-14 19:06:05 +00001298 TableInfo.Table.push_back(MCD::OPC_CheckField);
1299 TableInfo.Table.push_back(StartBits[I-1]);
1300 TableInfo.Table.push_back(NumBits);
1301 uint8_t Buffer[8], *p;
1302 encodeULEB128(FieldVals[I-1], Buffer);
1303 for (p = Buffer; *p >= 128 ; ++p)
1304 TableInfo.Table.push_back(*p);
1305 TableInfo.Table.push_back(*p);
1306 // Push location for NumToSkip backpatching.
1307 TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
1308 // The fixup is always 16-bits, so go ahead and allocate the space
1309 // in the table so all our relative position calculations work OK even
1310 // before we fully resolve the real value here.
1311 TableInfo.Table.push_back(0);
1312 TableInfo.Table.push_back(0);
Owen Anderson4e818902011-02-18 21:51:29 +00001313 }
Owen Anderson4e818902011-02-18 21:51:29 +00001314
Jim Grosbachecaef492012-08-14 19:06:05 +00001315 // Check for soft failure of the match.
1316 emitSoftFailTableEntry(TableInfo, Opc);
Owen Anderson4e818902011-02-18 21:51:29 +00001317
Petr Pavlu182b0572015-07-15 08:04:27 +00001318 bool HasCompleteDecoder;
1319 unsigned DIdx = getDecoderIndex(TableInfo.Decoders, Opc, HasCompleteDecoder);
1320
1321 // Produce OPC_Decode or OPC_TryDecode opcode based on the information
1322 // whether the instruction decoder is complete or not. If it is complete
1323 // then it handles all possible values of remaining variable/unfiltered bits
1324 // and for any value can determine if the bitpattern is a valid instruction
1325 // or not. This means OPC_Decode will be the final step in the decoding
1326 // process. If it is not complete, then the Fail return code from the
1327 // decoder method indicates that additional processing should be done to see
1328 // if there is any other instruction that also matches the bitpattern and
1329 // can decode it.
1330 TableInfo.Table.push_back(HasCompleteDecoder ? MCD::OPC_Decode :
1331 MCD::OPC_TryDecode);
Jim Grosbachecaef492012-08-14 19:06:05 +00001332 uint8_t Buffer[8], *p;
1333 encodeULEB128(Opc, Buffer);
1334 for (p = Buffer; *p >= 128 ; ++p)
1335 TableInfo.Table.push_back(*p);
1336 TableInfo.Table.push_back(*p);
1337
Jim Grosbachecaef492012-08-14 19:06:05 +00001338 SmallString<16> Bytes;
1339 raw_svector_ostream S(Bytes);
1340 encodeULEB128(DIdx, S);
Jim Grosbachecaef492012-08-14 19:06:05 +00001341
1342 // Decoder index
Craig Topper29688ab2012-08-17 05:42:16 +00001343 for (unsigned i = 0, e = Bytes.size(); i != e; ++i)
Jim Grosbachecaef492012-08-14 19:06:05 +00001344 TableInfo.Table.push_back(Bytes[i]);
Petr Pavlu182b0572015-07-15 08:04:27 +00001345
1346 if (!HasCompleteDecoder) {
1347 // Push location for NumToSkip backpatching.
1348 TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
1349 // Allocate the space for the fixup.
1350 TableInfo.Table.push_back(0);
1351 TableInfo.Table.push_back(0);
1352 }
Owen Anderson4e818902011-02-18 21:51:29 +00001353}
1354
Jim Grosbachecaef492012-08-14 19:06:05 +00001355// Emits table entries to decode the singleton, and then to decode the rest.
1356void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,
1357 const Filter &Best) const {
Owen Anderson4e818902011-02-18 21:51:29 +00001358 unsigned Opc = Best.getSingletonOpc();
1359
Jim Grosbachecaef492012-08-14 19:06:05 +00001360 // complex singletons need predicate checks from the first singleton
1361 // to refer forward to the variable filterchooser that follows.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001362 TableInfo.FixupStack.emplace_back();
Owen Anderson4e818902011-02-18 21:51:29 +00001363
Jim Grosbachecaef492012-08-14 19:06:05 +00001364 emitSingletonTableEntry(TableInfo, Opc);
Owen Anderson4e818902011-02-18 21:51:29 +00001365
Jim Grosbachecaef492012-08-14 19:06:05 +00001366 resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),
1367 TableInfo.Table.size());
1368 TableInfo.FixupStack.pop_back();
1369
1370 Best.getVariableFC().emitTableEntries(TableInfo);
Owen Anderson4e818902011-02-18 21:51:29 +00001371}
1372
Jim Grosbachecaef492012-08-14 19:06:05 +00001373
Owen Anderson4e818902011-02-18 21:51:29 +00001374// Assign a single filter and run with it. Top level API client can initialize
1375// with a single filter to start the filtering process.
Craig Topper48c112b2012-03-16 05:58:09 +00001376void FilterChooser::runSingleFilter(unsigned startBit, unsigned numBit,
1377 bool mixed) {
Owen Anderson4e818902011-02-18 21:51:29 +00001378 Filters.clear();
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001379 Filters.emplace_back(*this, startBit, numBit, true);
Owen Anderson4e818902011-02-18 21:51:29 +00001380 BestIndex = 0; // Sole Filter instance to choose from.
1381 bestFilter().recurse();
1382}
1383
1384// reportRegion is a helper function for filterProcessor to mark a region as
1385// eligible for use as a filter region.
1386void FilterChooser::reportRegion(bitAttr_t RA, unsigned StartBit,
Craig Topper82d0d5f2012-03-16 01:19:24 +00001387 unsigned BitIndex, bool AllowMixed) {
Owen Anderson4e818902011-02-18 21:51:29 +00001388 if (RA == ATTR_MIXED && AllowMixed)
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001389 Filters.emplace_back(*this, StartBit, BitIndex - StartBit, true);
Owen Anderson4e818902011-02-18 21:51:29 +00001390 else if (RA == ATTR_ALL_SET && !AllowMixed)
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001391 Filters.emplace_back(*this, StartBit, BitIndex - StartBit, false);
Owen Anderson4e818902011-02-18 21:51:29 +00001392}
1393
1394// FilterProcessor scans the well-known encoding bits of the instructions and
1395// builds up a list of candidate filters. It chooses the best filter and
1396// recursively descends down the decoding tree.
1397bool FilterChooser::filterProcessor(bool AllowMixed, bool Greedy) {
1398 Filters.clear();
1399 BestIndex = -1;
1400 unsigned numInstructions = Opcodes.size();
1401
1402 assert(numInstructions && "Filter created with no instructions");
1403
1404 // No further filtering is necessary.
1405 if (numInstructions == 1)
1406 return true;
1407
1408 // Heuristics. See also doFilter()'s "Heuristics" comment when num of
1409 // instructions is 3.
1410 if (AllowMixed && !Greedy) {
1411 assert(numInstructions == 3);
1412
1413 for (unsigned i = 0; i < Opcodes.size(); ++i) {
1414 std::vector<unsigned> StartBits;
1415 std::vector<unsigned> EndBits;
1416 std::vector<uint64_t> FieldVals;
1417 insn_t Insn;
1418
1419 insnWithID(Insn, Opcodes[i]);
1420
1421 // Look for islands of undecoded bits of any instruction.
1422 if (getIslands(StartBits, EndBits, FieldVals, Insn) > 0) {
1423 // Found an instruction with island(s). Now just assign a filter.
Craig Topper48c112b2012-03-16 05:58:09 +00001424 runSingleFilter(StartBits[0], EndBits[0] - StartBits[0] + 1, true);
Owen Anderson4e818902011-02-18 21:51:29 +00001425 return true;
1426 }
1427 }
1428 }
1429
Craig Topper29688ab2012-08-17 05:42:16 +00001430 unsigned BitIndex;
Owen Anderson4e818902011-02-18 21:51:29 +00001431
1432 // We maintain BIT_WIDTH copies of the bitAttrs automaton.
1433 // The automaton consumes the corresponding bit from each
1434 // instruction.
1435 //
1436 // Input symbols: 0, 1, and _ (unset).
1437 // States: NONE, FILTERED, ALL_SET, ALL_UNSET, and MIXED.
1438 // Initial state: NONE.
1439 //
1440 // (NONE) ------- [01] -> (ALL_SET)
1441 // (NONE) ------- _ ----> (ALL_UNSET)
1442 // (ALL_SET) ---- [01] -> (ALL_SET)
1443 // (ALL_SET) ---- _ ----> (MIXED)
1444 // (ALL_UNSET) -- [01] -> (MIXED)
1445 // (ALL_UNSET) -- _ ----> (ALL_UNSET)
1446 // (MIXED) ------ . ----> (MIXED)
1447 // (FILTERED)---- . ----> (FILTERED)
1448
Owen Andersonc78e03c2011-07-19 21:06:00 +00001449 std::vector<bitAttr_t> bitAttrs;
Owen Anderson4e818902011-02-18 21:51:29 +00001450
1451 // FILTERED bit positions provide no entropy and are not worthy of pursuing.
1452 // Filter::recurse() set either BIT_TRUE or BIT_FALSE for each position.
Owen Andersonc78e03c2011-07-19 21:06:00 +00001453 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex)
Owen Anderson4e818902011-02-18 21:51:29 +00001454 if (FilterBitValues[BitIndex] == BIT_TRUE ||
1455 FilterBitValues[BitIndex] == BIT_FALSE)
Owen Andersonc78e03c2011-07-19 21:06:00 +00001456 bitAttrs.push_back(ATTR_FILTERED);
Owen Anderson4e818902011-02-18 21:51:29 +00001457 else
Owen Andersonc78e03c2011-07-19 21:06:00 +00001458 bitAttrs.push_back(ATTR_NONE);
Owen Anderson4e818902011-02-18 21:51:29 +00001459
Craig Topper29688ab2012-08-17 05:42:16 +00001460 for (unsigned InsnIndex = 0; InsnIndex < numInstructions; ++InsnIndex) {
Owen Anderson4e818902011-02-18 21:51:29 +00001461 insn_t insn;
1462
1463 insnWithID(insn, Opcodes[InsnIndex]);
1464
Owen Andersonc78e03c2011-07-19 21:06:00 +00001465 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
Owen Anderson4e818902011-02-18 21:51:29 +00001466 switch (bitAttrs[BitIndex]) {
1467 case ATTR_NONE:
1468 if (insn[BitIndex] == BIT_UNSET)
1469 bitAttrs[BitIndex] = ATTR_ALL_UNSET;
1470 else
1471 bitAttrs[BitIndex] = ATTR_ALL_SET;
1472 break;
1473 case ATTR_ALL_SET:
1474 if (insn[BitIndex] == BIT_UNSET)
1475 bitAttrs[BitIndex] = ATTR_MIXED;
1476 break;
1477 case ATTR_ALL_UNSET:
1478 if (insn[BitIndex] != BIT_UNSET)
1479 bitAttrs[BitIndex] = ATTR_MIXED;
1480 break;
1481 case ATTR_MIXED:
1482 case ATTR_FILTERED:
1483 break;
1484 }
1485 }
1486 }
1487
1488 // The regionAttr automaton consumes the bitAttrs automatons' state,
1489 // lowest-to-highest.
1490 //
1491 // Input symbols: F(iltered), (all_)S(et), (all_)U(nset), M(ixed)
1492 // States: NONE, ALL_SET, MIXED
1493 // Initial state: NONE
1494 //
1495 // (NONE) ----- F --> (NONE)
1496 // (NONE) ----- S --> (ALL_SET) ; and set region start
1497 // (NONE) ----- U --> (NONE)
1498 // (NONE) ----- M --> (MIXED) ; and set region start
1499 // (ALL_SET) -- F --> (NONE) ; and report an ALL_SET region
1500 // (ALL_SET) -- S --> (ALL_SET)
1501 // (ALL_SET) -- U --> (NONE) ; and report an ALL_SET region
1502 // (ALL_SET) -- M --> (MIXED) ; and report an ALL_SET region
1503 // (MIXED) ---- F --> (NONE) ; and report a MIXED region
1504 // (MIXED) ---- S --> (ALL_SET) ; and report a MIXED region
1505 // (MIXED) ---- U --> (NONE) ; and report a MIXED region
1506 // (MIXED) ---- M --> (MIXED)
1507
1508 bitAttr_t RA = ATTR_NONE;
1509 unsigned StartBit = 0;
1510
Craig Topper29688ab2012-08-17 05:42:16 +00001511 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
Owen Anderson4e818902011-02-18 21:51:29 +00001512 bitAttr_t bitAttr = bitAttrs[BitIndex];
1513
1514 assert(bitAttr != ATTR_NONE && "Bit without attributes");
1515
1516 switch (RA) {
1517 case ATTR_NONE:
1518 switch (bitAttr) {
1519 case ATTR_FILTERED:
1520 break;
1521 case ATTR_ALL_SET:
1522 StartBit = BitIndex;
1523 RA = ATTR_ALL_SET;
1524 break;
1525 case ATTR_ALL_UNSET:
1526 break;
1527 case ATTR_MIXED:
1528 StartBit = BitIndex;
1529 RA = ATTR_MIXED;
1530 break;
1531 default:
Craig Topperc4965bc2012-02-05 07:21:30 +00001532 llvm_unreachable("Unexpected bitAttr!");
Owen Anderson4e818902011-02-18 21:51:29 +00001533 }
1534 break;
1535 case ATTR_ALL_SET:
1536 switch (bitAttr) {
1537 case ATTR_FILTERED:
1538 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1539 RA = ATTR_NONE;
1540 break;
1541 case ATTR_ALL_SET:
1542 break;
1543 case ATTR_ALL_UNSET:
1544 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1545 RA = ATTR_NONE;
1546 break;
1547 case ATTR_MIXED:
1548 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1549 StartBit = BitIndex;
1550 RA = ATTR_MIXED;
1551 break;
1552 default:
Craig Topperc4965bc2012-02-05 07:21:30 +00001553 llvm_unreachable("Unexpected bitAttr!");
Owen Anderson4e818902011-02-18 21:51:29 +00001554 }
1555 break;
1556 case ATTR_MIXED:
1557 switch (bitAttr) {
1558 case ATTR_FILTERED:
1559 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1560 StartBit = BitIndex;
1561 RA = ATTR_NONE;
1562 break;
1563 case ATTR_ALL_SET:
1564 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1565 StartBit = BitIndex;
1566 RA = ATTR_ALL_SET;
1567 break;
1568 case ATTR_ALL_UNSET:
1569 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1570 RA = ATTR_NONE;
1571 break;
1572 case ATTR_MIXED:
1573 break;
1574 default:
Craig Topperc4965bc2012-02-05 07:21:30 +00001575 llvm_unreachable("Unexpected bitAttr!");
Owen Anderson4e818902011-02-18 21:51:29 +00001576 }
1577 break;
1578 case ATTR_ALL_UNSET:
Craig Topperc4965bc2012-02-05 07:21:30 +00001579 llvm_unreachable("regionAttr state machine has no ATTR_UNSET state");
Owen Anderson4e818902011-02-18 21:51:29 +00001580 case ATTR_FILTERED:
Craig Topperc4965bc2012-02-05 07:21:30 +00001581 llvm_unreachable("regionAttr state machine has no ATTR_FILTERED state");
Owen Anderson4e818902011-02-18 21:51:29 +00001582 }
1583 }
1584
1585 // At the end, if we're still in ALL_SET or MIXED states, report a region
1586 switch (RA) {
1587 case ATTR_NONE:
1588 break;
1589 case ATTR_FILTERED:
1590 break;
1591 case ATTR_ALL_SET:
1592 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1593 break;
1594 case ATTR_ALL_UNSET:
1595 break;
1596 case ATTR_MIXED:
1597 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1598 break;
1599 }
1600
1601 // We have finished with the filter processings. Now it's time to choose
1602 // the best performing filter.
1603 BestIndex = 0;
1604 bool AllUseless = true;
1605 unsigned BestScore = 0;
1606
1607 for (unsigned i = 0, e = Filters.size(); i != e; ++i) {
1608 unsigned Usefulness = Filters[i].usefulness();
1609
1610 if (Usefulness)
1611 AllUseless = false;
1612
1613 if (Usefulness > BestScore) {
1614 BestIndex = i;
1615 BestScore = Usefulness;
1616 }
1617 }
1618
1619 if (!AllUseless)
1620 bestFilter().recurse();
1621
1622 return !AllUseless;
1623} // end of FilterChooser::filterProcessor(bool)
1624
1625// Decides on the best configuration of filter(s) to use in order to decode
1626// the instructions. A conflict of instructions may occur, in which case we
1627// dump the conflict set to the standard error.
1628void FilterChooser::doFilter() {
1629 unsigned Num = Opcodes.size();
1630 assert(Num && "FilterChooser created with no instructions");
1631
1632 // Try regions of consecutive known bit values first.
1633 if (filterProcessor(false))
1634 return;
1635
1636 // Then regions of mixed bits (both known and unitialized bit values allowed).
1637 if (filterProcessor(true))
1638 return;
1639
1640 // Heuristics to cope with conflict set {t2CMPrs, t2SUBSrr, t2SUBSrs} where
1641 // no single instruction for the maximum ATTR_MIXED region Inst{14-4} has a
1642 // well-known encoding pattern. In such case, we backtrack and scan for the
1643 // the very first consecutive ATTR_ALL_SET region and assign a filter to it.
1644 if (Num == 3 && filterProcessor(true, false))
1645 return;
1646
1647 // If we come to here, the instruction decoding has failed.
1648 // Set the BestIndex to -1 to indicate so.
1649 BestIndex = -1;
1650}
1651
Jim Grosbachecaef492012-08-14 19:06:05 +00001652// emitTableEntries - Emit state machine entries to decode our share of
1653// instructions.
1654void FilterChooser::emitTableEntries(DecoderTableInfo &TableInfo) const {
1655 if (Opcodes.size() == 1) {
Owen Anderson4e818902011-02-18 21:51:29 +00001656 // There is only one instruction in the set, which is great!
1657 // Call emitSingletonDecoder() to see whether there are any remaining
1658 // encodings bits.
Jim Grosbachecaef492012-08-14 19:06:05 +00001659 emitSingletonTableEntry(TableInfo, Opcodes[0]);
1660 return;
1661 }
Owen Anderson4e818902011-02-18 21:51:29 +00001662
1663 // Choose the best filter to do the decodings!
1664 if (BestIndex != -1) {
Craig Topper48c112b2012-03-16 05:58:09 +00001665 const Filter &Best = Filters[BestIndex];
Owen Anderson4e818902011-02-18 21:51:29 +00001666 if (Best.getNumFiltered() == 1)
Jim Grosbachecaef492012-08-14 19:06:05 +00001667 emitSingletonTableEntry(TableInfo, Best);
Owen Anderson4e818902011-02-18 21:51:29 +00001668 else
Jim Grosbachecaef492012-08-14 19:06:05 +00001669 Best.emitTableEntry(TableInfo);
1670 return;
Owen Anderson4e818902011-02-18 21:51:29 +00001671 }
1672
Jim Grosbachecaef492012-08-14 19:06:05 +00001673 // We don't know how to decode these instructions! Dump the
1674 // conflict set and bail.
Owen Anderson4e818902011-02-18 21:51:29 +00001675
1676 // Print out useful conflict information for postmortem analysis.
1677 errs() << "Decoding Conflict:\n";
1678
1679 dumpStack(errs(), "\t\t");
1680
Craig Topper82d0d5f2012-03-16 01:19:24 +00001681 for (unsigned i = 0; i < Opcodes.size(); ++i) {
Owen Anderson4e818902011-02-18 21:51:29 +00001682 const std::string &Name = nameWithID(Opcodes[i]);
1683
1684 errs() << '\t' << Name << " ";
1685 dumpBits(errs(),
1686 getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
1687 errs() << '\n';
1688 }
Owen Anderson4e818902011-02-18 21:51:29 +00001689}
1690
Matt Arsenault4cb438b2016-07-18 23:20:46 +00001691static std::string findOperandDecoderMethod(TypedInit *TI) {
1692 std::string Decoder;
1693
1694 RecordRecTy *Type = cast<RecordRecTy>(TI->getType());
1695 Record *TypeRecord = Type->getRecord();
1696
1697 RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod");
1698 StringInit *String = DecoderString ?
1699 dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
1700 if (String) {
1701 Decoder = String->getValue();
1702 if (!Decoder.empty())
1703 return Decoder;
1704 }
1705
1706 if (TypeRecord->isSubClassOf("RegisterOperand"))
1707 TypeRecord = TypeRecord->getValueAsDef("RegClass");
1708
1709 if (TypeRecord->isSubClassOf("RegisterClass")) {
1710 Decoder = "Decode" + TypeRecord->getName() + "RegisterClass";
1711 } else if (TypeRecord->isSubClassOf("PointerLikeRegClass")) {
1712 Decoder = "DecodePointerLikeRegClass" +
1713 utostr(TypeRecord->getValueAsInt("RegClassKind"));
1714 }
1715
1716 return Decoder;
1717}
1718
Hal Finkel71b2e202013-12-19 16:12:53 +00001719static bool populateInstruction(CodeGenTarget &Target,
1720 const CodeGenInstruction &CGI, unsigned Opc,
Craig Topper82d0d5f2012-03-16 01:19:24 +00001721 std::map<unsigned, std::vector<OperandInfo> > &Operands){
Owen Anderson4e818902011-02-18 21:51:29 +00001722 const Record &Def = *CGI.TheDef;
1723 // If all the bit positions are not specified; do not decode this instruction.
1724 // We are bound to fail! For proper disassembly, the well-known encoding bits
1725 // of the instruction must be fully specified.
Owen Anderson4e818902011-02-18 21:51:29 +00001726
David Greeneaf8ee2c2011-07-29 22:43:06 +00001727 BitsInit &Bits = getBitsField(Def, "Inst");
Jim Grosbachf3fd36e2011-07-06 21:33:38 +00001728 if (Bits.allInComplete()) return false;
1729
Owen Anderson4e818902011-02-18 21:51:29 +00001730 std::vector<OperandInfo> InsnOperands;
1731
1732 // If the instruction has specified a custom decoding hook, use that instead
1733 // of trying to auto-generate the decoder.
1734 std::string InstDecoder = Def.getValueAsString("DecoderMethod");
1735 if (InstDecoder != "") {
Petr Pavlu182b0572015-07-15 08:04:27 +00001736 bool HasCompleteInstDecoder = Def.getValueAsBit("hasCompleteDecoder");
1737 InsnOperands.push_back(OperandInfo(InstDecoder, HasCompleteInstDecoder));
Owen Anderson4e818902011-02-18 21:51:29 +00001738 Operands[Opc] = InsnOperands;
1739 return true;
1740 }
1741
1742 // Generate a description of the operand of the instruction that we know
1743 // how to decode automatically.
1744 // FIXME: We'll need to have a way to manually override this as needed.
1745
1746 // Gather the outputs/inputs of the instruction, so we can find their
1747 // positions in the encoding. This assumes for now that they appear in the
1748 // MCInst in the order that they're listed.
David Greeneaf8ee2c2011-07-29 22:43:06 +00001749 std::vector<std::pair<Init*, std::string> > InOutOperands;
1750 DagInit *Out = Def.getValueAsDag("OutOperandList");
1751 DagInit *In = Def.getValueAsDag("InOperandList");
Owen Anderson4e818902011-02-18 21:51:29 +00001752 for (unsigned i = 0; i < Out->getNumArgs(); ++i)
1753 InOutOperands.push_back(std::make_pair(Out->getArg(i), Out->getArgName(i)));
1754 for (unsigned i = 0; i < In->getNumArgs(); ++i)
1755 InOutOperands.push_back(std::make_pair(In->getArg(i), In->getArgName(i)));
1756
Owen Anderson53562d02011-07-28 23:56:20 +00001757 // Search for tied operands, so that we can correctly instantiate
1758 // operands that are not explicitly represented in the encoding.
Owen Andersoncb32ce22011-07-29 18:28:52 +00001759 std::map<std::string, std::string> TiedNames;
Owen Anderson53562d02011-07-28 23:56:20 +00001760 for (unsigned i = 0; i < CGI.Operands.size(); ++i) {
1761 int tiedTo = CGI.Operands[i].getTiedRegister();
Owen Andersoncb32ce22011-07-29 18:28:52 +00001762 if (tiedTo != -1) {
Hal Finkel71b2e202013-12-19 16:12:53 +00001763 std::pair<unsigned, unsigned> SO =
1764 CGI.Operands.getSubOperandNumber(tiedTo);
1765 TiedNames[InOutOperands[i].second] = InOutOperands[SO.first].second;
1766 TiedNames[InOutOperands[SO.first].second] = InOutOperands[i].second;
1767 }
1768 }
1769
1770 std::map<std::string, std::vector<OperandInfo> > NumberedInsnOperands;
1771 std::set<std::string> NumberedInsnOperandsNoTie;
1772 if (Target.getInstructionSet()->
1773 getValueAsBit("decodePositionallyEncodedOperands")) {
1774 const std::vector<RecordVal> &Vals = Def.getValues();
1775 unsigned NumberedOp = 0;
1776
Hal Finkel5457bd02014-03-13 07:57:54 +00001777 std::set<unsigned> NamedOpIndices;
1778 if (Target.getInstructionSet()->
1779 getValueAsBit("noNamedPositionallyEncodedOperands"))
1780 // Collect the set of operand indices that might correspond to named
1781 // operand, and skip these when assigning operands based on position.
1782 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1783 unsigned OpIdx;
1784 if (!CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx))
1785 continue;
1786
1787 NamedOpIndices.insert(OpIdx);
1788 }
1789
Hal Finkel71b2e202013-12-19 16:12:53 +00001790 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1791 // Ignore fixed fields in the record, we're looking for values like:
1792 // bits<5> RST = { ?, ?, ?, ?, ? };
1793 if (Vals[i].getPrefix() || Vals[i].getValue()->isComplete())
1794 continue;
1795
1796 // Determine if Vals[i] actually contributes to the Inst encoding.
1797 unsigned bi = 0;
1798 for (; bi < Bits.getNumBits(); ++bi) {
Craig Topper24064772014-04-15 07:20:03 +00001799 VarInit *Var = nullptr;
Hal Finkel71b2e202013-12-19 16:12:53 +00001800 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
1801 if (BI)
1802 Var = dyn_cast<VarInit>(BI->getBitVar());
1803 else
1804 Var = dyn_cast<VarInit>(Bits.getBit(bi));
1805
1806 if (Var && Var->getName() == Vals[i].getName())
1807 break;
1808 }
1809
1810 if (bi == Bits.getNumBits())
1811 continue;
1812
1813 // Skip variables that correspond to explicitly-named operands.
1814 unsigned OpIdx;
1815 if (CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx))
1816 continue;
1817
1818 // Get the bit range for this operand:
1819 unsigned bitStart = bi++, bitWidth = 1;
1820 for (; bi < Bits.getNumBits(); ++bi) {
Craig Topper24064772014-04-15 07:20:03 +00001821 VarInit *Var = nullptr;
Hal Finkel71b2e202013-12-19 16:12:53 +00001822 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
1823 if (BI)
1824 Var = dyn_cast<VarInit>(BI->getBitVar());
1825 else
1826 Var = dyn_cast<VarInit>(Bits.getBit(bi));
1827
1828 if (!Var)
1829 break;
1830
1831 if (Var->getName() != Vals[i].getName())
1832 break;
1833
1834 ++bitWidth;
1835 }
1836
1837 unsigned NumberOps = CGI.Operands.size();
1838 while (NumberedOp < NumberOps &&
Hal Finkel5457bd02014-03-13 07:57:54 +00001839 (CGI.Operands.isFlatOperandNotEmitted(NumberedOp) ||
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00001840 (!NamedOpIndices.empty() && NamedOpIndices.count(
Hal Finkel5457bd02014-03-13 07:57:54 +00001841 CGI.Operands.getSubOperandNumber(NumberedOp).first))))
Hal Finkel71b2e202013-12-19 16:12:53 +00001842 ++NumberedOp;
1843
1844 OpIdx = NumberedOp++;
1845
1846 // OpIdx now holds the ordered operand number of Vals[i].
1847 std::pair<unsigned, unsigned> SO =
1848 CGI.Operands.getSubOperandNumber(OpIdx);
1849 const std::string &Name = CGI.Operands[SO.first].Name;
1850
1851 DEBUG(dbgs() << "Numbered operand mapping for " << Def.getName() << ": " <<
1852 Name << "(" << SO.first << ", " << SO.second << ") => " <<
1853 Vals[i].getName() << "\n");
1854
1855 std::string Decoder = "";
1856 Record *TypeRecord = CGI.Operands[SO.first].Rec;
1857
1858 RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod");
1859 StringInit *String = DecoderString ?
Craig Topper24064772014-04-15 07:20:03 +00001860 dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
Hal Finkel71b2e202013-12-19 16:12:53 +00001861 if (String && String->getValue() != "")
1862 Decoder = String->getValue();
1863
1864 if (Decoder == "" &&
1865 CGI.Operands[SO.first].MIOperandInfo &&
1866 CGI.Operands[SO.first].MIOperandInfo->getNumArgs()) {
1867 Init *Arg = CGI.Operands[SO.first].MIOperandInfo->
1868 getArg(SO.second);
1869 if (TypedInit *TI = cast<TypedInit>(Arg)) {
1870 RecordRecTy *Type = cast<RecordRecTy>(TI->getType());
1871 TypeRecord = Type->getRecord();
1872 }
1873 }
1874
1875 bool isReg = false;
1876 if (TypeRecord->isSubClassOf("RegisterOperand"))
1877 TypeRecord = TypeRecord->getValueAsDef("RegClass");
1878 if (TypeRecord->isSubClassOf("RegisterClass")) {
1879 Decoder = "Decode" + TypeRecord->getName() + "RegisterClass";
1880 isReg = true;
1881 } else if (TypeRecord->isSubClassOf("PointerLikeRegClass")) {
1882 Decoder = "DecodePointerLikeRegClass" +
1883 utostr(TypeRecord->getValueAsInt("RegClassKind"));
1884 isReg = true;
1885 }
1886
1887 DecoderString = TypeRecord->getValue("DecoderMethod");
1888 String = DecoderString ?
Craig Topper24064772014-04-15 07:20:03 +00001889 dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
Hal Finkel71b2e202013-12-19 16:12:53 +00001890 if (!isReg && String && String->getValue() != "")
1891 Decoder = String->getValue();
1892
Petr Pavlu182b0572015-07-15 08:04:27 +00001893 RecordVal *HasCompleteDecoderVal =
1894 TypeRecord->getValue("hasCompleteDecoder");
1895 BitInit *HasCompleteDecoderBit = HasCompleteDecoderVal ?
1896 dyn_cast<BitInit>(HasCompleteDecoderVal->getValue()) : nullptr;
1897 bool HasCompleteDecoder = HasCompleteDecoderBit ?
1898 HasCompleteDecoderBit->getValue() : true;
1899
1900 OperandInfo OpInfo(Decoder, HasCompleteDecoder);
Hal Finkel71b2e202013-12-19 16:12:53 +00001901 OpInfo.addField(bitStart, bitWidth, 0);
1902
1903 NumberedInsnOperands[Name].push_back(OpInfo);
1904
1905 // FIXME: For complex operands with custom decoders we can't handle tied
1906 // sub-operands automatically. Skip those here and assume that this is
1907 // fixed up elsewhere.
1908 if (CGI.Operands[SO.first].MIOperandInfo &&
1909 CGI.Operands[SO.first].MIOperandInfo->getNumArgs() > 1 &&
1910 String && String->getValue() != "")
1911 NumberedInsnOperandsNoTie.insert(Name);
Owen Andersoncb32ce22011-07-29 18:28:52 +00001912 }
Owen Anderson53562d02011-07-28 23:56:20 +00001913 }
1914
Owen Anderson4e818902011-02-18 21:51:29 +00001915 // For each operand, see if we can figure out where it is encoded.
Craig Topper1f7604d2014-12-13 05:12:19 +00001916 for (const auto &Op : InOutOperands) {
1917 if (!NumberedInsnOperands[Op.second].empty()) {
Hal Finkel71b2e202013-12-19 16:12:53 +00001918 InsnOperands.insert(InsnOperands.end(),
Craig Topper1f7604d2014-12-13 05:12:19 +00001919 NumberedInsnOperands[Op.second].begin(),
1920 NumberedInsnOperands[Op.second].end());
Hal Finkel71b2e202013-12-19 16:12:53 +00001921 continue;
Craig Topper1f7604d2014-12-13 05:12:19 +00001922 }
1923 if (!NumberedInsnOperands[TiedNames[Op.second]].empty()) {
1924 if (!NumberedInsnOperandsNoTie.count(TiedNames[Op.second])) {
Hal Finkel71b2e202013-12-19 16:12:53 +00001925 // Figure out to which (sub)operand we're tied.
Craig Topper1f7604d2014-12-13 05:12:19 +00001926 unsigned i = CGI.Operands.getOperandNamed(TiedNames[Op.second]);
Hal Finkel71b2e202013-12-19 16:12:53 +00001927 int tiedTo = CGI.Operands[i].getTiedRegister();
1928 if (tiedTo == -1) {
Craig Topper1f7604d2014-12-13 05:12:19 +00001929 i = CGI.Operands.getOperandNamed(Op.second);
Hal Finkel71b2e202013-12-19 16:12:53 +00001930 tiedTo = CGI.Operands[i].getTiedRegister();
1931 }
1932
1933 if (tiedTo != -1) {
1934 std::pair<unsigned, unsigned> SO =
1935 CGI.Operands.getSubOperandNumber(tiedTo);
1936
Craig Topper1f7604d2014-12-13 05:12:19 +00001937 InsnOperands.push_back(NumberedInsnOperands[TiedNames[Op.second]]
Hal Finkel71b2e202013-12-19 16:12:53 +00001938 [SO.second]);
1939 }
1940 }
1941 continue;
1942 }
1943
Craig Topper1f7604d2014-12-13 05:12:19 +00001944 TypedInit *TI = cast<TypedInit>(Op.first);
Owen Andersone3591652011-07-28 21:54:31 +00001945
Matt Arsenault4cb438b2016-07-18 23:20:46 +00001946 // At this point, we can locate the decoder field, but we need to know how
1947 // to interpret it. As a first step, require the target to provide
1948 // callbacks for decoding register classes.
1949 std::string Decoder = findOperandDecoderMethod(TI);
1950 Record *TypeRecord = cast<RecordRecTy>(TI->getType())->getRecord();
Owen Andersone3591652011-07-28 21:54:31 +00001951
Petr Pavlu182b0572015-07-15 08:04:27 +00001952 RecordVal *HasCompleteDecoderVal =
1953 TypeRecord->getValue("hasCompleteDecoder");
1954 BitInit *HasCompleteDecoderBit = HasCompleteDecoderVal ?
1955 dyn_cast<BitInit>(HasCompleteDecoderVal->getValue()) : nullptr;
1956 bool HasCompleteDecoder = HasCompleteDecoderBit ?
1957 HasCompleteDecoderBit->getValue() : true;
1958
1959 OperandInfo OpInfo(Decoder, HasCompleteDecoder);
Owen Andersone3591652011-07-28 21:54:31 +00001960 unsigned Base = ~0U;
1961 unsigned Width = 0;
1962 unsigned Offset = 0;
1963
Owen Anderson4e818902011-02-18 21:51:29 +00001964 for (unsigned bi = 0; bi < Bits.getNumBits(); ++bi) {
Craig Topper24064772014-04-15 07:20:03 +00001965 VarInit *Var = nullptr;
Sean Silvafb509ed2012-10-10 20:24:43 +00001966 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
Owen Anderson3022d672011-08-01 22:45:43 +00001967 if (BI)
Sean Silvafb509ed2012-10-10 20:24:43 +00001968 Var = dyn_cast<VarInit>(BI->getBitVar());
Owen Anderson3022d672011-08-01 22:45:43 +00001969 else
Sean Silvafb509ed2012-10-10 20:24:43 +00001970 Var = dyn_cast<VarInit>(Bits.getBit(bi));
Owen Anderson3022d672011-08-01 22:45:43 +00001971
1972 if (!Var) {
Owen Andersone3591652011-07-28 21:54:31 +00001973 if (Base != ~0U) {
1974 OpInfo.addField(Base, Width, Offset);
1975 Base = ~0U;
1976 Width = 0;
1977 Offset = 0;
1978 }
1979 continue;
1980 }
Owen Anderson4e818902011-02-18 21:51:29 +00001981
Craig Topper1f7604d2014-12-13 05:12:19 +00001982 if (Var->getName() != Op.second &&
1983 Var->getName() != TiedNames[Op.second]) {
Owen Andersone3591652011-07-28 21:54:31 +00001984 if (Base != ~0U) {
1985 OpInfo.addField(Base, Width, Offset);
1986 Base = ~0U;
1987 Width = 0;
1988 Offset = 0;
1989 }
1990 continue;
Owen Anderson4e818902011-02-18 21:51:29 +00001991 }
1992
Owen Andersone3591652011-07-28 21:54:31 +00001993 if (Base == ~0U) {
1994 Base = bi;
1995 Width = 1;
Owen Anderson3022d672011-08-01 22:45:43 +00001996 Offset = BI ? BI->getBitNum() : 0;
1997 } else if (BI && BI->getBitNum() != Offset + Width) {
Owen Andersone08f5b52011-07-29 23:01:18 +00001998 OpInfo.addField(Base, Width, Offset);
1999 Base = bi;
2000 Width = 1;
2001 Offset = BI->getBitNum();
Owen Andersone3591652011-07-28 21:54:31 +00002002 } else {
2003 ++Width;
Owen Anderson4e818902011-02-18 21:51:29 +00002004 }
Owen Anderson4e818902011-02-18 21:51:29 +00002005 }
2006
Owen Andersone3591652011-07-28 21:54:31 +00002007 if (Base != ~0U)
2008 OpInfo.addField(Base, Width, Offset);
2009
2010 if (OpInfo.numFields() > 0)
2011 InsnOperands.push_back(OpInfo);
Owen Anderson4e818902011-02-18 21:51:29 +00002012 }
2013
2014 Operands[Opc] = InsnOperands;
2015
2016
2017#if 0
2018 DEBUG({
2019 // Dumps the instruction encoding bits.
2020 dumpBits(errs(), Bits);
2021
2022 errs() << '\n';
2023
2024 // Dumps the list of operand info.
2025 for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) {
2026 const CGIOperandList::OperandInfo &Info = CGI.Operands[i];
2027 const std::string &OperandName = Info.Name;
2028 const Record &OperandDef = *Info.Rec;
2029
2030 errs() << "\t" << OperandName << " (" << OperandDef.getName() << ")\n";
2031 }
2032 });
2033#endif
2034
2035 return true;
2036}
2037
Jim Grosbachecaef492012-08-14 19:06:05 +00002038// emitFieldFromInstruction - Emit the templated helper function
2039// fieldFromInstruction().
2040static void emitFieldFromInstruction(formatted_raw_ostream &OS) {
2041 OS << "// Helper function for extracting fields from encoded instructions.\n"
2042 << "template<typename InsnType>\n"
2043 << "static InsnType fieldFromInstruction(InsnType insn, unsigned startBit,\n"
2044 << " unsigned numBits) {\n"
2045 << " assert(startBit + numBits <= (sizeof(InsnType)*8) &&\n"
2046 << " \"Instruction field out of bounds!\");\n"
2047 << " InsnType fieldMask;\n"
2048 << " if (numBits == sizeof(InsnType)*8)\n"
2049 << " fieldMask = (InsnType)(-1LL);\n"
2050 << " else\n"
NAKAMURA Takumibf99a422012-12-26 06:43:14 +00002051 << " fieldMask = (((InsnType)1 << numBits) - 1) << startBit;\n"
Jim Grosbachecaef492012-08-14 19:06:05 +00002052 << " return (insn & fieldMask) >> startBit;\n"
2053 << "}\n\n";
2054}
Owen Anderson4e818902011-02-18 21:51:29 +00002055
Jim Grosbachecaef492012-08-14 19:06:05 +00002056// emitDecodeInstruction - Emit the templated helper function
2057// decodeInstruction().
2058static void emitDecodeInstruction(formatted_raw_ostream &OS) {
2059 OS << "template<typename InsnType>\n"
2060 << "static DecodeStatus decodeInstruction(const uint8_t DecodeTable[], MCInst &MI,\n"
2061 << " InsnType insn, uint64_t Address,\n"
2062 << " const void *DisAsm,\n"
2063 << " const MCSubtargetInfo &STI) {\n"
Michael Kupersteindb0712f2015-05-26 10:47:10 +00002064 << " const FeatureBitset& Bits = STI.getFeatureBits();\n"
Jim Grosbachecaef492012-08-14 19:06:05 +00002065 << "\n"
2066 << " const uint8_t *Ptr = DecodeTable;\n"
Jim Grosbach4c363492012-09-17 18:00:53 +00002067 << " uint32_t CurFieldValue = 0;\n"
Jim Grosbachecaef492012-08-14 19:06:05 +00002068 << " DecodeStatus S = MCDisassembler::Success;\n"
2069 << " for (;;) {\n"
2070 << " ptrdiff_t Loc = Ptr - DecodeTable;\n"
2071 << " switch (*Ptr) {\n"
2072 << " default:\n"
2073 << " errs() << Loc << \": Unexpected decode table opcode!\\n\";\n"
2074 << " return MCDisassembler::Fail;\n"
2075 << " case MCD::OPC_ExtractField: {\n"
2076 << " unsigned Start = *++Ptr;\n"
2077 << " unsigned Len = *++Ptr;\n"
2078 << " ++Ptr;\n"
2079 << " CurFieldValue = fieldFromInstruction(insn, Start, Len);\n"
2080 << " DEBUG(dbgs() << Loc << \": OPC_ExtractField(\" << Start << \", \"\n"
2081 << " << Len << \"): \" << CurFieldValue << \"\\n\");\n"
2082 << " break;\n"
2083 << " }\n"
2084 << " case MCD::OPC_FilterValue: {\n"
2085 << " // Decode the field value.\n"
2086 << " unsigned Len;\n"
2087 << " InsnType Val = decodeULEB128(++Ptr, &Len);\n"
2088 << " Ptr += Len;\n"
2089 << " // NumToSkip is a plain 16-bit integer.\n"
2090 << " unsigned NumToSkip = *Ptr++;\n"
2091 << " NumToSkip |= (*Ptr++) << 8;\n"
2092 << "\n"
2093 << " // Perform the filter operation.\n"
2094 << " if (Val != CurFieldValue)\n"
2095 << " Ptr += NumToSkip;\n"
2096 << " DEBUG(dbgs() << Loc << \": OPC_FilterValue(\" << Val << \", \" << NumToSkip\n"
2097 << " << \"): \" << ((Val != CurFieldValue) ? \"FAIL:\" : \"PASS:\")\n"
2098 << " << \" continuing at \" << (Ptr - DecodeTable) << \"\\n\");\n"
2099 << "\n"
2100 << " break;\n"
2101 << " }\n"
2102 << " case MCD::OPC_CheckField: {\n"
2103 << " unsigned Start = *++Ptr;\n"
2104 << " unsigned Len = *++Ptr;\n"
2105 << " InsnType FieldValue = fieldFromInstruction(insn, Start, Len);\n"
2106 << " // Decode the field value.\n"
2107 << " uint32_t ExpectedValue = decodeULEB128(++Ptr, &Len);\n"
2108 << " Ptr += Len;\n"
2109 << " // NumToSkip is a plain 16-bit integer.\n"
2110 << " unsigned NumToSkip = *Ptr++;\n"
2111 << " NumToSkip |= (*Ptr++) << 8;\n"
2112 << "\n"
2113 << " // If the actual and expected values don't match, skip.\n"
2114 << " if (ExpectedValue != FieldValue)\n"
2115 << " Ptr += NumToSkip;\n"
2116 << " DEBUG(dbgs() << Loc << \": OPC_CheckField(\" << Start << \", \"\n"
2117 << " << Len << \", \" << ExpectedValue << \", \" << NumToSkip\n"
2118 << " << \"): FieldValue = \" << FieldValue << \", ExpectedValue = \"\n"
2119 << " << ExpectedValue << \": \"\n"
2120 << " << ((ExpectedValue == FieldValue) ? \"PASS\\n\" : \"FAIL\\n\"));\n"
2121 << " break;\n"
2122 << " }\n"
2123 << " case MCD::OPC_CheckPredicate: {\n"
2124 << " unsigned Len;\n"
2125 << " // Decode the Predicate Index value.\n"
2126 << " unsigned PIdx = decodeULEB128(++Ptr, &Len);\n"
2127 << " Ptr += Len;\n"
2128 << " // NumToSkip is a plain 16-bit integer.\n"
2129 << " unsigned NumToSkip = *Ptr++;\n"
2130 << " NumToSkip |= (*Ptr++) << 8;\n"
2131 << " // Check the predicate.\n"
2132 << " bool Pred;\n"
2133 << " if (!(Pred = checkDecoderPredicate(PIdx, Bits)))\n"
2134 << " Ptr += NumToSkip;\n"
2135 << " (void)Pred;\n"
2136 << " DEBUG(dbgs() << Loc << \": OPC_CheckPredicate(\" << PIdx << \"): \"\n"
2137 << " << (Pred ? \"PASS\\n\" : \"FAIL\\n\"));\n"
2138 << "\n"
2139 << " break;\n"
2140 << " }\n"
2141 << " case MCD::OPC_Decode: {\n"
2142 << " unsigned Len;\n"
2143 << " // Decode the Opcode value.\n"
2144 << " unsigned Opc = decodeULEB128(++Ptr, &Len);\n"
2145 << " Ptr += Len;\n"
2146 << " unsigned DecodeIdx = decodeULEB128(Ptr, &Len);\n"
2147 << " Ptr += Len;\n"
Jim Grosbachecaef492012-08-14 19:06:05 +00002148 << "\n"
Cameron Esfahanif97999d2015-08-11 01:15:07 +00002149 << " MI.clear();\n"
Jim Grosbachecaef492012-08-14 19:06:05 +00002150 << " MI.setOpcode(Opc);\n"
Petr Pavlu182b0572015-07-15 08:04:27 +00002151 << " bool DecodeComplete;\n"
2152 << " S = decodeToMCInst(S, DecodeIdx, insn, MI, Address, DisAsm, DecodeComplete);\n"
2153 << " assert(DecodeComplete);\n"
2154 << "\n"
2155 << " DEBUG(dbgs() << Loc << \": OPC_Decode: opcode \" << Opc\n"
2156 << " << \", using decoder \" << DecodeIdx << \": \"\n"
2157 << " << (S != MCDisassembler::Fail ? \"PASS\" : \"FAIL\") << \"\\n\");\n"
2158 << " return S;\n"
2159 << " }\n"
2160 << " case MCD::OPC_TryDecode: {\n"
2161 << " unsigned Len;\n"
2162 << " // Decode the Opcode value.\n"
2163 << " unsigned Opc = decodeULEB128(++Ptr, &Len);\n"
2164 << " Ptr += Len;\n"
2165 << " unsigned DecodeIdx = decodeULEB128(Ptr, &Len);\n"
2166 << " Ptr += Len;\n"
2167 << " // NumToSkip is a plain 16-bit integer.\n"
2168 << " unsigned NumToSkip = *Ptr++;\n"
2169 << " NumToSkip |= (*Ptr++) << 8;\n"
2170 << "\n"
2171 << " // Perform the decode operation.\n"
2172 << " MCInst TmpMI;\n"
2173 << " TmpMI.setOpcode(Opc);\n"
2174 << " bool DecodeComplete;\n"
2175 << " S = decodeToMCInst(S, DecodeIdx, insn, TmpMI, Address, DisAsm, DecodeComplete);\n"
2176 << " DEBUG(dbgs() << Loc << \": OPC_TryDecode: opcode \" << Opc\n"
2177 << " << \", using decoder \" << DecodeIdx << \": \");\n"
2178 << "\n"
2179 << " if (DecodeComplete) {\n"
2180 << " // Decoding complete.\n"
2181 << " DEBUG(dbgs() << (S != MCDisassembler::Fail ? \"PASS\" : \"FAIL\") << \"\\n\");\n"
2182 << " MI = TmpMI;\n"
2183 << " return S;\n"
2184 << " } else {\n"
2185 << " assert(S == MCDisassembler::Fail);\n"
2186 << " // If the decoding was incomplete, skip.\n"
2187 << " Ptr += NumToSkip;\n"
2188 << " DEBUG(dbgs() << \"FAIL: continuing at \" << (Ptr - DecodeTable) << \"\\n\");\n"
2189 << " // Reset decode status. This also drops a SoftFail status that could be\n"
2190 << " // set before the decode attempt.\n"
2191 << " S = MCDisassembler::Success;\n"
2192 << " }\n"
2193 << " break;\n"
Jim Grosbachecaef492012-08-14 19:06:05 +00002194 << " }\n"
2195 << " case MCD::OPC_SoftFail: {\n"
2196 << " // Decode the mask values.\n"
2197 << " unsigned Len;\n"
2198 << " InsnType PositiveMask = decodeULEB128(++Ptr, &Len);\n"
2199 << " Ptr += Len;\n"
2200 << " InsnType NegativeMask = decodeULEB128(Ptr, &Len);\n"
2201 << " Ptr += Len;\n"
2202 << " bool Fail = (insn & PositiveMask) || (~insn & NegativeMask);\n"
2203 << " if (Fail)\n"
2204 << " S = MCDisassembler::SoftFail;\n"
2205 << " DEBUG(dbgs() << Loc << \": OPC_SoftFail: \" << (Fail ? \"FAIL\\n\":\"PASS\\n\"));\n"
2206 << " break;\n"
2207 << " }\n"
2208 << " case MCD::OPC_Fail: {\n"
2209 << " DEBUG(dbgs() << Loc << \": OPC_Fail\\n\");\n"
2210 << " return MCDisassembler::Fail;\n"
2211 << " }\n"
2212 << " }\n"
2213 << " }\n"
2214 << " llvm_unreachable(\"bogosity detected in disassembler state machine!\");\n"
2215 << "}\n\n";
Owen Anderson4e818902011-02-18 21:51:29 +00002216}
2217
2218// Emits disassembler code for instruction decoding.
Craig Topper82d0d5f2012-03-16 01:19:24 +00002219void FixedLenDecoderEmitter::run(raw_ostream &o) {
Jim Grosbachecaef492012-08-14 19:06:05 +00002220 formatted_raw_ostream OS(o);
2221 OS << "#include \"llvm/MC/MCInst.h\"\n";
2222 OS << "#include \"llvm/Support/Debug.h\"\n";
2223 OS << "#include \"llvm/Support/DataTypes.h\"\n";
2224 OS << "#include \"llvm/Support/LEB128.h\"\n";
2225 OS << "#include \"llvm/Support/raw_ostream.h\"\n";
2226 OS << "#include <assert.h>\n";
2227 OS << '\n';
2228 OS << "namespace llvm {\n\n";
2229
2230 emitFieldFromInstruction(OS);
Owen Anderson4e818902011-02-18 21:51:29 +00002231
Hal Finkel81e6fcc2013-12-17 22:37:50 +00002232 Target.reverseBitsForLittleEndianEncoding();
2233
Owen Andersonc78e03c2011-07-19 21:06:00 +00002234 // Parameterize the decoders based on namespace and instruction width.
Craig Topperf9265322016-01-17 20:38:14 +00002235 NumberedInstructions = Target.getInstructionsByEnumValue();
Owen Andersonc78e03c2011-07-19 21:06:00 +00002236 std::map<std::pair<std::string, unsigned>,
2237 std::vector<unsigned> > OpcMap;
2238 std::map<unsigned, std::vector<OperandInfo> > Operands;
2239
Craig Topperf9265322016-01-17 20:38:14 +00002240 for (unsigned i = 0; i < NumberedInstructions.size(); ++i) {
2241 const CodeGenInstruction *Inst = NumberedInstructions[i];
Craig Topper48c112b2012-03-16 05:58:09 +00002242 const Record *Def = Inst->TheDef;
Owen Andersonc78e03c2011-07-19 21:06:00 +00002243 unsigned Size = Def->getValueAsInt("Size");
2244 if (Def->getValueAsString("Namespace") == "TargetOpcode" ||
2245 Def->getValueAsBit("isPseudo") ||
2246 Def->getValueAsBit("isAsmParserOnly") ||
2247 Def->getValueAsBit("isCodeGenOnly"))
2248 continue;
2249
2250 std::string DecoderNamespace = Def->getValueAsString("DecoderNamespace");
2251
2252 if (Size) {
Hal Finkel71b2e202013-12-19 16:12:53 +00002253 if (populateInstruction(Target, *Inst, i, Operands)) {
Owen Andersonc78e03c2011-07-19 21:06:00 +00002254 OpcMap[std::make_pair(DecoderNamespace, Size)].push_back(i);
2255 }
2256 }
2257 }
2258
Jim Grosbachecaef492012-08-14 19:06:05 +00002259 DecoderTableInfo TableInfo;
Craig Topper1f7604d2014-12-13 05:12:19 +00002260 for (const auto &Opc : OpcMap) {
Owen Andersonc78e03c2011-07-19 21:06:00 +00002261 // Emit the decoder for this namespace+width combination.
Craig Topperf9265322016-01-17 20:38:14 +00002262 FilterChooser FC(NumberedInstructions, Opc.second, Operands,
Craig Topper1f7604d2014-12-13 05:12:19 +00002263 8*Opc.first.second, this);
Jim Grosbachecaef492012-08-14 19:06:05 +00002264
2265 // The decode table is cleared for each top level decoder function. The
2266 // predicates and decoders themselves, however, are shared across all
2267 // decoders to give more opportunities for uniqueing.
2268 TableInfo.Table.clear();
2269 TableInfo.FixupStack.clear();
2270 TableInfo.Table.reserve(16384);
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002271 TableInfo.FixupStack.emplace_back();
Jim Grosbachecaef492012-08-14 19:06:05 +00002272 FC.emitTableEntries(TableInfo);
2273 // Any NumToSkip fixups in the top level scope can resolve to the
2274 // OPC_Fail at the end of the table.
2275 assert(TableInfo.FixupStack.size() == 1 && "fixup stack phasing error!");
2276 // Resolve any NumToSkip fixups in the current scope.
2277 resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),
2278 TableInfo.Table.size());
2279 TableInfo.FixupStack.clear();
2280
2281 TableInfo.Table.push_back(MCD::OPC_Fail);
2282
2283 // Print the table to the output stream.
Craig Topper1f7604d2014-12-13 05:12:19 +00002284 emitTable(OS, TableInfo.Table, 0, FC.getBitWidth(), Opc.first.first);
Jim Grosbachecaef492012-08-14 19:06:05 +00002285 OS.flush();
Owen Andersonc78e03c2011-07-19 21:06:00 +00002286 }
Owen Anderson4e818902011-02-18 21:51:29 +00002287
Jim Grosbachecaef492012-08-14 19:06:05 +00002288 // Emit the predicate function.
2289 emitPredicateFunction(OS, TableInfo.Predicates, 0);
2290
2291 // Emit the decoder function.
2292 emitDecoderFunction(OS, TableInfo.Decoders, 0);
2293
2294 // Emit the main entry point for the decoder, decodeInstruction().
2295 emitDecodeInstruction(OS);
2296
2297 OS << "\n} // End llvm namespace\n";
Owen Anderson4e818902011-02-18 21:51:29 +00002298}
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +00002299
2300namespace llvm {
2301
2302void EmitFixedLenDecoder(RecordKeeper &RK, raw_ostream &OS,
Benjamin Kramerc321e532016-06-08 19:09:22 +00002303 const std::string &PredicateNamespace,
2304 const std::string &GPrefix,
2305 const std::string &GPostfix, const std::string &ROK,
2306 const std::string &RFail, const std::string &L) {
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +00002307 FixedLenDecoderEmitter(RK, PredicateNamespace, GPrefix, GPostfix,
2308 ROK, RFail, L).run(OS);
2309}
2310
2311} // End llvm namespace