1 //===------------ FixedLenDecoderEmitter.cpp - Decoder Generator ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // It contains the tablegen backend that emits the decoder functions for
11 // targets with fixed length instruction set.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "decoder-emitter"
17 #include "FixedLenDecoderEmitter.h"
18 #include "CodeGenTarget.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/raw_ostream.h"
30 // The set (BIT_TRUE, BIT_FALSE, BIT_UNSET) represents a ternary logic system
33 // BIT_UNFILTERED is used as the init value for a filter position. It is used
34 // only for filter processings.
39 BIT_UNFILTERED // unfiltered
42 static bool ValueSet(bit_value_t V) {
43 return (V == BIT_TRUE || V == BIT_FALSE);
45 static bool ValueNotSet(bit_value_t V) {
46 return (V == BIT_UNSET);
48 static int Value(bit_value_t V) {
49 return ValueNotSet(V) ? -1 : (V == BIT_FALSE ? 0 : 1);
51 static bit_value_t bitFromBits(const BitsInit &bits, unsigned index) {
52 if (const BitInit *bit = dynamic_cast<const BitInit*>(bits.getBit(index)))
53 return bit->getValue() ? BIT_TRUE : BIT_FALSE;
55 // The bit is uninitialized.
58 // Prints the bit value for each position.
59 static void dumpBits(raw_ostream &o, const BitsInit &bits) {
62 for (index = bits.getNumBits(); index > 0; index--) {
63 switch (bitFromBits(bits, index - 1)) {
74 assert(0 && "unexpected return value from bitFromBits");
79 static const BitsInit &getBitsField(const Record &def, const char *str) {
80 const BitsInit *bits = def.getValueAsBitsInit(str);
84 // Forward declaration.
87 // FIXME: Possibly auto-detected?
90 // Representation of the instruction to work on.
91 typedef bit_value_t insn_t[BIT_WIDTH];
93 /// Filter - Filter works with FilterChooser to produce the decoding tree for
96 /// It is useful to think of a Filter as governing the switch stmts of the
97 /// decoding tree in a certain level. Each case stmt delegates to an inferior
98 /// FilterChooser to decide what further decoding logic to employ, or in another
99 /// words, what other remaining bits to look at. The FilterChooser eventually
100 /// chooses a best Filter to do its job.
102 /// This recursive scheme ends when the number of Opcodes assigned to the
103 /// FilterChooser becomes 1 or if there is a conflict. A conflict happens when
104 /// the Filter/FilterChooser combo does not know how to distinguish among the
105 /// Opcodes assigned.
107 /// An example of a conflict is
110 /// 111101000.00........00010000....
111 /// 111101000.00........0001........
112 /// 1111010...00........0001........
113 /// 1111010...00....................
114 /// 1111010.........................
115 /// 1111............................
116 /// ................................
117 /// VST4q8a 111101000_00________00010000____
118 /// VST4q8b 111101000_00________00010000____
120 /// The Debug output shows the path that the decoding tree follows to reach the
121 /// the conclusion that there is a conflict. VST4q8a is a vst4 to double-spaced
122 /// even registers, while VST4q8b is a vst4 to double-spaced odd regsisters.
124 /// The encoding info in the .td files does not specify this meta information,
125 /// which could have been used by the decoder to resolve the conflict. The
126 /// decoder could try to decode the even/odd register numbering and assign to
127 /// VST4q8a or VST4q8b, but for the time being, the decoder chooses the "a"
128 /// version and return the Opcode since the two have the same Asm format string.
131 FilterChooser *Owner; // points to the FilterChooser who owns this filter
132 unsigned StartBit; // the starting bit position
133 unsigned NumBits; // number of bits to filter
134 bool Mixed; // a mixed region contains both set and unset bits
136 // Map of well-known segment value to the set of uid's with that value.
137 std::map<uint64_t, std::vector<unsigned> > FilteredInstructions;
139 // Set of uid's with non-constant segment values.
140 std::vector<unsigned> VariableInstructions;
142 // Map of well-known segment value to its delegate.
143 std::map<unsigned, FilterChooser*> FilterChooserMap;
145 // Number of instructions which fall under FilteredInstructions category.
146 unsigned NumFiltered;
148 // Keeps track of the last opcode in the filtered bucket.
149 unsigned LastOpcFiltered;
151 // Number of instructions which fall under VariableInstructions category.
152 unsigned NumVariable;
155 unsigned getNumFiltered() { return NumFiltered; }
156 unsigned getNumVariable() { return NumVariable; }
157 unsigned getSingletonOpc() {
158 assert(NumFiltered == 1);
159 return LastOpcFiltered;
161 // Return the filter chooser for the group of instructions without constant
163 FilterChooser &getVariableFC() {
164 assert(NumFiltered == 1);
165 assert(FilterChooserMap.size() == 1);
166 return *(FilterChooserMap.find((unsigned)-1)->second);
169 Filter(const Filter &f);
170 Filter(FilterChooser &owner, unsigned startBit, unsigned numBits, bool mixed);
174 // Divides the decoding task into sub tasks and delegates them to the
175 // inferior FilterChooser's.
177 // A special case arises when there's only one entry in the filtered
178 // instructions. In order to unambiguously decode the singleton, we need to
179 // match the remaining undecoded encoding bits against the singleton.
182 // Emit code to decode instructions given a segment or segments of bits.
183 void emit(raw_ostream &o, unsigned &Indentation);
185 // Returns the number of fanout produced by the filter. More fanout implies
186 // the filter distinguishes more categories of instructions.
187 unsigned usefulness() const;
188 }; // End of class Filter
190 // These are states of our finite state machines used in FilterChooser's
191 // filterProcessor() which produces the filter candidates to use.
200 /// FilterChooser - FilterChooser chooses the best filter among a set of Filters
201 /// in order to perform the decoding of instructions at the current level.
203 /// Decoding proceeds from the top down. Based on the well-known encoding bits
204 /// of instructions available, FilterChooser builds up the possible Filters that
205 /// can further the task of decoding by distinguishing among the remaining
206 /// candidate instructions.
208 /// Once a filter has been chosen, it is called upon to divide the decoding task
209 /// into sub-tasks and delegates them to its inferior FilterChoosers for further
212 /// It is useful to think of a Filter as governing the switch stmts of the
213 /// decoding tree. And each case is delegated to an inferior FilterChooser to
214 /// decide what further remaining bits to look at.
215 class FilterChooser {
219 // Vector of codegen instructions to choose our filter.
220 const std::vector<const CodeGenInstruction*> &AllInstructions;
222 // Vector of uid's for this filter chooser to work on.
223 const std::vector<unsigned> Opcodes;
225 // Lookup table for the operand decoding of instructions.
226 std::map<unsigned, std::vector<OperandInfo> > &Operands;
228 // Vector of candidate filters.
229 std::vector<Filter> Filters;
231 // Array of bit values passed down from our parent.
232 // Set to all BIT_UNFILTERED's for Parent == NULL.
233 bit_value_t FilterBitValues[BIT_WIDTH];
235 // Links to the FilterChooser above us in the decoding tree.
236 FilterChooser *Parent;
238 // Index of the best filter from Filters.
242 FilterChooser(const FilterChooser &FC) :
243 AllInstructions(FC.AllInstructions), Opcodes(FC.Opcodes),
244 Operands(FC.Operands), Filters(FC.Filters), Parent(FC.Parent),
245 BestIndex(FC.BestIndex) {
246 memcpy(FilterBitValues, FC.FilterBitValues, sizeof(FilterBitValues));
249 FilterChooser(const std::vector<const CodeGenInstruction*> &Insts,
250 const std::vector<unsigned> &IDs,
251 std::map<unsigned, std::vector<OperandInfo> > &Ops) :
252 AllInstructions(Insts), Opcodes(IDs), Operands(Ops), Filters(),
253 Parent(NULL), BestIndex(-1) {
254 for (unsigned i = 0; i < BIT_WIDTH; ++i)
255 FilterBitValues[i] = BIT_UNFILTERED;
260 FilterChooser(const std::vector<const CodeGenInstruction*> &Insts,
261 const std::vector<unsigned> &IDs,
262 std::map<unsigned, std::vector<OperandInfo> > &Ops,
263 bit_value_t (&ParentFilterBitValues)[BIT_WIDTH],
264 FilterChooser &parent) :
265 AllInstructions(Insts), Opcodes(IDs), Operands(Ops),
266 Filters(), Parent(&parent), BestIndex(-1) {
267 for (unsigned i = 0; i < BIT_WIDTH; ++i)
268 FilterBitValues[i] = ParentFilterBitValues[i];
273 // The top level filter chooser has NULL as its parent.
274 bool isTopLevel() { return Parent == NULL; }
276 // Emit the top level typedef and decodeInstruction() function.
277 void emitTop(raw_ostream &o, unsigned Indentation);
280 // Populates the insn given the uid.
281 void insnWithID(insn_t &Insn, unsigned Opcode) const {
282 const BitsInit &Bits =
283 getBitsField(*AllInstructions[Opcode]->TheDef, "Inst");
285 for (unsigned i = 0; i < BIT_WIDTH; ++i)
286 Insn[i] = bitFromBits(Bits, i);
289 // Returns the record name.
290 const std::string &nameWithID(unsigned Opcode) const {
291 return AllInstructions[Opcode]->TheDef->getName();
294 // Populates the field of the insn given the start position and the number of
295 // consecutive bits to scan for.
297 // Returns false if there exists any uninitialized bit value in the range.
298 // Returns true, otherwise.
299 bool fieldFromInsn(uint64_t &Field, insn_t &Insn, unsigned StartBit,
300 unsigned NumBits) const;
302 /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
303 /// filter array as a series of chars.
304 void dumpFilterArray(raw_ostream &o, bit_value_t (&filter)[BIT_WIDTH]);
306 /// dumpStack - dumpStack traverses the filter chooser chain and calls
307 /// dumpFilterArray on each filter chooser up to the top level one.
308 void dumpStack(raw_ostream &o, const char *prefix);
310 Filter &bestFilter() {
311 assert(BestIndex != -1 && "BestIndex not set");
312 return Filters[BestIndex];
315 // Called from Filter::recurse() when singleton exists. For debug purpose.
316 void SingletonExists(unsigned Opc);
318 bool PositionFiltered(unsigned i) {
319 return ValueSet(FilterBitValues[i]);
322 // Calculates the island(s) needed to decode the instruction.
323 // This returns a lit of undecoded bits of an instructions, for example,
324 // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
325 // decoded bits in order to verify that the instruction matches the Opcode.
326 unsigned getIslands(std::vector<unsigned> &StartBits,
327 std::vector<unsigned> &EndBits, std::vector<uint64_t> &FieldVals,
330 // Emits code to decode the singleton. Return true if we have matched all the
332 bool emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,unsigned Opc);
334 // Emits code to decode the singleton, and then to decode the rest.
335 void emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,Filter &Best);
337 // Assign a single filter and run with it.
338 void runSingleFilter(FilterChooser &owner, unsigned startBit, unsigned numBit,
341 // reportRegion is a helper function for filterProcessor to mark a region as
342 // eligible for use as a filter region.
343 void reportRegion(bitAttr_t RA, unsigned StartBit, unsigned BitIndex,
346 // FilterProcessor scans the well-known encoding bits of the instructions and
347 // builds up a list of candidate filters. It chooses the best filter and
348 // recursively descends down the decoding tree.
349 bool filterProcessor(bool AllowMixed, bool Greedy = true);
351 // Decides on the best configuration of filter(s) to use in order to decode
352 // the instructions. A conflict of instructions may occur, in which case we
353 // dump the conflict set to the standard error.
356 // Emits code to decode our share of instructions. Returns true if the
357 // emitted code causes a return, which occurs if we know how to decode
358 // the instruction at this level or the instruction is not decodeable.
359 bool emit(raw_ostream &o, unsigned &Indentation);
362 ///////////////////////////
364 // Filter Implmenetation //
366 ///////////////////////////
368 Filter::Filter(const Filter &f) :
369 Owner(f.Owner), StartBit(f.StartBit), NumBits(f.NumBits), Mixed(f.Mixed),
370 FilteredInstructions(f.FilteredInstructions),
371 VariableInstructions(f.VariableInstructions),
372 FilterChooserMap(f.FilterChooserMap), NumFiltered(f.NumFiltered),
373 LastOpcFiltered(f.LastOpcFiltered), NumVariable(f.NumVariable) {
376 Filter::Filter(FilterChooser &owner, unsigned startBit, unsigned numBits,
377 bool mixed) : Owner(&owner), StartBit(startBit), NumBits(numBits),
379 assert(StartBit + NumBits - 1 < BIT_WIDTH);
385 for (unsigned i = 0, e = Owner->Opcodes.size(); i != e; ++i) {
388 // Populates the insn given the uid.
389 Owner->insnWithID(Insn, Owner->Opcodes[i]);
392 // Scans the segment for possibly well-specified encoding bits.
393 bool ok = Owner->fieldFromInsn(Field, Insn, StartBit, NumBits);
396 // The encoding bits are well-known. Lets add the uid of the
397 // instruction into the bucket keyed off the constant field value.
398 LastOpcFiltered = Owner->Opcodes[i];
399 FilteredInstructions[Field].push_back(LastOpcFiltered);
402 // Some of the encoding bit(s) are unspecfied. This contributes to
403 // one additional member of "Variable" instructions.
404 VariableInstructions.push_back(Owner->Opcodes[i]);
409 assert((FilteredInstructions.size() + VariableInstructions.size() > 0)
410 && "Filter returns no instruction categories");
414 std::map<unsigned, FilterChooser*>::iterator filterIterator;
415 for (filterIterator = FilterChooserMap.begin();
416 filterIterator != FilterChooserMap.end();
418 delete filterIterator->second;
422 // Divides the decoding task into sub tasks and delegates them to the
423 // inferior FilterChooser's.
425 // A special case arises when there's only one entry in the filtered
426 // instructions. In order to unambiguously decode the singleton, we need to
427 // match the remaining undecoded encoding bits against the singleton.
428 void Filter::recurse() {
429 std::map<uint64_t, std::vector<unsigned> >::const_iterator mapIterator;
431 bit_value_t BitValueArray[BIT_WIDTH];
432 // Starts by inheriting our parent filter chooser's filter bit values.
433 memcpy(BitValueArray, Owner->FilterBitValues, sizeof(BitValueArray));
437 if (VariableInstructions.size()) {
438 // Conservatively marks each segment position as BIT_UNSET.
439 for (bitIndex = 0; bitIndex < NumBits; bitIndex++)
440 BitValueArray[StartBit + bitIndex] = BIT_UNSET;
442 // Delegates to an inferior filter chooser for further processing on this
443 // group of instructions whose segment values are variable.
444 FilterChooserMap.insert(std::pair<unsigned, FilterChooser*>(
446 new FilterChooser(Owner->AllInstructions,
447 VariableInstructions,
454 // No need to recurse for a singleton filtered instruction.
455 // See also Filter::emit().
456 if (getNumFiltered() == 1) {
457 //Owner->SingletonExists(LastOpcFiltered);
458 assert(FilterChooserMap.size() == 1);
462 // Otherwise, create sub choosers.
463 for (mapIterator = FilteredInstructions.begin();
464 mapIterator != FilteredInstructions.end();
467 // Marks all the segment positions with either BIT_TRUE or BIT_FALSE.
468 for (bitIndex = 0; bitIndex < NumBits; bitIndex++) {
469 if (mapIterator->first & (1ULL << bitIndex))
470 BitValueArray[StartBit + bitIndex] = BIT_TRUE;
472 BitValueArray[StartBit + bitIndex] = BIT_FALSE;
475 // Delegates to an inferior filter chooser for further processing on this
476 // category of instructions.
477 FilterChooserMap.insert(std::pair<unsigned, FilterChooser*>(
479 new FilterChooser(Owner->AllInstructions,
488 // Emit code to decode instructions given a segment or segments of bits.
489 void Filter::emit(raw_ostream &o, unsigned &Indentation) {
490 o.indent(Indentation) << "// Check Inst{";
493 o << (StartBit + NumBits - 1) << '-';
495 o << StartBit << "} ...\n";
497 o.indent(Indentation) << "switch (fieldFromInstruction(insn, "
498 << StartBit << ", " << NumBits << ")) {\n";
500 std::map<unsigned, FilterChooser*>::iterator filterIterator;
502 bool DefaultCase = false;
503 for (filterIterator = FilterChooserMap.begin();
504 filterIterator != FilterChooserMap.end();
507 // Field value -1 implies a non-empty set of variable instructions.
508 // See also recurse().
509 if (filterIterator->first == (unsigned)-1) {
512 o.indent(Indentation) << "default:\n";
513 o.indent(Indentation) << " break; // fallthrough\n";
515 // Closing curly brace for the switch statement.
516 // This is unconventional because we want the default processing to be
517 // performed for the fallthrough cases as well, i.e., when the "cases"
518 // did not prove a decoded instruction.
519 o.indent(Indentation) << "}\n";
522 o.indent(Indentation) << "case " << filterIterator->first << ":\n";
524 // We arrive at a category of instructions with the same segment value.
525 // Now delegate to the sub filter chooser for further decodings.
526 // The case may fallthrough, which happens if the remaining well-known
527 // encoding bits do not match exactly.
528 if (!DefaultCase) { ++Indentation; ++Indentation; }
530 bool finished = filterIterator->second->emit(o, Indentation);
531 // For top level default case, there's no need for a break statement.
532 if (Owner->isTopLevel() && DefaultCase)
535 o.indent(Indentation) << "break;\n";
537 if (!DefaultCase) { --Indentation; --Indentation; }
540 // If there is no default case, we still need to supply a closing brace.
542 // Closing curly brace for the switch statement.
543 o.indent(Indentation) << "}\n";
547 // Returns the number of fanout produced by the filter. More fanout implies
548 // the filter distinguishes more categories of instructions.
549 unsigned Filter::usefulness() const {
550 if (VariableInstructions.size())
551 return FilteredInstructions.size();
553 return FilteredInstructions.size() + 1;
556 //////////////////////////////////
558 // Filterchooser Implementation //
560 //////////////////////////////////
562 // Emit the top level typedef and decodeInstruction() function.
563 void FilterChooser::emitTop(raw_ostream &o, unsigned Indentation) {
566 o.indent(Indentation) << "typedef uint8_t field_t;\n";
569 o.indent(Indentation) << "typedef uint16_t field_t;\n";
572 o.indent(Indentation) << "typedef uint32_t field_t;\n";
575 o.indent(Indentation) << "typedef uint64_t field_t;\n";
578 assert(0 && "Unexpected instruction size!");
583 o.indent(Indentation) << "static field_t " <<
584 "fieldFromInstruction(field_t insn, unsigned startBit, unsigned numBits)\n";
586 o.indent(Indentation) << "{\n";
588 ++Indentation; ++Indentation;
589 o.indent(Indentation) << "assert(startBit + numBits <= " << BIT_WIDTH
590 << " && \"Instruction field out of bounds!\");\n";
592 o.indent(Indentation) << "field_t fieldMask;\n";
594 o.indent(Indentation) << "if (numBits == " << BIT_WIDTH << ")\n";
596 ++Indentation; ++Indentation;
597 o.indent(Indentation) << "fieldMask = (field_t)-1;\n";
598 --Indentation; --Indentation;
600 o.indent(Indentation) << "else\n";
602 ++Indentation; ++Indentation;
603 o.indent(Indentation) << "fieldMask = ((1 << numBits) - 1) << startBit;\n";
604 --Indentation; --Indentation;
607 o.indent(Indentation) << "return (insn & fieldMask) >> startBit;\n";
608 --Indentation; --Indentation;
610 o.indent(Indentation) << "}\n";
614 o.indent(Indentation) <<
615 "static bool decodeInstruction(MCInst &MI, field_t insn, "
616 "uint64_t Address, const void *Decoder) {\n";
617 o.indent(Indentation) << " unsigned tmp = 0;\n";
619 ++Indentation; ++Indentation;
620 // Emits code to decode the instructions.
621 emit(o, Indentation);
624 o.indent(Indentation) << "return false;\n";
625 --Indentation; --Indentation;
627 o.indent(Indentation) << "}\n";
632 // Populates the field of the insn given the start position and the number of
633 // consecutive bits to scan for.
635 // Returns false if and on the first uninitialized bit value encountered.
636 // Returns true, otherwise.
637 bool FilterChooser::fieldFromInsn(uint64_t &Field, insn_t &Insn,
638 unsigned StartBit, unsigned NumBits) const {
641 for (unsigned i = 0; i < NumBits; ++i) {
642 if (Insn[StartBit + i] == BIT_UNSET)
645 if (Insn[StartBit + i] == BIT_TRUE)
646 Field = Field | (1ULL << i);
652 /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
653 /// filter array as a series of chars.
654 void FilterChooser::dumpFilterArray(raw_ostream &o,
655 bit_value_t (&filter)[BIT_WIDTH]) {
658 for (bitIndex = BIT_WIDTH; bitIndex > 0; bitIndex--) {
659 switch (filter[bitIndex - 1]) {
676 /// dumpStack - dumpStack traverses the filter chooser chain and calls
677 /// dumpFilterArray on each filter chooser up to the top level one.
678 void FilterChooser::dumpStack(raw_ostream &o, const char *prefix) {
679 FilterChooser *current = this;
683 dumpFilterArray(o, current->FilterBitValues);
685 current = current->Parent;
689 // Called from Filter::recurse() when singleton exists. For debug purpose.
690 void FilterChooser::SingletonExists(unsigned Opc) {
692 insnWithID(Insn0, Opc);
694 errs() << "Singleton exists: " << nameWithID(Opc)
695 << " with its decoding dominating ";
696 for (unsigned i = 0; i < Opcodes.size(); ++i) {
697 if (Opcodes[i] == Opc) continue;
698 errs() << nameWithID(Opcodes[i]) << ' ';
702 dumpStack(errs(), "\t\t");
703 for (unsigned i = 0; i < Opcodes.size(); i++) {
704 const std::string &Name = nameWithID(Opcodes[i]);
706 errs() << '\t' << Name << " ";
708 getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
713 // Calculates the island(s) needed to decode the instruction.
714 // This returns a list of undecoded bits of an instructions, for example,
715 // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
716 // decoded bits in order to verify that the instruction matches the Opcode.
717 unsigned FilterChooser::getIslands(std::vector<unsigned> &StartBits,
718 std::vector<unsigned> &EndBits, std::vector<uint64_t> &FieldVals,
723 uint64_t FieldVal = 0;
726 // 1: Water (the bit value does not affect decoding)
727 // 2: Island (well-known bit value needed for decoding)
731 for (unsigned i = 0; i < BIT_WIDTH; ++i) {
732 Val = Value(Insn[i]);
733 bool Filtered = PositionFiltered(i);
736 assert(0 && "Unreachable code!");
740 if (Filtered || Val == -1)
741 State = 1; // Still in Water
743 State = 2; // Into the Island
745 StartBits.push_back(i);
750 if (Filtered || Val == -1) {
751 State = 1; // Into the Water
752 EndBits.push_back(i - 1);
753 FieldVals.push_back(FieldVal);
756 State = 2; // Still in Island
758 FieldVal = FieldVal | Val << BitNo;
763 // If we are still in Island after the loop, do some housekeeping.
765 EndBits.push_back(BIT_WIDTH - 1);
766 FieldVals.push_back(FieldVal);
770 assert(StartBits.size() == Num && EndBits.size() == Num &&
771 FieldVals.size() == Num);
775 // Emits code to decode the singleton. Return true if we have matched all the
777 bool FilterChooser::emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,
779 std::vector<unsigned> StartBits;
780 std::vector<unsigned> EndBits;
781 std::vector<uint64_t> FieldVals;
783 insnWithID(Insn, Opc);
785 // Look for islands of undecoded bits of the singleton.
786 getIslands(StartBits, EndBits, FieldVals, Insn);
788 unsigned Size = StartBits.size();
791 // If we have matched all the well-known bits, just issue a return.
793 o.indent(Indentation) << "{\n";
794 o.indent(Indentation) << " MI.setOpcode(" << Opc << ");\n";
795 std::vector<OperandInfo>& InsnOperands = Operands[Opc];
796 for (std::vector<OperandInfo>::iterator
797 I = InsnOperands.begin(), E = InsnOperands.end(); I != E; ++I) {
798 // If a custom instruction decoder was specified, use that.
799 if (I->FieldBase == ~0U && I->FieldLength == ~0U) {
800 o.indent(Indentation) << " " << I->Decoder
801 << "(MI, insn, Address, Decoder);\n";
805 o.indent(Indentation)
806 << " tmp = fieldFromInstruction(insn, " << I->FieldBase
807 << ", " << I->FieldLength << ");\n";
808 if (I->Decoder != "") {
809 o.indent(Indentation) << " " << I->Decoder
810 << "(MI, tmp, Address, Decoder);\n";
812 o.indent(Indentation)
813 << " MI.addOperand(MCOperand::CreateImm(tmp));\n";
817 o.indent(Indentation) << " return true; // " << nameWithID(Opc)
819 o.indent(Indentation) << "}\n";
823 // Otherwise, there are more decodings to be done!
825 // Emit code to match the island(s) for the singleton.
826 o.indent(Indentation) << "// Check ";
828 for (I = Size; I != 0; --I) {
829 o << "Inst{" << EndBits[I-1] << '-' << StartBits[I-1] << "} ";
833 o << "for singleton decoding...\n";
836 o.indent(Indentation) << "if (";
838 for (I = Size; I != 0; --I) {
839 NumBits = EndBits[I-1] - StartBits[I-1] + 1;
840 o << "fieldFromInstruction(insn, " << StartBits[I-1] << ", " << NumBits
841 << ") == " << FieldVals[I-1];
847 o.indent(Indentation) << " MI.setOpcode(" << Opc << ");\n";
848 std::vector<OperandInfo>& InsnOperands = Operands[Opc];
849 for (std::vector<OperandInfo>::iterator
850 I = InsnOperands.begin(), E = InsnOperands.end(); I != E; ++I) {
851 // If a custom instruction decoder was specified, use that.
852 if (I->FieldBase == ~0U && I->FieldLength == ~0U) {
853 o.indent(Indentation) << " " << I->Decoder
854 << "(MI, insn, Address, Decoder);\n";
858 o.indent(Indentation)
859 << " tmp = fieldFromInstruction(insn, " << I->FieldBase
860 << ", " << I->FieldLength << ");\n";
861 if (I->Decoder != "") {
862 o.indent(Indentation) << " " << I->Decoder
863 << "(MI, tmp, Address, Decoder);\n";
865 o.indent(Indentation)
866 << " MI.addOperand(MCOperand::CreateImm(tmp));\n";
869 o.indent(Indentation) << " return true; // " << nameWithID(Opc)
871 o.indent(Indentation) << "}\n";
876 // Emits code to decode the singleton, and then to decode the rest.
877 void FilterChooser::emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,
880 unsigned Opc = Best.getSingletonOpc();
882 emitSingletonDecoder(o, Indentation, Opc);
884 // Emit code for the rest.
885 o.indent(Indentation) << "else\n";
888 Best.getVariableFC().emit(o, Indentation);
892 // Assign a single filter and run with it. Top level API client can initialize
893 // with a single filter to start the filtering process.
894 void FilterChooser::runSingleFilter(FilterChooser &owner, unsigned startBit,
895 unsigned numBit, bool mixed) {
897 Filter F(*this, startBit, numBit, true);
898 Filters.push_back(F);
899 BestIndex = 0; // Sole Filter instance to choose from.
900 bestFilter().recurse();
903 // reportRegion is a helper function for filterProcessor to mark a region as
904 // eligible for use as a filter region.
905 void FilterChooser::reportRegion(bitAttr_t RA, unsigned StartBit,
906 unsigned BitIndex, bool AllowMixed) {
907 if (RA == ATTR_MIXED && AllowMixed)
908 Filters.push_back(Filter(*this, StartBit, BitIndex - StartBit, true));
909 else if (RA == ATTR_ALL_SET && !AllowMixed)
910 Filters.push_back(Filter(*this, StartBit, BitIndex - StartBit, false));
913 // FilterProcessor scans the well-known encoding bits of the instructions and
914 // builds up a list of candidate filters. It chooses the best filter and
915 // recursively descends down the decoding tree.
916 bool FilterChooser::filterProcessor(bool AllowMixed, bool Greedy) {
919 unsigned numInstructions = Opcodes.size();
921 assert(numInstructions && "Filter created with no instructions");
923 // No further filtering is necessary.
924 if (numInstructions == 1)
927 // Heuristics. See also doFilter()'s "Heuristics" comment when num of
928 // instructions is 3.
929 if (AllowMixed && !Greedy) {
930 assert(numInstructions == 3);
932 for (unsigned i = 0; i < Opcodes.size(); ++i) {
933 std::vector<unsigned> StartBits;
934 std::vector<unsigned> EndBits;
935 std::vector<uint64_t> FieldVals;
938 insnWithID(Insn, Opcodes[i]);
940 // Look for islands of undecoded bits of any instruction.
941 if (getIslands(StartBits, EndBits, FieldVals, Insn) > 0) {
942 // Found an instruction with island(s). Now just assign a filter.
943 runSingleFilter(*this, StartBits[0], EndBits[0] - StartBits[0] + 1,
950 unsigned BitIndex, InsnIndex;
952 // We maintain BIT_WIDTH copies of the bitAttrs automaton.
953 // The automaton consumes the corresponding bit from each
956 // Input symbols: 0, 1, and _ (unset).
957 // States: NONE, FILTERED, ALL_SET, ALL_UNSET, and MIXED.
958 // Initial state: NONE.
960 // (NONE) ------- [01] -> (ALL_SET)
961 // (NONE) ------- _ ----> (ALL_UNSET)
962 // (ALL_SET) ---- [01] -> (ALL_SET)
963 // (ALL_SET) ---- _ ----> (MIXED)
964 // (ALL_UNSET) -- [01] -> (MIXED)
965 // (ALL_UNSET) -- _ ----> (ALL_UNSET)
966 // (MIXED) ------ . ----> (MIXED)
967 // (FILTERED)---- . ----> (FILTERED)
969 bitAttr_t bitAttrs[BIT_WIDTH];
971 // FILTERED bit positions provide no entropy and are not worthy of pursuing.
972 // Filter::recurse() set either BIT_TRUE or BIT_FALSE for each position.
973 for (BitIndex = 0; BitIndex < BIT_WIDTH; ++BitIndex)
974 if (FilterBitValues[BitIndex] == BIT_TRUE ||
975 FilterBitValues[BitIndex] == BIT_FALSE)
976 bitAttrs[BitIndex] = ATTR_FILTERED;
978 bitAttrs[BitIndex] = ATTR_NONE;
980 for (InsnIndex = 0; InsnIndex < numInstructions; ++InsnIndex) {
983 insnWithID(insn, Opcodes[InsnIndex]);
985 for (BitIndex = 0; BitIndex < BIT_WIDTH; ++BitIndex) {
986 switch (bitAttrs[BitIndex]) {
988 if (insn[BitIndex] == BIT_UNSET)
989 bitAttrs[BitIndex] = ATTR_ALL_UNSET;
991 bitAttrs[BitIndex] = ATTR_ALL_SET;
994 if (insn[BitIndex] == BIT_UNSET)
995 bitAttrs[BitIndex] = ATTR_MIXED;
998 if (insn[BitIndex] != BIT_UNSET)
999 bitAttrs[BitIndex] = ATTR_MIXED;
1008 // The regionAttr automaton consumes the bitAttrs automatons' state,
1009 // lowest-to-highest.
1011 // Input symbols: F(iltered), (all_)S(et), (all_)U(nset), M(ixed)
1012 // States: NONE, ALL_SET, MIXED
1013 // Initial state: NONE
1015 // (NONE) ----- F --> (NONE)
1016 // (NONE) ----- S --> (ALL_SET) ; and set region start
1017 // (NONE) ----- U --> (NONE)
1018 // (NONE) ----- M --> (MIXED) ; and set region start
1019 // (ALL_SET) -- F --> (NONE) ; and report an ALL_SET region
1020 // (ALL_SET) -- S --> (ALL_SET)
1021 // (ALL_SET) -- U --> (NONE) ; and report an ALL_SET region
1022 // (ALL_SET) -- M --> (MIXED) ; and report an ALL_SET region
1023 // (MIXED) ---- F --> (NONE) ; and report a MIXED region
1024 // (MIXED) ---- S --> (ALL_SET) ; and report a MIXED region
1025 // (MIXED) ---- U --> (NONE) ; and report a MIXED region
1026 // (MIXED) ---- M --> (MIXED)
1028 bitAttr_t RA = ATTR_NONE;
1029 unsigned StartBit = 0;
1031 for (BitIndex = 0; BitIndex < BIT_WIDTH; BitIndex++) {
1032 bitAttr_t bitAttr = bitAttrs[BitIndex];
1034 assert(bitAttr != ATTR_NONE && "Bit without attributes");
1042 StartBit = BitIndex;
1045 case ATTR_ALL_UNSET:
1048 StartBit = BitIndex;
1052 assert(0 && "Unexpected bitAttr!");
1058 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1063 case ATTR_ALL_UNSET:
1064 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1068 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1069 StartBit = BitIndex;
1073 assert(0 && "Unexpected bitAttr!");
1079 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1080 StartBit = BitIndex;
1084 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1085 StartBit = BitIndex;
1088 case ATTR_ALL_UNSET:
1089 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1095 assert(0 && "Unexpected bitAttr!");
1098 case ATTR_ALL_UNSET:
1099 assert(0 && "regionAttr state machine has no ATTR_UNSET state");
1101 assert(0 && "regionAttr state machine has no ATTR_FILTERED state");
1105 // At the end, if we're still in ALL_SET or MIXED states, report a region
1112 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1114 case ATTR_ALL_UNSET:
1117 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1121 // We have finished with the filter processings. Now it's time to choose
1122 // the best performing filter.
1124 bool AllUseless = true;
1125 unsigned BestScore = 0;
1127 for (unsigned i = 0, e = Filters.size(); i != e; ++i) {
1128 unsigned Usefulness = Filters[i].usefulness();
1133 if (Usefulness > BestScore) {
1135 BestScore = Usefulness;
1140 bestFilter().recurse();
1143 } // end of FilterChooser::filterProcessor(bool)
1145 // Decides on the best configuration of filter(s) to use in order to decode
1146 // the instructions. A conflict of instructions may occur, in which case we
1147 // dump the conflict set to the standard error.
1148 void FilterChooser::doFilter() {
1149 unsigned Num = Opcodes.size();
1150 assert(Num && "FilterChooser created with no instructions");
1152 // Try regions of consecutive known bit values first.
1153 if (filterProcessor(false))
1156 // Then regions of mixed bits (both known and unitialized bit values allowed).
1157 if (filterProcessor(true))
1160 // Heuristics to cope with conflict set {t2CMPrs, t2SUBSrr, t2SUBSrs} where
1161 // no single instruction for the maximum ATTR_MIXED region Inst{14-4} has a
1162 // well-known encoding pattern. In such case, we backtrack and scan for the
1163 // the very first consecutive ATTR_ALL_SET region and assign a filter to it.
1164 if (Num == 3 && filterProcessor(true, false))
1167 // If we come to here, the instruction decoding has failed.
1168 // Set the BestIndex to -1 to indicate so.
1172 // Emits code to decode our share of instructions. Returns true if the
1173 // emitted code causes a return, which occurs if we know how to decode
1174 // the instruction at this level or the instruction is not decodeable.
1175 bool FilterChooser::emit(raw_ostream &o, unsigned &Indentation) {
1176 if (Opcodes.size() == 1)
1177 // There is only one instruction in the set, which is great!
1178 // Call emitSingletonDecoder() to see whether there are any remaining
1180 return emitSingletonDecoder(o, Indentation, Opcodes[0]);
1182 // Choose the best filter to do the decodings!
1183 if (BestIndex != -1) {
1184 Filter &Best = bestFilter();
1185 if (Best.getNumFiltered() == 1)
1186 emitSingletonDecoder(o, Indentation, Best);
1188 bestFilter().emit(o, Indentation);
1192 // We don't know how to decode these instructions! Return 0 and dump the
1194 o.indent(Indentation) << "return 0;" << " // Conflict set: ";
1195 for (int i = 0, N = Opcodes.size(); i < N; ++i) {
1196 o << nameWithID(Opcodes[i]);
1203 // Print out useful conflict information for postmortem analysis.
1204 errs() << "Decoding Conflict:\n";
1206 dumpStack(errs(), "\t\t");
1208 for (unsigned i = 0; i < Opcodes.size(); i++) {
1209 const std::string &Name = nameWithID(Opcodes[i]);
1211 errs() << '\t' << Name << " ";
1213 getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
1220 bool FixedLenDecoderEmitter::populateInstruction(const CodeGenInstruction &CGI,
1222 const Record &Def = *CGI.TheDef;
1223 // If all the bit positions are not specified; do not decode this instruction.
1224 // We are bound to fail! For proper disassembly, the well-known encoding bits
1225 // of the instruction must be fully specified.
1227 // This also removes pseudo instructions from considerations of disassembly,
1228 // which is a better design and less fragile than the name matchings.
1229 // Ignore "asm parser only" instructions.
1230 if (Def.getValueAsBit("isAsmParserOnly") ||
1231 Def.getValueAsBit("isCodeGenOnly"))
1234 const BitsInit &Bits = getBitsField(Def, "Inst");
1235 if (Bits.allInComplete()) return false;
1237 std::vector<OperandInfo> InsnOperands;
1239 // If the instruction has specified a custom decoding hook, use that instead
1240 // of trying to auto-generate the decoder.
1241 std::string InstDecoder = Def.getValueAsString("DecoderMethod");
1242 if (InstDecoder != "") {
1243 InsnOperands.push_back(OperandInfo(~0U, ~0U, InstDecoder));
1244 Operands[Opc] = InsnOperands;
1248 // Generate a description of the operand of the instruction that we know
1249 // how to decode automatically.
1250 // FIXME: We'll need to have a way to manually override this as needed.
1252 // Gather the outputs/inputs of the instruction, so we can find their
1253 // positions in the encoding. This assumes for now that they appear in the
1254 // MCInst in the order that they're listed.
1255 std::vector<std::pair<const Init*, std::string> > InOutOperands;
1256 const DagInit *Out = Def.getValueAsDag("OutOperandList");
1257 const DagInit *In = Def.getValueAsDag("InOperandList");
1258 for (unsigned i = 0; i < Out->getNumArgs(); ++i)
1259 InOutOperands.push_back(std::make_pair(Out->getArg(i), Out->getArgName(i)));
1260 for (unsigned i = 0; i < In->getNumArgs(); ++i)
1261 InOutOperands.push_back(std::make_pair(In->getArg(i), In->getArgName(i)));
1263 // For each operand, see if we can figure out where it is encoded.
1264 for (std::vector<std::pair<const Init*, std::string> >::iterator
1265 NI = InOutOperands.begin(), NE = InOutOperands.end(); NI != NE; ++NI) {
1266 unsigned PrevBit = ~0;
1268 unsigned PrevPos = ~0;
1269 std::string Decoder = "";
1271 for (unsigned bi = 0; bi < Bits.getNumBits(); ++bi) {
1272 const VarBitInit *BI = dynamic_cast<const VarBitInit*>(Bits.getBit(bi));
1275 const VarInit *Var = dynamic_cast<const VarInit*>(BI->getVariable());
1277 unsigned CurrBit = BI->getBitNum();
1278 if (Var->getName() != NI->second) continue;
1280 // Figure out the lowest bit of the value, and the width of the field.
1281 // Deliberately don't try to handle cases where the field is scattered,
1282 // or where not all bits of the the field are explicit.
1283 if (Base == ~0U && PrevBit == ~0U && PrevPos == ~0U) {
1290 if ((PrevPos != ~0U && bi-1 != PrevPos) ||
1291 (CurrBit != ~0U && CurrBit-1 != PrevBit)) {
1300 // At this point, we can locate the field, but we need to know how to
1301 // interpret it. As a first step, require the target to provide callbacks
1302 // for decoding register classes.
1303 // FIXME: This need to be extended to handle instructions with custom
1304 // decoder methods, and operands with (simple) MIOperandInfo's.
1305 const TypedInit *TI = dynamic_cast<const TypedInit*>(NI->first);
1306 RecordRecTy *Type = dynamic_cast<RecordRecTy*>(TI->getType());
1307 Record *TypeRecord = Type->getRecord();
1309 if (TypeRecord->isSubClassOf("RegisterOperand"))
1310 TypeRecord = TypeRecord->getValueAsDef("RegClass");
1311 if (TypeRecord->isSubClassOf("RegisterClass")) {
1312 Decoder = "Decode" + TypeRecord->getName() + "RegisterClass";
1316 RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod");
1317 const StringInit *String = DecoderString ?
1318 dynamic_cast<const StringInit*>(DecoderString->getValue()) :
1320 if (!isReg && String && String->getValue() != "")
1321 Decoder = String->getValue();
1325 InsnOperands.push_back(OperandInfo(Base, PrevBit+1, Decoder));
1326 DEBUG(errs() << "ENCODED OPERAND: $" << NI->second << " @ ("
1327 << utostr(Base+PrevBit) << ", " << utostr(Base) << ")\n");
1331 Operands[Opc] = InsnOperands;
1336 // Dumps the instruction encoding bits.
1337 dumpBits(errs(), Bits);
1341 // Dumps the list of operand info.
1342 for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) {
1343 const CGIOperandList::OperandInfo &Info = CGI.Operands[i];
1344 const std::string &OperandName = Info.Name;
1345 const Record &OperandDef = *Info.Rec;
1347 errs() << "\t" << OperandName << " (" << OperandDef.getName() << ")\n";
1355 void FixedLenDecoderEmitter::populateInstructions() {
1356 for (unsigned i = 0, e = NumberedInstructions.size(); i < e; ++i) {
1357 Record *R = NumberedInstructions[i]->TheDef;
1358 if (R->getValueAsString("Namespace") == "TargetOpcode" ||
1359 R->getValueAsBit("isPseudo"))
1362 if (populateInstruction(*NumberedInstructions[i], i))
1363 Opcodes.push_back(i);
1367 // Emits disassembler code for instruction decoding.
1368 void FixedLenDecoderEmitter::run(raw_ostream &o)
1370 o << "#include \"llvm/MC/MCInst.h\"\n";
1371 o << "#include \"llvm/Support/DataTypes.h\"\n";
1372 o << "#include <assert.h>\n";
1374 o << "namespace llvm {\n\n";
1376 NumberedInstructions = Target.getInstructionsByEnumValue();
1377 populateInstructions();
1378 FilterChooser FC(NumberedInstructions, Opcodes, Operands);
1381 o << "\n} // End llvm namespace \n";