FixedLenDecoderEmitter.cpp revision d4a9066c93da9a5aab47ca228d82e796fdec70c0
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 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} 51static 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; 54 55 // The bit is uninitialized. 56 return BIT_UNSET; 57} 58// Prints the bit value for each position. 59static void dumpBits(raw_ostream &o, const 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 79static const BitsInit &getBitsField(const Record &def, const char *str) { 80 const BitsInit *bits = def.getValueAsBitsInit(str); 81 return *bits; 82} 83 84// Forward declaration. 85class FilterChooser; 86 87// FIXME: Possibly auto-detected? 88#define BIT_WIDTH 32 89 90// Representation of the instruction to work on. 91typedef 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. 129class Filter { 130protected: 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 154public: 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. 192typedef 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. 215class FilterChooser { 216protected: 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 241public: 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 279protected: 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"); 284 285 for (unsigned i = 0; i < BIT_WIDTH; ++i) 286 Insn[i] = bitFromBits(Bits, i); 287 } 288 289 // Returns the record name. 290 const std::string &nameWithID(unsigned Opcode) const { 291 return AllInstructions[Opcode]->TheDef->getName(); 292 } 293 294 // Populates the field of the insn given the start position and the number of 295 // consecutive bits to scan for. 296 // 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; 301 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]); 305 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); 309 310 Filter &bestFilter() { 311 assert(BestIndex != -1 && "BestIndex not set"); 312 return Filters[BestIndex]; 313 } 314 315 // Called from Filter::recurse() when singleton exists. For debug purpose. 316 void SingletonExists(unsigned Opc); 317 318 bool PositionFiltered(unsigned i) { 319 return ValueSet(FilterBitValues[i]); 320 } 321 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, 328 insn_t &Insn); 329 330 // Emits code to decode the singleton. Return true if we have matched all the 331 // well-known bits. 332 bool emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,unsigned Opc); 333 334 // Emits code to decode the singleton, and then to decode the rest. 335 void emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,Filter &Best); 336 337 // Assign a single filter and run with it. 338 void runSingleFilter(FilterChooser &owner, unsigned startBit, unsigned numBit, 339 bool mixed); 340 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, 344 bool AllowMixed); 345 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); 350 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. 354 void doFilter(); 355 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); 360}; 361 362/////////////////////////// 363// // 364// Filter Implmenetation // 365// // 366/////////////////////////// 367 368Filter::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) { 374} 375 376Filter::Filter(FilterChooser &owner, unsigned startBit, unsigned numBits, 377 bool mixed) : Owner(&owner), StartBit(startBit), NumBits(numBits), 378 Mixed(mixed) { 379 assert(StartBit + NumBits - 1 < BIT_WIDTH); 380 381 NumFiltered = 0; 382 LastOpcFiltered = 0; 383 NumVariable = 0; 384 385 for (unsigned i = 0, e = Owner->Opcodes.size(); i != e; ++i) { 386 insn_t Insn; 387 388 // Populates the insn given the uid. 389 Owner->insnWithID(Insn, Owner->Opcodes[i]); 390 391 uint64_t Field; 392 // Scans the segment for possibly well-specified encoding bits. 393 bool ok = Owner->fieldFromInsn(Field, Insn, StartBit, NumBits); 394 395 if (ok) { 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); 400 ++NumFiltered; 401 } else { 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]); 405 ++NumVariable; 406 } 407 } 408 409 assert((FilteredInstructions.size() + VariableInstructions.size() > 0) 410 && "Filter returns no instruction categories"); 411} 412 413Filter::~Filter() { 414 std::map<unsigned, FilterChooser*>::iterator filterIterator; 415 for (filterIterator = FilterChooserMap.begin(); 416 filterIterator != FilterChooserMap.end(); 417 filterIterator++) { 418 delete filterIterator->second; 419 } 420} 421 422// Divides the decoding task into sub tasks and delegates them to the 423// inferior FilterChooser's. 424// 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. 428void Filter::recurse() { 429 std::map<uint64_t, std::vector<unsigned> >::const_iterator mapIterator; 430 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)); 434 435 unsigned bitIndex; 436 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; 441 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*>( 445 (unsigned)-1, 446 new FilterChooser(Owner->AllInstructions, 447 VariableInstructions, 448 Owner->Operands, 449 BitValueArray, 450 *Owner) 451 )); 452 } 453 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); 459 return; 460 } 461 462 // Otherwise, create sub choosers. 463 for (mapIterator = FilteredInstructions.begin(); 464 mapIterator != FilteredInstructions.end(); 465 mapIterator++) { 466 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; 471 else 472 BitValueArray[StartBit + bitIndex] = BIT_FALSE; 473 } 474 475 // Delegates to an inferior filter chooser for further processing on this 476 // category of instructions. 477 FilterChooserMap.insert(std::pair<unsigned, FilterChooser*>( 478 mapIterator->first, 479 new FilterChooser(Owner->AllInstructions, 480 mapIterator->second, 481 Owner->Operands, 482 BitValueArray, 483 *Owner) 484 )); 485 } 486} 487 488// Emit code to decode instructions given a segment or segments of bits. 489void Filter::emit(raw_ostream &o, unsigned &Indentation) { 490 o.indent(Indentation) << "// Check Inst{"; 491 492 if (NumBits > 1) 493 o << (StartBit + NumBits - 1) << '-'; 494 495 o << StartBit << "} ...\n"; 496 497 o.indent(Indentation) << "switch (fieldFromInstruction(insn, " 498 << StartBit << ", " << NumBits << ")) {\n"; 499 500 std::map<unsigned, FilterChooser*>::iterator filterIterator; 501 502 bool DefaultCase = false; 503 for (filterIterator = FilterChooserMap.begin(); 504 filterIterator != FilterChooserMap.end(); 505 filterIterator++) { 506 507 // Field value -1 implies a non-empty set of variable instructions. 508 // See also recurse(). 509 if (filterIterator->first == (unsigned)-1) { 510 DefaultCase = true; 511 512 o.indent(Indentation) << "default:\n"; 513 o.indent(Indentation) << " break; // fallthrough\n"; 514 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"; 520 521 } else 522 o.indent(Indentation) << "case " << filterIterator->first << ":\n"; 523 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; } 529 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) 533 break; 534 if (!finished) 535 o.indent(Indentation) << "break;\n"; 536 537 if (!DefaultCase) { --Indentation; --Indentation; } 538 } 539 540 // If there is no default case, we still need to supply a closing brace. 541 if (!DefaultCase) { 542 // Closing curly brace for the switch statement. 543 o.indent(Indentation) << "}\n"; 544 } 545} 546 547// Returns the number of fanout produced by the filter. More fanout implies 548// the filter distinguishes more categories of instructions. 549unsigned Filter::usefulness() const { 550 if (VariableInstructions.size()) 551 return FilteredInstructions.size(); 552 else 553 return FilteredInstructions.size() + 1; 554} 555 556////////////////////////////////// 557// // 558// Filterchooser Implementation // 559// // 560////////////////////////////////// 561 562// Emit the top level typedef and decodeInstruction() function. 563void FilterChooser::emitTop(raw_ostream &o, unsigned Indentation) { 564 switch (BIT_WIDTH) { 565 case 8: 566 o.indent(Indentation) << "typedef uint8_t field_t;\n"; 567 break; 568 case 16: 569 o.indent(Indentation) << "typedef uint16_t field_t;\n"; 570 break; 571 case 32: 572 o.indent(Indentation) << "typedef uint32_t field_t;\n"; 573 break; 574 case 64: 575 o.indent(Indentation) << "typedef uint64_t field_t;\n"; 576 break; 577 default: 578 assert(0 && "Unexpected instruction size!"); 579 } 580 581 o << '\n'; 582 583 o.indent(Indentation) << "static field_t " << 584 "fieldFromInstruction(field_t insn, unsigned startBit, unsigned numBits)\n"; 585 586 o.indent(Indentation) << "{\n"; 587 588 ++Indentation; ++Indentation; 589 o.indent(Indentation) << "assert(startBit + numBits <= " << BIT_WIDTH 590 << " && \"Instruction field out of bounds!\");\n"; 591 o << '\n'; 592 o.indent(Indentation) << "field_t fieldMask;\n"; 593 o << '\n'; 594 o.indent(Indentation) << "if (numBits == " << BIT_WIDTH << ")\n"; 595 596 ++Indentation; ++Indentation; 597 o.indent(Indentation) << "fieldMask = (field_t)-1;\n"; 598 --Indentation; --Indentation; 599 600 o.indent(Indentation) << "else\n"; 601 602 ++Indentation; ++Indentation; 603 o.indent(Indentation) << "fieldMask = ((1 << numBits) - 1) << startBit;\n"; 604 --Indentation; --Indentation; 605 606 o << '\n'; 607 o.indent(Indentation) << "return (insn & fieldMask) >> startBit;\n"; 608 --Indentation; --Indentation; 609 610 o.indent(Indentation) << "}\n"; 611 612 o << '\n'; 613 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"; 618 619 ++Indentation; ++Indentation; 620 // Emits code to decode the instructions. 621 emit(o, Indentation); 622 623 o << '\n'; 624 o.indent(Indentation) << "return false;\n"; 625 --Indentation; --Indentation; 626 627 o.indent(Indentation) << "}\n"; 628 629 o << '\n'; 630} 631 632// Populates the field of the insn given the start position and the number of 633// consecutive bits to scan for. 634// 635// Returns false if and on the first uninitialized bit value encountered. 636// Returns true, otherwise. 637bool FilterChooser::fieldFromInsn(uint64_t &Field, insn_t &Insn, 638 unsigned StartBit, unsigned NumBits) const { 639 Field = 0; 640 641 for (unsigned i = 0; i < NumBits; ++i) { 642 if (Insn[StartBit + i] == BIT_UNSET) 643 return false; 644 645 if (Insn[StartBit + i] == BIT_TRUE) 646 Field = Field | (1ULL << i); 647 } 648 649 return true; 650} 651 652/// dumpFilterArray - dumpFilterArray prints out debugging info for the given 653/// filter array as a series of chars. 654void FilterChooser::dumpFilterArray(raw_ostream &o, 655 bit_value_t (&filter)[BIT_WIDTH]) { 656 unsigned bitIndex; 657 658 for (bitIndex = BIT_WIDTH; bitIndex > 0; bitIndex--) { 659 switch (filter[bitIndex - 1]) { 660 case BIT_UNFILTERED: 661 o << "."; 662 break; 663 case BIT_UNSET: 664 o << "_"; 665 break; 666 case BIT_TRUE: 667 o << "1"; 668 break; 669 case BIT_FALSE: 670 o << "0"; 671 break; 672 } 673 } 674} 675 676/// dumpStack - dumpStack traverses the filter chooser chain and calls 677/// dumpFilterArray on each filter chooser up to the top level one. 678void FilterChooser::dumpStack(raw_ostream &o, const char *prefix) { 679 FilterChooser *current = this; 680 681 while (current) { 682 o << prefix; 683 dumpFilterArray(o, current->FilterBitValues); 684 o << '\n'; 685 current = current->Parent; 686 } 687} 688 689// Called from Filter::recurse() when singleton exists. For debug purpose. 690void FilterChooser::SingletonExists(unsigned Opc) { 691 insn_t Insn0; 692 insnWithID(Insn0, Opc); 693 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]) << ' '; 699 } 700 errs() << '\n'; 701 702 dumpStack(errs(), "\t\t"); 703 for (unsigned i = 0; i < Opcodes.size(); i++) { 704 const std::string &Name = nameWithID(Opcodes[i]); 705 706 errs() << '\t' << Name << " "; 707 dumpBits(errs(), 708 getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst")); 709 errs() << '\n'; 710 } 711} 712 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. 717unsigned FilterChooser::getIslands(std::vector<unsigned> &StartBits, 718 std::vector<unsigned> &EndBits, std::vector<uint64_t> &FieldVals, 719 insn_t &Insn) { 720 unsigned Num, BitNo; 721 Num = BitNo = 0; 722 723 uint64_t FieldVal = 0; 724 725 // 0: Init 726 // 1: Water (the bit value does not affect decoding) 727 // 2: Island (well-known bit value needed for decoding) 728 int State = 0; 729 int Val = -1; 730 731 for (unsigned i = 0; i < BIT_WIDTH; ++i) { 732 Val = Value(Insn[i]); 733 bool Filtered = PositionFiltered(i); 734 switch (State) { 735 default: 736 assert(0 && "Unreachable code!"); 737 break; 738 case 0: 739 case 1: 740 if (Filtered || Val == -1) 741 State = 1; // Still in Water 742 else { 743 State = 2; // Into the Island 744 BitNo = 0; 745 StartBits.push_back(i); 746 FieldVal = Val; 747 } 748 break; 749 case 2: 750 if (Filtered || Val == -1) { 751 State = 1; // Into the Water 752 EndBits.push_back(i - 1); 753 FieldVals.push_back(FieldVal); 754 ++Num; 755 } else { 756 State = 2; // Still in Island 757 ++BitNo; 758 FieldVal = FieldVal | Val << BitNo; 759 } 760 break; 761 } 762 } 763 // If we are still in Island after the loop, do some housekeeping. 764 if (State == 2) { 765 EndBits.push_back(BIT_WIDTH - 1); 766 FieldVals.push_back(FieldVal); 767 ++Num; 768 } 769 770 assert(StartBits.size() == Num && EndBits.size() == Num && 771 FieldVals.size() == Num); 772 return Num; 773} 774 775// Emits code to decode the singleton. Return true if we have matched all the 776// well-known bits. 777bool FilterChooser::emitSingletonDecoder(raw_ostream &o, unsigned &Indentation, 778 unsigned Opc) { 779 std::vector<unsigned> StartBits; 780 std::vector<unsigned> EndBits; 781 std::vector<uint64_t> FieldVals; 782 insn_t Insn; 783 insnWithID(Insn, Opc); 784 785 // Look for islands of undecoded bits of the singleton. 786 getIslands(StartBits, EndBits, FieldVals, Insn); 787 788 unsigned Size = StartBits.size(); 789 unsigned I, NumBits; 790 791 // If we have matched all the well-known bits, just issue a return. 792 if (Size == 0) { 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"; 802 break; 803 } 804 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"; 811 } else { 812 o.indent(Indentation) 813 << " MI.addOperand(MCOperand::CreateImm(tmp));\n"; 814 } 815 } 816 817 o.indent(Indentation) << " return true; // " << nameWithID(Opc) 818 << '\n'; 819 o.indent(Indentation) << "}\n"; 820 return true; 821 } 822 823 // Otherwise, there are more decodings to be done! 824 825 // Emit code to match the island(s) for the singleton. 826 o.indent(Indentation) << "// Check "; 827 828 for (I = Size; I != 0; --I) { 829 o << "Inst{" << EndBits[I-1] << '-' << StartBits[I-1] << "} "; 830 if (I > 1) 831 o << "&& "; 832 else 833 o << "for singleton decoding...\n"; 834 } 835 836 o.indent(Indentation) << "if ("; 837 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]; 842 if (I > 1) 843 o << " && "; 844 else 845 o << ") {\n"; 846 } 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"; 855 break; 856 } 857 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"; 864 } else { 865 o.indent(Indentation) 866 << " MI.addOperand(MCOperand::CreateImm(tmp));\n"; 867 } 868 } 869 o.indent(Indentation) << " return true; // " << nameWithID(Opc) 870 << '\n'; 871 o.indent(Indentation) << "}\n"; 872 873 return false; 874} 875 876// Emits code to decode the singleton, and then to decode the rest. 877void FilterChooser::emitSingletonDecoder(raw_ostream &o, unsigned &Indentation, 878 Filter &Best) { 879 880 unsigned Opc = Best.getSingletonOpc(); 881 882 emitSingletonDecoder(o, Indentation, Opc); 883 884 // Emit code for the rest. 885 o.indent(Indentation) << "else\n"; 886 887 Indentation += 2; 888 Best.getVariableFC().emit(o, Indentation); 889 Indentation -= 2; 890} 891 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. 894void FilterChooser::runSingleFilter(FilterChooser &owner, unsigned startBit, 895 unsigned numBit, bool mixed) { 896 Filters.clear(); 897 Filter F(*this, startBit, numBit, true); 898 Filters.push_back(F); 899 BestIndex = 0; // Sole Filter instance to choose from. 900 bestFilter().recurse(); 901} 902 903// reportRegion is a helper function for filterProcessor to mark a region as 904// eligible for use as a filter region. 905void 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)); 911} 912 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. 916bool FilterChooser::filterProcessor(bool AllowMixed, bool Greedy) { 917 Filters.clear(); 918 BestIndex = -1; 919 unsigned numInstructions = Opcodes.size(); 920 921 assert(numInstructions && "Filter created with no instructions"); 922 923 // No further filtering is necessary. 924 if (numInstructions == 1) 925 return true; 926 927 // Heuristics. See also doFilter()'s "Heuristics" comment when num of 928 // instructions is 3. 929 if (AllowMixed && !Greedy) { 930 assert(numInstructions == 3); 931 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; 936 insn_t Insn; 937 938 insnWithID(Insn, Opcodes[i]); 939 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, 944 true); 945 return true; 946 } 947 } 948 } 949 950 unsigned BitIndex, InsnIndex; 951 952 // We maintain BIT_WIDTH copies of the bitAttrs automaton. 953 // The automaton consumes the corresponding bit from each 954 // instruction. 955 // 956 // Input symbols: 0, 1, and _ (unset). 957 // States: NONE, FILTERED, ALL_SET, ALL_UNSET, and MIXED. 958 // Initial state: NONE. 959 // 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) 968 969 bitAttr_t bitAttrs[BIT_WIDTH]; 970 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; 977 else 978 bitAttrs[BitIndex] = ATTR_NONE; 979 980 for (InsnIndex = 0; InsnIndex < numInstructions; ++InsnIndex) { 981 insn_t insn; 982 983 insnWithID(insn, Opcodes[InsnIndex]); 984 985 for (BitIndex = 0; BitIndex < BIT_WIDTH; ++BitIndex) { 986 switch (bitAttrs[BitIndex]) { 987 case ATTR_NONE: 988 if (insn[BitIndex] == BIT_UNSET) 989 bitAttrs[BitIndex] = ATTR_ALL_UNSET; 990 else 991 bitAttrs[BitIndex] = ATTR_ALL_SET; 992 break; 993 case ATTR_ALL_SET: 994 if (insn[BitIndex] == BIT_UNSET) 995 bitAttrs[BitIndex] = ATTR_MIXED; 996 break; 997 case ATTR_ALL_UNSET: 998 if (insn[BitIndex] != BIT_UNSET) 999 bitAttrs[BitIndex] = ATTR_MIXED; 1000 break; 1001 case ATTR_MIXED: 1002 case ATTR_FILTERED: 1003 break; 1004 } 1005 } 1006 } 1007 1008 // The regionAttr automaton consumes the bitAttrs automatons' state, 1009 // lowest-to-highest. 1010 // 1011 // Input symbols: F(iltered), (all_)S(et), (all_)U(nset), M(ixed) 1012 // States: NONE, ALL_SET, MIXED 1013 // Initial state: NONE 1014 // 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) 1027 1028 bitAttr_t RA = ATTR_NONE; 1029 unsigned StartBit = 0; 1030 1031 for (BitIndex = 0; BitIndex < BIT_WIDTH; BitIndex++) { 1032 bitAttr_t bitAttr = bitAttrs[BitIndex]; 1033 1034 assert(bitAttr != ATTR_NONE && "Bit without attributes"); 1035 1036 switch (RA) { 1037 case ATTR_NONE: 1038 switch (bitAttr) { 1039 case ATTR_FILTERED: 1040 break; 1041 case ATTR_ALL_SET: 1042 StartBit = BitIndex; 1043 RA = ATTR_ALL_SET; 1044 break; 1045 case ATTR_ALL_UNSET: 1046 break; 1047 case ATTR_MIXED: 1048 StartBit = BitIndex; 1049 RA = ATTR_MIXED; 1050 break; 1051 default: 1052 assert(0 && "Unexpected bitAttr!"); 1053 } 1054 break; 1055 case ATTR_ALL_SET: 1056 switch (bitAttr) { 1057 case ATTR_FILTERED: 1058 reportRegion(RA, StartBit, BitIndex, AllowMixed); 1059 RA = ATTR_NONE; 1060 break; 1061 case ATTR_ALL_SET: 1062 break; 1063 case ATTR_ALL_UNSET: 1064 reportRegion(RA, StartBit, BitIndex, AllowMixed); 1065 RA = ATTR_NONE; 1066 break; 1067 case ATTR_MIXED: 1068 reportRegion(RA, StartBit, BitIndex, AllowMixed); 1069 StartBit = BitIndex; 1070 RA = ATTR_MIXED; 1071 break; 1072 default: 1073 assert(0 && "Unexpected bitAttr!"); 1074 } 1075 break; 1076 case ATTR_MIXED: 1077 switch (bitAttr) { 1078 case ATTR_FILTERED: 1079 reportRegion(RA, StartBit, BitIndex, AllowMixed); 1080 StartBit = BitIndex; 1081 RA = ATTR_NONE; 1082 break; 1083 case ATTR_ALL_SET: 1084 reportRegion(RA, StartBit, BitIndex, AllowMixed); 1085 StartBit = BitIndex; 1086 RA = ATTR_ALL_SET; 1087 break; 1088 case ATTR_ALL_UNSET: 1089 reportRegion(RA, StartBit, BitIndex, AllowMixed); 1090 RA = ATTR_NONE; 1091 break; 1092 case ATTR_MIXED: 1093 break; 1094 default: 1095 assert(0 && "Unexpected bitAttr!"); 1096 } 1097 break; 1098 case ATTR_ALL_UNSET: 1099 assert(0 && "regionAttr state machine has no ATTR_UNSET state"); 1100 case ATTR_FILTERED: 1101 assert(0 && "regionAttr state machine has no ATTR_FILTERED state"); 1102 } 1103 } 1104 1105 // At the end, if we're still in ALL_SET or MIXED states, report a region 1106 switch (RA) { 1107 case ATTR_NONE: 1108 break; 1109 case ATTR_FILTERED: 1110 break; 1111 case ATTR_ALL_SET: 1112 reportRegion(RA, StartBit, BitIndex, AllowMixed); 1113 break; 1114 case ATTR_ALL_UNSET: 1115 break; 1116 case ATTR_MIXED: 1117 reportRegion(RA, StartBit, BitIndex, AllowMixed); 1118 break; 1119 } 1120 1121 // We have finished with the filter processings. Now it's time to choose 1122 // the best performing filter. 1123 BestIndex = 0; 1124 bool AllUseless = true; 1125 unsigned BestScore = 0; 1126 1127 for (unsigned i = 0, e = Filters.size(); i != e; ++i) { 1128 unsigned Usefulness = Filters[i].usefulness(); 1129 1130 if (Usefulness) 1131 AllUseless = false; 1132 1133 if (Usefulness > BestScore) { 1134 BestIndex = i; 1135 BestScore = Usefulness; 1136 } 1137 } 1138 1139 if (!AllUseless) 1140 bestFilter().recurse(); 1141 1142 return !AllUseless; 1143} // end of FilterChooser::filterProcessor(bool) 1144 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. 1148void FilterChooser::doFilter() { 1149 unsigned Num = Opcodes.size(); 1150 assert(Num && "FilterChooser created with no instructions"); 1151 1152 // Try regions of consecutive known bit values first. 1153 if (filterProcessor(false)) 1154 return; 1155 1156 // Then regions of mixed bits (both known and unitialized bit values allowed). 1157 if (filterProcessor(true)) 1158 return; 1159 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)) 1165 return; 1166 1167 // If we come to here, the instruction decoding has failed. 1168 // Set the BestIndex to -1 to indicate so. 1169 BestIndex = -1; 1170} 1171 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. 1175bool 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 1179 // encodings bits. 1180 return emitSingletonDecoder(o, Indentation, Opcodes[0]); 1181 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); 1187 else 1188 bestFilter().emit(o, Indentation); 1189 return false; 1190 } 1191 1192 // We don't know how to decode these instructions! Return 0 and dump the 1193 // conflict set! 1194 o.indent(Indentation) << "return 0;" << " // Conflict set: "; 1195 for (int i = 0, N = Opcodes.size(); i < N; ++i) { 1196 o << nameWithID(Opcodes[i]); 1197 if (i < (N - 1)) 1198 o << ", "; 1199 else 1200 o << '\n'; 1201 } 1202 1203 // Print out useful conflict information for postmortem analysis. 1204 errs() << "Decoding Conflict:\n"; 1205 1206 dumpStack(errs(), "\t\t"); 1207 1208 for (unsigned i = 0; i < Opcodes.size(); i++) { 1209 const std::string &Name = nameWithID(Opcodes[i]); 1210 1211 errs() << '\t' << Name << " "; 1212 dumpBits(errs(), 1213 getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst")); 1214 errs() << '\n'; 1215 } 1216 1217 return true; 1218} 1219 1220bool FixedLenDecoderEmitter::populateInstruction(const CodeGenInstruction &CGI, 1221 unsigned Opc){ 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. 1226 // 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")) 1232 return false; 1233 1234 const BitsInit &Bits = getBitsField(Def, "Inst"); 1235 if (Bits.allInComplete()) return false; 1236 1237 std::vector<OperandInfo> InsnOperands; 1238 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; 1245 return true; 1246 } 1247 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. 1251 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))); 1262 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; 1267 unsigned Base = ~0; 1268 unsigned PrevPos = ~0; 1269 std::string Decoder = ""; 1270 1271 for (unsigned bi = 0; bi < Bits.getNumBits(); ++bi) { 1272 const VarBitInit *BI = dynamic_cast<const VarBitInit*>(Bits.getBit(bi)); 1273 if (!BI) continue; 1274 1275 const VarInit *Var = dynamic_cast<const VarInit*>(BI->getVariable()); 1276 assert(Var); 1277 unsigned CurrBit = BI->getBitNum(); 1278 if (Var->getName() != NI->second) continue; 1279 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) { 1284 if (CurrBit == 0) 1285 Base = bi; 1286 else 1287 continue; 1288 } 1289 1290 if ((PrevPos != ~0U && bi-1 != PrevPos) || 1291 (CurrBit != ~0U && CurrBit-1 != PrevBit)) { 1292 PrevBit = ~0; 1293 Base = ~0; 1294 PrevPos = ~0; 1295 } 1296 1297 PrevPos = bi; 1298 PrevBit = CurrBit; 1299 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(); 1308 bool isReg = false; 1309 if (TypeRecord->isSubClassOf("RegisterOperand")) 1310 TypeRecord = TypeRecord->getValueAsDef("RegClass"); 1311 if (TypeRecord->isSubClassOf("RegisterClass")) { 1312 Decoder = "Decode" + TypeRecord->getName() + "RegisterClass"; 1313 isReg = true; 1314 } 1315 1316 RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod"); 1317 const StringInit *String = DecoderString ? 1318 dynamic_cast<const StringInit*>(DecoderString->getValue()) : 1319 0; 1320 if (!isReg && String && String->getValue() != "") 1321 Decoder = String->getValue(); 1322 } 1323 1324 if (Base != ~0U) { 1325 InsnOperands.push_back(OperandInfo(Base, PrevBit+1, Decoder)); 1326 DEBUG(errs() << "ENCODED OPERAND: $" << NI->second << " @ (" 1327 << utostr(Base+PrevBit) << ", " << utostr(Base) << ")\n"); 1328 } 1329 } 1330 1331 Operands[Opc] = InsnOperands; 1332 1333 1334#if 0 1335 DEBUG({ 1336 // Dumps the instruction encoding bits. 1337 dumpBits(errs(), Bits); 1338 1339 errs() << '\n'; 1340 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; 1346 1347 errs() << "\t" << OperandName << " (" << OperandDef.getName() << ")\n"; 1348 } 1349 }); 1350#endif 1351 1352 return true; 1353} 1354 1355void 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")) 1360 continue; 1361 1362 if (populateInstruction(*NumberedInstructions[i], i)) 1363 Opcodes.push_back(i); 1364 } 1365} 1366 1367// Emits disassembler code for instruction decoding. 1368void FixedLenDecoderEmitter::run(raw_ostream &o) 1369{ 1370 o << "#include \"llvm/MC/MCInst.h\"\n"; 1371 o << "#include \"llvm/Support/DataTypes.h\"\n"; 1372 o << "#include <assert.h>\n"; 1373 o << '\n'; 1374 o << "namespace llvm {\n\n"; 1375 1376 NumberedInstructions = Target.getInstructionsByEnumValue(); 1377 populateInstructions(); 1378 FilterChooser FC(NumberedInstructions, Opcodes, Operands); 1379 FC.emitTop(o, 0); 1380 1381 o << "\n} // End llvm namespace \n"; 1382} 1383