blob: 5e621fc0efdd5f916afed3c9d1e99faa82e22701 [file] [log] [blame]
Owen Andersond8c87882011-02-18 21:51:29 +00001//===------------ FixedLenDecoderEmitter.cpp - Decoder Generator ----------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// It contains the tablegen backend that emits the decoder functions for
11// targets with fixed length instruction set.
12//
13//===----------------------------------------------------------------------===//
14
Eugene Zelenkoc02caf52016-11-30 17:48:10 +000015#include "CodeGenInstruction.h"
Owen Andersond8c87882011-02-18 21:51:29 +000016#include "CodeGenTarget.h"
James Molloy3015dfb2012-02-09 10:56:31 +000017#include "llvm/ADT/APInt.h"
Eugene Zelenkoc02caf52016-11-30 17:48:10 +000018#include "llvm/ADT/ArrayRef.h"
Justin Lebar2c937a12016-10-21 21:45:01 +000019#include "llvm/ADT/CachedHashString.h"
Jim Grosbachfc1a1612012-08-14 19:06:05 +000020#include "llvm/ADT/SmallString.h"
Eugene Zelenkoc02caf52016-11-30 17:48:10 +000021#include "llvm/ADT/SetVector.h"
22#include "llvm/ADT/STLExtras.h"
Owen Andersond8c87882011-02-18 21:51:29 +000023#include "llvm/ADT/StringExtras.h"
Jim Grosbachfc1a1612012-08-14 19:06:05 +000024#include "llvm/ADT/StringRef.h"
Jim Grosbachfc1a1612012-08-14 19:06:05 +000025#include "llvm/MC/MCFixedLenDisassembler.h"
Eugene Zelenkoc02caf52016-11-30 17:48:10 +000026#include "llvm/Support/Casting.h"
Owen Andersond8c87882011-02-18 21:51:29 +000027#include "llvm/Support/Debug.h"
Eugene Zelenkoc02caf52016-11-30 17:48:10 +000028#include "llvm/Support/ErrorHandling.h"
Jim Grosbachfc1a1612012-08-14 19:06:05 +000029#include "llvm/Support/FormattedStream.h"
30#include "llvm/Support/LEB128.h"
Owen Andersond8c87882011-02-18 21:51:29 +000031#include "llvm/Support/raw_ostream.h"
Chandler Carruth4ffd89f2012-12-04 10:37:14 +000032#include "llvm/TableGen/Error.h"
33#include "llvm/TableGen/Record.h"
Eugene Zelenkoc02caf52016-11-30 17:48:10 +000034#include <algorithm>
35#include <cassert>
36#include <cstddef>
37#include <cstdint>
Owen Andersond8c87882011-02-18 21:51:29 +000038#include <map>
Eugene Zelenkoc02caf52016-11-30 17:48:10 +000039#include <memory>
40#include <set>
Owen Andersond8c87882011-02-18 21:51:29 +000041#include <string>
Benjamin Kramer14aae012016-05-27 14:27:24 +000042#include <utility>
Chandler Carruth4ffd89f2012-12-04 10:37:14 +000043#include <vector>
Owen Andersond8c87882011-02-18 21:51:29 +000044
45using namespace llvm;
46
Chandler Carruth915c29c2014-04-22 03:06:00 +000047#define DEBUG_TYPE "decoder-emitter"
48
Jakob Stoklund Olesen6f36fa92012-06-11 15:37:55 +000049namespace {
Eugene Zelenkoc02caf52016-11-30 17:48:10 +000050
Jakob Stoklund Olesen6f36fa92012-06-11 15:37:55 +000051struct EncodingField {
52 unsigned Base, Width, Offset;
53 EncodingField(unsigned B, unsigned W, unsigned O)
54 : Base(B), Width(W), Offset(O) { }
55};
Jakob Stoklund Olesen6f36fa92012-06-11 15:37:55 +000056
Jakob Stoklund Olesen6f36fa92012-06-11 15:37:55 +000057struct OperandInfo {
58 std::vector<EncodingField> Fields;
59 std::string Decoder;
Petr Pavlud2e1e422015-07-15 08:04:27 +000060 bool HasCompleteDecoder;
Jakob Stoklund Olesen6f36fa92012-06-11 15:37:55 +000061
Petr Pavlud2e1e422015-07-15 08:04:27 +000062 OperandInfo(std::string D, bool HCD)
Benjamin Kramer14aae012016-05-27 14:27:24 +000063 : Decoder(std::move(D)), HasCompleteDecoder(HCD) {}
Jakob Stoklund Olesen6f36fa92012-06-11 15:37:55 +000064
65 void addField(unsigned Base, unsigned Width, unsigned Offset) {
66 Fields.push_back(EncodingField(Base, Width, Offset));
67 }
68
69 unsigned numFields() const { return Fields.size(); }
70
71 typedef std::vector<EncodingField>::const_iterator const_iterator;
72
73 const_iterator begin() const { return Fields.begin(); }
74 const_iterator end() const { return Fields.end(); }
75};
Jim Grosbachfc1a1612012-08-14 19:06:05 +000076
77typedef std::vector<uint8_t> DecoderTable;
78typedef uint32_t DecoderFixup;
79typedef std::vector<DecoderFixup> FixupList;
80typedef std::vector<FixupList> FixupScopeList;
Justin Lebar2c937a12016-10-21 21:45:01 +000081typedef SmallSetVector<CachedHashString, 16> PredicateSet;
82typedef SmallSetVector<CachedHashString, 16> DecoderSet;
Jim Grosbachfc1a1612012-08-14 19:06:05 +000083struct DecoderTableInfo {
84 DecoderTable Table;
85 FixupScopeList FixupStack;
86 PredicateSet Predicates;
87 DecoderSet Decoders;
88};
89
Daniel Sanders0de70682018-12-13 16:17:54 +000090struct EncodingAndInst {
91 const Record *EncodingDef;
92 const CodeGenInstruction *Inst;
93
94 EncodingAndInst(const Record *EncodingDef, const CodeGenInstruction *Inst)
95 : EncodingDef(EncodingDef), Inst(Inst) {}
96};
97
98raw_ostream &operator<<(raw_ostream &OS, const EncodingAndInst &Value) {
99 if (Value.EncodingDef != Value.Inst->TheDef)
100 OS << Value.EncodingDef->getName() << ":";
101 OS << Value.Inst->TheDef->getName();
102 return OS;
103}
104
Jakob Stoklund Olesen6f36fa92012-06-11 15:37:55 +0000105class FixedLenDecoderEmitter {
Daniel Sanders0de70682018-12-13 16:17:54 +0000106 std::vector<EncodingAndInst> NumberedEncodings;
Jakob Stoklund Olesen6f36fa92012-06-11 15:37:55 +0000107
Eugene Zelenkoc02caf52016-11-30 17:48:10 +0000108public:
Jakob Stoklund Olesen6f36fa92012-06-11 15:37:55 +0000109 // Defaults preserved here for documentation, even though they aren't
110 // strictly necessary given the way that this is currently being called.
Benjamin Kramer14aae012016-05-27 14:27:24 +0000111 FixedLenDecoderEmitter(RecordKeeper &R, std::string PredicateNamespace,
112 std::string GPrefix = "if (",
Petr Pavlud2e1e422015-07-15 08:04:27 +0000113 std::string GPostfix = " == MCDisassembler::Fail)",
Benjamin Kramer14aae012016-05-27 14:27:24 +0000114 std::string ROK = "MCDisassembler::Success",
115 std::string RFail = "MCDisassembler::Fail",
116 std::string L = "")
117 : Target(R), PredicateNamespace(std::move(PredicateNamespace)),
118 GuardPrefix(std::move(GPrefix)), GuardPostfix(std::move(GPostfix)),
119 ReturnOK(std::move(ROK)), ReturnFail(std::move(RFail)),
120 Locals(std::move(L)) {}
Jakob Stoklund Olesen6f36fa92012-06-11 15:37:55 +0000121
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000122 // Emit the decoder state machine table.
123 void emitTable(formatted_raw_ostream &o, DecoderTable &Table,
124 unsigned Indentation, unsigned BitWidth,
125 StringRef Namespace) const;
126 void emitPredicateFunction(formatted_raw_ostream &OS,
127 PredicateSet &Predicates,
128 unsigned Indentation) const;
129 void emitDecoderFunction(formatted_raw_ostream &OS,
130 DecoderSet &Decoders,
131 unsigned Indentation) const;
132
Jakob Stoklund Olesen6f36fa92012-06-11 15:37:55 +0000133 // run - Output the code emitter
134 void run(raw_ostream &o);
135
136private:
137 CodeGenTarget Target;
Eugene Zelenkoc02caf52016-11-30 17:48:10 +0000138
Jakob Stoklund Olesen6f36fa92012-06-11 15:37:55 +0000139public:
140 std::string PredicateNamespace;
141 std::string GuardPrefix, GuardPostfix;
142 std::string ReturnOK, ReturnFail;
143 std::string Locals;
144};
Eugene Zelenkoc02caf52016-11-30 17:48:10 +0000145
146} // end anonymous namespace
Jakob Stoklund Olesen6f36fa92012-06-11 15:37:55 +0000147
Owen Andersond8c87882011-02-18 21:51:29 +0000148// The set (BIT_TRUE, BIT_FALSE, BIT_UNSET) represents a ternary logic system
149// for a bit value.
150//
151// BIT_UNFILTERED is used as the init value for a filter position. It is used
152// only for filter processings.
153typedef enum {
154 BIT_TRUE, // '1'
155 BIT_FALSE, // '0'
156 BIT_UNSET, // '?'
157 BIT_UNFILTERED // unfiltered
158} bit_value_t;
159
160static bool ValueSet(bit_value_t V) {
161 return (V == BIT_TRUE || V == BIT_FALSE);
162}
Eugene Zelenkoc02caf52016-11-30 17:48:10 +0000163
Owen Andersond8c87882011-02-18 21:51:29 +0000164static bool ValueNotSet(bit_value_t V) {
165 return (V == BIT_UNSET);
166}
Eugene Zelenkoc02caf52016-11-30 17:48:10 +0000167
Owen Andersond8c87882011-02-18 21:51:29 +0000168static int Value(bit_value_t V) {
169 return ValueNotSet(V) ? -1 : (V == BIT_FALSE ? 0 : 1);
170}
Eugene Zelenkoc02caf52016-11-30 17:48:10 +0000171
Craig Toppereb5cd612012-03-16 05:58:09 +0000172static bit_value_t bitFromBits(const BitsInit &bits, unsigned index) {
Sean Silva6cfc8062012-10-10 20:24:43 +0000173 if (BitInit *bit = dyn_cast<BitInit>(bits.getBit(index)))
Owen Andersond8c87882011-02-18 21:51:29 +0000174 return bit->getValue() ? BIT_TRUE : BIT_FALSE;
175
176 // The bit is uninitialized.
177 return BIT_UNSET;
178}
Eugene Zelenkoc02caf52016-11-30 17:48:10 +0000179
Owen Andersond8c87882011-02-18 21:51:29 +0000180// Prints the bit value for each position.
Craig Toppereb5cd612012-03-16 05:58:09 +0000181static void dumpBits(raw_ostream &o, const BitsInit &bits) {
Craig Topper8cd9eae2012-08-17 05:42:16 +0000182 for (unsigned index = bits.getNumBits(); index > 0; --index) {
Owen Andersond8c87882011-02-18 21:51:29 +0000183 switch (bitFromBits(bits, index - 1)) {
184 case BIT_TRUE:
185 o << "1";
186 break;
187 case BIT_FALSE:
188 o << "0";
189 break;
190 case BIT_UNSET:
191 o << "_";
192 break;
193 default:
Craig Topper655b8de2012-02-05 07:21:30 +0000194 llvm_unreachable("unexpected return value from bitFromBits");
Owen Andersond8c87882011-02-18 21:51:29 +0000195 }
196 }
197}
198
Mehdi Aminid0bf4472016-10-04 23:47:33 +0000199static BitsInit &getBitsField(const Record &def, StringRef str) {
David Greene05bce0b2011-07-29 22:43:06 +0000200 BitsInit *bits = def.getValueAsBitsInit(str);
Owen Andersond8c87882011-02-18 21:51:29 +0000201 return *bits;
202}
203
Owen Andersond8c87882011-02-18 21:51:29 +0000204// Representation of the instruction to work on.
Owen Andersonf1a00902011-07-19 21:06:00 +0000205typedef std::vector<bit_value_t> insn_t;
Owen Andersond8c87882011-02-18 21:51:29 +0000206
Eugene Zelenkoc02caf52016-11-30 17:48:10 +0000207namespace {
208
209class FilterChooser;
210
Owen Andersond8c87882011-02-18 21:51:29 +0000211/// Filter - Filter works with FilterChooser to produce the decoding tree for
212/// the ISA.
213///
214/// It is useful to think of a Filter as governing the switch stmts of the
215/// decoding tree in a certain level. Each case stmt delegates to an inferior
216/// FilterChooser to decide what further decoding logic to employ, or in another
217/// words, what other remaining bits to look at. The FilterChooser eventually
218/// chooses a best Filter to do its job.
219///
220/// This recursive scheme ends when the number of Opcodes assigned to the
221/// FilterChooser becomes 1 or if there is a conflict. A conflict happens when
222/// the Filter/FilterChooser combo does not know how to distinguish among the
223/// Opcodes assigned.
224///
225/// An example of a conflict is
226///
227/// Conflict:
228/// 111101000.00........00010000....
229/// 111101000.00........0001........
230/// 1111010...00........0001........
231/// 1111010...00....................
232/// 1111010.........................
233/// 1111............................
234/// ................................
235/// VST4q8a 111101000_00________00010000____
236/// VST4q8b 111101000_00________00010000____
237///
238/// The Debug output shows the path that the decoding tree follows to reach the
239/// the conclusion that there is a conflict. VST4q8a is a vst4 to double-spaced
Petr Pavlu936924f2015-07-14 08:00:34 +0000240/// even registers, while VST4q8b is a vst4 to double-spaced odd registers.
Owen Andersond8c87882011-02-18 21:51:29 +0000241///
242/// The encoding info in the .td files does not specify this meta information,
243/// which could have been used by the decoder to resolve the conflict. The
244/// decoder could try to decode the even/odd register numbering and assign to
245/// VST4q8a or VST4q8b, but for the time being, the decoder chooses the "a"
246/// version and return the Opcode since the two have the same Asm format string.
247class Filter {
248protected:
Craig Topper5a4c7902012-03-16 06:52:56 +0000249 const FilterChooser *Owner;// points to the FilterChooser who owns this filter
Owen Andersond8c87882011-02-18 21:51:29 +0000250 unsigned StartBit; // the starting bit position
251 unsigned NumBits; // number of bits to filter
252 bool Mixed; // a mixed region contains both set and unset bits
253
254 // Map of well-known segment value to the set of uid's with that value.
Eugene Zelenkoc02caf52016-11-30 17:48:10 +0000255 std::map<uint64_t, std::vector<unsigned>> FilteredInstructions;
Owen Andersond8c87882011-02-18 21:51:29 +0000256
257 // Set of uid's with non-constant segment values.
258 std::vector<unsigned> VariableInstructions;
259
260 // Map of well-known segment value to its delegate.
Craig Topper732b0262014-09-03 06:07:54 +0000261 std::map<unsigned, std::unique_ptr<const FilterChooser>> FilterChooserMap;
Owen Andersond8c87882011-02-18 21:51:29 +0000262
263 // Number of instructions which fall under FilteredInstructions category.
264 unsigned NumFiltered;
265
266 // Keeps track of the last opcode in the filtered bucket.
267 unsigned LastOpcFiltered;
268
Owen Andersond8c87882011-02-18 21:51:29 +0000269public:
Eugene Zelenkoc02caf52016-11-30 17:48:10 +0000270 Filter(Filter &&f);
271 Filter(FilterChooser &owner, unsigned startBit, unsigned numBits, bool mixed);
272
273 ~Filter() = default;
274
Craig Toppereb5cd612012-03-16 05:58:09 +0000275 unsigned getNumFiltered() const { return NumFiltered; }
Eugene Zelenkoc02caf52016-11-30 17:48:10 +0000276
Craig Toppereb5cd612012-03-16 05:58:09 +0000277 unsigned getSingletonOpc() const {
Owen Andersond8c87882011-02-18 21:51:29 +0000278 assert(NumFiltered == 1);
279 return LastOpcFiltered;
280 }
Eugene Zelenkoc02caf52016-11-30 17:48:10 +0000281
Owen Andersond8c87882011-02-18 21:51:29 +0000282 // Return the filter chooser for the group of instructions without constant
283 // segment values.
Craig Toppereb5cd612012-03-16 05:58:09 +0000284 const FilterChooser &getVariableFC() const {
Owen Andersond8c87882011-02-18 21:51:29 +0000285 assert(NumFiltered == 1);
286 assert(FilterChooserMap.size() == 1);
287 return *(FilterChooserMap.find((unsigned)-1)->second);
288 }
289
Owen Andersond8c87882011-02-18 21:51:29 +0000290 // Divides the decoding task into sub tasks and delegates them to the
291 // inferior FilterChooser's.
292 //
293 // A special case arises when there's only one entry in the filtered
294 // instructions. In order to unambiguously decode the singleton, we need to
295 // match the remaining undecoded encoding bits against the singleton.
296 void recurse();
297
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000298 // Emit table entries to decode instructions given a segment or segments of
299 // bits.
300 void emitTableEntry(DecoderTableInfo &TableInfo) const;
Owen Andersond8c87882011-02-18 21:51:29 +0000301
302 // Returns the number of fanout produced by the filter. More fanout implies
303 // the filter distinguishes more categories of instructions.
304 unsigned usefulness() const;
Eugene Zelenkoc02caf52016-11-30 17:48:10 +0000305}; // end class Filter
306
307} // end anonymous namespace
Owen Andersond8c87882011-02-18 21:51:29 +0000308
309// These are states of our finite state machines used in FilterChooser's
310// filterProcessor() which produces the filter candidates to use.
311typedef enum {
312 ATTR_NONE,
313 ATTR_FILTERED,
314 ATTR_ALL_SET,
315 ATTR_ALL_UNSET,
316 ATTR_MIXED
317} bitAttr_t;
318
319/// FilterChooser - FilterChooser chooses the best filter among a set of Filters
320/// in order to perform the decoding of instructions at the current level.
321///
322/// Decoding proceeds from the top down. Based on the well-known encoding bits
323/// of instructions available, FilterChooser builds up the possible Filters that
324/// can further the task of decoding by distinguishing among the remaining
325/// candidate instructions.
326///
327/// Once a filter has been chosen, it is called upon to divide the decoding task
328/// into sub-tasks and delegates them to its inferior FilterChoosers for further
329/// processings.
330///
331/// It is useful to think of a Filter as governing the switch stmts of the
332/// decoding tree. And each case is delegated to an inferior FilterChooser to
333/// decide what further remaining bits to look at.
Jakob Stoklund Olesen6f36fa92012-06-11 15:37:55 +0000334namespace {
Eugene Zelenkoc02caf52016-11-30 17:48:10 +0000335
Owen Andersond8c87882011-02-18 21:51:29 +0000336class FilterChooser {
337protected:
338 friend class Filter;
339
340 // Vector of codegen instructions to choose our filter.
Daniel Sanders0de70682018-12-13 16:17:54 +0000341 ArrayRef<EncodingAndInst> AllInstructions;
Owen Andersond8c87882011-02-18 21:51:29 +0000342
343 // Vector of uid's for this filter chooser to work on.
Craig Topper5a4c7902012-03-16 06:52:56 +0000344 const std::vector<unsigned> &Opcodes;
Owen Andersond8c87882011-02-18 21:51:29 +0000345
346 // Lookup table for the operand decoding of instructions.
Eugene Zelenkoc02caf52016-11-30 17:48:10 +0000347 const std::map<unsigned, std::vector<OperandInfo>> &Operands;
Owen Andersond8c87882011-02-18 21:51:29 +0000348
349 // Vector of candidate filters.
350 std::vector<Filter> Filters;
351
352 // Array of bit values passed down from our parent.
353 // Set to all BIT_UNFILTERED's for Parent == NULL.
Owen Andersonf1a00902011-07-19 21:06:00 +0000354 std::vector<bit_value_t> FilterBitValues;
Owen Andersond8c87882011-02-18 21:51:29 +0000355
356 // Links to the FilterChooser above us in the decoding tree.
Craig Topper5a4c7902012-03-16 06:52:56 +0000357 const FilterChooser *Parent;
Owen Andersond8c87882011-02-18 21:51:29 +0000358
359 // Index of the best filter from Filters.
360 int BestIndex;
361
Owen Andersonf1a00902011-07-19 21:06:00 +0000362 // Width of instructions
363 unsigned BitWidth;
364
Owen Anderson83e3f672011-08-17 17:44:15 +0000365 // Parent emitter
366 const FixedLenDecoderEmitter *Emitter;
367
Owen Andersond8c87882011-02-18 21:51:29 +0000368public:
Daniel Sanders0de70682018-12-13 16:17:54 +0000369 FilterChooser(ArrayRef<EncodingAndInst> Insts,
Owen Andersond8c87882011-02-18 21:51:29 +0000370 const std::vector<unsigned> &IDs,
Eugene Zelenkoc02caf52016-11-30 17:48:10 +0000371 const std::map<unsigned, std::vector<OperandInfo>> &Ops,
Daniel Sanders0de70682018-12-13 16:17:54 +0000372 unsigned BW, const FixedLenDecoderEmitter *E)
373 : AllInstructions(Insts), Opcodes(IDs), Operands(Ops),
374 FilterBitValues(BW, BIT_UNFILTERED), Parent(nullptr), BestIndex(-1),
375 BitWidth(BW), Emitter(E) {
Owen Andersond8c87882011-02-18 21:51:29 +0000376 doFilter();
377 }
378
Daniel Sanders0de70682018-12-13 16:17:54 +0000379 FilterChooser(ArrayRef<EncodingAndInst> Insts,
Owen Andersond8c87882011-02-18 21:51:29 +0000380 const std::vector<unsigned> &IDs,
Eugene Zelenkoc02caf52016-11-30 17:48:10 +0000381 const std::map<unsigned, std::vector<OperandInfo>> &Ops,
Craig Topper5a4c7902012-03-16 06:52:56 +0000382 const std::vector<bit_value_t> &ParentFilterBitValues,
383 const FilterChooser &parent)
Daniel Sanders0de70682018-12-13 16:17:54 +0000384 : AllInstructions(Insts), Opcodes(IDs), Operands(Ops),
385 FilterBitValues(ParentFilterBitValues), Parent(&parent), BestIndex(-1),
386 BitWidth(parent.BitWidth), Emitter(parent.Emitter) {
Owen Andersond8c87882011-02-18 21:51:29 +0000387 doFilter();
388 }
389
Eugene Zelenkoc02caf52016-11-30 17:48:10 +0000390 FilterChooser(const FilterChooser &) = delete;
391 void operator=(const FilterChooser &) = delete;
392
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000393 unsigned getBitWidth() const { return BitWidth; }
Owen Andersond8c87882011-02-18 21:51:29 +0000394
395protected:
396 // Populates the insn given the uid.
397 void insnWithID(insn_t &Insn, unsigned Opcode) const {
Daniel Sanders0de70682018-12-13 16:17:54 +0000398 BitsInit &Bits = getBitsField(*AllInstructions[Opcode].EncodingDef, "Inst");
Owen Andersond8c87882011-02-18 21:51:29 +0000399
James Molloy3015dfb2012-02-09 10:56:31 +0000400 // We may have a SoftFail bitmask, which specifies a mask where an encoding
401 // may differ from the value in "Inst" and yet still be valid, but the
402 // disassembler should return SoftFail instead of Success.
403 //
404 // This is used for marking UNPREDICTABLE instructions in the ARM world.
Jim Grosbach9c826d22012-02-29 22:07:56 +0000405 BitsInit *SFBits =
Daniel Sanders0de70682018-12-13 16:17:54 +0000406 AllInstructions[Opcode].EncodingDef->getValueAsBitsInit("SoftFail");
James Molloy3015dfb2012-02-09 10:56:31 +0000407
408 for (unsigned i = 0; i < BitWidth; ++i) {
409 if (SFBits && bitFromBits(*SFBits, i) == BIT_TRUE)
410 Insn.push_back(BIT_UNSET);
411 else
412 Insn.push_back(bitFromBits(Bits, i));
413 }
Owen Andersond8c87882011-02-18 21:51:29 +0000414 }
415
Owen Andersond8c87882011-02-18 21:51:29 +0000416 // Populates the field of the insn given the start position and the number of
417 // consecutive bits to scan for.
418 //
419 // Returns false if there exists any uninitialized bit value in the range.
420 // Returns true, otherwise.
421 bool fieldFromInsn(uint64_t &Field, insn_t &Insn, unsigned StartBit,
Craig Topperd9360452012-03-16 01:19:24 +0000422 unsigned NumBits) const;
Owen Andersond8c87882011-02-18 21:51:29 +0000423
424 /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
425 /// filter array as a series of chars.
Craig Toppereb5cd612012-03-16 05:58:09 +0000426 void dumpFilterArray(raw_ostream &o,
427 const std::vector<bit_value_t> & filter) const;
Owen Andersond8c87882011-02-18 21:51:29 +0000428
429 /// dumpStack - dumpStack traverses the filter chooser chain and calls
430 /// dumpFilterArray on each filter chooser up to the top level one.
Craig Toppereb5cd612012-03-16 05:58:09 +0000431 void dumpStack(raw_ostream &o, const char *prefix) const;
Owen Andersond8c87882011-02-18 21:51:29 +0000432
433 Filter &bestFilter() {
434 assert(BestIndex != -1 && "BestIndex not set");
435 return Filters[BestIndex];
436 }
437
Craig Toppereb5cd612012-03-16 05:58:09 +0000438 bool PositionFiltered(unsigned i) const {
Owen Andersond8c87882011-02-18 21:51:29 +0000439 return ValueSet(FilterBitValues[i]);
440 }
441
442 // Calculates the island(s) needed to decode the instruction.
443 // This returns a lit of undecoded bits of an instructions, for example,
444 // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
445 // decoded bits in order to verify that the instruction matches the Opcode.
446 unsigned getIslands(std::vector<unsigned> &StartBits,
Craig Topperd9360452012-03-16 01:19:24 +0000447 std::vector<unsigned> &EndBits,
Craig Toppereb5cd612012-03-16 05:58:09 +0000448 std::vector<uint64_t> &FieldVals,
449 const insn_t &Insn) const;
Owen Andersond8c87882011-02-18 21:51:29 +0000450
James Molloya5d58562011-09-07 19:42:28 +0000451 // Emits code to check the Predicates member of an instruction are true.
452 // Returns true if predicate matches were emitted, false otherwise.
Craig Toppereb5cd612012-03-16 05:58:09 +0000453 bool emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
454 unsigned Opc) const;
James Molloya5d58562011-09-07 19:42:28 +0000455
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000456 bool doesOpcodeNeedPredicate(unsigned Opc) const;
457 unsigned getPredicateIndex(DecoderTableInfo &TableInfo, StringRef P) const;
458 void emitPredicateTableEntry(DecoderTableInfo &TableInfo,
459 unsigned Opc) const;
James Molloy3015dfb2012-02-09 10:56:31 +0000460
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000461 void emitSoftFailTableEntry(DecoderTableInfo &TableInfo,
462 unsigned Opc) const;
463
464 // Emits table entries to decode the singleton.
465 void emitSingletonTableEntry(DecoderTableInfo &TableInfo,
466 unsigned Opc) const;
Owen Andersond8c87882011-02-18 21:51:29 +0000467
468 // Emits code to decode the singleton, and then to decode the rest.
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000469 void emitSingletonTableEntry(DecoderTableInfo &TableInfo,
470 const Filter &Best) const;
Owen Andersond8c87882011-02-18 21:51:29 +0000471
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000472 void emitBinaryParser(raw_ostream &o, unsigned &Indentation,
Petr Pavlud2e1e422015-07-15 08:04:27 +0000473 const OperandInfo &OpInfo,
474 bool &OpHasCompleteDecoder) const;
Owen Andersond1e38df2011-07-28 21:54:31 +0000475
Petr Pavlud2e1e422015-07-15 08:04:27 +0000476 void emitDecoder(raw_ostream &OS, unsigned Indentation, unsigned Opc,
477 bool &HasCompleteDecoder) const;
478 unsigned getDecoderIndex(DecoderSet &Decoders, unsigned Opc,
479 bool &HasCompleteDecoder) const;
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000480
Owen Andersond8c87882011-02-18 21:51:29 +0000481 // Assign a single filter and run with it.
Craig Toppereb5cd612012-03-16 05:58:09 +0000482 void runSingleFilter(unsigned startBit, unsigned numBit, bool mixed);
Owen Andersond8c87882011-02-18 21:51:29 +0000483
484 // reportRegion is a helper function for filterProcessor to mark a region as
485 // eligible for use as a filter region.
486 void reportRegion(bitAttr_t RA, unsigned StartBit, unsigned BitIndex,
Craig Topperd9360452012-03-16 01:19:24 +0000487 bool AllowMixed);
Owen Andersond8c87882011-02-18 21:51:29 +0000488
489 // FilterProcessor scans the well-known encoding bits of the instructions and
490 // builds up a list of candidate filters. It chooses the best filter and
491 // recursively descends down the decoding tree.
492 bool filterProcessor(bool AllowMixed, bool Greedy = true);
493
494 // Decides on the best configuration of filter(s) to use in order to decode
495 // the instructions. A conflict of instructions may occur, in which case we
496 // dump the conflict set to the standard error.
497 void doFilter();
498
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000499public:
500 // emitTableEntries - Emit state machine entries to decode our share of
501 // instructions.
502 void emitTableEntries(DecoderTableInfo &TableInfo) const;
Owen Andersond8c87882011-02-18 21:51:29 +0000503};
Eugene Zelenkoc02caf52016-11-30 17:48:10 +0000504
505} // end anonymous namespace
Owen Andersond8c87882011-02-18 21:51:29 +0000506
507///////////////////////////
508// //
Craig Topper797ba552012-03-16 00:56:01 +0000509// Filter Implementation //
Owen Andersond8c87882011-02-18 21:51:29 +0000510// //
511///////////////////////////
512
Craig Topper5c581572014-09-03 05:49:07 +0000513Filter::Filter(Filter &&f)
Craig Topperd9360452012-03-16 01:19:24 +0000514 : Owner(f.Owner), StartBit(f.StartBit), NumBits(f.NumBits), Mixed(f.Mixed),
Craig Topper5c581572014-09-03 05:49:07 +0000515 FilteredInstructions(std::move(f.FilteredInstructions)),
516 VariableInstructions(std::move(f.VariableInstructions)),
517 FilterChooserMap(std::move(f.FilterChooserMap)), NumFiltered(f.NumFiltered),
Craig Topperd9360452012-03-16 01:19:24 +0000518 LastOpcFiltered(f.LastOpcFiltered) {
Owen Andersond8c87882011-02-18 21:51:29 +0000519}
520
521Filter::Filter(FilterChooser &owner, unsigned startBit, unsigned numBits,
Craig Topperd9360452012-03-16 01:19:24 +0000522 bool mixed)
523 : Owner(&owner), StartBit(startBit), NumBits(numBits), Mixed(mixed) {
Owen Andersonf1a00902011-07-19 21:06:00 +0000524 assert(StartBit + NumBits - 1 < Owner->BitWidth);
Owen Andersond8c87882011-02-18 21:51:29 +0000525
526 NumFiltered = 0;
527 LastOpcFiltered = 0;
Owen Andersond8c87882011-02-18 21:51:29 +0000528
529 for (unsigned i = 0, e = Owner->Opcodes.size(); i != e; ++i) {
530 insn_t Insn;
531
532 // Populates the insn given the uid.
533 Owner->insnWithID(Insn, Owner->Opcodes[i]);
534
535 uint64_t Field;
536 // Scans the segment for possibly well-specified encoding bits.
537 bool ok = Owner->fieldFromInsn(Field, Insn, StartBit, NumBits);
538
539 if (ok) {
540 // The encoding bits are well-known. Lets add the uid of the
541 // instruction into the bucket keyed off the constant field value.
542 LastOpcFiltered = Owner->Opcodes[i];
543 FilteredInstructions[Field].push_back(LastOpcFiltered);
544 ++NumFiltered;
545 } else {
Craig Topper797ba552012-03-16 00:56:01 +0000546 // Some of the encoding bit(s) are unspecified. This contributes to
Owen Andersond8c87882011-02-18 21:51:29 +0000547 // one additional member of "Variable" instructions.
548 VariableInstructions.push_back(Owner->Opcodes[i]);
Owen Andersond8c87882011-02-18 21:51:29 +0000549 }
550 }
551
552 assert((FilteredInstructions.size() + VariableInstructions.size() > 0)
553 && "Filter returns no instruction categories");
554}
555
Owen Andersond8c87882011-02-18 21:51:29 +0000556// Divides the decoding task into sub tasks and delegates them to the
557// inferior FilterChooser's.
558//
559// A special case arises when there's only one entry in the filtered
560// instructions. In order to unambiguously decode the singleton, we need to
561// match the remaining undecoded encoding bits against the singleton.
562void Filter::recurse() {
Owen Andersond8c87882011-02-18 21:51:29 +0000563 // Starts by inheriting our parent filter chooser's filter bit values.
Owen Andersonf1a00902011-07-19 21:06:00 +0000564 std::vector<bit_value_t> BitValueArray(Owner->FilterBitValues);
Owen Andersond8c87882011-02-18 21:51:29 +0000565
Alexander Kornienkob4c62672015-01-15 11:41:30 +0000566 if (!VariableInstructions.empty()) {
Owen Andersond8c87882011-02-18 21:51:29 +0000567 // Conservatively marks each segment position as BIT_UNSET.
Craig Topper8cd9eae2012-08-17 05:42:16 +0000568 for (unsigned bitIndex = 0; bitIndex < NumBits; ++bitIndex)
Owen Andersond8c87882011-02-18 21:51:29 +0000569 BitValueArray[StartBit + bitIndex] = BIT_UNSET;
570
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000571 // Delegates to an inferior filter chooser for further processing on this
Owen Andersond8c87882011-02-18 21:51:29 +0000572 // group of instructions whose segment values are variable.
Yaron Keren8f2394e2014-09-03 08:22:30 +0000573 FilterChooserMap.insert(
574 std::make_pair(-1U, llvm::make_unique<FilterChooser>(
575 Owner->AllInstructions, VariableInstructions,
576 Owner->Operands, BitValueArray, *Owner)));
Owen Andersond8c87882011-02-18 21:51:29 +0000577 }
578
579 // No need to recurse for a singleton filtered instruction.
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000580 // See also Filter::emit*().
Owen Andersond8c87882011-02-18 21:51:29 +0000581 if (getNumFiltered() == 1) {
Owen Andersond8c87882011-02-18 21:51:29 +0000582 assert(FilterChooserMap.size() == 1);
583 return;
584 }
585
586 // Otherwise, create sub choosers.
Craig Topper1b40b342014-12-13 05:12:19 +0000587 for (const auto &Inst : FilteredInstructions) {
Owen Andersond8c87882011-02-18 21:51:29 +0000588
589 // Marks all the segment positions with either BIT_TRUE or BIT_FALSE.
Craig Topper8cd9eae2012-08-17 05:42:16 +0000590 for (unsigned bitIndex = 0; bitIndex < NumBits; ++bitIndex) {
Craig Topper1b40b342014-12-13 05:12:19 +0000591 if (Inst.first & (1ULL << bitIndex))
Owen Andersond8c87882011-02-18 21:51:29 +0000592 BitValueArray[StartBit + bitIndex] = BIT_TRUE;
593 else
594 BitValueArray[StartBit + bitIndex] = BIT_FALSE;
595 }
596
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000597 // Delegates to an inferior filter chooser for further processing on this
Owen Andersond8c87882011-02-18 21:51:29 +0000598 // category of instructions.
Craig Topper732b0262014-09-03 06:07:54 +0000599 FilterChooserMap.insert(std::make_pair(
Craig Topper1b40b342014-12-13 05:12:19 +0000600 Inst.first, llvm::make_unique<FilterChooser>(
601 Owner->AllInstructions, Inst.second,
Yaron Keren8f2394e2014-09-03 08:22:30 +0000602 Owner->Operands, BitValueArray, *Owner)));
Owen Andersond8c87882011-02-18 21:51:29 +0000603 }
604}
605
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000606static void resolveTableFixups(DecoderTable &Table, const FixupList &Fixups,
607 uint32_t DestIdx) {
608 // Any NumToSkip fixups in the current scope can resolve to the
609 // current location.
610 for (FixupList::const_reverse_iterator I = Fixups.rbegin(),
611 E = Fixups.rend();
612 I != E; ++I) {
613 // Calculate the distance from the byte following the fixup entry byte
614 // to the destination. The Target is calculated from after the 16-bit
615 // NumToSkip entry itself, so subtract two from the displacement here
616 // to account for that.
617 uint32_t FixupIdx = *I;
Sander de Smalenc13d5962018-07-05 10:39:15 +0000618 uint32_t Delta = DestIdx - FixupIdx - 3;
619 // Our NumToSkip entries are 24-bits. Make sure our table isn't too
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000620 // big.
Sander de Smalenc13d5962018-07-05 10:39:15 +0000621 assert(Delta < (1u << 24));
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000622 Table[FixupIdx] = (uint8_t)Delta;
623 Table[FixupIdx + 1] = (uint8_t)(Delta >> 8);
Sander de Smalenc13d5962018-07-05 10:39:15 +0000624 Table[FixupIdx + 2] = (uint8_t)(Delta >> 16);
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000625 }
626}
Owen Andersond8c87882011-02-18 21:51:29 +0000627
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000628// Emit table entries to decode instructions given a segment or segments
629// of bits.
630void Filter::emitTableEntry(DecoderTableInfo &TableInfo) const {
631 TableInfo.Table.push_back(MCD::OPC_ExtractField);
632 TableInfo.Table.push_back(StartBit);
633 TableInfo.Table.push_back(NumBits);
Owen Andersond8c87882011-02-18 21:51:29 +0000634
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000635 // A new filter entry begins a new scope for fixup resolution.
Benjamin Kramer9589ff82015-05-29 19:43:39 +0000636 TableInfo.FixupStack.emplace_back();
Owen Andersond8c87882011-02-18 21:51:29 +0000637
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000638 DecoderTable &Table = TableInfo.Table;
639
640 size_t PrevFilter = 0;
641 bool HasFallthrough = false;
Craig Topper1b40b342014-12-13 05:12:19 +0000642 for (auto &Filter : FilterChooserMap) {
Owen Andersond8c87882011-02-18 21:51:29 +0000643 // Field value -1 implies a non-empty set of variable instructions.
644 // See also recurse().
Craig Topper1b40b342014-12-13 05:12:19 +0000645 if (Filter.first == (unsigned)-1) {
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000646 HasFallthrough = true;
Owen Andersond8c87882011-02-18 21:51:29 +0000647
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000648 // Each scope should always have at least one filter value to check
649 // for.
650 assert(PrevFilter != 0 && "empty filter set!");
651 FixupList &CurScope = TableInfo.FixupStack.back();
652 // Resolve any NumToSkip fixups in the current scope.
653 resolveTableFixups(Table, CurScope, Table.size());
654 CurScope.clear();
655 PrevFilter = 0; // Don't re-process the filter's fallthrough.
656 } else {
657 Table.push_back(MCD::OPC_FilterValue);
658 // Encode and emit the value to filter against.
Sander de Smalenc13d5962018-07-05 10:39:15 +0000659 uint8_t Buffer[16];
Craig Topper1b40b342014-12-13 05:12:19 +0000660 unsigned Len = encodeULEB128(Filter.first, Buffer);
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000661 Table.insert(Table.end(), Buffer, Buffer + Len);
662 // Reserve space for the NumToSkip entry. We'll backpatch the value
663 // later.
664 PrevFilter = Table.size();
665 Table.push_back(0);
666 Table.push_back(0);
Sander de Smalenc13d5962018-07-05 10:39:15 +0000667 Table.push_back(0);
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000668 }
Owen Andersond8c87882011-02-18 21:51:29 +0000669
670 // We arrive at a category of instructions with the same segment value.
671 // Now delegate to the sub filter chooser for further decodings.
672 // The case may fallthrough, which happens if the remaining well-known
673 // encoding bits do not match exactly.
Craig Topper1b40b342014-12-13 05:12:19 +0000674 Filter.second->emitTableEntries(TableInfo);
Owen Andersond8c87882011-02-18 21:51:29 +0000675
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000676 // Now that we've emitted the body of the handler, update the NumToSkip
677 // of the filter itself to be able to skip forward when false. Subtract
678 // two as to account for the width of the NumToSkip field itself.
679 if (PrevFilter) {
Sander de Smalenc13d5962018-07-05 10:39:15 +0000680 uint32_t NumToSkip = Table.size() - PrevFilter - 3;
681 assert(NumToSkip < (1u << 24) && "disassembler decoding table too large!");
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000682 Table[PrevFilter] = (uint8_t)NumToSkip;
683 Table[PrevFilter + 1] = (uint8_t)(NumToSkip >> 8);
Sander de Smalenc13d5962018-07-05 10:39:15 +0000684 Table[PrevFilter + 2] = (uint8_t)(NumToSkip >> 16);
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000685 }
Owen Andersond8c87882011-02-18 21:51:29 +0000686 }
687
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000688 // Any remaining unresolved fixups bubble up to the parent fixup scope.
689 assert(TableInfo.FixupStack.size() > 1 && "fixup stack underflow!");
690 FixupScopeList::iterator Source = TableInfo.FixupStack.end() - 1;
691 FixupScopeList::iterator Dest = Source - 1;
692 Dest->insert(Dest->end(), Source->begin(), Source->end());
693 TableInfo.FixupStack.pop_back();
694
695 // If there is no fallthrough, then the final filter should get fixed
696 // up according to the enclosing scope rather than the current position.
697 if (!HasFallthrough)
698 TableInfo.FixupStack.back().push_back(PrevFilter);
Owen Andersond8c87882011-02-18 21:51:29 +0000699}
700
701// Returns the number of fanout produced by the filter. More fanout implies
702// the filter distinguishes more categories of instructions.
703unsigned Filter::usefulness() const {
Alexander Kornienkob4c62672015-01-15 11:41:30 +0000704 if (!VariableInstructions.empty())
Owen Andersond8c87882011-02-18 21:51:29 +0000705 return FilteredInstructions.size();
706 else
707 return FilteredInstructions.size() + 1;
708}
709
710//////////////////////////////////
711// //
712// Filterchooser Implementation //
713// //
714//////////////////////////////////
715
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000716// Emit the decoder state machine table.
717void FixedLenDecoderEmitter::emitTable(formatted_raw_ostream &OS,
718 DecoderTable &Table,
719 unsigned Indentation,
720 unsigned BitWidth,
721 StringRef Namespace) const {
722 OS.indent(Indentation) << "static const uint8_t DecoderTable" << Namespace
723 << BitWidth << "[] = {\n";
Owen Andersond8c87882011-02-18 21:51:29 +0000724
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000725 Indentation += 2;
Owen Andersond8c87882011-02-18 21:51:29 +0000726
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000727 // FIXME: We may be able to use the NumToSkip values to recover
728 // appropriate indentation levels.
729 DecoderTable::const_iterator I = Table.begin();
730 DecoderTable::const_iterator E = Table.end();
731 while (I != E) {
732 assert (I < E && "incomplete decode table entry!");
Owen Andersond8c87882011-02-18 21:51:29 +0000733
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000734 uint64_t Pos = I - Table.begin();
735 OS << "/* " << Pos << " */";
736 OS.PadToColumn(12);
Owen Andersond8c87882011-02-18 21:51:29 +0000737
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000738 switch (*I) {
739 default:
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000740 PrintFatalError("invalid decode table opcode");
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000741 case MCD::OPC_ExtractField: {
742 ++I;
743 unsigned Start = *I++;
744 unsigned Len = *I++;
745 OS.indent(Indentation) << "MCD::OPC_ExtractField, " << Start << ", "
746 << Len << ", // Inst{";
747 if (Len > 1)
748 OS << (Start + Len - 1) << "-";
749 OS << Start << "} ...\n";
750 break;
751 }
752 case MCD::OPC_FilterValue: {
753 ++I;
754 OS.indent(Indentation) << "MCD::OPC_FilterValue, ";
755 // The filter value is ULEB128 encoded.
756 while (*I >= 128)
Craig Topperac8a9912016-01-31 01:55:15 +0000757 OS << (unsigned)*I++ << ", ";
758 OS << (unsigned)*I++ << ", ";
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000759
Sander de Smalenc13d5962018-07-05 10:39:15 +0000760 // 24-bit numtoskip value.
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000761 uint8_t Byte = *I++;
762 uint32_t NumToSkip = Byte;
Craig Topperac8a9912016-01-31 01:55:15 +0000763 OS << (unsigned)Byte << ", ";
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000764 Byte = *I++;
Craig Topperac8a9912016-01-31 01:55:15 +0000765 OS << (unsigned)Byte << ", ";
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000766 NumToSkip |= Byte << 8;
Sander de Smalenc13d5962018-07-05 10:39:15 +0000767 Byte = *I++;
768 OS << utostr(Byte) << ", ";
769 NumToSkip |= Byte << 16;
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000770 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
771 break;
772 }
773 case MCD::OPC_CheckField: {
774 ++I;
775 unsigned Start = *I++;
776 unsigned Len = *I++;
777 OS.indent(Indentation) << "MCD::OPC_CheckField, " << Start << ", "
778 << Len << ", ";// << Val << ", " << NumToSkip << ",\n";
779 // ULEB128 encoded field value.
780 for (; *I >= 128; ++I)
Craig Topperac8a9912016-01-31 01:55:15 +0000781 OS << (unsigned)*I << ", ";
782 OS << (unsigned)*I++ << ", ";
Sander de Smalenc13d5962018-07-05 10:39:15 +0000783 // 24-bit numtoskip value.
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000784 uint8_t Byte = *I++;
785 uint32_t NumToSkip = Byte;
Craig Topperac8a9912016-01-31 01:55:15 +0000786 OS << (unsigned)Byte << ", ";
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000787 Byte = *I++;
Craig Topperac8a9912016-01-31 01:55:15 +0000788 OS << (unsigned)Byte << ", ";
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000789 NumToSkip |= Byte << 8;
Sander de Smalenc13d5962018-07-05 10:39:15 +0000790 Byte = *I++;
791 OS << utostr(Byte) << ", ";
792 NumToSkip |= Byte << 16;
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000793 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
794 break;
795 }
796 case MCD::OPC_CheckPredicate: {
797 ++I;
798 OS.indent(Indentation) << "MCD::OPC_CheckPredicate, ";
799 for (; *I >= 128; ++I)
Craig Topperac8a9912016-01-31 01:55:15 +0000800 OS << (unsigned)*I << ", ";
801 OS << (unsigned)*I++ << ", ";
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000802
Sander de Smalenc13d5962018-07-05 10:39:15 +0000803 // 24-bit numtoskip value.
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000804 uint8_t Byte = *I++;
805 uint32_t NumToSkip = Byte;
Craig Topperac8a9912016-01-31 01:55:15 +0000806 OS << (unsigned)Byte << ", ";
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000807 Byte = *I++;
Craig Topperac8a9912016-01-31 01:55:15 +0000808 OS << (unsigned)Byte << ", ";
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000809 NumToSkip |= Byte << 8;
Sander de Smalenc13d5962018-07-05 10:39:15 +0000810 Byte = *I++;
811 OS << utostr(Byte) << ", ";
812 NumToSkip |= Byte << 16;
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000813 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
814 break;
815 }
Petr Pavlud2e1e422015-07-15 08:04:27 +0000816 case MCD::OPC_Decode:
817 case MCD::OPC_TryDecode: {
818 bool IsTry = *I == MCD::OPC_TryDecode;
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000819 ++I;
820 // Extract the ULEB128 encoded Opcode to a buffer.
Sander de Smalenc13d5962018-07-05 10:39:15 +0000821 uint8_t Buffer[16], *p = Buffer;
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000822 while ((*p++ = *I++) >= 128)
823 assert((p - Buffer) <= (ptrdiff_t)sizeof(Buffer)
824 && "ULEB128 value too large!");
825 // Decode the Opcode value.
826 unsigned Opc = decodeULEB128(Buffer);
Petr Pavlud2e1e422015-07-15 08:04:27 +0000827 OS.indent(Indentation) << "MCD::OPC_" << (IsTry ? "Try" : "")
828 << "Decode, ";
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000829 for (p = Buffer; *p >= 128; ++p)
Craig Topperac8a9912016-01-31 01:55:15 +0000830 OS << (unsigned)*p << ", ";
831 OS << (unsigned)*p << ", ";
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000832
833 // Decoder index.
834 for (; *I >= 128; ++I)
Craig Topperac8a9912016-01-31 01:55:15 +0000835 OS << (unsigned)*I << ", ";
836 OS << (unsigned)*I++ << ", ";
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000837
Petr Pavlud2e1e422015-07-15 08:04:27 +0000838 if (!IsTry) {
Daniel Sanders0de70682018-12-13 16:17:54 +0000839 OS << "// Opcode: " << NumberedEncodings[Opc] << "\n";
Petr Pavlud2e1e422015-07-15 08:04:27 +0000840 break;
841 }
842
843 // Fallthrough for OPC_TryDecode.
844
Sander de Smalenc13d5962018-07-05 10:39:15 +0000845 // 24-bit numtoskip value.
Petr Pavlud2e1e422015-07-15 08:04:27 +0000846 uint8_t Byte = *I++;
847 uint32_t NumToSkip = Byte;
Craig Topperac8a9912016-01-31 01:55:15 +0000848 OS << (unsigned)Byte << ", ";
Petr Pavlud2e1e422015-07-15 08:04:27 +0000849 Byte = *I++;
Craig Topperac8a9912016-01-31 01:55:15 +0000850 OS << (unsigned)Byte << ", ";
Petr Pavlud2e1e422015-07-15 08:04:27 +0000851 NumToSkip |= Byte << 8;
Sander de Smalenc13d5962018-07-05 10:39:15 +0000852 Byte = *I++;
853 OS << utostr(Byte) << ", ";
854 NumToSkip |= Byte << 16;
Petr Pavlud2e1e422015-07-15 08:04:27 +0000855
Daniel Sanders0de70682018-12-13 16:17:54 +0000856 OS << "// Opcode: " << NumberedEncodings[Opc]
Petr Pavlud2e1e422015-07-15 08:04:27 +0000857 << ", skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000858 break;
859 }
860 case MCD::OPC_SoftFail: {
861 ++I;
862 OS.indent(Indentation) << "MCD::OPC_SoftFail";
863 // Positive mask
864 uint64_t Value = 0;
865 unsigned Shift = 0;
866 do {
Craig Topperac8a9912016-01-31 01:55:15 +0000867 OS << ", " << (unsigned)*I;
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000868 Value += (*I & 0x7f) << Shift;
869 Shift += 7;
870 } while (*I++ >= 128);
Craig Topperac8a9912016-01-31 01:55:15 +0000871 if (Value > 127) {
872 OS << " /* 0x";
873 OS.write_hex(Value);
874 OS << " */";
875 }
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000876 // Negative mask
877 Value = 0;
878 Shift = 0;
879 do {
Craig Topperac8a9912016-01-31 01:55:15 +0000880 OS << ", " << (unsigned)*I;
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000881 Value += (*I & 0x7f) << Shift;
882 Shift += 7;
883 } while (*I++ >= 128);
Craig Topperac8a9912016-01-31 01:55:15 +0000884 if (Value > 127) {
885 OS << " /* 0x";
886 OS.write_hex(Value);
887 OS << " */";
888 }
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000889 OS << ",\n";
890 break;
891 }
892 case MCD::OPC_Fail: {
893 ++I;
894 OS.indent(Indentation) << "MCD::OPC_Fail,\n";
895 break;
896 }
897 }
898 }
899 OS.indent(Indentation) << "0\n";
900
901 Indentation -= 2;
902
903 OS.indent(Indentation) << "};\n\n";
904}
905
906void FixedLenDecoderEmitter::
907emitPredicateFunction(formatted_raw_ostream &OS, PredicateSet &Predicates,
908 unsigned Indentation) const {
909 // The predicate function is just a big switch statement based on the
910 // input predicate index.
911 OS.indent(Indentation) << "static bool checkDecoderPredicate(unsigned Idx, "
Michael Kupersteind714fcf2015-05-26 10:47:10 +0000912 << "const FeatureBitset& Bits) {\n";
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000913 Indentation += 2;
Aaron Ballman54911a52013-07-15 16:53:32 +0000914 if (!Predicates.empty()) {
915 OS.indent(Indentation) << "switch (Idx) {\n";
916 OS.indent(Indentation) << "default: llvm_unreachable(\"Invalid index!\");\n";
917 unsigned Index = 0;
Craig Topper1b40b342014-12-13 05:12:19 +0000918 for (const auto &Predicate : Predicates) {
919 OS.indent(Indentation) << "case " << Index++ << ":\n";
920 OS.indent(Indentation+2) << "return (" << Predicate << ");\n";
Aaron Ballman54911a52013-07-15 16:53:32 +0000921 }
922 OS.indent(Indentation) << "}\n";
923 } else {
924 // No case statement to emit
925 OS.indent(Indentation) << "llvm_unreachable(\"Invalid index!\");\n";
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000926 }
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000927 Indentation -= 2;
928 OS.indent(Indentation) << "}\n\n";
929}
930
931void FixedLenDecoderEmitter::
932emitDecoderFunction(formatted_raw_ostream &OS, DecoderSet &Decoders,
933 unsigned Indentation) const {
934 // The decoder function is just a big switch statement based on the
935 // input decoder index.
936 OS.indent(Indentation) << "template<typename InsnType>\n";
937 OS.indent(Indentation) << "static DecodeStatus decodeToMCInst(DecodeStatus S,"
938 << " unsigned Idx, InsnType insn, MCInst &MI,\n";
939 OS.indent(Indentation) << " uint64_t "
Petr Pavlud2e1e422015-07-15 08:04:27 +0000940 << "Address, const void *Decoder, bool &DecodeComplete) {\n";
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000941 Indentation += 2;
Petr Pavlud2e1e422015-07-15 08:04:27 +0000942 OS.indent(Indentation) << "DecodeComplete = true;\n";
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000943 OS.indent(Indentation) << "InsnType tmp;\n";
944 OS.indent(Indentation) << "switch (Idx) {\n";
945 OS.indent(Indentation) << "default: llvm_unreachable(\"Invalid index!\");\n";
946 unsigned Index = 0;
Craig Topper1b40b342014-12-13 05:12:19 +0000947 for (const auto &Decoder : Decoders) {
948 OS.indent(Indentation) << "case " << Index++ << ":\n";
949 OS << Decoder;
Jim Grosbachfc1a1612012-08-14 19:06:05 +0000950 OS.indent(Indentation+2) << "return S;\n";
951 }
952 OS.indent(Indentation) << "}\n";
953 Indentation -= 2;
954 OS.indent(Indentation) << "}\n\n";
Owen Andersond8c87882011-02-18 21:51:29 +0000955}
956
957// Populates the field of the insn given the start position and the number of
958// consecutive bits to scan for.
959//
960// Returns false if and on the first uninitialized bit value encountered.
961// Returns true, otherwise.
962bool FilterChooser::fieldFromInsn(uint64_t &Field, insn_t &Insn,
Craig Toppereb5cd612012-03-16 05:58:09 +0000963 unsigned StartBit, unsigned NumBits) const {
Owen Andersond8c87882011-02-18 21:51:29 +0000964 Field = 0;
965
966 for (unsigned i = 0; i < NumBits; ++i) {
967 if (Insn[StartBit + i] == BIT_UNSET)
968 return false;
969
970 if (Insn[StartBit + i] == BIT_TRUE)
971 Field = Field | (1ULL << i);
972 }
973
974 return true;
975}
976
977/// dumpFilterArray - dumpFilterArray prints out debugging info for the given
978/// filter array as a series of chars.
979void FilterChooser::dumpFilterArray(raw_ostream &o,
Craig Toppereb5cd612012-03-16 05:58:09 +0000980 const std::vector<bit_value_t> &filter) const {
Craig Topper8cd9eae2012-08-17 05:42:16 +0000981 for (unsigned bitIndex = BitWidth; bitIndex > 0; bitIndex--) {
Owen Andersond8c87882011-02-18 21:51:29 +0000982 switch (filter[bitIndex - 1]) {
983 case BIT_UNFILTERED:
984 o << ".";
985 break;
986 case BIT_UNSET:
987 o << "_";
988 break;
989 case BIT_TRUE:
990 o << "1";
991 break;
992 case BIT_FALSE:
993 o << "0";
994 break;
995 }
996 }
997}
998
999/// dumpStack - dumpStack traverses the filter chooser chain and calls
1000/// dumpFilterArray on each filter chooser up to the top level one.
Craig Toppereb5cd612012-03-16 05:58:09 +00001001void FilterChooser::dumpStack(raw_ostream &o, const char *prefix) const {
1002 const FilterChooser *current = this;
Owen Andersond8c87882011-02-18 21:51:29 +00001003
1004 while (current) {
1005 o << prefix;
1006 dumpFilterArray(o, current->FilterBitValues);
1007 o << '\n';
1008 current = current->Parent;
1009 }
1010}
1011
Owen Andersond8c87882011-02-18 21:51:29 +00001012// Calculates the island(s) needed to decode the instruction.
1013// This returns a list of undecoded bits of an instructions, for example,
1014// Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
1015// decoded bits in order to verify that the instruction matches the Opcode.
1016unsigned FilterChooser::getIslands(std::vector<unsigned> &StartBits,
Craig Topperd9360452012-03-16 01:19:24 +00001017 std::vector<unsigned> &EndBits,
1018 std::vector<uint64_t> &FieldVals,
Craig Toppereb5cd612012-03-16 05:58:09 +00001019 const insn_t &Insn) const {
Owen Andersond8c87882011-02-18 21:51:29 +00001020 unsigned Num, BitNo;
1021 Num = BitNo = 0;
1022
1023 uint64_t FieldVal = 0;
1024
1025 // 0: Init
1026 // 1: Water (the bit value does not affect decoding)
1027 // 2: Island (well-known bit value needed for decoding)
1028 int State = 0;
1029 int Val = -1;
1030
Owen Andersonf1a00902011-07-19 21:06:00 +00001031 for (unsigned i = 0; i < BitWidth; ++i) {
Owen Andersond8c87882011-02-18 21:51:29 +00001032 Val = Value(Insn[i]);
1033 bool Filtered = PositionFiltered(i);
1034 switch (State) {
Craig Topper655b8de2012-02-05 07:21:30 +00001035 default: llvm_unreachable("Unreachable code!");
Owen Andersond8c87882011-02-18 21:51:29 +00001036 case 0:
1037 case 1:
1038 if (Filtered || Val == -1)
1039 State = 1; // Still in Water
1040 else {
1041 State = 2; // Into the Island
1042 BitNo = 0;
1043 StartBits.push_back(i);
1044 FieldVal = Val;
1045 }
1046 break;
1047 case 2:
1048 if (Filtered || Val == -1) {
1049 State = 1; // Into the Water
1050 EndBits.push_back(i - 1);
1051 FieldVals.push_back(FieldVal);
1052 ++Num;
1053 } else {
1054 State = 2; // Still in Island
1055 ++BitNo;
1056 FieldVal = FieldVal | Val << BitNo;
1057 }
1058 break;
1059 }
1060 }
1061 // If we are still in Island after the loop, do some housekeeping.
1062 if (State == 2) {
Owen Andersonf1a00902011-07-19 21:06:00 +00001063 EndBits.push_back(BitWidth - 1);
Owen Andersond8c87882011-02-18 21:51:29 +00001064 FieldVals.push_back(FieldVal);
1065 ++Num;
1066 }
1067
1068 assert(StartBits.size() == Num && EndBits.size() == Num &&
1069 FieldVals.size() == Num);
1070 return Num;
1071}
1072
Owen Andersond1e38df2011-07-28 21:54:31 +00001073void FilterChooser::emitBinaryParser(raw_ostream &o, unsigned &Indentation,
Petr Pavlud2e1e422015-07-15 08:04:27 +00001074 const OperandInfo &OpInfo,
1075 bool &OpHasCompleteDecoder) const {
Craig Toppereb5cd612012-03-16 05:58:09 +00001076 const std::string &Decoder = OpInfo.Decoder;
Owen Andersond1e38df2011-07-28 21:54:31 +00001077
Craig Topper2895d952014-09-27 05:26:42 +00001078 if (OpInfo.numFields() != 1)
Craig Topperc0564832012-08-17 05:16:15 +00001079 o.indent(Indentation) << "tmp = 0;\n";
Craig Topper2895d952014-09-27 05:26:42 +00001080
1081 for (const EncodingField &EF : OpInfo) {
1082 o.indent(Indentation) << "tmp ";
1083 if (OpInfo.numFields() != 1) o << '|';
1084 o << "= fieldFromInstruction"
1085 << "(insn, " << EF.Base << ", " << EF.Width << ')';
1086 if (OpInfo.numFields() != 1 || EF.Offset != 0)
1087 o << " << " << EF.Offset;
1088 o << ";\n";
Owen Andersond1e38df2011-07-28 21:54:31 +00001089 }
1090
Petr Pavlud2e1e422015-07-15 08:04:27 +00001091 if (Decoder != "") {
1092 OpHasCompleteDecoder = OpInfo.HasCompleteDecoder;
Craig Topperc0564832012-08-17 05:16:15 +00001093 o.indent(Indentation) << Emitter->GuardPrefix << Decoder
Petr Pavlud2e1e422015-07-15 08:04:27 +00001094 << "(MI, tmp, Address, Decoder)"
1095 << Emitter->GuardPostfix
1096 << " { " << (OpHasCompleteDecoder ? "" : "DecodeComplete = false; ")
1097 << "return MCDisassembler::Fail; }\n";
1098 } else {
1099 OpHasCompleteDecoder = true;
Jim Grosbachdb703aa2015-05-13 18:37:00 +00001100 o.indent(Indentation) << "MI.addOperand(MCOperand::createImm(tmp));\n";
Petr Pavlud2e1e422015-07-15 08:04:27 +00001101 }
Owen Andersond1e38df2011-07-28 21:54:31 +00001102}
1103
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001104void FilterChooser::emitDecoder(raw_ostream &OS, unsigned Indentation,
Petr Pavlud2e1e422015-07-15 08:04:27 +00001105 unsigned Opc, bool &HasCompleteDecoder) const {
1106 HasCompleteDecoder = true;
1107
Craig Topper1b40b342014-12-13 05:12:19 +00001108 for (const auto &Op : Operands.find(Opc)->second) {
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001109 // If a custom instruction decoder was specified, use that.
Eugene Zelenkoc02caf52016-11-30 17:48:10 +00001110 if (Op.numFields() == 0 && !Op.Decoder.empty()) {
Petr Pavlud2e1e422015-07-15 08:04:27 +00001111 HasCompleteDecoder = Op.HasCompleteDecoder;
Craig Topper1b40b342014-12-13 05:12:19 +00001112 OS.indent(Indentation) << Emitter->GuardPrefix << Op.Decoder
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001113 << "(MI, insn, Address, Decoder)"
Petr Pavlud2e1e422015-07-15 08:04:27 +00001114 << Emitter->GuardPostfix
1115 << " { " << (HasCompleteDecoder ? "" : "DecodeComplete = false; ")
1116 << "return MCDisassembler::Fail; }\n";
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001117 break;
1118 }
1119
Petr Pavlud2e1e422015-07-15 08:04:27 +00001120 bool OpHasCompleteDecoder;
1121 emitBinaryParser(OS, Indentation, Op, OpHasCompleteDecoder);
1122 if (!OpHasCompleteDecoder)
1123 HasCompleteDecoder = false;
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001124 }
1125}
1126
1127unsigned FilterChooser::getDecoderIndex(DecoderSet &Decoders,
Petr Pavlud2e1e422015-07-15 08:04:27 +00001128 unsigned Opc,
1129 bool &HasCompleteDecoder) const {
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001130 // Build up the predicate string.
1131 SmallString<256> Decoder;
1132 // FIXME: emitDecoder() function can take a buffer directly rather than
1133 // a stream.
1134 raw_svector_ostream S(Decoder);
Craig Topperc0564832012-08-17 05:16:15 +00001135 unsigned I = 4;
Petr Pavlud2e1e422015-07-15 08:04:27 +00001136 emitDecoder(S, I, Opc, HasCompleteDecoder);
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001137
1138 // Using the full decoder string as the key value here is a bit
1139 // heavyweight, but is effective. If the string comparisons become a
1140 // performance concern, we can implement a mangling of the predicate
Nick Lewyckycca41d32015-08-18 22:41:58 +00001141 // data easily enough with a map back to the actual string. That's
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001142 // overkill for now, though.
1143
1144 // Make sure the predicate is in the table.
Justin Lebar2c937a12016-10-21 21:45:01 +00001145 Decoders.insert(CachedHashString(Decoder));
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001146 // Now figure out the index for when we write out the table.
David Majnemer2d62ce62016-08-12 03:55:06 +00001147 DecoderSet::const_iterator P = find(Decoders, Decoder.str());
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001148 return (unsigned)(P - Decoders.begin());
1149}
1150
James Molloya5d58562011-09-07 19:42:28 +00001151static void emitSinglePredicateMatch(raw_ostream &o, StringRef str,
Craig Toppereb5cd612012-03-16 05:58:09 +00001152 const std::string &PredicateNamespace) {
Andrew Trick22b4c812011-09-08 05:25:49 +00001153 if (str[0] == '!')
Michael Kupersteind714fcf2015-05-26 10:47:10 +00001154 o << "!Bits[" << PredicateNamespace << "::"
1155 << str.slice(1,str.size()) << "]";
James Molloya5d58562011-09-07 19:42:28 +00001156 else
Michael Kupersteind714fcf2015-05-26 10:47:10 +00001157 o << "Bits[" << PredicateNamespace << "::" << str << "]";
James Molloya5d58562011-09-07 19:42:28 +00001158}
1159
1160bool FilterChooser::emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
Craig Toppereb5cd612012-03-16 05:58:09 +00001161 unsigned Opc) const {
Jim Grosbach9c826d22012-02-29 22:07:56 +00001162 ListInit *Predicates =
Daniel Sanders0de70682018-12-13 16:17:54 +00001163 AllInstructions[Opc].EncodingDef->getValueAsListInit("Predicates");
Toma Tabacu0e407e72015-04-07 12:10:11 +00001164 bool IsFirstEmission = true;
Craig Topper61f49542015-06-02 04:15:57 +00001165 for (unsigned i = 0; i < Predicates->size(); ++i) {
James Molloya5d58562011-09-07 19:42:28 +00001166 Record *Pred = Predicates->getElementAsRecord(i);
1167 if (!Pred->getValue("AssemblerMatcherPredicate"))
1168 continue;
1169
Craig Topper2a129872017-05-31 21:12:46 +00001170 StringRef P = Pred->getValueAsString("AssemblerCondString");
James Molloya5d58562011-09-07 19:42:28 +00001171
Craig Topper2a129872017-05-31 21:12:46 +00001172 if (P.empty())
James Molloya5d58562011-09-07 19:42:28 +00001173 continue;
1174
Toma Tabacu0e407e72015-04-07 12:10:11 +00001175 if (!IsFirstEmission)
James Molloya5d58562011-09-07 19:42:28 +00001176 o << " && ";
1177
Craig Topper2a129872017-05-31 21:12:46 +00001178 std::pair<StringRef, StringRef> pairs = P.split(',');
Eugene Zelenkoc02caf52016-11-30 17:48:10 +00001179 while (!pairs.second.empty()) {
James Molloya5d58562011-09-07 19:42:28 +00001180 emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
1181 o << " && ";
1182 pairs = pairs.second.split(',');
1183 }
1184 emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
Toma Tabacu0e407e72015-04-07 12:10:11 +00001185 IsFirstEmission = false;
James Molloya5d58562011-09-07 19:42:28 +00001186 }
Craig Topper61f49542015-06-02 04:15:57 +00001187 return !Predicates->empty();
Andrew Tricked968a92011-09-08 05:23:14 +00001188}
James Molloya5d58562011-09-07 19:42:28 +00001189
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001190bool FilterChooser::doesOpcodeNeedPredicate(unsigned Opc) const {
1191 ListInit *Predicates =
Daniel Sanders0de70682018-12-13 16:17:54 +00001192 AllInstructions[Opc].EncodingDef->getValueAsListInit("Predicates");
Craig Topper61f49542015-06-02 04:15:57 +00001193 for (unsigned i = 0; i < Predicates->size(); ++i) {
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001194 Record *Pred = Predicates->getElementAsRecord(i);
1195 if (!Pred->getValue("AssemblerMatcherPredicate"))
1196 continue;
1197
Craig Topper2a129872017-05-31 21:12:46 +00001198 StringRef P = Pred->getValueAsString("AssemblerCondString");
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001199
Craig Topper2a129872017-05-31 21:12:46 +00001200 if (P.empty())
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001201 continue;
1202
1203 return true;
1204 }
1205 return false;
1206}
1207
1208unsigned FilterChooser::getPredicateIndex(DecoderTableInfo &TableInfo,
1209 StringRef Predicate) const {
1210 // Using the full predicate string as the key value here is a bit
1211 // heavyweight, but is effective. If the string comparisons become a
1212 // performance concern, we can implement a mangling of the predicate
Nick Lewyckycca41d32015-08-18 22:41:58 +00001213 // data easily enough with a map back to the actual string. That's
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001214 // overkill for now, though.
1215
1216 // Make sure the predicate is in the table.
Justin Lebar2c937a12016-10-21 21:45:01 +00001217 TableInfo.Predicates.insert(CachedHashString(Predicate));
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001218 // Now figure out the index for when we write out the table.
Justin Lebar2c937a12016-10-21 21:45:01 +00001219 PredicateSet::const_iterator P = find(TableInfo.Predicates, Predicate);
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001220 return (unsigned)(P - TableInfo.Predicates.begin());
1221}
1222
1223void FilterChooser::emitPredicateTableEntry(DecoderTableInfo &TableInfo,
1224 unsigned Opc) const {
1225 if (!doesOpcodeNeedPredicate(Opc))
1226 return;
1227
1228 // Build up the predicate string.
1229 SmallString<256> Predicate;
1230 // FIXME: emitPredicateMatch() functions can take a buffer directly rather
1231 // than a stream.
1232 raw_svector_ostream PS(Predicate);
1233 unsigned I = 0;
1234 emitPredicateMatch(PS, I, Opc);
1235
1236 // Figure out the index into the predicate table for the predicate just
1237 // computed.
1238 unsigned PIdx = getPredicateIndex(TableInfo, PS.str());
1239 SmallString<16> PBytes;
1240 raw_svector_ostream S(PBytes);
1241 encodeULEB128(PIdx, S);
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001242
1243 TableInfo.Table.push_back(MCD::OPC_CheckPredicate);
1244 // Predicate index
Craig Topper8cd9eae2012-08-17 05:42:16 +00001245 for (unsigned i = 0, e = PBytes.size(); i != e; ++i)
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001246 TableInfo.Table.push_back(PBytes[i]);
1247 // Push location for NumToSkip backpatching.
1248 TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
1249 TableInfo.Table.push_back(0);
1250 TableInfo.Table.push_back(0);
Sander de Smalenc13d5962018-07-05 10:39:15 +00001251 TableInfo.Table.push_back(0);
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001252}
1253
1254void FilterChooser::emitSoftFailTableEntry(DecoderTableInfo &TableInfo,
1255 unsigned Opc) const {
Jim Grosbach9c826d22012-02-29 22:07:56 +00001256 BitsInit *SFBits =
Daniel Sanders0de70682018-12-13 16:17:54 +00001257 AllInstructions[Opc].EncodingDef->getValueAsBitsInit("SoftFail");
James Molloy3015dfb2012-02-09 10:56:31 +00001258 if (!SFBits) return;
Daniel Sanders0de70682018-12-13 16:17:54 +00001259 BitsInit *InstBits =
1260 AllInstructions[Opc].EncodingDef->getValueAsBitsInit("Inst");
James Molloy3015dfb2012-02-09 10:56:31 +00001261
1262 APInt PositiveMask(BitWidth, 0ULL);
1263 APInt NegativeMask(BitWidth, 0ULL);
1264 for (unsigned i = 0; i < BitWidth; ++i) {
1265 bit_value_t B = bitFromBits(*SFBits, i);
1266 bit_value_t IB = bitFromBits(*InstBits, i);
1267
1268 if (B != BIT_TRUE) continue;
1269
1270 switch (IB) {
1271 case BIT_FALSE:
1272 // The bit is meant to be false, so emit a check to see if it is true.
1273 PositiveMask.setBit(i);
1274 break;
1275 case BIT_TRUE:
1276 // The bit is meant to be true, so emit a check to see if it is false.
1277 NegativeMask.setBit(i);
1278 break;
1279 default:
1280 // The bit is not set; this must be an error!
Daniel Sanders0de70682018-12-13 16:17:54 +00001281 errs() << "SoftFail Conflict: bit SoftFail{" << i << "} in "
1282 << AllInstructions[Opc] << " is set but Inst{" << i
1283 << "} is unset!\n"
James Molloy3015dfb2012-02-09 10:56:31 +00001284 << " - You can only mark a bit as SoftFail if it is fully defined"
1285 << " (1/0 - not '?') in Inst\n";
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001286 return;
James Molloy3015dfb2012-02-09 10:56:31 +00001287 }
1288 }
1289
1290 bool NeedPositiveMask = PositiveMask.getBoolValue();
1291 bool NeedNegativeMask = NegativeMask.getBoolValue();
1292
1293 if (!NeedPositiveMask && !NeedNegativeMask)
1294 return;
1295
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001296 TableInfo.Table.push_back(MCD::OPC_SoftFail);
James Molloy3015dfb2012-02-09 10:56:31 +00001297
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001298 SmallString<16> MaskBytes;
1299 raw_svector_ostream S(MaskBytes);
1300 if (NeedPositiveMask) {
1301 encodeULEB128(PositiveMask.getZExtValue(), S);
Craig Topper8cd9eae2012-08-17 05:42:16 +00001302 for (unsigned i = 0, e = MaskBytes.size(); i != e; ++i)
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001303 TableInfo.Table.push_back(MaskBytes[i]);
1304 } else
1305 TableInfo.Table.push_back(0);
1306 if (NeedNegativeMask) {
1307 MaskBytes.clear();
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001308 encodeULEB128(NegativeMask.getZExtValue(), S);
Craig Topper8cd9eae2012-08-17 05:42:16 +00001309 for (unsigned i = 0, e = MaskBytes.size(); i != e; ++i)
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001310 TableInfo.Table.push_back(MaskBytes[i]);
1311 } else
1312 TableInfo.Table.push_back(0);
James Molloy3015dfb2012-02-09 10:56:31 +00001313}
1314
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001315// Emits table entries to decode the singleton.
1316void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,
1317 unsigned Opc) const {
Owen Andersond8c87882011-02-18 21:51:29 +00001318 std::vector<unsigned> StartBits;
1319 std::vector<unsigned> EndBits;
1320 std::vector<uint64_t> FieldVals;
1321 insn_t Insn;
1322 insnWithID(Insn, Opc);
1323
1324 // Look for islands of undecoded bits of the singleton.
1325 getIslands(StartBits, EndBits, FieldVals, Insn);
1326
1327 unsigned Size = StartBits.size();
Owen Andersond8c87882011-02-18 21:51:29 +00001328
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001329 // Emit the predicate table entry if one is needed.
1330 emitPredicateTableEntry(TableInfo, Opc);
Owen Andersond8c87882011-02-18 21:51:29 +00001331
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001332 // Check any additional encoding fields needed.
Craig Topper8cd9eae2012-08-17 05:42:16 +00001333 for (unsigned I = Size; I != 0; --I) {
1334 unsigned NumBits = EndBits[I-1] - StartBits[I-1] + 1;
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001335 TableInfo.Table.push_back(MCD::OPC_CheckField);
1336 TableInfo.Table.push_back(StartBits[I-1]);
1337 TableInfo.Table.push_back(NumBits);
Sander de Smalenc13d5962018-07-05 10:39:15 +00001338 uint8_t Buffer[16], *p;
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001339 encodeULEB128(FieldVals[I-1], Buffer);
1340 for (p = Buffer; *p >= 128 ; ++p)
1341 TableInfo.Table.push_back(*p);
1342 TableInfo.Table.push_back(*p);
1343 // Push location for NumToSkip backpatching.
1344 TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
Sander de Smalenc13d5962018-07-05 10:39:15 +00001345 // The fixup is always 24-bits, so go ahead and allocate the space
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001346 // in the table so all our relative position calculations work OK even
1347 // before we fully resolve the real value here.
1348 TableInfo.Table.push_back(0);
1349 TableInfo.Table.push_back(0);
Sander de Smalenc13d5962018-07-05 10:39:15 +00001350 TableInfo.Table.push_back(0);
Owen Andersond8c87882011-02-18 21:51:29 +00001351 }
Owen Andersond8c87882011-02-18 21:51:29 +00001352
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001353 // Check for soft failure of the match.
1354 emitSoftFailTableEntry(TableInfo, Opc);
Owen Andersond8c87882011-02-18 21:51:29 +00001355
Petr Pavlud2e1e422015-07-15 08:04:27 +00001356 bool HasCompleteDecoder;
1357 unsigned DIdx = getDecoderIndex(TableInfo.Decoders, Opc, HasCompleteDecoder);
1358
1359 // Produce OPC_Decode or OPC_TryDecode opcode based on the information
1360 // whether the instruction decoder is complete or not. If it is complete
1361 // then it handles all possible values of remaining variable/unfiltered bits
1362 // and for any value can determine if the bitpattern is a valid instruction
1363 // or not. This means OPC_Decode will be the final step in the decoding
1364 // process. If it is not complete, then the Fail return code from the
1365 // decoder method indicates that additional processing should be done to see
1366 // if there is any other instruction that also matches the bitpattern and
1367 // can decode it.
1368 TableInfo.Table.push_back(HasCompleteDecoder ? MCD::OPC_Decode :
1369 MCD::OPC_TryDecode);
Sander de Smalenc13d5962018-07-05 10:39:15 +00001370 uint8_t Buffer[16], *p;
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001371 encodeULEB128(Opc, Buffer);
1372 for (p = Buffer; *p >= 128 ; ++p)
1373 TableInfo.Table.push_back(*p);
1374 TableInfo.Table.push_back(*p);
1375
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001376 SmallString<16> Bytes;
1377 raw_svector_ostream S(Bytes);
1378 encodeULEB128(DIdx, S);
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001379
1380 // Decoder index
Craig Topper8cd9eae2012-08-17 05:42:16 +00001381 for (unsigned i = 0, e = Bytes.size(); i != e; ++i)
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001382 TableInfo.Table.push_back(Bytes[i]);
Petr Pavlud2e1e422015-07-15 08:04:27 +00001383
1384 if (!HasCompleteDecoder) {
1385 // Push location for NumToSkip backpatching.
1386 TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
1387 // Allocate the space for the fixup.
1388 TableInfo.Table.push_back(0);
1389 TableInfo.Table.push_back(0);
Sander de Smalenc13d5962018-07-05 10:39:15 +00001390 TableInfo.Table.push_back(0);
Petr Pavlud2e1e422015-07-15 08:04:27 +00001391 }
Owen Andersond8c87882011-02-18 21:51:29 +00001392}
1393
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001394// Emits table entries to decode the singleton, and then to decode the rest.
1395void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,
1396 const Filter &Best) const {
Owen Andersond8c87882011-02-18 21:51:29 +00001397 unsigned Opc = Best.getSingletonOpc();
1398
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001399 // complex singletons need predicate checks from the first singleton
1400 // to refer forward to the variable filterchooser that follows.
Benjamin Kramer9589ff82015-05-29 19:43:39 +00001401 TableInfo.FixupStack.emplace_back();
Owen Andersond8c87882011-02-18 21:51:29 +00001402
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001403 emitSingletonTableEntry(TableInfo, Opc);
Owen Andersond8c87882011-02-18 21:51:29 +00001404
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001405 resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),
1406 TableInfo.Table.size());
1407 TableInfo.FixupStack.pop_back();
1408
1409 Best.getVariableFC().emitTableEntries(TableInfo);
Owen Andersond8c87882011-02-18 21:51:29 +00001410}
1411
1412// Assign a single filter and run with it. Top level API client can initialize
1413// with a single filter to start the filtering process.
Craig Toppereb5cd612012-03-16 05:58:09 +00001414void FilterChooser::runSingleFilter(unsigned startBit, unsigned numBit,
1415 bool mixed) {
Owen Andersond8c87882011-02-18 21:51:29 +00001416 Filters.clear();
Benjamin Kramer9589ff82015-05-29 19:43:39 +00001417 Filters.emplace_back(*this, startBit, numBit, true);
Owen Andersond8c87882011-02-18 21:51:29 +00001418 BestIndex = 0; // Sole Filter instance to choose from.
1419 bestFilter().recurse();
1420}
1421
1422// reportRegion is a helper function for filterProcessor to mark a region as
1423// eligible for use as a filter region.
1424void FilterChooser::reportRegion(bitAttr_t RA, unsigned StartBit,
Craig Topperd9360452012-03-16 01:19:24 +00001425 unsigned BitIndex, bool AllowMixed) {
Owen Andersond8c87882011-02-18 21:51:29 +00001426 if (RA == ATTR_MIXED && AllowMixed)
Benjamin Kramer9589ff82015-05-29 19:43:39 +00001427 Filters.emplace_back(*this, StartBit, BitIndex - StartBit, true);
Owen Andersond8c87882011-02-18 21:51:29 +00001428 else if (RA == ATTR_ALL_SET && !AllowMixed)
Benjamin Kramer9589ff82015-05-29 19:43:39 +00001429 Filters.emplace_back(*this, StartBit, BitIndex - StartBit, false);
Owen Andersond8c87882011-02-18 21:51:29 +00001430}
1431
1432// FilterProcessor scans the well-known encoding bits of the instructions and
1433// builds up a list of candidate filters. It chooses the best filter and
1434// recursively descends down the decoding tree.
1435bool FilterChooser::filterProcessor(bool AllowMixed, bool Greedy) {
1436 Filters.clear();
1437 BestIndex = -1;
1438 unsigned numInstructions = Opcodes.size();
1439
1440 assert(numInstructions && "Filter created with no instructions");
1441
1442 // No further filtering is necessary.
1443 if (numInstructions == 1)
1444 return true;
1445
1446 // Heuristics. See also doFilter()'s "Heuristics" comment when num of
1447 // instructions is 3.
1448 if (AllowMixed && !Greedy) {
1449 assert(numInstructions == 3);
1450
1451 for (unsigned i = 0; i < Opcodes.size(); ++i) {
1452 std::vector<unsigned> StartBits;
1453 std::vector<unsigned> EndBits;
1454 std::vector<uint64_t> FieldVals;
1455 insn_t Insn;
1456
1457 insnWithID(Insn, Opcodes[i]);
1458
1459 // Look for islands of undecoded bits of any instruction.
1460 if (getIslands(StartBits, EndBits, FieldVals, Insn) > 0) {
1461 // Found an instruction with island(s). Now just assign a filter.
Craig Toppereb5cd612012-03-16 05:58:09 +00001462 runSingleFilter(StartBits[0], EndBits[0] - StartBits[0] + 1, true);
Owen Andersond8c87882011-02-18 21:51:29 +00001463 return true;
1464 }
1465 }
1466 }
1467
Craig Topper8cd9eae2012-08-17 05:42:16 +00001468 unsigned BitIndex;
Owen Andersond8c87882011-02-18 21:51:29 +00001469
1470 // We maintain BIT_WIDTH copies of the bitAttrs automaton.
1471 // The automaton consumes the corresponding bit from each
1472 // instruction.
1473 //
1474 // Input symbols: 0, 1, and _ (unset).
1475 // States: NONE, FILTERED, ALL_SET, ALL_UNSET, and MIXED.
1476 // Initial state: NONE.
1477 //
1478 // (NONE) ------- [01] -> (ALL_SET)
1479 // (NONE) ------- _ ----> (ALL_UNSET)
1480 // (ALL_SET) ---- [01] -> (ALL_SET)
1481 // (ALL_SET) ---- _ ----> (MIXED)
1482 // (ALL_UNSET) -- [01] -> (MIXED)
1483 // (ALL_UNSET) -- _ ----> (ALL_UNSET)
1484 // (MIXED) ------ . ----> (MIXED)
1485 // (FILTERED)---- . ----> (FILTERED)
1486
Owen Andersonf1a00902011-07-19 21:06:00 +00001487 std::vector<bitAttr_t> bitAttrs;
Owen Andersond8c87882011-02-18 21:51:29 +00001488
1489 // FILTERED bit positions provide no entropy and are not worthy of pursuing.
1490 // Filter::recurse() set either BIT_TRUE or BIT_FALSE for each position.
Owen Andersonf1a00902011-07-19 21:06:00 +00001491 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex)
Owen Andersond8c87882011-02-18 21:51:29 +00001492 if (FilterBitValues[BitIndex] == BIT_TRUE ||
1493 FilterBitValues[BitIndex] == BIT_FALSE)
Owen Andersonf1a00902011-07-19 21:06:00 +00001494 bitAttrs.push_back(ATTR_FILTERED);
Owen Andersond8c87882011-02-18 21:51:29 +00001495 else
Owen Andersonf1a00902011-07-19 21:06:00 +00001496 bitAttrs.push_back(ATTR_NONE);
Owen Andersond8c87882011-02-18 21:51:29 +00001497
Craig Topper8cd9eae2012-08-17 05:42:16 +00001498 for (unsigned InsnIndex = 0; InsnIndex < numInstructions; ++InsnIndex) {
Owen Andersond8c87882011-02-18 21:51:29 +00001499 insn_t insn;
1500
1501 insnWithID(insn, Opcodes[InsnIndex]);
1502
Owen Andersonf1a00902011-07-19 21:06:00 +00001503 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
Owen Andersond8c87882011-02-18 21:51:29 +00001504 switch (bitAttrs[BitIndex]) {
1505 case ATTR_NONE:
1506 if (insn[BitIndex] == BIT_UNSET)
1507 bitAttrs[BitIndex] = ATTR_ALL_UNSET;
1508 else
1509 bitAttrs[BitIndex] = ATTR_ALL_SET;
1510 break;
1511 case ATTR_ALL_SET:
1512 if (insn[BitIndex] == BIT_UNSET)
1513 bitAttrs[BitIndex] = ATTR_MIXED;
1514 break;
1515 case ATTR_ALL_UNSET:
1516 if (insn[BitIndex] != BIT_UNSET)
1517 bitAttrs[BitIndex] = ATTR_MIXED;
1518 break;
1519 case ATTR_MIXED:
1520 case ATTR_FILTERED:
1521 break;
1522 }
1523 }
1524 }
1525
1526 // The regionAttr automaton consumes the bitAttrs automatons' state,
1527 // lowest-to-highest.
1528 //
1529 // Input symbols: F(iltered), (all_)S(et), (all_)U(nset), M(ixed)
1530 // States: NONE, ALL_SET, MIXED
1531 // Initial state: NONE
1532 //
1533 // (NONE) ----- F --> (NONE)
1534 // (NONE) ----- S --> (ALL_SET) ; and set region start
1535 // (NONE) ----- U --> (NONE)
1536 // (NONE) ----- M --> (MIXED) ; and set region start
1537 // (ALL_SET) -- F --> (NONE) ; and report an ALL_SET region
1538 // (ALL_SET) -- S --> (ALL_SET)
1539 // (ALL_SET) -- U --> (NONE) ; and report an ALL_SET region
1540 // (ALL_SET) -- M --> (MIXED) ; and report an ALL_SET region
1541 // (MIXED) ---- F --> (NONE) ; and report a MIXED region
1542 // (MIXED) ---- S --> (ALL_SET) ; and report a MIXED region
1543 // (MIXED) ---- U --> (NONE) ; and report a MIXED region
1544 // (MIXED) ---- M --> (MIXED)
1545
1546 bitAttr_t RA = ATTR_NONE;
1547 unsigned StartBit = 0;
1548
Craig Topper8cd9eae2012-08-17 05:42:16 +00001549 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
Owen Andersond8c87882011-02-18 21:51:29 +00001550 bitAttr_t bitAttr = bitAttrs[BitIndex];
1551
1552 assert(bitAttr != ATTR_NONE && "Bit without attributes");
1553
1554 switch (RA) {
1555 case ATTR_NONE:
1556 switch (bitAttr) {
1557 case ATTR_FILTERED:
1558 break;
1559 case ATTR_ALL_SET:
1560 StartBit = BitIndex;
1561 RA = ATTR_ALL_SET;
1562 break;
1563 case ATTR_ALL_UNSET:
1564 break;
1565 case ATTR_MIXED:
1566 StartBit = BitIndex;
1567 RA = ATTR_MIXED;
1568 break;
1569 default:
Craig Topper655b8de2012-02-05 07:21:30 +00001570 llvm_unreachable("Unexpected bitAttr!");
Owen Andersond8c87882011-02-18 21:51:29 +00001571 }
1572 break;
1573 case ATTR_ALL_SET:
1574 switch (bitAttr) {
1575 case ATTR_FILTERED:
1576 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1577 RA = ATTR_NONE;
1578 break;
1579 case ATTR_ALL_SET:
1580 break;
1581 case ATTR_ALL_UNSET:
1582 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1583 RA = ATTR_NONE;
1584 break;
1585 case ATTR_MIXED:
1586 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1587 StartBit = BitIndex;
1588 RA = ATTR_MIXED;
1589 break;
1590 default:
Craig Topper655b8de2012-02-05 07:21:30 +00001591 llvm_unreachable("Unexpected bitAttr!");
Owen Andersond8c87882011-02-18 21:51:29 +00001592 }
1593 break;
1594 case ATTR_MIXED:
1595 switch (bitAttr) {
1596 case ATTR_FILTERED:
1597 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1598 StartBit = BitIndex;
1599 RA = ATTR_NONE;
1600 break;
1601 case ATTR_ALL_SET:
1602 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1603 StartBit = BitIndex;
1604 RA = ATTR_ALL_SET;
1605 break;
1606 case ATTR_ALL_UNSET:
1607 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1608 RA = ATTR_NONE;
1609 break;
1610 case ATTR_MIXED:
1611 break;
1612 default:
Craig Topper655b8de2012-02-05 07:21:30 +00001613 llvm_unreachable("Unexpected bitAttr!");
Owen Andersond8c87882011-02-18 21:51:29 +00001614 }
1615 break;
1616 case ATTR_ALL_UNSET:
Craig Topper655b8de2012-02-05 07:21:30 +00001617 llvm_unreachable("regionAttr state machine has no ATTR_UNSET state");
Owen Andersond8c87882011-02-18 21:51:29 +00001618 case ATTR_FILTERED:
Craig Topper655b8de2012-02-05 07:21:30 +00001619 llvm_unreachable("regionAttr state machine has no ATTR_FILTERED state");
Owen Andersond8c87882011-02-18 21:51:29 +00001620 }
1621 }
1622
1623 // At the end, if we're still in ALL_SET or MIXED states, report a region
1624 switch (RA) {
1625 case ATTR_NONE:
1626 break;
1627 case ATTR_FILTERED:
1628 break;
1629 case ATTR_ALL_SET:
1630 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1631 break;
1632 case ATTR_ALL_UNSET:
1633 break;
1634 case ATTR_MIXED:
1635 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1636 break;
1637 }
1638
1639 // We have finished with the filter processings. Now it's time to choose
1640 // the best performing filter.
1641 BestIndex = 0;
1642 bool AllUseless = true;
1643 unsigned BestScore = 0;
1644
1645 for (unsigned i = 0, e = Filters.size(); i != e; ++i) {
1646 unsigned Usefulness = Filters[i].usefulness();
1647
1648 if (Usefulness)
1649 AllUseless = false;
1650
1651 if (Usefulness > BestScore) {
1652 BestIndex = i;
1653 BestScore = Usefulness;
1654 }
1655 }
1656
1657 if (!AllUseless)
1658 bestFilter().recurse();
1659
1660 return !AllUseless;
1661} // end of FilterChooser::filterProcessor(bool)
1662
1663// Decides on the best configuration of filter(s) to use in order to decode
1664// the instructions. A conflict of instructions may occur, in which case we
1665// dump the conflict set to the standard error.
1666void FilterChooser::doFilter() {
1667 unsigned Num = Opcodes.size();
1668 assert(Num && "FilterChooser created with no instructions");
1669
1670 // Try regions of consecutive known bit values first.
1671 if (filterProcessor(false))
1672 return;
1673
1674 // Then regions of mixed bits (both known and unitialized bit values allowed).
1675 if (filterProcessor(true))
1676 return;
1677
1678 // Heuristics to cope with conflict set {t2CMPrs, t2SUBSrr, t2SUBSrs} where
1679 // no single instruction for the maximum ATTR_MIXED region Inst{14-4} has a
1680 // well-known encoding pattern. In such case, we backtrack and scan for the
1681 // the very first consecutive ATTR_ALL_SET region and assign a filter to it.
1682 if (Num == 3 && filterProcessor(true, false))
1683 return;
1684
1685 // If we come to here, the instruction decoding has failed.
1686 // Set the BestIndex to -1 to indicate so.
1687 BestIndex = -1;
1688}
1689
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001690// emitTableEntries - Emit state machine entries to decode our share of
1691// instructions.
1692void FilterChooser::emitTableEntries(DecoderTableInfo &TableInfo) const {
1693 if (Opcodes.size() == 1) {
Owen Andersond8c87882011-02-18 21:51:29 +00001694 // There is only one instruction in the set, which is great!
1695 // Call emitSingletonDecoder() to see whether there are any remaining
1696 // encodings bits.
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001697 emitSingletonTableEntry(TableInfo, Opcodes[0]);
1698 return;
1699 }
Owen Andersond8c87882011-02-18 21:51:29 +00001700
1701 // Choose the best filter to do the decodings!
1702 if (BestIndex != -1) {
Craig Toppereb5cd612012-03-16 05:58:09 +00001703 const Filter &Best = Filters[BestIndex];
Owen Andersond8c87882011-02-18 21:51:29 +00001704 if (Best.getNumFiltered() == 1)
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001705 emitSingletonTableEntry(TableInfo, Best);
Owen Andersond8c87882011-02-18 21:51:29 +00001706 else
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001707 Best.emitTableEntry(TableInfo);
1708 return;
Owen Andersond8c87882011-02-18 21:51:29 +00001709 }
1710
Jim Grosbachfc1a1612012-08-14 19:06:05 +00001711 // We don't know how to decode these instructions! Dump the
1712 // conflict set and bail.
Owen Andersond8c87882011-02-18 21:51:29 +00001713
1714 // Print out useful conflict information for postmortem analysis.
1715 errs() << "Decoding Conflict:\n";
1716
1717 dumpStack(errs(), "\t\t");
1718
Craig Topperd9360452012-03-16 01:19:24 +00001719 for (unsigned i = 0; i < Opcodes.size(); ++i) {
Daniel Sanders5367c022019-01-03 00:14:33 +00001720 errs() << '\t' << AllInstructions[Opcodes[i]] << " ";
Owen Andersond8c87882011-02-18 21:51:29 +00001721 dumpBits(errs(),
Daniel Sanders0de70682018-12-13 16:17:54 +00001722 getBitsField(*AllInstructions[Opcodes[i]].EncodingDef, "Inst"));
Owen Andersond8c87882011-02-18 21:51:29 +00001723 errs() << '\n';
1724 }
Owen Andersond8c87882011-02-18 21:51:29 +00001725}
1726
Matt Arsenault2d37e252016-07-18 23:20:46 +00001727static std::string findOperandDecoderMethod(TypedInit *TI) {
1728 std::string Decoder;
1729
Nicolai Haehnle8cb107d2018-03-05 14:01:30 +00001730 Record *Record = cast<DefInit>(TI)->getDef();
Matt Arsenault2d37e252016-07-18 23:20:46 +00001731
Nicolai Haehnle8cb107d2018-03-05 14:01:30 +00001732 RecordVal *DecoderString = Record->getValue("DecoderMethod");
Matt Arsenault2d37e252016-07-18 23:20:46 +00001733 StringInit *String = DecoderString ?
1734 dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
1735 if (String) {
1736 Decoder = String->getValue();
1737 if (!Decoder.empty())
1738 return Decoder;
1739 }
1740
Nicolai Haehnle8cb107d2018-03-05 14:01:30 +00001741 if (Record->isSubClassOf("RegisterOperand"))
1742 Record = Record->getValueAsDef("RegClass");
Matt Arsenault2d37e252016-07-18 23:20:46 +00001743
Nicolai Haehnle8cb107d2018-03-05 14:01:30 +00001744 if (Record->isSubClassOf("RegisterClass")) {
1745 Decoder = "Decode" + Record->getName().str() + "RegisterClass";
1746 } else if (Record->isSubClassOf("PointerLikeRegClass")) {
Matt Arsenault2d37e252016-07-18 23:20:46 +00001747 Decoder = "DecodePointerLikeRegClass" +
Nicolai Haehnle8cb107d2018-03-05 14:01:30 +00001748 utostr(Record->getValueAsInt("RegClassKind"));
Matt Arsenault2d37e252016-07-18 23:20:46 +00001749 }
1750
1751 return Decoder;
1752}
1753
Hal Finkeld715c3e2013-12-19 16:12:53 +00001754static bool populateInstruction(CodeGenTarget &Target,
1755 const CodeGenInstruction &CGI, unsigned Opc,
Eugene Zelenkoc02caf52016-11-30 17:48:10 +00001756 std::map<unsigned, std::vector<OperandInfo>> &Operands){
Owen Andersond8c87882011-02-18 21:51:29 +00001757 const Record &Def = *CGI.TheDef;
1758 // If all the bit positions are not specified; do not decode this instruction.
1759 // We are bound to fail! For proper disassembly, the well-known encoding bits
1760 // of the instruction must be fully specified.
Owen Andersond8c87882011-02-18 21:51:29 +00001761
David Greene05bce0b2011-07-29 22:43:06 +00001762 BitsInit &Bits = getBitsField(Def, "Inst");
Jim Grosbach806fcc02011-07-06 21:33:38 +00001763 if (Bits.allInComplete()) return false;
1764
Owen Andersond8c87882011-02-18 21:51:29 +00001765 std::vector<OperandInfo> InsnOperands;
1766
1767 // If the instruction has specified a custom decoding hook, use that instead
1768 // of trying to auto-generate the decoder.
Craig Topper2a129872017-05-31 21:12:46 +00001769 StringRef InstDecoder = Def.getValueAsString("DecoderMethod");
Owen Andersond8c87882011-02-18 21:51:29 +00001770 if (InstDecoder != "") {
Petr Pavlud2e1e422015-07-15 08:04:27 +00001771 bool HasCompleteInstDecoder = Def.getValueAsBit("hasCompleteDecoder");
1772 InsnOperands.push_back(OperandInfo(InstDecoder, HasCompleteInstDecoder));
Owen Andersond8c87882011-02-18 21:51:29 +00001773 Operands[Opc] = InsnOperands;
1774 return true;
1775 }
1776
1777 // Generate a description of the operand of the instruction that we know
1778 // how to decode automatically.
1779 // FIXME: We'll need to have a way to manually override this as needed.
1780
1781 // Gather the outputs/inputs of the instruction, so we can find their
1782 // positions in the encoding. This assumes for now that they appear in the
1783 // MCInst in the order that they're listed.
Matthias Braunddbd6db2016-12-05 06:00:46 +00001784 std::vector<std::pair<Init*, StringRef>> InOutOperands;
David Greene05bce0b2011-07-29 22:43:06 +00001785 DagInit *Out = Def.getValueAsDag("OutOperandList");
1786 DagInit *In = Def.getValueAsDag("InOperandList");
Owen Andersond8c87882011-02-18 21:51:29 +00001787 for (unsigned i = 0; i < Out->getNumArgs(); ++i)
Matthias Braunddbd6db2016-12-05 06:00:46 +00001788 InOutOperands.push_back(std::make_pair(Out->getArg(i),
1789 Out->getArgNameStr(i)));
Owen Andersond8c87882011-02-18 21:51:29 +00001790 for (unsigned i = 0; i < In->getNumArgs(); ++i)
Matthias Braunddbd6db2016-12-05 06:00:46 +00001791 InOutOperands.push_back(std::make_pair(In->getArg(i),
1792 In->getArgNameStr(i)));
Owen Andersond8c87882011-02-18 21:51:29 +00001793
Owen Anderson00ef6e32011-07-28 23:56:20 +00001794 // Search for tied operands, so that we can correctly instantiate
1795 // operands that are not explicitly represented in the encoding.
Owen Andersonea242982011-07-29 18:28:52 +00001796 std::map<std::string, std::string> TiedNames;
Owen Anderson00ef6e32011-07-28 23:56:20 +00001797 for (unsigned i = 0; i < CGI.Operands.size(); ++i) {
1798 int tiedTo = CGI.Operands[i].getTiedRegister();
Owen Andersonea242982011-07-29 18:28:52 +00001799 if (tiedTo != -1) {
Hal Finkeld715c3e2013-12-19 16:12:53 +00001800 std::pair<unsigned, unsigned> SO =
1801 CGI.Operands.getSubOperandNumber(tiedTo);
1802 TiedNames[InOutOperands[i].second] = InOutOperands[SO.first].second;
1803 TiedNames[InOutOperands[SO.first].second] = InOutOperands[i].second;
1804 }
1805 }
1806
Eugene Zelenkoc02caf52016-11-30 17:48:10 +00001807 std::map<std::string, std::vector<OperandInfo>> NumberedInsnOperands;
Hal Finkeld715c3e2013-12-19 16:12:53 +00001808 std::set<std::string> NumberedInsnOperandsNoTie;
1809 if (Target.getInstructionSet()->
1810 getValueAsBit("decodePositionallyEncodedOperands")) {
1811 const std::vector<RecordVal> &Vals = Def.getValues();
1812 unsigned NumberedOp = 0;
1813
Hal Finkel79c15b22014-03-13 07:57:54 +00001814 std::set<unsigned> NamedOpIndices;
1815 if (Target.getInstructionSet()->
1816 getValueAsBit("noNamedPositionallyEncodedOperands"))
1817 // Collect the set of operand indices that might correspond to named
1818 // operand, and skip these when assigning operands based on position.
1819 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1820 unsigned OpIdx;
1821 if (!CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx))
1822 continue;
1823
1824 NamedOpIndices.insert(OpIdx);
1825 }
1826
Hal Finkeld715c3e2013-12-19 16:12:53 +00001827 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1828 // Ignore fixed fields in the record, we're looking for values like:
1829 // bits<5> RST = { ?, ?, ?, ?, ? };
1830 if (Vals[i].getPrefix() || Vals[i].getValue()->isComplete())
1831 continue;
1832
1833 // Determine if Vals[i] actually contributes to the Inst encoding.
1834 unsigned bi = 0;
1835 for (; bi < Bits.getNumBits(); ++bi) {
Craig Topper095734c2014-04-15 07:20:03 +00001836 VarInit *Var = nullptr;
Hal Finkeld715c3e2013-12-19 16:12:53 +00001837 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
1838 if (BI)
1839 Var = dyn_cast<VarInit>(BI->getBitVar());
1840 else
1841 Var = dyn_cast<VarInit>(Bits.getBit(bi));
1842
1843 if (Var && Var->getName() == Vals[i].getName())
1844 break;
1845 }
1846
1847 if (bi == Bits.getNumBits())
1848 continue;
1849
1850 // Skip variables that correspond to explicitly-named operands.
1851 unsigned OpIdx;
1852 if (CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx))
1853 continue;
1854
1855 // Get the bit range for this operand:
1856 unsigned bitStart = bi++, bitWidth = 1;
1857 for (; bi < Bits.getNumBits(); ++bi) {
Craig Topper095734c2014-04-15 07:20:03 +00001858 VarInit *Var = nullptr;
Hal Finkeld715c3e2013-12-19 16:12:53 +00001859 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
1860 if (BI)
1861 Var = dyn_cast<VarInit>(BI->getBitVar());
1862 else
1863 Var = dyn_cast<VarInit>(Bits.getBit(bi));
1864
1865 if (!Var)
1866 break;
1867
1868 if (Var->getName() != Vals[i].getName())
1869 break;
1870
1871 ++bitWidth;
1872 }
1873
1874 unsigned NumberOps = CGI.Operands.size();
1875 while (NumberedOp < NumberOps &&
Hal Finkel79c15b22014-03-13 07:57:54 +00001876 (CGI.Operands.isFlatOperandNotEmitted(NumberedOp) ||
Alexander Kornienkob4c62672015-01-15 11:41:30 +00001877 (!NamedOpIndices.empty() && NamedOpIndices.count(
Hal Finkel79c15b22014-03-13 07:57:54 +00001878 CGI.Operands.getSubOperandNumber(NumberedOp).first))))
Hal Finkeld715c3e2013-12-19 16:12:53 +00001879 ++NumberedOp;
1880
1881 OpIdx = NumberedOp++;
1882
1883 // OpIdx now holds the ordered operand number of Vals[i].
1884 std::pair<unsigned, unsigned> SO =
1885 CGI.Operands.getSubOperandNumber(OpIdx);
1886 const std::string &Name = CGI.Operands[SO.first].Name;
1887
Nicola Zaghen0818e782018-05-14 12:53:11 +00001888 LLVM_DEBUG(dbgs() << "Numbered operand mapping for " << Def.getName()
1889 << ": " << Name << "(" << SO.first << ", " << SO.second
1890 << ") => " << Vals[i].getName() << "\n");
Hal Finkeld715c3e2013-12-19 16:12:53 +00001891
Eugene Zelenkoc02caf52016-11-30 17:48:10 +00001892 std::string Decoder;
Hal Finkeld715c3e2013-12-19 16:12:53 +00001893 Record *TypeRecord = CGI.Operands[SO.first].Rec;
1894
1895 RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod");
1896 StringInit *String = DecoderString ?
Craig Topper095734c2014-04-15 07:20:03 +00001897 dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
Hal Finkeld715c3e2013-12-19 16:12:53 +00001898 if (String && String->getValue() != "")
1899 Decoder = String->getValue();
1900
1901 if (Decoder == "" &&
1902 CGI.Operands[SO.first].MIOperandInfo &&
1903 CGI.Operands[SO.first].MIOperandInfo->getNumArgs()) {
1904 Init *Arg = CGI.Operands[SO.first].MIOperandInfo->
1905 getArg(SO.second);
Nicolai Haehnle8cb107d2018-03-05 14:01:30 +00001906 if (DefInit *DI = cast<DefInit>(Arg))
1907 TypeRecord = DI->getDef();
Hal Finkeld715c3e2013-12-19 16:12:53 +00001908 }
1909
1910 bool isReg = false;
1911 if (TypeRecord->isSubClassOf("RegisterOperand"))
1912 TypeRecord = TypeRecord->getValueAsDef("RegClass");
1913 if (TypeRecord->isSubClassOf("RegisterClass")) {
Matthias Braun0c517c82016-12-04 05:48:16 +00001914 Decoder = "Decode" + TypeRecord->getName().str() + "RegisterClass";
Hal Finkeld715c3e2013-12-19 16:12:53 +00001915 isReg = true;
1916 } else if (TypeRecord->isSubClassOf("PointerLikeRegClass")) {
1917 Decoder = "DecodePointerLikeRegClass" +
1918 utostr(TypeRecord->getValueAsInt("RegClassKind"));
1919 isReg = true;
1920 }
1921
1922 DecoderString = TypeRecord->getValue("DecoderMethod");
1923 String = DecoderString ?
Craig Topper095734c2014-04-15 07:20:03 +00001924 dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
Hal Finkeld715c3e2013-12-19 16:12:53 +00001925 if (!isReg && String && String->getValue() != "")
1926 Decoder = String->getValue();
1927
Petr Pavlud2e1e422015-07-15 08:04:27 +00001928 RecordVal *HasCompleteDecoderVal =
1929 TypeRecord->getValue("hasCompleteDecoder");
1930 BitInit *HasCompleteDecoderBit = HasCompleteDecoderVal ?
1931 dyn_cast<BitInit>(HasCompleteDecoderVal->getValue()) : nullptr;
1932 bool HasCompleteDecoder = HasCompleteDecoderBit ?
1933 HasCompleteDecoderBit->getValue() : true;
1934
1935 OperandInfo OpInfo(Decoder, HasCompleteDecoder);
Hal Finkeld715c3e2013-12-19 16:12:53 +00001936 OpInfo.addField(bitStart, bitWidth, 0);
1937
1938 NumberedInsnOperands[Name].push_back(OpInfo);
1939
1940 // FIXME: For complex operands with custom decoders we can't handle tied
1941 // sub-operands automatically. Skip those here and assume that this is
1942 // fixed up elsewhere.
1943 if (CGI.Operands[SO.first].MIOperandInfo &&
1944 CGI.Operands[SO.first].MIOperandInfo->getNumArgs() > 1 &&
1945 String && String->getValue() != "")
1946 NumberedInsnOperandsNoTie.insert(Name);
Owen Andersonea242982011-07-29 18:28:52 +00001947 }
Owen Anderson00ef6e32011-07-28 23:56:20 +00001948 }
1949
Owen Andersond8c87882011-02-18 21:51:29 +00001950 // For each operand, see if we can figure out where it is encoded.
Craig Topper1b40b342014-12-13 05:12:19 +00001951 for (const auto &Op : InOutOperands) {
1952 if (!NumberedInsnOperands[Op.second].empty()) {
Hal Finkeld715c3e2013-12-19 16:12:53 +00001953 InsnOperands.insert(InsnOperands.end(),
Craig Topper1b40b342014-12-13 05:12:19 +00001954 NumberedInsnOperands[Op.second].begin(),
1955 NumberedInsnOperands[Op.second].end());
Hal Finkeld715c3e2013-12-19 16:12:53 +00001956 continue;
Craig Topper1b40b342014-12-13 05:12:19 +00001957 }
1958 if (!NumberedInsnOperands[TiedNames[Op.second]].empty()) {
1959 if (!NumberedInsnOperandsNoTie.count(TiedNames[Op.second])) {
Hal Finkeld715c3e2013-12-19 16:12:53 +00001960 // Figure out to which (sub)operand we're tied.
Craig Topper1b40b342014-12-13 05:12:19 +00001961 unsigned i = CGI.Operands.getOperandNamed(TiedNames[Op.second]);
Hal Finkeld715c3e2013-12-19 16:12:53 +00001962 int tiedTo = CGI.Operands[i].getTiedRegister();
1963 if (tiedTo == -1) {
Craig Topper1b40b342014-12-13 05:12:19 +00001964 i = CGI.Operands.getOperandNamed(Op.second);
Hal Finkeld715c3e2013-12-19 16:12:53 +00001965 tiedTo = CGI.Operands[i].getTiedRegister();
1966 }
1967
1968 if (tiedTo != -1) {
1969 std::pair<unsigned, unsigned> SO =
1970 CGI.Operands.getSubOperandNumber(tiedTo);
1971
Craig Topper1b40b342014-12-13 05:12:19 +00001972 InsnOperands.push_back(NumberedInsnOperands[TiedNames[Op.second]]
Hal Finkeld715c3e2013-12-19 16:12:53 +00001973 [SO.second]);
1974 }
1975 }
1976 continue;
1977 }
1978
Craig Topper1b40b342014-12-13 05:12:19 +00001979 TypedInit *TI = cast<TypedInit>(Op.first);
Owen Andersond1e38df2011-07-28 21:54:31 +00001980
Matt Arsenault2d37e252016-07-18 23:20:46 +00001981 // At this point, we can locate the decoder field, but we need to know how
1982 // to interpret it. As a first step, require the target to provide
1983 // callbacks for decoding register classes.
1984 std::string Decoder = findOperandDecoderMethod(TI);
Nicolai Haehnle8cb107d2018-03-05 14:01:30 +00001985 Record *TypeRecord = cast<DefInit>(TI)->getDef();
Owen Andersond1e38df2011-07-28 21:54:31 +00001986
Petr Pavlud2e1e422015-07-15 08:04:27 +00001987 RecordVal *HasCompleteDecoderVal =
1988 TypeRecord->getValue("hasCompleteDecoder");
1989 BitInit *HasCompleteDecoderBit = HasCompleteDecoderVal ?
1990 dyn_cast<BitInit>(HasCompleteDecoderVal->getValue()) : nullptr;
1991 bool HasCompleteDecoder = HasCompleteDecoderBit ?
1992 HasCompleteDecoderBit->getValue() : true;
1993
1994 OperandInfo OpInfo(Decoder, HasCompleteDecoder);
Owen Andersond1e38df2011-07-28 21:54:31 +00001995 unsigned Base = ~0U;
1996 unsigned Width = 0;
1997 unsigned Offset = 0;
1998
Owen Andersond8c87882011-02-18 21:51:29 +00001999 for (unsigned bi = 0; bi < Bits.getNumBits(); ++bi) {
Craig Topper095734c2014-04-15 07:20:03 +00002000 VarInit *Var = nullptr;
Sean Silva6cfc8062012-10-10 20:24:43 +00002001 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
Owen Andersoncf603952011-08-01 22:45:43 +00002002 if (BI)
Sean Silva6cfc8062012-10-10 20:24:43 +00002003 Var = dyn_cast<VarInit>(BI->getBitVar());
Owen Andersoncf603952011-08-01 22:45:43 +00002004 else
Sean Silva6cfc8062012-10-10 20:24:43 +00002005 Var = dyn_cast<VarInit>(Bits.getBit(bi));
Owen Andersoncf603952011-08-01 22:45:43 +00002006
2007 if (!Var) {
Owen Andersond1e38df2011-07-28 21:54:31 +00002008 if (Base != ~0U) {
2009 OpInfo.addField(Base, Width, Offset);
2010 Base = ~0U;
2011 Width = 0;
2012 Offset = 0;
2013 }
2014 continue;
2015 }
Owen Andersond8c87882011-02-18 21:51:29 +00002016
Craig Topper1b40b342014-12-13 05:12:19 +00002017 if (Var->getName() != Op.second &&
2018 Var->getName() != TiedNames[Op.second]) {
Owen Andersond1e38df2011-07-28 21:54:31 +00002019 if (Base != ~0U) {
2020 OpInfo.addField(Base, Width, Offset);
2021 Base = ~0U;
2022 Width = 0;
2023 Offset = 0;
2024 }
2025 continue;
Owen Andersond8c87882011-02-18 21:51:29 +00002026 }
2027
Owen Andersond1e38df2011-07-28 21:54:31 +00002028 if (Base == ~0U) {
2029 Base = bi;
2030 Width = 1;
Owen Andersoncf603952011-08-01 22:45:43 +00002031 Offset = BI ? BI->getBitNum() : 0;
2032 } else if (BI && BI->getBitNum() != Offset + Width) {
Owen Andersoneb809f52011-07-29 23:01:18 +00002033 OpInfo.addField(Base, Width, Offset);
2034 Base = bi;
2035 Width = 1;
2036 Offset = BI->getBitNum();
Owen Andersond1e38df2011-07-28 21:54:31 +00002037 } else {
2038 ++Width;
Owen Andersond8c87882011-02-18 21:51:29 +00002039 }
Owen Andersond8c87882011-02-18 21:51:29 +00002040 }
2041
Owen Andersond1e38df2011-07-28 21:54:31 +00002042 if (Base != ~0U)
2043 OpInfo.addField(Base, Width, Offset);
2044
2045 if (OpInfo.numFields() > 0)
2046 InsnOperands.push_back(OpInfo);
Owen Andersond8c87882011-02-18 21:51:29 +00002047 }
2048
2049 Operands[Opc] = InsnOperands;
2050
Owen Andersond8c87882011-02-18 21:51:29 +00002051#if 0
Nicola Zaghen0818e782018-05-14 12:53:11 +00002052 LLVM_DEBUG({
Owen Andersond8c87882011-02-18 21:51:29 +00002053 // Dumps the instruction encoding bits.
2054 dumpBits(errs(), Bits);
2055
2056 errs() << '\n';
2057
2058 // Dumps the list of operand info.
2059 for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) {
2060 const CGIOperandList::OperandInfo &Info = CGI.Operands[i];
2061 const std::string &OperandName = Info.Name;
2062 const Record &OperandDef = *Info.Rec;
2063
2064 errs() << "\t" << OperandName << " (" << OperandDef.getName() << ")\n";
2065 }
2066 });
2067#endif
2068
2069 return true;
2070}
2071
Jim Grosbachfc1a1612012-08-14 19:06:05 +00002072// emitFieldFromInstruction - Emit the templated helper function
2073// fieldFromInstruction().
Stella Stamenova4f30db42018-07-25 17:33:20 +00002074// On Windows we make sure that this function is not inlined when
2075// using the VS compiler. It has a bug which causes the function
2076// to be optimized out in some circustances. See llvm.org/pr38292
Jim Grosbachfc1a1612012-08-14 19:06:05 +00002077static void emitFieldFromInstruction(formatted_raw_ostream &OS) {
Daniel Sandersca762c62018-10-23 17:23:31 +00002078 OS << "// Helper functions for extracting fields from encoded instructions.\n"
2079 << "// InsnType must either be integral or an APInt-like object that "
2080 "must:\n"
2081 << "// * Have a static const max_size_in_bits equal to the number of bits "
2082 "in the\n"
2083 << "// encoding.\n"
2084 << "// * be default-constructible and copy-constructible\n"
2085 << "// * be constructible from a uint64_t\n"
2086 << "// * be constructible from an APInt (this can be private)\n"
2087 << "// * Support getBitsSet(loBit, hiBit)\n"
2088 << "// * be convertible to uint64_t\n"
2089 << "// * Support the ~, &, ==, !=, and |= operators with other objects of "
2090 "the same type\n"
2091 << "// * Support shift (<<, >>) with signed and unsigned integers on the "
2092 "RHS\n"
2093 << "// * Support put (<<) to raw_ostream&\n"
Daniel Sanders5b293092018-10-23 17:41:39 +00002094 << "template<typename InsnType>\n"
Stella Stamenova4f30db42018-07-25 17:33:20 +00002095 << "#if defined(_MSC_VER) && !defined(__clang__)\n"
2096 << "__declspec(noinline)\n"
2097 << "#endif\n"
Daniel Sandersca762c62018-10-23 17:23:31 +00002098 << "static InsnType fieldFromInstruction(InsnType insn, unsigned "
2099 "startBit,\n"
2100 << " unsigned numBits, "
2101 "std::true_type) {\n"
2102 << " assert(startBit + numBits <= 64 && \"Cannot support >64-bit "
2103 "extractions!\");\n"
2104 << " assert(startBit + numBits <= (sizeof(InsnType) * 8) &&\n"
2105 << " \"Instruction field out of bounds!\");\n"
2106 << " InsnType fieldMask;\n"
2107 << " if (numBits == sizeof(InsnType) * 8)\n"
2108 << " fieldMask = (InsnType)(-1LL);\n"
2109 << " else\n"
2110 << " fieldMask = (((InsnType)1 << numBits) - 1) << startBit;\n"
2111 << " return (insn & fieldMask) >> startBit;\n"
2112 << "}\n"
2113 << "\n"
2114 << "template<typename InsnType>\n"
2115 << "static InsnType fieldFromInstruction(InsnType insn, unsigned "
2116 "startBit,\n"
2117 << " unsigned numBits, "
2118 "std::false_type) {\n"
2119 << " assert(startBit + numBits <= InsnType::max_size_in_bits && "
2120 "\"Instruction field out of bounds!\");\n"
2121 << " InsnType fieldMask = InsnType::getBitsSet(0, numBits);\n"
2122 << " return (insn >> startBit) & fieldMask;\n"
2123 << "}\n"
2124 << "\n"
2125 << "template<typename InsnType>\n"
2126 << "static InsnType fieldFromInstruction(InsnType insn, unsigned "
2127 "startBit,\n"
Jim Grosbachfc1a1612012-08-14 19:06:05 +00002128 << " unsigned numBits) {\n"
Daniel Sandersca762c62018-10-23 17:23:31 +00002129 << " return fieldFromInstruction(insn, startBit, numBits, "
2130 "std::is_integral<InsnType>());\n"
Jim Grosbachfc1a1612012-08-14 19:06:05 +00002131 << "}\n\n";
2132}
Owen Andersond8c87882011-02-18 21:51:29 +00002133
Jim Grosbachfc1a1612012-08-14 19:06:05 +00002134// emitDecodeInstruction - Emit the templated helper function
2135// decodeInstruction().
2136static void emitDecodeInstruction(formatted_raw_ostream &OS) {
2137 OS << "template<typename InsnType>\n"
Nicola Zaghen0818e782018-05-14 12:53:11 +00002138 << "static DecodeStatus decodeInstruction(const uint8_t DecodeTable[], "
2139 "MCInst &MI,\n"
2140 << " InsnType insn, uint64_t "
2141 "Address,\n"
Jim Grosbachfc1a1612012-08-14 19:06:05 +00002142 << " const void *DisAsm,\n"
2143 << " const MCSubtargetInfo &STI) {\n"
Michael Kupersteind714fcf2015-05-26 10:47:10 +00002144 << " const FeatureBitset& Bits = STI.getFeatureBits();\n"
Jim Grosbachfc1a1612012-08-14 19:06:05 +00002145 << "\n"
2146 << " const uint8_t *Ptr = DecodeTable;\n"
Jim Grosbach9bb938c2012-09-17 18:00:53 +00002147 << " uint32_t CurFieldValue = 0;\n"
Jim Grosbachfc1a1612012-08-14 19:06:05 +00002148 << " DecodeStatus S = MCDisassembler::Success;\n"
Eugene Zelenkoc02caf52016-11-30 17:48:10 +00002149 << " while (true) {\n"
Jim Grosbachfc1a1612012-08-14 19:06:05 +00002150 << " ptrdiff_t Loc = Ptr - DecodeTable;\n"
2151 << " switch (*Ptr) {\n"
2152 << " default:\n"
2153 << " errs() << Loc << \": Unexpected decode table opcode!\\n\";\n"
2154 << " return MCDisassembler::Fail;\n"
2155 << " case MCD::OPC_ExtractField: {\n"
2156 << " unsigned Start = *++Ptr;\n"
2157 << " unsigned Len = *++Ptr;\n"
2158 << " ++Ptr;\n"
2159 << " CurFieldValue = fieldFromInstruction(insn, Start, Len);\n"
Nicola Zaghen0818e782018-05-14 12:53:11 +00002160 << " LLVM_DEBUG(dbgs() << Loc << \": OPC_ExtractField(\" << Start << "
2161 "\", \"\n"
Jim Grosbachfc1a1612012-08-14 19:06:05 +00002162 << " << Len << \"): \" << CurFieldValue << \"\\n\");\n"
2163 << " break;\n"
2164 << " }\n"
2165 << " case MCD::OPC_FilterValue: {\n"
2166 << " // Decode the field value.\n"
2167 << " unsigned Len;\n"
2168 << " InsnType Val = decodeULEB128(++Ptr, &Len);\n"
2169 << " Ptr += Len;\n"
Sander de Smalenc13d5962018-07-05 10:39:15 +00002170 << " // NumToSkip is a plain 24-bit integer.\n"
Jim Grosbachfc1a1612012-08-14 19:06:05 +00002171 << " unsigned NumToSkip = *Ptr++;\n"
2172 << " NumToSkip |= (*Ptr++) << 8;\n"
Sander de Smalenc13d5962018-07-05 10:39:15 +00002173 << " NumToSkip |= (*Ptr++) << 16;\n"
Jim Grosbachfc1a1612012-08-14 19:06:05 +00002174 << "\n"
2175 << " // Perform the filter operation.\n"
2176 << " if (Val != CurFieldValue)\n"
2177 << " Ptr += NumToSkip;\n"
Nicola Zaghen0818e782018-05-14 12:53:11 +00002178 << " LLVM_DEBUG(dbgs() << Loc << \": OPC_FilterValue(\" << Val << "
2179 "\", \" << NumToSkip\n"
2180 << " << \"): \" << ((Val != CurFieldValue) ? \"FAIL:\" "
2181 ": \"PASS:\")\n"
2182 << " << \" continuing at \" << (Ptr - DecodeTable) << "
2183 "\"\\n\");\n"
Jim Grosbachfc1a1612012-08-14 19:06:05 +00002184 << "\n"
2185 << " break;\n"
2186 << " }\n"
2187 << " case MCD::OPC_CheckField: {\n"
2188 << " unsigned Start = *++Ptr;\n"
2189 << " unsigned Len = *++Ptr;\n"
2190 << " InsnType FieldValue = fieldFromInstruction(insn, Start, Len);\n"
2191 << " // Decode the field value.\n"
2192 << " uint32_t ExpectedValue = decodeULEB128(++Ptr, &Len);\n"
2193 << " Ptr += Len;\n"
Sander de Smalenc13d5962018-07-05 10:39:15 +00002194 << " // NumToSkip is a plain 24-bit integer.\n"
Jim Grosbachfc1a1612012-08-14 19:06:05 +00002195 << " unsigned NumToSkip = *Ptr++;\n"
2196 << " NumToSkip |= (*Ptr++) << 8;\n"
Sander de Smalenc13d5962018-07-05 10:39:15 +00002197 << " NumToSkip |= (*Ptr++) << 16;\n"
Jim Grosbachfc1a1612012-08-14 19:06:05 +00002198 << "\n"
2199 << " // If the actual and expected values don't match, skip.\n"
2200 << " if (ExpectedValue != FieldValue)\n"
2201 << " Ptr += NumToSkip;\n"
Nicola Zaghen0818e782018-05-14 12:53:11 +00002202 << " LLVM_DEBUG(dbgs() << Loc << \": OPC_CheckField(\" << Start << "
2203 "\", \"\n"
2204 << " << Len << \", \" << ExpectedValue << \", \" << "
2205 "NumToSkip\n"
2206 << " << \"): FieldValue = \" << FieldValue << \", "
2207 "ExpectedValue = \"\n"
Jim Grosbachfc1a1612012-08-14 19:06:05 +00002208 << " << ExpectedValue << \": \"\n"
Nicola Zaghen0818e782018-05-14 12:53:11 +00002209 << " << ((ExpectedValue == FieldValue) ? \"PASS\\n\" : "
2210 "\"FAIL\\n\"));\n"
Jim Grosbachfc1a1612012-08-14 19:06:05 +00002211 << " break;\n"
2212 << " }\n"
2213 << " case MCD::OPC_CheckPredicate: {\n"
2214 << " unsigned Len;\n"
2215 << " // Decode the Predicate Index value.\n"
2216 << " unsigned PIdx = decodeULEB128(++Ptr, &Len);\n"
2217 << " Ptr += Len;\n"
Sander de Smalenc13d5962018-07-05 10:39:15 +00002218 << " // NumToSkip is a plain 24-bit integer.\n"
Jim Grosbachfc1a1612012-08-14 19:06:05 +00002219 << " unsigned NumToSkip = *Ptr++;\n"
2220 << " NumToSkip |= (*Ptr++) << 8;\n"
Sander de Smalenc13d5962018-07-05 10:39:15 +00002221 << " NumToSkip |= (*Ptr++) << 16;\n"
Jim Grosbachfc1a1612012-08-14 19:06:05 +00002222 << " // Check the predicate.\n"
2223 << " bool Pred;\n"
2224 << " if (!(Pred = checkDecoderPredicate(PIdx, Bits)))\n"
2225 << " Ptr += NumToSkip;\n"
2226 << " (void)Pred;\n"
Nicola Zaghen0818e782018-05-14 12:53:11 +00002227 << " LLVM_DEBUG(dbgs() << Loc << \": OPC_CheckPredicate(\" << PIdx "
2228 "<< \"): \"\n"
Jim Grosbachfc1a1612012-08-14 19:06:05 +00002229 << " << (Pred ? \"PASS\\n\" : \"FAIL\\n\"));\n"
2230 << "\n"
2231 << " break;\n"
2232 << " }\n"
2233 << " case MCD::OPC_Decode: {\n"
2234 << " unsigned Len;\n"
2235 << " // Decode the Opcode value.\n"
2236 << " unsigned Opc = decodeULEB128(++Ptr, &Len);\n"
2237 << " Ptr += Len;\n"
2238 << " unsigned DecodeIdx = decodeULEB128(Ptr, &Len);\n"
2239 << " Ptr += Len;\n"
Jim Grosbachfc1a1612012-08-14 19:06:05 +00002240 << "\n"
Cameron Esfahani7ec94a32015-08-11 01:15:07 +00002241 << " MI.clear();\n"
Jim Grosbachfc1a1612012-08-14 19:06:05 +00002242 << " MI.setOpcode(Opc);\n"
Petr Pavlud2e1e422015-07-15 08:04:27 +00002243 << " bool DecodeComplete;\n"
Nicola Zaghen0818e782018-05-14 12:53:11 +00002244 << " S = decodeToMCInst(S, DecodeIdx, insn, MI, Address, DisAsm, "
2245 "DecodeComplete);\n"
Petr Pavlud2e1e422015-07-15 08:04:27 +00002246 << " assert(DecodeComplete);\n"
2247 << "\n"
Nicola Zaghen0818e782018-05-14 12:53:11 +00002248 << " LLVM_DEBUG(dbgs() << Loc << \": OPC_Decode: opcode \" << Opc\n"
Petr Pavlud2e1e422015-07-15 08:04:27 +00002249 << " << \", using decoder \" << DecodeIdx << \": \"\n"
Nicola Zaghen0818e782018-05-14 12:53:11 +00002250 << " << (S != MCDisassembler::Fail ? \"PASS\" : "
2251 "\"FAIL\") << \"\\n\");\n"
Petr Pavlud2e1e422015-07-15 08:04:27 +00002252 << " return S;\n"
2253 << " }\n"
2254 << " case MCD::OPC_TryDecode: {\n"
2255 << " unsigned Len;\n"
2256 << " // Decode the Opcode value.\n"
2257 << " unsigned Opc = decodeULEB128(++Ptr, &Len);\n"
2258 << " Ptr += Len;\n"
2259 << " unsigned DecodeIdx = decodeULEB128(Ptr, &Len);\n"
2260 << " Ptr += Len;\n"
Sander de Smalenc13d5962018-07-05 10:39:15 +00002261 << " // NumToSkip is a plain 24-bit integer.\n"
Petr Pavlud2e1e422015-07-15 08:04:27 +00002262 << " unsigned NumToSkip = *Ptr++;\n"
2263 << " NumToSkip |= (*Ptr++) << 8;\n"
Sander de Smalenc13d5962018-07-05 10:39:15 +00002264 << " NumToSkip |= (*Ptr++) << 16;\n"
Petr Pavlud2e1e422015-07-15 08:04:27 +00002265 << "\n"
2266 << " // Perform the decode operation.\n"
2267 << " MCInst TmpMI;\n"
2268 << " TmpMI.setOpcode(Opc);\n"
2269 << " bool DecodeComplete;\n"
Nicola Zaghen0818e782018-05-14 12:53:11 +00002270 << " S = decodeToMCInst(S, DecodeIdx, insn, TmpMI, Address, DisAsm, "
2271 "DecodeComplete);\n"
2272 << " LLVM_DEBUG(dbgs() << Loc << \": OPC_TryDecode: opcode \" << "
2273 "Opc\n"
Petr Pavlud2e1e422015-07-15 08:04:27 +00002274 << " << \", using decoder \" << DecodeIdx << \": \");\n"
2275 << "\n"
2276 << " if (DecodeComplete) {\n"
2277 << " // Decoding complete.\n"
Nicola Zaghen0818e782018-05-14 12:53:11 +00002278 << " LLVM_DEBUG(dbgs() << (S != MCDisassembler::Fail ? \"PASS\" : "
2279 "\"FAIL\") << \"\\n\");\n"
Petr Pavlud2e1e422015-07-15 08:04:27 +00002280 << " MI = TmpMI;\n"
2281 << " return S;\n"
2282 << " } else {\n"
2283 << " assert(S == MCDisassembler::Fail);\n"
2284 << " // If the decoding was incomplete, skip.\n"
2285 << " Ptr += NumToSkip;\n"
Nicola Zaghen0818e782018-05-14 12:53:11 +00002286 << " LLVM_DEBUG(dbgs() << \"FAIL: continuing at \" << (Ptr - "
2287 "DecodeTable) << \"\\n\");\n"
2288 << " // Reset decode status. This also drops a SoftFail status "
2289 "that could be\n"
Petr Pavlud2e1e422015-07-15 08:04:27 +00002290 << " // set before the decode attempt.\n"
2291 << " S = MCDisassembler::Success;\n"
2292 << " }\n"
2293 << " break;\n"
Jim Grosbachfc1a1612012-08-14 19:06:05 +00002294 << " }\n"
2295 << " case MCD::OPC_SoftFail: {\n"
2296 << " // Decode the mask values.\n"
2297 << " unsigned Len;\n"
2298 << " InsnType PositiveMask = decodeULEB128(++Ptr, &Len);\n"
2299 << " Ptr += Len;\n"
2300 << " InsnType NegativeMask = decodeULEB128(Ptr, &Len);\n"
2301 << " Ptr += Len;\n"
2302 << " bool Fail = (insn & PositiveMask) || (~insn & NegativeMask);\n"
2303 << " if (Fail)\n"
2304 << " S = MCDisassembler::SoftFail;\n"
Nicola Zaghen0818e782018-05-14 12:53:11 +00002305 << " LLVM_DEBUG(dbgs() << Loc << \": OPC_SoftFail: \" << (Fail ? "
2306 "\"FAIL\\n\":\"PASS\\n\"));\n"
Jim Grosbachfc1a1612012-08-14 19:06:05 +00002307 << " break;\n"
2308 << " }\n"
2309 << " case MCD::OPC_Fail: {\n"
Nicola Zaghen0818e782018-05-14 12:53:11 +00002310 << " LLVM_DEBUG(dbgs() << Loc << \": OPC_Fail\\n\");\n"
Jim Grosbachfc1a1612012-08-14 19:06:05 +00002311 << " return MCDisassembler::Fail;\n"
2312 << " }\n"
2313 << " }\n"
2314 << " }\n"
Nicola Zaghen0818e782018-05-14 12:53:11 +00002315 << " llvm_unreachable(\"bogosity detected in disassembler state "
2316 "machine!\");\n"
Jim Grosbachfc1a1612012-08-14 19:06:05 +00002317 << "}\n\n";
Owen Andersond8c87882011-02-18 21:51:29 +00002318}
2319
2320// Emits disassembler code for instruction decoding.
Craig Topperd9360452012-03-16 01:19:24 +00002321void FixedLenDecoderEmitter::run(raw_ostream &o) {
Jim Grosbachfc1a1612012-08-14 19:06:05 +00002322 formatted_raw_ostream OS(o);
2323 OS << "#include \"llvm/MC/MCInst.h\"\n";
2324 OS << "#include \"llvm/Support/Debug.h\"\n";
2325 OS << "#include \"llvm/Support/DataTypes.h\"\n";
2326 OS << "#include \"llvm/Support/LEB128.h\"\n";
2327 OS << "#include \"llvm/Support/raw_ostream.h\"\n";
2328 OS << "#include <assert.h>\n";
2329 OS << '\n';
2330 OS << "namespace llvm {\n\n";
2331
2332 emitFieldFromInstruction(OS);
Owen Andersond8c87882011-02-18 21:51:29 +00002333
Hal Finkelaf73dfe2013-12-17 22:37:50 +00002334 Target.reverseBitsForLittleEndianEncoding();
2335
Owen Andersonf1a00902011-07-19 21:06:00 +00002336 // Parameterize the decoders based on namespace and instruction width.
Daniel Sanders0de70682018-12-13 16:17:54 +00002337 const auto &NumberedInstructions = Target.getInstructionsByEnumValue();
2338 NumberedEncodings.reserve(NumberedInstructions.size());
2339 for (const auto &NumberedInstruction : NumberedInstructions)
2340 NumberedEncodings.emplace_back(NumberedInstruction->TheDef, NumberedInstruction);
2341
Owen Andersonf1a00902011-07-19 21:06:00 +00002342 std::map<std::pair<std::string, unsigned>,
Eugene Zelenkoc02caf52016-11-30 17:48:10 +00002343 std::vector<unsigned>> OpcMap;
2344 std::map<unsigned, std::vector<OperandInfo>> Operands;
Owen Andersonf1a00902011-07-19 21:06:00 +00002345
Daniel Sanders0de70682018-12-13 16:17:54 +00002346 for (unsigned i = 0; i < NumberedEncodings.size(); ++i) {
2347 const CodeGenInstruction *Inst = NumberedEncodings[i].Inst;
Craig Toppereb5cd612012-03-16 05:58:09 +00002348 const Record *Def = Inst->TheDef;
Owen Andersonf1a00902011-07-19 21:06:00 +00002349 unsigned Size = Def->getValueAsInt("Size");
2350 if (Def->getValueAsString("Namespace") == "TargetOpcode" ||
2351 Def->getValueAsBit("isPseudo") ||
2352 Def->getValueAsBit("isAsmParserOnly") ||
2353 Def->getValueAsBit("isCodeGenOnly"))
2354 continue;
2355
Craig Topper2a129872017-05-31 21:12:46 +00002356 StringRef DecoderNamespace = Def->getValueAsString("DecoderNamespace");
Owen Andersonf1a00902011-07-19 21:06:00 +00002357
2358 if (Size) {
Hal Finkeld715c3e2013-12-19 16:12:53 +00002359 if (populateInstruction(Target, *Inst, i, Operands)) {
Owen Andersonf1a00902011-07-19 21:06:00 +00002360 OpcMap[std::make_pair(DecoderNamespace, Size)].push_back(i);
2361 }
2362 }
2363 }
2364
Jim Grosbachfc1a1612012-08-14 19:06:05 +00002365 DecoderTableInfo TableInfo;
Craig Topper1b40b342014-12-13 05:12:19 +00002366 for (const auto &Opc : OpcMap) {
Owen Andersonf1a00902011-07-19 21:06:00 +00002367 // Emit the decoder for this namespace+width combination.
Daniel Sanders0de70682018-12-13 16:17:54 +00002368 ArrayRef<EncodingAndInst> NumberedEncodingsRef(NumberedEncodings.data(),
2369 NumberedEncodings.size());
2370 FilterChooser FC(NumberedEncodingsRef, Opc.second, Operands,
2371 8 * Opc.first.second, this);
Jim Grosbachfc1a1612012-08-14 19:06:05 +00002372
2373 // The decode table is cleared for each top level decoder function. The
2374 // predicates and decoders themselves, however, are shared across all
2375 // decoders to give more opportunities for uniqueing.
2376 TableInfo.Table.clear();
2377 TableInfo.FixupStack.clear();
2378 TableInfo.Table.reserve(16384);
Benjamin Kramer9589ff82015-05-29 19:43:39 +00002379 TableInfo.FixupStack.emplace_back();
Jim Grosbachfc1a1612012-08-14 19:06:05 +00002380 FC.emitTableEntries(TableInfo);
2381 // Any NumToSkip fixups in the top level scope can resolve to the
2382 // OPC_Fail at the end of the table.
2383 assert(TableInfo.FixupStack.size() == 1 && "fixup stack phasing error!");
2384 // Resolve any NumToSkip fixups in the current scope.
2385 resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),
2386 TableInfo.Table.size());
2387 TableInfo.FixupStack.clear();
2388
2389 TableInfo.Table.push_back(MCD::OPC_Fail);
2390
2391 // Print the table to the output stream.
Craig Topper1b40b342014-12-13 05:12:19 +00002392 emitTable(OS, TableInfo.Table, 0, FC.getBitWidth(), Opc.first.first);
Jim Grosbachfc1a1612012-08-14 19:06:05 +00002393 OS.flush();
Owen Andersonf1a00902011-07-19 21:06:00 +00002394 }
Owen Andersond8c87882011-02-18 21:51:29 +00002395
Jim Grosbachfc1a1612012-08-14 19:06:05 +00002396 // Emit the predicate function.
2397 emitPredicateFunction(OS, TableInfo.Predicates, 0);
2398
2399 // Emit the decoder function.
2400 emitDecoderFunction(OS, TableInfo.Decoders, 0);
2401
2402 // Emit the main entry point for the decoder, decodeInstruction().
2403 emitDecodeInstruction(OS);
2404
2405 OS << "\n} // End llvm namespace\n";
Owen Andersond8c87882011-02-18 21:51:29 +00002406}
Jakob Stoklund Olesen6f36fa92012-06-11 15:37:55 +00002407
2408namespace llvm {
2409
2410void EmitFixedLenDecoder(RecordKeeper &RK, raw_ostream &OS,
Benjamin Kramer36538ff2016-06-08 19:09:22 +00002411 const std::string &PredicateNamespace,
2412 const std::string &GPrefix,
2413 const std::string &GPostfix, const std::string &ROK,
2414 const std::string &RFail, const std::string &L) {
Jakob Stoklund Olesen6f36fa92012-06-11 15:37:55 +00002415 FixedLenDecoderEmitter(RK, PredicateNamespace, GPrefix, GPostfix,
2416 ROK, RFail, L).run(OS);
2417}
2418
Eugene Zelenkoc02caf52016-11-30 17:48:10 +00002419} // end namespace llvm