blob: c0a0a80f1da578e08ce8cbff4e4e57cc8a6f1041 [file] [log] [blame]
Owen Andersond8c87882011-02-18 21:51:29 +00001//===------------ FixedLenDecoderEmitter.cpp - Decoder Generator ----------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// It contains the tablegen backend that emits the decoder functions for
11// targets with fixed length instruction set.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "decoder-emitter"
16
17#include "FixedLenDecoderEmitter.h"
18#include "CodeGenTarget.h"
Peter Collingbourne7c788882011-10-01 16:41:13 +000019#include "llvm/TableGen/Record.h"
Owen Andersond8c87882011-02-18 21:51:29 +000020#include "llvm/ADT/StringExtras.h"
21#include "llvm/Support/Debug.h"
22#include "llvm/Support/raw_ostream.h"
23
24#include <vector>
25#include <map>
26#include <string>
27
28using namespace llvm;
29
30// The set (BIT_TRUE, BIT_FALSE, BIT_UNSET) represents a ternary logic system
31// for a bit value.
32//
33// BIT_UNFILTERED is used as the init value for a filter position. It is used
34// only for filter processings.
35typedef enum {
36 BIT_TRUE, // '1'
37 BIT_FALSE, // '0'
38 BIT_UNSET, // '?'
39 BIT_UNFILTERED // unfiltered
40} bit_value_t;
41
42static bool ValueSet(bit_value_t V) {
43 return (V == BIT_TRUE || V == BIT_FALSE);
44}
45static bool ValueNotSet(bit_value_t V) {
46 return (V == BIT_UNSET);
47}
48static int Value(bit_value_t V) {
49 return ValueNotSet(V) ? -1 : (V == BIT_FALSE ? 0 : 1);
50}
David Greene05bce0b2011-07-29 22:43:06 +000051static bit_value_t bitFromBits(BitsInit &bits, unsigned index) {
52 if (BitInit *bit = dynamic_cast<BitInit*>(bits.getBit(index)))
Owen Andersond8c87882011-02-18 21:51:29 +000053 return bit->getValue() ? BIT_TRUE : BIT_FALSE;
54
55 // The bit is uninitialized.
56 return BIT_UNSET;
57}
58// Prints the bit value for each position.
David Greene05bce0b2011-07-29 22:43:06 +000059static void dumpBits(raw_ostream &o, BitsInit &bits) {
Owen Andersond8c87882011-02-18 21:51:29 +000060 unsigned index;
61
62 for (index = bits.getNumBits(); index > 0; index--) {
63 switch (bitFromBits(bits, index - 1)) {
64 case BIT_TRUE:
65 o << "1";
66 break;
67 case BIT_FALSE:
68 o << "0";
69 break;
70 case BIT_UNSET:
71 o << "_";
72 break;
73 default:
Craig Topper655b8de2012-02-05 07:21:30 +000074 llvm_unreachable("unexpected return value from bitFromBits");
Owen Andersond8c87882011-02-18 21:51:29 +000075 }
76 }
77}
78
David Greene05bce0b2011-07-29 22:43:06 +000079static BitsInit &getBitsField(const Record &def, const char *str) {
80 BitsInit *bits = def.getValueAsBitsInit(str);
Owen Andersond8c87882011-02-18 21:51:29 +000081 return *bits;
82}
83
84// Forward declaration.
85class FilterChooser;
86
Owen Andersond8c87882011-02-18 21:51:29 +000087// Representation of the instruction to work on.
Owen Andersonf1a00902011-07-19 21:06:00 +000088typedef std::vector<bit_value_t> insn_t;
Owen Andersond8c87882011-02-18 21:51:29 +000089
90/// Filter - Filter works with FilterChooser to produce the decoding tree for
91/// the ISA.
92///
93/// It is useful to think of a Filter as governing the switch stmts of the
94/// decoding tree in a certain level. Each case stmt delegates to an inferior
95/// FilterChooser to decide what further decoding logic to employ, or in another
96/// words, what other remaining bits to look at. The FilterChooser eventually
97/// chooses a best Filter to do its job.
98///
99/// This recursive scheme ends when the number of Opcodes assigned to the
100/// FilterChooser becomes 1 or if there is a conflict. A conflict happens when
101/// the Filter/FilterChooser combo does not know how to distinguish among the
102/// Opcodes assigned.
103///
104/// An example of a conflict is
105///
106/// Conflict:
107/// 111101000.00........00010000....
108/// 111101000.00........0001........
109/// 1111010...00........0001........
110/// 1111010...00....................
111/// 1111010.........................
112/// 1111............................
113/// ................................
114/// VST4q8a 111101000_00________00010000____
115/// VST4q8b 111101000_00________00010000____
116///
117/// The Debug output shows the path that the decoding tree follows to reach the
118/// the conclusion that there is a conflict. VST4q8a is a vst4 to double-spaced
119/// even registers, while VST4q8b is a vst4 to double-spaced odd regsisters.
120///
121/// The encoding info in the .td files does not specify this meta information,
122/// which could have been used by the decoder to resolve the conflict. The
123/// decoder could try to decode the even/odd register numbering and assign to
124/// VST4q8a or VST4q8b, but for the time being, the decoder chooses the "a"
125/// version and return the Opcode since the two have the same Asm format string.
126class Filter {
127protected:
128 FilterChooser *Owner; // points to the FilterChooser who owns this filter
129 unsigned StartBit; // the starting bit position
130 unsigned NumBits; // number of bits to filter
131 bool Mixed; // a mixed region contains both set and unset bits
132
133 // Map of well-known segment value to the set of uid's with that value.
134 std::map<uint64_t, std::vector<unsigned> > FilteredInstructions;
135
136 // Set of uid's with non-constant segment values.
137 std::vector<unsigned> VariableInstructions;
138
139 // Map of well-known segment value to its delegate.
140 std::map<unsigned, FilterChooser*> FilterChooserMap;
141
142 // Number of instructions which fall under FilteredInstructions category.
143 unsigned NumFiltered;
144
145 // Keeps track of the last opcode in the filtered bucket.
146 unsigned LastOpcFiltered;
147
148 // Number of instructions which fall under VariableInstructions category.
149 unsigned NumVariable;
150
151public:
152 unsigned getNumFiltered() { return NumFiltered; }
153 unsigned getNumVariable() { return NumVariable; }
154 unsigned getSingletonOpc() {
155 assert(NumFiltered == 1);
156 return LastOpcFiltered;
157 }
158 // Return the filter chooser for the group of instructions without constant
159 // segment values.
160 FilterChooser &getVariableFC() {
161 assert(NumFiltered == 1);
162 assert(FilterChooserMap.size() == 1);
163 return *(FilterChooserMap.find((unsigned)-1)->second);
164 }
165
166 Filter(const Filter &f);
167 Filter(FilterChooser &owner, unsigned startBit, unsigned numBits, bool mixed);
168
169 ~Filter();
170
171 // Divides the decoding task into sub tasks and delegates them to the
172 // inferior FilterChooser's.
173 //
174 // A special case arises when there's only one entry in the filtered
175 // instructions. In order to unambiguously decode the singleton, we need to
176 // match the remaining undecoded encoding bits against the singleton.
177 void recurse();
178
179 // Emit code to decode instructions given a segment or segments of bits.
180 void emit(raw_ostream &o, unsigned &Indentation);
181
182 // Returns the number of fanout produced by the filter. More fanout implies
183 // the filter distinguishes more categories of instructions.
184 unsigned usefulness() const;
185}; // End of class Filter
186
187// These are states of our finite state machines used in FilterChooser's
188// filterProcessor() which produces the filter candidates to use.
189typedef enum {
190 ATTR_NONE,
191 ATTR_FILTERED,
192 ATTR_ALL_SET,
193 ATTR_ALL_UNSET,
194 ATTR_MIXED
195} bitAttr_t;
196
197/// FilterChooser - FilterChooser chooses the best filter among a set of Filters
198/// in order to perform the decoding of instructions at the current level.
199///
200/// Decoding proceeds from the top down. Based on the well-known encoding bits
201/// of instructions available, FilterChooser builds up the possible Filters that
202/// can further the task of decoding by distinguishing among the remaining
203/// candidate instructions.
204///
205/// Once a filter has been chosen, it is called upon to divide the decoding task
206/// into sub-tasks and delegates them to its inferior FilterChoosers for further
207/// processings.
208///
209/// It is useful to think of a Filter as governing the switch stmts of the
210/// decoding tree. And each case is delegated to an inferior FilterChooser to
211/// decide what further remaining bits to look at.
212class FilterChooser {
213protected:
214 friend class Filter;
215
216 // Vector of codegen instructions to choose our filter.
217 const std::vector<const CodeGenInstruction*> &AllInstructions;
218
219 // Vector of uid's for this filter chooser to work on.
220 const std::vector<unsigned> Opcodes;
221
222 // Lookup table for the operand decoding of instructions.
223 std::map<unsigned, std::vector<OperandInfo> > &Operands;
224
225 // Vector of candidate filters.
226 std::vector<Filter> Filters;
227
228 // Array of bit values passed down from our parent.
229 // Set to all BIT_UNFILTERED's for Parent == NULL.
Owen Andersonf1a00902011-07-19 21:06:00 +0000230 std::vector<bit_value_t> FilterBitValues;
Owen Andersond8c87882011-02-18 21:51:29 +0000231
232 // Links to the FilterChooser above us in the decoding tree.
233 FilterChooser *Parent;
234
235 // Index of the best filter from Filters.
236 int BestIndex;
237
Owen Andersonf1a00902011-07-19 21:06:00 +0000238 // Width of instructions
239 unsigned BitWidth;
240
Owen Anderson83e3f672011-08-17 17:44:15 +0000241 // Parent emitter
242 const FixedLenDecoderEmitter *Emitter;
243
Owen Andersond8c87882011-02-18 21:51:29 +0000244public:
245 FilterChooser(const FilterChooser &FC) :
246 AllInstructions(FC.AllInstructions), Opcodes(FC.Opcodes),
Owen Andersonf1a00902011-07-19 21:06:00 +0000247 Operands(FC.Operands), Filters(FC.Filters),
248 FilterBitValues(FC.FilterBitValues), Parent(FC.Parent),
Owen Anderson83e3f672011-08-17 17:44:15 +0000249 BestIndex(FC.BestIndex), BitWidth(FC.BitWidth),
250 Emitter(FC.Emitter) { }
Owen Andersond8c87882011-02-18 21:51:29 +0000251
252 FilterChooser(const std::vector<const CodeGenInstruction*> &Insts,
253 const std::vector<unsigned> &IDs,
Owen Andersonf1a00902011-07-19 21:06:00 +0000254 std::map<unsigned, std::vector<OperandInfo> > &Ops,
Owen Anderson83e3f672011-08-17 17:44:15 +0000255 unsigned BW,
256 const FixedLenDecoderEmitter *E) :
Owen Andersond8c87882011-02-18 21:51:29 +0000257 AllInstructions(Insts), Opcodes(IDs), Operands(Ops), Filters(),
Owen Anderson83e3f672011-08-17 17:44:15 +0000258 Parent(NULL), BestIndex(-1), BitWidth(BW), Emitter(E) {
Owen Andersonf1a00902011-07-19 21:06:00 +0000259 for (unsigned i = 0; i < BitWidth; ++i)
260 FilterBitValues.push_back(BIT_UNFILTERED);
Owen Andersond8c87882011-02-18 21:51:29 +0000261
262 doFilter();
263 }
264
265 FilterChooser(const std::vector<const CodeGenInstruction*> &Insts,
266 const std::vector<unsigned> &IDs,
267 std::map<unsigned, std::vector<OperandInfo> > &Ops,
Owen Andersonf1a00902011-07-19 21:06:00 +0000268 std::vector<bit_value_t> &ParentFilterBitValues,
Owen Andersond8c87882011-02-18 21:51:29 +0000269 FilterChooser &parent) :
270 AllInstructions(Insts), Opcodes(IDs), Operands(Ops),
Owen Andersonf1a00902011-07-19 21:06:00 +0000271 Filters(), FilterBitValues(ParentFilterBitValues),
Owen Anderson83e3f672011-08-17 17:44:15 +0000272 Parent(&parent), BestIndex(-1), BitWidth(parent.BitWidth),
273 Emitter(parent.Emitter) {
Owen Andersond8c87882011-02-18 21:51:29 +0000274 doFilter();
275 }
276
277 // The top level filter chooser has NULL as its parent.
278 bool isTopLevel() { return Parent == NULL; }
279
280 // Emit the top level typedef and decodeInstruction() function.
Owen Andersonf1a00902011-07-19 21:06:00 +0000281 void emitTop(raw_ostream &o, unsigned Indentation, std::string Namespace);
Owen Andersond8c87882011-02-18 21:51:29 +0000282
283protected:
284 // Populates the insn given the uid.
285 void insnWithID(insn_t &Insn, unsigned Opcode) const {
David Greene05bce0b2011-07-29 22:43:06 +0000286 BitsInit &Bits = getBitsField(*AllInstructions[Opcode]->TheDef, "Inst");
Owen Andersond8c87882011-02-18 21:51:29 +0000287
Owen Andersonf1a00902011-07-19 21:06:00 +0000288 for (unsigned i = 0; i < BitWidth; ++i)
289 Insn.push_back(bitFromBits(Bits, i));
Owen Andersond8c87882011-02-18 21:51:29 +0000290 }
291
292 // Returns the record name.
293 const std::string &nameWithID(unsigned Opcode) const {
294 return AllInstructions[Opcode]->TheDef->getName();
295 }
296
297 // Populates the field of the insn given the start position and the number of
298 // consecutive bits to scan for.
299 //
300 // Returns false if there exists any uninitialized bit value in the range.
301 // Returns true, otherwise.
302 bool fieldFromInsn(uint64_t &Field, insn_t &Insn, unsigned StartBit,
303 unsigned NumBits) const;
304
305 /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
306 /// filter array as a series of chars.
Owen Andersonf1a00902011-07-19 21:06:00 +0000307 void dumpFilterArray(raw_ostream &o, std::vector<bit_value_t> & filter);
Owen Andersond8c87882011-02-18 21:51:29 +0000308
309 /// dumpStack - dumpStack traverses the filter chooser chain and calls
310 /// dumpFilterArray on each filter chooser up to the top level one.
311 void dumpStack(raw_ostream &o, const char *prefix);
312
313 Filter &bestFilter() {
314 assert(BestIndex != -1 && "BestIndex not set");
315 return Filters[BestIndex];
316 }
317
318 // Called from Filter::recurse() when singleton exists. For debug purpose.
319 void SingletonExists(unsigned Opc);
320
321 bool PositionFiltered(unsigned i) {
322 return ValueSet(FilterBitValues[i]);
323 }
324
325 // Calculates the island(s) needed to decode the instruction.
326 // This returns a lit of undecoded bits of an instructions, for example,
327 // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
328 // decoded bits in order to verify that the instruction matches the Opcode.
329 unsigned getIslands(std::vector<unsigned> &StartBits,
330 std::vector<unsigned> &EndBits, std::vector<uint64_t> &FieldVals,
331 insn_t &Insn);
332
James Molloya5d58562011-09-07 19:42:28 +0000333 // Emits code to check the Predicates member of an instruction are true.
334 // Returns true if predicate matches were emitted, false otherwise.
335 bool emitPredicateMatch(raw_ostream &o, unsigned &Indentation,unsigned Opc);
336
Owen Andersond8c87882011-02-18 21:51:29 +0000337 // Emits code to decode the singleton. Return true if we have matched all the
338 // well-known bits.
339 bool emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,unsigned Opc);
340
341 // Emits code to decode the singleton, and then to decode the rest.
342 void emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,Filter &Best);
343
Owen Andersond1e38df2011-07-28 21:54:31 +0000344 void emitBinaryParser(raw_ostream &o , unsigned &Indentation,
345 OperandInfo &OpInfo);
346
Owen Andersond8c87882011-02-18 21:51:29 +0000347 // Assign a single filter and run with it.
348 void runSingleFilter(FilterChooser &owner, unsigned startBit, unsigned numBit,
349 bool mixed);
350
351 // reportRegion is a helper function for filterProcessor to mark a region as
352 // eligible for use as a filter region.
353 void reportRegion(bitAttr_t RA, unsigned StartBit, unsigned BitIndex,
354 bool AllowMixed);
355
356 // FilterProcessor scans the well-known encoding bits of the instructions and
357 // builds up a list of candidate filters. It chooses the best filter and
358 // recursively descends down the decoding tree.
359 bool filterProcessor(bool AllowMixed, bool Greedy = true);
360
361 // Decides on the best configuration of filter(s) to use in order to decode
362 // the instructions. A conflict of instructions may occur, in which case we
363 // dump the conflict set to the standard error.
364 void doFilter();
365
366 // Emits code to decode our share of instructions. Returns true if the
367 // emitted code causes a return, which occurs if we know how to decode
368 // the instruction at this level or the instruction is not decodeable.
369 bool emit(raw_ostream &o, unsigned &Indentation);
370};
371
372///////////////////////////
373// //
374// Filter Implmenetation //
375// //
376///////////////////////////
377
378Filter::Filter(const Filter &f) :
379 Owner(f.Owner), StartBit(f.StartBit), NumBits(f.NumBits), Mixed(f.Mixed),
380 FilteredInstructions(f.FilteredInstructions),
381 VariableInstructions(f.VariableInstructions),
382 FilterChooserMap(f.FilterChooserMap), NumFiltered(f.NumFiltered),
383 LastOpcFiltered(f.LastOpcFiltered), NumVariable(f.NumVariable) {
384}
385
386Filter::Filter(FilterChooser &owner, unsigned startBit, unsigned numBits,
387 bool mixed) : Owner(&owner), StartBit(startBit), NumBits(numBits),
388 Mixed(mixed) {
Owen Andersonf1a00902011-07-19 21:06:00 +0000389 assert(StartBit + NumBits - 1 < Owner->BitWidth);
Owen Andersond8c87882011-02-18 21:51:29 +0000390
391 NumFiltered = 0;
392 LastOpcFiltered = 0;
393 NumVariable = 0;
394
395 for (unsigned i = 0, e = Owner->Opcodes.size(); i != e; ++i) {
396 insn_t Insn;
397
398 // Populates the insn given the uid.
399 Owner->insnWithID(Insn, Owner->Opcodes[i]);
400
401 uint64_t Field;
402 // Scans the segment for possibly well-specified encoding bits.
403 bool ok = Owner->fieldFromInsn(Field, Insn, StartBit, NumBits);
404
405 if (ok) {
406 // The encoding bits are well-known. Lets add the uid of the
407 // instruction into the bucket keyed off the constant field value.
408 LastOpcFiltered = Owner->Opcodes[i];
409 FilteredInstructions[Field].push_back(LastOpcFiltered);
410 ++NumFiltered;
411 } else {
412 // Some of the encoding bit(s) are unspecfied. This contributes to
413 // one additional member of "Variable" instructions.
414 VariableInstructions.push_back(Owner->Opcodes[i]);
415 ++NumVariable;
416 }
417 }
418
419 assert((FilteredInstructions.size() + VariableInstructions.size() > 0)
420 && "Filter returns no instruction categories");
421}
422
423Filter::~Filter() {
424 std::map<unsigned, FilterChooser*>::iterator filterIterator;
425 for (filterIterator = FilterChooserMap.begin();
426 filterIterator != FilterChooserMap.end();
427 filterIterator++) {
428 delete filterIterator->second;
429 }
430}
431
432// Divides the decoding task into sub tasks and delegates them to the
433// inferior FilterChooser's.
434//
435// A special case arises when there's only one entry in the filtered
436// instructions. In order to unambiguously decode the singleton, we need to
437// match the remaining undecoded encoding bits against the singleton.
438void Filter::recurse() {
439 std::map<uint64_t, std::vector<unsigned> >::const_iterator mapIterator;
440
Owen Andersond8c87882011-02-18 21:51:29 +0000441 // Starts by inheriting our parent filter chooser's filter bit values.
Owen Andersonf1a00902011-07-19 21:06:00 +0000442 std::vector<bit_value_t> BitValueArray(Owner->FilterBitValues);
Owen Andersond8c87882011-02-18 21:51:29 +0000443
444 unsigned bitIndex;
445
446 if (VariableInstructions.size()) {
447 // Conservatively marks each segment position as BIT_UNSET.
448 for (bitIndex = 0; bitIndex < NumBits; bitIndex++)
449 BitValueArray[StartBit + bitIndex] = BIT_UNSET;
450
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000451 // Delegates to an inferior filter chooser for further processing on this
Owen Andersond8c87882011-02-18 21:51:29 +0000452 // group of instructions whose segment values are variable.
453 FilterChooserMap.insert(std::pair<unsigned, FilterChooser*>(
454 (unsigned)-1,
455 new FilterChooser(Owner->AllInstructions,
456 VariableInstructions,
457 Owner->Operands,
458 BitValueArray,
459 *Owner)
460 ));
461 }
462
463 // No need to recurse for a singleton filtered instruction.
464 // See also Filter::emit().
465 if (getNumFiltered() == 1) {
466 //Owner->SingletonExists(LastOpcFiltered);
467 assert(FilterChooserMap.size() == 1);
468 return;
469 }
470
471 // Otherwise, create sub choosers.
472 for (mapIterator = FilteredInstructions.begin();
473 mapIterator != FilteredInstructions.end();
474 mapIterator++) {
475
476 // Marks all the segment positions with either BIT_TRUE or BIT_FALSE.
477 for (bitIndex = 0; bitIndex < NumBits; bitIndex++) {
478 if (mapIterator->first & (1ULL << bitIndex))
479 BitValueArray[StartBit + bitIndex] = BIT_TRUE;
480 else
481 BitValueArray[StartBit + bitIndex] = BIT_FALSE;
482 }
483
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000484 // Delegates to an inferior filter chooser for further processing on this
Owen Andersond8c87882011-02-18 21:51:29 +0000485 // category of instructions.
486 FilterChooserMap.insert(std::pair<unsigned, FilterChooser*>(
487 mapIterator->first,
488 new FilterChooser(Owner->AllInstructions,
489 mapIterator->second,
490 Owner->Operands,
491 BitValueArray,
492 *Owner)
493 ));
494 }
495}
496
497// Emit code to decode instructions given a segment or segments of bits.
498void Filter::emit(raw_ostream &o, unsigned &Indentation) {
499 o.indent(Indentation) << "// Check Inst{";
500
501 if (NumBits > 1)
502 o << (StartBit + NumBits - 1) << '-';
503
504 o << StartBit << "} ...\n";
505
Owen Andersonf1a00902011-07-19 21:06:00 +0000506 o.indent(Indentation) << "switch (fieldFromInstruction" << Owner->BitWidth
507 << "(insn, " << StartBit << ", "
508 << NumBits << ")) {\n";
Owen Andersond8c87882011-02-18 21:51:29 +0000509
510 std::map<unsigned, FilterChooser*>::iterator filterIterator;
511
512 bool DefaultCase = false;
513 for (filterIterator = FilterChooserMap.begin();
514 filterIterator != FilterChooserMap.end();
515 filterIterator++) {
516
517 // Field value -1 implies a non-empty set of variable instructions.
518 // See also recurse().
519 if (filterIterator->first == (unsigned)-1) {
520 DefaultCase = true;
521
522 o.indent(Indentation) << "default:\n";
523 o.indent(Indentation) << " break; // fallthrough\n";
524
525 // Closing curly brace for the switch statement.
526 // This is unconventional because we want the default processing to be
527 // performed for the fallthrough cases as well, i.e., when the "cases"
528 // did not prove a decoded instruction.
529 o.indent(Indentation) << "}\n";
530
531 } else
532 o.indent(Indentation) << "case " << filterIterator->first << ":\n";
533
534 // We arrive at a category of instructions with the same segment value.
535 // Now delegate to the sub filter chooser for further decodings.
536 // The case may fallthrough, which happens if the remaining well-known
537 // encoding bits do not match exactly.
538 if (!DefaultCase) { ++Indentation; ++Indentation; }
539
540 bool finished = filterIterator->second->emit(o, Indentation);
541 // For top level default case, there's no need for a break statement.
542 if (Owner->isTopLevel() && DefaultCase)
543 break;
544 if (!finished)
545 o.indent(Indentation) << "break;\n";
546
547 if (!DefaultCase) { --Indentation; --Indentation; }
548 }
549
550 // If there is no default case, we still need to supply a closing brace.
551 if (!DefaultCase) {
552 // Closing curly brace for the switch statement.
553 o.indent(Indentation) << "}\n";
554 }
555}
556
557// Returns the number of fanout produced by the filter. More fanout implies
558// the filter distinguishes more categories of instructions.
559unsigned Filter::usefulness() const {
560 if (VariableInstructions.size())
561 return FilteredInstructions.size();
562 else
563 return FilteredInstructions.size() + 1;
564}
565
566//////////////////////////////////
567// //
568// Filterchooser Implementation //
569// //
570//////////////////////////////////
571
572// Emit the top level typedef and decodeInstruction() function.
Owen Andersonf1a00902011-07-19 21:06:00 +0000573void FilterChooser::emitTop(raw_ostream &o, unsigned Indentation,
574 std::string Namespace) {
Owen Andersond8c87882011-02-18 21:51:29 +0000575 o.indent(Indentation) <<
Owen Anderson83e3f672011-08-17 17:44:15 +0000576 "static MCDisassembler::DecodeStatus decode" << Namespace << "Instruction" << BitWidth
Owen Andersonf1a00902011-07-19 21:06:00 +0000577 << "(MCInst &MI, uint" << BitWidth << "_t insn, uint64_t Address, "
James Molloya5d58562011-09-07 19:42:28 +0000578 << "const void *Decoder, const MCSubtargetInfo &STI) {\n";
Owen Anderson684dfcf2011-10-17 16:56:47 +0000579 o.indent(Indentation) << " unsigned tmp = 0;\n";
580 o.indent(Indentation) << " (void)tmp;\n";
581 o.indent(Indentation) << Emitter->Locals << "\n";
Bob Wilson1cea66c2011-10-01 02:47:54 +0000582 o.indent(Indentation) << " uint64_t Bits = STI.getFeatureBits();\n";
Owen Anderson684dfcf2011-10-17 16:56:47 +0000583 o.indent(Indentation) << " (void)Bits;\n";
Owen Andersond8c87882011-02-18 21:51:29 +0000584
585 ++Indentation; ++Indentation;
586 // Emits code to decode the instructions.
587 emit(o, Indentation);
588
589 o << '\n';
Owen Anderson83e3f672011-08-17 17:44:15 +0000590 o.indent(Indentation) << "return " << Emitter->ReturnFail << ";\n";
Owen Andersond8c87882011-02-18 21:51:29 +0000591 --Indentation; --Indentation;
592
593 o.indent(Indentation) << "}\n";
594
595 o << '\n';
596}
597
598// Populates the field of the insn given the start position and the number of
599// consecutive bits to scan for.
600//
601// Returns false if and on the first uninitialized bit value encountered.
602// Returns true, otherwise.
603bool FilterChooser::fieldFromInsn(uint64_t &Field, insn_t &Insn,
604 unsigned StartBit, unsigned NumBits) const {
605 Field = 0;
606
607 for (unsigned i = 0; i < NumBits; ++i) {
608 if (Insn[StartBit + i] == BIT_UNSET)
609 return false;
610
611 if (Insn[StartBit + i] == BIT_TRUE)
612 Field = Field | (1ULL << i);
613 }
614
615 return true;
616}
617
618/// dumpFilterArray - dumpFilterArray prints out debugging info for the given
619/// filter array as a series of chars.
620void FilterChooser::dumpFilterArray(raw_ostream &o,
Owen Andersonf1a00902011-07-19 21:06:00 +0000621 std::vector<bit_value_t> &filter) {
Owen Andersond8c87882011-02-18 21:51:29 +0000622 unsigned bitIndex;
623
Owen Andersonf1a00902011-07-19 21:06:00 +0000624 for (bitIndex = BitWidth; bitIndex > 0; bitIndex--) {
Owen Andersond8c87882011-02-18 21:51:29 +0000625 switch (filter[bitIndex - 1]) {
626 case BIT_UNFILTERED:
627 o << ".";
628 break;
629 case BIT_UNSET:
630 o << "_";
631 break;
632 case BIT_TRUE:
633 o << "1";
634 break;
635 case BIT_FALSE:
636 o << "0";
637 break;
638 }
639 }
640}
641
642/// dumpStack - dumpStack traverses the filter chooser chain and calls
643/// dumpFilterArray on each filter chooser up to the top level one.
644void FilterChooser::dumpStack(raw_ostream &o, const char *prefix) {
645 FilterChooser *current = this;
646
647 while (current) {
648 o << prefix;
649 dumpFilterArray(o, current->FilterBitValues);
650 o << '\n';
651 current = current->Parent;
652 }
653}
654
655// Called from Filter::recurse() when singleton exists. For debug purpose.
656void FilterChooser::SingletonExists(unsigned Opc) {
657 insn_t Insn0;
658 insnWithID(Insn0, Opc);
659
660 errs() << "Singleton exists: " << nameWithID(Opc)
661 << " with its decoding dominating ";
662 for (unsigned i = 0; i < Opcodes.size(); ++i) {
663 if (Opcodes[i] == Opc) continue;
664 errs() << nameWithID(Opcodes[i]) << ' ';
665 }
666 errs() << '\n';
667
668 dumpStack(errs(), "\t\t");
669 for (unsigned i = 0; i < Opcodes.size(); i++) {
670 const std::string &Name = nameWithID(Opcodes[i]);
671
672 errs() << '\t' << Name << " ";
673 dumpBits(errs(),
674 getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
675 errs() << '\n';
676 }
677}
678
679// Calculates the island(s) needed to decode the instruction.
680// This returns a list of undecoded bits of an instructions, for example,
681// Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
682// decoded bits in order to verify that the instruction matches the Opcode.
683unsigned FilterChooser::getIslands(std::vector<unsigned> &StartBits,
684 std::vector<unsigned> &EndBits, std::vector<uint64_t> &FieldVals,
685 insn_t &Insn) {
686 unsigned Num, BitNo;
687 Num = BitNo = 0;
688
689 uint64_t FieldVal = 0;
690
691 // 0: Init
692 // 1: Water (the bit value does not affect decoding)
693 // 2: Island (well-known bit value needed for decoding)
694 int State = 0;
695 int Val = -1;
696
Owen Andersonf1a00902011-07-19 21:06:00 +0000697 for (unsigned i = 0; i < BitWidth; ++i) {
Owen Andersond8c87882011-02-18 21:51:29 +0000698 Val = Value(Insn[i]);
699 bool Filtered = PositionFiltered(i);
700 switch (State) {
Craig Topper655b8de2012-02-05 07:21:30 +0000701 default: llvm_unreachable("Unreachable code!");
Owen Andersond8c87882011-02-18 21:51:29 +0000702 case 0:
703 case 1:
704 if (Filtered || Val == -1)
705 State = 1; // Still in Water
706 else {
707 State = 2; // Into the Island
708 BitNo = 0;
709 StartBits.push_back(i);
710 FieldVal = Val;
711 }
712 break;
713 case 2:
714 if (Filtered || Val == -1) {
715 State = 1; // Into the Water
716 EndBits.push_back(i - 1);
717 FieldVals.push_back(FieldVal);
718 ++Num;
719 } else {
720 State = 2; // Still in Island
721 ++BitNo;
722 FieldVal = FieldVal | Val << BitNo;
723 }
724 break;
725 }
726 }
727 // If we are still in Island after the loop, do some housekeeping.
728 if (State == 2) {
Owen Andersonf1a00902011-07-19 21:06:00 +0000729 EndBits.push_back(BitWidth - 1);
Owen Andersond8c87882011-02-18 21:51:29 +0000730 FieldVals.push_back(FieldVal);
731 ++Num;
732 }
733
734 assert(StartBits.size() == Num && EndBits.size() == Num &&
735 FieldVals.size() == Num);
736 return Num;
737}
738
Owen Andersond1e38df2011-07-28 21:54:31 +0000739void FilterChooser::emitBinaryParser(raw_ostream &o, unsigned &Indentation,
740 OperandInfo &OpInfo) {
741 std::string &Decoder = OpInfo.Decoder;
742
743 if (OpInfo.numFields() == 1) {
744 OperandInfo::iterator OI = OpInfo.begin();
745 o.indent(Indentation) << " tmp = fieldFromInstruction" << BitWidth
746 << "(insn, " << OI->Base << ", " << OI->Width
747 << ");\n";
748 } else {
749 o.indent(Indentation) << " tmp = 0;\n";
750 for (OperandInfo::iterator OI = OpInfo.begin(), OE = OpInfo.end();
751 OI != OE; ++OI) {
752 o.indent(Indentation) << " tmp |= (fieldFromInstruction" << BitWidth
Andrew Tricked968a92011-09-08 05:23:14 +0000753 << "(insn, " << OI->Base << ", " << OI->Width
Owen Andersond1e38df2011-07-28 21:54:31 +0000754 << ") << " << OI->Offset << ");\n";
755 }
756 }
757
758 if (Decoder != "")
Owen Anderson83e3f672011-08-17 17:44:15 +0000759 o.indent(Indentation) << " " << Emitter->GuardPrefix << Decoder
760 << "(MI, tmp, Address, Decoder)" << Emitter->GuardPostfix << "\n";
Owen Andersond1e38df2011-07-28 21:54:31 +0000761 else
762 o.indent(Indentation) << " MI.addOperand(MCOperand::CreateImm(tmp));\n";
763
764}
765
James Molloya5d58562011-09-07 19:42:28 +0000766static void emitSinglePredicateMatch(raw_ostream &o, StringRef str,
767 std::string PredicateNamespace) {
Andrew Trick22b4c812011-09-08 05:25:49 +0000768 if (str[0] == '!')
769 o << "!(Bits & " << PredicateNamespace << "::"
770 << str.slice(1,str.size()) << ")";
James Molloya5d58562011-09-07 19:42:28 +0000771 else
Andrew Trick22b4c812011-09-08 05:25:49 +0000772 o << "(Bits & " << PredicateNamespace << "::" << str << ")";
James Molloya5d58562011-09-07 19:42:28 +0000773}
774
775bool FilterChooser::emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
776 unsigned Opc) {
777 ListInit *Predicates = AllInstructions[Opc]->TheDef->getValueAsListInit("Predicates");
778 for (unsigned i = 0; i < Predicates->getSize(); ++i) {
779 Record *Pred = Predicates->getElementAsRecord(i);
780 if (!Pred->getValue("AssemblerMatcherPredicate"))
781 continue;
782
783 std::string P = Pred->getValueAsString("AssemblerCondString");
784
785 if (!P.length())
786 continue;
787
788 if (i != 0)
789 o << " && ";
790
791 StringRef SR(P);
792 std::pair<StringRef, StringRef> pairs = SR.split(',');
793 while (pairs.second.size()) {
794 emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
795 o << " && ";
796 pairs = pairs.second.split(',');
797 }
798 emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
799 }
800 return Predicates->getSize() > 0;
Andrew Tricked968a92011-09-08 05:23:14 +0000801}
James Molloya5d58562011-09-07 19:42:28 +0000802
Owen Andersond8c87882011-02-18 21:51:29 +0000803// Emits code to decode the singleton. Return true if we have matched all the
804// well-known bits.
805bool FilterChooser::emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,
806 unsigned Opc) {
807 std::vector<unsigned> StartBits;
808 std::vector<unsigned> EndBits;
809 std::vector<uint64_t> FieldVals;
810 insn_t Insn;
811 insnWithID(Insn, Opc);
812
813 // Look for islands of undecoded bits of the singleton.
814 getIslands(StartBits, EndBits, FieldVals, Insn);
815
816 unsigned Size = StartBits.size();
817 unsigned I, NumBits;
818
819 // If we have matched all the well-known bits, just issue a return.
820 if (Size == 0) {
James Molloya5d58562011-09-07 19:42:28 +0000821 o.indent(Indentation) << "if (";
Eli Friedman64a17b32011-09-08 21:00:31 +0000822 if (!emitPredicateMatch(o, Indentation, Opc))
823 o << "1";
James Molloya5d58562011-09-07 19:42:28 +0000824 o << ") {\n";
Owen Andersond8c87882011-02-18 21:51:29 +0000825 o.indent(Indentation) << " MI.setOpcode(" << Opc << ");\n";
826 std::vector<OperandInfo>& InsnOperands = Operands[Opc];
827 for (std::vector<OperandInfo>::iterator
828 I = InsnOperands.begin(), E = InsnOperands.end(); I != E; ++I) {
829 // If a custom instruction decoder was specified, use that.
Owen Andersond1e38df2011-07-28 21:54:31 +0000830 if (I->numFields() == 0 && I->Decoder.size()) {
Owen Anderson83e3f672011-08-17 17:44:15 +0000831 o.indent(Indentation) << " " << Emitter->GuardPrefix << I->Decoder
832 << "(MI, insn, Address, Decoder)" << Emitter->GuardPostfix << "\n";
Owen Andersond8c87882011-02-18 21:51:29 +0000833 break;
834 }
835
Owen Andersond1e38df2011-07-28 21:54:31 +0000836 emitBinaryParser(o, Indentation, *I);
Owen Andersond8c87882011-02-18 21:51:29 +0000837 }
838
Owen Anderson83e3f672011-08-17 17:44:15 +0000839 o.indent(Indentation) << " return " << Emitter->ReturnOK << "; // " << nameWithID(Opc)
Owen Andersond8c87882011-02-18 21:51:29 +0000840 << '\n';
James Molloya5d58562011-09-07 19:42:28 +0000841 o.indent(Indentation) << "}\n"; // Closing predicate block.
Owen Andersond8c87882011-02-18 21:51:29 +0000842 return true;
843 }
844
845 // Otherwise, there are more decodings to be done!
846
847 // Emit code to match the island(s) for the singleton.
848 o.indent(Indentation) << "// Check ";
849
850 for (I = Size; I != 0; --I) {
851 o << "Inst{" << EndBits[I-1] << '-' << StartBits[I-1] << "} ";
852 if (I > 1)
James Molloya5d58562011-09-07 19:42:28 +0000853 o << " && ";
Owen Andersond8c87882011-02-18 21:51:29 +0000854 else
855 o << "for singleton decoding...\n";
856 }
857
858 o.indent(Indentation) << "if (";
James Molloy0d76b192011-09-08 08:12:01 +0000859 if (emitPredicateMatch(o, Indentation, Opc)) {
James Molloya5d58562011-09-07 19:42:28 +0000860 o << " &&\n";
861 o.indent(Indentation+4);
862 }
Owen Andersond8c87882011-02-18 21:51:29 +0000863
864 for (I = Size; I != 0; --I) {
865 NumBits = EndBits[I-1] - StartBits[I-1] + 1;
Owen Andersonf1a00902011-07-19 21:06:00 +0000866 o << "fieldFromInstruction" << BitWidth << "(insn, "
867 << StartBits[I-1] << ", " << NumBits
Owen Andersond8c87882011-02-18 21:51:29 +0000868 << ") == " << FieldVals[I-1];
869 if (I > 1)
870 o << " && ";
871 else
872 o << ") {\n";
873 }
874 o.indent(Indentation) << " MI.setOpcode(" << Opc << ");\n";
875 std::vector<OperandInfo>& InsnOperands = Operands[Opc];
876 for (std::vector<OperandInfo>::iterator
877 I = InsnOperands.begin(), E = InsnOperands.end(); I != E; ++I) {
878 // If a custom instruction decoder was specified, use that.
Owen Andersond1e38df2011-07-28 21:54:31 +0000879 if (I->numFields() == 0 && I->Decoder.size()) {
Owen Anderson83e3f672011-08-17 17:44:15 +0000880 o.indent(Indentation) << " " << Emitter->GuardPrefix << I->Decoder
881 << "(MI, insn, Address, Decoder)" << Emitter->GuardPostfix << "\n";
Owen Andersond8c87882011-02-18 21:51:29 +0000882 break;
883 }
884
Owen Andersond1e38df2011-07-28 21:54:31 +0000885 emitBinaryParser(o, Indentation, *I);
Owen Andersond8c87882011-02-18 21:51:29 +0000886 }
Owen Anderson83e3f672011-08-17 17:44:15 +0000887 o.indent(Indentation) << " return " << Emitter->ReturnOK << "; // " << nameWithID(Opc)
Owen Andersond8c87882011-02-18 21:51:29 +0000888 << '\n';
889 o.indent(Indentation) << "}\n";
890
891 return false;
892}
893
894// Emits code to decode the singleton, and then to decode the rest.
895void FilterChooser::emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,
896 Filter &Best) {
897
898 unsigned Opc = Best.getSingletonOpc();
899
900 emitSingletonDecoder(o, Indentation, Opc);
901
902 // Emit code for the rest.
903 o.indent(Indentation) << "else\n";
904
905 Indentation += 2;
906 Best.getVariableFC().emit(o, Indentation);
907 Indentation -= 2;
908}
909
910// Assign a single filter and run with it. Top level API client can initialize
911// with a single filter to start the filtering process.
912void FilterChooser::runSingleFilter(FilterChooser &owner, unsigned startBit,
913 unsigned numBit, bool mixed) {
914 Filters.clear();
915 Filter F(*this, startBit, numBit, true);
916 Filters.push_back(F);
917 BestIndex = 0; // Sole Filter instance to choose from.
918 bestFilter().recurse();
919}
920
921// reportRegion is a helper function for filterProcessor to mark a region as
922// eligible for use as a filter region.
923void FilterChooser::reportRegion(bitAttr_t RA, unsigned StartBit,
924 unsigned BitIndex, bool AllowMixed) {
925 if (RA == ATTR_MIXED && AllowMixed)
926 Filters.push_back(Filter(*this, StartBit, BitIndex - StartBit, true));
927 else if (RA == ATTR_ALL_SET && !AllowMixed)
928 Filters.push_back(Filter(*this, StartBit, BitIndex - StartBit, false));
929}
930
931// FilterProcessor scans the well-known encoding bits of the instructions and
932// builds up a list of candidate filters. It chooses the best filter and
933// recursively descends down the decoding tree.
934bool FilterChooser::filterProcessor(bool AllowMixed, bool Greedy) {
935 Filters.clear();
936 BestIndex = -1;
937 unsigned numInstructions = Opcodes.size();
938
939 assert(numInstructions && "Filter created with no instructions");
940
941 // No further filtering is necessary.
942 if (numInstructions == 1)
943 return true;
944
945 // Heuristics. See also doFilter()'s "Heuristics" comment when num of
946 // instructions is 3.
947 if (AllowMixed && !Greedy) {
948 assert(numInstructions == 3);
949
950 for (unsigned i = 0; i < Opcodes.size(); ++i) {
951 std::vector<unsigned> StartBits;
952 std::vector<unsigned> EndBits;
953 std::vector<uint64_t> FieldVals;
954 insn_t Insn;
955
956 insnWithID(Insn, Opcodes[i]);
957
958 // Look for islands of undecoded bits of any instruction.
959 if (getIslands(StartBits, EndBits, FieldVals, Insn) > 0) {
960 // Found an instruction with island(s). Now just assign a filter.
961 runSingleFilter(*this, StartBits[0], EndBits[0] - StartBits[0] + 1,
962 true);
963 return true;
964 }
965 }
966 }
967
968 unsigned BitIndex, InsnIndex;
969
970 // We maintain BIT_WIDTH copies of the bitAttrs automaton.
971 // The automaton consumes the corresponding bit from each
972 // instruction.
973 //
974 // Input symbols: 0, 1, and _ (unset).
975 // States: NONE, FILTERED, ALL_SET, ALL_UNSET, and MIXED.
976 // Initial state: NONE.
977 //
978 // (NONE) ------- [01] -> (ALL_SET)
979 // (NONE) ------- _ ----> (ALL_UNSET)
980 // (ALL_SET) ---- [01] -> (ALL_SET)
981 // (ALL_SET) ---- _ ----> (MIXED)
982 // (ALL_UNSET) -- [01] -> (MIXED)
983 // (ALL_UNSET) -- _ ----> (ALL_UNSET)
984 // (MIXED) ------ . ----> (MIXED)
985 // (FILTERED)---- . ----> (FILTERED)
986
Owen Andersonf1a00902011-07-19 21:06:00 +0000987 std::vector<bitAttr_t> bitAttrs;
Owen Andersond8c87882011-02-18 21:51:29 +0000988
989 // FILTERED bit positions provide no entropy and are not worthy of pursuing.
990 // Filter::recurse() set either BIT_TRUE or BIT_FALSE for each position.
Owen Andersonf1a00902011-07-19 21:06:00 +0000991 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex)
Owen Andersond8c87882011-02-18 21:51:29 +0000992 if (FilterBitValues[BitIndex] == BIT_TRUE ||
993 FilterBitValues[BitIndex] == BIT_FALSE)
Owen Andersonf1a00902011-07-19 21:06:00 +0000994 bitAttrs.push_back(ATTR_FILTERED);
Owen Andersond8c87882011-02-18 21:51:29 +0000995 else
Owen Andersonf1a00902011-07-19 21:06:00 +0000996 bitAttrs.push_back(ATTR_NONE);
Owen Andersond8c87882011-02-18 21:51:29 +0000997
998 for (InsnIndex = 0; InsnIndex < numInstructions; ++InsnIndex) {
999 insn_t insn;
1000
1001 insnWithID(insn, Opcodes[InsnIndex]);
1002
Owen Andersonf1a00902011-07-19 21:06:00 +00001003 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
Owen Andersond8c87882011-02-18 21:51:29 +00001004 switch (bitAttrs[BitIndex]) {
1005 case ATTR_NONE:
1006 if (insn[BitIndex] == BIT_UNSET)
1007 bitAttrs[BitIndex] = ATTR_ALL_UNSET;
1008 else
1009 bitAttrs[BitIndex] = ATTR_ALL_SET;
1010 break;
1011 case ATTR_ALL_SET:
1012 if (insn[BitIndex] == BIT_UNSET)
1013 bitAttrs[BitIndex] = ATTR_MIXED;
1014 break;
1015 case ATTR_ALL_UNSET:
1016 if (insn[BitIndex] != BIT_UNSET)
1017 bitAttrs[BitIndex] = ATTR_MIXED;
1018 break;
1019 case ATTR_MIXED:
1020 case ATTR_FILTERED:
1021 break;
1022 }
1023 }
1024 }
1025
1026 // The regionAttr automaton consumes the bitAttrs automatons' state,
1027 // lowest-to-highest.
1028 //
1029 // Input symbols: F(iltered), (all_)S(et), (all_)U(nset), M(ixed)
1030 // States: NONE, ALL_SET, MIXED
1031 // Initial state: NONE
1032 //
1033 // (NONE) ----- F --> (NONE)
1034 // (NONE) ----- S --> (ALL_SET) ; and set region start
1035 // (NONE) ----- U --> (NONE)
1036 // (NONE) ----- M --> (MIXED) ; and set region start
1037 // (ALL_SET) -- F --> (NONE) ; and report an ALL_SET region
1038 // (ALL_SET) -- S --> (ALL_SET)
1039 // (ALL_SET) -- U --> (NONE) ; and report an ALL_SET region
1040 // (ALL_SET) -- M --> (MIXED) ; and report an ALL_SET region
1041 // (MIXED) ---- F --> (NONE) ; and report a MIXED region
1042 // (MIXED) ---- S --> (ALL_SET) ; and report a MIXED region
1043 // (MIXED) ---- U --> (NONE) ; and report a MIXED region
1044 // (MIXED) ---- M --> (MIXED)
1045
1046 bitAttr_t RA = ATTR_NONE;
1047 unsigned StartBit = 0;
1048
Owen Andersonf1a00902011-07-19 21:06:00 +00001049 for (BitIndex = 0; BitIndex < BitWidth; BitIndex++) {
Owen Andersond8c87882011-02-18 21:51:29 +00001050 bitAttr_t bitAttr = bitAttrs[BitIndex];
1051
1052 assert(bitAttr != ATTR_NONE && "Bit without attributes");
1053
1054 switch (RA) {
1055 case ATTR_NONE:
1056 switch (bitAttr) {
1057 case ATTR_FILTERED:
1058 break;
1059 case ATTR_ALL_SET:
1060 StartBit = BitIndex;
1061 RA = ATTR_ALL_SET;
1062 break;
1063 case ATTR_ALL_UNSET:
1064 break;
1065 case ATTR_MIXED:
1066 StartBit = BitIndex;
1067 RA = ATTR_MIXED;
1068 break;
1069 default:
Craig Topper655b8de2012-02-05 07:21:30 +00001070 llvm_unreachable("Unexpected bitAttr!");
Owen Andersond8c87882011-02-18 21:51:29 +00001071 }
1072 break;
1073 case ATTR_ALL_SET:
1074 switch (bitAttr) {
1075 case ATTR_FILTERED:
1076 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1077 RA = ATTR_NONE;
1078 break;
1079 case ATTR_ALL_SET:
1080 break;
1081 case ATTR_ALL_UNSET:
1082 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1083 RA = ATTR_NONE;
1084 break;
1085 case ATTR_MIXED:
1086 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1087 StartBit = BitIndex;
1088 RA = ATTR_MIXED;
1089 break;
1090 default:
Craig Topper655b8de2012-02-05 07:21:30 +00001091 llvm_unreachable("Unexpected bitAttr!");
Owen Andersond8c87882011-02-18 21:51:29 +00001092 }
1093 break;
1094 case ATTR_MIXED:
1095 switch (bitAttr) {
1096 case ATTR_FILTERED:
1097 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1098 StartBit = BitIndex;
1099 RA = ATTR_NONE;
1100 break;
1101 case ATTR_ALL_SET:
1102 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1103 StartBit = BitIndex;
1104 RA = ATTR_ALL_SET;
1105 break;
1106 case ATTR_ALL_UNSET:
1107 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1108 RA = ATTR_NONE;
1109 break;
1110 case ATTR_MIXED:
1111 break;
1112 default:
Craig Topper655b8de2012-02-05 07:21:30 +00001113 llvm_unreachable("Unexpected bitAttr!");
Owen Andersond8c87882011-02-18 21:51:29 +00001114 }
1115 break;
1116 case ATTR_ALL_UNSET:
Craig Topper655b8de2012-02-05 07:21:30 +00001117 llvm_unreachable("regionAttr state machine has no ATTR_UNSET state");
Owen Andersond8c87882011-02-18 21:51:29 +00001118 case ATTR_FILTERED:
Craig Topper655b8de2012-02-05 07:21:30 +00001119 llvm_unreachable("regionAttr state machine has no ATTR_FILTERED state");
Owen Andersond8c87882011-02-18 21:51:29 +00001120 }
1121 }
1122
1123 // At the end, if we're still in ALL_SET or MIXED states, report a region
1124 switch (RA) {
1125 case ATTR_NONE:
1126 break;
1127 case ATTR_FILTERED:
1128 break;
1129 case ATTR_ALL_SET:
1130 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1131 break;
1132 case ATTR_ALL_UNSET:
1133 break;
1134 case ATTR_MIXED:
1135 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1136 break;
1137 }
1138
1139 // We have finished with the filter processings. Now it's time to choose
1140 // the best performing filter.
1141 BestIndex = 0;
1142 bool AllUseless = true;
1143 unsigned BestScore = 0;
1144
1145 for (unsigned i = 0, e = Filters.size(); i != e; ++i) {
1146 unsigned Usefulness = Filters[i].usefulness();
1147
1148 if (Usefulness)
1149 AllUseless = false;
1150
1151 if (Usefulness > BestScore) {
1152 BestIndex = i;
1153 BestScore = Usefulness;
1154 }
1155 }
1156
1157 if (!AllUseless)
1158 bestFilter().recurse();
1159
1160 return !AllUseless;
1161} // end of FilterChooser::filterProcessor(bool)
1162
1163// Decides on the best configuration of filter(s) to use in order to decode
1164// the instructions. A conflict of instructions may occur, in which case we
1165// dump the conflict set to the standard error.
1166void FilterChooser::doFilter() {
1167 unsigned Num = Opcodes.size();
1168 assert(Num && "FilterChooser created with no instructions");
1169
1170 // Try regions of consecutive known bit values first.
1171 if (filterProcessor(false))
1172 return;
1173
1174 // Then regions of mixed bits (both known and unitialized bit values allowed).
1175 if (filterProcessor(true))
1176 return;
1177
1178 // Heuristics to cope with conflict set {t2CMPrs, t2SUBSrr, t2SUBSrs} where
1179 // no single instruction for the maximum ATTR_MIXED region Inst{14-4} has a
1180 // well-known encoding pattern. In such case, we backtrack and scan for the
1181 // the very first consecutive ATTR_ALL_SET region and assign a filter to it.
1182 if (Num == 3 && filterProcessor(true, false))
1183 return;
1184
1185 // If we come to here, the instruction decoding has failed.
1186 // Set the BestIndex to -1 to indicate so.
1187 BestIndex = -1;
1188}
1189
1190// Emits code to decode our share of instructions. Returns true if the
1191// emitted code causes a return, which occurs if we know how to decode
1192// the instruction at this level or the instruction is not decodeable.
1193bool FilterChooser::emit(raw_ostream &o, unsigned &Indentation) {
1194 if (Opcodes.size() == 1)
1195 // There is only one instruction in the set, which is great!
1196 // Call emitSingletonDecoder() to see whether there are any remaining
1197 // encodings bits.
1198 return emitSingletonDecoder(o, Indentation, Opcodes[0]);
1199
1200 // Choose the best filter to do the decodings!
1201 if (BestIndex != -1) {
1202 Filter &Best = bestFilter();
1203 if (Best.getNumFiltered() == 1)
1204 emitSingletonDecoder(o, Indentation, Best);
1205 else
1206 bestFilter().emit(o, Indentation);
1207 return false;
1208 }
1209
1210 // We don't know how to decode these instructions! Return 0 and dump the
1211 // conflict set!
1212 o.indent(Indentation) << "return 0;" << " // Conflict set: ";
1213 for (int i = 0, N = Opcodes.size(); i < N; ++i) {
1214 o << nameWithID(Opcodes[i]);
1215 if (i < (N - 1))
1216 o << ", ";
1217 else
1218 o << '\n';
1219 }
1220
1221 // Print out useful conflict information for postmortem analysis.
1222 errs() << "Decoding Conflict:\n";
1223
1224 dumpStack(errs(), "\t\t");
1225
1226 for (unsigned i = 0; i < Opcodes.size(); i++) {
1227 const std::string &Name = nameWithID(Opcodes[i]);
1228
1229 errs() << '\t' << Name << " ";
1230 dumpBits(errs(),
1231 getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
1232 errs() << '\n';
1233 }
1234
1235 return true;
1236}
1237
Owen Andersonf1a00902011-07-19 21:06:00 +00001238static bool populateInstruction(const CodeGenInstruction &CGI,
1239 unsigned Opc,
1240 std::map<unsigned, std::vector<OperandInfo> >& Operands){
Owen Andersond8c87882011-02-18 21:51:29 +00001241 const Record &Def = *CGI.TheDef;
1242 // If all the bit positions are not specified; do not decode this instruction.
1243 // We are bound to fail! For proper disassembly, the well-known encoding bits
1244 // of the instruction must be fully specified.
1245 //
1246 // This also removes pseudo instructions from considerations of disassembly,
1247 // which is a better design and less fragile than the name matchings.
Owen Andersond8c87882011-02-18 21:51:29 +00001248 // Ignore "asm parser only" instructions.
Owen Anderson4dd27eb2011-03-14 20:58:49 +00001249 if (Def.getValueAsBit("isAsmParserOnly") ||
1250 Def.getValueAsBit("isCodeGenOnly"))
Owen Andersond8c87882011-02-18 21:51:29 +00001251 return false;
1252
David Greene05bce0b2011-07-29 22:43:06 +00001253 BitsInit &Bits = getBitsField(Def, "Inst");
Jim Grosbach806fcc02011-07-06 21:33:38 +00001254 if (Bits.allInComplete()) return false;
1255
Owen Andersond8c87882011-02-18 21:51:29 +00001256 std::vector<OperandInfo> InsnOperands;
1257
1258 // If the instruction has specified a custom decoding hook, use that instead
1259 // of trying to auto-generate the decoder.
1260 std::string InstDecoder = Def.getValueAsString("DecoderMethod");
1261 if (InstDecoder != "") {
Owen Andersond1e38df2011-07-28 21:54:31 +00001262 InsnOperands.push_back(OperandInfo(InstDecoder));
Owen Andersond8c87882011-02-18 21:51:29 +00001263 Operands[Opc] = InsnOperands;
1264 return true;
1265 }
1266
1267 // Generate a description of the operand of the instruction that we know
1268 // how to decode automatically.
1269 // FIXME: We'll need to have a way to manually override this as needed.
1270
1271 // Gather the outputs/inputs of the instruction, so we can find their
1272 // positions in the encoding. This assumes for now that they appear in the
1273 // MCInst in the order that they're listed.
David Greene05bce0b2011-07-29 22:43:06 +00001274 std::vector<std::pair<Init*, std::string> > InOutOperands;
1275 DagInit *Out = Def.getValueAsDag("OutOperandList");
1276 DagInit *In = Def.getValueAsDag("InOperandList");
Owen Andersond8c87882011-02-18 21:51:29 +00001277 for (unsigned i = 0; i < Out->getNumArgs(); ++i)
1278 InOutOperands.push_back(std::make_pair(Out->getArg(i), Out->getArgName(i)));
1279 for (unsigned i = 0; i < In->getNumArgs(); ++i)
1280 InOutOperands.push_back(std::make_pair(In->getArg(i), In->getArgName(i)));
1281
Owen Anderson00ef6e32011-07-28 23:56:20 +00001282 // Search for tied operands, so that we can correctly instantiate
1283 // operands that are not explicitly represented in the encoding.
Owen Andersonea242982011-07-29 18:28:52 +00001284 std::map<std::string, std::string> TiedNames;
Owen Anderson00ef6e32011-07-28 23:56:20 +00001285 for (unsigned i = 0; i < CGI.Operands.size(); ++i) {
1286 int tiedTo = CGI.Operands[i].getTiedRegister();
Owen Andersonea242982011-07-29 18:28:52 +00001287 if (tiedTo != -1) {
1288 TiedNames[InOutOperands[i].second] = InOutOperands[tiedTo].second;
1289 TiedNames[InOutOperands[tiedTo].second] = InOutOperands[i].second;
1290 }
Owen Anderson00ef6e32011-07-28 23:56:20 +00001291 }
1292
Owen Andersond8c87882011-02-18 21:51:29 +00001293 // For each operand, see if we can figure out where it is encoded.
David Greene05bce0b2011-07-29 22:43:06 +00001294 for (std::vector<std::pair<Init*, std::string> >::iterator
Owen Andersond8c87882011-02-18 21:51:29 +00001295 NI = InOutOperands.begin(), NE = InOutOperands.end(); NI != NE; ++NI) {
Owen Andersond8c87882011-02-18 21:51:29 +00001296 std::string Decoder = "";
1297
Owen Andersond1e38df2011-07-28 21:54:31 +00001298 // At this point, we can locate the field, but we need to know how to
1299 // interpret it. As a first step, require the target to provide callbacks
1300 // for decoding register classes.
1301 // FIXME: This need to be extended to handle instructions with custom
1302 // decoder methods, and operands with (simple) MIOperandInfo's.
David Greene05bce0b2011-07-29 22:43:06 +00001303 TypedInit *TI = dynamic_cast<TypedInit*>(NI->first);
Owen Andersond1e38df2011-07-28 21:54:31 +00001304 RecordRecTy *Type = dynamic_cast<RecordRecTy*>(TI->getType());
1305 Record *TypeRecord = Type->getRecord();
1306 bool isReg = false;
1307 if (TypeRecord->isSubClassOf("RegisterOperand"))
1308 TypeRecord = TypeRecord->getValueAsDef("RegClass");
1309 if (TypeRecord->isSubClassOf("RegisterClass")) {
1310 Decoder = "Decode" + TypeRecord->getName() + "RegisterClass";
1311 isReg = true;
1312 }
1313
1314 RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod");
David Greene05bce0b2011-07-29 22:43:06 +00001315 StringInit *String = DecoderString ?
1316 dynamic_cast<StringInit*>(DecoderString->getValue()) : 0;
Owen Andersond1e38df2011-07-28 21:54:31 +00001317 if (!isReg && String && String->getValue() != "")
1318 Decoder = String->getValue();
1319
1320 OperandInfo OpInfo(Decoder);
1321 unsigned Base = ~0U;
1322 unsigned Width = 0;
1323 unsigned Offset = 0;
1324
Owen Andersond8c87882011-02-18 21:51:29 +00001325 for (unsigned bi = 0; bi < Bits.getNumBits(); ++bi) {
Owen Andersoncf603952011-08-01 22:45:43 +00001326 VarInit *Var = 0;
David Greene05bce0b2011-07-29 22:43:06 +00001327 VarBitInit *BI = dynamic_cast<VarBitInit*>(Bits.getBit(bi));
Owen Andersoncf603952011-08-01 22:45:43 +00001328 if (BI)
1329 Var = dynamic_cast<VarInit*>(BI->getVariable());
1330 else
1331 Var = dynamic_cast<VarInit*>(Bits.getBit(bi));
1332
1333 if (!Var) {
Owen Andersond1e38df2011-07-28 21:54:31 +00001334 if (Base != ~0U) {
1335 OpInfo.addField(Base, Width, Offset);
1336 Base = ~0U;
1337 Width = 0;
1338 Offset = 0;
1339 }
1340 continue;
1341 }
Owen Andersond8c87882011-02-18 21:51:29 +00001342
Owen Anderson00ef6e32011-07-28 23:56:20 +00001343 if (Var->getName() != NI->second &&
Owen Andersonea242982011-07-29 18:28:52 +00001344 Var->getName() != TiedNames[NI->second]) {
Owen Andersond1e38df2011-07-28 21:54:31 +00001345 if (Base != ~0U) {
1346 OpInfo.addField(Base, Width, Offset);
1347 Base = ~0U;
1348 Width = 0;
1349 Offset = 0;
1350 }
1351 continue;
Owen Andersond8c87882011-02-18 21:51:29 +00001352 }
1353
Owen Andersond1e38df2011-07-28 21:54:31 +00001354 if (Base == ~0U) {
1355 Base = bi;
1356 Width = 1;
Owen Andersoncf603952011-08-01 22:45:43 +00001357 Offset = BI ? BI->getBitNum() : 0;
1358 } else if (BI && BI->getBitNum() != Offset + Width) {
Owen Andersoneb809f52011-07-29 23:01:18 +00001359 OpInfo.addField(Base, Width, Offset);
1360 Base = bi;
1361 Width = 1;
1362 Offset = BI->getBitNum();
Owen Andersond1e38df2011-07-28 21:54:31 +00001363 } else {
1364 ++Width;
Owen Andersond8c87882011-02-18 21:51:29 +00001365 }
Owen Andersond8c87882011-02-18 21:51:29 +00001366 }
1367
Owen Andersond1e38df2011-07-28 21:54:31 +00001368 if (Base != ~0U)
1369 OpInfo.addField(Base, Width, Offset);
1370
1371 if (OpInfo.numFields() > 0)
1372 InsnOperands.push_back(OpInfo);
Owen Andersond8c87882011-02-18 21:51:29 +00001373 }
1374
1375 Operands[Opc] = InsnOperands;
1376
1377
1378#if 0
1379 DEBUG({
1380 // Dumps the instruction encoding bits.
1381 dumpBits(errs(), Bits);
1382
1383 errs() << '\n';
1384
1385 // Dumps the list of operand info.
1386 for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) {
1387 const CGIOperandList::OperandInfo &Info = CGI.Operands[i];
1388 const std::string &OperandName = Info.Name;
1389 const Record &OperandDef = *Info.Rec;
1390
1391 errs() << "\t" << OperandName << " (" << OperandDef.getName() << ")\n";
1392 }
1393 });
1394#endif
1395
1396 return true;
1397}
1398
Owen Andersonf1a00902011-07-19 21:06:00 +00001399static void emitHelper(llvm::raw_ostream &o, unsigned BitWidth) {
1400 unsigned Indentation = 0;
1401 std::string WidthStr = "uint" + utostr(BitWidth) + "_t";
Owen Andersond8c87882011-02-18 21:51:29 +00001402
Owen Andersonf1a00902011-07-19 21:06:00 +00001403 o << '\n';
1404
1405 o.indent(Indentation) << "static " << WidthStr <<
1406 " fieldFromInstruction" << BitWidth <<
1407 "(" << WidthStr <<" insn, unsigned startBit, unsigned numBits)\n";
1408
1409 o.indent(Indentation) << "{\n";
1410
1411 ++Indentation; ++Indentation;
1412 o.indent(Indentation) << "assert(startBit + numBits <= " << BitWidth
1413 << " && \"Instruction field out of bounds!\");\n";
1414 o << '\n';
1415 o.indent(Indentation) << WidthStr << " fieldMask;\n";
1416 o << '\n';
1417 o.indent(Indentation) << "if (numBits == " << BitWidth << ")\n";
1418
1419 ++Indentation; ++Indentation;
1420 o.indent(Indentation) << "fieldMask = (" << WidthStr << ")-1;\n";
1421 --Indentation; --Indentation;
1422
1423 o.indent(Indentation) << "else\n";
1424
1425 ++Indentation; ++Indentation;
1426 o.indent(Indentation) << "fieldMask = ((1 << numBits) - 1) << startBit;\n";
1427 --Indentation; --Indentation;
1428
1429 o << '\n';
1430 o.indent(Indentation) << "return (insn & fieldMask) >> startBit;\n";
1431 --Indentation; --Indentation;
1432
1433 o.indent(Indentation) << "}\n";
1434
1435 o << '\n';
Owen Andersond8c87882011-02-18 21:51:29 +00001436}
1437
1438// Emits disassembler code for instruction decoding.
1439void FixedLenDecoderEmitter::run(raw_ostream &o)
1440{
1441 o << "#include \"llvm/MC/MCInst.h\"\n";
1442 o << "#include \"llvm/Support/DataTypes.h\"\n";
1443 o << "#include <assert.h>\n";
1444 o << '\n';
1445 o << "namespace llvm {\n\n";
1446
Owen Andersonf1a00902011-07-19 21:06:00 +00001447 // Parameterize the decoders based on namespace and instruction width.
Owen Andersond8c87882011-02-18 21:51:29 +00001448 NumberedInstructions = Target.getInstructionsByEnumValue();
Owen Andersonf1a00902011-07-19 21:06:00 +00001449 std::map<std::pair<std::string, unsigned>,
1450 std::vector<unsigned> > OpcMap;
1451 std::map<unsigned, std::vector<OperandInfo> > Operands;
1452
1453 for (unsigned i = 0; i < NumberedInstructions.size(); ++i) {
1454 const CodeGenInstruction *Inst = NumberedInstructions[i];
1455 Record *Def = Inst->TheDef;
1456 unsigned Size = Def->getValueAsInt("Size");
1457 if (Def->getValueAsString("Namespace") == "TargetOpcode" ||
1458 Def->getValueAsBit("isPseudo") ||
1459 Def->getValueAsBit("isAsmParserOnly") ||
1460 Def->getValueAsBit("isCodeGenOnly"))
1461 continue;
1462
1463 std::string DecoderNamespace = Def->getValueAsString("DecoderNamespace");
1464
1465 if (Size) {
1466 if (populateInstruction(*Inst, i, Operands)) {
1467 OpcMap[std::make_pair(DecoderNamespace, Size)].push_back(i);
1468 }
1469 }
1470 }
1471
1472 std::set<unsigned> Sizes;
1473 for (std::map<std::pair<std::string, unsigned>,
1474 std::vector<unsigned> >::iterator
1475 I = OpcMap.begin(), E = OpcMap.end(); I != E; ++I) {
1476 // If we haven't visited this instruction width before, emit the
1477 // helper method to extract fields.
1478 if (!Sizes.count(I->first.second)) {
1479 emitHelper(o, 8*I->first.second);
1480 Sizes.insert(I->first.second);
1481 }
1482
1483 // Emit the decoder for this namespace+width combination.
1484 FilterChooser FC(NumberedInstructions, I->second, Operands,
Owen Anderson83e3f672011-08-17 17:44:15 +00001485 8*I->first.second, this);
Owen Andersonf1a00902011-07-19 21:06:00 +00001486 FC.emitTop(o, 0, I->first.first);
1487 }
Owen Andersond8c87882011-02-18 21:51:29 +00001488
1489 o << "\n} // End llvm namespace \n";
1490}