1 //===------------ 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" 19 #include "Record.h" 20 #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 28 using 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. 35 typedef enum { 36 BIT_TRUE, // '1' 37 BIT_FALSE, // '0' 38 BIT_UNSET, // '?' 39 BIT_UNFILTERED // unfiltered 40 } bit_value_t; 41 42 static bool ValueSet(bit_value_t V) { 43 return (V == BIT_TRUE || V == BIT_FALSE); 44 } 45 static bool ValueNotSet(bit_value_t V) { 46 return (V == BIT_UNSET); 47 } 48 static int Value(bit_value_t V) { 49 return ValueNotSet(V) ? -1 : (V == BIT_FALSE ? 0 : 1); 50 } 51 static bit_value_t bitFromBits(BitsInit &bits, unsigned index) { 52 if (BitInit *bit = dynamic_cast<BitInit*>(bits.getBit(index))) 53 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. 59 static void dumpBits(raw_ostream &o, BitsInit &bits) { 60 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: 74 assert(0 && "unexpected return value from bitFromBits"); 75 } 76 } 77 } 78 79 static BitsInit &getBitsField(const Record &def, const char *str) { 80 BitsInit *bits = def.getValueAsBitsInit(str); 81 return *bits; 82 } 83 84 // Forward declaration. 85 class FilterChooser; 86 87 // FIXME: Possibly auto-detected? 88 #define BIT_WIDTH 32 89 90 // Representation of the instruction to work on. 91 typedef bit_value_t insn_t[BIT_WIDTH]; 92 93 /// Filter - Filter works with FilterChooser to produce the decoding tree for 94 /// the ISA. 95 /// 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. 101 /// 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. 106 /// 107 /// An example of a conflict is 108 /// 109 /// Conflict: 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____ 119 /// 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. 123 /// 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. 129 class Filter { 130 protected: 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 135 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; 138 139 // Set of uid's with non-constant segment values. 140 std::vector<unsigned> VariableInstructions; 141 142 // Map of well-known segment value to its delegate. 143 std::map<unsigned, FilterChooser*> FilterChooserMap; 144 145 // Number of instructions which fall under FilteredInstructions category. 146 unsigned NumFiltered; 147 148 // Keeps track of the last opcode in the filtered bucket. 149 unsigned LastOpcFiltered; 150 151 // Number of instructions which fall under VariableInstructions category. 152 unsigned NumVariable; 153 154 public: 155 unsigned getNumFiltered() { return NumFiltered; } 156 unsigned getNumVariable() { return NumVariable; } 157 unsigned getSingletonOpc() { 158 assert(NumFiltered == 1); 159 return LastOpcFiltered; 160 } 161 // Return the filter chooser for the group of instructions without constant 162 // segment values. 163 FilterChooser &getVariableFC() { 164 assert(NumFiltered == 1); 165 assert(FilterChooserMap.size() == 1); 166 return *(FilterChooserMap.find((unsigned)-1)->second); 167 } 168 169 Filter(const Filter &f); 170 Filter(FilterChooser &owner, unsigned startBit, unsigned numBits, bool mixed); 171 172 ~Filter(); 173 174 // Divides the decoding task into sub tasks and delegates them to the 175 // inferior FilterChooser's. 176 // 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. 180 void recurse(); 181 182 // Emit code to decode instructions given a segment or segments of bits. 183 void emit(raw_ostream &o, unsigned &Indentation); 184 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 189 190 // These are states of our finite state machines used in FilterChooser's 191 // filterProcessor() which produces the filter candidates to use. 192 typedef enum { 193 ATTR_NONE, 194 ATTR_FILTERED, 195 ATTR_ALL_SET, 196 ATTR_ALL_UNSET, 197 ATTR_MIXED 198 } bitAttr_t; 199 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. 202 /// 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. 207 /// 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 210 /// processings. 211 /// 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 { 216 protected: 217 friend class Filter; 218 219 // Vector of codegen instructions to choose our filter. 220 const std::vector<const CodeGenInstruction*> &AllInstructions; 221 222 // Vector of uid's for this filter chooser to work on. 223 const std::vector<unsigned> Opcodes; 224 225 // Lookup table for the operand decoding of instructions. 226 std::map<unsigned, std::vector<OperandInfo> > &Operands; 227 228 // Vector of candidate filters. 229 std::vector<Filter> Filters; 230 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]; 234 235 // Links to the FilterChooser above us in the decoding tree. 236 FilterChooser *Parent; 237 238 // Index of the best filter from Filters. 239 int BestIndex; 240 241 public: 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)); 247 } 248 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; 256 257 doFilter(); 258 } 259 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]; 269 270 doFilter(); 271 } 272 273 // The top level filter chooser has NULL as its parent. 274 bool isTopLevel() { return Parent == NULL; } 275 276 // Emit the top level typedef and decodeInstruction() function. 277 void emitTop(raw_ostream &o, unsigned Indentation); 278 279 protected: 280 // Populates the insn given the uid. 281 void insnWithID(insn_t &Insn, unsigned Opcode) const { 282 BitsInit &Bits = getBitsField(*AllInstructions[Opcode]->TheDef, "Inst"); 283 284 for (unsigned i = 0; i < BIT_WIDTH; ++i) 285 Insn[i] = bitFromBits(Bits, i); 286 } 287 288 // Returns the record name. 289 const std::string &nameWithID(unsigned Opcode) const { 290 return AllInstructions[Opcode]->TheDef->getName(); 291 } 292 293 // Populates the field of the insn given the start position and the number of 294 // consecutive bits to scan for. 295 // 296 // Returns false if there exists any uninitialized bit value in the range. 297 // Returns true, otherwise. 298 bool fieldFromInsn(uint64_t &Field, insn_t &Insn, unsigned StartBit, 299 unsigned NumBits) const; 300 301 /// dumpFilterArray - dumpFilterArray prints out debugging info for the given 302 /// filter array as a series of chars. 303 void dumpFilterArray(raw_ostream &o, bit_value_t (&filter)[BIT_WIDTH]); 304 305 /// dumpStack - dumpStack traverses the filter chooser chain and calls 306 /// dumpFilterArray on each filter chooser up to the top level one. 307 void dumpStack(raw_ostream &o, const char *prefix); 308 309 Filter &bestFilter() { 310 assert(BestIndex != -1 && "BestIndex not set"); 311 return Filters[BestIndex]; 312 } 313 314 // Called from Filter::recurse() when singleton exists. For debug purpose. 315 void SingletonExists(unsigned Opc); 316 317 bool PositionFiltered(unsigned i) { 318 return ValueSet(FilterBitValues[i]); 319 } 320 321 // Calculates the island(s) needed to decode the instruction. 322 // This returns a lit of undecoded bits of an instructions, for example, 323 // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be 324 // decoded bits in order to verify that the instruction matches the Opcode. 325 unsigned getIslands(std::vector<unsigned> &StartBits, 326 std::vector<unsigned> &EndBits, std::vector<uint64_t> &FieldVals, 327 insn_t &Insn); 328 329 // Emits code to decode the singleton. Return true if we have matched all the 330 // well-known bits. 331 bool emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,unsigned Opc); 332 333 // Emits code to decode the singleton, and then to decode the rest. 334 void emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,Filter &Best); 335 336 // Assign a single filter and run with it. 337 void runSingleFilter(FilterChooser &owner, unsigned startBit, unsigned numBit, 338 bool mixed); 339 340 // reportRegion is a helper function for filterProcessor to mark a region as 341 // eligible for use as a filter region. 342 void reportRegion(bitAttr_t RA, unsigned StartBit, unsigned BitIndex, 343 bool AllowMixed); 344 345 // FilterProcessor scans the well-known encoding bits of the instructions and 346 // builds up a list of candidate filters. It chooses the best filter and 347 // recursively descends down the decoding tree. 348 bool filterProcessor(bool AllowMixed, bool Greedy = true); 349 350 // Decides on the best configuration of filter(s) to use in order to decode 351 // the instructions. A conflict of instructions may occur, in which case we 352 // dump the conflict set to the standard error. 353 void doFilter(); 354 355 // Emits code to decode our share of instructions. Returns true if the 356 // emitted code causes a return, which occurs if we know how to decode 357 // the instruction at this level or the instruction is not decodeable. 358 bool emit(raw_ostream &o, unsigned &Indentation); 359 }; 360 361 /////////////////////////// 362 // // 363 // Filter Implmenetation // 364 // // 365 /////////////////////////// 366 367 Filter::Filter(const Filter &f) : 368 Owner(f.Owner), StartBit(f.StartBit), NumBits(f.NumBits), Mixed(f.Mixed), 369 FilteredInstructions(f.FilteredInstructions), 370 VariableInstructions(f.VariableInstructions), 371 FilterChooserMap(f.FilterChooserMap), NumFiltered(f.NumFiltered), 372 LastOpcFiltered(f.LastOpcFiltered), NumVariable(f.NumVariable) { 373 } 374 375 Filter::Filter(FilterChooser &owner, unsigned startBit, unsigned numBits, 376 bool mixed) : Owner(&owner), StartBit(startBit), NumBits(numBits), 377 Mixed(mixed) { 378 assert(StartBit + NumBits - 1 < BIT_WIDTH); 379 380 NumFiltered = 0; 381 LastOpcFiltered = 0; 382 NumVariable = 0; 383 384 for (unsigned i = 0, e = Owner->Opcodes.size(); i != e; ++i) { 385 insn_t Insn; 386 387 // Populates the insn given the uid. 388 Owner->insnWithID(Insn, Owner->Opcodes[i]); 389 390 uint64_t Field; 391 // Scans the segment for possibly well-specified encoding bits. 392 bool ok = Owner->fieldFromInsn(Field, Insn, StartBit, NumBits); 393 394 if (ok) { 395 // The encoding bits are well-known. Lets add the uid of the 396 // instruction into the bucket keyed off the constant field value. 397 LastOpcFiltered = Owner->Opcodes[i]; 398 FilteredInstructions[Field].push_back(LastOpcFiltered); 399 ++NumFiltered; 400 } else { 401 // Some of the encoding bit(s) are unspecfied. This contributes to 402 // one additional member of "Variable" instructions. 403 VariableInstructions.push_back(Owner->Opcodes[i]); 404 ++NumVariable; 405 } 406 } 407 408 assert((FilteredInstructions.size() + VariableInstructions.size() > 0) 409 && "Filter returns no instruction categories"); 410 } 411 412 Filter::~Filter() { 413 std::map<unsigned, FilterChooser*>::iterator filterIterator; 414 for (filterIterator = FilterChooserMap.begin(); 415 filterIterator != FilterChooserMap.end(); 416 filterIterator++) { 417 delete filterIterator->second; 418 } 419 } 420 421 // Divides the decoding task into sub tasks and delegates them to the 422 // inferior FilterChooser's. 423 // 424 // A special case arises when there's only one entry in the filtered 425 // instructions. In order to unambiguously decode the singleton, we need to 426 // match the remaining undecoded encoding bits against the singleton. 427 void Filter::recurse() { 428 std::map<uint64_t, std::vector<unsigned> >::const_iterator mapIterator; 429 430 bit_value_t BitValueArray[BIT_WIDTH]; 431 // Starts by inheriting our parent filter chooser's filter bit values. 432 memcpy(BitValueArray, Owner->FilterBitValues, sizeof(BitValueArray)); 433 434 unsigned bitIndex; 435 436 if (VariableInstructions.size()) { 437 // Conservatively marks each segment position as BIT_UNSET. 438 for (bitIndex = 0; bitIndex < NumBits; bitIndex++) 439 BitValueArray[StartBit + bitIndex] = BIT_UNSET; 440 441 // Delegates to an inferior filter chooser for further processing on this 442 // group of instructions whose segment values are variable. 443 FilterChooserMap.insert(std::pair<unsigned, FilterChooser*>( 444 (unsigned)-1, 445 new FilterChooser(Owner->AllInstructions, 446 VariableInstructions, 447 Owner->Operands, 448 BitValueArray, 449 *Owner) 450 )); 451 } 452 453 // No need to recurse for a singleton filtered instruction. 454 // See also Filter::emit(). 455 if (getNumFiltered() == 1) { 456 //Owner->SingletonExists(LastOpcFiltered); 457 assert(FilterChooserMap.size() == 1); 458 return; 459 } 460 461 // Otherwise, create sub choosers. 462 for (mapIterator = FilteredInstructions.begin(); 463 mapIterator != FilteredInstructions.end(); 464 mapIterator++) { 465 466 // Marks all the segment positions with either BIT_TRUE or BIT_FALSE. 467 for (bitIndex = 0; bitIndex < NumBits; bitIndex++) { 468 if (mapIterator->first & (1ULL << bitIndex)) 469 BitValueArray[StartBit + bitIndex] = BIT_TRUE; 470 else 471 BitValueArray[StartBit + bitIndex] = BIT_FALSE; 472 } 473 474 // Delegates to an inferior filter chooser for further processing on this 475 // category of instructions. 476 FilterChooserMap.insert(std::pair<unsigned, FilterChooser*>( 477 mapIterator->first, 478 new FilterChooser(Owner->AllInstructions, 479 mapIterator->second, 480 Owner->Operands, 481 BitValueArray, 482 *Owner) 483 )); 484 } 485 } 486 487 // Emit code to decode instructions given a segment or segments of bits. 488 void Filter::emit(raw_ostream &o, unsigned &Indentation) { 489 o.indent(Indentation) << "// Check Inst{"; 490 491 if (NumBits > 1) 492 o << (StartBit + NumBits - 1) << '-'; 493 494 o << StartBit << "} ...\n"; 495 496 o.indent(Indentation) << "switch (fieldFromInstruction(insn, " 497 << StartBit << ", " << NumBits << ")) {\n"; 498 499 std::map<unsigned, FilterChooser*>::iterator filterIterator; 500 501 bool DefaultCase = false; 502 for (filterIterator = FilterChooserMap.begin(); 503 filterIterator != FilterChooserMap.end(); 504 filterIterator++) { 505 506 // Field value -1 implies a non-empty set of variable instructions. 507 // See also recurse(). 508 if (filterIterator->first == (unsigned)-1) { 509 DefaultCase = true; 510 511 o.indent(Indentation) << "default:\n"; 512 o.indent(Indentation) << " break; // fallthrough\n"; 513 514 // Closing curly brace for the switch statement. 515 // This is unconventional because we want the default processing to be 516 // performed for the fallthrough cases as well, i.e., when the "cases" 517 // did not prove a decoded instruction. 518 o.indent(Indentation) << "}\n"; 519 520 } else 521 o.indent(Indentation) << "case " << filterIterator->first << ":\n"; 522 523 // We arrive at a category of instructions with the same segment value. 524 // Now delegate to the sub filter chooser for further decodings. 525 // The case may fallthrough, which happens if the remaining well-known 526 // encoding bits do not match exactly. 527 if (!DefaultCase) { ++Indentation; ++Indentation; } 528 529 bool finished = filterIterator->second->emit(o, Indentation); 530 // For top level default case, there's no need for a break statement. 531 if (Owner->isTopLevel() && DefaultCase) 532 break; 533 if (!finished) 534 o.indent(Indentation) << "break;\n"; 535 536 if (!DefaultCase) { --Indentation; --Indentation; } 537 } 538 539 // If there is no default case, we still need to supply a closing brace. 540 if (!DefaultCase) { 541 // Closing curly brace for the switch statement. 542 o.indent(Indentation) << "}\n"; 543 } 544 } 545 546 // Returns the number of fanout produced by the filter. More fanout implies 547 // the filter distinguishes more categories of instructions. 548 unsigned Filter::usefulness() const { 549 if (VariableInstructions.size()) 550 return FilteredInstructions.size(); 551 else 552 return FilteredInstructions.size() + 1; 553 } 554 555 ////////////////////////////////// 556 // // 557 // Filterchooser Implementation // 558 // // 559 ////////////////////////////////// 560 561 // Emit the top level typedef and decodeInstruction() function. 562 void FilterChooser::emitTop(raw_ostream &o, unsigned Indentation) { 563 switch (BIT_WIDTH) { 564 case 8: 565 o.indent(Indentation) << "typedef uint8_t field_t;\n"; 566 break; 567 case 16: 568 o.indent(Indentation) << "typedef uint16_t field_t;\n"; 569 break; 570 case 32: 571 o.indent(Indentation) << "typedef uint32_t field_t;\n"; 572 break; 573 case 64: 574 o.indent(Indentation) << "typedef uint64_t field_t;\n"; 575 break; 576 default: 577 assert(0 && "Unexpected instruction size!"); 578 } 579 580 o << '\n'; 581 582 o.indent(Indentation) << "static field_t " << 583 "fieldFromInstruction(field_t insn, unsigned startBit, unsigned numBits)\n"; 584 585 o.indent(Indentation) << "{\n"; 586 587 ++Indentation; ++Indentation; 588 o.indent(Indentation) << "assert(startBit + numBits <= " << BIT_WIDTH 589 << " && \"Instruction field out of bounds!\");\n"; 590 o << '\n'; 591 o.indent(Indentation) << "field_t fieldMask;\n"; 592 o << '\n'; 593 o.indent(Indentation) << "if (numBits == " << BIT_WIDTH << ")\n"; 594 595 ++Indentation; ++Indentation; 596 o.indent(Indentation) << "fieldMask = (field_t)-1;\n"; 597 --Indentation; --Indentation; 598 599 o.indent(Indentation) << "else\n"; 600 601 ++Indentation; ++Indentation; 602 o.indent(Indentation) << "fieldMask = ((1 << numBits) - 1) << startBit;\n"; 603 --Indentation; --Indentation; 604 605 o << '\n'; 606 o.indent(Indentation) << "return (insn & fieldMask) >> startBit;\n"; 607 --Indentation; --Indentation; 608 609 o.indent(Indentation) << "}\n"; 610 611 o << '\n'; 612 613 o.indent(Indentation) << 614 "static bool decodeInstruction(MCInst &MI, field_t insn, " 615 "uint64_t Address, const void *Decoder) {\n"; 616 o.indent(Indentation) << " unsigned tmp = 0;\n"; 617 618 ++Indentation; ++Indentation; 619 // Emits code to decode the instructions. 620 emit(o, Indentation); 621 622 o << '\n'; 623 o.indent(Indentation) << "return false;\n"; 624 --Indentation; --Indentation; 625 626 o.indent(Indentation) << "}\n"; 627 628 o << '\n'; 629 } 630 631 // Populates the field of the insn given the start position and the number of 632 // consecutive bits to scan for. 633 // 634 // Returns false if and on the first uninitialized bit value encountered. 635 // Returns true, otherwise. 636 bool FilterChooser::fieldFromInsn(uint64_t &Field, insn_t &Insn, 637 unsigned StartBit, unsigned NumBits) const { 638 Field = 0; 639 640 for (unsigned i = 0; i < NumBits; ++i) { 641 if (Insn[StartBit + i] == BIT_UNSET) 642 return false; 643 644 if (Insn[StartBit + i] == BIT_TRUE) 645 Field = Field | (1ULL << i); 646 } 647 648 return true; 649 } 650 651 /// dumpFilterArray - dumpFilterArray prints out debugging info for the given 652 /// filter array as a series of chars. 653 void FilterChooser::dumpFilterArray(raw_ostream &o, 654 bit_value_t (&filter)[BIT_WIDTH]) { 655 unsigned bitIndex; 656 657 for (bitIndex = BIT_WIDTH; bitIndex > 0; bitIndex--) { 658 switch (filter[bitIndex - 1]) { 659 case BIT_UNFILTERED: 660 o << "."; 661 break; 662 case BIT_UNSET: 663 o << "_"; 664 break; 665 case BIT_TRUE: 666 o << "1"; 667 break; 668 case BIT_FALSE: 669 o << "0"; 670 break; 671 } 672 } 673 } 674 675 /// dumpStack - dumpStack traverses the filter chooser chain and calls 676 /// dumpFilterArray on each filter chooser up to the top level one. 677 void FilterChooser::dumpStack(raw_ostream &o, const char *prefix) { 678 FilterChooser *current = this; 679 680 while (current) { 681 o << prefix; 682 dumpFilterArray(o, current->FilterBitValues); 683 o << '\n'; 684 current = current->Parent; 685 } 686 } 687 688 // Called from Filter::recurse() when singleton exists. For debug purpose. 689 void FilterChooser::SingletonExists(unsigned Opc) { 690 insn_t Insn0; 691 insnWithID(Insn0, Opc); 692 693 errs() << "Singleton exists: " << nameWithID(Opc) 694 << " with its decoding dominating "; 695 for (unsigned i = 0; i < Opcodes.size(); ++i) { 696 if (Opcodes[i] == Opc) continue; 697 errs() << nameWithID(Opcodes[i]) << ' '; 698 } 699 errs() << '\n'; 700 701 dumpStack(errs(), "\t\t"); 702 for (unsigned i = 0; i < Opcodes.size(); i++) { 703 const std::string &Name = nameWithID(Opcodes[i]); 704 705 errs() << '\t' << Name << " "; 706 dumpBits(errs(), 707 getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst")); 708 errs() << '\n'; 709 } 710 } 711 712 // Calculates the island(s) needed to decode the instruction. 713 // This returns a list of undecoded bits of an instructions, for example, 714 // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be 715 // decoded bits in order to verify that the instruction matches the Opcode. 716 unsigned FilterChooser::getIslands(std::vector<unsigned> &StartBits, 717 std::vector<unsigned> &EndBits, std::vector<uint64_t> &FieldVals, 718 insn_t &Insn) { 719 unsigned Num, BitNo; 720 Num = BitNo = 0; 721 722 uint64_t FieldVal = 0; 723 724 // 0: Init 725 // 1: Water (the bit value does not affect decoding) 726 // 2: Island (well-known bit value needed for decoding) 727 int State = 0; 728 int Val = -1; 729 730 for (unsigned i = 0; i < BIT_WIDTH; ++i) { 731 Val = Value(Insn[i]); 732 bool Filtered = PositionFiltered(i); 733 switch (State) { 734 default: 735 assert(0 && "Unreachable code!"); 736 break; 737 case 0: 738 case 1: 739 if (Filtered || Val == -1) 740 State = 1; // Still in Water 741 else { 742 State = 2; // Into the Island 743 BitNo = 0; 744 StartBits.push_back(i); 745 FieldVal = Val; 746 } 747 break; 748 case 2: 749 if (Filtered || Val == -1) { 750 State = 1; // Into the Water 751 EndBits.push_back(i - 1); 752 FieldVals.push_back(FieldVal); 753 ++Num; 754 } else { 755 State = 2; // Still in Island 756 ++BitNo; 757 FieldVal = FieldVal | Val << BitNo; 758 } 759 break; 760 } 761 } 762 // If we are still in Island after the loop, do some housekeeping. 763 if (State == 2) { 764 EndBits.push_back(BIT_WIDTH - 1); 765 FieldVals.push_back(FieldVal); 766 ++Num; 767 } 768 769 assert(StartBits.size() == Num && EndBits.size() == Num && 770 FieldVals.size() == Num); 771 return Num; 772 } 773 774 // Emits code to decode the singleton. Return true if we have matched all the 775 // well-known bits. 776 bool FilterChooser::emitSingletonDecoder(raw_ostream &o, unsigned &Indentation, 777 unsigned Opc) { 778 std::vector<unsigned> StartBits; 779 std::vector<unsigned> EndBits; 780 std::vector<uint64_t> FieldVals; 781 insn_t Insn; 782 insnWithID(Insn, Opc); 783 784 // Look for islands of undecoded bits of the singleton. 785 getIslands(StartBits, EndBits, FieldVals, Insn); 786 787 unsigned Size = StartBits.size(); 788 unsigned I, NumBits; 789 790 // If we have matched all the well-known bits, just issue a return. 791 if (Size == 0) { 792 o.indent(Indentation) << "{\n"; 793 o.indent(Indentation) << " MI.setOpcode(" << Opc << ");\n"; 794 std::vector<OperandInfo>& InsnOperands = Operands[Opc]; 795 for (std::vector<OperandInfo>::iterator 796 I = InsnOperands.begin(), E = InsnOperands.end(); I != E; ++I) { 797 // If a custom instruction decoder was specified, use that. 798 if (I->FieldBase == ~0U && I->FieldLength == ~0U) { 799 o.indent(Indentation) << " " << I->Decoder 800 << "(MI, insn, Address, Decoder);\n"; 801 break; 802 } 803 804 o.indent(Indentation) 805 << " tmp = fieldFromInstruction(insn, " << I->FieldBase 806 << ", " << I->FieldLength << ");\n"; 807 if (I->Decoder != "") { 808 o.indent(Indentation) << " " << I->Decoder 809 << "(MI, tmp, Address, Decoder);\n"; 810 } else { 811 o.indent(Indentation) 812 << " MI.addOperand(MCOperand::CreateImm(tmp));\n"; 813 } 814 } 815 816 o.indent(Indentation) << " return true; // " << nameWithID(Opc) 817 << '\n'; 818 o.indent(Indentation) << "}\n"; 819 return true; 820 } 821 822 // Otherwise, there are more decodings to be done! 823 824 // Emit code to match the island(s) for the singleton. 825 o.indent(Indentation) << "// Check "; 826 827 for (I = Size; I != 0; --I) { 828 o << "Inst{" << EndBits[I-1] << '-' << StartBits[I-1] << "} "; 829 if (I > 1) 830 o << "&& "; 831 else 832 o << "for singleton decoding...\n"; 833 } 834 835 o.indent(Indentation) << "if ("; 836 837 for (I = Size; I != 0; --I) { 838 NumBits = EndBits[I-1] - StartBits[I-1] + 1; 839 o << "fieldFromInstruction(insn, " << StartBits[I-1] << ", " << NumBits 840 << ") == " << FieldVals[I-1]; 841 if (I > 1) 842 o << " && "; 843 else 844 o << ") {\n"; 845 } 846 o.indent(Indentation) << " MI.setOpcode(" << Opc << ");\n"; 847 std::vector<OperandInfo>& InsnOperands = Operands[Opc]; 848 for (std::vector<OperandInfo>::iterator 849 I = InsnOperands.begin(), E = InsnOperands.end(); I != E; ++I) { 850 // If a custom instruction decoder was specified, use that. 851 if (I->FieldBase == ~0U && I->FieldLength == ~0U) { 852 o.indent(Indentation) << " " << I->Decoder 853 << "(MI, insn, Address, Decoder);\n"; 854 break; 855 } 856 857 o.indent(Indentation) 858 << " tmp = fieldFromInstruction(insn, " << I->FieldBase 859 << ", " << I->FieldLength << ");\n"; 860 if (I->Decoder != "") { 861 o.indent(Indentation) << " " << I->Decoder 862 << "(MI, tmp, Address, Decoder);\n"; 863 } else { 864 o.indent(Indentation) 865 << " MI.addOperand(MCOperand::CreateImm(tmp));\n"; 866 } 867 } 868 o.indent(Indentation) << " return true; // " << nameWithID(Opc) 869 << '\n'; 870 o.indent(Indentation) << "}\n"; 871 872 return false; 873 } 874 875 // Emits code to decode the singleton, and then to decode the rest. 876 void FilterChooser::emitSingletonDecoder(raw_ostream &o, unsigned &Indentation, 877 Filter &Best) { 878 879 unsigned Opc = Best.getSingletonOpc(); 880 881 emitSingletonDecoder(o, Indentation, Opc); 882 883 // Emit code for the rest. 884 o.indent(Indentation) << "else\n"; 885 886 Indentation += 2; 887 Best.getVariableFC().emit(o, Indentation); 888 Indentation -= 2; 889 } 890 891 // Assign a single filter and run with it. Top level API client can initialize 892 // with a single filter to start the filtering process. 893 void FilterChooser::runSingleFilter(FilterChooser &owner, unsigned startBit, 894 unsigned numBit, bool mixed) { 895 Filters.clear(); 896 Filter F(*this, startBit, numBit, true); 897 Filters.push_back(F); 898 BestIndex = 0; // Sole Filter instance to choose from. 899 bestFilter().recurse(); 900 } 901 902 // reportRegion is a helper function for filterProcessor to mark a region as 903 // eligible for use as a filter region. 904 void FilterChooser::reportRegion(bitAttr_t RA, unsigned StartBit, 905 unsigned BitIndex, bool AllowMixed) { 906 if (RA == ATTR_MIXED && AllowMixed) 907 Filters.push_back(Filter(*this, StartBit, BitIndex - StartBit, true)); 908 else if (RA == ATTR_ALL_SET && !AllowMixed) 909 Filters.push_back(Filter(*this, StartBit, BitIndex - StartBit, false)); 910 } 911 912 // FilterProcessor scans the well-known encoding bits of the instructions and 913 // builds up a list of candidate filters. It chooses the best filter and 914 // recursively descends down the decoding tree. 915 bool FilterChooser::filterProcessor(bool AllowMixed, bool Greedy) { 916 Filters.clear(); 917 BestIndex = -1; 918 unsigned numInstructions = Opcodes.size(); 919 920 assert(numInstructions && "Filter created with no instructions"); 921 922 // No further filtering is necessary. 923 if (numInstructions == 1) 924 return true; 925 926 // Heuristics. See also doFilter()'s "Heuristics" comment when num of 927 // instructions is 3. 928 if (AllowMixed && !Greedy) { 929 assert(numInstructions == 3); 930 931 for (unsigned i = 0; i < Opcodes.size(); ++i) { 932 std::vector<unsigned> StartBits; 933 std::vector<unsigned> EndBits; 934 std::vector<uint64_t> FieldVals; 935 insn_t Insn; 936 937 insnWithID(Insn, Opcodes[i]); 938 939 // Look for islands of undecoded bits of any instruction. 940 if (getIslands(StartBits, EndBits, FieldVals, Insn) > 0) { 941 // Found an instruction with island(s). Now just assign a filter. 942 runSingleFilter(*this, StartBits[0], EndBits[0] - StartBits[0] + 1, 943 true); 944 return true; 945 } 946 } 947 } 948 949 unsigned BitIndex, InsnIndex; 950 951 // We maintain BIT_WIDTH copies of the bitAttrs automaton. 952 // The automaton consumes the corresponding bit from each 953 // instruction. 954 // 955 // Input symbols: 0, 1, and _ (unset). 956 // States: NONE, FILTERED, ALL_SET, ALL_UNSET, and MIXED. 957 // Initial state: NONE. 958 // 959 // (NONE) ------- [01] -> (ALL_SET) 960 // (NONE) ------- _ ----> (ALL_UNSET) 961 // (ALL_SET) ---- [01] -> (ALL_SET) 962 // (ALL_SET) ---- _ ----> (MIXED) 963 // (ALL_UNSET) -- [01] -> (MIXED) 964 // (ALL_UNSET) -- _ ----> (ALL_UNSET) 965 // (MIXED) ------ . ----> (MIXED) 966 // (FILTERED)---- . ----> (FILTERED) 967 968 bitAttr_t bitAttrs[BIT_WIDTH]; 969 970 // FILTERED bit positions provide no entropy and are not worthy of pursuing. 971 // Filter::recurse() set either BIT_TRUE or BIT_FALSE for each position. 972 for (BitIndex = 0; BitIndex < BIT_WIDTH; ++BitIndex) 973 if (FilterBitValues[BitIndex] == BIT_TRUE || 974 FilterBitValues[BitIndex] == BIT_FALSE) 975 bitAttrs[BitIndex] = ATTR_FILTERED; 976 else 977 bitAttrs[BitIndex] = ATTR_NONE; 978 979 for (InsnIndex = 0; InsnIndex < numInstructions; ++InsnIndex) { 980 insn_t insn; 981 982 insnWithID(insn, Opcodes[InsnIndex]); 983 984 for (BitIndex = 0; BitIndex < BIT_WIDTH; ++BitIndex) { 985 switch (bitAttrs[BitIndex]) { 986 case ATTR_NONE: 987 if (insn[BitIndex] == BIT_UNSET) 988 bitAttrs[BitIndex] = ATTR_ALL_UNSET; 989 else 990 bitAttrs[BitIndex] = ATTR_ALL_SET; 991 break; 992 case ATTR_ALL_SET: 993 if (insn[BitIndex] == BIT_UNSET) 994 bitAttrs[BitIndex] = ATTR_MIXED; 995 break; 996 case ATTR_ALL_UNSET: 997 if (insn[BitIndex] != BIT_UNSET) 998 bitAttrs[BitIndex] = ATTR_MIXED; 999 break; 1000 case ATTR_MIXED: 1001 case ATTR_FILTERED: 1002 break; 1003 } 1004 } 1005 } 1006 1007 // The regionAttr automaton consumes the bitAttrs automatons' state, 1008 // lowest-to-highest. 1009 // 1010 // Input symbols: F(iltered), (all_)S(et), (all_)U(nset), M(ixed) 1011 // States: NONE, ALL_SET, MIXED 1012 // Initial state: NONE 1013 // 1014 // (NONE) ----- F --> (NONE) 1015 // (NONE) ----- S --> (ALL_SET) ; and set region start 1016 // (NONE) ----- U --> (NONE) 1017 // (NONE) ----- M --> (MIXED) ; and set region start 1018 // (ALL_SET) -- F --> (NONE) ; and report an ALL_SET region 1019 // (ALL_SET) -- S --> (ALL_SET) 1020 // (ALL_SET) -- U --> (NONE) ; and report an ALL_SET region 1021 // (ALL_SET) -- M --> (MIXED) ; and report an ALL_SET region 1022 // (MIXED) ---- F --> (NONE) ; and report a MIXED region 1023 // (MIXED) ---- S --> (ALL_SET) ; and report a MIXED region 1024 // (MIXED) ---- U --> (NONE) ; and report a MIXED region 1025 // (MIXED) ---- M --> (MIXED) 1026 1027 bitAttr_t RA = ATTR_NONE; 1028 unsigned StartBit = 0; 1029 1030 for (BitIndex = 0; BitIndex < BIT_WIDTH; BitIndex++) { 1031 bitAttr_t bitAttr = bitAttrs[BitIndex]; 1032 1033 assert(bitAttr != ATTR_NONE && "Bit without attributes"); 1034 1035 switch (RA) { 1036 case ATTR_NONE: 1037 switch (bitAttr) { 1038 case ATTR_FILTERED: 1039 break; 1040 case ATTR_ALL_SET: 1041 StartBit = BitIndex; 1042 RA = ATTR_ALL_SET; 1043 break; 1044 case ATTR_ALL_UNSET: 1045 break; 1046 case ATTR_MIXED: 1047 StartBit = BitIndex; 1048 RA = ATTR_MIXED; 1049 break; 1050 default: 1051 assert(0 && "Unexpected bitAttr!"); 1052 } 1053 break; 1054 case ATTR_ALL_SET: 1055 switch (bitAttr) { 1056 case ATTR_FILTERED: 1057 reportRegion(RA, StartBit, BitIndex, AllowMixed); 1058 RA = ATTR_NONE; 1059 break; 1060 case ATTR_ALL_SET: 1061 break; 1062 case ATTR_ALL_UNSET: 1063 reportRegion(RA, StartBit, BitIndex, AllowMixed); 1064 RA = ATTR_NONE; 1065 break; 1066 case ATTR_MIXED: 1067 reportRegion(RA, StartBit, BitIndex, AllowMixed); 1068 StartBit = BitIndex; 1069 RA = ATTR_MIXED; 1070 break; 1071 default: 1072 assert(0 && "Unexpected bitAttr!"); 1073 } 1074 break; 1075 case ATTR_MIXED: 1076 switch (bitAttr) { 1077 case ATTR_FILTERED: 1078 reportRegion(RA, StartBit, BitIndex, AllowMixed); 1079 StartBit = BitIndex; 1080 RA = ATTR_NONE; 1081 break; 1082 case ATTR_ALL_SET: 1083 reportRegion(RA, StartBit, BitIndex, AllowMixed); 1084 StartBit = BitIndex; 1085 RA = ATTR_ALL_SET; 1086 break; 1087 case ATTR_ALL_UNSET: 1088 reportRegion(RA, StartBit, BitIndex, AllowMixed); 1089 RA = ATTR_NONE; 1090 break; 1091 case ATTR_MIXED: 1092 break; 1093 default: 1094 assert(0 && "Unexpected bitAttr!"); 1095 } 1096 break; 1097 case ATTR_ALL_UNSET: 1098 assert(0 && "regionAttr state machine has no ATTR_UNSET state"); 1099 case ATTR_FILTERED: 1100 assert(0 && "regionAttr state machine has no ATTR_FILTERED state"); 1101 } 1102 } 1103 1104 // At the end, if we're still in ALL_SET or MIXED states, report a region 1105 switch (RA) { 1106 case ATTR_NONE: 1107 break; 1108 case ATTR_FILTERED: 1109 break; 1110 case ATTR_ALL_SET: 1111 reportRegion(RA, StartBit, BitIndex, AllowMixed); 1112 break; 1113 case ATTR_ALL_UNSET: 1114 break; 1115 case ATTR_MIXED: 1116 reportRegion(RA, StartBit, BitIndex, AllowMixed); 1117 break; 1118 } 1119 1120 // We have finished with the filter processings. Now it's time to choose 1121 // the best performing filter. 1122 BestIndex = 0; 1123 bool AllUseless = true; 1124 unsigned BestScore = 0; 1125 1126 for (unsigned i = 0, e = Filters.size(); i != e; ++i) { 1127 unsigned Usefulness = Filters[i].usefulness(); 1128 1129 if (Usefulness) 1130 AllUseless = false; 1131 1132 if (Usefulness > BestScore) { 1133 BestIndex = i; 1134 BestScore = Usefulness; 1135 } 1136 } 1137 1138 if (!AllUseless) 1139 bestFilter().recurse(); 1140 1141 return !AllUseless; 1142 } // end of FilterChooser::filterProcessor(bool) 1143 1144 // Decides on the best configuration of filter(s) to use in order to decode 1145 // the instructions. A conflict of instructions may occur, in which case we 1146 // dump the conflict set to the standard error. 1147 void FilterChooser::doFilter() { 1148 unsigned Num = Opcodes.size(); 1149 assert(Num && "FilterChooser created with no instructions"); 1150 1151 // Try regions of consecutive known bit values first. 1152 if (filterProcessor(false)) 1153 return; 1154 1155 // Then regions of mixed bits (both known and unitialized bit values allowed). 1156 if (filterProcessor(true)) 1157 return; 1158 1159 // Heuristics to cope with conflict set {t2CMPrs, t2SUBSrr, t2SUBSrs} where 1160 // no single instruction for the maximum ATTR_MIXED region Inst{14-4} has a 1161 // well-known encoding pattern. In such case, we backtrack and scan for the 1162 // the very first consecutive ATTR_ALL_SET region and assign a filter to it. 1163 if (Num == 3 && filterProcessor(true, false)) 1164 return; 1165 1166 // If we come to here, the instruction decoding has failed. 1167 // Set the BestIndex to -1 to indicate so. 1168 BestIndex = -1; 1169 } 1170 1171 // Emits code to decode our share of instructions. Returns true if the 1172 // emitted code causes a return, which occurs if we know how to decode 1173 // the instruction at this level or the instruction is not decodeable. 1174 bool FilterChooser::emit(raw_ostream &o, unsigned &Indentation) { 1175 if (Opcodes.size() == 1) 1176 // There is only one instruction in the set, which is great! 1177 // Call emitSingletonDecoder() to see whether there are any remaining 1178 // encodings bits. 1179 return emitSingletonDecoder(o, Indentation, Opcodes[0]); 1180 1181 // Choose the best filter to do the decodings! 1182 if (BestIndex != -1) { 1183 Filter &Best = bestFilter(); 1184 if (Best.getNumFiltered() == 1) 1185 emitSingletonDecoder(o, Indentation, Best); 1186 else 1187 bestFilter().emit(o, Indentation); 1188 return false; 1189 } 1190 1191 // We don't know how to decode these instructions! Return 0 and dump the 1192 // conflict set! 1193 o.indent(Indentation) << "return 0;" << " // Conflict set: "; 1194 for (int i = 0, N = Opcodes.size(); i < N; ++i) { 1195 o << nameWithID(Opcodes[i]); 1196 if (i < (N - 1)) 1197 o << ", "; 1198 else 1199 o << '\n'; 1200 } 1201 1202 // Print out useful conflict information for postmortem analysis. 1203 errs() << "Decoding Conflict:\n"; 1204 1205 dumpStack(errs(), "\t\t"); 1206 1207 for (unsigned i = 0; i < Opcodes.size(); i++) { 1208 const std::string &Name = nameWithID(Opcodes[i]); 1209 1210 errs() << '\t' << Name << " "; 1211 dumpBits(errs(), 1212 getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst")); 1213 errs() << '\n'; 1214 } 1215 1216 return true; 1217 } 1218 1219 bool FixedLenDecoderEmitter::populateInstruction(const CodeGenInstruction &CGI, 1220 unsigned Opc){ 1221 const Record &Def = *CGI.TheDef; 1222 // If all the bit positions are not specified; do not decode this instruction. 1223 // We are bound to fail! For proper disassembly, the well-known encoding bits 1224 // of the instruction must be fully specified. 1225 // 1226 // This also removes pseudo instructions from considerations of disassembly, 1227 // which is a better design and less fragile than the name matchings. 1228 // Ignore "asm parser only" instructions. 1229 if (Def.getValueAsBit("isAsmParserOnly") || 1230 Def.getValueAsBit("isCodeGenOnly")) 1231 return false; 1232 1233 BitsInit &Bits = getBitsField(Def, "Inst"); 1234 if (Bits.allInComplete()) return false; 1235 1236 std::vector<OperandInfo> InsnOperands; 1237 1238 // If the instruction has specified a custom decoding hook, use that instead 1239 // of trying to auto-generate the decoder. 1240 std::string InstDecoder = Def.getValueAsString("DecoderMethod"); 1241 if (InstDecoder != "") { 1242 InsnOperands.push_back(OperandInfo(~0U, ~0U, InstDecoder)); 1243 Operands[Opc] = InsnOperands; 1244 return true; 1245 } 1246 1247 // Generate a description of the operand of the instruction that we know 1248 // how to decode automatically. 1249 // FIXME: We'll need to have a way to manually override this as needed. 1250 1251 // Gather the outputs/inputs of the instruction, so we can find their 1252 // positions in the encoding. This assumes for now that they appear in the 1253 // MCInst in the order that they're listed. 1254 std::vector<std::pair<Init*, std::string> > InOutOperands; 1255 DagInit *Out = Def.getValueAsDag("OutOperandList"); 1256 DagInit *In = Def.getValueAsDag("InOperandList"); 1257 for (unsigned i = 0; i < Out->getNumArgs(); ++i) 1258 InOutOperands.push_back(std::make_pair(Out->getArg(i), Out->getArgName(i))); 1259 for (unsigned i = 0; i < In->getNumArgs(); ++i) 1260 InOutOperands.push_back(std::make_pair(In->getArg(i), In->getArgName(i))); 1261 1262 // For each operand, see if we can figure out where it is encoded. 1263 for (std::vector<std::pair<Init*, std::string> >::iterator 1264 NI = InOutOperands.begin(), NE = InOutOperands.end(); NI != NE; ++NI) { 1265 unsigned PrevBit = ~0; 1266 unsigned Base = ~0; 1267 unsigned PrevPos = ~0; 1268 std::string Decoder = ""; 1269 1270 for (unsigned bi = 0; bi < Bits.getNumBits(); ++bi) { 1271 VarBitInit *BI = dynamic_cast<VarBitInit*>(Bits.getBit(bi)); 1272 if (!BI) continue; 1273 1274 VarInit *Var = dynamic_cast<VarInit*>(BI->getVariable()); 1275 assert(Var); 1276 unsigned CurrBit = BI->getBitNum(); 1277 if (Var->getName() != NI->second) continue; 1278 1279 // Figure out the lowest bit of the value, and the width of the field. 1280 // Deliberately don't try to handle cases where the field is scattered, 1281 // or where not all bits of the the field are explicit. 1282 if (Base == ~0U && PrevBit == ~0U && PrevPos == ~0U) { 1283 if (CurrBit == 0) 1284 Base = bi; 1285 else 1286 continue; 1287 } 1288 1289 if ((PrevPos != ~0U && bi-1 != PrevPos) || 1290 (CurrBit != ~0U && CurrBit-1 != PrevBit)) { 1291 PrevBit = ~0; 1292 Base = ~0; 1293 PrevPos = ~0; 1294 } 1295 1296 PrevPos = bi; 1297 PrevBit = CurrBit; 1298 1299 // At this point, we can locate the field, but we need to know how to 1300 // interpret it. As a first step, require the target to provide callbacks 1301 // for decoding register classes. 1302 // FIXME: This need to be extended to handle instructions with custom 1303 // decoder methods, and operands with (simple) MIOperandInfo's. 1304 TypedInit *TI = dynamic_cast<TypedInit*>(NI->first); 1305 RecordRecTy *Type = dynamic_cast<RecordRecTy*>(TI->getType()); 1306 Record *TypeRecord = Type->getRecord(); 1307 bool isReg = false; 1308 if (TypeRecord->isSubClassOf("RegisterOperand")) 1309 TypeRecord = TypeRecord->getValueAsDef("RegClass"); 1310 if (TypeRecord->isSubClassOf("RegisterClass")) { 1311 Decoder = "Decode" + TypeRecord->getName() + "RegisterClass"; 1312 isReg = true; 1313 } 1314 1315 RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod"); 1316 StringInit *String = DecoderString ? 1317 dynamic_cast<StringInit*>(DecoderString->getValue()) : 1318 0; 1319 if (!isReg && String && String->getValue() != "") 1320 Decoder = String->getValue(); 1321 } 1322 1323 if (Base != ~0U) { 1324 InsnOperands.push_back(OperandInfo(Base, PrevBit+1, Decoder)); 1325 DEBUG(errs() << "ENCODED OPERAND: $" << NI->second << " @ (" 1326 << utostr(Base+PrevBit) << ", " << utostr(Base) << ")\n"); 1327 } 1328 } 1329 1330 Operands[Opc] = InsnOperands; 1331 1332 1333 #if 0 1334 DEBUG({ 1335 // Dumps the instruction encoding bits. 1336 dumpBits(errs(), Bits); 1337 1338 errs() << '\n'; 1339 1340 // Dumps the list of operand info. 1341 for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) { 1342 const CGIOperandList::OperandInfo &Info = CGI.Operands[i]; 1343 const std::string &OperandName = Info.Name; 1344 const Record &OperandDef = *Info.Rec; 1345 1346 errs() << "\t" << OperandName << " (" << OperandDef.getName() << ")\n"; 1347 } 1348 }); 1349 #endif 1350 1351 return true; 1352 } 1353 1354 void FixedLenDecoderEmitter::populateInstructions() { 1355 for (unsigned i = 0, e = NumberedInstructions.size(); i < e; ++i) { 1356 Record *R = NumberedInstructions[i]->TheDef; 1357 if (R->getValueAsString("Namespace") == "TargetOpcode" || 1358 R->getValueAsBit("isPseudo")) 1359 continue; 1360 1361 if (populateInstruction(*NumberedInstructions[i], i)) 1362 Opcodes.push_back(i); 1363 } 1364 } 1365 1366 // Emits disassembler code for instruction decoding. 1367 void FixedLenDecoderEmitter::run(raw_ostream &o) 1368 { 1369 o << "#include \"llvm/MC/MCInst.h\"\n"; 1370 o << "#include \"llvm/Support/DataTypes.h\"\n"; 1371 o << "#include <assert.h>\n"; 1372 o << '\n'; 1373 o << "namespace llvm {\n\n"; 1374 1375 NumberedInstructions = Target.getInstructionsByEnumValue(); 1376 populateInstructions(); 1377 FilterChooser FC(NumberedInstructions, Opcodes, Operands); 1378 FC.emitTop(o, 0); 1379 1380 o << "\n} // End llvm namespace \n"; 1381 } 1382