1 //===- AsmMatcherEmitter.cpp - Generate an assembly matcher ---------------===// 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 // This tablegen backend emits a target specifier matcher for converting parsed 11 // assembly operands in the MCInst structures. It also emits a matcher for 12 // custom operand parsing. 13 // 14 // Converting assembly operands into MCInst structures 15 // --------------------------------------------------- 16 // 17 // The input to the target specific matcher is a list of literal tokens and 18 // operands. The target specific parser should generally eliminate any syntax 19 // which is not relevant for matching; for example, comma tokens should have 20 // already been consumed and eliminated by the parser. Most instructions will 21 // end up with a single literal token (the instruction name) and some number of 22 // operands. 23 // 24 // Some example inputs, for X86: 25 // 'addl' (immediate ...) (register ...) 26 // 'add' (immediate ...) (memory ...) 27 // 'call' '*' %epc 28 // 29 // The assembly matcher is responsible for converting this input into a precise 30 // machine instruction (i.e., an instruction with a well defined encoding). This 31 // mapping has several properties which complicate matching: 32 // 33 // - It may be ambiguous; many architectures can legally encode particular 34 // variants of an instruction in different ways (for example, using a smaller 35 // encoding for small immediates). Such ambiguities should never be 36 // arbitrarily resolved by the assembler, the assembler is always responsible 37 // for choosing the "best" available instruction. 38 // 39 // - It may depend on the subtarget or the assembler context. Instructions 40 // which are invalid for the current mode, but otherwise unambiguous (e.g., 41 // an SSE instruction in a file being assembled for i486) should be accepted 42 // and rejected by the assembler front end. However, if the proper encoding 43 // for an instruction is dependent on the assembler context then the matcher 44 // is responsible for selecting the correct machine instruction for the 45 // current mode. 46 // 47 // The core matching algorithm attempts to exploit the regularity in most 48 // instruction sets to quickly determine the set of possibly matching 49 // instructions, and the simplify the generated code. Additionally, this helps 50 // to ensure that the ambiguities are intentionally resolved by the user. 51 // 52 // The matching is divided into two distinct phases: 53 // 54 // 1. Classification: Each operand is mapped to the unique set which (a) 55 // contains it, and (b) is the largest such subset for which a single 56 // instruction could match all members. 57 // 58 // For register classes, we can generate these subgroups automatically. For 59 // arbitrary operands, we expect the user to define the classes and their 60 // relations to one another (for example, 8-bit signed immediates as a 61 // subset of 32-bit immediates). 62 // 63 // By partitioning the operands in this way, we guarantee that for any 64 // tuple of classes, any single instruction must match either all or none 65 // of the sets of operands which could classify to that tuple. 66 // 67 // In addition, the subset relation amongst classes induces a partial order 68 // on such tuples, which we use to resolve ambiguities. 69 // 70 // 2. The input can now be treated as a tuple of classes (static tokens are 71 // simple singleton sets). Each such tuple should generally map to a single 72 // instruction (we currently ignore cases where this isn't true, whee!!!), 73 // which we can emit a simple matcher for. 74 // 75 // Custom Operand Parsing 76 // ---------------------- 77 // 78 // Some targets need a custom way to parse operands, some specific instructions 79 // can contain arguments that can represent processor flags and other kinds of 80 // identifiers that need to be mapped to specific valeus in the final encoded 81 // instructions. The target specific custom operand parsing works in the 82 // following way: 83 // 84 // 1. A operand match table is built, each entry contains a mnemonic, an 85 // operand class, a mask for all operand positions for that same 86 // class/mnemonic and target features to be checked while trying to match. 87 // 88 // 2. The operand matcher will try every possible entry with the same 89 // mnemonic and will check if the target feature for this mnemonic also 90 // matches. After that, if the operand to be matched has its index 91 // present in the mask, a successful match occurs. Otherwise, fallback 92 // to the regular operand parsing. 93 // 94 // 3. For a match success, each operand class that has a 'ParserMethod' 95 // becomes part of a switch from where the custom method is called. 96 // 97 //===----------------------------------------------------------------------===// 98 99 #include "CodeGenTarget.h" 100 #include "StringToOffsetTable.h" 101 #include "llvm/ADT/OwningPtr.h" 102 #include "llvm/ADT/PointerUnion.h" 103 #include "llvm/ADT/SmallPtrSet.h" 104 #include "llvm/ADT/SmallVector.h" 105 #include "llvm/ADT/STLExtras.h" 106 #include "llvm/ADT/StringExtras.h" 107 #include "llvm/Support/CommandLine.h" 108 #include "llvm/Support/Debug.h" 109 #include "llvm/Support/ErrorHandling.h" 110 #include "llvm/TableGen/Error.h" 111 #include "llvm/TableGen/Record.h" 112 #include "llvm/TableGen/StringMatcher.h" 113 #include "llvm/TableGen/TableGenBackend.h" 114 #include <cassert> 115 #include <map> 116 #include <set> 117 using namespace llvm; 118 119 static cl::opt<std::string> 120 MatchPrefix("match-prefix", cl::init(""), 121 cl::desc("Only match instructions with the given prefix")); 122 123 namespace { 124 class AsmMatcherInfo; 125 struct SubtargetFeatureInfo; 126 127 class AsmMatcherEmitter { 128 RecordKeeper &Records; 129 public: 130 AsmMatcherEmitter(RecordKeeper &R) : Records(R) {} 131 132 void run(raw_ostream &o); 133 }; 134 135 /// ClassInfo - Helper class for storing the information about a particular 136 /// class of operands which can be matched. 137 struct ClassInfo { 138 enum ClassInfoKind { 139 /// Invalid kind, for use as a sentinel value. 140 Invalid = 0, 141 142 /// The class for a particular token. 143 Token, 144 145 /// The (first) register class, subsequent register classes are 146 /// RegisterClass0+1, and so on. 147 RegisterClass0, 148 149 /// The (first) user defined class, subsequent user defined classes are 150 /// UserClass0+1, and so on. 151 UserClass0 = 1<<16 152 }; 153 154 /// Kind - The class kind, which is either a predefined kind, or (UserClass0 + 155 /// N) for the Nth user defined class. 156 unsigned Kind; 157 158 /// SuperClasses - The super classes of this class. Note that for simplicities 159 /// sake user operands only record their immediate super class, while register 160 /// operands include all superclasses. 161 std::vector<ClassInfo*> SuperClasses; 162 163 /// Name - The full class name, suitable for use in an enum. 164 std::string Name; 165 166 /// ClassName - The unadorned generic name for this class (e.g., Token). 167 std::string ClassName; 168 169 /// ValueName - The name of the value this class represents; for a token this 170 /// is the literal token string, for an operand it is the TableGen class (or 171 /// empty if this is a derived class). 172 std::string ValueName; 173 174 /// PredicateMethod - The name of the operand method to test whether the 175 /// operand matches this class; this is not valid for Token or register kinds. 176 std::string PredicateMethod; 177 178 /// RenderMethod - The name of the operand method to add this operand to an 179 /// MCInst; this is not valid for Token or register kinds. 180 std::string RenderMethod; 181 182 /// ParserMethod - The name of the operand method to do a target specific 183 /// parsing on the operand. 184 std::string ParserMethod; 185 186 /// For register classes, the records for all the registers in this class. 187 std::set<Record*> Registers; 188 189 public: 190 /// isRegisterClass() - Check if this is a register class. 191 bool isRegisterClass() const { 192 return Kind >= RegisterClass0 && Kind < UserClass0; 193 } 194 195 /// isUserClass() - Check if this is a user defined class. 196 bool isUserClass() const { 197 return Kind >= UserClass0; 198 } 199 200 /// isRelatedTo - Check whether this class is "related" to \arg RHS. Classes 201 /// are related if they are in the same class hierarchy. 202 bool isRelatedTo(const ClassInfo &RHS) const { 203 // Tokens are only related to tokens. 204 if (Kind == Token || RHS.Kind == Token) 205 return Kind == Token && RHS.Kind == Token; 206 207 // Registers classes are only related to registers classes, and only if 208 // their intersection is non-empty. 209 if (isRegisterClass() || RHS.isRegisterClass()) { 210 if (!isRegisterClass() || !RHS.isRegisterClass()) 211 return false; 212 213 std::set<Record*> Tmp; 214 std::insert_iterator< std::set<Record*> > II(Tmp, Tmp.begin()); 215 std::set_intersection(Registers.begin(), Registers.end(), 216 RHS.Registers.begin(), RHS.Registers.end(), 217 II); 218 219 return !Tmp.empty(); 220 } 221 222 // Otherwise we have two users operands; they are related if they are in the 223 // same class hierarchy. 224 // 225 // FIXME: This is an oversimplification, they should only be related if they 226 // intersect, however we don't have that information. 227 assert(isUserClass() && RHS.isUserClass() && "Unexpected class!"); 228 const ClassInfo *Root = this; 229 while (!Root->SuperClasses.empty()) 230 Root = Root->SuperClasses.front(); 231 232 const ClassInfo *RHSRoot = &RHS; 233 while (!RHSRoot->SuperClasses.empty()) 234 RHSRoot = RHSRoot->SuperClasses.front(); 235 236 return Root == RHSRoot; 237 } 238 239 /// isSubsetOf - Test whether this class is a subset of \arg RHS; 240 bool isSubsetOf(const ClassInfo &RHS) const { 241 // This is a subset of RHS if it is the same class... 242 if (this == &RHS) 243 return true; 244 245 // ... or if any of its super classes are a subset of RHS. 246 for (std::vector<ClassInfo*>::const_iterator it = SuperClasses.begin(), 247 ie = SuperClasses.end(); it != ie; ++it) 248 if ((*it)->isSubsetOf(RHS)) 249 return true; 250 251 return false; 252 } 253 254 /// operator< - Compare two classes. 255 bool operator<(const ClassInfo &RHS) const { 256 if (this == &RHS) 257 return false; 258 259 // Unrelated classes can be ordered by kind. 260 if (!isRelatedTo(RHS)) 261 return Kind < RHS.Kind; 262 263 switch (Kind) { 264 case Invalid: 265 llvm_unreachable("Invalid kind!"); 266 267 default: 268 // This class precedes the RHS if it is a proper subset of the RHS. 269 if (isSubsetOf(RHS)) 270 return true; 271 if (RHS.isSubsetOf(*this)) 272 return false; 273 274 // Otherwise, order by name to ensure we have a total ordering. 275 return ValueName < RHS.ValueName; 276 } 277 } 278 }; 279 280 /// MatchableInfo - Helper class for storing the necessary information for an 281 /// instruction or alias which is capable of being matched. 282 struct MatchableInfo { 283 struct AsmOperand { 284 /// Token - This is the token that the operand came from. 285 StringRef Token; 286 287 /// The unique class instance this operand should match. 288 ClassInfo *Class; 289 290 /// The operand name this is, if anything. 291 StringRef SrcOpName; 292 293 /// The suboperand index within SrcOpName, or -1 for the entire operand. 294 int SubOpIdx; 295 296 /// Register record if this token is singleton register. 297 Record *SingletonReg; 298 299 explicit AsmOperand(StringRef T) : Token(T), Class(0), SubOpIdx(-1), 300 SingletonReg(0) {} 301 }; 302 303 /// ResOperand - This represents a single operand in the result instruction 304 /// generated by the match. In cases (like addressing modes) where a single 305 /// assembler operand expands to multiple MCOperands, this represents the 306 /// single assembler operand, not the MCOperand. 307 struct ResOperand { 308 enum { 309 /// RenderAsmOperand - This represents an operand result that is 310 /// generated by calling the render method on the assembly operand. The 311 /// corresponding AsmOperand is specified by AsmOperandNum. 312 RenderAsmOperand, 313 314 /// TiedOperand - This represents a result operand that is a duplicate of 315 /// a previous result operand. 316 TiedOperand, 317 318 /// ImmOperand - This represents an immediate value that is dumped into 319 /// the operand. 320 ImmOperand, 321 322 /// RegOperand - This represents a fixed register that is dumped in. 323 RegOperand 324 } Kind; 325 326 union { 327 /// This is the operand # in the AsmOperands list that this should be 328 /// copied from. 329 unsigned AsmOperandNum; 330 331 /// TiedOperandNum - This is the (earlier) result operand that should be 332 /// copied from. 333 unsigned TiedOperandNum; 334 335 /// ImmVal - This is the immediate value added to the instruction. 336 int64_t ImmVal; 337 338 /// Register - This is the register record. 339 Record *Register; 340 }; 341 342 /// MINumOperands - The number of MCInst operands populated by this 343 /// operand. 344 unsigned MINumOperands; 345 346 static ResOperand getRenderedOp(unsigned AsmOpNum, unsigned NumOperands) { 347 ResOperand X; 348 X.Kind = RenderAsmOperand; 349 X.AsmOperandNum = AsmOpNum; 350 X.MINumOperands = NumOperands; 351 return X; 352 } 353 354 static ResOperand getTiedOp(unsigned TiedOperandNum) { 355 ResOperand X; 356 X.Kind = TiedOperand; 357 X.TiedOperandNum = TiedOperandNum; 358 X.MINumOperands = 1; 359 return X; 360 } 361 362 static ResOperand getImmOp(int64_t Val) { 363 ResOperand X; 364 X.Kind = ImmOperand; 365 X.ImmVal = Val; 366 X.MINumOperands = 1; 367 return X; 368 } 369 370 static ResOperand getRegOp(Record *Reg) { 371 ResOperand X; 372 X.Kind = RegOperand; 373 X.Register = Reg; 374 X.MINumOperands = 1; 375 return X; 376 } 377 }; 378 379 /// AsmVariantID - Target's assembly syntax variant no. 380 int AsmVariantID; 381 382 /// TheDef - This is the definition of the instruction or InstAlias that this 383 /// matchable came from. 384 Record *const TheDef; 385 386 /// DefRec - This is the definition that it came from. 387 PointerUnion<const CodeGenInstruction*, const CodeGenInstAlias*> DefRec; 388 389 const CodeGenInstruction *getResultInst() const { 390 if (DefRec.is<const CodeGenInstruction*>()) 391 return DefRec.get<const CodeGenInstruction*>(); 392 return DefRec.get<const CodeGenInstAlias*>()->ResultInst; 393 } 394 395 /// ResOperands - This is the operand list that should be built for the result 396 /// MCInst. 397 SmallVector<ResOperand, 8> ResOperands; 398 399 /// AsmString - The assembly string for this instruction (with variants 400 /// removed), e.g. "movsx $src, $dst". 401 std::string AsmString; 402 403 /// Mnemonic - This is the first token of the matched instruction, its 404 /// mnemonic. 405 StringRef Mnemonic; 406 407 /// AsmOperands - The textual operands that this instruction matches, 408 /// annotated with a class and where in the OperandList they were defined. 409 /// This directly corresponds to the tokenized AsmString after the mnemonic is 410 /// removed. 411 SmallVector<AsmOperand, 8> AsmOperands; 412 413 /// Predicates - The required subtarget features to match this instruction. 414 SmallVector<SubtargetFeatureInfo*, 4> RequiredFeatures; 415 416 /// ConversionFnKind - The enum value which is passed to the generated 417 /// ConvertToMCInst to convert parsed operands into an MCInst for this 418 /// function. 419 std::string ConversionFnKind; 420 421 MatchableInfo(const CodeGenInstruction &CGI) 422 : AsmVariantID(0), TheDef(CGI.TheDef), DefRec(&CGI), 423 AsmString(CGI.AsmString) { 424 } 425 426 MatchableInfo(const CodeGenInstAlias *Alias) 427 : AsmVariantID(0), TheDef(Alias->TheDef), DefRec(Alias), 428 AsmString(Alias->AsmString) { 429 } 430 431 // Two-operand aliases clone from the main matchable, but mark the second 432 // operand as a tied operand of the first for purposes of the assembler. 433 void formTwoOperandAlias(StringRef Constraint); 434 435 void initialize(const AsmMatcherInfo &Info, 436 SmallPtrSet<Record*, 16> &SingletonRegisters, 437 int AsmVariantNo, std::string &RegisterPrefix); 438 439 /// validate - Return true if this matchable is a valid thing to match against 440 /// and perform a bunch of validity checking. 441 bool validate(StringRef CommentDelimiter, bool Hack) const; 442 443 /// extractSingletonRegisterForAsmOperand - Extract singleton register, 444 /// if present, from specified token. 445 void 446 extractSingletonRegisterForAsmOperand(unsigned i, const AsmMatcherInfo &Info, 447 std::string &RegisterPrefix); 448 449 /// findAsmOperand - Find the AsmOperand with the specified name and 450 /// suboperand index. 451 int findAsmOperand(StringRef N, int SubOpIdx) const { 452 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) 453 if (N == AsmOperands[i].SrcOpName && 454 SubOpIdx == AsmOperands[i].SubOpIdx) 455 return i; 456 return -1; 457 } 458 459 /// findAsmOperandNamed - Find the first AsmOperand with the specified name. 460 /// This does not check the suboperand index. 461 int findAsmOperandNamed(StringRef N) const { 462 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) 463 if (N == AsmOperands[i].SrcOpName) 464 return i; 465 return -1; 466 } 467 468 void buildInstructionResultOperands(); 469 void buildAliasResultOperands(); 470 471 /// operator< - Compare two matchables. 472 bool operator<(const MatchableInfo &RHS) const { 473 // The primary comparator is the instruction mnemonic. 474 if (Mnemonic != RHS.Mnemonic) 475 return Mnemonic < RHS.Mnemonic; 476 477 if (AsmOperands.size() != RHS.AsmOperands.size()) 478 return AsmOperands.size() < RHS.AsmOperands.size(); 479 480 // Compare lexicographically by operand. The matcher validates that other 481 // orderings wouldn't be ambiguous using \see couldMatchAmbiguouslyWith(). 482 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) { 483 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class) 484 return true; 485 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class) 486 return false; 487 } 488 489 return false; 490 } 491 492 /// couldMatchAmbiguouslyWith - Check whether this matchable could 493 /// ambiguously match the same set of operands as \arg RHS (without being a 494 /// strictly superior match). 495 bool couldMatchAmbiguouslyWith(const MatchableInfo &RHS) { 496 // The primary comparator is the instruction mnemonic. 497 if (Mnemonic != RHS.Mnemonic) 498 return false; 499 500 // The number of operands is unambiguous. 501 if (AsmOperands.size() != RHS.AsmOperands.size()) 502 return false; 503 504 // Otherwise, make sure the ordering of the two instructions is unambiguous 505 // by checking that either (a) a token or operand kind discriminates them, 506 // or (b) the ordering among equivalent kinds is consistent. 507 508 // Tokens and operand kinds are unambiguous (assuming a correct target 509 // specific parser). 510 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) 511 if (AsmOperands[i].Class->Kind != RHS.AsmOperands[i].Class->Kind || 512 AsmOperands[i].Class->Kind == ClassInfo::Token) 513 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class || 514 *RHS.AsmOperands[i].Class < *AsmOperands[i].Class) 515 return false; 516 517 // Otherwise, this operand could commute if all operands are equivalent, or 518 // there is a pair of operands that compare less than and a pair that 519 // compare greater than. 520 bool HasLT = false, HasGT = false; 521 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) { 522 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class) 523 HasLT = true; 524 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class) 525 HasGT = true; 526 } 527 528 return !(HasLT ^ HasGT); 529 } 530 531 void dump(); 532 533 private: 534 void tokenizeAsmString(const AsmMatcherInfo &Info); 535 }; 536 537 /// SubtargetFeatureInfo - Helper class for storing information on a subtarget 538 /// feature which participates in instruction matching. 539 struct SubtargetFeatureInfo { 540 /// \brief The predicate record for this feature. 541 Record *TheDef; 542 543 /// \brief An unique index assigned to represent this feature. 544 unsigned Index; 545 546 SubtargetFeatureInfo(Record *D, unsigned Idx) : TheDef(D), Index(Idx) {} 547 548 /// \brief The name of the enumerated constant identifying this feature. 549 std::string getEnumName() const { 550 return "Feature_" + TheDef->getName(); 551 } 552 }; 553 554 struct OperandMatchEntry { 555 unsigned OperandMask; 556 MatchableInfo* MI; 557 ClassInfo *CI; 558 559 static OperandMatchEntry create(MatchableInfo* mi, ClassInfo *ci, 560 unsigned opMask) { 561 OperandMatchEntry X; 562 X.OperandMask = opMask; 563 X.CI = ci; 564 X.MI = mi; 565 return X; 566 } 567 }; 568 569 570 class AsmMatcherInfo { 571 public: 572 /// Tracked Records 573 RecordKeeper &Records; 574 575 /// The tablegen AsmParser record. 576 Record *AsmParser; 577 578 /// Target - The target information. 579 CodeGenTarget &Target; 580 581 /// The classes which are needed for matching. 582 std::vector<ClassInfo*> Classes; 583 584 /// The information on the matchables to match. 585 std::vector<MatchableInfo*> Matchables; 586 587 /// Info for custom matching operands by user defined methods. 588 std::vector<OperandMatchEntry> OperandMatchInfo; 589 590 /// Map of Register records to their class information. 591 std::map<Record*, ClassInfo*> RegisterClasses; 592 593 /// Map of Predicate records to their subtarget information. 594 std::map<Record*, SubtargetFeatureInfo*> SubtargetFeatures; 595 596 private: 597 /// Map of token to class information which has already been constructed. 598 std::map<std::string, ClassInfo*> TokenClasses; 599 600 /// Map of RegisterClass records to their class information. 601 std::map<Record*, ClassInfo*> RegisterClassClasses; 602 603 /// Map of AsmOperandClass records to their class information. 604 std::map<Record*, ClassInfo*> AsmOperandClasses; 605 606 private: 607 /// getTokenClass - Lookup or create the class for the given token. 608 ClassInfo *getTokenClass(StringRef Token); 609 610 /// getOperandClass - Lookup or create the class for the given operand. 611 ClassInfo *getOperandClass(const CGIOperandList::OperandInfo &OI, 612 int SubOpIdx); 613 ClassInfo *getOperandClass(Record *Rec, int SubOpIdx); 614 615 /// buildRegisterClasses - Build the ClassInfo* instances for register 616 /// classes. 617 void buildRegisterClasses(SmallPtrSet<Record*, 16> &SingletonRegisters); 618 619 /// buildOperandClasses - Build the ClassInfo* instances for user defined 620 /// operand classes. 621 void buildOperandClasses(); 622 623 void buildInstructionOperandReference(MatchableInfo *II, StringRef OpName, 624 unsigned AsmOpIdx); 625 void buildAliasOperandReference(MatchableInfo *II, StringRef OpName, 626 MatchableInfo::AsmOperand &Op); 627 628 public: 629 AsmMatcherInfo(Record *AsmParser, 630 CodeGenTarget &Target, 631 RecordKeeper &Records); 632 633 /// buildInfo - Construct the various tables used during matching. 634 void buildInfo(); 635 636 /// buildOperandMatchInfo - Build the necessary information to handle user 637 /// defined operand parsing methods. 638 void buildOperandMatchInfo(); 639 640 /// getSubtargetFeature - Lookup or create the subtarget feature info for the 641 /// given operand. 642 SubtargetFeatureInfo *getSubtargetFeature(Record *Def) const { 643 assert(Def->isSubClassOf("Predicate") && "Invalid predicate type!"); 644 std::map<Record*, SubtargetFeatureInfo*>::const_iterator I = 645 SubtargetFeatures.find(Def); 646 return I == SubtargetFeatures.end() ? 0 : I->second; 647 } 648 649 RecordKeeper &getRecords() const { 650 return Records; 651 } 652 }; 653 654 } // End anonymous namespace 655 656 void MatchableInfo::dump() { 657 errs() << TheDef->getName() << " -- " << "flattened:\"" << AsmString <<"\"\n"; 658 659 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) { 660 AsmOperand &Op = AsmOperands[i]; 661 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - "; 662 errs() << '\"' << Op.Token << "\"\n"; 663 } 664 } 665 666 static std::pair<StringRef, StringRef> 667 parseTwoOperandConstraint(StringRef S, SMLoc Loc) { 668 // Split via the '='. 669 std::pair<StringRef, StringRef> Ops = S.split('='); 670 if (Ops.second == "") 671 throw TGError(Loc, "missing '=' in two-operand alias constraint"); 672 // Trim whitespace and the leading '$' on the operand names. 673 size_t start = Ops.first.find_first_of('$'); 674 if (start == std::string::npos) 675 throw TGError(Loc, "expected '$' prefix on asm operand name"); 676 Ops.first = Ops.first.slice(start + 1, std::string::npos); 677 size_t end = Ops.first.find_last_of(" \t"); 678 Ops.first = Ops.first.slice(0, end); 679 // Now the second operand. 680 start = Ops.second.find_first_of('$'); 681 if (start == std::string::npos) 682 throw TGError(Loc, "expected '$' prefix on asm operand name"); 683 Ops.second = Ops.second.slice(start + 1, std::string::npos); 684 end = Ops.second.find_last_of(" \t"); 685 Ops.first = Ops.first.slice(0, end); 686 return Ops; 687 } 688 689 void MatchableInfo::formTwoOperandAlias(StringRef Constraint) { 690 // Figure out which operands are aliased and mark them as tied. 691 std::pair<StringRef, StringRef> Ops = 692 parseTwoOperandConstraint(Constraint, TheDef->getLoc()); 693 694 // Find the AsmOperands that refer to the operands we're aliasing. 695 int SrcAsmOperand = findAsmOperandNamed(Ops.first); 696 int DstAsmOperand = findAsmOperandNamed(Ops.second); 697 if (SrcAsmOperand == -1) 698 throw TGError(TheDef->getLoc(), 699 "unknown source two-operand alias operand '" + 700 Ops.first.str() + "'."); 701 if (DstAsmOperand == -1) 702 throw TGError(TheDef->getLoc(), 703 "unknown destination two-operand alias operand '" + 704 Ops.second.str() + "'."); 705 706 // Find the ResOperand that refers to the operand we're aliasing away 707 // and update it to refer to the combined operand instead. 708 for (unsigned i = 0, e = ResOperands.size(); i != e; ++i) { 709 ResOperand &Op = ResOperands[i]; 710 if (Op.Kind == ResOperand::RenderAsmOperand && 711 Op.AsmOperandNum == (unsigned)SrcAsmOperand) { 712 Op.AsmOperandNum = DstAsmOperand; 713 break; 714 } 715 } 716 // Remove the AsmOperand for the alias operand. 717 AsmOperands.erase(AsmOperands.begin() + SrcAsmOperand); 718 // Adjust the ResOperand references to any AsmOperands that followed 719 // the one we just deleted. 720 for (unsigned i = 0, e = ResOperands.size(); i != e; ++i) { 721 ResOperand &Op = ResOperands[i]; 722 switch(Op.Kind) { 723 default: 724 // Nothing to do for operands that don't reference AsmOperands. 725 break; 726 case ResOperand::RenderAsmOperand: 727 if (Op.AsmOperandNum > (unsigned)SrcAsmOperand) 728 --Op.AsmOperandNum; 729 break; 730 case ResOperand::TiedOperand: 731 if (Op.TiedOperandNum > (unsigned)SrcAsmOperand) 732 --Op.TiedOperandNum; 733 break; 734 } 735 } 736 } 737 738 void MatchableInfo::initialize(const AsmMatcherInfo &Info, 739 SmallPtrSet<Record*, 16> &SingletonRegisters, 740 int AsmVariantNo, std::string &RegisterPrefix) { 741 AsmVariantID = AsmVariantNo; 742 AsmString = 743 CodeGenInstruction::FlattenAsmStringVariants(AsmString, AsmVariantNo); 744 745 tokenizeAsmString(Info); 746 747 // Compute the require features. 748 std::vector<Record*> Predicates =TheDef->getValueAsListOfDefs("Predicates"); 749 for (unsigned i = 0, e = Predicates.size(); i != e; ++i) 750 if (SubtargetFeatureInfo *Feature = 751 Info.getSubtargetFeature(Predicates[i])) 752 RequiredFeatures.push_back(Feature); 753 754 // Collect singleton registers, if used. 755 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) { 756 extractSingletonRegisterForAsmOperand(i, Info, RegisterPrefix); 757 if (Record *Reg = AsmOperands[i].SingletonReg) 758 SingletonRegisters.insert(Reg); 759 } 760 } 761 762 /// tokenizeAsmString - Tokenize a simplified assembly string. 763 void MatchableInfo::tokenizeAsmString(const AsmMatcherInfo &Info) { 764 StringRef String = AsmString; 765 unsigned Prev = 0; 766 bool InTok = true; 767 for (unsigned i = 0, e = String.size(); i != e; ++i) { 768 switch (String[i]) { 769 case '[': 770 case ']': 771 case '*': 772 case '!': 773 case ' ': 774 case '\t': 775 case ',': 776 if (InTok) { 777 AsmOperands.push_back(AsmOperand(String.slice(Prev, i))); 778 InTok = false; 779 } 780 if (!isspace(String[i]) && String[i] != ',') 781 AsmOperands.push_back(AsmOperand(String.substr(i, 1))); 782 Prev = i + 1; 783 break; 784 785 case '\\': 786 if (InTok) { 787 AsmOperands.push_back(AsmOperand(String.slice(Prev, i))); 788 InTok = false; 789 } 790 ++i; 791 assert(i != String.size() && "Invalid quoted character"); 792 AsmOperands.push_back(AsmOperand(String.substr(i, 1))); 793 Prev = i + 1; 794 break; 795 796 case '$': { 797 if (InTok) { 798 AsmOperands.push_back(AsmOperand(String.slice(Prev, i))); 799 InTok = false; 800 } 801 802 // If this isn't "${", treat like a normal token. 803 if (i + 1 == String.size() || String[i + 1] != '{') { 804 Prev = i; 805 break; 806 } 807 808 StringRef::iterator End = std::find(String.begin() + i, String.end(),'}'); 809 assert(End != String.end() && "Missing brace in operand reference!"); 810 size_t EndPos = End - String.begin(); 811 AsmOperands.push_back(AsmOperand(String.slice(i, EndPos+1))); 812 Prev = EndPos + 1; 813 i = EndPos; 814 break; 815 } 816 817 case '.': 818 if (InTok) 819 AsmOperands.push_back(AsmOperand(String.slice(Prev, i))); 820 Prev = i; 821 InTok = true; 822 break; 823 824 default: 825 InTok = true; 826 } 827 } 828 if (InTok && Prev != String.size()) 829 AsmOperands.push_back(AsmOperand(String.substr(Prev))); 830 831 // The first token of the instruction is the mnemonic, which must be a 832 // simple string, not a $foo variable or a singleton register. 833 if (AsmOperands.empty()) 834 throw TGError(TheDef->getLoc(), 835 "Instruction '" + TheDef->getName() + "' has no tokens"); 836 Mnemonic = AsmOperands[0].Token; 837 if (Mnemonic.empty()) 838 throw TGError(TheDef->getLoc(), 839 "Missing instruction mnemonic"); 840 // FIXME : Check and raise an error if it is a register. 841 if (Mnemonic[0] == '$') 842 throw TGError(TheDef->getLoc(), 843 "Invalid instruction mnemonic '" + Mnemonic.str() + "'!"); 844 845 // Remove the first operand, it is tracked in the mnemonic field. 846 AsmOperands.erase(AsmOperands.begin()); 847 } 848 849 bool MatchableInfo::validate(StringRef CommentDelimiter, bool Hack) const { 850 // Reject matchables with no .s string. 851 if (AsmString.empty()) 852 throw TGError(TheDef->getLoc(), "instruction with empty asm string"); 853 854 // Reject any matchables with a newline in them, they should be marked 855 // isCodeGenOnly if they are pseudo instructions. 856 if (AsmString.find('\n') != std::string::npos) 857 throw TGError(TheDef->getLoc(), 858 "multiline instruction is not valid for the asmparser, " 859 "mark it isCodeGenOnly"); 860 861 // Remove comments from the asm string. We know that the asmstring only 862 // has one line. 863 if (!CommentDelimiter.empty() && 864 StringRef(AsmString).find(CommentDelimiter) != StringRef::npos) 865 throw TGError(TheDef->getLoc(), 866 "asmstring for instruction has comment character in it, " 867 "mark it isCodeGenOnly"); 868 869 // Reject matchables with operand modifiers, these aren't something we can 870 // handle, the target should be refactored to use operands instead of 871 // modifiers. 872 // 873 // Also, check for instructions which reference the operand multiple times; 874 // this implies a constraint we would not honor. 875 std::set<std::string> OperandNames; 876 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) { 877 StringRef Tok = AsmOperands[i].Token; 878 if (Tok[0] == '$' && Tok.find(':') != StringRef::npos) 879 throw TGError(TheDef->getLoc(), 880 "matchable with operand modifier '" + Tok.str() + 881 "' not supported by asm matcher. Mark isCodeGenOnly!"); 882 883 // Verify that any operand is only mentioned once. 884 // We reject aliases and ignore instructions for now. 885 if (Tok[0] == '$' && !OperandNames.insert(Tok).second) { 886 if (!Hack) 887 throw TGError(TheDef->getLoc(), 888 "ERROR: matchable with tied operand '" + Tok.str() + 889 "' can never be matched!"); 890 // FIXME: Should reject these. The ARM backend hits this with $lane in a 891 // bunch of instructions. It is unclear what the right answer is. 892 DEBUG({ 893 errs() << "warning: '" << TheDef->getName() << "': " 894 << "ignoring instruction with tied operand '" 895 << Tok.str() << "'\n"; 896 }); 897 return false; 898 } 899 } 900 901 return true; 902 } 903 904 /// extractSingletonRegisterForAsmOperand - Extract singleton register, 905 /// if present, from specified token. 906 void MatchableInfo:: 907 extractSingletonRegisterForAsmOperand(unsigned OperandNo, 908 const AsmMatcherInfo &Info, 909 std::string &RegisterPrefix) { 910 StringRef Tok = AsmOperands[OperandNo].Token; 911 if (RegisterPrefix.empty()) { 912 std::string LoweredTok = Tok.lower(); 913 if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(LoweredTok)) 914 AsmOperands[OperandNo].SingletonReg = Reg->TheDef; 915 return; 916 } 917 918 if (!Tok.startswith(RegisterPrefix)) 919 return; 920 921 StringRef RegName = Tok.substr(RegisterPrefix.size()); 922 if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(RegName)) 923 AsmOperands[OperandNo].SingletonReg = Reg->TheDef; 924 925 // If there is no register prefix (i.e. "%" in "%eax"), then this may 926 // be some random non-register token, just ignore it. 927 return; 928 } 929 930 static std::string getEnumNameForToken(StringRef Str) { 931 std::string Res; 932 933 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) { 934 switch (*it) { 935 case '*': Res += "_STAR_"; break; 936 case '%': Res += "_PCT_"; break; 937 case ':': Res += "_COLON_"; break; 938 case '!': Res += "_EXCLAIM_"; break; 939 case '.': Res += "_DOT_"; break; 940 default: 941 if (isalnum(*it)) 942 Res += *it; 943 else 944 Res += "_" + utostr((unsigned) *it) + "_"; 945 } 946 } 947 948 return Res; 949 } 950 951 ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) { 952 ClassInfo *&Entry = TokenClasses[Token]; 953 954 if (!Entry) { 955 Entry = new ClassInfo(); 956 Entry->Kind = ClassInfo::Token; 957 Entry->ClassName = "Token"; 958 Entry->Name = "MCK_" + getEnumNameForToken(Token); 959 Entry->ValueName = Token; 960 Entry->PredicateMethod = "<invalid>"; 961 Entry->RenderMethod = "<invalid>"; 962 Entry->ParserMethod = ""; 963 Classes.push_back(Entry); 964 } 965 966 return Entry; 967 } 968 969 ClassInfo * 970 AsmMatcherInfo::getOperandClass(const CGIOperandList::OperandInfo &OI, 971 int SubOpIdx) { 972 Record *Rec = OI.Rec; 973 if (SubOpIdx != -1) 974 Rec = dynamic_cast<DefInit*>(OI.MIOperandInfo->getArg(SubOpIdx))->getDef(); 975 return getOperandClass(Rec, SubOpIdx); 976 } 977 978 ClassInfo * 979 AsmMatcherInfo::getOperandClass(Record *Rec, int SubOpIdx) { 980 if (Rec->isSubClassOf("RegisterOperand")) { 981 // RegisterOperand may have an associated ParserMatchClass. If it does, 982 // use it, else just fall back to the underlying register class. 983 const RecordVal *R = Rec->getValue("ParserMatchClass"); 984 if (R == 0 || R->getValue() == 0) 985 throw "Record `" + Rec->getName() + 986 "' does not have a ParserMatchClass!\n"; 987 988 if (DefInit *DI= dynamic_cast<DefInit*>(R->getValue())) { 989 Record *MatchClass = DI->getDef(); 990 if (ClassInfo *CI = AsmOperandClasses[MatchClass]) 991 return CI; 992 } 993 994 // No custom match class. Just use the register class. 995 Record *ClassRec = Rec->getValueAsDef("RegClass"); 996 if (!ClassRec) 997 throw TGError(Rec->getLoc(), "RegisterOperand `" + Rec->getName() + 998 "' has no associated register class!\n"); 999 if (ClassInfo *CI = RegisterClassClasses[ClassRec]) 1000 return CI; 1001 throw TGError(Rec->getLoc(), "register class has no class info!"); 1002 } 1003 1004 1005 if (Rec->isSubClassOf("RegisterClass")) { 1006 if (ClassInfo *CI = RegisterClassClasses[Rec]) 1007 return CI; 1008 throw TGError(Rec->getLoc(), "register class has no class info!"); 1009 } 1010 1011 assert(Rec->isSubClassOf("Operand") && "Unexpected operand!"); 1012 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass"); 1013 if (ClassInfo *CI = AsmOperandClasses[MatchClass]) 1014 return CI; 1015 1016 throw TGError(Rec->getLoc(), "operand has no match class!"); 1017 } 1018 1019 void AsmMatcherInfo:: 1020 buildRegisterClasses(SmallPtrSet<Record*, 16> &SingletonRegisters) { 1021 const std::vector<CodeGenRegister*> &Registers = 1022 Target.getRegBank().getRegisters(); 1023 ArrayRef<CodeGenRegisterClass*> RegClassList = 1024 Target.getRegBank().getRegClasses(); 1025 1026 // The register sets used for matching. 1027 std::set< std::set<Record*> > RegisterSets; 1028 1029 // Gather the defined sets. 1030 for (ArrayRef<CodeGenRegisterClass*>::const_iterator it = 1031 RegClassList.begin(), ie = RegClassList.end(); it != ie; ++it) 1032 RegisterSets.insert(std::set<Record*>( 1033 (*it)->getOrder().begin(), (*it)->getOrder().end())); 1034 1035 // Add any required singleton sets. 1036 for (SmallPtrSet<Record*, 16>::iterator it = SingletonRegisters.begin(), 1037 ie = SingletonRegisters.end(); it != ie; ++it) { 1038 Record *Rec = *it; 1039 RegisterSets.insert(std::set<Record*>(&Rec, &Rec + 1)); 1040 } 1041 1042 // Introduce derived sets where necessary (when a register does not determine 1043 // a unique register set class), and build the mapping of registers to the set 1044 // they should classify to. 1045 std::map<Record*, std::set<Record*> > RegisterMap; 1046 for (std::vector<CodeGenRegister*>::const_iterator it = Registers.begin(), 1047 ie = Registers.end(); it != ie; ++it) { 1048 const CodeGenRegister &CGR = **it; 1049 // Compute the intersection of all sets containing this register. 1050 std::set<Record*> ContainingSet; 1051 1052 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(), 1053 ie = RegisterSets.end(); it != ie; ++it) { 1054 if (!it->count(CGR.TheDef)) 1055 continue; 1056 1057 if (ContainingSet.empty()) { 1058 ContainingSet = *it; 1059 continue; 1060 } 1061 1062 std::set<Record*> Tmp; 1063 std::swap(Tmp, ContainingSet); 1064 std::insert_iterator< std::set<Record*> > II(ContainingSet, 1065 ContainingSet.begin()); 1066 std::set_intersection(Tmp.begin(), Tmp.end(), it->begin(), it->end(), II); 1067 } 1068 1069 if (!ContainingSet.empty()) { 1070 RegisterSets.insert(ContainingSet); 1071 RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet)); 1072 } 1073 } 1074 1075 // Construct the register classes. 1076 std::map<std::set<Record*>, ClassInfo*> RegisterSetClasses; 1077 unsigned Index = 0; 1078 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(), 1079 ie = RegisterSets.end(); it != ie; ++it, ++Index) { 1080 ClassInfo *CI = new ClassInfo(); 1081 CI->Kind = ClassInfo::RegisterClass0 + Index; 1082 CI->ClassName = "Reg" + utostr(Index); 1083 CI->Name = "MCK_Reg" + utostr(Index); 1084 CI->ValueName = ""; 1085 CI->PredicateMethod = ""; // unused 1086 CI->RenderMethod = "addRegOperands"; 1087 CI->Registers = *it; 1088 Classes.push_back(CI); 1089 RegisterSetClasses.insert(std::make_pair(*it, CI)); 1090 } 1091 1092 // Find the superclasses; we could compute only the subgroup lattice edges, 1093 // but there isn't really a point. 1094 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(), 1095 ie = RegisterSets.end(); it != ie; ++it) { 1096 ClassInfo *CI = RegisterSetClasses[*it]; 1097 for (std::set< std::set<Record*> >::iterator it2 = RegisterSets.begin(), 1098 ie2 = RegisterSets.end(); it2 != ie2; ++it2) 1099 if (*it != *it2 && 1100 std::includes(it2->begin(), it2->end(), it->begin(), it->end())) 1101 CI->SuperClasses.push_back(RegisterSetClasses[*it2]); 1102 } 1103 1104 // Name the register classes which correspond to a user defined RegisterClass. 1105 for (ArrayRef<CodeGenRegisterClass*>::const_iterator 1106 it = RegClassList.begin(), ie = RegClassList.end(); it != ie; ++it) { 1107 const CodeGenRegisterClass &RC = **it; 1108 // Def will be NULL for non-user defined register classes. 1109 Record *Def = RC.getDef(); 1110 if (!Def) 1111 continue; 1112 ClassInfo *CI = RegisterSetClasses[std::set<Record*>(RC.getOrder().begin(), 1113 RC.getOrder().end())]; 1114 if (CI->ValueName.empty()) { 1115 CI->ClassName = RC.getName(); 1116 CI->Name = "MCK_" + RC.getName(); 1117 CI->ValueName = RC.getName(); 1118 } else 1119 CI->ValueName = CI->ValueName + "," + RC.getName(); 1120 1121 RegisterClassClasses.insert(std::make_pair(Def, CI)); 1122 } 1123 1124 // Populate the map for individual registers. 1125 for (std::map<Record*, std::set<Record*> >::iterator it = RegisterMap.begin(), 1126 ie = RegisterMap.end(); it != ie; ++it) 1127 RegisterClasses[it->first] = RegisterSetClasses[it->second]; 1128 1129 // Name the register classes which correspond to singleton registers. 1130 for (SmallPtrSet<Record*, 16>::iterator it = SingletonRegisters.begin(), 1131 ie = SingletonRegisters.end(); it != ie; ++it) { 1132 Record *Rec = *it; 1133 ClassInfo *CI = RegisterClasses[Rec]; 1134 assert(CI && "Missing singleton register class info!"); 1135 1136 if (CI->ValueName.empty()) { 1137 CI->ClassName = Rec->getName(); 1138 CI->Name = "MCK_" + Rec->getName(); 1139 CI->ValueName = Rec->getName(); 1140 } else 1141 CI->ValueName = CI->ValueName + "," + Rec->getName(); 1142 } 1143 } 1144 1145 void AsmMatcherInfo::buildOperandClasses() { 1146 std::vector<Record*> AsmOperands = 1147 Records.getAllDerivedDefinitions("AsmOperandClass"); 1148 1149 // Pre-populate AsmOperandClasses map. 1150 for (std::vector<Record*>::iterator it = AsmOperands.begin(), 1151 ie = AsmOperands.end(); it != ie; ++it) 1152 AsmOperandClasses[*it] = new ClassInfo(); 1153 1154 unsigned Index = 0; 1155 for (std::vector<Record*>::iterator it = AsmOperands.begin(), 1156 ie = AsmOperands.end(); it != ie; ++it, ++Index) { 1157 ClassInfo *CI = AsmOperandClasses[*it]; 1158 CI->Kind = ClassInfo::UserClass0 + Index; 1159 1160 ListInit *Supers = (*it)->getValueAsListInit("SuperClasses"); 1161 for (unsigned i = 0, e = Supers->getSize(); i != e; ++i) { 1162 DefInit *DI = dynamic_cast<DefInit*>(Supers->getElement(i)); 1163 if (!DI) { 1164 PrintError((*it)->getLoc(), "Invalid super class reference!"); 1165 continue; 1166 } 1167 1168 ClassInfo *SC = AsmOperandClasses[DI->getDef()]; 1169 if (!SC) 1170 PrintError((*it)->getLoc(), "Invalid super class reference!"); 1171 else 1172 CI->SuperClasses.push_back(SC); 1173 } 1174 CI->ClassName = (*it)->getValueAsString("Name"); 1175 CI->Name = "MCK_" + CI->ClassName; 1176 CI->ValueName = (*it)->getName(); 1177 1178 // Get or construct the predicate method name. 1179 Init *PMName = (*it)->getValueInit("PredicateMethod"); 1180 if (StringInit *SI = dynamic_cast<StringInit*>(PMName)) { 1181 CI->PredicateMethod = SI->getValue(); 1182 } else { 1183 assert(dynamic_cast<UnsetInit*>(PMName) && 1184 "Unexpected PredicateMethod field!"); 1185 CI->PredicateMethod = "is" + CI->ClassName; 1186 } 1187 1188 // Get or construct the render method name. 1189 Init *RMName = (*it)->getValueInit("RenderMethod"); 1190 if (StringInit *SI = dynamic_cast<StringInit*>(RMName)) { 1191 CI->RenderMethod = SI->getValue(); 1192 } else { 1193 assert(dynamic_cast<UnsetInit*>(RMName) && 1194 "Unexpected RenderMethod field!"); 1195 CI->RenderMethod = "add" + CI->ClassName + "Operands"; 1196 } 1197 1198 // Get the parse method name or leave it as empty. 1199 Init *PRMName = (*it)->getValueInit("ParserMethod"); 1200 if (StringInit *SI = dynamic_cast<StringInit*>(PRMName)) 1201 CI->ParserMethod = SI->getValue(); 1202 1203 AsmOperandClasses[*it] = CI; 1204 Classes.push_back(CI); 1205 } 1206 } 1207 1208 AsmMatcherInfo::AsmMatcherInfo(Record *asmParser, 1209 CodeGenTarget &target, 1210 RecordKeeper &records) 1211 : Records(records), AsmParser(asmParser), Target(target) { 1212 } 1213 1214 /// buildOperandMatchInfo - Build the necessary information to handle user 1215 /// defined operand parsing methods. 1216 void AsmMatcherInfo::buildOperandMatchInfo() { 1217 1218 /// Map containing a mask with all operands indices that can be found for 1219 /// that class inside a instruction. 1220 std::map<ClassInfo*, unsigned> OpClassMask; 1221 1222 for (std::vector<MatchableInfo*>::const_iterator it = 1223 Matchables.begin(), ie = Matchables.end(); 1224 it != ie; ++it) { 1225 MatchableInfo &II = **it; 1226 OpClassMask.clear(); 1227 1228 // Keep track of all operands of this instructions which belong to the 1229 // same class. 1230 for (unsigned i = 0, e = II.AsmOperands.size(); i != e; ++i) { 1231 MatchableInfo::AsmOperand &Op = II.AsmOperands[i]; 1232 if (Op.Class->ParserMethod.empty()) 1233 continue; 1234 unsigned &OperandMask = OpClassMask[Op.Class]; 1235 OperandMask |= (1 << i); 1236 } 1237 1238 // Generate operand match info for each mnemonic/operand class pair. 1239 for (std::map<ClassInfo*, unsigned>::iterator iit = OpClassMask.begin(), 1240 iie = OpClassMask.end(); iit != iie; ++iit) { 1241 unsigned OpMask = iit->second; 1242 ClassInfo *CI = iit->first; 1243 OperandMatchInfo.push_back(OperandMatchEntry::create(&II, CI, OpMask)); 1244 } 1245 } 1246 } 1247 1248 void AsmMatcherInfo::buildInfo() { 1249 // Build information about all of the AssemblerPredicates. 1250 std::vector<Record*> AllPredicates = 1251 Records.getAllDerivedDefinitions("Predicate"); 1252 for (unsigned i = 0, e = AllPredicates.size(); i != e; ++i) { 1253 Record *Pred = AllPredicates[i]; 1254 // Ignore predicates that are not intended for the assembler. 1255 if (!Pred->getValueAsBit("AssemblerMatcherPredicate")) 1256 continue; 1257 1258 if (Pred->getName().empty()) 1259 throw TGError(Pred->getLoc(), "Predicate has no name!"); 1260 1261 unsigned FeatureNo = SubtargetFeatures.size(); 1262 SubtargetFeatures[Pred] = new SubtargetFeatureInfo(Pred, FeatureNo); 1263 assert(FeatureNo < 32 && "Too many subtarget features!"); 1264 } 1265 1266 // Parse the instructions; we need to do this first so that we can gather the 1267 // singleton register classes. 1268 SmallPtrSet<Record*, 16> SingletonRegisters; 1269 unsigned VariantCount = Target.getAsmParserVariantCount(); 1270 for (unsigned VC = 0; VC != VariantCount; ++VC) { 1271 Record *AsmVariant = Target.getAsmParserVariant(VC); 1272 std::string CommentDelimiter = 1273 AsmVariant->getValueAsString("CommentDelimiter"); 1274 std::string RegisterPrefix = AsmVariant->getValueAsString("RegisterPrefix"); 1275 int AsmVariantNo = AsmVariant->getValueAsInt("Variant"); 1276 1277 for (CodeGenTarget::inst_iterator I = Target.inst_begin(), 1278 E = Target.inst_end(); I != E; ++I) { 1279 const CodeGenInstruction &CGI = **I; 1280 1281 // If the tblgen -match-prefix option is specified (for tblgen hackers), 1282 // filter the set of instructions we consider. 1283 if (!StringRef(CGI.TheDef->getName()).startswith(MatchPrefix)) 1284 continue; 1285 1286 // Ignore "codegen only" instructions. 1287 if (CGI.TheDef->getValueAsBit("isCodeGenOnly")) 1288 continue; 1289 1290 // Validate the operand list to ensure we can handle this instruction. 1291 for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) { 1292 const CGIOperandList::OperandInfo &OI = CGI.Operands[i]; 1293 1294 // Validate tied operands. 1295 if (OI.getTiedRegister() != -1) { 1296 // If we have a tied operand that consists of multiple MCOperands, 1297 // reject it. We reject aliases and ignore instructions for now. 1298 if (OI.MINumOperands != 1) { 1299 // FIXME: Should reject these. The ARM backend hits this with $lane 1300 // in a bunch of instructions. The right answer is unclear. 1301 DEBUG({ 1302 errs() << "warning: '" << CGI.TheDef->getName() << "': " 1303 << "ignoring instruction with multi-operand tied operand '" 1304 << OI.Name << "'\n"; 1305 }); 1306 continue; 1307 } 1308 } 1309 } 1310 1311 OwningPtr<MatchableInfo> II(new MatchableInfo(CGI)); 1312 1313 II->initialize(*this, SingletonRegisters, AsmVariantNo, RegisterPrefix); 1314 1315 // Ignore instructions which shouldn't be matched and diagnose invalid 1316 // instruction definitions with an error. 1317 if (!II->validate(CommentDelimiter, true)) 1318 continue; 1319 1320 // Ignore "Int_*" and "*_Int" instructions, which are internal aliases. 1321 // 1322 // FIXME: This is a total hack. 1323 if (StringRef(II->TheDef->getName()).startswith("Int_") || 1324 StringRef(II->TheDef->getName()).endswith("_Int")) 1325 continue; 1326 1327 Matchables.push_back(II.take()); 1328 } 1329 1330 // Parse all of the InstAlias definitions and stick them in the list of 1331 // matchables. 1332 std::vector<Record*> AllInstAliases = 1333 Records.getAllDerivedDefinitions("InstAlias"); 1334 for (unsigned i = 0, e = AllInstAliases.size(); i != e; ++i) { 1335 CodeGenInstAlias *Alias = new CodeGenInstAlias(AllInstAliases[i], Target); 1336 1337 // If the tblgen -match-prefix option is specified (for tblgen hackers), 1338 // filter the set of instruction aliases we consider, based on the target 1339 // instruction. 1340 if (!StringRef(Alias->ResultInst->TheDef->getName()) 1341 .startswith( MatchPrefix)) 1342 continue; 1343 1344 OwningPtr<MatchableInfo> II(new MatchableInfo(Alias)); 1345 1346 II->initialize(*this, SingletonRegisters, AsmVariantNo, RegisterPrefix); 1347 1348 // Validate the alias definitions. 1349 II->validate(CommentDelimiter, false); 1350 1351 Matchables.push_back(II.take()); 1352 } 1353 } 1354 1355 // Build info for the register classes. 1356 buildRegisterClasses(SingletonRegisters); 1357 1358 // Build info for the user defined assembly operand classes. 1359 buildOperandClasses(); 1360 1361 // Build the information about matchables, now that we have fully formed 1362 // classes. 1363 std::vector<MatchableInfo*> NewMatchables; 1364 for (std::vector<MatchableInfo*>::iterator it = Matchables.begin(), 1365 ie = Matchables.end(); it != ie; ++it) { 1366 MatchableInfo *II = *it; 1367 1368 // Parse the tokens after the mnemonic. 1369 // Note: buildInstructionOperandReference may insert new AsmOperands, so 1370 // don't precompute the loop bound. 1371 for (unsigned i = 0; i != II->AsmOperands.size(); ++i) { 1372 MatchableInfo::AsmOperand &Op = II->AsmOperands[i]; 1373 StringRef Token = Op.Token; 1374 1375 // Check for singleton registers. 1376 if (Record *RegRecord = II->AsmOperands[i].SingletonReg) { 1377 Op.Class = RegisterClasses[RegRecord]; 1378 assert(Op.Class && Op.Class->Registers.size() == 1 && 1379 "Unexpected class for singleton register"); 1380 continue; 1381 } 1382 1383 // Check for simple tokens. 1384 if (Token[0] != '$') { 1385 Op.Class = getTokenClass(Token); 1386 continue; 1387 } 1388 1389 if (Token.size() > 1 && isdigit(Token[1])) { 1390 Op.Class = getTokenClass(Token); 1391 continue; 1392 } 1393 1394 // Otherwise this is an operand reference. 1395 StringRef OperandName; 1396 if (Token[1] == '{') 1397 OperandName = Token.substr(2, Token.size() - 3); 1398 else 1399 OperandName = Token.substr(1); 1400 1401 if (II->DefRec.is<const CodeGenInstruction*>()) 1402 buildInstructionOperandReference(II, OperandName, i); 1403 else 1404 buildAliasOperandReference(II, OperandName, Op); 1405 } 1406 1407 if (II->DefRec.is<const CodeGenInstruction*>()) { 1408 II->buildInstructionResultOperands(); 1409 // If the instruction has a two-operand alias, build up the 1410 // matchable here. We'll add them in bulk at the end to avoid 1411 // confusing this loop. 1412 std::string Constraint = 1413 II->TheDef->getValueAsString("TwoOperandAliasConstraint"); 1414 if (Constraint != "") { 1415 // Start by making a copy of the original matchable. 1416 OwningPtr<MatchableInfo> AliasII(new MatchableInfo(*II)); 1417 1418 // Adjust it to be a two-operand alias. 1419 AliasII->formTwoOperandAlias(Constraint); 1420 1421 // Add the alias to the matchables list. 1422 NewMatchables.push_back(AliasII.take()); 1423 } 1424 } else 1425 II->buildAliasResultOperands(); 1426 } 1427 if (!NewMatchables.empty()) 1428 Matchables.insert(Matchables.end(), NewMatchables.begin(), 1429 NewMatchables.end()); 1430 1431 // Process token alias definitions and set up the associated superclass 1432 // information. 1433 std::vector<Record*> AllTokenAliases = 1434 Records.getAllDerivedDefinitions("TokenAlias"); 1435 for (unsigned i = 0, e = AllTokenAliases.size(); i != e; ++i) { 1436 Record *Rec = AllTokenAliases[i]; 1437 ClassInfo *FromClass = getTokenClass(Rec->getValueAsString("FromToken")); 1438 ClassInfo *ToClass = getTokenClass(Rec->getValueAsString("ToToken")); 1439 if (FromClass == ToClass) 1440 throw TGError(Rec->getLoc(), 1441 "error: Destination value identical to source value."); 1442 FromClass->SuperClasses.push_back(ToClass); 1443 } 1444 1445 // Reorder classes so that classes precede super classes. 1446 std::sort(Classes.begin(), Classes.end(), less_ptr<ClassInfo>()); 1447 } 1448 1449 /// buildInstructionOperandReference - The specified operand is a reference to a 1450 /// named operand such as $src. Resolve the Class and OperandInfo pointers. 1451 void AsmMatcherInfo:: 1452 buildInstructionOperandReference(MatchableInfo *II, 1453 StringRef OperandName, 1454 unsigned AsmOpIdx) { 1455 const CodeGenInstruction &CGI = *II->DefRec.get<const CodeGenInstruction*>(); 1456 const CGIOperandList &Operands = CGI.Operands; 1457 MatchableInfo::AsmOperand *Op = &II->AsmOperands[AsmOpIdx]; 1458 1459 // Map this token to an operand. 1460 unsigned Idx; 1461 if (!Operands.hasOperandNamed(OperandName, Idx)) 1462 throw TGError(II->TheDef->getLoc(), "error: unable to find operand: '" + 1463 OperandName.str() + "'"); 1464 1465 // If the instruction operand has multiple suboperands, but the parser 1466 // match class for the asm operand is still the default "ImmAsmOperand", 1467 // then handle each suboperand separately. 1468 if (Op->SubOpIdx == -1 && Operands[Idx].MINumOperands > 1) { 1469 Record *Rec = Operands[Idx].Rec; 1470 assert(Rec->isSubClassOf("Operand") && "Unexpected operand!"); 1471 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass"); 1472 if (MatchClass && MatchClass->getValueAsString("Name") == "Imm") { 1473 // Insert remaining suboperands after AsmOpIdx in II->AsmOperands. 1474 StringRef Token = Op->Token; // save this in case Op gets moved 1475 for (unsigned SI = 1, SE = Operands[Idx].MINumOperands; SI != SE; ++SI) { 1476 MatchableInfo::AsmOperand NewAsmOp(Token); 1477 NewAsmOp.SubOpIdx = SI; 1478 II->AsmOperands.insert(II->AsmOperands.begin()+AsmOpIdx+SI, NewAsmOp); 1479 } 1480 // Replace Op with first suboperand. 1481 Op = &II->AsmOperands[AsmOpIdx]; // update the pointer in case it moved 1482 Op->SubOpIdx = 0; 1483 } 1484 } 1485 1486 // Set up the operand class. 1487 Op->Class = getOperandClass(Operands[Idx], Op->SubOpIdx); 1488 1489 // If the named operand is tied, canonicalize it to the untied operand. 1490 // For example, something like: 1491 // (outs GPR:$dst), (ins GPR:$src) 1492 // with an asmstring of 1493 // "inc $src" 1494 // we want to canonicalize to: 1495 // "inc $dst" 1496 // so that we know how to provide the $dst operand when filling in the result. 1497 int OITied = Operands[Idx].getTiedRegister(); 1498 if (OITied != -1) { 1499 // The tied operand index is an MIOperand index, find the operand that 1500 // contains it. 1501 std::pair<unsigned, unsigned> Idx = Operands.getSubOperandNumber(OITied); 1502 OperandName = Operands[Idx.first].Name; 1503 Op->SubOpIdx = Idx.second; 1504 } 1505 1506 Op->SrcOpName = OperandName; 1507 } 1508 1509 /// buildAliasOperandReference - When parsing an operand reference out of the 1510 /// matching string (e.g. "movsx $src, $dst"), determine what the class of the 1511 /// operand reference is by looking it up in the result pattern definition. 1512 void AsmMatcherInfo::buildAliasOperandReference(MatchableInfo *II, 1513 StringRef OperandName, 1514 MatchableInfo::AsmOperand &Op) { 1515 const CodeGenInstAlias &CGA = *II->DefRec.get<const CodeGenInstAlias*>(); 1516 1517 // Set up the operand class. 1518 for (unsigned i = 0, e = CGA.ResultOperands.size(); i != e; ++i) 1519 if (CGA.ResultOperands[i].isRecord() && 1520 CGA.ResultOperands[i].getName() == OperandName) { 1521 // It's safe to go with the first one we find, because CodeGenInstAlias 1522 // validates that all operands with the same name have the same record. 1523 Op.SubOpIdx = CGA.ResultInstOperandIndex[i].second; 1524 // Use the match class from the Alias definition, not the 1525 // destination instruction, as we may have an immediate that's 1526 // being munged by the match class. 1527 Op.Class = getOperandClass(CGA.ResultOperands[i].getRecord(), 1528 Op.SubOpIdx); 1529 Op.SrcOpName = OperandName; 1530 return; 1531 } 1532 1533 throw TGError(II->TheDef->getLoc(), "error: unable to find operand: '" + 1534 OperandName.str() + "'"); 1535 } 1536 1537 void MatchableInfo::buildInstructionResultOperands() { 1538 const CodeGenInstruction *ResultInst = getResultInst(); 1539 1540 // Loop over all operands of the result instruction, determining how to 1541 // populate them. 1542 for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) { 1543 const CGIOperandList::OperandInfo &OpInfo = ResultInst->Operands[i]; 1544 1545 // If this is a tied operand, just copy from the previously handled operand. 1546 int TiedOp = OpInfo.getTiedRegister(); 1547 if (TiedOp != -1) { 1548 ResOperands.push_back(ResOperand::getTiedOp(TiedOp)); 1549 continue; 1550 } 1551 1552 // Find out what operand from the asmparser this MCInst operand comes from. 1553 int SrcOperand = findAsmOperandNamed(OpInfo.Name); 1554 if (OpInfo.Name.empty() || SrcOperand == -1) 1555 throw TGError(TheDef->getLoc(), "Instruction '" + 1556 TheDef->getName() + "' has operand '" + OpInfo.Name + 1557 "' that doesn't appear in asm string!"); 1558 1559 // Check if the one AsmOperand populates the entire operand. 1560 unsigned NumOperands = OpInfo.MINumOperands; 1561 if (AsmOperands[SrcOperand].SubOpIdx == -1) { 1562 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand, NumOperands)); 1563 continue; 1564 } 1565 1566 // Add a separate ResOperand for each suboperand. 1567 for (unsigned AI = 0; AI < NumOperands; ++AI) { 1568 assert(AsmOperands[SrcOperand+AI].SubOpIdx == (int)AI && 1569 AsmOperands[SrcOperand+AI].SrcOpName == OpInfo.Name && 1570 "unexpected AsmOperands for suboperands"); 1571 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand + AI, 1)); 1572 } 1573 } 1574 } 1575 1576 void MatchableInfo::buildAliasResultOperands() { 1577 const CodeGenInstAlias &CGA = *DefRec.get<const CodeGenInstAlias*>(); 1578 const CodeGenInstruction *ResultInst = getResultInst(); 1579 1580 // Loop over all operands of the result instruction, determining how to 1581 // populate them. 1582 unsigned AliasOpNo = 0; 1583 unsigned LastOpNo = CGA.ResultInstOperandIndex.size(); 1584 for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) { 1585 const CGIOperandList::OperandInfo *OpInfo = &ResultInst->Operands[i]; 1586 1587 // If this is a tied operand, just copy from the previously handled operand. 1588 int TiedOp = OpInfo->getTiedRegister(); 1589 if (TiedOp != -1) { 1590 ResOperands.push_back(ResOperand::getTiedOp(TiedOp)); 1591 continue; 1592 } 1593 1594 // Handle all the suboperands for this operand. 1595 const std::string &OpName = OpInfo->Name; 1596 for ( ; AliasOpNo < LastOpNo && 1597 CGA.ResultInstOperandIndex[AliasOpNo].first == i; ++AliasOpNo) { 1598 int SubIdx = CGA.ResultInstOperandIndex[AliasOpNo].second; 1599 1600 // Find out what operand from the asmparser that this MCInst operand 1601 // comes from. 1602 switch (CGA.ResultOperands[AliasOpNo].Kind) { 1603 case CodeGenInstAlias::ResultOperand::K_Record: { 1604 StringRef Name = CGA.ResultOperands[AliasOpNo].getName(); 1605 int SrcOperand = findAsmOperand(Name, SubIdx); 1606 if (SrcOperand == -1) 1607 throw TGError(TheDef->getLoc(), "Instruction '" + 1608 TheDef->getName() + "' has operand '" + OpName + 1609 "' that doesn't appear in asm string!"); 1610 unsigned NumOperands = (SubIdx == -1 ? OpInfo->MINumOperands : 1); 1611 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand, 1612 NumOperands)); 1613 break; 1614 } 1615 case CodeGenInstAlias::ResultOperand::K_Imm: { 1616 int64_t ImmVal = CGA.ResultOperands[AliasOpNo].getImm(); 1617 ResOperands.push_back(ResOperand::getImmOp(ImmVal)); 1618 break; 1619 } 1620 case CodeGenInstAlias::ResultOperand::K_Reg: { 1621 Record *Reg = CGA.ResultOperands[AliasOpNo].getRegister(); 1622 ResOperands.push_back(ResOperand::getRegOp(Reg)); 1623 break; 1624 } 1625 } 1626 } 1627 } 1628 } 1629 1630 static void emitConvertToMCInst(CodeGenTarget &Target, StringRef ClassName, 1631 std::vector<MatchableInfo*> &Infos, 1632 raw_ostream &OS) { 1633 // Write the convert function to a separate stream, so we can drop it after 1634 // the enum. 1635 std::string ConvertFnBody; 1636 raw_string_ostream CvtOS(ConvertFnBody); 1637 1638 // Function we have already generated. 1639 std::set<std::string> GeneratedFns; 1640 1641 // Start the unified conversion function. 1642 CvtOS << "bool " << Target.getName() << ClassName << "::\n"; 1643 CvtOS << "ConvertToMCInst(unsigned Kind, MCInst &Inst, " 1644 << "unsigned Opcode,\n" 1645 << " const SmallVectorImpl<MCParsedAsmOperand*" 1646 << "> &Operands) {\n"; 1647 CvtOS << " Inst.setOpcode(Opcode);\n"; 1648 CvtOS << " switch (Kind) {\n"; 1649 CvtOS << " default:\n"; 1650 1651 // Start the enum, which we will generate inline. 1652 1653 OS << "// Unified function for converting operands to MCInst instances.\n\n"; 1654 OS << "enum ConversionKind {\n"; 1655 1656 // TargetOperandClass - This is the target's operand class, like X86Operand. 1657 std::string TargetOperandClass = Target.getName() + "Operand"; 1658 1659 for (std::vector<MatchableInfo*>::const_iterator it = Infos.begin(), 1660 ie = Infos.end(); it != ie; ++it) { 1661 MatchableInfo &II = **it; 1662 1663 // Check if we have a custom match function. 1664 std::string AsmMatchConverter = 1665 II.getResultInst()->TheDef->getValueAsString("AsmMatchConverter"); 1666 if (!AsmMatchConverter.empty()) { 1667 std::string Signature = "ConvertCustom_" + AsmMatchConverter; 1668 II.ConversionFnKind = Signature; 1669 1670 // Check if we have already generated this signature. 1671 if (!GeneratedFns.insert(Signature).second) 1672 continue; 1673 1674 // If not, emit it now. Add to the enum list. 1675 OS << " " << Signature << ",\n"; 1676 1677 CvtOS << " case " << Signature << ":\n"; 1678 CvtOS << " return " << AsmMatchConverter 1679 << "(Inst, Opcode, Operands);\n"; 1680 continue; 1681 } 1682 1683 // Build the conversion function signature. 1684 std::string Signature = "Convert"; 1685 std::string CaseBody; 1686 raw_string_ostream CaseOS(CaseBody); 1687 1688 // Compute the convert enum and the case body. 1689 for (unsigned i = 0, e = II.ResOperands.size(); i != e; ++i) { 1690 const MatchableInfo::ResOperand &OpInfo = II.ResOperands[i]; 1691 1692 // Generate code to populate each result operand. 1693 switch (OpInfo.Kind) { 1694 case MatchableInfo::ResOperand::RenderAsmOperand: { 1695 // This comes from something we parsed. 1696 MatchableInfo::AsmOperand &Op = II.AsmOperands[OpInfo.AsmOperandNum]; 1697 1698 // Registers are always converted the same, don't duplicate the 1699 // conversion function based on them. 1700 Signature += "__"; 1701 if (Op.Class->isRegisterClass()) 1702 Signature += "Reg"; 1703 else 1704 Signature += Op.Class->ClassName; 1705 Signature += utostr(OpInfo.MINumOperands); 1706 Signature += "_" + itostr(OpInfo.AsmOperandNum); 1707 1708 CaseOS << " ((" << TargetOperandClass << "*)Operands[" 1709 << (OpInfo.AsmOperandNum+1) << "])->" << Op.Class->RenderMethod 1710 << "(Inst, " << OpInfo.MINumOperands << ");\n"; 1711 break; 1712 } 1713 1714 case MatchableInfo::ResOperand::TiedOperand: { 1715 // If this operand is tied to a previous one, just copy the MCInst 1716 // operand from the earlier one.We can only tie single MCOperand values. 1717 //assert(OpInfo.MINumOperands == 1 && "Not a singular MCOperand"); 1718 unsigned TiedOp = OpInfo.TiedOperandNum; 1719 assert(i > TiedOp && "Tied operand precedes its target!"); 1720 CaseOS << " Inst.addOperand(Inst.getOperand(" << TiedOp << "));\n"; 1721 Signature += "__Tie" + utostr(TiedOp); 1722 break; 1723 } 1724 case MatchableInfo::ResOperand::ImmOperand: { 1725 int64_t Val = OpInfo.ImmVal; 1726 CaseOS << " Inst.addOperand(MCOperand::CreateImm(" << Val << "));\n"; 1727 Signature += "__imm" + itostr(Val); 1728 break; 1729 } 1730 case MatchableInfo::ResOperand::RegOperand: { 1731 if (OpInfo.Register == 0) { 1732 CaseOS << " Inst.addOperand(MCOperand::CreateReg(0));\n"; 1733 Signature += "__reg0"; 1734 } else { 1735 std::string N = getQualifiedName(OpInfo.Register); 1736 CaseOS << " Inst.addOperand(MCOperand::CreateReg(" << N << "));\n"; 1737 Signature += "__reg" + OpInfo.Register->getName(); 1738 } 1739 } 1740 } 1741 } 1742 1743 II.ConversionFnKind = Signature; 1744 1745 // Check if we have already generated this signature. 1746 if (!GeneratedFns.insert(Signature).second) 1747 continue; 1748 1749 // If not, emit it now. Add to the enum list. 1750 OS << " " << Signature << ",\n"; 1751 1752 CvtOS << " case " << Signature << ":\n"; 1753 CvtOS << CaseOS.str(); 1754 CvtOS << " return true;\n"; 1755 } 1756 1757 // Finish the convert function. 1758 1759 CvtOS << " }\n"; 1760 CvtOS << " return false;\n"; 1761 CvtOS << "}\n\n"; 1762 1763 // Finish the enum, and drop the convert function after it. 1764 1765 OS << " NumConversionVariants\n"; 1766 OS << "};\n\n"; 1767 1768 OS << CvtOS.str(); 1769 } 1770 1771 /// emitMatchClassEnumeration - Emit the enumeration for match class kinds. 1772 static void emitMatchClassEnumeration(CodeGenTarget &Target, 1773 std::vector<ClassInfo*> &Infos, 1774 raw_ostream &OS) { 1775 OS << "namespace {\n\n"; 1776 1777 OS << "/// MatchClassKind - The kinds of classes which participate in\n" 1778 << "/// instruction matching.\n"; 1779 OS << "enum MatchClassKind {\n"; 1780 OS << " InvalidMatchClass = 0,\n"; 1781 for (std::vector<ClassInfo*>::iterator it = Infos.begin(), 1782 ie = Infos.end(); it != ie; ++it) { 1783 ClassInfo &CI = **it; 1784 OS << " " << CI.Name << ", // "; 1785 if (CI.Kind == ClassInfo::Token) { 1786 OS << "'" << CI.ValueName << "'\n"; 1787 } else if (CI.isRegisterClass()) { 1788 if (!CI.ValueName.empty()) 1789 OS << "register class '" << CI.ValueName << "'\n"; 1790 else 1791 OS << "derived register class\n"; 1792 } else { 1793 OS << "user defined class '" << CI.ValueName << "'\n"; 1794 } 1795 } 1796 OS << " NumMatchClassKinds\n"; 1797 OS << "};\n\n"; 1798 1799 OS << "}\n\n"; 1800 } 1801 1802 /// emitValidateOperandClass - Emit the function to validate an operand class. 1803 static void emitValidateOperandClass(AsmMatcherInfo &Info, 1804 raw_ostream &OS) { 1805 OS << "static bool validateOperandClass(MCParsedAsmOperand *GOp, " 1806 << "MatchClassKind Kind) {\n"; 1807 OS << " " << Info.Target.getName() << "Operand &Operand = *(" 1808 << Info.Target.getName() << "Operand*)GOp;\n"; 1809 1810 // The InvalidMatchClass is not to match any operand. 1811 OS << " if (Kind == InvalidMatchClass)\n"; 1812 OS << " return false;\n\n"; 1813 1814 // Check for Token operands first. 1815 OS << " if (Operand.isToken())\n"; 1816 OS << " return isSubclass(matchTokenString(Operand.getToken()), Kind);" 1817 << "\n\n"; 1818 1819 // Check for register operands, including sub-classes. 1820 OS << " if (Operand.isReg()) {\n"; 1821 OS << " MatchClassKind OpKind;\n"; 1822 OS << " switch (Operand.getReg()) {\n"; 1823 OS << " default: OpKind = InvalidMatchClass; break;\n"; 1824 for (std::map<Record*, ClassInfo*>::iterator 1825 it = Info.RegisterClasses.begin(), ie = Info.RegisterClasses.end(); 1826 it != ie; ++it) 1827 OS << " case " << Info.Target.getName() << "::" 1828 << it->first->getName() << ": OpKind = " << it->second->Name 1829 << "; break;\n"; 1830 OS << " }\n"; 1831 OS << " return isSubclass(OpKind, Kind);\n"; 1832 OS << " }\n\n"; 1833 1834 // Check the user classes. We don't care what order since we're only 1835 // actually matching against one of them. 1836 for (std::vector<ClassInfo*>::iterator it = Info.Classes.begin(), 1837 ie = Info.Classes.end(); it != ie; ++it) { 1838 ClassInfo &CI = **it; 1839 1840 if (!CI.isUserClass()) 1841 continue; 1842 1843 OS << " // '" << CI.ClassName << "' class\n"; 1844 OS << " if (Kind == " << CI.Name 1845 << " && Operand." << CI.PredicateMethod << "()) {\n"; 1846 OS << " return true;\n"; 1847 OS << " }\n\n"; 1848 } 1849 1850 OS << " return false;\n"; 1851 OS << "}\n\n"; 1852 } 1853 1854 /// emitIsSubclass - Emit the subclass predicate function. 1855 static void emitIsSubclass(CodeGenTarget &Target, 1856 std::vector<ClassInfo*> &Infos, 1857 raw_ostream &OS) { 1858 OS << "/// isSubclass - Compute whether \\arg A is a subclass of \\arg B.\n"; 1859 OS << "static bool isSubclass(MatchClassKind A, MatchClassKind B) {\n"; 1860 OS << " if (A == B)\n"; 1861 OS << " return true;\n\n"; 1862 1863 OS << " switch (A) {\n"; 1864 OS << " default:\n"; 1865 OS << " return false;\n"; 1866 for (std::vector<ClassInfo*>::iterator it = Infos.begin(), 1867 ie = Infos.end(); it != ie; ++it) { 1868 ClassInfo &A = **it; 1869 1870 std::vector<StringRef> SuperClasses; 1871 for (std::vector<ClassInfo*>::iterator it = Infos.begin(), 1872 ie = Infos.end(); it != ie; ++it) { 1873 ClassInfo &B = **it; 1874 1875 if (&A != &B && A.isSubsetOf(B)) 1876 SuperClasses.push_back(B.Name); 1877 } 1878 1879 if (SuperClasses.empty()) 1880 continue; 1881 1882 OS << "\n case " << A.Name << ":\n"; 1883 1884 if (SuperClasses.size() == 1) { 1885 OS << " return B == " << SuperClasses.back() << ";\n"; 1886 continue; 1887 } 1888 1889 OS << " switch (B) {\n"; 1890 OS << " default: return false;\n"; 1891 for (unsigned i = 0, e = SuperClasses.size(); i != e; ++i) 1892 OS << " case " << SuperClasses[i] << ": return true;\n"; 1893 OS << " }\n"; 1894 } 1895 OS << " }\n"; 1896 OS << "}\n\n"; 1897 } 1898 1899 /// emitMatchTokenString - Emit the function to match a token string to the 1900 /// appropriate match class value. 1901 static void emitMatchTokenString(CodeGenTarget &Target, 1902 std::vector<ClassInfo*> &Infos, 1903 raw_ostream &OS) { 1904 // Construct the match list. 1905 std::vector<StringMatcher::StringPair> Matches; 1906 for (std::vector<ClassInfo*>::iterator it = Infos.begin(), 1907 ie = Infos.end(); it != ie; ++it) { 1908 ClassInfo &CI = **it; 1909 1910 if (CI.Kind == ClassInfo::Token) 1911 Matches.push_back(StringMatcher::StringPair(CI.ValueName, 1912 "return " + CI.Name + ";")); 1913 } 1914 1915 OS << "static MatchClassKind matchTokenString(StringRef Name) {\n"; 1916 1917 StringMatcher("Name", Matches, OS).Emit(); 1918 1919 OS << " return InvalidMatchClass;\n"; 1920 OS << "}\n\n"; 1921 } 1922 1923 /// emitMatchRegisterName - Emit the function to match a string to the target 1924 /// specific register enum. 1925 static void emitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser, 1926 raw_ostream &OS) { 1927 // Construct the match list. 1928 std::vector<StringMatcher::StringPair> Matches; 1929 const std::vector<CodeGenRegister*> &Regs = 1930 Target.getRegBank().getRegisters(); 1931 for (unsigned i = 0, e = Regs.size(); i != e; ++i) { 1932 const CodeGenRegister *Reg = Regs[i]; 1933 if (Reg->TheDef->getValueAsString("AsmName").empty()) 1934 continue; 1935 1936 Matches.push_back(StringMatcher::StringPair( 1937 Reg->TheDef->getValueAsString("AsmName"), 1938 "return " + utostr(Reg->EnumValue) + ";")); 1939 } 1940 1941 OS << "static unsigned MatchRegisterName(StringRef Name) {\n"; 1942 1943 StringMatcher("Name", Matches, OS).Emit(); 1944 1945 OS << " return 0;\n"; 1946 OS << "}\n\n"; 1947 } 1948 1949 /// emitSubtargetFeatureFlagEnumeration - Emit the subtarget feature flag 1950 /// definitions. 1951 static void emitSubtargetFeatureFlagEnumeration(AsmMatcherInfo &Info, 1952 raw_ostream &OS) { 1953 OS << "// Flags for subtarget features that participate in " 1954 << "instruction matching.\n"; 1955 OS << "enum SubtargetFeatureFlag {\n"; 1956 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator 1957 it = Info.SubtargetFeatures.begin(), 1958 ie = Info.SubtargetFeatures.end(); it != ie; ++it) { 1959 SubtargetFeatureInfo &SFI = *it->second; 1960 OS << " " << SFI.getEnumName() << " = (1 << " << SFI.Index << "),\n"; 1961 } 1962 OS << " Feature_None = 0\n"; 1963 OS << "};\n\n"; 1964 } 1965 1966 /// emitGetSubtargetFeatureName - Emit the helper function to get the 1967 /// user-level name for a subtarget feature. 1968 static void emitGetSubtargetFeatureName(AsmMatcherInfo &Info, raw_ostream &OS) { 1969 OS << "// User-level names for subtarget features that participate in\n" 1970 << "// instruction matching.\n" 1971 << "static const char *getSubtargetFeatureName(unsigned Val) {\n" 1972 << " switch(Val) {\n"; 1973 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator 1974 it = Info.SubtargetFeatures.begin(), 1975 ie = Info.SubtargetFeatures.end(); it != ie; ++it) { 1976 SubtargetFeatureInfo &SFI = *it->second; 1977 // FIXME: Totally just a placeholder name to get the algorithm working. 1978 OS << " case " << SFI.getEnumName() << ": return \"" 1979 << SFI.TheDef->getValueAsString("PredicateName") << "\";\n"; 1980 } 1981 OS << " default: return \"(unknown)\";\n"; 1982 OS << " }\n}\n\n"; 1983 } 1984 1985 /// emitComputeAvailableFeatures - Emit the function to compute the list of 1986 /// available features given a subtarget. 1987 static void emitComputeAvailableFeatures(AsmMatcherInfo &Info, 1988 raw_ostream &OS) { 1989 std::string ClassName = 1990 Info.AsmParser->getValueAsString("AsmParserClassName"); 1991 1992 OS << "unsigned " << Info.Target.getName() << ClassName << "::\n" 1993 << "ComputeAvailableFeatures(uint64_t FB) const {\n"; 1994 OS << " unsigned Features = 0;\n"; 1995 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator 1996 it = Info.SubtargetFeatures.begin(), 1997 ie = Info.SubtargetFeatures.end(); it != ie; ++it) { 1998 SubtargetFeatureInfo &SFI = *it->second; 1999 2000 OS << " if ("; 2001 std::string CondStorage = 2002 SFI.TheDef->getValueAsString("AssemblerCondString"); 2003 StringRef Conds = CondStorage; 2004 std::pair<StringRef,StringRef> Comma = Conds.split(','); 2005 bool First = true; 2006 do { 2007 if (!First) 2008 OS << " && "; 2009 2010 bool Neg = false; 2011 StringRef Cond = Comma.first; 2012 if (Cond[0] == '!') { 2013 Neg = true; 2014 Cond = Cond.substr(1); 2015 } 2016 2017 OS << "((FB & " << Info.Target.getName() << "::" << Cond << ")"; 2018 if (Neg) 2019 OS << " == 0"; 2020 else 2021 OS << " != 0"; 2022 OS << ")"; 2023 2024 if (Comma.second.empty()) 2025 break; 2026 2027 First = false; 2028 Comma = Comma.second.split(','); 2029 } while (true); 2030 2031 OS << ")\n"; 2032 OS << " Features |= " << SFI.getEnumName() << ";\n"; 2033 } 2034 OS << " return Features;\n"; 2035 OS << "}\n\n"; 2036 } 2037 2038 static std::string GetAliasRequiredFeatures(Record *R, 2039 const AsmMatcherInfo &Info) { 2040 std::vector<Record*> ReqFeatures = R->getValueAsListOfDefs("Predicates"); 2041 std::string Result; 2042 unsigned NumFeatures = 0; 2043 for (unsigned i = 0, e = ReqFeatures.size(); i != e; ++i) { 2044 SubtargetFeatureInfo *F = Info.getSubtargetFeature(ReqFeatures[i]); 2045 2046 if (F == 0) 2047 throw TGError(R->getLoc(), "Predicate '" + ReqFeatures[i]->getName() + 2048 "' is not marked as an AssemblerPredicate!"); 2049 2050 if (NumFeatures) 2051 Result += '|'; 2052 2053 Result += F->getEnumName(); 2054 ++NumFeatures; 2055 } 2056 2057 if (NumFeatures > 1) 2058 Result = '(' + Result + ')'; 2059 return Result; 2060 } 2061 2062 /// emitMnemonicAliases - If the target has any MnemonicAlias<> definitions, 2063 /// emit a function for them and return true, otherwise return false. 2064 static bool emitMnemonicAliases(raw_ostream &OS, const AsmMatcherInfo &Info) { 2065 // Ignore aliases when match-prefix is set. 2066 if (!MatchPrefix.empty()) 2067 return false; 2068 2069 std::vector<Record*> Aliases = 2070 Info.getRecords().getAllDerivedDefinitions("MnemonicAlias"); 2071 if (Aliases.empty()) return false; 2072 2073 OS << "static void applyMnemonicAliases(StringRef &Mnemonic, " 2074 "unsigned Features) {\n"; 2075 2076 // Keep track of all the aliases from a mnemonic. Use an std::map so that the 2077 // iteration order of the map is stable. 2078 std::map<std::string, std::vector<Record*> > AliasesFromMnemonic; 2079 2080 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) { 2081 Record *R = Aliases[i]; 2082 AliasesFromMnemonic[R->getValueAsString("FromMnemonic")].push_back(R); 2083 } 2084 2085 // Process each alias a "from" mnemonic at a time, building the code executed 2086 // by the string remapper. 2087 std::vector<StringMatcher::StringPair> Cases; 2088 for (std::map<std::string, std::vector<Record*> >::iterator 2089 I = AliasesFromMnemonic.begin(), E = AliasesFromMnemonic.end(); 2090 I != E; ++I) { 2091 const std::vector<Record*> &ToVec = I->second; 2092 2093 // Loop through each alias and emit code that handles each case. If there 2094 // are two instructions without predicates, emit an error. If there is one, 2095 // emit it last. 2096 std::string MatchCode; 2097 int AliasWithNoPredicate = -1; 2098 2099 for (unsigned i = 0, e = ToVec.size(); i != e; ++i) { 2100 Record *R = ToVec[i]; 2101 std::string FeatureMask = GetAliasRequiredFeatures(R, Info); 2102 2103 // If this unconditionally matches, remember it for later and diagnose 2104 // duplicates. 2105 if (FeatureMask.empty()) { 2106 if (AliasWithNoPredicate != -1) { 2107 // We can't have two aliases from the same mnemonic with no predicate. 2108 PrintError(ToVec[AliasWithNoPredicate]->getLoc(), 2109 "two MnemonicAliases with the same 'from' mnemonic!"); 2110 throw TGError(R->getLoc(), "this is the other MnemonicAlias."); 2111 } 2112 2113 AliasWithNoPredicate = i; 2114 continue; 2115 } 2116 if (R->getValueAsString("ToMnemonic") == I->first) 2117 throw TGError(R->getLoc(), "MnemonicAlias to the same string"); 2118 2119 if (!MatchCode.empty()) 2120 MatchCode += "else "; 2121 MatchCode += "if ((Features & " + FeatureMask + ") == "+FeatureMask+")\n"; 2122 MatchCode += " Mnemonic = \"" +R->getValueAsString("ToMnemonic")+"\";\n"; 2123 } 2124 2125 if (AliasWithNoPredicate != -1) { 2126 Record *R = ToVec[AliasWithNoPredicate]; 2127 if (!MatchCode.empty()) 2128 MatchCode += "else\n "; 2129 MatchCode += "Mnemonic = \"" + R->getValueAsString("ToMnemonic")+"\";\n"; 2130 } 2131 2132 MatchCode += "return;"; 2133 2134 Cases.push_back(std::make_pair(I->first, MatchCode)); 2135 } 2136 2137 StringMatcher("Mnemonic", Cases, OS).Emit(); 2138 OS << "}\n\n"; 2139 2140 return true; 2141 } 2142 2143 static const char *getMinimalTypeForRange(uint64_t Range) { 2144 assert(Range < 0xFFFFFFFFULL && "Enum too large"); 2145 if (Range > 0xFFFF) 2146 return "uint32_t"; 2147 if (Range > 0xFF) 2148 return "uint16_t"; 2149 return "uint8_t"; 2150 } 2151 2152 static void emitCustomOperandParsing(raw_ostream &OS, CodeGenTarget &Target, 2153 const AsmMatcherInfo &Info, StringRef ClassName) { 2154 // Emit the static custom operand parsing table; 2155 OS << "namespace {\n"; 2156 OS << " struct OperandMatchEntry {\n"; 2157 OS << " static const char *const MnemonicTable;\n"; 2158 OS << " uint32_t OperandMask;\n"; 2159 OS << " uint32_t Mnemonic;\n"; 2160 OS << " " << getMinimalTypeForRange(1ULL << Info.SubtargetFeatures.size()) 2161 << " RequiredFeatures;\n"; 2162 OS << " " << getMinimalTypeForRange(Info.Classes.size()) 2163 << " Class;\n\n"; 2164 OS << " StringRef getMnemonic() const {\n"; 2165 OS << " return StringRef(MnemonicTable + Mnemonic + 1,\n"; 2166 OS << " MnemonicTable[Mnemonic]);\n"; 2167 OS << " }\n"; 2168 OS << " };\n\n"; 2169 2170 OS << " // Predicate for searching for an opcode.\n"; 2171 OS << " struct LessOpcodeOperand {\n"; 2172 OS << " bool operator()(const OperandMatchEntry &LHS, StringRef RHS) {\n"; 2173 OS << " return LHS.getMnemonic() < RHS;\n"; 2174 OS << " }\n"; 2175 OS << " bool operator()(StringRef LHS, const OperandMatchEntry &RHS) {\n"; 2176 OS << " return LHS < RHS.getMnemonic();\n"; 2177 OS << " }\n"; 2178 OS << " bool operator()(const OperandMatchEntry &LHS,"; 2179 OS << " const OperandMatchEntry &RHS) {\n"; 2180 OS << " return LHS.getMnemonic() < RHS.getMnemonic();\n"; 2181 OS << " }\n"; 2182 OS << " };\n"; 2183 2184 OS << "} // end anonymous namespace.\n\n"; 2185 2186 StringToOffsetTable StringTable; 2187 2188 OS << "static const OperandMatchEntry OperandMatchTable[" 2189 << Info.OperandMatchInfo.size() << "] = {\n"; 2190 2191 OS << " /* Operand List Mask, Mnemonic, Operand Class, Features */\n"; 2192 for (std::vector<OperandMatchEntry>::const_iterator it = 2193 Info.OperandMatchInfo.begin(), ie = Info.OperandMatchInfo.end(); 2194 it != ie; ++it) { 2195 const OperandMatchEntry &OMI = *it; 2196 const MatchableInfo &II = *OMI.MI; 2197 2198 OS << " { " << OMI.OperandMask; 2199 2200 OS << " /* "; 2201 bool printComma = false; 2202 for (int i = 0, e = 31; i !=e; ++i) 2203 if (OMI.OperandMask & (1 << i)) { 2204 if (printComma) 2205 OS << ", "; 2206 OS << i; 2207 printComma = true; 2208 } 2209 OS << " */"; 2210 2211 // Store a pascal-style length byte in the mnemonic. 2212 std::string LenMnemonic = char(II.Mnemonic.size()) + II.Mnemonic.str(); 2213 OS << ", " << StringTable.GetOrAddStringOffset(LenMnemonic, false) 2214 << " /* " << II.Mnemonic << " */, "; 2215 2216 // Write the required features mask. 2217 if (!II.RequiredFeatures.empty()) { 2218 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) { 2219 if (i) OS << "|"; 2220 OS << II.RequiredFeatures[i]->getEnumName(); 2221 } 2222 } else 2223 OS << "0"; 2224 2225 OS << ", " << OMI.CI->Name; 2226 2227 OS << " },\n"; 2228 } 2229 OS << "};\n\n"; 2230 2231 OS << "const char *const OperandMatchEntry::MnemonicTable =\n"; 2232 StringTable.EmitString(OS); 2233 OS << ";\n\n"; 2234 2235 // Emit the operand class switch to call the correct custom parser for 2236 // the found operand class. 2237 OS << Target.getName() << ClassName << "::OperandMatchResultTy " 2238 << Target.getName() << ClassName << "::\n" 2239 << "tryCustomParseOperand(SmallVectorImpl<MCParsedAsmOperand*>" 2240 << " &Operands,\n unsigned MCK) {\n\n" 2241 << " switch(MCK) {\n"; 2242 2243 for (std::vector<ClassInfo*>::const_iterator it = Info.Classes.begin(), 2244 ie = Info.Classes.end(); it != ie; ++it) { 2245 ClassInfo *CI = *it; 2246 if (CI->ParserMethod.empty()) 2247 continue; 2248 OS << " case " << CI->Name << ":\n" 2249 << " return " << CI->ParserMethod << "(Operands);\n"; 2250 } 2251 2252 OS << " default:\n"; 2253 OS << " return MatchOperand_NoMatch;\n"; 2254 OS << " }\n"; 2255 OS << " return MatchOperand_NoMatch;\n"; 2256 OS << "}\n\n"; 2257 2258 // Emit the static custom operand parser. This code is very similar with 2259 // the other matcher. Also use MatchResultTy here just in case we go for 2260 // a better error handling. 2261 OS << Target.getName() << ClassName << "::OperandMatchResultTy " 2262 << Target.getName() << ClassName << "::\n" 2263 << "MatchOperandParserImpl(SmallVectorImpl<MCParsedAsmOperand*>" 2264 << " &Operands,\n StringRef Mnemonic) {\n"; 2265 2266 // Emit code to get the available features. 2267 OS << " // Get the current feature set.\n"; 2268 OS << " unsigned AvailableFeatures = getAvailableFeatures();\n\n"; 2269 2270 OS << " // Get the next operand index.\n"; 2271 OS << " unsigned NextOpNum = Operands.size()-1;\n"; 2272 2273 // Emit code to search the table. 2274 OS << " // Search the table.\n"; 2275 OS << " std::pair<const OperandMatchEntry*, const OperandMatchEntry*>"; 2276 OS << " MnemonicRange =\n"; 2277 OS << " std::equal_range(OperandMatchTable, OperandMatchTable+" 2278 << Info.OperandMatchInfo.size() << ", Mnemonic,\n" 2279 << " LessOpcodeOperand());\n\n"; 2280 2281 OS << " if (MnemonicRange.first == MnemonicRange.second)\n"; 2282 OS << " return MatchOperand_NoMatch;\n\n"; 2283 2284 OS << " for (const OperandMatchEntry *it = MnemonicRange.first,\n" 2285 << " *ie = MnemonicRange.second; it != ie; ++it) {\n"; 2286 2287 OS << " // equal_range guarantees that instruction mnemonic matches.\n"; 2288 OS << " assert(Mnemonic == it->getMnemonic());\n\n"; 2289 2290 // Emit check that the required features are available. 2291 OS << " // check if the available features match\n"; 2292 OS << " if ((AvailableFeatures & it->RequiredFeatures) " 2293 << "!= it->RequiredFeatures) {\n"; 2294 OS << " continue;\n"; 2295 OS << " }\n\n"; 2296 2297 // Emit check to ensure the operand number matches. 2298 OS << " // check if the operand in question has a custom parser.\n"; 2299 OS << " if (!(it->OperandMask & (1 << NextOpNum)))\n"; 2300 OS << " continue;\n\n"; 2301 2302 // Emit call to the custom parser method 2303 OS << " // call custom parse method to handle the operand\n"; 2304 OS << " OperandMatchResultTy Result = "; 2305 OS << "tryCustomParseOperand(Operands, it->Class);\n"; 2306 OS << " if (Result != MatchOperand_NoMatch)\n"; 2307 OS << " return Result;\n"; 2308 OS << " }\n\n"; 2309 2310 OS << " // Okay, we had no match.\n"; 2311 OS << " return MatchOperand_NoMatch;\n"; 2312 OS << "}\n\n"; 2313 } 2314 2315 void AsmMatcherEmitter::run(raw_ostream &OS) { 2316 CodeGenTarget Target(Records); 2317 Record *AsmParser = Target.getAsmParser(); 2318 std::string ClassName = AsmParser->getValueAsString("AsmParserClassName"); 2319 2320 // Compute the information on the instructions to match. 2321 AsmMatcherInfo Info(AsmParser, Target, Records); 2322 Info.buildInfo(); 2323 2324 // Sort the instruction table using the partial order on classes. We use 2325 // stable_sort to ensure that ambiguous instructions are still 2326 // deterministically ordered. 2327 std::stable_sort(Info.Matchables.begin(), Info.Matchables.end(), 2328 less_ptr<MatchableInfo>()); 2329 2330 DEBUG_WITH_TYPE("instruction_info", { 2331 for (std::vector<MatchableInfo*>::iterator 2332 it = Info.Matchables.begin(), ie = Info.Matchables.end(); 2333 it != ie; ++it) 2334 (*it)->dump(); 2335 }); 2336 2337 // Check for ambiguous matchables. 2338 DEBUG_WITH_TYPE("ambiguous_instrs", { 2339 unsigned NumAmbiguous = 0; 2340 for (unsigned i = 0, e = Info.Matchables.size(); i != e; ++i) { 2341 for (unsigned j = i + 1; j != e; ++j) { 2342 MatchableInfo &A = *Info.Matchables[i]; 2343 MatchableInfo &B = *Info.Matchables[j]; 2344 2345 if (A.couldMatchAmbiguouslyWith(B)) { 2346 errs() << "warning: ambiguous matchables:\n"; 2347 A.dump(); 2348 errs() << "\nis incomparable with:\n"; 2349 B.dump(); 2350 errs() << "\n\n"; 2351 ++NumAmbiguous; 2352 } 2353 } 2354 } 2355 if (NumAmbiguous) 2356 errs() << "warning: " << NumAmbiguous 2357 << " ambiguous matchables!\n"; 2358 }); 2359 2360 // Compute the information on the custom operand parsing. 2361 Info.buildOperandMatchInfo(); 2362 2363 // Write the output. 2364 2365 // Information for the class declaration. 2366 OS << "\n#ifdef GET_ASSEMBLER_HEADER\n"; 2367 OS << "#undef GET_ASSEMBLER_HEADER\n"; 2368 OS << " // This should be included into the middle of the declaration of\n"; 2369 OS << " // your subclasses implementation of MCTargetAsmParser.\n"; 2370 OS << " unsigned ComputeAvailableFeatures(uint64_t FeatureBits) const;\n"; 2371 OS << " bool ConvertToMCInst(unsigned Kind, MCInst &Inst, " 2372 << "unsigned Opcode,\n" 2373 << " const SmallVectorImpl<MCParsedAsmOperand*> " 2374 << "&Operands);\n"; 2375 OS << " bool MnemonicIsValid(StringRef Mnemonic);\n"; 2376 OS << " unsigned MatchInstructionImpl(\n"; 2377 OS << " const SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n"; 2378 OS << " MCInst &Inst, unsigned &ErrorInfo, unsigned VariantID = 0);\n"; 2379 2380 if (Info.OperandMatchInfo.size()) { 2381 OS << "\n enum OperandMatchResultTy {\n"; 2382 OS << " MatchOperand_Success, // operand matched successfully\n"; 2383 OS << " MatchOperand_NoMatch, // operand did not match\n"; 2384 OS << " MatchOperand_ParseFail // operand matched but had errors\n"; 2385 OS << " };\n"; 2386 OS << " OperandMatchResultTy MatchOperandParserImpl(\n"; 2387 OS << " SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n"; 2388 OS << " StringRef Mnemonic);\n"; 2389 2390 OS << " OperandMatchResultTy tryCustomParseOperand(\n"; 2391 OS << " SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n"; 2392 OS << " unsigned MCK);\n\n"; 2393 } 2394 2395 OS << "#endif // GET_ASSEMBLER_HEADER_INFO\n\n"; 2396 2397 OS << "\n#ifdef GET_REGISTER_MATCHER\n"; 2398 OS << "#undef GET_REGISTER_MATCHER\n\n"; 2399 2400 // Emit the subtarget feature enumeration. 2401 emitSubtargetFeatureFlagEnumeration(Info, OS); 2402 2403 // Emit the function to match a register name to number. 2404 emitMatchRegisterName(Target, AsmParser, OS); 2405 2406 OS << "#endif // GET_REGISTER_MATCHER\n\n"; 2407 2408 OS << "\n#ifdef GET_SUBTARGET_FEATURE_NAME\n"; 2409 OS << "#undef GET_SUBTARGET_FEATURE_NAME\n\n"; 2410 2411 // Generate the helper function to get the names for subtarget features. 2412 emitGetSubtargetFeatureName(Info, OS); 2413 2414 OS << "#endif // GET_SUBTARGET_FEATURE_NAME\n\n"; 2415 2416 OS << "\n#ifdef GET_MATCHER_IMPLEMENTATION\n"; 2417 OS << "#undef GET_MATCHER_IMPLEMENTATION\n\n"; 2418 2419 // Generate the function that remaps for mnemonic aliases. 2420 bool HasMnemonicAliases = emitMnemonicAliases(OS, Info); 2421 2422 // Generate the unified function to convert operands into an MCInst. 2423 emitConvertToMCInst(Target, ClassName, Info.Matchables, OS); 2424 2425 // Emit the enumeration for classes which participate in matching. 2426 emitMatchClassEnumeration(Target, Info.Classes, OS); 2427 2428 // Emit the routine to match token strings to their match class. 2429 emitMatchTokenString(Target, Info.Classes, OS); 2430 2431 // Emit the subclass predicate routine. 2432 emitIsSubclass(Target, Info.Classes, OS); 2433 2434 // Emit the routine to validate an operand against a match class. 2435 emitValidateOperandClass(Info, OS); 2436 2437 // Emit the available features compute function. 2438 emitComputeAvailableFeatures(Info, OS); 2439 2440 2441 size_t MaxNumOperands = 0; 2442 for (std::vector<MatchableInfo*>::const_iterator it = 2443 Info.Matchables.begin(), ie = Info.Matchables.end(); 2444 it != ie; ++it) 2445 MaxNumOperands = std::max(MaxNumOperands, (*it)->AsmOperands.size()); 2446 2447 // Emit the static match table; unused classes get initalized to 0 which is 2448 // guaranteed to be InvalidMatchClass. 2449 // 2450 // FIXME: We can reduce the size of this table very easily. First, we change 2451 // it so that store the kinds in separate bit-fields for each index, which 2452 // only needs to be the max width used for classes at that index (we also need 2453 // to reject based on this during classification). If we then make sure to 2454 // order the match kinds appropriately (putting mnemonics last), then we 2455 // should only end up using a few bits for each class, especially the ones 2456 // following the mnemonic. 2457 OS << "namespace {\n"; 2458 OS << " struct MatchEntry {\n"; 2459 OS << " static const char *const MnemonicTable;\n"; 2460 OS << " uint32_t Mnemonic;\n"; 2461 OS << " uint16_t Opcode;\n"; 2462 OS << " " << getMinimalTypeForRange(Info.Matchables.size()) 2463 << " ConvertFn;\n"; 2464 OS << " " << getMinimalTypeForRange(1ULL << Info.SubtargetFeatures.size()) 2465 << " RequiredFeatures;\n"; 2466 OS << " " << getMinimalTypeForRange(Info.Classes.size()) 2467 << " Classes[" << MaxNumOperands << "];\n"; 2468 OS << " uint8_t AsmVariantID;\n\n"; 2469 OS << " StringRef getMnemonic() const {\n"; 2470 OS << " return StringRef(MnemonicTable + Mnemonic + 1,\n"; 2471 OS << " MnemonicTable[Mnemonic]);\n"; 2472 OS << " }\n"; 2473 OS << " };\n\n"; 2474 2475 OS << " // Predicate for searching for an opcode.\n"; 2476 OS << " struct LessOpcode {\n"; 2477 OS << " bool operator()(const MatchEntry &LHS, StringRef RHS) {\n"; 2478 OS << " return LHS.getMnemonic() < RHS;\n"; 2479 OS << " }\n"; 2480 OS << " bool operator()(StringRef LHS, const MatchEntry &RHS) {\n"; 2481 OS << " return LHS < RHS.getMnemonic();\n"; 2482 OS << " }\n"; 2483 OS << " bool operator()(const MatchEntry &LHS, const MatchEntry &RHS) {\n"; 2484 OS << " return LHS.getMnemonic() < RHS.getMnemonic();\n"; 2485 OS << " }\n"; 2486 OS << " };\n"; 2487 2488 OS << "} // end anonymous namespace.\n\n"; 2489 2490 StringToOffsetTable StringTable; 2491 2492 OS << "static const MatchEntry MatchTable[" 2493 << Info.Matchables.size() << "] = {\n"; 2494 2495 for (std::vector<MatchableInfo*>::const_iterator it = 2496 Info.Matchables.begin(), ie = Info.Matchables.end(); 2497 it != ie; ++it) { 2498 MatchableInfo &II = **it; 2499 2500 // Store a pascal-style length byte in the mnemonic. 2501 std::string LenMnemonic = char(II.Mnemonic.size()) + II.Mnemonic.str(); 2502 OS << " { " << StringTable.GetOrAddStringOffset(LenMnemonic, false) 2503 << " /* " << II.Mnemonic << " */, " 2504 << Target.getName() << "::" 2505 << II.getResultInst()->TheDef->getName() << ", " 2506 << II.ConversionFnKind << ", "; 2507 2508 // Write the required features mask. 2509 if (!II.RequiredFeatures.empty()) { 2510 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) { 2511 if (i) OS << "|"; 2512 OS << II.RequiredFeatures[i]->getEnumName(); 2513 } 2514 } else 2515 OS << "0"; 2516 2517 OS << ", { "; 2518 for (unsigned i = 0, e = II.AsmOperands.size(); i != e; ++i) { 2519 MatchableInfo::AsmOperand &Op = II.AsmOperands[i]; 2520 2521 if (i) OS << ", "; 2522 OS << Op.Class->Name; 2523 } 2524 OS << " }, " << II.AsmVariantID; 2525 OS << "},\n"; 2526 } 2527 2528 OS << "};\n\n"; 2529 2530 OS << "const char *const MatchEntry::MnemonicTable =\n"; 2531 StringTable.EmitString(OS); 2532 OS << ";\n\n"; 2533 2534 // A method to determine if a mnemonic is in the list. 2535 OS << "bool " << Target.getName() << ClassName << "::\n" 2536 << "MnemonicIsValid(StringRef Mnemonic) {\n"; 2537 OS << " // Search the table.\n"; 2538 OS << " std::pair<const MatchEntry*, const MatchEntry*> MnemonicRange =\n"; 2539 OS << " std::equal_range(MatchTable, MatchTable+" 2540 << Info.Matchables.size() << ", Mnemonic, LessOpcode());\n"; 2541 OS << " return MnemonicRange.first != MnemonicRange.second;\n"; 2542 OS << "}\n\n"; 2543 2544 // Finally, build the match function. 2545 OS << "unsigned " 2546 << Target.getName() << ClassName << "::\n" 2547 << "MatchInstructionImpl(const SmallVectorImpl<MCParsedAsmOperand*>" 2548 << " &Operands,\n"; 2549 OS << " MCInst &Inst, unsigned &ErrorInfo, "; 2550 OS << "unsigned VariantID) {\n"; 2551 2552 // Emit code to get the available features. 2553 OS << " // Get the current feature set.\n"; 2554 OS << " unsigned AvailableFeatures = getAvailableFeatures();\n\n"; 2555 2556 OS << " // Get the instruction mnemonic, which is the first token.\n"; 2557 OS << " StringRef Mnemonic = ((" << Target.getName() 2558 << "Operand*)Operands[0])->getToken();\n\n"; 2559 2560 if (HasMnemonicAliases) { 2561 OS << " // Process all MnemonicAliases to remap the mnemonic.\n"; 2562 OS << " // FIXME : Add an entry in AsmParserVariant to check this.\n"; 2563 OS << " if (!VariantID)\n"; 2564 OS << " applyMnemonicAliases(Mnemonic, AvailableFeatures);\n\n"; 2565 } 2566 2567 // Emit code to compute the class list for this operand vector. 2568 OS << " // Eliminate obvious mismatches.\n"; 2569 OS << " if (Operands.size() > " << (MaxNumOperands+1) << ") {\n"; 2570 OS << " ErrorInfo = " << (MaxNumOperands+1) << ";\n"; 2571 OS << " return Match_InvalidOperand;\n"; 2572 OS << " }\n\n"; 2573 2574 OS << " // Some state to try to produce better error messages.\n"; 2575 OS << " bool HadMatchOtherThanFeatures = false;\n"; 2576 OS << " bool HadMatchOtherThanPredicate = false;\n"; 2577 OS << " unsigned RetCode = Match_InvalidOperand;\n"; 2578 OS << " // Set ErrorInfo to the operand that mismatches if it is\n"; 2579 OS << " // wrong for all instances of the instruction.\n"; 2580 OS << " ErrorInfo = ~0U;\n"; 2581 2582 // Emit code to search the table. 2583 OS << " // Search the table.\n"; 2584 OS << " std::pair<const MatchEntry*, const MatchEntry*> MnemonicRange =\n"; 2585 OS << " std::equal_range(MatchTable, MatchTable+" 2586 << Info.Matchables.size() << ", Mnemonic, LessOpcode());\n\n"; 2587 2588 OS << " // Return a more specific error code if no mnemonics match.\n"; 2589 OS << " if (MnemonicRange.first == MnemonicRange.second)\n"; 2590 OS << " return Match_MnemonicFail;\n\n"; 2591 2592 OS << " for (const MatchEntry *it = MnemonicRange.first, " 2593 << "*ie = MnemonicRange.second;\n"; 2594 OS << " it != ie; ++it) {\n"; 2595 2596 OS << " // equal_range guarantees that instruction mnemonic matches.\n"; 2597 OS << " assert(Mnemonic == it->getMnemonic());\n"; 2598 2599 // Emit check that the subclasses match. 2600 OS << " if (VariantID != it->AsmVariantID) continue;\n"; 2601 OS << " bool OperandsValid = true;\n"; 2602 OS << " for (unsigned i = 0; i != " << MaxNumOperands << "; ++i) {\n"; 2603 OS << " if (i + 1 >= Operands.size()) {\n"; 2604 OS << " OperandsValid = (it->Classes[i] == " <<"InvalidMatchClass);\n"; 2605 OS << " break;\n"; 2606 OS << " }\n"; 2607 OS << " if (validateOperandClass(Operands[i+1], " 2608 "(MatchClassKind)it->Classes[i]))\n"; 2609 OS << " continue;\n"; 2610 OS << " // If this operand is broken for all of the instances of this\n"; 2611 OS << " // mnemonic, keep track of it so we can report loc info.\n"; 2612 OS << " if (it == MnemonicRange.first || ErrorInfo <= i+1)\n"; 2613 OS << " ErrorInfo = i+1;\n"; 2614 OS << " // Otherwise, just reject this instance of the mnemonic.\n"; 2615 OS << " OperandsValid = false;\n"; 2616 OS << " break;\n"; 2617 OS << " }\n\n"; 2618 2619 OS << " if (!OperandsValid) continue;\n"; 2620 2621 // Emit check that the required features are available. 2622 OS << " if ((AvailableFeatures & it->RequiredFeatures) " 2623 << "!= it->RequiredFeatures) {\n"; 2624 OS << " HadMatchOtherThanFeatures = true;\n"; 2625 OS << " ErrorInfo = it->RequiredFeatures & ~AvailableFeatures;\n"; 2626 OS << " continue;\n"; 2627 OS << " }\n"; 2628 OS << "\n"; 2629 OS << " // We have selected a definite instruction, convert the parsed\n" 2630 << " // operands into the appropriate MCInst.\n"; 2631 OS << " if (!ConvertToMCInst(it->ConvertFn, Inst,\n" 2632 << " it->Opcode, Operands))\n"; 2633 OS << " return Match_ConversionFail;\n"; 2634 OS << "\n"; 2635 2636 // Verify the instruction with the target-specific match predicate function. 2637 OS << " // We have a potential match. Check the target predicate to\n" 2638 << " // handle any context sensitive constraints.\n" 2639 << " unsigned MatchResult;\n" 2640 << " if ((MatchResult = checkTargetMatchPredicate(Inst)) !=" 2641 << " Match_Success) {\n" 2642 << " Inst.clear();\n" 2643 << " RetCode = MatchResult;\n" 2644 << " HadMatchOtherThanPredicate = true;\n" 2645 << " continue;\n" 2646 << " }\n\n"; 2647 2648 // Call the post-processing function, if used. 2649 std::string InsnCleanupFn = 2650 AsmParser->getValueAsString("AsmParserInstCleanup"); 2651 if (!InsnCleanupFn.empty()) 2652 OS << " " << InsnCleanupFn << "(Inst);\n"; 2653 2654 OS << " return Match_Success;\n"; 2655 OS << " }\n\n"; 2656 2657 OS << " // Okay, we had no match. Try to return a useful error code.\n"; 2658 OS << " if (HadMatchOtherThanPredicate || !HadMatchOtherThanFeatures)"; 2659 OS << " return RetCode;\n"; 2660 OS << " assert(ErrorInfo && \"missing feature(s) but what?!\");"; 2661 OS << " return Match_MissingFeature;\n"; 2662 OS << "}\n\n"; 2663 2664 if (Info.OperandMatchInfo.size()) 2665 emitCustomOperandParsing(OS, Target, Info, ClassName); 2666 2667 OS << "#endif // GET_MATCHER_IMPLEMENTATION\n\n"; 2668 } 2669 2670 namespace llvm { 2671 2672 void EmitAsmMatcher(RecordKeeper &RK, raw_ostream &OS) { 2673 emitSourceFileHeader("Assembly Matcher Source Fragment", OS); 2674 AsmMatcherEmitter(RK).run(OS); 2675 } 2676 2677 } // End llvm namespace 2678