blob: f2d54e6fe5afb8aac3d7cef5d1eaa144c0de5c6c [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"
Justin Lebar5e83dfe2016-10-21 21:45:01 +000017#include "llvm/ADT/CachedHashString.h"
Jim Grosbachecaef492012-08-14 19:06:05 +000018#include "llvm/ADT/SmallString.h"
Owen Anderson4e818902011-02-18 21:51:29 +000019#include "llvm/ADT/StringExtras.h"
Jim Grosbachecaef492012-08-14 19:06:05 +000020#include "llvm/ADT/StringRef.h"
21#include "llvm/ADT/Twine.h"
22#include "llvm/MC/MCFixedLenDisassembler.h"
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000023#include "llvm/Support/DataTypes.h"
Owen Anderson4e818902011-02-18 21:51:29 +000024#include "llvm/Support/Debug.h"
Jim Grosbachecaef492012-08-14 19:06:05 +000025#include "llvm/Support/FormattedStream.h"
26#include "llvm/Support/LEB128.h"
Owen Anderson4e818902011-02-18 21:51:29 +000027#include "llvm/Support/raw_ostream.h"
Chandler Carruth91d19d82012-12-04 10:37:14 +000028#include "llvm/TableGen/Error.h"
29#include "llvm/TableGen/Record.h"
Owen Anderson4e818902011-02-18 21:51:29 +000030#include <map>
31#include <string>
Benjamin Kramer82de7d32016-05-27 14:27:24 +000032#include <utility>
Chandler Carruth91d19d82012-12-04 10:37:14 +000033#include <vector>
Owen Anderson4e818902011-02-18 21:51:29 +000034
35using namespace llvm;
36
Chandler Carruth97acce22014-04-22 03:06:00 +000037#define DEBUG_TYPE "decoder-emitter"
38
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000039namespace {
40struct EncodingField {
41 unsigned Base, Width, Offset;
42 EncodingField(unsigned B, unsigned W, unsigned O)
43 : Base(B), Width(W), Offset(O) { }
44};
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000045
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000046struct OperandInfo {
47 std::vector<EncodingField> Fields;
48 std::string Decoder;
Petr Pavlu182b0572015-07-15 08:04:27 +000049 bool HasCompleteDecoder;
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000050
Petr Pavlu182b0572015-07-15 08:04:27 +000051 OperandInfo(std::string D, bool HCD)
Benjamin Kramer82de7d32016-05-27 14:27:24 +000052 : Decoder(std::move(D)), HasCompleteDecoder(HCD) {}
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000053
54 void addField(unsigned Base, unsigned Width, unsigned Offset) {
55 Fields.push_back(EncodingField(Base, Width, Offset));
56 }
57
58 unsigned numFields() const { return Fields.size(); }
59
60 typedef std::vector<EncodingField>::const_iterator const_iterator;
61
62 const_iterator begin() const { return Fields.begin(); }
63 const_iterator end() const { return Fields.end(); }
64};
Jim Grosbachecaef492012-08-14 19:06:05 +000065
66typedef std::vector<uint8_t> DecoderTable;
67typedef uint32_t DecoderFixup;
68typedef std::vector<DecoderFixup> FixupList;
69typedef std::vector<FixupList> FixupScopeList;
Justin Lebar5e83dfe2016-10-21 21:45:01 +000070typedef SmallSetVector<CachedHashString, 16> PredicateSet;
71typedef SmallSetVector<CachedHashString, 16> DecoderSet;
Jim Grosbachecaef492012-08-14 19:06:05 +000072struct DecoderTableInfo {
73 DecoderTable Table;
74 FixupScopeList FixupStack;
75 PredicateSet Predicates;
76 DecoderSet Decoders;
77};
78
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000079} // End anonymous namespace
80
81namespace {
82class FixedLenDecoderEmitter {
Craig Topperf9265322016-01-17 20:38:14 +000083 ArrayRef<const CodeGenInstruction *> NumberedInstructions;
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000084public:
85
86 // Defaults preserved here for documentation, even though they aren't
87 // strictly necessary given the way that this is currently being called.
Benjamin Kramer82de7d32016-05-27 14:27:24 +000088 FixedLenDecoderEmitter(RecordKeeper &R, std::string PredicateNamespace,
89 std::string GPrefix = "if (",
Petr Pavlu182b0572015-07-15 08:04:27 +000090 std::string GPostfix = " == MCDisassembler::Fail)",
Benjamin Kramer82de7d32016-05-27 14:27:24 +000091 std::string ROK = "MCDisassembler::Success",
92 std::string RFail = "MCDisassembler::Fail",
93 std::string L = "")
94 : Target(R), PredicateNamespace(std::move(PredicateNamespace)),
95 GuardPrefix(std::move(GPrefix)), GuardPostfix(std::move(GPostfix)),
96 ReturnOK(std::move(ROK)), ReturnFail(std::move(RFail)),
97 Locals(std::move(L)) {}
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000098
Jim Grosbachecaef492012-08-14 19:06:05 +000099 // Emit the decoder state machine table.
100 void emitTable(formatted_raw_ostream &o, DecoderTable &Table,
101 unsigned Indentation, unsigned BitWidth,
102 StringRef Namespace) const;
103 void emitPredicateFunction(formatted_raw_ostream &OS,
104 PredicateSet &Predicates,
105 unsigned Indentation) const;
106 void emitDecoderFunction(formatted_raw_ostream &OS,
107 DecoderSet &Decoders,
108 unsigned Indentation) const;
109
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +0000110 // run - Output the code emitter
111 void run(raw_ostream &o);
112
113private:
114 CodeGenTarget Target;
115public:
116 std::string PredicateNamespace;
117 std::string GuardPrefix, GuardPostfix;
118 std::string ReturnOK, ReturnFail;
119 std::string Locals;
120};
121} // End anonymous namespace
122
Owen Anderson4e818902011-02-18 21:51:29 +0000123// The set (BIT_TRUE, BIT_FALSE, BIT_UNSET) represents a ternary logic system
124// for a bit value.
125//
126// BIT_UNFILTERED is used as the init value for a filter position. It is used
127// only for filter processings.
128typedef enum {
129 BIT_TRUE, // '1'
130 BIT_FALSE, // '0'
131 BIT_UNSET, // '?'
132 BIT_UNFILTERED // unfiltered
133} bit_value_t;
134
135static bool ValueSet(bit_value_t V) {
136 return (V == BIT_TRUE || V == BIT_FALSE);
137}
138static bool ValueNotSet(bit_value_t V) {
139 return (V == BIT_UNSET);
140}
141static int Value(bit_value_t V) {
142 return ValueNotSet(V) ? -1 : (V == BIT_FALSE ? 0 : 1);
143}
Craig Topper48c112b2012-03-16 05:58:09 +0000144static bit_value_t bitFromBits(const BitsInit &bits, unsigned index) {
Sean Silvafb509ed2012-10-10 20:24:43 +0000145 if (BitInit *bit = dyn_cast<BitInit>(bits.getBit(index)))
Owen Anderson4e818902011-02-18 21:51:29 +0000146 return bit->getValue() ? BIT_TRUE : BIT_FALSE;
147
148 // The bit is uninitialized.
149 return BIT_UNSET;
150}
151// Prints the bit value for each position.
Craig Topper48c112b2012-03-16 05:58:09 +0000152static void dumpBits(raw_ostream &o, const BitsInit &bits) {
Craig Topper29688ab2012-08-17 05:42:16 +0000153 for (unsigned index = bits.getNumBits(); index > 0; --index) {
Owen Anderson4e818902011-02-18 21:51:29 +0000154 switch (bitFromBits(bits, index - 1)) {
155 case BIT_TRUE:
156 o << "1";
157 break;
158 case BIT_FALSE:
159 o << "0";
160 break;
161 case BIT_UNSET:
162 o << "_";
163 break;
164 default:
Craig Topperc4965bc2012-02-05 07:21:30 +0000165 llvm_unreachable("unexpected return value from bitFromBits");
Owen Anderson4e818902011-02-18 21:51:29 +0000166 }
167 }
168}
169
Mehdi Amini32986ed2016-10-04 23:47:33 +0000170static BitsInit &getBitsField(const Record &def, StringRef str) {
David Greeneaf8ee2c2011-07-29 22:43:06 +0000171 BitsInit *bits = def.getValueAsBitsInit(str);
Owen Anderson4e818902011-02-18 21:51:29 +0000172 return *bits;
173}
174
175// Forward declaration.
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +0000176namespace {
Owen Anderson4e818902011-02-18 21:51:29 +0000177class FilterChooser;
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +0000178} // End anonymous namespace
Owen Anderson4e818902011-02-18 21:51:29 +0000179
Owen Anderson4e818902011-02-18 21:51:29 +0000180// Representation of the instruction to work on.
Owen Andersonc78e03c2011-07-19 21:06:00 +0000181typedef std::vector<bit_value_t> insn_t;
Owen Anderson4e818902011-02-18 21:51:29 +0000182
183/// Filter - Filter works with FilterChooser to produce the decoding tree for
184/// the ISA.
185///
186/// It is useful to think of a Filter as governing the switch stmts of the
187/// decoding tree in a certain level. Each case stmt delegates to an inferior
188/// FilterChooser to decide what further decoding logic to employ, or in another
189/// words, what other remaining bits to look at. The FilterChooser eventually
190/// chooses a best Filter to do its job.
191///
192/// This recursive scheme ends when the number of Opcodes assigned to the
193/// FilterChooser becomes 1 or if there is a conflict. A conflict happens when
194/// the Filter/FilterChooser combo does not know how to distinguish among the
195/// Opcodes assigned.
196///
197/// An example of a conflict is
198///
199/// Conflict:
200/// 111101000.00........00010000....
201/// 111101000.00........0001........
202/// 1111010...00........0001........
203/// 1111010...00....................
204/// 1111010.........................
205/// 1111............................
206/// ................................
207/// VST4q8a 111101000_00________00010000____
208/// VST4q8b 111101000_00________00010000____
209///
210/// The Debug output shows the path that the decoding tree follows to reach the
211/// the conclusion that there is a conflict. VST4q8a is a vst4 to double-spaced
Petr Pavlu21894652015-07-14 08:00:34 +0000212/// even registers, while VST4q8b is a vst4 to double-spaced odd registers.
Owen Anderson4e818902011-02-18 21:51:29 +0000213///
214/// The encoding info in the .td files does not specify this meta information,
215/// which could have been used by the decoder to resolve the conflict. The
216/// decoder could try to decode the even/odd register numbering and assign to
217/// VST4q8a or VST4q8b, but for the time being, the decoder chooses the "a"
218/// version and return the Opcode since the two have the same Asm format string.
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +0000219namespace {
Owen Anderson4e818902011-02-18 21:51:29 +0000220class Filter {
221protected:
Craig Topper501d95c2012-03-16 06:52:56 +0000222 const FilterChooser *Owner;// points to the FilterChooser who owns this filter
Owen Anderson4e818902011-02-18 21:51:29 +0000223 unsigned StartBit; // the starting bit position
224 unsigned NumBits; // number of bits to filter
225 bool Mixed; // a mixed region contains both set and unset bits
226
227 // Map of well-known segment value to the set of uid's with that value.
228 std::map<uint64_t, std::vector<unsigned> > FilteredInstructions;
229
230 // Set of uid's with non-constant segment values.
231 std::vector<unsigned> VariableInstructions;
232
233 // Map of well-known segment value to its delegate.
Craig Toppercf05f912014-09-03 06:07:54 +0000234 std::map<unsigned, std::unique_ptr<const FilterChooser>> FilterChooserMap;
Owen Anderson4e818902011-02-18 21:51:29 +0000235
236 // Number of instructions which fall under FilteredInstructions category.
237 unsigned NumFiltered;
238
239 // Keeps track of the last opcode in the filtered bucket.
240 unsigned LastOpcFiltered;
241
Owen Anderson4e818902011-02-18 21:51:29 +0000242public:
Craig Topper48c112b2012-03-16 05:58:09 +0000243 unsigned getNumFiltered() const { return NumFiltered; }
244 unsigned getSingletonOpc() const {
Owen Anderson4e818902011-02-18 21:51:29 +0000245 assert(NumFiltered == 1);
246 return LastOpcFiltered;
247 }
248 // Return the filter chooser for the group of instructions without constant
249 // segment values.
Craig Topper48c112b2012-03-16 05:58:09 +0000250 const FilterChooser &getVariableFC() const {
Owen Anderson4e818902011-02-18 21:51:29 +0000251 assert(NumFiltered == 1);
252 assert(FilterChooserMap.size() == 1);
253 return *(FilterChooserMap.find((unsigned)-1)->second);
254 }
255
Craig Topper5c2b4ac2014-09-03 05:49:07 +0000256 Filter(Filter &&f);
Owen Anderson4e818902011-02-18 21:51:29 +0000257 Filter(FilterChooser &owner, unsigned startBit, unsigned numBits, bool mixed);
258
259 ~Filter();
260
261 // Divides the decoding task into sub tasks and delegates them to the
262 // inferior FilterChooser's.
263 //
264 // A special case arises when there's only one entry in the filtered
265 // instructions. In order to unambiguously decode the singleton, we need to
266 // match the remaining undecoded encoding bits against the singleton.
267 void recurse();
268
Jim Grosbachecaef492012-08-14 19:06:05 +0000269 // Emit table entries to decode instructions given a segment or segments of
270 // bits.
271 void emitTableEntry(DecoderTableInfo &TableInfo) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000272
273 // Returns the number of fanout produced by the filter. More fanout implies
274 // the filter distinguishes more categories of instructions.
275 unsigned usefulness() const;
276}; // End of class Filter
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +0000277} // End anonymous namespace
Owen Anderson4e818902011-02-18 21:51:29 +0000278
279// These are states of our finite state machines used in FilterChooser's
280// filterProcessor() which produces the filter candidates to use.
281typedef enum {
282 ATTR_NONE,
283 ATTR_FILTERED,
284 ATTR_ALL_SET,
285 ATTR_ALL_UNSET,
286 ATTR_MIXED
287} bitAttr_t;
288
289/// FilterChooser - FilterChooser chooses the best filter among a set of Filters
290/// in order to perform the decoding of instructions at the current level.
291///
292/// Decoding proceeds from the top down. Based on the well-known encoding bits
293/// of instructions available, FilterChooser builds up the possible Filters that
294/// can further the task of decoding by distinguishing among the remaining
295/// candidate instructions.
296///
297/// Once a filter has been chosen, it is called upon to divide the decoding task
298/// into sub-tasks and delegates them to its inferior FilterChoosers for further
299/// processings.
300///
301/// It is useful to think of a Filter as governing the switch stmts of the
302/// decoding tree. And each case is delegated to an inferior FilterChooser to
303/// decide what further remaining bits to look at.
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +0000304namespace {
Owen Anderson4e818902011-02-18 21:51:29 +0000305class FilterChooser {
306protected:
307 friend class Filter;
308
309 // Vector of codegen instructions to choose our filter.
Craig Topperf9265322016-01-17 20:38:14 +0000310 ArrayRef<const CodeGenInstruction *> AllInstructions;
Owen Anderson4e818902011-02-18 21:51:29 +0000311
312 // Vector of uid's for this filter chooser to work on.
Craig Topper501d95c2012-03-16 06:52:56 +0000313 const std::vector<unsigned> &Opcodes;
Owen Anderson4e818902011-02-18 21:51:29 +0000314
315 // Lookup table for the operand decoding of instructions.
Craig Topper501d95c2012-03-16 06:52:56 +0000316 const std::map<unsigned, std::vector<OperandInfo> > &Operands;
Owen Anderson4e818902011-02-18 21:51:29 +0000317
318 // Vector of candidate filters.
319 std::vector<Filter> Filters;
320
321 // Array of bit values passed down from our parent.
322 // Set to all BIT_UNFILTERED's for Parent == NULL.
Owen Andersonc78e03c2011-07-19 21:06:00 +0000323 std::vector<bit_value_t> FilterBitValues;
Owen Anderson4e818902011-02-18 21:51:29 +0000324
325 // Links to the FilterChooser above us in the decoding tree.
Craig Topper501d95c2012-03-16 06:52:56 +0000326 const FilterChooser *Parent;
Owen Anderson4e818902011-02-18 21:51:29 +0000327
328 // Index of the best filter from Filters.
329 int BestIndex;
330
Owen Andersonc78e03c2011-07-19 21:06:00 +0000331 // Width of instructions
332 unsigned BitWidth;
333
Owen Andersona4043c42011-08-17 17:44:15 +0000334 // Parent emitter
335 const FixedLenDecoderEmitter *Emitter;
336
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000337 FilterChooser(const FilterChooser &) = delete;
338 void operator=(const FilterChooser &) = delete;
Owen Anderson4e818902011-02-18 21:51:29 +0000339public:
Owen Anderson4e818902011-02-18 21:51:29 +0000340
Craig Topperf9265322016-01-17 20:38:14 +0000341 FilterChooser(ArrayRef<const CodeGenInstruction *> Insts,
Owen Anderson4e818902011-02-18 21:51:29 +0000342 const std::vector<unsigned> &IDs,
Craig Topper501d95c2012-03-16 06:52:56 +0000343 const std::map<unsigned, std::vector<OperandInfo> > &Ops,
Owen Andersona4043c42011-08-17 17:44:15 +0000344 unsigned BW,
Craig Topper82d0d5f2012-03-16 01:19:24 +0000345 const FixedLenDecoderEmitter *E)
346 : AllInstructions(Insts), Opcodes(IDs), Operands(Ops), Filters(),
Craig Topper1ddc2882014-09-04 04:49:03 +0000347 FilterBitValues(BW, BIT_UNFILTERED), Parent(nullptr), BestIndex(-1),
348 BitWidth(BW), Emitter(E) {
Owen Anderson4e818902011-02-18 21:51:29 +0000349 doFilter();
350 }
351
Craig Topperf9265322016-01-17 20:38:14 +0000352 FilterChooser(ArrayRef<const CodeGenInstruction *> Insts,
Owen Anderson4e818902011-02-18 21:51:29 +0000353 const std::vector<unsigned> &IDs,
Craig Topper501d95c2012-03-16 06:52:56 +0000354 const std::map<unsigned, std::vector<OperandInfo> > &Ops,
355 const std::vector<bit_value_t> &ParentFilterBitValues,
356 const FilterChooser &parent)
Craig Topper82d0d5f2012-03-16 01:19:24 +0000357 : AllInstructions(Insts), Opcodes(IDs), Operands(Ops),
Owen Andersonc78e03c2011-07-19 21:06:00 +0000358 Filters(), FilterBitValues(ParentFilterBitValues),
Owen Andersona4043c42011-08-17 17:44:15 +0000359 Parent(&parent), BestIndex(-1), BitWidth(parent.BitWidth),
360 Emitter(parent.Emitter) {
Owen Anderson4e818902011-02-18 21:51:29 +0000361 doFilter();
362 }
363
Jim Grosbachecaef492012-08-14 19:06:05 +0000364 unsigned getBitWidth() const { return BitWidth; }
Owen Anderson4e818902011-02-18 21:51:29 +0000365
366protected:
367 // Populates the insn given the uid.
368 void insnWithID(insn_t &Insn, unsigned Opcode) const {
David Greeneaf8ee2c2011-07-29 22:43:06 +0000369 BitsInit &Bits = getBitsField(*AllInstructions[Opcode]->TheDef, "Inst");
Owen Anderson4e818902011-02-18 21:51:29 +0000370
James Molloyd9ba4fd2012-02-09 10:56:31 +0000371 // We may have a SoftFail bitmask, which specifies a mask where an encoding
372 // may differ from the value in "Inst" and yet still be valid, but the
373 // disassembler should return SoftFail instead of Success.
374 //
375 // This is used for marking UNPREDICTABLE instructions in the ARM world.
Jim Grosbach3f4b2392012-02-29 22:07:56 +0000376 BitsInit *SFBits =
377 AllInstructions[Opcode]->TheDef->getValueAsBitsInit("SoftFail");
James Molloyd9ba4fd2012-02-09 10:56:31 +0000378
379 for (unsigned i = 0; i < BitWidth; ++i) {
380 if (SFBits && bitFromBits(*SFBits, i) == BIT_TRUE)
381 Insn.push_back(BIT_UNSET);
382 else
383 Insn.push_back(bitFromBits(Bits, i));
384 }
Owen Anderson4e818902011-02-18 21:51:29 +0000385 }
386
387 // Returns the record name.
388 const std::string &nameWithID(unsigned Opcode) const {
389 return AllInstructions[Opcode]->TheDef->getName();
390 }
391
392 // Populates the field of the insn given the start position and the number of
393 // consecutive bits to scan for.
394 //
395 // Returns false if there exists any uninitialized bit value in the range.
396 // Returns true, otherwise.
397 bool fieldFromInsn(uint64_t &Field, insn_t &Insn, unsigned StartBit,
Craig Topper82d0d5f2012-03-16 01:19:24 +0000398 unsigned NumBits) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000399
400 /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
401 /// filter array as a series of chars.
Craig Topper48c112b2012-03-16 05:58:09 +0000402 void dumpFilterArray(raw_ostream &o,
403 const std::vector<bit_value_t> & filter) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000404
405 /// dumpStack - dumpStack traverses the filter chooser chain and calls
406 /// dumpFilterArray on each filter chooser up to the top level one.
Craig Topper48c112b2012-03-16 05:58:09 +0000407 void dumpStack(raw_ostream &o, const char *prefix) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000408
409 Filter &bestFilter() {
410 assert(BestIndex != -1 && "BestIndex not set");
411 return Filters[BestIndex];
412 }
413
Craig Topper48c112b2012-03-16 05:58:09 +0000414 bool PositionFiltered(unsigned i) const {
Owen Anderson4e818902011-02-18 21:51:29 +0000415 return ValueSet(FilterBitValues[i]);
416 }
417
418 // Calculates the island(s) needed to decode the instruction.
419 // This returns a lit of undecoded bits of an instructions, for example,
420 // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
421 // decoded bits in order to verify that the instruction matches the Opcode.
422 unsigned getIslands(std::vector<unsigned> &StartBits,
Craig Topper82d0d5f2012-03-16 01:19:24 +0000423 std::vector<unsigned> &EndBits,
Craig Topper48c112b2012-03-16 05:58:09 +0000424 std::vector<uint64_t> &FieldVals,
425 const insn_t &Insn) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000426
James Molloy8067df92011-09-07 19:42:28 +0000427 // Emits code to check the Predicates member of an instruction are true.
428 // Returns true if predicate matches were emitted, false otherwise.
Craig Topper48c112b2012-03-16 05:58:09 +0000429 bool emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
430 unsigned Opc) const;
James Molloy8067df92011-09-07 19:42:28 +0000431
Jim Grosbachecaef492012-08-14 19:06:05 +0000432 bool doesOpcodeNeedPredicate(unsigned Opc) const;
433 unsigned getPredicateIndex(DecoderTableInfo &TableInfo, StringRef P) const;
434 void emitPredicateTableEntry(DecoderTableInfo &TableInfo,
435 unsigned Opc) const;
James Molloyd9ba4fd2012-02-09 10:56:31 +0000436
Jim Grosbachecaef492012-08-14 19:06:05 +0000437 void emitSoftFailTableEntry(DecoderTableInfo &TableInfo,
438 unsigned Opc) const;
439
440 // Emits table entries to decode the singleton.
441 void emitSingletonTableEntry(DecoderTableInfo &TableInfo,
442 unsigned Opc) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000443
444 // Emits code to decode the singleton, and then to decode the rest.
Jim Grosbachecaef492012-08-14 19:06:05 +0000445 void emitSingletonTableEntry(DecoderTableInfo &TableInfo,
446 const Filter &Best) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000447
Jim Grosbachecaef492012-08-14 19:06:05 +0000448 void emitBinaryParser(raw_ostream &o, unsigned &Indentation,
Petr Pavlu182b0572015-07-15 08:04:27 +0000449 const OperandInfo &OpInfo,
450 bool &OpHasCompleteDecoder) const;
Owen Andersone3591652011-07-28 21:54:31 +0000451
Petr Pavlu182b0572015-07-15 08:04:27 +0000452 void emitDecoder(raw_ostream &OS, unsigned Indentation, unsigned Opc,
453 bool &HasCompleteDecoder) const;
454 unsigned getDecoderIndex(DecoderSet &Decoders, unsigned Opc,
455 bool &HasCompleteDecoder) const;
Jim Grosbachecaef492012-08-14 19:06:05 +0000456
Owen Anderson4e818902011-02-18 21:51:29 +0000457 // Assign a single filter and run with it.
Craig Topper48c112b2012-03-16 05:58:09 +0000458 void runSingleFilter(unsigned startBit, unsigned numBit, bool mixed);
Owen Anderson4e818902011-02-18 21:51:29 +0000459
460 // reportRegion is a helper function for filterProcessor to mark a region as
461 // eligible for use as a filter region.
462 void reportRegion(bitAttr_t RA, unsigned StartBit, unsigned BitIndex,
Craig Topper82d0d5f2012-03-16 01:19:24 +0000463 bool AllowMixed);
Owen Anderson4e818902011-02-18 21:51:29 +0000464
465 // FilterProcessor scans the well-known encoding bits of the instructions and
466 // builds up a list of candidate filters. It chooses the best filter and
467 // recursively descends down the decoding tree.
468 bool filterProcessor(bool AllowMixed, bool Greedy = true);
469
470 // Decides on the best configuration of filter(s) to use in order to decode
471 // the instructions. A conflict of instructions may occur, in which case we
472 // dump the conflict set to the standard error.
473 void doFilter();
474
Jim Grosbachecaef492012-08-14 19:06:05 +0000475public:
476 // emitTableEntries - Emit state machine entries to decode our share of
477 // instructions.
478 void emitTableEntries(DecoderTableInfo &TableInfo) const;
Owen Anderson4e818902011-02-18 21:51:29 +0000479};
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +0000480} // End anonymous namespace
Owen Anderson4e818902011-02-18 21:51:29 +0000481
482///////////////////////////
483// //
Craig Topper93e64342012-03-16 00:56:01 +0000484// Filter Implementation //
Owen Anderson4e818902011-02-18 21:51:29 +0000485// //
486///////////////////////////
487
Craig Topper5c2b4ac2014-09-03 05:49:07 +0000488Filter::Filter(Filter &&f)
Craig Topper82d0d5f2012-03-16 01:19:24 +0000489 : Owner(f.Owner), StartBit(f.StartBit), NumBits(f.NumBits), Mixed(f.Mixed),
Craig Topper5c2b4ac2014-09-03 05:49:07 +0000490 FilteredInstructions(std::move(f.FilteredInstructions)),
491 VariableInstructions(std::move(f.VariableInstructions)),
492 FilterChooserMap(std::move(f.FilterChooserMap)), NumFiltered(f.NumFiltered),
Craig Topper82d0d5f2012-03-16 01:19:24 +0000493 LastOpcFiltered(f.LastOpcFiltered) {
Owen Anderson4e818902011-02-18 21:51:29 +0000494}
495
496Filter::Filter(FilterChooser &owner, unsigned startBit, unsigned numBits,
Craig Topper82d0d5f2012-03-16 01:19:24 +0000497 bool mixed)
498 : Owner(&owner), StartBit(startBit), NumBits(numBits), Mixed(mixed) {
Owen Andersonc78e03c2011-07-19 21:06:00 +0000499 assert(StartBit + NumBits - 1 < Owner->BitWidth);
Owen Anderson4e818902011-02-18 21:51:29 +0000500
501 NumFiltered = 0;
502 LastOpcFiltered = 0;
Owen Anderson4e818902011-02-18 21:51:29 +0000503
504 for (unsigned i = 0, e = Owner->Opcodes.size(); i != e; ++i) {
505 insn_t Insn;
506
507 // Populates the insn given the uid.
508 Owner->insnWithID(Insn, Owner->Opcodes[i]);
509
510 uint64_t Field;
511 // Scans the segment for possibly well-specified encoding bits.
512 bool ok = Owner->fieldFromInsn(Field, Insn, StartBit, NumBits);
513
514 if (ok) {
515 // The encoding bits are well-known. Lets add the uid of the
516 // instruction into the bucket keyed off the constant field value.
517 LastOpcFiltered = Owner->Opcodes[i];
518 FilteredInstructions[Field].push_back(LastOpcFiltered);
519 ++NumFiltered;
520 } else {
Craig Topper93e64342012-03-16 00:56:01 +0000521 // Some of the encoding bit(s) are unspecified. This contributes to
Owen Anderson4e818902011-02-18 21:51:29 +0000522 // one additional member of "Variable" instructions.
523 VariableInstructions.push_back(Owner->Opcodes[i]);
Owen Anderson4e818902011-02-18 21:51:29 +0000524 }
525 }
526
527 assert((FilteredInstructions.size() + VariableInstructions.size() > 0)
528 && "Filter returns no instruction categories");
529}
530
531Filter::~Filter() {
Owen Anderson4e818902011-02-18 21:51:29 +0000532}
533
534// Divides the decoding task into sub tasks and delegates them to the
535// inferior FilterChooser's.
536//
537// A special case arises when there's only one entry in the filtered
538// instructions. In order to unambiguously decode the singleton, we need to
539// match the remaining undecoded encoding bits against the singleton.
540void Filter::recurse() {
Owen Anderson4e818902011-02-18 21:51:29 +0000541 // Starts by inheriting our parent filter chooser's filter bit values.
Owen Andersonc78e03c2011-07-19 21:06:00 +0000542 std::vector<bit_value_t> BitValueArray(Owner->FilterBitValues);
Owen Anderson4e818902011-02-18 21:51:29 +0000543
Alexander Kornienko8c0809c2015-01-15 11:41:30 +0000544 if (!VariableInstructions.empty()) {
Owen Anderson4e818902011-02-18 21:51:29 +0000545 // Conservatively marks each segment position as BIT_UNSET.
Craig Topper29688ab2012-08-17 05:42:16 +0000546 for (unsigned bitIndex = 0; bitIndex < NumBits; ++bitIndex)
Owen Anderson4e818902011-02-18 21:51:29 +0000547 BitValueArray[StartBit + bitIndex] = BIT_UNSET;
548
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000549 // Delegates to an inferior filter chooser for further processing on this
Owen Anderson4e818902011-02-18 21:51:29 +0000550 // group of instructions whose segment values are variable.
Yaron Kerene499db02014-09-03 08:22:30 +0000551 FilterChooserMap.insert(
552 std::make_pair(-1U, llvm::make_unique<FilterChooser>(
553 Owner->AllInstructions, VariableInstructions,
554 Owner->Operands, BitValueArray, *Owner)));
Owen Anderson4e818902011-02-18 21:51:29 +0000555 }
556
557 // No need to recurse for a singleton filtered instruction.
Jim Grosbachecaef492012-08-14 19:06:05 +0000558 // See also Filter::emit*().
Owen Anderson4e818902011-02-18 21:51:29 +0000559 if (getNumFiltered() == 1) {
Owen Anderson4e818902011-02-18 21:51:29 +0000560 assert(FilterChooserMap.size() == 1);
561 return;
562 }
563
564 // Otherwise, create sub choosers.
Craig Topper1f7604d2014-12-13 05:12:19 +0000565 for (const auto &Inst : FilteredInstructions) {
Owen Anderson4e818902011-02-18 21:51:29 +0000566
567 // Marks all the segment positions with either BIT_TRUE or BIT_FALSE.
Craig Topper29688ab2012-08-17 05:42:16 +0000568 for (unsigned bitIndex = 0; bitIndex < NumBits; ++bitIndex) {
Craig Topper1f7604d2014-12-13 05:12:19 +0000569 if (Inst.first & (1ULL << bitIndex))
Owen Anderson4e818902011-02-18 21:51:29 +0000570 BitValueArray[StartBit + bitIndex] = BIT_TRUE;
571 else
572 BitValueArray[StartBit + bitIndex] = BIT_FALSE;
573 }
574
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000575 // Delegates to an inferior filter chooser for further processing on this
Owen Anderson4e818902011-02-18 21:51:29 +0000576 // category of instructions.
Craig Toppercf05f912014-09-03 06:07:54 +0000577 FilterChooserMap.insert(std::make_pair(
Craig Topper1f7604d2014-12-13 05:12:19 +0000578 Inst.first, llvm::make_unique<FilterChooser>(
579 Owner->AllInstructions, Inst.second,
Yaron Kerene499db02014-09-03 08:22:30 +0000580 Owner->Operands, BitValueArray, *Owner)));
Owen Anderson4e818902011-02-18 21:51:29 +0000581 }
582}
583
Jim Grosbachecaef492012-08-14 19:06:05 +0000584static void resolveTableFixups(DecoderTable &Table, const FixupList &Fixups,
585 uint32_t DestIdx) {
586 // Any NumToSkip fixups in the current scope can resolve to the
587 // current location.
588 for (FixupList::const_reverse_iterator I = Fixups.rbegin(),
589 E = Fixups.rend();
590 I != E; ++I) {
591 // Calculate the distance from the byte following the fixup entry byte
592 // to the destination. The Target is calculated from after the 16-bit
593 // NumToSkip entry itself, so subtract two from the displacement here
594 // to account for that.
595 uint32_t FixupIdx = *I;
596 uint32_t Delta = DestIdx - FixupIdx - 2;
597 // Our NumToSkip entries are 16-bits. Make sure our table isn't too
598 // big.
599 assert(Delta < 65536U && "disassembler decoding table too large!");
600 Table[FixupIdx] = (uint8_t)Delta;
601 Table[FixupIdx + 1] = (uint8_t)(Delta >> 8);
602 }
603}
Owen Anderson4e818902011-02-18 21:51:29 +0000604
Jim Grosbachecaef492012-08-14 19:06:05 +0000605// Emit table entries to decode instructions given a segment or segments
606// of bits.
607void Filter::emitTableEntry(DecoderTableInfo &TableInfo) const {
608 TableInfo.Table.push_back(MCD::OPC_ExtractField);
609 TableInfo.Table.push_back(StartBit);
610 TableInfo.Table.push_back(NumBits);
Owen Anderson4e818902011-02-18 21:51:29 +0000611
Jim Grosbachecaef492012-08-14 19:06:05 +0000612 // A new filter entry begins a new scope for fixup resolution.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000613 TableInfo.FixupStack.emplace_back();
Owen Anderson4e818902011-02-18 21:51:29 +0000614
Jim Grosbachecaef492012-08-14 19:06:05 +0000615 DecoderTable &Table = TableInfo.Table;
616
617 size_t PrevFilter = 0;
618 bool HasFallthrough = false;
Craig Topper1f7604d2014-12-13 05:12:19 +0000619 for (auto &Filter : FilterChooserMap) {
Owen Anderson4e818902011-02-18 21:51:29 +0000620 // Field value -1 implies a non-empty set of variable instructions.
621 // See also recurse().
Craig Topper1f7604d2014-12-13 05:12:19 +0000622 if (Filter.first == (unsigned)-1) {
Jim Grosbachecaef492012-08-14 19:06:05 +0000623 HasFallthrough = true;
Owen Anderson4e818902011-02-18 21:51:29 +0000624
Jim Grosbachecaef492012-08-14 19:06:05 +0000625 // Each scope should always have at least one filter value to check
626 // for.
627 assert(PrevFilter != 0 && "empty filter set!");
628 FixupList &CurScope = TableInfo.FixupStack.back();
629 // Resolve any NumToSkip fixups in the current scope.
630 resolveTableFixups(Table, CurScope, Table.size());
631 CurScope.clear();
632 PrevFilter = 0; // Don't re-process the filter's fallthrough.
633 } else {
634 Table.push_back(MCD::OPC_FilterValue);
635 // Encode and emit the value to filter against.
636 uint8_t Buffer[8];
Craig Topper1f7604d2014-12-13 05:12:19 +0000637 unsigned Len = encodeULEB128(Filter.first, Buffer);
Jim Grosbachecaef492012-08-14 19:06:05 +0000638 Table.insert(Table.end(), Buffer, Buffer + Len);
639 // Reserve space for the NumToSkip entry. We'll backpatch the value
640 // later.
641 PrevFilter = Table.size();
642 Table.push_back(0);
643 Table.push_back(0);
644 }
Owen Anderson4e818902011-02-18 21:51:29 +0000645
646 // We arrive at a category of instructions with the same segment value.
647 // Now delegate to the sub filter chooser for further decodings.
648 // The case may fallthrough, which happens if the remaining well-known
649 // encoding bits do not match exactly.
Craig Topper1f7604d2014-12-13 05:12:19 +0000650 Filter.second->emitTableEntries(TableInfo);
Owen Anderson4e818902011-02-18 21:51:29 +0000651
Jim Grosbachecaef492012-08-14 19:06:05 +0000652 // Now that we've emitted the body of the handler, update the NumToSkip
653 // of the filter itself to be able to skip forward when false. Subtract
654 // two as to account for the width of the NumToSkip field itself.
655 if (PrevFilter) {
656 uint32_t NumToSkip = Table.size() - PrevFilter - 2;
657 assert(NumToSkip < 65536U && "disassembler decoding table too large!");
658 Table[PrevFilter] = (uint8_t)NumToSkip;
659 Table[PrevFilter + 1] = (uint8_t)(NumToSkip >> 8);
660 }
Owen Anderson4e818902011-02-18 21:51:29 +0000661 }
662
Jim Grosbachecaef492012-08-14 19:06:05 +0000663 // Any remaining unresolved fixups bubble up to the parent fixup scope.
664 assert(TableInfo.FixupStack.size() > 1 && "fixup stack underflow!");
665 FixupScopeList::iterator Source = TableInfo.FixupStack.end() - 1;
666 FixupScopeList::iterator Dest = Source - 1;
667 Dest->insert(Dest->end(), Source->begin(), Source->end());
668 TableInfo.FixupStack.pop_back();
669
670 // If there is no fallthrough, then the final filter should get fixed
671 // up according to the enclosing scope rather than the current position.
672 if (!HasFallthrough)
673 TableInfo.FixupStack.back().push_back(PrevFilter);
Owen Anderson4e818902011-02-18 21:51:29 +0000674}
675
676// Returns the number of fanout produced by the filter. More fanout implies
677// the filter distinguishes more categories of instructions.
678unsigned Filter::usefulness() const {
Alexander Kornienko8c0809c2015-01-15 11:41:30 +0000679 if (!VariableInstructions.empty())
Owen Anderson4e818902011-02-18 21:51:29 +0000680 return FilteredInstructions.size();
681 else
682 return FilteredInstructions.size() + 1;
683}
684
685//////////////////////////////////
686// //
687// Filterchooser Implementation //
688// //
689//////////////////////////////////
690
Jim Grosbachecaef492012-08-14 19:06:05 +0000691// Emit the decoder state machine table.
692void FixedLenDecoderEmitter::emitTable(formatted_raw_ostream &OS,
693 DecoderTable &Table,
694 unsigned Indentation,
695 unsigned BitWidth,
696 StringRef Namespace) const {
697 OS.indent(Indentation) << "static const uint8_t DecoderTable" << Namespace
698 << BitWidth << "[] = {\n";
Owen Anderson4e818902011-02-18 21:51:29 +0000699
Jim Grosbachecaef492012-08-14 19:06:05 +0000700 Indentation += 2;
Owen Anderson4e818902011-02-18 21:51:29 +0000701
Jim Grosbachecaef492012-08-14 19:06:05 +0000702 // FIXME: We may be able to use the NumToSkip values to recover
703 // appropriate indentation levels.
704 DecoderTable::const_iterator I = Table.begin();
705 DecoderTable::const_iterator E = Table.end();
706 while (I != E) {
707 assert (I < E && "incomplete decode table entry!");
Owen Anderson4e818902011-02-18 21:51:29 +0000708
Jim Grosbachecaef492012-08-14 19:06:05 +0000709 uint64_t Pos = I - Table.begin();
710 OS << "/* " << Pos << " */";
711 OS.PadToColumn(12);
Owen Anderson4e818902011-02-18 21:51:29 +0000712
Jim Grosbachecaef492012-08-14 19:06:05 +0000713 switch (*I) {
714 default:
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000715 PrintFatalError("invalid decode table opcode");
Jim Grosbachecaef492012-08-14 19:06:05 +0000716 case MCD::OPC_ExtractField: {
717 ++I;
718 unsigned Start = *I++;
719 unsigned Len = *I++;
720 OS.indent(Indentation) << "MCD::OPC_ExtractField, " << Start << ", "
721 << Len << ", // Inst{";
722 if (Len > 1)
723 OS << (Start + Len - 1) << "-";
724 OS << Start << "} ...\n";
725 break;
726 }
727 case MCD::OPC_FilterValue: {
728 ++I;
729 OS.indent(Indentation) << "MCD::OPC_FilterValue, ";
730 // The filter value is ULEB128 encoded.
731 while (*I >= 128)
Craig Topper429093a2016-01-31 01:55:15 +0000732 OS << (unsigned)*I++ << ", ";
733 OS << (unsigned)*I++ << ", ";
Jim Grosbachecaef492012-08-14 19:06:05 +0000734
735 // 16-bit numtoskip value.
736 uint8_t Byte = *I++;
737 uint32_t NumToSkip = Byte;
Craig Topper429093a2016-01-31 01:55:15 +0000738 OS << (unsigned)Byte << ", ";
Jim Grosbachecaef492012-08-14 19:06:05 +0000739 Byte = *I++;
Craig Topper429093a2016-01-31 01:55:15 +0000740 OS << (unsigned)Byte << ", ";
Jim Grosbachecaef492012-08-14 19:06:05 +0000741 NumToSkip |= Byte << 8;
742 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
743 break;
744 }
745 case MCD::OPC_CheckField: {
746 ++I;
747 unsigned Start = *I++;
748 unsigned Len = *I++;
749 OS.indent(Indentation) << "MCD::OPC_CheckField, " << Start << ", "
750 << Len << ", ";// << Val << ", " << NumToSkip << ",\n";
751 // ULEB128 encoded field value.
752 for (; *I >= 128; ++I)
Craig Topper429093a2016-01-31 01:55:15 +0000753 OS << (unsigned)*I << ", ";
754 OS << (unsigned)*I++ << ", ";
Jim Grosbachecaef492012-08-14 19:06:05 +0000755 // 16-bit numtoskip value.
756 uint8_t Byte = *I++;
757 uint32_t NumToSkip = Byte;
Craig Topper429093a2016-01-31 01:55:15 +0000758 OS << (unsigned)Byte << ", ";
Jim Grosbachecaef492012-08-14 19:06:05 +0000759 Byte = *I++;
Craig Topper429093a2016-01-31 01:55:15 +0000760 OS << (unsigned)Byte << ", ";
Jim Grosbachecaef492012-08-14 19:06:05 +0000761 NumToSkip |= Byte << 8;
762 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
763 break;
764 }
765 case MCD::OPC_CheckPredicate: {
766 ++I;
767 OS.indent(Indentation) << "MCD::OPC_CheckPredicate, ";
768 for (; *I >= 128; ++I)
Craig Topper429093a2016-01-31 01:55:15 +0000769 OS << (unsigned)*I << ", ";
770 OS << (unsigned)*I++ << ", ";
Jim Grosbachecaef492012-08-14 19:06:05 +0000771
772 // 16-bit numtoskip value.
773 uint8_t Byte = *I++;
774 uint32_t NumToSkip = Byte;
Craig Topper429093a2016-01-31 01:55:15 +0000775 OS << (unsigned)Byte << ", ";
Jim Grosbachecaef492012-08-14 19:06:05 +0000776 Byte = *I++;
Craig Topper429093a2016-01-31 01:55:15 +0000777 OS << (unsigned)Byte << ", ";
Jim Grosbachecaef492012-08-14 19:06:05 +0000778 NumToSkip |= Byte << 8;
779 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
780 break;
781 }
Petr Pavlu182b0572015-07-15 08:04:27 +0000782 case MCD::OPC_Decode:
783 case MCD::OPC_TryDecode: {
784 bool IsTry = *I == MCD::OPC_TryDecode;
Jim Grosbachecaef492012-08-14 19:06:05 +0000785 ++I;
786 // Extract the ULEB128 encoded Opcode to a buffer.
787 uint8_t Buffer[8], *p = Buffer;
788 while ((*p++ = *I++) >= 128)
789 assert((p - Buffer) <= (ptrdiff_t)sizeof(Buffer)
790 && "ULEB128 value too large!");
791 // Decode the Opcode value.
792 unsigned Opc = decodeULEB128(Buffer);
Petr Pavlu182b0572015-07-15 08:04:27 +0000793 OS.indent(Indentation) << "MCD::OPC_" << (IsTry ? "Try" : "")
794 << "Decode, ";
Jim Grosbachecaef492012-08-14 19:06:05 +0000795 for (p = Buffer; *p >= 128; ++p)
Craig Topper429093a2016-01-31 01:55:15 +0000796 OS << (unsigned)*p << ", ";
797 OS << (unsigned)*p << ", ";
Jim Grosbachecaef492012-08-14 19:06:05 +0000798
799 // Decoder index.
800 for (; *I >= 128; ++I)
Craig Topper429093a2016-01-31 01:55:15 +0000801 OS << (unsigned)*I << ", ";
802 OS << (unsigned)*I++ << ", ";
Jim Grosbachecaef492012-08-14 19:06:05 +0000803
Petr Pavlu182b0572015-07-15 08:04:27 +0000804 if (!IsTry) {
805 OS << "// Opcode: "
Craig Topperf9265322016-01-17 20:38:14 +0000806 << NumberedInstructions[Opc]->TheDef->getName() << "\n";
Petr Pavlu182b0572015-07-15 08:04:27 +0000807 break;
808 }
809
810 // Fallthrough for OPC_TryDecode.
811
812 // 16-bit numtoskip value.
813 uint8_t Byte = *I++;
814 uint32_t NumToSkip = Byte;
Craig Topper429093a2016-01-31 01:55:15 +0000815 OS << (unsigned)Byte << ", ";
Petr Pavlu182b0572015-07-15 08:04:27 +0000816 Byte = *I++;
Craig Topper429093a2016-01-31 01:55:15 +0000817 OS << (unsigned)Byte << ", ";
Petr Pavlu182b0572015-07-15 08:04:27 +0000818 NumToSkip |= Byte << 8;
819
Jim Grosbachecaef492012-08-14 19:06:05 +0000820 OS << "// Opcode: "
Craig Topperf9265322016-01-17 20:38:14 +0000821 << NumberedInstructions[Opc]->TheDef->getName()
Petr Pavlu182b0572015-07-15 08:04:27 +0000822 << ", skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
Jim Grosbachecaef492012-08-14 19:06:05 +0000823 break;
824 }
825 case MCD::OPC_SoftFail: {
826 ++I;
827 OS.indent(Indentation) << "MCD::OPC_SoftFail";
828 // Positive mask
829 uint64_t Value = 0;
830 unsigned Shift = 0;
831 do {
Craig Topper429093a2016-01-31 01:55:15 +0000832 OS << ", " << (unsigned)*I;
Jim Grosbachecaef492012-08-14 19:06:05 +0000833 Value += (*I & 0x7f) << Shift;
834 Shift += 7;
835 } while (*I++ >= 128);
Craig Topper429093a2016-01-31 01:55:15 +0000836 if (Value > 127) {
837 OS << " /* 0x";
838 OS.write_hex(Value);
839 OS << " */";
840 }
Jim Grosbachecaef492012-08-14 19:06:05 +0000841 // Negative mask
842 Value = 0;
843 Shift = 0;
844 do {
Craig Topper429093a2016-01-31 01:55:15 +0000845 OS << ", " << (unsigned)*I;
Jim Grosbachecaef492012-08-14 19:06:05 +0000846 Value += (*I & 0x7f) << Shift;
847 Shift += 7;
848 } while (*I++ >= 128);
Craig Topper429093a2016-01-31 01:55:15 +0000849 if (Value > 127) {
850 OS << " /* 0x";
851 OS.write_hex(Value);
852 OS << " */";
853 }
Jim Grosbachecaef492012-08-14 19:06:05 +0000854 OS << ",\n";
855 break;
856 }
857 case MCD::OPC_Fail: {
858 ++I;
859 OS.indent(Indentation) << "MCD::OPC_Fail,\n";
860 break;
861 }
862 }
863 }
864 OS.indent(Indentation) << "0\n";
865
866 Indentation -= 2;
867
868 OS.indent(Indentation) << "};\n\n";
869}
870
871void FixedLenDecoderEmitter::
872emitPredicateFunction(formatted_raw_ostream &OS, PredicateSet &Predicates,
873 unsigned Indentation) const {
874 // The predicate function is just a big switch statement based on the
875 // input predicate index.
876 OS.indent(Indentation) << "static bool checkDecoderPredicate(unsigned Idx, "
Michael Kupersteindb0712f2015-05-26 10:47:10 +0000877 << "const FeatureBitset& Bits) {\n";
Jim Grosbachecaef492012-08-14 19:06:05 +0000878 Indentation += 2;
Aaron Ballmane59e3582013-07-15 16:53:32 +0000879 if (!Predicates.empty()) {
880 OS.indent(Indentation) << "switch (Idx) {\n";
881 OS.indent(Indentation) << "default: llvm_unreachable(\"Invalid index!\");\n";
882 unsigned Index = 0;
Craig Topper1f7604d2014-12-13 05:12:19 +0000883 for (const auto &Predicate : Predicates) {
884 OS.indent(Indentation) << "case " << Index++ << ":\n";
885 OS.indent(Indentation+2) << "return (" << Predicate << ");\n";
Aaron Ballmane59e3582013-07-15 16:53:32 +0000886 }
887 OS.indent(Indentation) << "}\n";
888 } else {
889 // No case statement to emit
890 OS.indent(Indentation) << "llvm_unreachable(\"Invalid index!\");\n";
Jim Grosbachecaef492012-08-14 19:06:05 +0000891 }
Jim Grosbachecaef492012-08-14 19:06:05 +0000892 Indentation -= 2;
893 OS.indent(Indentation) << "}\n\n";
894}
895
896void FixedLenDecoderEmitter::
897emitDecoderFunction(formatted_raw_ostream &OS, DecoderSet &Decoders,
898 unsigned Indentation) const {
899 // The decoder function is just a big switch statement based on the
900 // input decoder index.
901 OS.indent(Indentation) << "template<typename InsnType>\n";
902 OS.indent(Indentation) << "static DecodeStatus decodeToMCInst(DecodeStatus S,"
903 << " unsigned Idx, InsnType insn, MCInst &MI,\n";
904 OS.indent(Indentation) << " uint64_t "
Petr Pavlu182b0572015-07-15 08:04:27 +0000905 << "Address, const void *Decoder, bool &DecodeComplete) {\n";
Jim Grosbachecaef492012-08-14 19:06:05 +0000906 Indentation += 2;
Petr Pavlu182b0572015-07-15 08:04:27 +0000907 OS.indent(Indentation) << "DecodeComplete = true;\n";
Jim Grosbachecaef492012-08-14 19:06:05 +0000908 OS.indent(Indentation) << "InsnType tmp;\n";
909 OS.indent(Indentation) << "switch (Idx) {\n";
910 OS.indent(Indentation) << "default: llvm_unreachable(\"Invalid index!\");\n";
911 unsigned Index = 0;
Craig Topper1f7604d2014-12-13 05:12:19 +0000912 for (const auto &Decoder : Decoders) {
913 OS.indent(Indentation) << "case " << Index++ << ":\n";
914 OS << Decoder;
Jim Grosbachecaef492012-08-14 19:06:05 +0000915 OS.indent(Indentation+2) << "return S;\n";
916 }
917 OS.indent(Indentation) << "}\n";
918 Indentation -= 2;
919 OS.indent(Indentation) << "}\n\n";
Owen Anderson4e818902011-02-18 21:51:29 +0000920}
921
922// Populates the field of the insn given the start position and the number of
923// consecutive bits to scan for.
924//
925// Returns false if and on the first uninitialized bit value encountered.
926// Returns true, otherwise.
927bool FilterChooser::fieldFromInsn(uint64_t &Field, insn_t &Insn,
Craig Topper48c112b2012-03-16 05:58:09 +0000928 unsigned StartBit, unsigned NumBits) const {
Owen Anderson4e818902011-02-18 21:51:29 +0000929 Field = 0;
930
931 for (unsigned i = 0; i < NumBits; ++i) {
932 if (Insn[StartBit + i] == BIT_UNSET)
933 return false;
934
935 if (Insn[StartBit + i] == BIT_TRUE)
936 Field = Field | (1ULL << i);
937 }
938
939 return true;
940}
941
942/// dumpFilterArray - dumpFilterArray prints out debugging info for the given
943/// filter array as a series of chars.
944void FilterChooser::dumpFilterArray(raw_ostream &o,
Craig Topper48c112b2012-03-16 05:58:09 +0000945 const std::vector<bit_value_t> &filter) const {
Craig Topper29688ab2012-08-17 05:42:16 +0000946 for (unsigned bitIndex = BitWidth; bitIndex > 0; bitIndex--) {
Owen Anderson4e818902011-02-18 21:51:29 +0000947 switch (filter[bitIndex - 1]) {
948 case BIT_UNFILTERED:
949 o << ".";
950 break;
951 case BIT_UNSET:
952 o << "_";
953 break;
954 case BIT_TRUE:
955 o << "1";
956 break;
957 case BIT_FALSE:
958 o << "0";
959 break;
960 }
961 }
962}
963
964/// dumpStack - dumpStack traverses the filter chooser chain and calls
965/// dumpFilterArray on each filter chooser up to the top level one.
Craig Topper48c112b2012-03-16 05:58:09 +0000966void FilterChooser::dumpStack(raw_ostream &o, const char *prefix) const {
967 const FilterChooser *current = this;
Owen Anderson4e818902011-02-18 21:51:29 +0000968
969 while (current) {
970 o << prefix;
971 dumpFilterArray(o, current->FilterBitValues);
972 o << '\n';
973 current = current->Parent;
974 }
975}
976
Owen Anderson4e818902011-02-18 21:51:29 +0000977// Calculates the island(s) needed to decode the instruction.
978// This returns a list of undecoded bits of an instructions, for example,
979// Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
980// decoded bits in order to verify that the instruction matches the Opcode.
981unsigned FilterChooser::getIslands(std::vector<unsigned> &StartBits,
Craig Topper82d0d5f2012-03-16 01:19:24 +0000982 std::vector<unsigned> &EndBits,
983 std::vector<uint64_t> &FieldVals,
Craig Topper48c112b2012-03-16 05:58:09 +0000984 const insn_t &Insn) const {
Owen Anderson4e818902011-02-18 21:51:29 +0000985 unsigned Num, BitNo;
986 Num = BitNo = 0;
987
988 uint64_t FieldVal = 0;
989
990 // 0: Init
991 // 1: Water (the bit value does not affect decoding)
992 // 2: Island (well-known bit value needed for decoding)
993 int State = 0;
994 int Val = -1;
995
Owen Andersonc78e03c2011-07-19 21:06:00 +0000996 for (unsigned i = 0; i < BitWidth; ++i) {
Owen Anderson4e818902011-02-18 21:51:29 +0000997 Val = Value(Insn[i]);
998 bool Filtered = PositionFiltered(i);
999 switch (State) {
Craig Topperc4965bc2012-02-05 07:21:30 +00001000 default: llvm_unreachable("Unreachable code!");
Owen Anderson4e818902011-02-18 21:51:29 +00001001 case 0:
1002 case 1:
1003 if (Filtered || Val == -1)
1004 State = 1; // Still in Water
1005 else {
1006 State = 2; // Into the Island
1007 BitNo = 0;
1008 StartBits.push_back(i);
1009 FieldVal = Val;
1010 }
1011 break;
1012 case 2:
1013 if (Filtered || Val == -1) {
1014 State = 1; // Into the Water
1015 EndBits.push_back(i - 1);
1016 FieldVals.push_back(FieldVal);
1017 ++Num;
1018 } else {
1019 State = 2; // Still in Island
1020 ++BitNo;
1021 FieldVal = FieldVal | Val << BitNo;
1022 }
1023 break;
1024 }
1025 }
1026 // If we are still in Island after the loop, do some housekeeping.
1027 if (State == 2) {
Owen Andersonc78e03c2011-07-19 21:06:00 +00001028 EndBits.push_back(BitWidth - 1);
Owen Anderson4e818902011-02-18 21:51:29 +00001029 FieldVals.push_back(FieldVal);
1030 ++Num;
1031 }
1032
1033 assert(StartBits.size() == Num && EndBits.size() == Num &&
1034 FieldVals.size() == Num);
1035 return Num;
1036}
1037
Owen Andersone3591652011-07-28 21:54:31 +00001038void FilterChooser::emitBinaryParser(raw_ostream &o, unsigned &Indentation,
Petr Pavlu182b0572015-07-15 08:04:27 +00001039 const OperandInfo &OpInfo,
1040 bool &OpHasCompleteDecoder) const {
Craig Topper48c112b2012-03-16 05:58:09 +00001041 const std::string &Decoder = OpInfo.Decoder;
Owen Andersone3591652011-07-28 21:54:31 +00001042
Craig Topper5546f8c2014-09-27 05:26:42 +00001043 if (OpInfo.numFields() != 1)
Craig Topperebc3aa22012-08-17 05:16:15 +00001044 o.indent(Indentation) << "tmp = 0;\n";
Craig Topper5546f8c2014-09-27 05:26:42 +00001045
1046 for (const EncodingField &EF : OpInfo) {
1047 o.indent(Indentation) << "tmp ";
1048 if (OpInfo.numFields() != 1) o << '|';
1049 o << "= fieldFromInstruction"
1050 << "(insn, " << EF.Base << ", " << EF.Width << ')';
1051 if (OpInfo.numFields() != 1 || EF.Offset != 0)
1052 o << " << " << EF.Offset;
1053 o << ";\n";
Owen Andersone3591652011-07-28 21:54:31 +00001054 }
1055
Petr Pavlu182b0572015-07-15 08:04:27 +00001056 if (Decoder != "") {
1057 OpHasCompleteDecoder = OpInfo.HasCompleteDecoder;
Craig Topperebc3aa22012-08-17 05:16:15 +00001058 o.indent(Indentation) << Emitter->GuardPrefix << Decoder
Petr Pavlu182b0572015-07-15 08:04:27 +00001059 << "(MI, tmp, Address, Decoder)"
1060 << Emitter->GuardPostfix
1061 << " { " << (OpHasCompleteDecoder ? "" : "DecodeComplete = false; ")
1062 << "return MCDisassembler::Fail; }\n";
1063 } else {
1064 OpHasCompleteDecoder = true;
Jim Grosbache9119e42015-05-13 18:37:00 +00001065 o.indent(Indentation) << "MI.addOperand(MCOperand::createImm(tmp));\n";
Petr Pavlu182b0572015-07-15 08:04:27 +00001066 }
Owen Andersone3591652011-07-28 21:54:31 +00001067}
1068
Jim Grosbachecaef492012-08-14 19:06:05 +00001069void FilterChooser::emitDecoder(raw_ostream &OS, unsigned Indentation,
Petr Pavlu182b0572015-07-15 08:04:27 +00001070 unsigned Opc, bool &HasCompleteDecoder) const {
1071 HasCompleteDecoder = true;
1072
Craig Topper1f7604d2014-12-13 05:12:19 +00001073 for (const auto &Op : Operands.find(Opc)->second) {
Jim Grosbachecaef492012-08-14 19:06:05 +00001074 // If a custom instruction decoder was specified, use that.
Craig Topper1f7604d2014-12-13 05:12:19 +00001075 if (Op.numFields() == 0 && Op.Decoder.size()) {
Petr Pavlu182b0572015-07-15 08:04:27 +00001076 HasCompleteDecoder = Op.HasCompleteDecoder;
Craig Topper1f7604d2014-12-13 05:12:19 +00001077 OS.indent(Indentation) << Emitter->GuardPrefix << Op.Decoder
Jim Grosbachecaef492012-08-14 19:06:05 +00001078 << "(MI, insn, Address, Decoder)"
Petr Pavlu182b0572015-07-15 08:04:27 +00001079 << Emitter->GuardPostfix
1080 << " { " << (HasCompleteDecoder ? "" : "DecodeComplete = false; ")
1081 << "return MCDisassembler::Fail; }\n";
Jim Grosbachecaef492012-08-14 19:06:05 +00001082 break;
1083 }
1084
Petr Pavlu182b0572015-07-15 08:04:27 +00001085 bool OpHasCompleteDecoder;
1086 emitBinaryParser(OS, Indentation, Op, OpHasCompleteDecoder);
1087 if (!OpHasCompleteDecoder)
1088 HasCompleteDecoder = false;
Jim Grosbachecaef492012-08-14 19:06:05 +00001089 }
1090}
1091
1092unsigned FilterChooser::getDecoderIndex(DecoderSet &Decoders,
Petr Pavlu182b0572015-07-15 08:04:27 +00001093 unsigned Opc,
1094 bool &HasCompleteDecoder) const {
Jim Grosbachecaef492012-08-14 19:06:05 +00001095 // Build up the predicate string.
1096 SmallString<256> Decoder;
1097 // FIXME: emitDecoder() function can take a buffer directly rather than
1098 // a stream.
1099 raw_svector_ostream S(Decoder);
Craig Topperebc3aa22012-08-17 05:16:15 +00001100 unsigned I = 4;
Petr Pavlu182b0572015-07-15 08:04:27 +00001101 emitDecoder(S, I, Opc, HasCompleteDecoder);
Jim Grosbachecaef492012-08-14 19:06:05 +00001102
1103 // Using the full decoder string as the key value here is a bit
1104 // heavyweight, but is effective. If the string comparisons become a
1105 // performance concern, we can implement a mangling of the predicate
Nick Lewycky06b0ea22015-08-18 22:41:58 +00001106 // data easily enough with a map back to the actual string. That's
Jim Grosbachecaef492012-08-14 19:06:05 +00001107 // overkill for now, though.
1108
1109 // Make sure the predicate is in the table.
Justin Lebar5e83dfe2016-10-21 21:45:01 +00001110 Decoders.insert(CachedHashString(Decoder));
Jim Grosbachecaef492012-08-14 19:06:05 +00001111 // Now figure out the index for when we write out the table.
David Majnemer42531262016-08-12 03:55:06 +00001112 DecoderSet::const_iterator P = find(Decoders, Decoder.str());
Jim Grosbachecaef492012-08-14 19:06:05 +00001113 return (unsigned)(P - Decoders.begin());
1114}
1115
James Molloy8067df92011-09-07 19:42:28 +00001116static void emitSinglePredicateMatch(raw_ostream &o, StringRef str,
Craig Topper48c112b2012-03-16 05:58:09 +00001117 const std::string &PredicateNamespace) {
Andrew Trick43674ad2011-09-08 05:25:49 +00001118 if (str[0] == '!')
Michael Kupersteindb0712f2015-05-26 10:47:10 +00001119 o << "!Bits[" << PredicateNamespace << "::"
1120 << str.slice(1,str.size()) << "]";
James Molloy8067df92011-09-07 19:42:28 +00001121 else
Michael Kupersteindb0712f2015-05-26 10:47:10 +00001122 o << "Bits[" << PredicateNamespace << "::" << str << "]";
James Molloy8067df92011-09-07 19:42:28 +00001123}
1124
1125bool FilterChooser::emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
Craig Topper48c112b2012-03-16 05:58:09 +00001126 unsigned Opc) const {
Jim Grosbach3f4b2392012-02-29 22:07:56 +00001127 ListInit *Predicates =
1128 AllInstructions[Opc]->TheDef->getValueAsListInit("Predicates");
Toma Tabacu3d5ce492015-04-07 12:10:11 +00001129 bool IsFirstEmission = true;
Craig Topper664f6a02015-06-02 04:15:57 +00001130 for (unsigned i = 0; i < Predicates->size(); ++i) {
James Molloy8067df92011-09-07 19:42:28 +00001131 Record *Pred = Predicates->getElementAsRecord(i);
1132 if (!Pred->getValue("AssemblerMatcherPredicate"))
1133 continue;
1134
1135 std::string P = Pred->getValueAsString("AssemblerCondString");
1136
1137 if (!P.length())
1138 continue;
1139
Toma Tabacu3d5ce492015-04-07 12:10:11 +00001140 if (!IsFirstEmission)
James Molloy8067df92011-09-07 19:42:28 +00001141 o << " && ";
1142
1143 StringRef SR(P);
1144 std::pair<StringRef, StringRef> pairs = SR.split(',');
1145 while (pairs.second.size()) {
1146 emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
1147 o << " && ";
1148 pairs = pairs.second.split(',');
1149 }
1150 emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
Toma Tabacu3d5ce492015-04-07 12:10:11 +00001151 IsFirstEmission = false;
James Molloy8067df92011-09-07 19:42:28 +00001152 }
Craig Topper664f6a02015-06-02 04:15:57 +00001153 return !Predicates->empty();
Andrew Trick61abca62011-09-08 05:23:14 +00001154}
James Molloy8067df92011-09-07 19:42:28 +00001155
Jim Grosbachecaef492012-08-14 19:06:05 +00001156bool FilterChooser::doesOpcodeNeedPredicate(unsigned Opc) const {
1157 ListInit *Predicates =
1158 AllInstructions[Opc]->TheDef->getValueAsListInit("Predicates");
Craig Topper664f6a02015-06-02 04:15:57 +00001159 for (unsigned i = 0; i < Predicates->size(); ++i) {
Jim Grosbachecaef492012-08-14 19:06:05 +00001160 Record *Pred = Predicates->getElementAsRecord(i);
1161 if (!Pred->getValue("AssemblerMatcherPredicate"))
1162 continue;
1163
1164 std::string P = Pred->getValueAsString("AssemblerCondString");
1165
1166 if (!P.length())
1167 continue;
1168
1169 return true;
1170 }
1171 return false;
1172}
1173
1174unsigned FilterChooser::getPredicateIndex(DecoderTableInfo &TableInfo,
1175 StringRef Predicate) const {
1176 // Using the full predicate string as the key value here is a bit
1177 // heavyweight, but is effective. If the string comparisons become a
1178 // performance concern, we can implement a mangling of the predicate
Nick Lewycky06b0ea22015-08-18 22:41:58 +00001179 // data easily enough with a map back to the actual string. That's
Jim Grosbachecaef492012-08-14 19:06:05 +00001180 // overkill for now, though.
1181
1182 // Make sure the predicate is in the table.
Justin Lebar5e83dfe2016-10-21 21:45:01 +00001183 TableInfo.Predicates.insert(CachedHashString(Predicate));
Jim Grosbachecaef492012-08-14 19:06:05 +00001184 // Now figure out the index for when we write out the table.
Justin Lebar5e83dfe2016-10-21 21:45:01 +00001185 PredicateSet::const_iterator P = find(TableInfo.Predicates, Predicate);
Jim Grosbachecaef492012-08-14 19:06:05 +00001186 return (unsigned)(P - TableInfo.Predicates.begin());
1187}
1188
1189void FilterChooser::emitPredicateTableEntry(DecoderTableInfo &TableInfo,
1190 unsigned Opc) const {
1191 if (!doesOpcodeNeedPredicate(Opc))
1192 return;
1193
1194 // Build up the predicate string.
1195 SmallString<256> Predicate;
1196 // FIXME: emitPredicateMatch() functions can take a buffer directly rather
1197 // than a stream.
1198 raw_svector_ostream PS(Predicate);
1199 unsigned I = 0;
1200 emitPredicateMatch(PS, I, Opc);
1201
1202 // Figure out the index into the predicate table for the predicate just
1203 // computed.
1204 unsigned PIdx = getPredicateIndex(TableInfo, PS.str());
1205 SmallString<16> PBytes;
1206 raw_svector_ostream S(PBytes);
1207 encodeULEB128(PIdx, S);
Jim Grosbachecaef492012-08-14 19:06:05 +00001208
1209 TableInfo.Table.push_back(MCD::OPC_CheckPredicate);
1210 // Predicate index
Craig Topper29688ab2012-08-17 05:42:16 +00001211 for (unsigned i = 0, e = PBytes.size(); i != e; ++i)
Jim Grosbachecaef492012-08-14 19:06:05 +00001212 TableInfo.Table.push_back(PBytes[i]);
1213 // Push location for NumToSkip backpatching.
1214 TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
1215 TableInfo.Table.push_back(0);
1216 TableInfo.Table.push_back(0);
1217}
1218
1219void FilterChooser::emitSoftFailTableEntry(DecoderTableInfo &TableInfo,
1220 unsigned Opc) const {
Jim Grosbach3f4b2392012-02-29 22:07:56 +00001221 BitsInit *SFBits =
1222 AllInstructions[Opc]->TheDef->getValueAsBitsInit("SoftFail");
James Molloyd9ba4fd2012-02-09 10:56:31 +00001223 if (!SFBits) return;
1224 BitsInit *InstBits = AllInstructions[Opc]->TheDef->getValueAsBitsInit("Inst");
1225
1226 APInt PositiveMask(BitWidth, 0ULL);
1227 APInt NegativeMask(BitWidth, 0ULL);
1228 for (unsigned i = 0; i < BitWidth; ++i) {
1229 bit_value_t B = bitFromBits(*SFBits, i);
1230 bit_value_t IB = bitFromBits(*InstBits, i);
1231
1232 if (B != BIT_TRUE) continue;
1233
1234 switch (IB) {
1235 case BIT_FALSE:
1236 // The bit is meant to be false, so emit a check to see if it is true.
1237 PositiveMask.setBit(i);
1238 break;
1239 case BIT_TRUE:
1240 // The bit is meant to be true, so emit a check to see if it is false.
1241 NegativeMask.setBit(i);
1242 break;
1243 default:
1244 // The bit is not set; this must be an error!
1245 StringRef Name = AllInstructions[Opc]->TheDef->getName();
Jim Grosbachecaef492012-08-14 19:06:05 +00001246 errs() << "SoftFail Conflict: bit SoftFail{" << i << "} in " << Name
1247 << " is set but Inst{" << i << "} is unset!\n"
James Molloyd9ba4fd2012-02-09 10:56:31 +00001248 << " - You can only mark a bit as SoftFail if it is fully defined"
1249 << " (1/0 - not '?') in Inst\n";
Jim Grosbachecaef492012-08-14 19:06:05 +00001250 return;
James Molloyd9ba4fd2012-02-09 10:56:31 +00001251 }
1252 }
1253
1254 bool NeedPositiveMask = PositiveMask.getBoolValue();
1255 bool NeedNegativeMask = NegativeMask.getBoolValue();
1256
1257 if (!NeedPositiveMask && !NeedNegativeMask)
1258 return;
1259
Jim Grosbachecaef492012-08-14 19:06:05 +00001260 TableInfo.Table.push_back(MCD::OPC_SoftFail);
James Molloyd9ba4fd2012-02-09 10:56:31 +00001261
Jim Grosbachecaef492012-08-14 19:06:05 +00001262 SmallString<16> MaskBytes;
1263 raw_svector_ostream S(MaskBytes);
1264 if (NeedPositiveMask) {
1265 encodeULEB128(PositiveMask.getZExtValue(), S);
Craig Topper29688ab2012-08-17 05:42:16 +00001266 for (unsigned i = 0, e = MaskBytes.size(); i != e; ++i)
Jim Grosbachecaef492012-08-14 19:06:05 +00001267 TableInfo.Table.push_back(MaskBytes[i]);
1268 } else
1269 TableInfo.Table.push_back(0);
1270 if (NeedNegativeMask) {
1271 MaskBytes.clear();
Jim Grosbachecaef492012-08-14 19:06:05 +00001272 encodeULEB128(NegativeMask.getZExtValue(), S);
Craig Topper29688ab2012-08-17 05:42:16 +00001273 for (unsigned i = 0, e = MaskBytes.size(); i != e; ++i)
Jim Grosbachecaef492012-08-14 19:06:05 +00001274 TableInfo.Table.push_back(MaskBytes[i]);
1275 } else
1276 TableInfo.Table.push_back(0);
James Molloyd9ba4fd2012-02-09 10:56:31 +00001277}
1278
Jim Grosbachecaef492012-08-14 19:06:05 +00001279// Emits table entries to decode the singleton.
1280void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,
1281 unsigned Opc) const {
Owen Anderson4e818902011-02-18 21:51:29 +00001282 std::vector<unsigned> StartBits;
1283 std::vector<unsigned> EndBits;
1284 std::vector<uint64_t> FieldVals;
1285 insn_t Insn;
1286 insnWithID(Insn, Opc);
1287
1288 // Look for islands of undecoded bits of the singleton.
1289 getIslands(StartBits, EndBits, FieldVals, Insn);
1290
1291 unsigned Size = StartBits.size();
Owen Anderson4e818902011-02-18 21:51:29 +00001292
Jim Grosbachecaef492012-08-14 19:06:05 +00001293 // Emit the predicate table entry if one is needed.
1294 emitPredicateTableEntry(TableInfo, Opc);
Owen Anderson4e818902011-02-18 21:51:29 +00001295
Jim Grosbachecaef492012-08-14 19:06:05 +00001296 // Check any additional encoding fields needed.
Craig Topper29688ab2012-08-17 05:42:16 +00001297 for (unsigned I = Size; I != 0; --I) {
1298 unsigned NumBits = EndBits[I-1] - StartBits[I-1] + 1;
Jim Grosbachecaef492012-08-14 19:06:05 +00001299 TableInfo.Table.push_back(MCD::OPC_CheckField);
1300 TableInfo.Table.push_back(StartBits[I-1]);
1301 TableInfo.Table.push_back(NumBits);
1302 uint8_t Buffer[8], *p;
1303 encodeULEB128(FieldVals[I-1], Buffer);
1304 for (p = Buffer; *p >= 128 ; ++p)
1305 TableInfo.Table.push_back(*p);
1306 TableInfo.Table.push_back(*p);
1307 // Push location for NumToSkip backpatching.
1308 TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
1309 // The fixup is always 16-bits, so go ahead and allocate the space
1310 // in the table so all our relative position calculations work OK even
1311 // before we fully resolve the real value here.
1312 TableInfo.Table.push_back(0);
1313 TableInfo.Table.push_back(0);
Owen Anderson4e818902011-02-18 21:51:29 +00001314 }
Owen Anderson4e818902011-02-18 21:51:29 +00001315
Jim Grosbachecaef492012-08-14 19:06:05 +00001316 // Check for soft failure of the match.
1317 emitSoftFailTableEntry(TableInfo, Opc);
Owen Anderson4e818902011-02-18 21:51:29 +00001318
Petr Pavlu182b0572015-07-15 08:04:27 +00001319 bool HasCompleteDecoder;
1320 unsigned DIdx = getDecoderIndex(TableInfo.Decoders, Opc, HasCompleteDecoder);
1321
1322 // Produce OPC_Decode or OPC_TryDecode opcode based on the information
1323 // whether the instruction decoder is complete or not. If it is complete
1324 // then it handles all possible values of remaining variable/unfiltered bits
1325 // and for any value can determine if the bitpattern is a valid instruction
1326 // or not. This means OPC_Decode will be the final step in the decoding
1327 // process. If it is not complete, then the Fail return code from the
1328 // decoder method indicates that additional processing should be done to see
1329 // if there is any other instruction that also matches the bitpattern and
1330 // can decode it.
1331 TableInfo.Table.push_back(HasCompleteDecoder ? MCD::OPC_Decode :
1332 MCD::OPC_TryDecode);
Jim Grosbachecaef492012-08-14 19:06:05 +00001333 uint8_t Buffer[8], *p;
1334 encodeULEB128(Opc, Buffer);
1335 for (p = Buffer; *p >= 128 ; ++p)
1336 TableInfo.Table.push_back(*p);
1337 TableInfo.Table.push_back(*p);
1338
Jim Grosbachecaef492012-08-14 19:06:05 +00001339 SmallString<16> Bytes;
1340 raw_svector_ostream S(Bytes);
1341 encodeULEB128(DIdx, S);
Jim Grosbachecaef492012-08-14 19:06:05 +00001342
1343 // Decoder index
Craig Topper29688ab2012-08-17 05:42:16 +00001344 for (unsigned i = 0, e = Bytes.size(); i != e; ++i)
Jim Grosbachecaef492012-08-14 19:06:05 +00001345 TableInfo.Table.push_back(Bytes[i]);
Petr Pavlu182b0572015-07-15 08:04:27 +00001346
1347 if (!HasCompleteDecoder) {
1348 // Push location for NumToSkip backpatching.
1349 TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
1350 // Allocate the space for the fixup.
1351 TableInfo.Table.push_back(0);
1352 TableInfo.Table.push_back(0);
1353 }
Owen Anderson4e818902011-02-18 21:51:29 +00001354}
1355
Jim Grosbachecaef492012-08-14 19:06:05 +00001356// Emits table entries to decode the singleton, and then to decode the rest.
1357void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,
1358 const Filter &Best) const {
Owen Anderson4e818902011-02-18 21:51:29 +00001359 unsigned Opc = Best.getSingletonOpc();
1360
Jim Grosbachecaef492012-08-14 19:06:05 +00001361 // complex singletons need predicate checks from the first singleton
1362 // to refer forward to the variable filterchooser that follows.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001363 TableInfo.FixupStack.emplace_back();
Owen Anderson4e818902011-02-18 21:51:29 +00001364
Jim Grosbachecaef492012-08-14 19:06:05 +00001365 emitSingletonTableEntry(TableInfo, Opc);
Owen Anderson4e818902011-02-18 21:51:29 +00001366
Jim Grosbachecaef492012-08-14 19:06:05 +00001367 resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),
1368 TableInfo.Table.size());
1369 TableInfo.FixupStack.pop_back();
1370
1371 Best.getVariableFC().emitTableEntries(TableInfo);
Owen Anderson4e818902011-02-18 21:51:29 +00001372}
1373
Jim Grosbachecaef492012-08-14 19:06:05 +00001374
Owen Anderson4e818902011-02-18 21:51:29 +00001375// Assign a single filter and run with it. Top level API client can initialize
1376// with a single filter to start the filtering process.
Craig Topper48c112b2012-03-16 05:58:09 +00001377void FilterChooser::runSingleFilter(unsigned startBit, unsigned numBit,
1378 bool mixed) {
Owen Anderson4e818902011-02-18 21:51:29 +00001379 Filters.clear();
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001380 Filters.emplace_back(*this, startBit, numBit, true);
Owen Anderson4e818902011-02-18 21:51:29 +00001381 BestIndex = 0; // Sole Filter instance to choose from.
1382 bestFilter().recurse();
1383}
1384
1385// reportRegion is a helper function for filterProcessor to mark a region as
1386// eligible for use as a filter region.
1387void FilterChooser::reportRegion(bitAttr_t RA, unsigned StartBit,
Craig Topper82d0d5f2012-03-16 01:19:24 +00001388 unsigned BitIndex, bool AllowMixed) {
Owen Anderson4e818902011-02-18 21:51:29 +00001389 if (RA == ATTR_MIXED && AllowMixed)
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001390 Filters.emplace_back(*this, StartBit, BitIndex - StartBit, true);
Owen Anderson4e818902011-02-18 21:51:29 +00001391 else if (RA == ATTR_ALL_SET && !AllowMixed)
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001392 Filters.emplace_back(*this, StartBit, BitIndex - StartBit, false);
Owen Anderson4e818902011-02-18 21:51:29 +00001393}
1394
1395// FilterProcessor scans the well-known encoding bits of the instructions and
1396// builds up a list of candidate filters. It chooses the best filter and
1397// recursively descends down the decoding tree.
1398bool FilterChooser::filterProcessor(bool AllowMixed, bool Greedy) {
1399 Filters.clear();
1400 BestIndex = -1;
1401 unsigned numInstructions = Opcodes.size();
1402
1403 assert(numInstructions && "Filter created with no instructions");
1404
1405 // No further filtering is necessary.
1406 if (numInstructions == 1)
1407 return true;
1408
1409 // Heuristics. See also doFilter()'s "Heuristics" comment when num of
1410 // instructions is 3.
1411 if (AllowMixed && !Greedy) {
1412 assert(numInstructions == 3);
1413
1414 for (unsigned i = 0; i < Opcodes.size(); ++i) {
1415 std::vector<unsigned> StartBits;
1416 std::vector<unsigned> EndBits;
1417 std::vector<uint64_t> FieldVals;
1418 insn_t Insn;
1419
1420 insnWithID(Insn, Opcodes[i]);
1421
1422 // Look for islands of undecoded bits of any instruction.
1423 if (getIslands(StartBits, EndBits, FieldVals, Insn) > 0) {
1424 // Found an instruction with island(s). Now just assign a filter.
Craig Topper48c112b2012-03-16 05:58:09 +00001425 runSingleFilter(StartBits[0], EndBits[0] - StartBits[0] + 1, true);
Owen Anderson4e818902011-02-18 21:51:29 +00001426 return true;
1427 }
1428 }
1429 }
1430
Craig Topper29688ab2012-08-17 05:42:16 +00001431 unsigned BitIndex;
Owen Anderson4e818902011-02-18 21:51:29 +00001432
1433 // We maintain BIT_WIDTH copies of the bitAttrs automaton.
1434 // The automaton consumes the corresponding bit from each
1435 // instruction.
1436 //
1437 // Input symbols: 0, 1, and _ (unset).
1438 // States: NONE, FILTERED, ALL_SET, ALL_UNSET, and MIXED.
1439 // Initial state: NONE.
1440 //
1441 // (NONE) ------- [01] -> (ALL_SET)
1442 // (NONE) ------- _ ----> (ALL_UNSET)
1443 // (ALL_SET) ---- [01] -> (ALL_SET)
1444 // (ALL_SET) ---- _ ----> (MIXED)
1445 // (ALL_UNSET) -- [01] -> (MIXED)
1446 // (ALL_UNSET) -- _ ----> (ALL_UNSET)
1447 // (MIXED) ------ . ----> (MIXED)
1448 // (FILTERED)---- . ----> (FILTERED)
1449
Owen Andersonc78e03c2011-07-19 21:06:00 +00001450 std::vector<bitAttr_t> bitAttrs;
Owen Anderson4e818902011-02-18 21:51:29 +00001451
1452 // FILTERED bit positions provide no entropy and are not worthy of pursuing.
1453 // Filter::recurse() set either BIT_TRUE or BIT_FALSE for each position.
Owen Andersonc78e03c2011-07-19 21:06:00 +00001454 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex)
Owen Anderson4e818902011-02-18 21:51:29 +00001455 if (FilterBitValues[BitIndex] == BIT_TRUE ||
1456 FilterBitValues[BitIndex] == BIT_FALSE)
Owen Andersonc78e03c2011-07-19 21:06:00 +00001457 bitAttrs.push_back(ATTR_FILTERED);
Owen Anderson4e818902011-02-18 21:51:29 +00001458 else
Owen Andersonc78e03c2011-07-19 21:06:00 +00001459 bitAttrs.push_back(ATTR_NONE);
Owen Anderson4e818902011-02-18 21:51:29 +00001460
Craig Topper29688ab2012-08-17 05:42:16 +00001461 for (unsigned InsnIndex = 0; InsnIndex < numInstructions; ++InsnIndex) {
Owen Anderson4e818902011-02-18 21:51:29 +00001462 insn_t insn;
1463
1464 insnWithID(insn, Opcodes[InsnIndex]);
1465
Owen Andersonc78e03c2011-07-19 21:06:00 +00001466 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
Owen Anderson4e818902011-02-18 21:51:29 +00001467 switch (bitAttrs[BitIndex]) {
1468 case ATTR_NONE:
1469 if (insn[BitIndex] == BIT_UNSET)
1470 bitAttrs[BitIndex] = ATTR_ALL_UNSET;
1471 else
1472 bitAttrs[BitIndex] = ATTR_ALL_SET;
1473 break;
1474 case ATTR_ALL_SET:
1475 if (insn[BitIndex] == BIT_UNSET)
1476 bitAttrs[BitIndex] = ATTR_MIXED;
1477 break;
1478 case ATTR_ALL_UNSET:
1479 if (insn[BitIndex] != BIT_UNSET)
1480 bitAttrs[BitIndex] = ATTR_MIXED;
1481 break;
1482 case ATTR_MIXED:
1483 case ATTR_FILTERED:
1484 break;
1485 }
1486 }
1487 }
1488
1489 // The regionAttr automaton consumes the bitAttrs automatons' state,
1490 // lowest-to-highest.
1491 //
1492 // Input symbols: F(iltered), (all_)S(et), (all_)U(nset), M(ixed)
1493 // States: NONE, ALL_SET, MIXED
1494 // Initial state: NONE
1495 //
1496 // (NONE) ----- F --> (NONE)
1497 // (NONE) ----- S --> (ALL_SET) ; and set region start
1498 // (NONE) ----- U --> (NONE)
1499 // (NONE) ----- M --> (MIXED) ; and set region start
1500 // (ALL_SET) -- F --> (NONE) ; and report an ALL_SET region
1501 // (ALL_SET) -- S --> (ALL_SET)
1502 // (ALL_SET) -- U --> (NONE) ; and report an ALL_SET region
1503 // (ALL_SET) -- M --> (MIXED) ; and report an ALL_SET region
1504 // (MIXED) ---- F --> (NONE) ; and report a MIXED region
1505 // (MIXED) ---- S --> (ALL_SET) ; and report a MIXED region
1506 // (MIXED) ---- U --> (NONE) ; and report a MIXED region
1507 // (MIXED) ---- M --> (MIXED)
1508
1509 bitAttr_t RA = ATTR_NONE;
1510 unsigned StartBit = 0;
1511
Craig Topper29688ab2012-08-17 05:42:16 +00001512 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
Owen Anderson4e818902011-02-18 21:51:29 +00001513 bitAttr_t bitAttr = bitAttrs[BitIndex];
1514
1515 assert(bitAttr != ATTR_NONE && "Bit without attributes");
1516
1517 switch (RA) {
1518 case ATTR_NONE:
1519 switch (bitAttr) {
1520 case ATTR_FILTERED:
1521 break;
1522 case ATTR_ALL_SET:
1523 StartBit = BitIndex;
1524 RA = ATTR_ALL_SET;
1525 break;
1526 case ATTR_ALL_UNSET:
1527 break;
1528 case ATTR_MIXED:
1529 StartBit = BitIndex;
1530 RA = ATTR_MIXED;
1531 break;
1532 default:
Craig Topperc4965bc2012-02-05 07:21:30 +00001533 llvm_unreachable("Unexpected bitAttr!");
Owen Anderson4e818902011-02-18 21:51:29 +00001534 }
1535 break;
1536 case ATTR_ALL_SET:
1537 switch (bitAttr) {
1538 case ATTR_FILTERED:
1539 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1540 RA = ATTR_NONE;
1541 break;
1542 case ATTR_ALL_SET:
1543 break;
1544 case ATTR_ALL_UNSET:
1545 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1546 RA = ATTR_NONE;
1547 break;
1548 case ATTR_MIXED:
1549 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1550 StartBit = BitIndex;
1551 RA = ATTR_MIXED;
1552 break;
1553 default:
Craig Topperc4965bc2012-02-05 07:21:30 +00001554 llvm_unreachable("Unexpected bitAttr!");
Owen Anderson4e818902011-02-18 21:51:29 +00001555 }
1556 break;
1557 case ATTR_MIXED:
1558 switch (bitAttr) {
1559 case ATTR_FILTERED:
1560 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1561 StartBit = BitIndex;
1562 RA = ATTR_NONE;
1563 break;
1564 case ATTR_ALL_SET:
1565 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1566 StartBit = BitIndex;
1567 RA = ATTR_ALL_SET;
1568 break;
1569 case ATTR_ALL_UNSET:
1570 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1571 RA = ATTR_NONE;
1572 break;
1573 case ATTR_MIXED:
1574 break;
1575 default:
Craig Topperc4965bc2012-02-05 07:21:30 +00001576 llvm_unreachable("Unexpected bitAttr!");
Owen Anderson4e818902011-02-18 21:51:29 +00001577 }
1578 break;
1579 case ATTR_ALL_UNSET:
Craig Topperc4965bc2012-02-05 07:21:30 +00001580 llvm_unreachable("regionAttr state machine has no ATTR_UNSET state");
Owen Anderson4e818902011-02-18 21:51:29 +00001581 case ATTR_FILTERED:
Craig Topperc4965bc2012-02-05 07:21:30 +00001582 llvm_unreachable("regionAttr state machine has no ATTR_FILTERED state");
Owen Anderson4e818902011-02-18 21:51:29 +00001583 }
1584 }
1585
1586 // At the end, if we're still in ALL_SET or MIXED states, report a region
1587 switch (RA) {
1588 case ATTR_NONE:
1589 break;
1590 case ATTR_FILTERED:
1591 break;
1592 case ATTR_ALL_SET:
1593 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1594 break;
1595 case ATTR_ALL_UNSET:
1596 break;
1597 case ATTR_MIXED:
1598 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1599 break;
1600 }
1601
1602 // We have finished with the filter processings. Now it's time to choose
1603 // the best performing filter.
1604 BestIndex = 0;
1605 bool AllUseless = true;
1606 unsigned BestScore = 0;
1607
1608 for (unsigned i = 0, e = Filters.size(); i != e; ++i) {
1609 unsigned Usefulness = Filters[i].usefulness();
1610
1611 if (Usefulness)
1612 AllUseless = false;
1613
1614 if (Usefulness > BestScore) {
1615 BestIndex = i;
1616 BestScore = Usefulness;
1617 }
1618 }
1619
1620 if (!AllUseless)
1621 bestFilter().recurse();
1622
1623 return !AllUseless;
1624} // end of FilterChooser::filterProcessor(bool)
1625
1626// Decides on the best configuration of filter(s) to use in order to decode
1627// the instructions. A conflict of instructions may occur, in which case we
1628// dump the conflict set to the standard error.
1629void FilterChooser::doFilter() {
1630 unsigned Num = Opcodes.size();
1631 assert(Num && "FilterChooser created with no instructions");
1632
1633 // Try regions of consecutive known bit values first.
1634 if (filterProcessor(false))
1635 return;
1636
1637 // Then regions of mixed bits (both known and unitialized bit values allowed).
1638 if (filterProcessor(true))
1639 return;
1640
1641 // Heuristics to cope with conflict set {t2CMPrs, t2SUBSrr, t2SUBSrs} where
1642 // no single instruction for the maximum ATTR_MIXED region Inst{14-4} has a
1643 // well-known encoding pattern. In such case, we backtrack and scan for the
1644 // the very first consecutive ATTR_ALL_SET region and assign a filter to it.
1645 if (Num == 3 && filterProcessor(true, false))
1646 return;
1647
1648 // If we come to here, the instruction decoding has failed.
1649 // Set the BestIndex to -1 to indicate so.
1650 BestIndex = -1;
1651}
1652
Jim Grosbachecaef492012-08-14 19:06:05 +00001653// emitTableEntries - Emit state machine entries to decode our share of
1654// instructions.
1655void FilterChooser::emitTableEntries(DecoderTableInfo &TableInfo) const {
1656 if (Opcodes.size() == 1) {
Owen Anderson4e818902011-02-18 21:51:29 +00001657 // There is only one instruction in the set, which is great!
1658 // Call emitSingletonDecoder() to see whether there are any remaining
1659 // encodings bits.
Jim Grosbachecaef492012-08-14 19:06:05 +00001660 emitSingletonTableEntry(TableInfo, Opcodes[0]);
1661 return;
1662 }
Owen Anderson4e818902011-02-18 21:51:29 +00001663
1664 // Choose the best filter to do the decodings!
1665 if (BestIndex != -1) {
Craig Topper48c112b2012-03-16 05:58:09 +00001666 const Filter &Best = Filters[BestIndex];
Owen Anderson4e818902011-02-18 21:51:29 +00001667 if (Best.getNumFiltered() == 1)
Jim Grosbachecaef492012-08-14 19:06:05 +00001668 emitSingletonTableEntry(TableInfo, Best);
Owen Anderson4e818902011-02-18 21:51:29 +00001669 else
Jim Grosbachecaef492012-08-14 19:06:05 +00001670 Best.emitTableEntry(TableInfo);
1671 return;
Owen Anderson4e818902011-02-18 21:51:29 +00001672 }
1673
Jim Grosbachecaef492012-08-14 19:06:05 +00001674 // We don't know how to decode these instructions! Dump the
1675 // conflict set and bail.
Owen Anderson4e818902011-02-18 21:51:29 +00001676
1677 // Print out useful conflict information for postmortem analysis.
1678 errs() << "Decoding Conflict:\n";
1679
1680 dumpStack(errs(), "\t\t");
1681
Craig Topper82d0d5f2012-03-16 01:19:24 +00001682 for (unsigned i = 0; i < Opcodes.size(); ++i) {
Owen Anderson4e818902011-02-18 21:51:29 +00001683 const std::string &Name = nameWithID(Opcodes[i]);
1684
1685 errs() << '\t' << Name << " ";
1686 dumpBits(errs(),
1687 getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
1688 errs() << '\n';
1689 }
Owen Anderson4e818902011-02-18 21:51:29 +00001690}
1691
Matt Arsenault4cb438b2016-07-18 23:20:46 +00001692static std::string findOperandDecoderMethod(TypedInit *TI) {
1693 std::string Decoder;
1694
1695 RecordRecTy *Type = cast<RecordRecTy>(TI->getType());
1696 Record *TypeRecord = Type->getRecord();
1697
1698 RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod");
1699 StringInit *String = DecoderString ?
1700 dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
1701 if (String) {
1702 Decoder = String->getValue();
1703 if (!Decoder.empty())
1704 return Decoder;
1705 }
1706
1707 if (TypeRecord->isSubClassOf("RegisterOperand"))
1708 TypeRecord = TypeRecord->getValueAsDef("RegClass");
1709
1710 if (TypeRecord->isSubClassOf("RegisterClass")) {
1711 Decoder = "Decode" + TypeRecord->getName() + "RegisterClass";
1712 } else if (TypeRecord->isSubClassOf("PointerLikeRegClass")) {
1713 Decoder = "DecodePointerLikeRegClass" +
1714 utostr(TypeRecord->getValueAsInt("RegClassKind"));
1715 }
1716
1717 return Decoder;
1718}
1719
Hal Finkel71b2e202013-12-19 16:12:53 +00001720static bool populateInstruction(CodeGenTarget &Target,
1721 const CodeGenInstruction &CGI, unsigned Opc,
Craig Topper82d0d5f2012-03-16 01:19:24 +00001722 std::map<unsigned, std::vector<OperandInfo> > &Operands){
Owen Anderson4e818902011-02-18 21:51:29 +00001723 const Record &Def = *CGI.TheDef;
1724 // If all the bit positions are not specified; do not decode this instruction.
1725 // We are bound to fail! For proper disassembly, the well-known encoding bits
1726 // of the instruction must be fully specified.
Owen Anderson4e818902011-02-18 21:51:29 +00001727
David Greeneaf8ee2c2011-07-29 22:43:06 +00001728 BitsInit &Bits = getBitsField(Def, "Inst");
Jim Grosbachf3fd36e2011-07-06 21:33:38 +00001729 if (Bits.allInComplete()) return false;
1730
Owen Anderson4e818902011-02-18 21:51:29 +00001731 std::vector<OperandInfo> InsnOperands;
1732
1733 // If the instruction has specified a custom decoding hook, use that instead
1734 // of trying to auto-generate the decoder.
1735 std::string InstDecoder = Def.getValueAsString("DecoderMethod");
1736 if (InstDecoder != "") {
Petr Pavlu182b0572015-07-15 08:04:27 +00001737 bool HasCompleteInstDecoder = Def.getValueAsBit("hasCompleteDecoder");
1738 InsnOperands.push_back(OperandInfo(InstDecoder, HasCompleteInstDecoder));
Owen Anderson4e818902011-02-18 21:51:29 +00001739 Operands[Opc] = InsnOperands;
1740 return true;
1741 }
1742
1743 // Generate a description of the operand of the instruction that we know
1744 // how to decode automatically.
1745 // FIXME: We'll need to have a way to manually override this as needed.
1746
1747 // Gather the outputs/inputs of the instruction, so we can find their
1748 // positions in the encoding. This assumes for now that they appear in the
1749 // MCInst in the order that they're listed.
David Greeneaf8ee2c2011-07-29 22:43:06 +00001750 std::vector<std::pair<Init*, std::string> > InOutOperands;
1751 DagInit *Out = Def.getValueAsDag("OutOperandList");
1752 DagInit *In = Def.getValueAsDag("InOperandList");
Owen Anderson4e818902011-02-18 21:51:29 +00001753 for (unsigned i = 0; i < Out->getNumArgs(); ++i)
1754 InOutOperands.push_back(std::make_pair(Out->getArg(i), Out->getArgName(i)));
1755 for (unsigned i = 0; i < In->getNumArgs(); ++i)
1756 InOutOperands.push_back(std::make_pair(In->getArg(i), In->getArgName(i)));
1757
Owen Anderson53562d02011-07-28 23:56:20 +00001758 // Search for tied operands, so that we can correctly instantiate
1759 // operands that are not explicitly represented in the encoding.
Owen Andersoncb32ce22011-07-29 18:28:52 +00001760 std::map<std::string, std::string> TiedNames;
Owen Anderson53562d02011-07-28 23:56:20 +00001761 for (unsigned i = 0; i < CGI.Operands.size(); ++i) {
1762 int tiedTo = CGI.Operands[i].getTiedRegister();
Owen Andersoncb32ce22011-07-29 18:28:52 +00001763 if (tiedTo != -1) {
Hal Finkel71b2e202013-12-19 16:12:53 +00001764 std::pair<unsigned, unsigned> SO =
1765 CGI.Operands.getSubOperandNumber(tiedTo);
1766 TiedNames[InOutOperands[i].second] = InOutOperands[SO.first].second;
1767 TiedNames[InOutOperands[SO.first].second] = InOutOperands[i].second;
1768 }
1769 }
1770
1771 std::map<std::string, std::vector<OperandInfo> > NumberedInsnOperands;
1772 std::set<std::string> NumberedInsnOperandsNoTie;
1773 if (Target.getInstructionSet()->
1774 getValueAsBit("decodePositionallyEncodedOperands")) {
1775 const std::vector<RecordVal> &Vals = Def.getValues();
1776 unsigned NumberedOp = 0;
1777
Hal Finkel5457bd02014-03-13 07:57:54 +00001778 std::set<unsigned> NamedOpIndices;
1779 if (Target.getInstructionSet()->
1780 getValueAsBit("noNamedPositionallyEncodedOperands"))
1781 // Collect the set of operand indices that might correspond to named
1782 // operand, and skip these when assigning operands based on position.
1783 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1784 unsigned OpIdx;
1785 if (!CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx))
1786 continue;
1787
1788 NamedOpIndices.insert(OpIdx);
1789 }
1790
Hal Finkel71b2e202013-12-19 16:12:53 +00001791 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1792 // Ignore fixed fields in the record, we're looking for values like:
1793 // bits<5> RST = { ?, ?, ?, ?, ? };
1794 if (Vals[i].getPrefix() || Vals[i].getValue()->isComplete())
1795 continue;
1796
1797 // Determine if Vals[i] actually contributes to the Inst encoding.
1798 unsigned bi = 0;
1799 for (; bi < Bits.getNumBits(); ++bi) {
Craig Topper24064772014-04-15 07:20:03 +00001800 VarInit *Var = nullptr;
Hal Finkel71b2e202013-12-19 16:12:53 +00001801 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
1802 if (BI)
1803 Var = dyn_cast<VarInit>(BI->getBitVar());
1804 else
1805 Var = dyn_cast<VarInit>(Bits.getBit(bi));
1806
1807 if (Var && Var->getName() == Vals[i].getName())
1808 break;
1809 }
1810
1811 if (bi == Bits.getNumBits())
1812 continue;
1813
1814 // Skip variables that correspond to explicitly-named operands.
1815 unsigned OpIdx;
1816 if (CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx))
1817 continue;
1818
1819 // Get the bit range for this operand:
1820 unsigned bitStart = bi++, bitWidth = 1;
1821 for (; bi < Bits.getNumBits(); ++bi) {
Craig Topper24064772014-04-15 07:20:03 +00001822 VarInit *Var = nullptr;
Hal Finkel71b2e202013-12-19 16:12:53 +00001823 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
1824 if (BI)
1825 Var = dyn_cast<VarInit>(BI->getBitVar());
1826 else
1827 Var = dyn_cast<VarInit>(Bits.getBit(bi));
1828
1829 if (!Var)
1830 break;
1831
1832 if (Var->getName() != Vals[i].getName())
1833 break;
1834
1835 ++bitWidth;
1836 }
1837
1838 unsigned NumberOps = CGI.Operands.size();
1839 while (NumberedOp < NumberOps &&
Hal Finkel5457bd02014-03-13 07:57:54 +00001840 (CGI.Operands.isFlatOperandNotEmitted(NumberedOp) ||
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00001841 (!NamedOpIndices.empty() && NamedOpIndices.count(
Hal Finkel5457bd02014-03-13 07:57:54 +00001842 CGI.Operands.getSubOperandNumber(NumberedOp).first))))
Hal Finkel71b2e202013-12-19 16:12:53 +00001843 ++NumberedOp;
1844
1845 OpIdx = NumberedOp++;
1846
1847 // OpIdx now holds the ordered operand number of Vals[i].
1848 std::pair<unsigned, unsigned> SO =
1849 CGI.Operands.getSubOperandNumber(OpIdx);
1850 const std::string &Name = CGI.Operands[SO.first].Name;
1851
1852 DEBUG(dbgs() << "Numbered operand mapping for " << Def.getName() << ": " <<
1853 Name << "(" << SO.first << ", " << SO.second << ") => " <<
1854 Vals[i].getName() << "\n");
1855
1856 std::string Decoder = "";
1857 Record *TypeRecord = CGI.Operands[SO.first].Rec;
1858
1859 RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod");
1860 StringInit *String = DecoderString ?
Craig Topper24064772014-04-15 07:20:03 +00001861 dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
Hal Finkel71b2e202013-12-19 16:12:53 +00001862 if (String && String->getValue() != "")
1863 Decoder = String->getValue();
1864
1865 if (Decoder == "" &&
1866 CGI.Operands[SO.first].MIOperandInfo &&
1867 CGI.Operands[SO.first].MIOperandInfo->getNumArgs()) {
1868 Init *Arg = CGI.Operands[SO.first].MIOperandInfo->
1869 getArg(SO.second);
1870 if (TypedInit *TI = cast<TypedInit>(Arg)) {
1871 RecordRecTy *Type = cast<RecordRecTy>(TI->getType());
1872 TypeRecord = Type->getRecord();
1873 }
1874 }
1875
1876 bool isReg = false;
1877 if (TypeRecord->isSubClassOf("RegisterOperand"))
1878 TypeRecord = TypeRecord->getValueAsDef("RegClass");
1879 if (TypeRecord->isSubClassOf("RegisterClass")) {
1880 Decoder = "Decode" + TypeRecord->getName() + "RegisterClass";
1881 isReg = true;
1882 } else if (TypeRecord->isSubClassOf("PointerLikeRegClass")) {
1883 Decoder = "DecodePointerLikeRegClass" +
1884 utostr(TypeRecord->getValueAsInt("RegClassKind"));
1885 isReg = true;
1886 }
1887
1888 DecoderString = TypeRecord->getValue("DecoderMethod");
1889 String = DecoderString ?
Craig Topper24064772014-04-15 07:20:03 +00001890 dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
Hal Finkel71b2e202013-12-19 16:12:53 +00001891 if (!isReg && String && String->getValue() != "")
1892 Decoder = String->getValue();
1893
Petr Pavlu182b0572015-07-15 08:04:27 +00001894 RecordVal *HasCompleteDecoderVal =
1895 TypeRecord->getValue("hasCompleteDecoder");
1896 BitInit *HasCompleteDecoderBit = HasCompleteDecoderVal ?
1897 dyn_cast<BitInit>(HasCompleteDecoderVal->getValue()) : nullptr;
1898 bool HasCompleteDecoder = HasCompleteDecoderBit ?
1899 HasCompleteDecoderBit->getValue() : true;
1900
1901 OperandInfo OpInfo(Decoder, HasCompleteDecoder);
Hal Finkel71b2e202013-12-19 16:12:53 +00001902 OpInfo.addField(bitStart, bitWidth, 0);
1903
1904 NumberedInsnOperands[Name].push_back(OpInfo);
1905
1906 // FIXME: For complex operands with custom decoders we can't handle tied
1907 // sub-operands automatically. Skip those here and assume that this is
1908 // fixed up elsewhere.
1909 if (CGI.Operands[SO.first].MIOperandInfo &&
1910 CGI.Operands[SO.first].MIOperandInfo->getNumArgs() > 1 &&
1911 String && String->getValue() != "")
1912 NumberedInsnOperandsNoTie.insert(Name);
Owen Andersoncb32ce22011-07-29 18:28:52 +00001913 }
Owen Anderson53562d02011-07-28 23:56:20 +00001914 }
1915
Owen Anderson4e818902011-02-18 21:51:29 +00001916 // For each operand, see if we can figure out where it is encoded.
Craig Topper1f7604d2014-12-13 05:12:19 +00001917 for (const auto &Op : InOutOperands) {
1918 if (!NumberedInsnOperands[Op.second].empty()) {
Hal Finkel71b2e202013-12-19 16:12:53 +00001919 InsnOperands.insert(InsnOperands.end(),
Craig Topper1f7604d2014-12-13 05:12:19 +00001920 NumberedInsnOperands[Op.second].begin(),
1921 NumberedInsnOperands[Op.second].end());
Hal Finkel71b2e202013-12-19 16:12:53 +00001922 continue;
Craig Topper1f7604d2014-12-13 05:12:19 +00001923 }
1924 if (!NumberedInsnOperands[TiedNames[Op.second]].empty()) {
1925 if (!NumberedInsnOperandsNoTie.count(TiedNames[Op.second])) {
Hal Finkel71b2e202013-12-19 16:12:53 +00001926 // Figure out to which (sub)operand we're tied.
Craig Topper1f7604d2014-12-13 05:12:19 +00001927 unsigned i = CGI.Operands.getOperandNamed(TiedNames[Op.second]);
Hal Finkel71b2e202013-12-19 16:12:53 +00001928 int tiedTo = CGI.Operands[i].getTiedRegister();
1929 if (tiedTo == -1) {
Craig Topper1f7604d2014-12-13 05:12:19 +00001930 i = CGI.Operands.getOperandNamed(Op.second);
Hal Finkel71b2e202013-12-19 16:12:53 +00001931 tiedTo = CGI.Operands[i].getTiedRegister();
1932 }
1933
1934 if (tiedTo != -1) {
1935 std::pair<unsigned, unsigned> SO =
1936 CGI.Operands.getSubOperandNumber(tiedTo);
1937
Craig Topper1f7604d2014-12-13 05:12:19 +00001938 InsnOperands.push_back(NumberedInsnOperands[TiedNames[Op.second]]
Hal Finkel71b2e202013-12-19 16:12:53 +00001939 [SO.second]);
1940 }
1941 }
1942 continue;
1943 }
1944
Craig Topper1f7604d2014-12-13 05:12:19 +00001945 TypedInit *TI = cast<TypedInit>(Op.first);
Owen Andersone3591652011-07-28 21:54:31 +00001946
Matt Arsenault4cb438b2016-07-18 23:20:46 +00001947 // At this point, we can locate the decoder field, but we need to know how
1948 // to interpret it. As a first step, require the target to provide
1949 // callbacks for decoding register classes.
1950 std::string Decoder = findOperandDecoderMethod(TI);
1951 Record *TypeRecord = cast<RecordRecTy>(TI->getType())->getRecord();
Owen Andersone3591652011-07-28 21:54:31 +00001952
Petr Pavlu182b0572015-07-15 08:04:27 +00001953 RecordVal *HasCompleteDecoderVal =
1954 TypeRecord->getValue("hasCompleteDecoder");
1955 BitInit *HasCompleteDecoderBit = HasCompleteDecoderVal ?
1956 dyn_cast<BitInit>(HasCompleteDecoderVal->getValue()) : nullptr;
1957 bool HasCompleteDecoder = HasCompleteDecoderBit ?
1958 HasCompleteDecoderBit->getValue() : true;
1959
1960 OperandInfo OpInfo(Decoder, HasCompleteDecoder);
Owen Andersone3591652011-07-28 21:54:31 +00001961 unsigned Base = ~0U;
1962 unsigned Width = 0;
1963 unsigned Offset = 0;
1964
Owen Anderson4e818902011-02-18 21:51:29 +00001965 for (unsigned bi = 0; bi < Bits.getNumBits(); ++bi) {
Craig Topper24064772014-04-15 07:20:03 +00001966 VarInit *Var = nullptr;
Sean Silvafb509ed2012-10-10 20:24:43 +00001967 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
Owen Anderson3022d672011-08-01 22:45:43 +00001968 if (BI)
Sean Silvafb509ed2012-10-10 20:24:43 +00001969 Var = dyn_cast<VarInit>(BI->getBitVar());
Owen Anderson3022d672011-08-01 22:45:43 +00001970 else
Sean Silvafb509ed2012-10-10 20:24:43 +00001971 Var = dyn_cast<VarInit>(Bits.getBit(bi));
Owen Anderson3022d672011-08-01 22:45:43 +00001972
1973 if (!Var) {
Owen Andersone3591652011-07-28 21:54:31 +00001974 if (Base != ~0U) {
1975 OpInfo.addField(Base, Width, Offset);
1976 Base = ~0U;
1977 Width = 0;
1978 Offset = 0;
1979 }
1980 continue;
1981 }
Owen Anderson4e818902011-02-18 21:51:29 +00001982
Craig Topper1f7604d2014-12-13 05:12:19 +00001983 if (Var->getName() != Op.second &&
1984 Var->getName() != TiedNames[Op.second]) {
Owen Andersone3591652011-07-28 21:54:31 +00001985 if (Base != ~0U) {
1986 OpInfo.addField(Base, Width, Offset);
1987 Base = ~0U;
1988 Width = 0;
1989 Offset = 0;
1990 }
1991 continue;
Owen Anderson4e818902011-02-18 21:51:29 +00001992 }
1993
Owen Andersone3591652011-07-28 21:54:31 +00001994 if (Base == ~0U) {
1995 Base = bi;
1996 Width = 1;
Owen Anderson3022d672011-08-01 22:45:43 +00001997 Offset = BI ? BI->getBitNum() : 0;
1998 } else if (BI && BI->getBitNum() != Offset + Width) {
Owen Andersone08f5b52011-07-29 23:01:18 +00001999 OpInfo.addField(Base, Width, Offset);
2000 Base = bi;
2001 Width = 1;
2002 Offset = BI->getBitNum();
Owen Andersone3591652011-07-28 21:54:31 +00002003 } else {
2004 ++Width;
Owen Anderson4e818902011-02-18 21:51:29 +00002005 }
Owen Anderson4e818902011-02-18 21:51:29 +00002006 }
2007
Owen Andersone3591652011-07-28 21:54:31 +00002008 if (Base != ~0U)
2009 OpInfo.addField(Base, Width, Offset);
2010
2011 if (OpInfo.numFields() > 0)
2012 InsnOperands.push_back(OpInfo);
Owen Anderson4e818902011-02-18 21:51:29 +00002013 }
2014
2015 Operands[Opc] = InsnOperands;
2016
2017
2018#if 0
2019 DEBUG({
2020 // Dumps the instruction encoding bits.
2021 dumpBits(errs(), Bits);
2022
2023 errs() << '\n';
2024
2025 // Dumps the list of operand info.
2026 for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) {
2027 const CGIOperandList::OperandInfo &Info = CGI.Operands[i];
2028 const std::string &OperandName = Info.Name;
2029 const Record &OperandDef = *Info.Rec;
2030
2031 errs() << "\t" << OperandName << " (" << OperandDef.getName() << ")\n";
2032 }
2033 });
2034#endif
2035
2036 return true;
2037}
2038
Jim Grosbachecaef492012-08-14 19:06:05 +00002039// emitFieldFromInstruction - Emit the templated helper function
2040// fieldFromInstruction().
2041static void emitFieldFromInstruction(formatted_raw_ostream &OS) {
2042 OS << "// Helper function for extracting fields from encoded instructions.\n"
2043 << "template<typename InsnType>\n"
2044 << "static InsnType fieldFromInstruction(InsnType insn, unsigned startBit,\n"
2045 << " unsigned numBits) {\n"
2046 << " assert(startBit + numBits <= (sizeof(InsnType)*8) &&\n"
2047 << " \"Instruction field out of bounds!\");\n"
2048 << " InsnType fieldMask;\n"
2049 << " if (numBits == sizeof(InsnType)*8)\n"
2050 << " fieldMask = (InsnType)(-1LL);\n"
2051 << " else\n"
NAKAMURA Takumibf99a422012-12-26 06:43:14 +00002052 << " fieldMask = (((InsnType)1 << numBits) - 1) << startBit;\n"
Jim Grosbachecaef492012-08-14 19:06:05 +00002053 << " return (insn & fieldMask) >> startBit;\n"
2054 << "}\n\n";
2055}
Owen Anderson4e818902011-02-18 21:51:29 +00002056
Jim Grosbachecaef492012-08-14 19:06:05 +00002057// emitDecodeInstruction - Emit the templated helper function
2058// decodeInstruction().
2059static void emitDecodeInstruction(formatted_raw_ostream &OS) {
2060 OS << "template<typename InsnType>\n"
2061 << "static DecodeStatus decodeInstruction(const uint8_t DecodeTable[], MCInst &MI,\n"
2062 << " InsnType insn, uint64_t Address,\n"
2063 << " const void *DisAsm,\n"
2064 << " const MCSubtargetInfo &STI) {\n"
Michael Kupersteindb0712f2015-05-26 10:47:10 +00002065 << " const FeatureBitset& Bits = STI.getFeatureBits();\n"
Jim Grosbachecaef492012-08-14 19:06:05 +00002066 << "\n"
2067 << " const uint8_t *Ptr = DecodeTable;\n"
Jim Grosbach4c363492012-09-17 18:00:53 +00002068 << " uint32_t CurFieldValue = 0;\n"
Jim Grosbachecaef492012-08-14 19:06:05 +00002069 << " DecodeStatus S = MCDisassembler::Success;\n"
2070 << " for (;;) {\n"
2071 << " ptrdiff_t Loc = Ptr - DecodeTable;\n"
2072 << " switch (*Ptr) {\n"
2073 << " default:\n"
2074 << " errs() << Loc << \": Unexpected decode table opcode!\\n\";\n"
2075 << " return MCDisassembler::Fail;\n"
2076 << " case MCD::OPC_ExtractField: {\n"
2077 << " unsigned Start = *++Ptr;\n"
2078 << " unsigned Len = *++Ptr;\n"
2079 << " ++Ptr;\n"
2080 << " CurFieldValue = fieldFromInstruction(insn, Start, Len);\n"
2081 << " DEBUG(dbgs() << Loc << \": OPC_ExtractField(\" << Start << \", \"\n"
2082 << " << Len << \"): \" << CurFieldValue << \"\\n\");\n"
2083 << " break;\n"
2084 << " }\n"
2085 << " case MCD::OPC_FilterValue: {\n"
2086 << " // Decode the field value.\n"
2087 << " unsigned Len;\n"
2088 << " InsnType Val = decodeULEB128(++Ptr, &Len);\n"
2089 << " Ptr += Len;\n"
2090 << " // NumToSkip is a plain 16-bit integer.\n"
2091 << " unsigned NumToSkip = *Ptr++;\n"
2092 << " NumToSkip |= (*Ptr++) << 8;\n"
2093 << "\n"
2094 << " // Perform the filter operation.\n"
2095 << " if (Val != CurFieldValue)\n"
2096 << " Ptr += NumToSkip;\n"
2097 << " DEBUG(dbgs() << Loc << \": OPC_FilterValue(\" << Val << \", \" << NumToSkip\n"
2098 << " << \"): \" << ((Val != CurFieldValue) ? \"FAIL:\" : \"PASS:\")\n"
2099 << " << \" continuing at \" << (Ptr - DecodeTable) << \"\\n\");\n"
2100 << "\n"
2101 << " break;\n"
2102 << " }\n"
2103 << " case MCD::OPC_CheckField: {\n"
2104 << " unsigned Start = *++Ptr;\n"
2105 << " unsigned Len = *++Ptr;\n"
2106 << " InsnType FieldValue = fieldFromInstruction(insn, Start, Len);\n"
2107 << " // Decode the field value.\n"
2108 << " uint32_t ExpectedValue = decodeULEB128(++Ptr, &Len);\n"
2109 << " Ptr += Len;\n"
2110 << " // NumToSkip is a plain 16-bit integer.\n"
2111 << " unsigned NumToSkip = *Ptr++;\n"
2112 << " NumToSkip |= (*Ptr++) << 8;\n"
2113 << "\n"
2114 << " // If the actual and expected values don't match, skip.\n"
2115 << " if (ExpectedValue != FieldValue)\n"
2116 << " Ptr += NumToSkip;\n"
2117 << " DEBUG(dbgs() << Loc << \": OPC_CheckField(\" << Start << \", \"\n"
2118 << " << Len << \", \" << ExpectedValue << \", \" << NumToSkip\n"
2119 << " << \"): FieldValue = \" << FieldValue << \", ExpectedValue = \"\n"
2120 << " << ExpectedValue << \": \"\n"
2121 << " << ((ExpectedValue == FieldValue) ? \"PASS\\n\" : \"FAIL\\n\"));\n"
2122 << " break;\n"
2123 << " }\n"
2124 << " case MCD::OPC_CheckPredicate: {\n"
2125 << " unsigned Len;\n"
2126 << " // Decode the Predicate Index value.\n"
2127 << " unsigned PIdx = decodeULEB128(++Ptr, &Len);\n"
2128 << " Ptr += Len;\n"
2129 << " // NumToSkip is a plain 16-bit integer.\n"
2130 << " unsigned NumToSkip = *Ptr++;\n"
2131 << " NumToSkip |= (*Ptr++) << 8;\n"
2132 << " // Check the predicate.\n"
2133 << " bool Pred;\n"
2134 << " if (!(Pred = checkDecoderPredicate(PIdx, Bits)))\n"
2135 << " Ptr += NumToSkip;\n"
2136 << " (void)Pred;\n"
2137 << " DEBUG(dbgs() << Loc << \": OPC_CheckPredicate(\" << PIdx << \"): \"\n"
2138 << " << (Pred ? \"PASS\\n\" : \"FAIL\\n\"));\n"
2139 << "\n"
2140 << " break;\n"
2141 << " }\n"
2142 << " case MCD::OPC_Decode: {\n"
2143 << " unsigned Len;\n"
2144 << " // Decode the Opcode value.\n"
2145 << " unsigned Opc = decodeULEB128(++Ptr, &Len);\n"
2146 << " Ptr += Len;\n"
2147 << " unsigned DecodeIdx = decodeULEB128(Ptr, &Len);\n"
2148 << " Ptr += Len;\n"
Jim Grosbachecaef492012-08-14 19:06:05 +00002149 << "\n"
Cameron Esfahanif97999d2015-08-11 01:15:07 +00002150 << " MI.clear();\n"
Jim Grosbachecaef492012-08-14 19:06:05 +00002151 << " MI.setOpcode(Opc);\n"
Petr Pavlu182b0572015-07-15 08:04:27 +00002152 << " bool DecodeComplete;\n"
2153 << " S = decodeToMCInst(S, DecodeIdx, insn, MI, Address, DisAsm, DecodeComplete);\n"
2154 << " assert(DecodeComplete);\n"
2155 << "\n"
2156 << " DEBUG(dbgs() << Loc << \": OPC_Decode: opcode \" << Opc\n"
2157 << " << \", using decoder \" << DecodeIdx << \": \"\n"
2158 << " << (S != MCDisassembler::Fail ? \"PASS\" : \"FAIL\") << \"\\n\");\n"
2159 << " return S;\n"
2160 << " }\n"
2161 << " case MCD::OPC_TryDecode: {\n"
2162 << " unsigned Len;\n"
2163 << " // Decode the Opcode value.\n"
2164 << " unsigned Opc = decodeULEB128(++Ptr, &Len);\n"
2165 << " Ptr += Len;\n"
2166 << " unsigned DecodeIdx = decodeULEB128(Ptr, &Len);\n"
2167 << " Ptr += Len;\n"
2168 << " // NumToSkip is a plain 16-bit integer.\n"
2169 << " unsigned NumToSkip = *Ptr++;\n"
2170 << " NumToSkip |= (*Ptr++) << 8;\n"
2171 << "\n"
2172 << " // Perform the decode operation.\n"
2173 << " MCInst TmpMI;\n"
2174 << " TmpMI.setOpcode(Opc);\n"
2175 << " bool DecodeComplete;\n"
2176 << " S = decodeToMCInst(S, DecodeIdx, insn, TmpMI, Address, DisAsm, DecodeComplete);\n"
2177 << " DEBUG(dbgs() << Loc << \": OPC_TryDecode: opcode \" << Opc\n"
2178 << " << \", using decoder \" << DecodeIdx << \": \");\n"
2179 << "\n"
2180 << " if (DecodeComplete) {\n"
2181 << " // Decoding complete.\n"
2182 << " DEBUG(dbgs() << (S != MCDisassembler::Fail ? \"PASS\" : \"FAIL\") << \"\\n\");\n"
2183 << " MI = TmpMI;\n"
2184 << " return S;\n"
2185 << " } else {\n"
2186 << " assert(S == MCDisassembler::Fail);\n"
2187 << " // If the decoding was incomplete, skip.\n"
2188 << " Ptr += NumToSkip;\n"
2189 << " DEBUG(dbgs() << \"FAIL: continuing at \" << (Ptr - DecodeTable) << \"\\n\");\n"
2190 << " // Reset decode status. This also drops a SoftFail status that could be\n"
2191 << " // set before the decode attempt.\n"
2192 << " S = MCDisassembler::Success;\n"
2193 << " }\n"
2194 << " break;\n"
Jim Grosbachecaef492012-08-14 19:06:05 +00002195 << " }\n"
2196 << " case MCD::OPC_SoftFail: {\n"
2197 << " // Decode the mask values.\n"
2198 << " unsigned Len;\n"
2199 << " InsnType PositiveMask = decodeULEB128(++Ptr, &Len);\n"
2200 << " Ptr += Len;\n"
2201 << " InsnType NegativeMask = decodeULEB128(Ptr, &Len);\n"
2202 << " Ptr += Len;\n"
2203 << " bool Fail = (insn & PositiveMask) || (~insn & NegativeMask);\n"
2204 << " if (Fail)\n"
2205 << " S = MCDisassembler::SoftFail;\n"
2206 << " DEBUG(dbgs() << Loc << \": OPC_SoftFail: \" << (Fail ? \"FAIL\\n\":\"PASS\\n\"));\n"
2207 << " break;\n"
2208 << " }\n"
2209 << " case MCD::OPC_Fail: {\n"
2210 << " DEBUG(dbgs() << Loc << \": OPC_Fail\\n\");\n"
2211 << " return MCDisassembler::Fail;\n"
2212 << " }\n"
2213 << " }\n"
2214 << " }\n"
2215 << " llvm_unreachable(\"bogosity detected in disassembler state machine!\");\n"
2216 << "}\n\n";
Owen Anderson4e818902011-02-18 21:51:29 +00002217}
2218
2219// Emits disassembler code for instruction decoding.
Craig Topper82d0d5f2012-03-16 01:19:24 +00002220void FixedLenDecoderEmitter::run(raw_ostream &o) {
Jim Grosbachecaef492012-08-14 19:06:05 +00002221 formatted_raw_ostream OS(o);
2222 OS << "#include \"llvm/MC/MCInst.h\"\n";
2223 OS << "#include \"llvm/Support/Debug.h\"\n";
2224 OS << "#include \"llvm/Support/DataTypes.h\"\n";
2225 OS << "#include \"llvm/Support/LEB128.h\"\n";
2226 OS << "#include \"llvm/Support/raw_ostream.h\"\n";
2227 OS << "#include <assert.h>\n";
2228 OS << '\n';
2229 OS << "namespace llvm {\n\n";
2230
2231 emitFieldFromInstruction(OS);
Owen Anderson4e818902011-02-18 21:51:29 +00002232
Hal Finkel81e6fcc2013-12-17 22:37:50 +00002233 Target.reverseBitsForLittleEndianEncoding();
2234
Owen Andersonc78e03c2011-07-19 21:06:00 +00002235 // Parameterize the decoders based on namespace and instruction width.
Craig Topperf9265322016-01-17 20:38:14 +00002236 NumberedInstructions = Target.getInstructionsByEnumValue();
Owen Andersonc78e03c2011-07-19 21:06:00 +00002237 std::map<std::pair<std::string, unsigned>,
2238 std::vector<unsigned> > OpcMap;
2239 std::map<unsigned, std::vector<OperandInfo> > Operands;
2240
Craig Topperf9265322016-01-17 20:38:14 +00002241 for (unsigned i = 0; i < NumberedInstructions.size(); ++i) {
2242 const CodeGenInstruction *Inst = NumberedInstructions[i];
Craig Topper48c112b2012-03-16 05:58:09 +00002243 const Record *Def = Inst->TheDef;
Owen Andersonc78e03c2011-07-19 21:06:00 +00002244 unsigned Size = Def->getValueAsInt("Size");
2245 if (Def->getValueAsString("Namespace") == "TargetOpcode" ||
2246 Def->getValueAsBit("isPseudo") ||
2247 Def->getValueAsBit("isAsmParserOnly") ||
2248 Def->getValueAsBit("isCodeGenOnly"))
2249 continue;
2250
2251 std::string DecoderNamespace = Def->getValueAsString("DecoderNamespace");
2252
2253 if (Size) {
Hal Finkel71b2e202013-12-19 16:12:53 +00002254 if (populateInstruction(Target, *Inst, i, Operands)) {
Owen Andersonc78e03c2011-07-19 21:06:00 +00002255 OpcMap[std::make_pair(DecoderNamespace, Size)].push_back(i);
2256 }
2257 }
2258 }
2259
Jim Grosbachecaef492012-08-14 19:06:05 +00002260 DecoderTableInfo TableInfo;
Craig Topper1f7604d2014-12-13 05:12:19 +00002261 for (const auto &Opc : OpcMap) {
Owen Andersonc78e03c2011-07-19 21:06:00 +00002262 // Emit the decoder for this namespace+width combination.
Craig Topperf9265322016-01-17 20:38:14 +00002263 FilterChooser FC(NumberedInstructions, Opc.second, Operands,
Craig Topper1f7604d2014-12-13 05:12:19 +00002264 8*Opc.first.second, this);
Jim Grosbachecaef492012-08-14 19:06:05 +00002265
2266 // The decode table is cleared for each top level decoder function. The
2267 // predicates and decoders themselves, however, are shared across all
2268 // decoders to give more opportunities for uniqueing.
2269 TableInfo.Table.clear();
2270 TableInfo.FixupStack.clear();
2271 TableInfo.Table.reserve(16384);
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002272 TableInfo.FixupStack.emplace_back();
Jim Grosbachecaef492012-08-14 19:06:05 +00002273 FC.emitTableEntries(TableInfo);
2274 // Any NumToSkip fixups in the top level scope can resolve to the
2275 // OPC_Fail at the end of the table.
2276 assert(TableInfo.FixupStack.size() == 1 && "fixup stack phasing error!");
2277 // Resolve any NumToSkip fixups in the current scope.
2278 resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),
2279 TableInfo.Table.size());
2280 TableInfo.FixupStack.clear();
2281
2282 TableInfo.Table.push_back(MCD::OPC_Fail);
2283
2284 // Print the table to the output stream.
Craig Topper1f7604d2014-12-13 05:12:19 +00002285 emitTable(OS, TableInfo.Table, 0, FC.getBitWidth(), Opc.first.first);
Jim Grosbachecaef492012-08-14 19:06:05 +00002286 OS.flush();
Owen Andersonc78e03c2011-07-19 21:06:00 +00002287 }
Owen Anderson4e818902011-02-18 21:51:29 +00002288
Jim Grosbachecaef492012-08-14 19:06:05 +00002289 // Emit the predicate function.
2290 emitPredicateFunction(OS, TableInfo.Predicates, 0);
2291
2292 // Emit the decoder function.
2293 emitDecoderFunction(OS, TableInfo.Decoders, 0);
2294
2295 // Emit the main entry point for the decoder, decodeInstruction().
2296 emitDecodeInstruction(OS);
2297
2298 OS << "\n} // End llvm namespace\n";
Owen Anderson4e818902011-02-18 21:51:29 +00002299}
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +00002300
2301namespace llvm {
2302
2303void EmitFixedLenDecoder(RecordKeeper &RK, raw_ostream &OS,
Benjamin Kramerc321e532016-06-08 19:09:22 +00002304 const std::string &PredicateNamespace,
2305 const std::string &GPrefix,
2306 const std::string &GPostfix, const std::string &ROK,
2307 const std::string &RFail, const std::string &L) {
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +00002308 FixedLenDecoderEmitter(RK, PredicateNamespace, GPrefix, GPostfix,
2309 ROK, RFail, L).run(OS);
2310}
2311
2312} // End llvm namespace