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 values 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 "llvm/ADT/PointerUnion.h" 101 #include "llvm/ADT/STLExtras.h" 102 #include "llvm/ADT/SmallPtrSet.h" 103 #include "llvm/ADT/SmallVector.h" 104 #include "llvm/ADT/StringExtras.h" 105 #include "llvm/Support/CommandLine.h" 106 #include "llvm/Support/Debug.h" 107 #include "llvm/Support/ErrorHandling.h" 108 #include "llvm/TableGen/Error.h" 109 #include "llvm/TableGen/Record.h" 110 #include "llvm/TableGen/StringMatcher.h" 111 #include "llvm/TableGen/StringToOffsetTable.h" 112 #include "llvm/TableGen/TableGenBackend.h" 113 #include <cassert> 114 #include <cctype> 115 #include <map> 116 #include <set> 117 #include <sstream> 118 #include <forward_list> 119 using namespace llvm; 120 121 #define DEBUG_TYPE "asm-matcher-emitter" 122 123 static cl::opt<std::string> 124 MatchPrefix("match-prefix", cl::init(""), 125 cl::desc("Only match instructions with the given prefix")); 126 127 namespace { 128 class AsmMatcherInfo; 129 struct SubtargetFeatureInfo; 130 131 // Register sets are used as keys in some second-order sets TableGen creates 132 // when generating its data structures. This means that the order of two 133 // RegisterSets can be seen in the outputted AsmMatcher tables occasionally, and 134 // can even affect compiler output (at least seen in diagnostics produced when 135 // all matches fail). So we use a type that sorts them consistently. 136 typedef std::set<Record*, LessRecordByID> RegisterSet; 137 138 class AsmMatcherEmitter { 139 RecordKeeper &Records; 140 public: 141 AsmMatcherEmitter(RecordKeeper &R) : Records(R) {} 142 143 void run(raw_ostream &o); 144 }; 145 146 /// ClassInfo - Helper class for storing the information about a particular 147 /// class of operands which can be matched. 148 struct ClassInfo { 149 enum ClassInfoKind { 150 /// Invalid kind, for use as a sentinel value. 151 Invalid = 0, 152 153 /// The class for a particular token. 154 Token, 155 156 /// The (first) register class, subsequent register classes are 157 /// RegisterClass0+1, and so on. 158 RegisterClass0, 159 160 /// The (first) user defined class, subsequent user defined classes are 161 /// UserClass0+1, and so on. 162 UserClass0 = 1<<16 163 }; 164 165 /// Kind - The class kind, which is either a predefined kind, or (UserClass0 + 166 /// N) for the Nth user defined class. 167 unsigned Kind; 168 169 /// SuperClasses - The super classes of this class. Note that for simplicities 170 /// sake user operands only record their immediate super class, while register 171 /// operands include all superclasses. 172 std::vector<ClassInfo*> SuperClasses; 173 174 /// Name - The full class name, suitable for use in an enum. 175 std::string Name; 176 177 /// ClassName - The unadorned generic name for this class (e.g., Token). 178 std::string ClassName; 179 180 /// ValueName - The name of the value this class represents; for a token this 181 /// is the literal token string, for an operand it is the TableGen class (or 182 /// empty if this is a derived class). 183 std::string ValueName; 184 185 /// PredicateMethod - The name of the operand method to test whether the 186 /// operand matches this class; this is not valid for Token or register kinds. 187 std::string PredicateMethod; 188 189 /// RenderMethod - The name of the operand method to add this operand to an 190 /// MCInst; this is not valid for Token or register kinds. 191 std::string RenderMethod; 192 193 /// ParserMethod - The name of the operand method to do a target specific 194 /// parsing on the operand. 195 std::string ParserMethod; 196 197 /// For register classes: the records for all the registers in this class. 198 RegisterSet Registers; 199 200 /// For custom match classes: the diagnostic kind for when the predicate fails. 201 std::string DiagnosticType; 202 public: 203 /// isRegisterClass() - Check if this is a register class. 204 bool isRegisterClass() const { 205 return Kind >= RegisterClass0 && Kind < UserClass0; 206 } 207 208 /// isUserClass() - Check if this is a user defined class. 209 bool isUserClass() const { 210 return Kind >= UserClass0; 211 } 212 213 /// isRelatedTo - Check whether this class is "related" to \p RHS. Classes 214 /// are related if they are in the same class hierarchy. 215 bool isRelatedTo(const ClassInfo &RHS) const { 216 // Tokens are only related to tokens. 217 if (Kind == Token || RHS.Kind == Token) 218 return Kind == Token && RHS.Kind == Token; 219 220 // Registers classes are only related to registers classes, and only if 221 // their intersection is non-empty. 222 if (isRegisterClass() || RHS.isRegisterClass()) { 223 if (!isRegisterClass() || !RHS.isRegisterClass()) 224 return false; 225 226 RegisterSet Tmp; 227 std::insert_iterator<RegisterSet> II(Tmp, Tmp.begin()); 228 std::set_intersection(Registers.begin(), Registers.end(), 229 RHS.Registers.begin(), RHS.Registers.end(), 230 II, LessRecordByID()); 231 232 return !Tmp.empty(); 233 } 234 235 // Otherwise we have two users operands; they are related if they are in the 236 // same class hierarchy. 237 // 238 // FIXME: This is an oversimplification, they should only be related if they 239 // intersect, however we don't have that information. 240 assert(isUserClass() && RHS.isUserClass() && "Unexpected class!"); 241 const ClassInfo *Root = this; 242 while (!Root->SuperClasses.empty()) 243 Root = Root->SuperClasses.front(); 244 245 const ClassInfo *RHSRoot = &RHS; 246 while (!RHSRoot->SuperClasses.empty()) 247 RHSRoot = RHSRoot->SuperClasses.front(); 248 249 return Root == RHSRoot; 250 } 251 252 /// isSubsetOf - Test whether this class is a subset of \p RHS. 253 bool isSubsetOf(const ClassInfo &RHS) const { 254 // This is a subset of RHS if it is the same class... 255 if (this == &RHS) 256 return true; 257 258 // ... or if any of its super classes are a subset of RHS. 259 for (const ClassInfo *CI : SuperClasses) 260 if (CI->isSubsetOf(RHS)) 261 return true; 262 263 return false; 264 } 265 266 int getTreeDepth() const { 267 int Depth = 0; 268 const ClassInfo *Root = this; 269 while (!Root->SuperClasses.empty()) { 270 Depth++; 271 Root = Root->SuperClasses.front(); 272 } 273 return Depth; 274 } 275 276 const ClassInfo *findRoot() const { 277 const ClassInfo *Root = this; 278 while (!Root->SuperClasses.empty()) 279 Root = Root->SuperClasses.front(); 280 return Root; 281 } 282 283 /// Compare two classes. This does not produce a total ordering, but does 284 /// guarantee that subclasses are sorted before their parents, and that the 285 /// ordering is transitive. 286 bool operator<(const ClassInfo &RHS) const { 287 if (this == &RHS) 288 return false; 289 290 // First, enforce the ordering between the three different types of class. 291 // Tokens sort before registers, which sort before user classes. 292 if (Kind == Token) { 293 if (RHS.Kind != Token) 294 return true; 295 assert(RHS.Kind == Token); 296 } else if (isRegisterClass()) { 297 if (RHS.Kind == Token) 298 return false; 299 else if (RHS.isUserClass()) 300 return true; 301 assert(RHS.isRegisterClass()); 302 } else if (isUserClass()) { 303 if (!RHS.isUserClass()) 304 return false; 305 assert(RHS.isUserClass()); 306 } else { 307 llvm_unreachable("Unknown ClassInfoKind"); 308 } 309 310 if (Kind == Token || isUserClass()) { 311 // Related tokens and user classes get sorted by depth in the inheritence 312 // tree (so that subclasses are before their parents). 313 if (isRelatedTo(RHS)) { 314 if (getTreeDepth() > RHS.getTreeDepth()) 315 return true; 316 if (getTreeDepth() < RHS.getTreeDepth()) 317 return false; 318 } else { 319 // Unrelated tokens and user classes are ordered by the name of their 320 // root nodes, so that there is a consistent ordering between 321 // unconnected trees. 322 return findRoot()->ValueName < RHS.findRoot()->ValueName; 323 } 324 } else if (isRegisterClass()) { 325 // For register sets, sort by number of registers. This guarantees that 326 // a set will always sort before all of it's strict supersets. 327 if (Registers.size() != RHS.Registers.size()) 328 return Registers.size() < RHS.Registers.size(); 329 } else { 330 llvm_unreachable("Unknown ClassInfoKind"); 331 } 332 333 // FIXME: We should be able to just return false here, as we only need a 334 // partial order (we use stable sorts, so this is deterministic) and the 335 // name of a class shouldn't be significant. However, some of the backends 336 // accidentally rely on this behaviour, so it will have to stay like this 337 // until they are fixed. 338 return ValueName < RHS.ValueName; 339 } 340 }; 341 342 class AsmVariantInfo { 343 public: 344 std::string RegisterPrefix; 345 std::string TokenizingCharacters; 346 std::string SeparatorCharacters; 347 std::string BreakCharacters; 348 int AsmVariantNo; 349 }; 350 351 /// MatchableInfo - Helper class for storing the necessary information for an 352 /// instruction or alias which is capable of being matched. 353 struct MatchableInfo { 354 struct AsmOperand { 355 /// Token - This is the token that the operand came from. 356 StringRef Token; 357 358 /// The unique class instance this operand should match. 359 ClassInfo *Class; 360 361 /// The operand name this is, if anything. 362 StringRef SrcOpName; 363 364 /// The suboperand index within SrcOpName, or -1 for the entire operand. 365 int SubOpIdx; 366 367 /// Whether the token is "isolated", i.e., it is preceded and followed 368 /// by separators. 369 bool IsIsolatedToken; 370 371 /// Register record if this token is singleton register. 372 Record *SingletonReg; 373 374 explicit AsmOperand(bool IsIsolatedToken, StringRef T) 375 : Token(T), Class(nullptr), SubOpIdx(-1), 376 IsIsolatedToken(IsIsolatedToken), SingletonReg(nullptr) {} 377 }; 378 379 /// ResOperand - This represents a single operand in the result instruction 380 /// generated by the match. In cases (like addressing modes) where a single 381 /// assembler operand expands to multiple MCOperands, this represents the 382 /// single assembler operand, not the MCOperand. 383 struct ResOperand { 384 enum { 385 /// RenderAsmOperand - This represents an operand result that is 386 /// generated by calling the render method on the assembly operand. The 387 /// corresponding AsmOperand is specified by AsmOperandNum. 388 RenderAsmOperand, 389 390 /// TiedOperand - This represents a result operand that is a duplicate of 391 /// a previous result operand. 392 TiedOperand, 393 394 /// ImmOperand - This represents an immediate value that is dumped into 395 /// the operand. 396 ImmOperand, 397 398 /// RegOperand - This represents a fixed register that is dumped in. 399 RegOperand 400 } Kind; 401 402 union { 403 /// This is the operand # in the AsmOperands list that this should be 404 /// copied from. 405 unsigned AsmOperandNum; 406 407 /// TiedOperandNum - This is the (earlier) result operand that should be 408 /// copied from. 409 unsigned TiedOperandNum; 410 411 /// ImmVal - This is the immediate value added to the instruction. 412 int64_t ImmVal; 413 414 /// Register - This is the register record. 415 Record *Register; 416 }; 417 418 /// MINumOperands - The number of MCInst operands populated by this 419 /// operand. 420 unsigned MINumOperands; 421 422 static ResOperand getRenderedOp(unsigned AsmOpNum, unsigned NumOperands) { 423 ResOperand X; 424 X.Kind = RenderAsmOperand; 425 X.AsmOperandNum = AsmOpNum; 426 X.MINumOperands = NumOperands; 427 return X; 428 } 429 430 static ResOperand getTiedOp(unsigned TiedOperandNum) { 431 ResOperand X; 432 X.Kind = TiedOperand; 433 X.TiedOperandNum = TiedOperandNum; 434 X.MINumOperands = 1; 435 return X; 436 } 437 438 static ResOperand getImmOp(int64_t Val) { 439 ResOperand X; 440 X.Kind = ImmOperand; 441 X.ImmVal = Val; 442 X.MINumOperands = 1; 443 return X; 444 } 445 446 static ResOperand getRegOp(Record *Reg) { 447 ResOperand X; 448 X.Kind = RegOperand; 449 X.Register = Reg; 450 X.MINumOperands = 1; 451 return X; 452 } 453 }; 454 455 /// AsmVariantID - Target's assembly syntax variant no. 456 int AsmVariantID; 457 458 /// AsmString - The assembly string for this instruction (with variants 459 /// removed), e.g. "movsx $src, $dst". 460 std::string AsmString; 461 462 /// TheDef - This is the definition of the instruction or InstAlias that this 463 /// matchable came from. 464 Record *const TheDef; 465 466 /// DefRec - This is the definition that it came from. 467 PointerUnion<const CodeGenInstruction*, const CodeGenInstAlias*> DefRec; 468 469 const CodeGenInstruction *getResultInst() const { 470 if (DefRec.is<const CodeGenInstruction*>()) 471 return DefRec.get<const CodeGenInstruction*>(); 472 return DefRec.get<const CodeGenInstAlias*>()->ResultInst; 473 } 474 475 /// ResOperands - This is the operand list that should be built for the result 476 /// MCInst. 477 SmallVector<ResOperand, 8> ResOperands; 478 479 /// Mnemonic - This is the first token of the matched instruction, its 480 /// mnemonic. 481 StringRef Mnemonic; 482 483 /// AsmOperands - The textual operands that this instruction matches, 484 /// annotated with a class and where in the OperandList they were defined. 485 /// This directly corresponds to the tokenized AsmString after the mnemonic is 486 /// removed. 487 SmallVector<AsmOperand, 8> AsmOperands; 488 489 /// Predicates - The required subtarget features to match this instruction. 490 SmallVector<const SubtargetFeatureInfo *, 4> RequiredFeatures; 491 492 /// ConversionFnKind - The enum value which is passed to the generated 493 /// convertToMCInst to convert parsed operands into an MCInst for this 494 /// function. 495 std::string ConversionFnKind; 496 497 /// If this instruction is deprecated in some form. 498 bool HasDeprecation; 499 500 /// If this is an alias, this is use to determine whether or not to using 501 /// the conversion function defined by the instruction's AsmMatchConverter 502 /// or to use the function generated by the alias. 503 bool UseInstAsmMatchConverter; 504 505 MatchableInfo(const CodeGenInstruction &CGI) 506 : AsmVariantID(0), AsmString(CGI.AsmString), TheDef(CGI.TheDef), DefRec(&CGI), 507 UseInstAsmMatchConverter(true) { 508 } 509 510 MatchableInfo(std::unique_ptr<const CodeGenInstAlias> Alias) 511 : AsmVariantID(0), AsmString(Alias->AsmString), TheDef(Alias->TheDef), 512 DefRec(Alias.release()), 513 UseInstAsmMatchConverter( 514 TheDef->getValueAsBit("UseInstAsmMatchConverter")) { 515 } 516 517 // Could remove this and the dtor if PointerUnion supported unique_ptr 518 // elements with a dynamic failure/assertion (like the one below) in the case 519 // where it was copied while being in an owning state. 520 MatchableInfo(const MatchableInfo &RHS) 521 : AsmVariantID(RHS.AsmVariantID), AsmString(RHS.AsmString), 522 TheDef(RHS.TheDef), DefRec(RHS.DefRec), ResOperands(RHS.ResOperands), 523 Mnemonic(RHS.Mnemonic), AsmOperands(RHS.AsmOperands), 524 RequiredFeatures(RHS.RequiredFeatures), 525 ConversionFnKind(RHS.ConversionFnKind), 526 HasDeprecation(RHS.HasDeprecation), 527 UseInstAsmMatchConverter(RHS.UseInstAsmMatchConverter) { 528 assert(!DefRec.is<const CodeGenInstAlias *>()); 529 } 530 531 ~MatchableInfo() { 532 delete DefRec.dyn_cast<const CodeGenInstAlias*>(); 533 } 534 535 // Two-operand aliases clone from the main matchable, but mark the second 536 // operand as a tied operand of the first for purposes of the assembler. 537 void formTwoOperandAlias(StringRef Constraint); 538 539 void initialize(const AsmMatcherInfo &Info, 540 SmallPtrSetImpl<Record*> &SingletonRegisters, 541 AsmVariantInfo const &Variant, 542 bool HasMnemonicFirst); 543 544 /// validate - Return true if this matchable is a valid thing to match against 545 /// and perform a bunch of validity checking. 546 bool validate(StringRef CommentDelimiter, bool Hack) const; 547 548 /// findAsmOperand - Find the AsmOperand with the specified name and 549 /// suboperand index. 550 int findAsmOperand(StringRef N, int SubOpIdx) const { 551 auto I = std::find_if(AsmOperands.begin(), AsmOperands.end(), 552 [&](const AsmOperand &Op) { 553 return Op.SrcOpName == N && Op.SubOpIdx == SubOpIdx; 554 }); 555 return (I != AsmOperands.end()) ? I - AsmOperands.begin() : -1; 556 } 557 558 /// findAsmOperandNamed - Find the first AsmOperand with the specified name. 559 /// This does not check the suboperand index. 560 int findAsmOperandNamed(StringRef N) const { 561 auto I = std::find_if(AsmOperands.begin(), AsmOperands.end(), 562 [&](const AsmOperand &Op) { 563 return Op.SrcOpName == N; 564 }); 565 return (I != AsmOperands.end()) ? I - AsmOperands.begin() : -1; 566 } 567 568 void buildInstructionResultOperands(); 569 void buildAliasResultOperands(); 570 571 /// operator< - Compare two matchables. 572 bool operator<(const MatchableInfo &RHS) const { 573 // The primary comparator is the instruction mnemonic. 574 if (Mnemonic != RHS.Mnemonic) 575 return Mnemonic < RHS.Mnemonic; 576 577 if (AsmOperands.size() != RHS.AsmOperands.size()) 578 return AsmOperands.size() < RHS.AsmOperands.size(); 579 580 // Compare lexicographically by operand. The matcher validates that other 581 // orderings wouldn't be ambiguous using \see couldMatchAmbiguouslyWith(). 582 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) { 583 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class) 584 return true; 585 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class) 586 return false; 587 } 588 589 // Give matches that require more features higher precedence. This is useful 590 // because we cannot define AssemblerPredicates with the negation of 591 // processor features. For example, ARM v6 "nop" may be either a HINT or 592 // MOV. With v6, we want to match HINT. The assembler has no way to 593 // predicate MOV under "NoV6", but HINT will always match first because it 594 // requires V6 while MOV does not. 595 if (RequiredFeatures.size() != RHS.RequiredFeatures.size()) 596 return RequiredFeatures.size() > RHS.RequiredFeatures.size(); 597 598 return false; 599 } 600 601 /// couldMatchAmbiguouslyWith - Check whether this matchable could 602 /// ambiguously match the same set of operands as \p RHS (without being a 603 /// strictly superior match). 604 bool couldMatchAmbiguouslyWith(const MatchableInfo &RHS) const { 605 // The primary comparator is the instruction mnemonic. 606 if (Mnemonic != RHS.Mnemonic) 607 return false; 608 609 // The number of operands is unambiguous. 610 if (AsmOperands.size() != RHS.AsmOperands.size()) 611 return false; 612 613 // Otherwise, make sure the ordering of the two instructions is unambiguous 614 // by checking that either (a) a token or operand kind discriminates them, 615 // or (b) the ordering among equivalent kinds is consistent. 616 617 // Tokens and operand kinds are unambiguous (assuming a correct target 618 // specific parser). 619 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) 620 if (AsmOperands[i].Class->Kind != RHS.AsmOperands[i].Class->Kind || 621 AsmOperands[i].Class->Kind == ClassInfo::Token) 622 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class || 623 *RHS.AsmOperands[i].Class < *AsmOperands[i].Class) 624 return false; 625 626 // Otherwise, this operand could commute if all operands are equivalent, or 627 // there is a pair of operands that compare less than and a pair that 628 // compare greater than. 629 bool HasLT = false, HasGT = false; 630 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) { 631 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class) 632 HasLT = true; 633 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class) 634 HasGT = true; 635 } 636 637 return HasLT == HasGT; 638 } 639 640 void dump() const; 641 642 private: 643 void tokenizeAsmString(AsmMatcherInfo const &Info, 644 AsmVariantInfo const &Variant); 645 void addAsmOperand(StringRef Token, bool IsIsolatedToken = false); 646 }; 647 648 /// SubtargetFeatureInfo - Helper class for storing information on a subtarget 649 /// feature which participates in instruction matching. 650 struct SubtargetFeatureInfo { 651 /// \brief The predicate record for this feature. 652 Record *TheDef; 653 654 /// \brief An unique index assigned to represent this feature. 655 uint64_t Index; 656 657 SubtargetFeatureInfo(Record *D, uint64_t Idx) : TheDef(D), Index(Idx) {} 658 659 /// \brief The name of the enumerated constant identifying this feature. 660 std::string getEnumName() const { 661 return "Feature_" + TheDef->getName(); 662 } 663 664 void dump() const { 665 errs() << getEnumName() << " " << Index << "\n"; 666 TheDef->dump(); 667 } 668 }; 669 670 struct OperandMatchEntry { 671 unsigned OperandMask; 672 const MatchableInfo* MI; 673 ClassInfo *CI; 674 675 static OperandMatchEntry create(const MatchableInfo *mi, ClassInfo *ci, 676 unsigned opMask) { 677 OperandMatchEntry X; 678 X.OperandMask = opMask; 679 X.CI = ci; 680 X.MI = mi; 681 return X; 682 } 683 }; 684 685 686 class AsmMatcherInfo { 687 public: 688 /// Tracked Records 689 RecordKeeper &Records; 690 691 /// The tablegen AsmParser record. 692 Record *AsmParser; 693 694 /// Target - The target information. 695 CodeGenTarget &Target; 696 697 /// The classes which are needed for matching. 698 std::forward_list<ClassInfo> Classes; 699 700 /// The information on the matchables to match. 701 std::vector<std::unique_ptr<MatchableInfo>> Matchables; 702 703 /// Info for custom matching operands by user defined methods. 704 std::vector<OperandMatchEntry> OperandMatchInfo; 705 706 /// Map of Register records to their class information. 707 typedef std::map<Record*, ClassInfo*, LessRecordByID> RegisterClassesTy; 708 RegisterClassesTy RegisterClasses; 709 710 /// Map of Predicate records to their subtarget information. 711 std::map<Record *, SubtargetFeatureInfo, LessRecordByID> SubtargetFeatures; 712 713 /// Map of AsmOperandClass records to their class information. 714 std::map<Record*, ClassInfo*> AsmOperandClasses; 715 716 private: 717 /// Map of token to class information which has already been constructed. 718 std::map<std::string, ClassInfo*> TokenClasses; 719 720 /// Map of RegisterClass records to their class information. 721 std::map<Record*, ClassInfo*> RegisterClassClasses; 722 723 private: 724 /// getTokenClass - Lookup or create the class for the given token. 725 ClassInfo *getTokenClass(StringRef Token); 726 727 /// getOperandClass - Lookup or create the class for the given operand. 728 ClassInfo *getOperandClass(const CGIOperandList::OperandInfo &OI, 729 int SubOpIdx); 730 ClassInfo *getOperandClass(Record *Rec, int SubOpIdx); 731 732 /// buildRegisterClasses - Build the ClassInfo* instances for register 733 /// classes. 734 void buildRegisterClasses(SmallPtrSetImpl<Record*> &SingletonRegisters); 735 736 /// buildOperandClasses - Build the ClassInfo* instances for user defined 737 /// operand classes. 738 void buildOperandClasses(); 739 740 void buildInstructionOperandReference(MatchableInfo *II, StringRef OpName, 741 unsigned AsmOpIdx); 742 void buildAliasOperandReference(MatchableInfo *II, StringRef OpName, 743 MatchableInfo::AsmOperand &Op); 744 745 public: 746 AsmMatcherInfo(Record *AsmParser, 747 CodeGenTarget &Target, 748 RecordKeeper &Records); 749 750 /// buildInfo - Construct the various tables used during matching. 751 void buildInfo(); 752 753 /// buildOperandMatchInfo - Build the necessary information to handle user 754 /// defined operand parsing methods. 755 void buildOperandMatchInfo(); 756 757 /// getSubtargetFeature - Lookup or create the subtarget feature info for the 758 /// given operand. 759 const SubtargetFeatureInfo *getSubtargetFeature(Record *Def) const { 760 assert(Def->isSubClassOf("Predicate") && "Invalid predicate type!"); 761 const auto &I = SubtargetFeatures.find(Def); 762 return I == SubtargetFeatures.end() ? nullptr : &I->second; 763 } 764 765 RecordKeeper &getRecords() const { 766 return Records; 767 } 768 }; 769 770 } // End anonymous namespace 771 772 void MatchableInfo::dump() const { 773 errs() << TheDef->getName() << " -- " << "flattened:\"" << AsmString <<"\"\n"; 774 775 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) { 776 const AsmOperand &Op = AsmOperands[i]; 777 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - "; 778 errs() << '\"' << Op.Token << "\"\n"; 779 } 780 } 781 782 static std::pair<StringRef, StringRef> 783 parseTwoOperandConstraint(StringRef S, ArrayRef<SMLoc> Loc) { 784 // Split via the '='. 785 std::pair<StringRef, StringRef> Ops = S.split('='); 786 if (Ops.second == "") 787 PrintFatalError(Loc, "missing '=' in two-operand alias constraint"); 788 // Trim whitespace and the leading '$' on the operand names. 789 size_t start = Ops.first.find_first_of('$'); 790 if (start == std::string::npos) 791 PrintFatalError(Loc, "expected '$' prefix on asm operand name"); 792 Ops.first = Ops.first.slice(start + 1, std::string::npos); 793 size_t end = Ops.first.find_last_of(" \t"); 794 Ops.first = Ops.first.slice(0, end); 795 // Now the second operand. 796 start = Ops.second.find_first_of('$'); 797 if (start == std::string::npos) 798 PrintFatalError(Loc, "expected '$' prefix on asm operand name"); 799 Ops.second = Ops.second.slice(start + 1, std::string::npos); 800 end = Ops.second.find_last_of(" \t"); 801 Ops.first = Ops.first.slice(0, end); 802 return Ops; 803 } 804 805 void MatchableInfo::formTwoOperandAlias(StringRef Constraint) { 806 // Figure out which operands are aliased and mark them as tied. 807 std::pair<StringRef, StringRef> Ops = 808 parseTwoOperandConstraint(Constraint, TheDef->getLoc()); 809 810 // Find the AsmOperands that refer to the operands we're aliasing. 811 int SrcAsmOperand = findAsmOperandNamed(Ops.first); 812 int DstAsmOperand = findAsmOperandNamed(Ops.second); 813 if (SrcAsmOperand == -1) 814 PrintFatalError(TheDef->getLoc(), 815 "unknown source two-operand alias operand '" + Ops.first + 816 "'."); 817 if (DstAsmOperand == -1) 818 PrintFatalError(TheDef->getLoc(), 819 "unknown destination two-operand alias operand '" + 820 Ops.second + "'."); 821 822 // Find the ResOperand that refers to the operand we're aliasing away 823 // and update it to refer to the combined operand instead. 824 for (ResOperand &Op : ResOperands) { 825 if (Op.Kind == ResOperand::RenderAsmOperand && 826 Op.AsmOperandNum == (unsigned)SrcAsmOperand) { 827 Op.AsmOperandNum = DstAsmOperand; 828 break; 829 } 830 } 831 // Remove the AsmOperand for the alias operand. 832 AsmOperands.erase(AsmOperands.begin() + SrcAsmOperand); 833 // Adjust the ResOperand references to any AsmOperands that followed 834 // the one we just deleted. 835 for (ResOperand &Op : ResOperands) { 836 switch(Op.Kind) { 837 default: 838 // Nothing to do for operands that don't reference AsmOperands. 839 break; 840 case ResOperand::RenderAsmOperand: 841 if (Op.AsmOperandNum > (unsigned)SrcAsmOperand) 842 --Op.AsmOperandNum; 843 break; 844 case ResOperand::TiedOperand: 845 if (Op.TiedOperandNum > (unsigned)SrcAsmOperand) 846 --Op.TiedOperandNum; 847 break; 848 } 849 } 850 } 851 852 /// extractSingletonRegisterForAsmOperand - Extract singleton register, 853 /// if present, from specified token. 854 static void 855 extractSingletonRegisterForAsmOperand(MatchableInfo::AsmOperand &Op, 856 const AsmMatcherInfo &Info, 857 StringRef RegisterPrefix) { 858 StringRef Tok = Op.Token; 859 860 // If this token is not an isolated token, i.e., it isn't separated from 861 // other tokens (e.g. with whitespace), don't interpret it as a register name. 862 if (!Op.IsIsolatedToken) 863 return; 864 865 if (RegisterPrefix.empty()) { 866 std::string LoweredTok = Tok.lower(); 867 if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(LoweredTok)) 868 Op.SingletonReg = Reg->TheDef; 869 return; 870 } 871 872 if (!Tok.startswith(RegisterPrefix)) 873 return; 874 875 StringRef RegName = Tok.substr(RegisterPrefix.size()); 876 if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(RegName)) 877 Op.SingletonReg = Reg->TheDef; 878 879 // If there is no register prefix (i.e. "%" in "%eax"), then this may 880 // be some random non-register token, just ignore it. 881 return; 882 } 883 884 void MatchableInfo::initialize(const AsmMatcherInfo &Info, 885 SmallPtrSetImpl<Record*> &SingletonRegisters, 886 AsmVariantInfo const &Variant, 887 bool HasMnemonicFirst) { 888 AsmVariantID = Variant.AsmVariantNo; 889 AsmString = 890 CodeGenInstruction::FlattenAsmStringVariants(AsmString, 891 Variant.AsmVariantNo); 892 893 tokenizeAsmString(Info, Variant); 894 895 // The first token of the instruction is the mnemonic, which must be a 896 // simple string, not a $foo variable or a singleton register. 897 if (AsmOperands.empty()) 898 PrintFatalError(TheDef->getLoc(), 899 "Instruction '" + TheDef->getName() + "' has no tokens"); 900 901 assert(!AsmOperands[0].Token.empty()); 902 if (HasMnemonicFirst) { 903 Mnemonic = AsmOperands[0].Token; 904 if (Mnemonic[0] == '$') 905 PrintFatalError(TheDef->getLoc(), 906 "Invalid instruction mnemonic '" + Mnemonic + "'!"); 907 908 // Remove the first operand, it is tracked in the mnemonic field. 909 AsmOperands.erase(AsmOperands.begin()); 910 } else if (AsmOperands[0].Token[0] != '$') 911 Mnemonic = AsmOperands[0].Token; 912 913 // Compute the require features. 914 for (Record *Predicate : TheDef->getValueAsListOfDefs("Predicates")) 915 if (const SubtargetFeatureInfo *Feature = 916 Info.getSubtargetFeature(Predicate)) 917 RequiredFeatures.push_back(Feature); 918 919 // Collect singleton registers, if used. 920 for (MatchableInfo::AsmOperand &Op : AsmOperands) { 921 extractSingletonRegisterForAsmOperand(Op, Info, Variant.RegisterPrefix); 922 if (Record *Reg = Op.SingletonReg) 923 SingletonRegisters.insert(Reg); 924 } 925 926 const RecordVal *DepMask = TheDef->getValue("DeprecatedFeatureMask"); 927 if (!DepMask) 928 DepMask = TheDef->getValue("ComplexDeprecationPredicate"); 929 930 HasDeprecation = 931 DepMask ? !DepMask->getValue()->getAsUnquotedString().empty() : false; 932 } 933 934 /// Append an AsmOperand for the given substring of AsmString. 935 void MatchableInfo::addAsmOperand(StringRef Token, bool IsIsolatedToken) { 936 AsmOperands.push_back(AsmOperand(IsIsolatedToken, Token)); 937 } 938 939 /// tokenizeAsmString - Tokenize a simplified assembly string. 940 void MatchableInfo::tokenizeAsmString(const AsmMatcherInfo &Info, 941 AsmVariantInfo const &Variant) { 942 StringRef String = AsmString; 943 size_t Prev = 0; 944 bool InTok = false; 945 bool IsIsolatedToken = true; 946 for (size_t i = 0, e = String.size(); i != e; ++i) { 947 char Char = String[i]; 948 if (Variant.BreakCharacters.find(Char) != std::string::npos) { 949 if (InTok) { 950 addAsmOperand(String.slice(Prev, i), false); 951 Prev = i; 952 IsIsolatedToken = false; 953 } 954 InTok = true; 955 continue; 956 } 957 if (Variant.TokenizingCharacters.find(Char) != std::string::npos) { 958 if (InTok) { 959 addAsmOperand(String.slice(Prev, i), IsIsolatedToken); 960 InTok = false; 961 IsIsolatedToken = false; 962 } 963 addAsmOperand(String.slice(i, i + 1), IsIsolatedToken); 964 Prev = i + 1; 965 IsIsolatedToken = true; 966 continue; 967 } 968 if (Variant.SeparatorCharacters.find(Char) != std::string::npos) { 969 if (InTok) { 970 addAsmOperand(String.slice(Prev, i), IsIsolatedToken); 971 InTok = false; 972 } 973 Prev = i + 1; 974 IsIsolatedToken = true; 975 continue; 976 } 977 978 switch (Char) { 979 case '\\': 980 if (InTok) { 981 addAsmOperand(String.slice(Prev, i), false); 982 InTok = false; 983 IsIsolatedToken = false; 984 } 985 ++i; 986 assert(i != String.size() && "Invalid quoted character"); 987 addAsmOperand(String.slice(i, i + 1), IsIsolatedToken); 988 Prev = i + 1; 989 IsIsolatedToken = false; 990 break; 991 992 case '$': { 993 if (InTok) { 994 addAsmOperand(String.slice(Prev, i), false); 995 InTok = false; 996 IsIsolatedToken = false; 997 } 998 999 // If this isn't "${", start new identifier looking like "$xxx" 1000 if (i + 1 == String.size() || String[i + 1] != '{') { 1001 Prev = i; 1002 break; 1003 } 1004 1005 size_t EndPos = String.find('}', i); 1006 assert(EndPos != StringRef::npos && 1007 "Missing brace in operand reference!"); 1008 addAsmOperand(String.slice(i, EndPos+1), IsIsolatedToken); 1009 Prev = EndPos + 1; 1010 i = EndPos; 1011 IsIsolatedToken = false; 1012 break; 1013 } 1014 1015 default: 1016 InTok = true; 1017 break; 1018 } 1019 } 1020 if (InTok && Prev != String.size()) 1021 addAsmOperand(String.substr(Prev), IsIsolatedToken); 1022 } 1023 1024 bool MatchableInfo::validate(StringRef CommentDelimiter, bool Hack) const { 1025 // Reject matchables with no .s string. 1026 if (AsmString.empty()) 1027 PrintFatalError(TheDef->getLoc(), "instruction with empty asm string"); 1028 1029 // Reject any matchables with a newline in them, they should be marked 1030 // isCodeGenOnly if they are pseudo instructions. 1031 if (AsmString.find('\n') != std::string::npos) 1032 PrintFatalError(TheDef->getLoc(), 1033 "multiline instruction is not valid for the asmparser, " 1034 "mark it isCodeGenOnly"); 1035 1036 // Remove comments from the asm string. We know that the asmstring only 1037 // has one line. 1038 if (!CommentDelimiter.empty() && 1039 StringRef(AsmString).find(CommentDelimiter) != StringRef::npos) 1040 PrintFatalError(TheDef->getLoc(), 1041 "asmstring for instruction has comment character in it, " 1042 "mark it isCodeGenOnly"); 1043 1044 // Reject matchables with operand modifiers, these aren't something we can 1045 // handle, the target should be refactored to use operands instead of 1046 // modifiers. 1047 // 1048 // Also, check for instructions which reference the operand multiple times; 1049 // this implies a constraint we would not honor. 1050 std::set<std::string> OperandNames; 1051 for (const AsmOperand &Op : AsmOperands) { 1052 StringRef Tok = Op.Token; 1053 if (Tok[0] == '$' && Tok.find(':') != StringRef::npos) 1054 PrintFatalError(TheDef->getLoc(), 1055 "matchable with operand modifier '" + Tok + 1056 "' not supported by asm matcher. Mark isCodeGenOnly!"); 1057 1058 // Verify that any operand is only mentioned once. 1059 // We reject aliases and ignore instructions for now. 1060 if (Tok[0] == '$' && !OperandNames.insert(Tok).second) { 1061 if (!Hack) 1062 PrintFatalError(TheDef->getLoc(), 1063 "ERROR: matchable with tied operand '" + Tok + 1064 "' can never be matched!"); 1065 // FIXME: Should reject these. The ARM backend hits this with $lane in a 1066 // bunch of instructions. It is unclear what the right answer is. 1067 DEBUG({ 1068 errs() << "warning: '" << TheDef->getName() << "': " 1069 << "ignoring instruction with tied operand '" 1070 << Tok << "'\n"; 1071 }); 1072 return false; 1073 } 1074 } 1075 1076 return true; 1077 } 1078 1079 static std::string getEnumNameForToken(StringRef Str) { 1080 std::string Res; 1081 1082 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) { 1083 switch (*it) { 1084 case '*': Res += "_STAR_"; break; 1085 case '%': Res += "_PCT_"; break; 1086 case ':': Res += "_COLON_"; break; 1087 case '!': Res += "_EXCLAIM_"; break; 1088 case '.': Res += "_DOT_"; break; 1089 case '<': Res += "_LT_"; break; 1090 case '>': Res += "_GT_"; break; 1091 case '-': Res += "_MINUS_"; break; 1092 default: 1093 if ((*it >= 'A' && *it <= 'Z') || 1094 (*it >= 'a' && *it <= 'z') || 1095 (*it >= '0' && *it <= '9')) 1096 Res += *it; 1097 else 1098 Res += "_" + utostr((unsigned) *it) + "_"; 1099 } 1100 } 1101 1102 return Res; 1103 } 1104 1105 ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) { 1106 ClassInfo *&Entry = TokenClasses[Token]; 1107 1108 if (!Entry) { 1109 Classes.emplace_front(); 1110 Entry = &Classes.front(); 1111 Entry->Kind = ClassInfo::Token; 1112 Entry->ClassName = "Token"; 1113 Entry->Name = "MCK_" + getEnumNameForToken(Token); 1114 Entry->ValueName = Token; 1115 Entry->PredicateMethod = "<invalid>"; 1116 Entry->RenderMethod = "<invalid>"; 1117 Entry->ParserMethod = ""; 1118 Entry->DiagnosticType = ""; 1119 } 1120 1121 return Entry; 1122 } 1123 1124 ClassInfo * 1125 AsmMatcherInfo::getOperandClass(const CGIOperandList::OperandInfo &OI, 1126 int SubOpIdx) { 1127 Record *Rec = OI.Rec; 1128 if (SubOpIdx != -1) 1129 Rec = cast<DefInit>(OI.MIOperandInfo->getArg(SubOpIdx))->getDef(); 1130 return getOperandClass(Rec, SubOpIdx); 1131 } 1132 1133 ClassInfo * 1134 AsmMatcherInfo::getOperandClass(Record *Rec, int SubOpIdx) { 1135 if (Rec->isSubClassOf("RegisterOperand")) { 1136 // RegisterOperand may have an associated ParserMatchClass. If it does, 1137 // use it, else just fall back to the underlying register class. 1138 const RecordVal *R = Rec->getValue("ParserMatchClass"); 1139 if (!R || !R->getValue()) 1140 PrintFatalError("Record `" + Rec->getName() + 1141 "' does not have a ParserMatchClass!\n"); 1142 1143 if (DefInit *DI= dyn_cast<DefInit>(R->getValue())) { 1144 Record *MatchClass = DI->getDef(); 1145 if (ClassInfo *CI = AsmOperandClasses[MatchClass]) 1146 return CI; 1147 } 1148 1149 // No custom match class. Just use the register class. 1150 Record *ClassRec = Rec->getValueAsDef("RegClass"); 1151 if (!ClassRec) 1152 PrintFatalError(Rec->getLoc(), "RegisterOperand `" + Rec->getName() + 1153 "' has no associated register class!\n"); 1154 if (ClassInfo *CI = RegisterClassClasses[ClassRec]) 1155 return CI; 1156 PrintFatalError(Rec->getLoc(), "register class has no class info!"); 1157 } 1158 1159 1160 if (Rec->isSubClassOf("RegisterClass")) { 1161 if (ClassInfo *CI = RegisterClassClasses[Rec]) 1162 return CI; 1163 PrintFatalError(Rec->getLoc(), "register class has no class info!"); 1164 } 1165 1166 if (!Rec->isSubClassOf("Operand")) 1167 PrintFatalError(Rec->getLoc(), "Operand `" + Rec->getName() + 1168 "' does not derive from class Operand!\n"); 1169 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass"); 1170 if (ClassInfo *CI = AsmOperandClasses[MatchClass]) 1171 return CI; 1172 1173 PrintFatalError(Rec->getLoc(), "operand has no match class!"); 1174 } 1175 1176 struct LessRegisterSet { 1177 bool operator() (const RegisterSet &LHS, const RegisterSet & RHS) const { 1178 // std::set<T> defines its own compariso "operator<", but it 1179 // performs a lexicographical comparison by T's innate comparison 1180 // for some reason. We don't want non-deterministic pointer 1181 // comparisons so use this instead. 1182 return std::lexicographical_compare(LHS.begin(), LHS.end(), 1183 RHS.begin(), RHS.end(), 1184 LessRecordByID()); 1185 } 1186 }; 1187 1188 void AsmMatcherInfo:: 1189 buildRegisterClasses(SmallPtrSetImpl<Record*> &SingletonRegisters) { 1190 const auto &Registers = Target.getRegBank().getRegisters(); 1191 auto &RegClassList = Target.getRegBank().getRegClasses(); 1192 1193 typedef std::set<RegisterSet, LessRegisterSet> RegisterSetSet; 1194 1195 // The register sets used for matching. 1196 RegisterSetSet RegisterSets; 1197 1198 // Gather the defined sets. 1199 for (const CodeGenRegisterClass &RC : RegClassList) 1200 RegisterSets.insert( 1201 RegisterSet(RC.getOrder().begin(), RC.getOrder().end())); 1202 1203 // Add any required singleton sets. 1204 for (Record *Rec : SingletonRegisters) { 1205 RegisterSets.insert(RegisterSet(&Rec, &Rec + 1)); 1206 } 1207 1208 // Introduce derived sets where necessary (when a register does not determine 1209 // a unique register set class), and build the mapping of registers to the set 1210 // they should classify to. 1211 std::map<Record*, RegisterSet> RegisterMap; 1212 for (const CodeGenRegister &CGR : Registers) { 1213 // Compute the intersection of all sets containing this register. 1214 RegisterSet ContainingSet; 1215 1216 for (const RegisterSet &RS : RegisterSets) { 1217 if (!RS.count(CGR.TheDef)) 1218 continue; 1219 1220 if (ContainingSet.empty()) { 1221 ContainingSet = RS; 1222 continue; 1223 } 1224 1225 RegisterSet Tmp; 1226 std::swap(Tmp, ContainingSet); 1227 std::insert_iterator<RegisterSet> II(ContainingSet, 1228 ContainingSet.begin()); 1229 std::set_intersection(Tmp.begin(), Tmp.end(), RS.begin(), RS.end(), II, 1230 LessRecordByID()); 1231 } 1232 1233 if (!ContainingSet.empty()) { 1234 RegisterSets.insert(ContainingSet); 1235 RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet)); 1236 } 1237 } 1238 1239 // Construct the register classes. 1240 std::map<RegisterSet, ClassInfo*, LessRegisterSet> RegisterSetClasses; 1241 unsigned Index = 0; 1242 for (const RegisterSet &RS : RegisterSets) { 1243 Classes.emplace_front(); 1244 ClassInfo *CI = &Classes.front(); 1245 CI->Kind = ClassInfo::RegisterClass0 + Index; 1246 CI->ClassName = "Reg" + utostr(Index); 1247 CI->Name = "MCK_Reg" + utostr(Index); 1248 CI->ValueName = ""; 1249 CI->PredicateMethod = ""; // unused 1250 CI->RenderMethod = "addRegOperands"; 1251 CI->Registers = RS; 1252 // FIXME: diagnostic type. 1253 CI->DiagnosticType = ""; 1254 RegisterSetClasses.insert(std::make_pair(RS, CI)); 1255 ++Index; 1256 } 1257 1258 // Find the superclasses; we could compute only the subgroup lattice edges, 1259 // but there isn't really a point. 1260 for (const RegisterSet &RS : RegisterSets) { 1261 ClassInfo *CI = RegisterSetClasses[RS]; 1262 for (const RegisterSet &RS2 : RegisterSets) 1263 if (RS != RS2 && 1264 std::includes(RS2.begin(), RS2.end(), RS.begin(), RS.end(), 1265 LessRecordByID())) 1266 CI->SuperClasses.push_back(RegisterSetClasses[RS2]); 1267 } 1268 1269 // Name the register classes which correspond to a user defined RegisterClass. 1270 for (const CodeGenRegisterClass &RC : RegClassList) { 1271 // Def will be NULL for non-user defined register classes. 1272 Record *Def = RC.getDef(); 1273 if (!Def) 1274 continue; 1275 ClassInfo *CI = RegisterSetClasses[RegisterSet(RC.getOrder().begin(), 1276 RC.getOrder().end())]; 1277 if (CI->ValueName.empty()) { 1278 CI->ClassName = RC.getName(); 1279 CI->Name = "MCK_" + RC.getName(); 1280 CI->ValueName = RC.getName(); 1281 } else 1282 CI->ValueName = CI->ValueName + "," + RC.getName(); 1283 1284 RegisterClassClasses.insert(std::make_pair(Def, CI)); 1285 } 1286 1287 // Populate the map for individual registers. 1288 for (std::map<Record*, RegisterSet>::iterator it = RegisterMap.begin(), 1289 ie = RegisterMap.end(); it != ie; ++it) 1290 RegisterClasses[it->first] = RegisterSetClasses[it->second]; 1291 1292 // Name the register classes which correspond to singleton registers. 1293 for (Record *Rec : SingletonRegisters) { 1294 ClassInfo *CI = RegisterClasses[Rec]; 1295 assert(CI && "Missing singleton register class info!"); 1296 1297 if (CI->ValueName.empty()) { 1298 CI->ClassName = Rec->getName(); 1299 CI->Name = "MCK_" + Rec->getName(); 1300 CI->ValueName = Rec->getName(); 1301 } else 1302 CI->ValueName = CI->ValueName + "," + Rec->getName(); 1303 } 1304 } 1305 1306 void AsmMatcherInfo::buildOperandClasses() { 1307 std::vector<Record*> AsmOperands = 1308 Records.getAllDerivedDefinitions("AsmOperandClass"); 1309 1310 // Pre-populate AsmOperandClasses map. 1311 for (Record *Rec : AsmOperands) { 1312 Classes.emplace_front(); 1313 AsmOperandClasses[Rec] = &Classes.front(); 1314 } 1315 1316 unsigned Index = 0; 1317 for (Record *Rec : AsmOperands) { 1318 ClassInfo *CI = AsmOperandClasses[Rec]; 1319 CI->Kind = ClassInfo::UserClass0 + Index; 1320 1321 ListInit *Supers = Rec->getValueAsListInit("SuperClasses"); 1322 for (Init *I : Supers->getValues()) { 1323 DefInit *DI = dyn_cast<DefInit>(I); 1324 if (!DI) { 1325 PrintError(Rec->getLoc(), "Invalid super class reference!"); 1326 continue; 1327 } 1328 1329 ClassInfo *SC = AsmOperandClasses[DI->getDef()]; 1330 if (!SC) 1331 PrintError(Rec->getLoc(), "Invalid super class reference!"); 1332 else 1333 CI->SuperClasses.push_back(SC); 1334 } 1335 CI->ClassName = Rec->getValueAsString("Name"); 1336 CI->Name = "MCK_" + CI->ClassName; 1337 CI->ValueName = Rec->getName(); 1338 1339 // Get or construct the predicate method name. 1340 Init *PMName = Rec->getValueInit("PredicateMethod"); 1341 if (StringInit *SI = dyn_cast<StringInit>(PMName)) { 1342 CI->PredicateMethod = SI->getValue(); 1343 } else { 1344 assert(isa<UnsetInit>(PMName) && "Unexpected PredicateMethod field!"); 1345 CI->PredicateMethod = "is" + CI->ClassName; 1346 } 1347 1348 // Get or construct the render method name. 1349 Init *RMName = Rec->getValueInit("RenderMethod"); 1350 if (StringInit *SI = dyn_cast<StringInit>(RMName)) { 1351 CI->RenderMethod = SI->getValue(); 1352 } else { 1353 assert(isa<UnsetInit>(RMName) && "Unexpected RenderMethod field!"); 1354 CI->RenderMethod = "add" + CI->ClassName + "Operands"; 1355 } 1356 1357 // Get the parse method name or leave it as empty. 1358 Init *PRMName = Rec->getValueInit("ParserMethod"); 1359 if (StringInit *SI = dyn_cast<StringInit>(PRMName)) 1360 CI->ParserMethod = SI->getValue(); 1361 1362 // Get the diagnostic type or leave it as empty. 1363 // Get the parse method name or leave it as empty. 1364 Init *DiagnosticType = Rec->getValueInit("DiagnosticType"); 1365 if (StringInit *SI = dyn_cast<StringInit>(DiagnosticType)) 1366 CI->DiagnosticType = SI->getValue(); 1367 1368 ++Index; 1369 } 1370 } 1371 1372 AsmMatcherInfo::AsmMatcherInfo(Record *asmParser, 1373 CodeGenTarget &target, 1374 RecordKeeper &records) 1375 : Records(records), AsmParser(asmParser), Target(target) { 1376 } 1377 1378 /// buildOperandMatchInfo - Build the necessary information to handle user 1379 /// defined operand parsing methods. 1380 void AsmMatcherInfo::buildOperandMatchInfo() { 1381 1382 /// Map containing a mask with all operands indices that can be found for 1383 /// that class inside a instruction. 1384 typedef std::map<ClassInfo *, unsigned, less_ptr<ClassInfo>> OpClassMaskTy; 1385 OpClassMaskTy OpClassMask; 1386 1387 for (const auto &MI : Matchables) { 1388 OpClassMask.clear(); 1389 1390 // Keep track of all operands of this instructions which belong to the 1391 // same class. 1392 for (unsigned i = 0, e = MI->AsmOperands.size(); i != e; ++i) { 1393 const MatchableInfo::AsmOperand &Op = MI->AsmOperands[i]; 1394 if (Op.Class->ParserMethod.empty()) 1395 continue; 1396 unsigned &OperandMask = OpClassMask[Op.Class]; 1397 OperandMask |= (1 << i); 1398 } 1399 1400 // Generate operand match info for each mnemonic/operand class pair. 1401 for (const auto &OCM : OpClassMask) { 1402 unsigned OpMask = OCM.second; 1403 ClassInfo *CI = OCM.first; 1404 OperandMatchInfo.push_back(OperandMatchEntry::create(MI.get(), CI, 1405 OpMask)); 1406 } 1407 } 1408 } 1409 1410 void AsmMatcherInfo::buildInfo() { 1411 // Build information about all of the AssemblerPredicates. 1412 std::vector<Record*> AllPredicates = 1413 Records.getAllDerivedDefinitions("Predicate"); 1414 for (Record *Pred : AllPredicates) { 1415 // Ignore predicates that are not intended for the assembler. 1416 if (!Pred->getValueAsBit("AssemblerMatcherPredicate")) 1417 continue; 1418 1419 if (Pred->getName().empty()) 1420 PrintFatalError(Pred->getLoc(), "Predicate has no name!"); 1421 1422 SubtargetFeatures.insert(std::make_pair( 1423 Pred, SubtargetFeatureInfo(Pred, SubtargetFeatures.size()))); 1424 DEBUG(SubtargetFeatures.find(Pred)->second.dump()); 1425 assert(SubtargetFeatures.size() <= 64 && "Too many subtarget features!"); 1426 } 1427 1428 bool HasMnemonicFirst = AsmParser->getValueAsBit("HasMnemonicFirst"); 1429 1430 // Parse the instructions; we need to do this first so that we can gather the 1431 // singleton register classes. 1432 SmallPtrSet<Record*, 16> SingletonRegisters; 1433 unsigned VariantCount = Target.getAsmParserVariantCount(); 1434 for (unsigned VC = 0; VC != VariantCount; ++VC) { 1435 Record *AsmVariant = Target.getAsmParserVariant(VC); 1436 std::string CommentDelimiter = 1437 AsmVariant->getValueAsString("CommentDelimiter"); 1438 AsmVariantInfo Variant; 1439 Variant.RegisterPrefix = AsmVariant->getValueAsString("RegisterPrefix"); 1440 Variant.TokenizingCharacters = 1441 AsmVariant->getValueAsString("TokenizingCharacters"); 1442 Variant.SeparatorCharacters = 1443 AsmVariant->getValueAsString("SeparatorCharacters"); 1444 Variant.BreakCharacters = 1445 AsmVariant->getValueAsString("BreakCharacters"); 1446 Variant.AsmVariantNo = AsmVariant->getValueAsInt("Variant"); 1447 1448 for (const CodeGenInstruction *CGI : Target.getInstructionsByEnumValue()) { 1449 1450 // If the tblgen -match-prefix option is specified (for tblgen hackers), 1451 // filter the set of instructions we consider. 1452 if (!StringRef(CGI->TheDef->getName()).startswith(MatchPrefix)) 1453 continue; 1454 1455 // Ignore "codegen only" instructions. 1456 if (CGI->TheDef->getValueAsBit("isCodeGenOnly")) 1457 continue; 1458 1459 auto II = llvm::make_unique<MatchableInfo>(*CGI); 1460 1461 II->initialize(*this, SingletonRegisters, Variant, HasMnemonicFirst); 1462 1463 // Ignore instructions which shouldn't be matched and diagnose invalid 1464 // instruction definitions with an error. 1465 if (!II->validate(CommentDelimiter, true)) 1466 continue; 1467 1468 Matchables.push_back(std::move(II)); 1469 } 1470 1471 // Parse all of the InstAlias definitions and stick them in the list of 1472 // matchables. 1473 std::vector<Record*> AllInstAliases = 1474 Records.getAllDerivedDefinitions("InstAlias"); 1475 for (unsigned i = 0, e = AllInstAliases.size(); i != e; ++i) { 1476 auto Alias = llvm::make_unique<CodeGenInstAlias>(AllInstAliases[i], 1477 Variant.AsmVariantNo, 1478 Target); 1479 1480 // If the tblgen -match-prefix option is specified (for tblgen hackers), 1481 // filter the set of instruction aliases we consider, based on the target 1482 // instruction. 1483 if (!StringRef(Alias->ResultInst->TheDef->getName()) 1484 .startswith( MatchPrefix)) 1485 continue; 1486 1487 auto II = llvm::make_unique<MatchableInfo>(std::move(Alias)); 1488 1489 II->initialize(*this, SingletonRegisters, Variant, HasMnemonicFirst); 1490 1491 // Validate the alias definitions. 1492 II->validate(CommentDelimiter, false); 1493 1494 Matchables.push_back(std::move(II)); 1495 } 1496 } 1497 1498 // Build info for the register classes. 1499 buildRegisterClasses(SingletonRegisters); 1500 1501 // Build info for the user defined assembly operand classes. 1502 buildOperandClasses(); 1503 1504 // Build the information about matchables, now that we have fully formed 1505 // classes. 1506 std::vector<std::unique_ptr<MatchableInfo>> NewMatchables; 1507 for (auto &II : Matchables) { 1508 // Parse the tokens after the mnemonic. 1509 // Note: buildInstructionOperandReference may insert new AsmOperands, so 1510 // don't precompute the loop bound. 1511 for (unsigned i = 0; i != II->AsmOperands.size(); ++i) { 1512 MatchableInfo::AsmOperand &Op = II->AsmOperands[i]; 1513 StringRef Token = Op.Token; 1514 1515 // Check for singleton registers. 1516 if (Record *RegRecord = Op.SingletonReg) { 1517 Op.Class = RegisterClasses[RegRecord]; 1518 assert(Op.Class && Op.Class->Registers.size() == 1 && 1519 "Unexpected class for singleton register"); 1520 continue; 1521 } 1522 1523 // Check for simple tokens. 1524 if (Token[0] != '$') { 1525 Op.Class = getTokenClass(Token); 1526 continue; 1527 } 1528 1529 if (Token.size() > 1 && isdigit(Token[1])) { 1530 Op.Class = getTokenClass(Token); 1531 continue; 1532 } 1533 1534 // Otherwise this is an operand reference. 1535 StringRef OperandName; 1536 if (Token[1] == '{') 1537 OperandName = Token.substr(2, Token.size() - 3); 1538 else 1539 OperandName = Token.substr(1); 1540 1541 if (II->DefRec.is<const CodeGenInstruction*>()) 1542 buildInstructionOperandReference(II.get(), OperandName, i); 1543 else 1544 buildAliasOperandReference(II.get(), OperandName, Op); 1545 } 1546 1547 if (II->DefRec.is<const CodeGenInstruction*>()) { 1548 II->buildInstructionResultOperands(); 1549 // If the instruction has a two-operand alias, build up the 1550 // matchable here. We'll add them in bulk at the end to avoid 1551 // confusing this loop. 1552 std::string Constraint = 1553 II->TheDef->getValueAsString("TwoOperandAliasConstraint"); 1554 if (Constraint != "") { 1555 // Start by making a copy of the original matchable. 1556 auto AliasII = llvm::make_unique<MatchableInfo>(*II); 1557 1558 // Adjust it to be a two-operand alias. 1559 AliasII->formTwoOperandAlias(Constraint); 1560 1561 // Add the alias to the matchables list. 1562 NewMatchables.push_back(std::move(AliasII)); 1563 } 1564 } else 1565 II->buildAliasResultOperands(); 1566 } 1567 if (!NewMatchables.empty()) 1568 Matchables.insert(Matchables.end(), 1569 std::make_move_iterator(NewMatchables.begin()), 1570 std::make_move_iterator(NewMatchables.end())); 1571 1572 // Process token alias definitions and set up the associated superclass 1573 // information. 1574 std::vector<Record*> AllTokenAliases = 1575 Records.getAllDerivedDefinitions("TokenAlias"); 1576 for (Record *Rec : AllTokenAliases) { 1577 ClassInfo *FromClass = getTokenClass(Rec->getValueAsString("FromToken")); 1578 ClassInfo *ToClass = getTokenClass(Rec->getValueAsString("ToToken")); 1579 if (FromClass == ToClass) 1580 PrintFatalError(Rec->getLoc(), 1581 "error: Destination value identical to source value."); 1582 FromClass->SuperClasses.push_back(ToClass); 1583 } 1584 1585 // Reorder classes so that classes precede super classes. 1586 Classes.sort(); 1587 1588 #ifndef NDEBUG 1589 // Verify that the table is now sorted 1590 for (auto I = Classes.begin(), E = Classes.end(); I != E; ++I) { 1591 for (auto J = I; J != E; ++J) { 1592 assert(!(*J < *I)); 1593 assert(I == J || !J->isSubsetOf(*I)); 1594 } 1595 } 1596 #endif 1597 } 1598 1599 /// buildInstructionOperandReference - The specified operand is a reference to a 1600 /// named operand such as $src. Resolve the Class and OperandInfo pointers. 1601 void AsmMatcherInfo:: 1602 buildInstructionOperandReference(MatchableInfo *II, 1603 StringRef OperandName, 1604 unsigned AsmOpIdx) { 1605 const CodeGenInstruction &CGI = *II->DefRec.get<const CodeGenInstruction*>(); 1606 const CGIOperandList &Operands = CGI.Operands; 1607 MatchableInfo::AsmOperand *Op = &II->AsmOperands[AsmOpIdx]; 1608 1609 // Map this token to an operand. 1610 unsigned Idx; 1611 if (!Operands.hasOperandNamed(OperandName, Idx)) 1612 PrintFatalError(II->TheDef->getLoc(), 1613 "error: unable to find operand: '" + OperandName + "'"); 1614 1615 // If the instruction operand has multiple suboperands, but the parser 1616 // match class for the asm operand is still the default "ImmAsmOperand", 1617 // then handle each suboperand separately. 1618 if (Op->SubOpIdx == -1 && Operands[Idx].MINumOperands > 1) { 1619 Record *Rec = Operands[Idx].Rec; 1620 assert(Rec->isSubClassOf("Operand") && "Unexpected operand!"); 1621 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass"); 1622 if (MatchClass && MatchClass->getValueAsString("Name") == "Imm") { 1623 // Insert remaining suboperands after AsmOpIdx in II->AsmOperands. 1624 StringRef Token = Op->Token; // save this in case Op gets moved 1625 for (unsigned SI = 1, SE = Operands[Idx].MINumOperands; SI != SE; ++SI) { 1626 MatchableInfo::AsmOperand NewAsmOp(/*IsIsolatedToken=*/true, Token); 1627 NewAsmOp.SubOpIdx = SI; 1628 II->AsmOperands.insert(II->AsmOperands.begin()+AsmOpIdx+SI, NewAsmOp); 1629 } 1630 // Replace Op with first suboperand. 1631 Op = &II->AsmOperands[AsmOpIdx]; // update the pointer in case it moved 1632 Op->SubOpIdx = 0; 1633 } 1634 } 1635 1636 // Set up the operand class. 1637 Op->Class = getOperandClass(Operands[Idx], Op->SubOpIdx); 1638 1639 // If the named operand is tied, canonicalize it to the untied operand. 1640 // For example, something like: 1641 // (outs GPR:$dst), (ins GPR:$src) 1642 // with an asmstring of 1643 // "inc $src" 1644 // we want to canonicalize to: 1645 // "inc $dst" 1646 // so that we know how to provide the $dst operand when filling in the result. 1647 int OITied = -1; 1648 if (Operands[Idx].MINumOperands == 1) 1649 OITied = Operands[Idx].getTiedRegister(); 1650 if (OITied != -1) { 1651 // The tied operand index is an MIOperand index, find the operand that 1652 // contains it. 1653 std::pair<unsigned, unsigned> Idx = Operands.getSubOperandNumber(OITied); 1654 OperandName = Operands[Idx.first].Name; 1655 Op->SubOpIdx = Idx.second; 1656 } 1657 1658 Op->SrcOpName = OperandName; 1659 } 1660 1661 /// buildAliasOperandReference - When parsing an operand reference out of the 1662 /// matching string (e.g. "movsx $src, $dst"), determine what the class of the 1663 /// operand reference is by looking it up in the result pattern definition. 1664 void AsmMatcherInfo::buildAliasOperandReference(MatchableInfo *II, 1665 StringRef OperandName, 1666 MatchableInfo::AsmOperand &Op) { 1667 const CodeGenInstAlias &CGA = *II->DefRec.get<const CodeGenInstAlias*>(); 1668 1669 // Set up the operand class. 1670 for (unsigned i = 0, e = CGA.ResultOperands.size(); i != e; ++i) 1671 if (CGA.ResultOperands[i].isRecord() && 1672 CGA.ResultOperands[i].getName() == OperandName) { 1673 // It's safe to go with the first one we find, because CodeGenInstAlias 1674 // validates that all operands with the same name have the same record. 1675 Op.SubOpIdx = CGA.ResultInstOperandIndex[i].second; 1676 // Use the match class from the Alias definition, not the 1677 // destination instruction, as we may have an immediate that's 1678 // being munged by the match class. 1679 Op.Class = getOperandClass(CGA.ResultOperands[i].getRecord(), 1680 Op.SubOpIdx); 1681 Op.SrcOpName = OperandName; 1682 return; 1683 } 1684 1685 PrintFatalError(II->TheDef->getLoc(), 1686 "error: unable to find operand: '" + OperandName + "'"); 1687 } 1688 1689 void MatchableInfo::buildInstructionResultOperands() { 1690 const CodeGenInstruction *ResultInst = getResultInst(); 1691 1692 // Loop over all operands of the result instruction, determining how to 1693 // populate them. 1694 for (const CGIOperandList::OperandInfo &OpInfo : ResultInst->Operands) { 1695 // If this is a tied operand, just copy from the previously handled operand. 1696 int TiedOp = -1; 1697 if (OpInfo.MINumOperands == 1) 1698 TiedOp = OpInfo.getTiedRegister(); 1699 if (TiedOp != -1) { 1700 ResOperands.push_back(ResOperand::getTiedOp(TiedOp)); 1701 continue; 1702 } 1703 1704 // Find out what operand from the asmparser this MCInst operand comes from. 1705 int SrcOperand = findAsmOperandNamed(OpInfo.Name); 1706 if (OpInfo.Name.empty() || SrcOperand == -1) { 1707 // This may happen for operands that are tied to a suboperand of a 1708 // complex operand. Simply use a dummy value here; nobody should 1709 // use this operand slot. 1710 // FIXME: The long term goal is for the MCOperand list to not contain 1711 // tied operands at all. 1712 ResOperands.push_back(ResOperand::getImmOp(0)); 1713 continue; 1714 } 1715 1716 // Check if the one AsmOperand populates the entire operand. 1717 unsigned NumOperands = OpInfo.MINumOperands; 1718 if (AsmOperands[SrcOperand].SubOpIdx == -1) { 1719 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand, NumOperands)); 1720 continue; 1721 } 1722 1723 // Add a separate ResOperand for each suboperand. 1724 for (unsigned AI = 0; AI < NumOperands; ++AI) { 1725 assert(AsmOperands[SrcOperand+AI].SubOpIdx == (int)AI && 1726 AsmOperands[SrcOperand+AI].SrcOpName == OpInfo.Name && 1727 "unexpected AsmOperands for suboperands"); 1728 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand + AI, 1)); 1729 } 1730 } 1731 } 1732 1733 void MatchableInfo::buildAliasResultOperands() { 1734 const CodeGenInstAlias &CGA = *DefRec.get<const CodeGenInstAlias*>(); 1735 const CodeGenInstruction *ResultInst = getResultInst(); 1736 1737 // Loop over all operands of the result instruction, determining how to 1738 // populate them. 1739 unsigned AliasOpNo = 0; 1740 unsigned LastOpNo = CGA.ResultInstOperandIndex.size(); 1741 for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) { 1742 const CGIOperandList::OperandInfo *OpInfo = &ResultInst->Operands[i]; 1743 1744 // If this is a tied operand, just copy from the previously handled operand. 1745 int TiedOp = -1; 1746 if (OpInfo->MINumOperands == 1) 1747 TiedOp = OpInfo->getTiedRegister(); 1748 if (TiedOp != -1) { 1749 ResOperands.push_back(ResOperand::getTiedOp(TiedOp)); 1750 continue; 1751 } 1752 1753 // Handle all the suboperands for this operand. 1754 const std::string &OpName = OpInfo->Name; 1755 for ( ; AliasOpNo < LastOpNo && 1756 CGA.ResultInstOperandIndex[AliasOpNo].first == i; ++AliasOpNo) { 1757 int SubIdx = CGA.ResultInstOperandIndex[AliasOpNo].second; 1758 1759 // Find out what operand from the asmparser that this MCInst operand 1760 // comes from. 1761 switch (CGA.ResultOperands[AliasOpNo].Kind) { 1762 case CodeGenInstAlias::ResultOperand::K_Record: { 1763 StringRef Name = CGA.ResultOperands[AliasOpNo].getName(); 1764 int SrcOperand = findAsmOperand(Name, SubIdx); 1765 if (SrcOperand == -1) 1766 PrintFatalError(TheDef->getLoc(), "Instruction '" + 1767 TheDef->getName() + "' has operand '" + OpName + 1768 "' that doesn't appear in asm string!"); 1769 unsigned NumOperands = (SubIdx == -1 ? OpInfo->MINumOperands : 1); 1770 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand, 1771 NumOperands)); 1772 break; 1773 } 1774 case CodeGenInstAlias::ResultOperand::K_Imm: { 1775 int64_t ImmVal = CGA.ResultOperands[AliasOpNo].getImm(); 1776 ResOperands.push_back(ResOperand::getImmOp(ImmVal)); 1777 break; 1778 } 1779 case CodeGenInstAlias::ResultOperand::K_Reg: { 1780 Record *Reg = CGA.ResultOperands[AliasOpNo].getRegister(); 1781 ResOperands.push_back(ResOperand::getRegOp(Reg)); 1782 break; 1783 } 1784 } 1785 } 1786 } 1787 } 1788 1789 static unsigned getConverterOperandID(const std::string &Name, 1790 SmallSetVector<std::string, 16> &Table, 1791 bool &IsNew) { 1792 IsNew = Table.insert(Name); 1793 1794 unsigned ID = IsNew ? Table.size() - 1 : 1795 std::find(Table.begin(), Table.end(), Name) - Table.begin(); 1796 1797 assert(ID < Table.size()); 1798 1799 return ID; 1800 } 1801 1802 1803 static void emitConvertFuncs(CodeGenTarget &Target, StringRef ClassName, 1804 std::vector<std::unique_ptr<MatchableInfo>> &Infos, 1805 bool HasMnemonicFirst, raw_ostream &OS) { 1806 SmallSetVector<std::string, 16> OperandConversionKinds; 1807 SmallSetVector<std::string, 16> InstructionConversionKinds; 1808 std::vector<std::vector<uint8_t> > ConversionTable; 1809 size_t MaxRowLength = 2; // minimum is custom converter plus terminator. 1810 1811 // TargetOperandClass - This is the target's operand class, like X86Operand. 1812 std::string TargetOperandClass = Target.getName() + "Operand"; 1813 1814 // Write the convert function to a separate stream, so we can drop it after 1815 // the enum. We'll build up the conversion handlers for the individual 1816 // operand types opportunistically as we encounter them. 1817 std::string ConvertFnBody; 1818 raw_string_ostream CvtOS(ConvertFnBody); 1819 // Start the unified conversion function. 1820 CvtOS << "void " << Target.getName() << ClassName << "::\n" 1821 << "convertToMCInst(unsigned Kind, MCInst &Inst, " 1822 << "unsigned Opcode,\n" 1823 << " const OperandVector" 1824 << " &Operands) {\n" 1825 << " assert(Kind < CVT_NUM_SIGNATURES && \"Invalid signature!\");\n" 1826 << " const uint8_t *Converter = ConversionTable[Kind];\n" 1827 << " Inst.setOpcode(Opcode);\n" 1828 << " for (const uint8_t *p = Converter; *p; p+= 2) {\n" 1829 << " switch (*p) {\n" 1830 << " default: llvm_unreachable(\"invalid conversion entry!\");\n" 1831 << " case CVT_Reg:\n" 1832 << " static_cast<" << TargetOperandClass 1833 << "&>(*Operands[*(p + 1)]).addRegOperands(Inst, 1);\n" 1834 << " break;\n" 1835 << " case CVT_Tied:\n" 1836 << " Inst.addOperand(Inst.getOperand(*(p + 1)));\n" 1837 << " break;\n"; 1838 1839 std::string OperandFnBody; 1840 raw_string_ostream OpOS(OperandFnBody); 1841 // Start the operand number lookup function. 1842 OpOS << "void " << Target.getName() << ClassName << "::\n" 1843 << "convertToMapAndConstraints(unsigned Kind,\n"; 1844 OpOS.indent(27); 1845 OpOS << "const OperandVector &Operands) {\n" 1846 << " assert(Kind < CVT_NUM_SIGNATURES && \"Invalid signature!\");\n" 1847 << " unsigned NumMCOperands = 0;\n" 1848 << " const uint8_t *Converter = ConversionTable[Kind];\n" 1849 << " for (const uint8_t *p = Converter; *p; p+= 2) {\n" 1850 << " switch (*p) {\n" 1851 << " default: llvm_unreachable(\"invalid conversion entry!\");\n" 1852 << " case CVT_Reg:\n" 1853 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n" 1854 << " Operands[*(p + 1)]->setConstraint(\"r\");\n" 1855 << " ++NumMCOperands;\n" 1856 << " break;\n" 1857 << " case CVT_Tied:\n" 1858 << " ++NumMCOperands;\n" 1859 << " break;\n"; 1860 1861 // Pre-populate the operand conversion kinds with the standard always 1862 // available entries. 1863 OperandConversionKinds.insert("CVT_Done"); 1864 OperandConversionKinds.insert("CVT_Reg"); 1865 OperandConversionKinds.insert("CVT_Tied"); 1866 enum { CVT_Done, CVT_Reg, CVT_Tied }; 1867 1868 for (auto &II : Infos) { 1869 // Check if we have a custom match function. 1870 std::string AsmMatchConverter = 1871 II->getResultInst()->TheDef->getValueAsString("AsmMatchConverter"); 1872 if (!AsmMatchConverter.empty() && II->UseInstAsmMatchConverter) { 1873 std::string Signature = "ConvertCustom_" + AsmMatchConverter; 1874 II->ConversionFnKind = Signature; 1875 1876 // Check if we have already generated this signature. 1877 if (!InstructionConversionKinds.insert(Signature)) 1878 continue; 1879 1880 // Remember this converter for the kind enum. 1881 unsigned KindID = OperandConversionKinds.size(); 1882 OperandConversionKinds.insert("CVT_" + 1883 getEnumNameForToken(AsmMatchConverter)); 1884 1885 // Add the converter row for this instruction. 1886 ConversionTable.emplace_back(); 1887 ConversionTable.back().push_back(KindID); 1888 ConversionTable.back().push_back(CVT_Done); 1889 1890 // Add the handler to the conversion driver function. 1891 CvtOS << " case CVT_" 1892 << getEnumNameForToken(AsmMatchConverter) << ":\n" 1893 << " " << AsmMatchConverter << "(Inst, Operands);\n" 1894 << " break;\n"; 1895 1896 // FIXME: Handle the operand number lookup for custom match functions. 1897 continue; 1898 } 1899 1900 // Build the conversion function signature. 1901 std::string Signature = "Convert"; 1902 1903 std::vector<uint8_t> ConversionRow; 1904 1905 // Compute the convert enum and the case body. 1906 MaxRowLength = std::max(MaxRowLength, II->ResOperands.size()*2 + 1 ); 1907 1908 for (unsigned i = 0, e = II->ResOperands.size(); i != e; ++i) { 1909 const MatchableInfo::ResOperand &OpInfo = II->ResOperands[i]; 1910 1911 // Generate code to populate each result operand. 1912 switch (OpInfo.Kind) { 1913 case MatchableInfo::ResOperand::RenderAsmOperand: { 1914 // This comes from something we parsed. 1915 const MatchableInfo::AsmOperand &Op = 1916 II->AsmOperands[OpInfo.AsmOperandNum]; 1917 1918 // Registers are always converted the same, don't duplicate the 1919 // conversion function based on them. 1920 Signature += "__"; 1921 std::string Class; 1922 Class = Op.Class->isRegisterClass() ? "Reg" : Op.Class->ClassName; 1923 Signature += Class; 1924 Signature += utostr(OpInfo.MINumOperands); 1925 Signature += "_" + itostr(OpInfo.AsmOperandNum); 1926 1927 // Add the conversion kind, if necessary, and get the associated ID 1928 // the index of its entry in the vector). 1929 std::string Name = "CVT_" + (Op.Class->isRegisterClass() ? "Reg" : 1930 Op.Class->RenderMethod); 1931 Name = getEnumNameForToken(Name); 1932 1933 bool IsNewConverter = false; 1934 unsigned ID = getConverterOperandID(Name, OperandConversionKinds, 1935 IsNewConverter); 1936 1937 // Add the operand entry to the instruction kind conversion row. 1938 ConversionRow.push_back(ID); 1939 ConversionRow.push_back(OpInfo.AsmOperandNum + HasMnemonicFirst); 1940 1941 if (!IsNewConverter) 1942 break; 1943 1944 // This is a new operand kind. Add a handler for it to the 1945 // converter driver. 1946 CvtOS << " case " << Name << ":\n" 1947 << " static_cast<" << TargetOperandClass 1948 << "&>(*Operands[*(p + 1)])." << Op.Class->RenderMethod 1949 << "(Inst, " << OpInfo.MINumOperands << ");\n" 1950 << " break;\n"; 1951 1952 // Add a handler for the operand number lookup. 1953 OpOS << " case " << Name << ":\n" 1954 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"; 1955 1956 if (Op.Class->isRegisterClass()) 1957 OpOS << " Operands[*(p + 1)]->setConstraint(\"r\");\n"; 1958 else 1959 OpOS << " Operands[*(p + 1)]->setConstraint(\"m\");\n"; 1960 OpOS << " NumMCOperands += " << OpInfo.MINumOperands << ";\n" 1961 << " break;\n"; 1962 break; 1963 } 1964 case MatchableInfo::ResOperand::TiedOperand: { 1965 // If this operand is tied to a previous one, just copy the MCInst 1966 // operand from the earlier one.We can only tie single MCOperand values. 1967 assert(OpInfo.MINumOperands == 1 && "Not a singular MCOperand"); 1968 unsigned TiedOp = OpInfo.TiedOperandNum; 1969 assert(i > TiedOp && "Tied operand precedes its target!"); 1970 Signature += "__Tie" + utostr(TiedOp); 1971 ConversionRow.push_back(CVT_Tied); 1972 ConversionRow.push_back(TiedOp); 1973 break; 1974 } 1975 case MatchableInfo::ResOperand::ImmOperand: { 1976 int64_t Val = OpInfo.ImmVal; 1977 std::string Ty = "imm_" + itostr(Val); 1978 Ty = getEnumNameForToken(Ty); 1979 Signature += "__" + Ty; 1980 1981 std::string Name = "CVT_" + Ty; 1982 bool IsNewConverter = false; 1983 unsigned ID = getConverterOperandID(Name, OperandConversionKinds, 1984 IsNewConverter); 1985 // Add the operand entry to the instruction kind conversion row. 1986 ConversionRow.push_back(ID); 1987 ConversionRow.push_back(0); 1988 1989 if (!IsNewConverter) 1990 break; 1991 1992 CvtOS << " case " << Name << ":\n" 1993 << " Inst.addOperand(MCOperand::createImm(" << Val << "));\n" 1994 << " break;\n"; 1995 1996 OpOS << " case " << Name << ":\n" 1997 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n" 1998 << " Operands[*(p + 1)]->setConstraint(\"\");\n" 1999 << " ++NumMCOperands;\n" 2000 << " break;\n"; 2001 break; 2002 } 2003 case MatchableInfo::ResOperand::RegOperand: { 2004 std::string Reg, Name; 2005 if (!OpInfo.Register) { 2006 Name = "reg0"; 2007 Reg = "0"; 2008 } else { 2009 Reg = getQualifiedName(OpInfo.Register); 2010 Name = "reg" + OpInfo.Register->getName(); 2011 } 2012 Signature += "__" + Name; 2013 Name = "CVT_" + Name; 2014 bool IsNewConverter = false; 2015 unsigned ID = getConverterOperandID(Name, OperandConversionKinds, 2016 IsNewConverter); 2017 // Add the operand entry to the instruction kind conversion row. 2018 ConversionRow.push_back(ID); 2019 ConversionRow.push_back(0); 2020 2021 if (!IsNewConverter) 2022 break; 2023 CvtOS << " case " << Name << ":\n" 2024 << " Inst.addOperand(MCOperand::createReg(" << Reg << "));\n" 2025 << " break;\n"; 2026 2027 OpOS << " case " << Name << ":\n" 2028 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n" 2029 << " Operands[*(p + 1)]->setConstraint(\"m\");\n" 2030 << " ++NumMCOperands;\n" 2031 << " break;\n"; 2032 } 2033 } 2034 } 2035 2036 // If there were no operands, add to the signature to that effect 2037 if (Signature == "Convert") 2038 Signature += "_NoOperands"; 2039 2040 II->ConversionFnKind = Signature; 2041 2042 // Save the signature. If we already have it, don't add a new row 2043 // to the table. 2044 if (!InstructionConversionKinds.insert(Signature)) 2045 continue; 2046 2047 // Add the row to the table. 2048 ConversionTable.push_back(std::move(ConversionRow)); 2049 } 2050 2051 // Finish up the converter driver function. 2052 CvtOS << " }\n }\n}\n\n"; 2053 2054 // Finish up the operand number lookup function. 2055 OpOS << " }\n }\n}\n\n"; 2056 2057 OS << "namespace {\n"; 2058 2059 // Output the operand conversion kind enum. 2060 OS << "enum OperatorConversionKind {\n"; 2061 for (const std::string &Converter : OperandConversionKinds) 2062 OS << " " << Converter << ",\n"; 2063 OS << " CVT_NUM_CONVERTERS\n"; 2064 OS << "};\n\n"; 2065 2066 // Output the instruction conversion kind enum. 2067 OS << "enum InstructionConversionKind {\n"; 2068 for (const std::string &Signature : InstructionConversionKinds) 2069 OS << " " << Signature << ",\n"; 2070 OS << " CVT_NUM_SIGNATURES\n"; 2071 OS << "};\n\n"; 2072 2073 2074 OS << "} // end anonymous namespace\n\n"; 2075 2076 // Output the conversion table. 2077 OS << "static const uint8_t ConversionTable[CVT_NUM_SIGNATURES][" 2078 << MaxRowLength << "] = {\n"; 2079 2080 for (unsigned Row = 0, ERow = ConversionTable.size(); Row != ERow; ++Row) { 2081 assert(ConversionTable[Row].size() % 2 == 0 && "bad conversion row!"); 2082 OS << " // " << InstructionConversionKinds[Row] << "\n"; 2083 OS << " { "; 2084 for (unsigned i = 0, e = ConversionTable[Row].size(); i != e; i += 2) 2085 OS << OperandConversionKinds[ConversionTable[Row][i]] << ", " 2086 << (unsigned)(ConversionTable[Row][i + 1]) << ", "; 2087 OS << "CVT_Done },\n"; 2088 } 2089 2090 OS << "};\n\n"; 2091 2092 // Spit out the conversion driver function. 2093 OS << CvtOS.str(); 2094 2095 // Spit out the operand number lookup function. 2096 OS << OpOS.str(); 2097 } 2098 2099 /// emitMatchClassEnumeration - Emit the enumeration for match class kinds. 2100 static void emitMatchClassEnumeration(CodeGenTarget &Target, 2101 std::forward_list<ClassInfo> &Infos, 2102 raw_ostream &OS) { 2103 OS << "namespace {\n\n"; 2104 2105 OS << "/// MatchClassKind - The kinds of classes which participate in\n" 2106 << "/// instruction matching.\n"; 2107 OS << "enum MatchClassKind {\n"; 2108 OS << " InvalidMatchClass = 0,\n"; 2109 for (const auto &CI : Infos) { 2110 OS << " " << CI.Name << ", // "; 2111 if (CI.Kind == ClassInfo::Token) { 2112 OS << "'" << CI.ValueName << "'\n"; 2113 } else if (CI.isRegisterClass()) { 2114 if (!CI.ValueName.empty()) 2115 OS << "register class '" << CI.ValueName << "'\n"; 2116 else 2117 OS << "derived register class\n"; 2118 } else { 2119 OS << "user defined class '" << CI.ValueName << "'\n"; 2120 } 2121 } 2122 OS << " NumMatchClassKinds\n"; 2123 OS << "};\n\n"; 2124 2125 OS << "}\n\n"; 2126 } 2127 2128 /// emitValidateOperandClass - Emit the function to validate an operand class. 2129 static void emitValidateOperandClass(AsmMatcherInfo &Info, 2130 raw_ostream &OS) { 2131 OS << "static unsigned validateOperandClass(MCParsedAsmOperand &GOp, " 2132 << "MatchClassKind Kind) {\n"; 2133 OS << " " << Info.Target.getName() << "Operand &Operand = (" 2134 << Info.Target.getName() << "Operand&)GOp;\n"; 2135 2136 // The InvalidMatchClass is not to match any operand. 2137 OS << " if (Kind == InvalidMatchClass)\n"; 2138 OS << " return MCTargetAsmParser::Match_InvalidOperand;\n\n"; 2139 2140 // Check for Token operands first. 2141 // FIXME: Use a more specific diagnostic type. 2142 OS << " if (Operand.isToken())\n"; 2143 OS << " return isSubclass(matchTokenString(Operand.getToken()), Kind) ?\n" 2144 << " MCTargetAsmParser::Match_Success :\n" 2145 << " MCTargetAsmParser::Match_InvalidOperand;\n\n"; 2146 2147 // Check the user classes. We don't care what order since we're only 2148 // actually matching against one of them. 2149 for (const auto &CI : Info.Classes) { 2150 if (!CI.isUserClass()) 2151 continue; 2152 2153 OS << " // '" << CI.ClassName << "' class\n"; 2154 OS << " if (Kind == " << CI.Name << ") {\n"; 2155 OS << " if (Operand." << CI.PredicateMethod << "())\n"; 2156 OS << " return MCTargetAsmParser::Match_Success;\n"; 2157 if (!CI.DiagnosticType.empty()) 2158 OS << " return " << Info.Target.getName() << "AsmParser::Match_" 2159 << CI.DiagnosticType << ";\n"; 2160 OS << " }\n\n"; 2161 } 2162 2163 // Check for register operands, including sub-classes. 2164 OS << " if (Operand.isReg()) {\n"; 2165 OS << " MatchClassKind OpKind;\n"; 2166 OS << " switch (Operand.getReg()) {\n"; 2167 OS << " default: OpKind = InvalidMatchClass; break;\n"; 2168 for (const auto &RC : Info.RegisterClasses) 2169 OS << " case " << Info.Target.getName() << "::" 2170 << RC.first->getName() << ": OpKind = " << RC.second->Name 2171 << "; break;\n"; 2172 OS << " }\n"; 2173 OS << " return isSubclass(OpKind, Kind) ? " 2174 << "MCTargetAsmParser::Match_Success :\n " 2175 << " MCTargetAsmParser::Match_InvalidOperand;\n }\n\n"; 2176 2177 // Generic fallthrough match failure case for operands that don't have 2178 // specialized diagnostic types. 2179 OS << " return MCTargetAsmParser::Match_InvalidOperand;\n"; 2180 OS << "}\n\n"; 2181 } 2182 2183 /// emitIsSubclass - Emit the subclass predicate function. 2184 static void emitIsSubclass(CodeGenTarget &Target, 2185 std::forward_list<ClassInfo> &Infos, 2186 raw_ostream &OS) { 2187 OS << "/// isSubclass - Compute whether \\p A is a subclass of \\p B.\n"; 2188 OS << "static bool isSubclass(MatchClassKind A, MatchClassKind B) {\n"; 2189 OS << " if (A == B)\n"; 2190 OS << " return true;\n\n"; 2191 2192 bool EmittedSwitch = false; 2193 for (const auto &A : Infos) { 2194 std::vector<StringRef> SuperClasses; 2195 for (const auto &B : Infos) { 2196 if (&A != &B && A.isSubsetOf(B)) 2197 SuperClasses.push_back(B.Name); 2198 } 2199 2200 if (SuperClasses.empty()) 2201 continue; 2202 2203 // If this is the first SuperClass, emit the switch header. 2204 if (!EmittedSwitch) { 2205 OS << " switch (A) {\n"; 2206 OS << " default:\n"; 2207 OS << " return false;\n"; 2208 EmittedSwitch = true; 2209 } 2210 2211 OS << "\n case " << A.Name << ":\n"; 2212 2213 if (SuperClasses.size() == 1) { 2214 OS << " return B == " << SuperClasses.back() << ";\n"; 2215 continue; 2216 } 2217 2218 if (!SuperClasses.empty()) { 2219 OS << " switch (B) {\n"; 2220 OS << " default: return false;\n"; 2221 for (StringRef SC : SuperClasses) 2222 OS << " case " << SC << ": return true;\n"; 2223 OS << " }\n"; 2224 } else { 2225 // No case statement to emit 2226 OS << " return false;\n"; 2227 } 2228 } 2229 2230 // If there were case statements emitted into the string stream write the 2231 // default. 2232 if (EmittedSwitch) 2233 OS << " }\n"; 2234 else 2235 OS << " return false;\n"; 2236 2237 OS << "}\n\n"; 2238 } 2239 2240 /// emitMatchTokenString - Emit the function to match a token string to the 2241 /// appropriate match class value. 2242 static void emitMatchTokenString(CodeGenTarget &Target, 2243 std::forward_list<ClassInfo> &Infos, 2244 raw_ostream &OS) { 2245 // Construct the match list. 2246 std::vector<StringMatcher::StringPair> Matches; 2247 for (const auto &CI : Infos) { 2248 if (CI.Kind == ClassInfo::Token) 2249 Matches.emplace_back(CI.ValueName, "return " + CI.Name + ";"); 2250 } 2251 2252 OS << "static MatchClassKind matchTokenString(StringRef Name) {\n"; 2253 2254 StringMatcher("Name", Matches, OS).Emit(); 2255 2256 OS << " return InvalidMatchClass;\n"; 2257 OS << "}\n\n"; 2258 } 2259 2260 /// emitMatchRegisterName - Emit the function to match a string to the target 2261 /// specific register enum. 2262 static void emitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser, 2263 raw_ostream &OS) { 2264 // Construct the match list. 2265 std::vector<StringMatcher::StringPair> Matches; 2266 const auto &Regs = Target.getRegBank().getRegisters(); 2267 for (const CodeGenRegister &Reg : Regs) { 2268 if (Reg.TheDef->getValueAsString("AsmName").empty()) 2269 continue; 2270 2271 Matches.emplace_back(Reg.TheDef->getValueAsString("AsmName"), 2272 "return " + utostr(Reg.EnumValue) + ";"); 2273 } 2274 2275 OS << "static unsigned MatchRegisterName(StringRef Name) {\n"; 2276 2277 StringMatcher("Name", Matches, OS).Emit(); 2278 2279 OS << " return 0;\n"; 2280 OS << "}\n\n"; 2281 } 2282 2283 static const char *getMinimalTypeForRange(uint64_t Range) { 2284 assert(Range <= 0xFFFFFFFFFFFFFFFFULL && "Enum too large"); 2285 if (Range > 0xFFFFFFFFULL) 2286 return "uint64_t"; 2287 if (Range > 0xFFFF) 2288 return "uint32_t"; 2289 if (Range > 0xFF) 2290 return "uint16_t"; 2291 return "uint8_t"; 2292 } 2293 2294 static const char *getMinimalRequiredFeaturesType(const AsmMatcherInfo &Info) { 2295 uint64_t MaxIndex = Info.SubtargetFeatures.size(); 2296 if (MaxIndex > 0) 2297 MaxIndex--; 2298 return getMinimalTypeForRange(1ULL << MaxIndex); 2299 } 2300 2301 /// emitSubtargetFeatureFlagEnumeration - Emit the subtarget feature flag 2302 /// definitions. 2303 static void emitSubtargetFeatureFlagEnumeration(AsmMatcherInfo &Info, 2304 raw_ostream &OS) { 2305 OS << "// Flags for subtarget features that participate in " 2306 << "instruction matching.\n"; 2307 OS << "enum SubtargetFeatureFlag : " << getMinimalRequiredFeaturesType(Info) 2308 << " {\n"; 2309 for (const auto &SF : Info.SubtargetFeatures) { 2310 const SubtargetFeatureInfo &SFI = SF.second; 2311 OS << " " << SFI.getEnumName() << " = (1ULL << " << SFI.Index << "),\n"; 2312 } 2313 OS << " Feature_None = 0\n"; 2314 OS << "};\n\n"; 2315 } 2316 2317 /// emitOperandDiagnosticTypes - Emit the operand matching diagnostic types. 2318 static void emitOperandDiagnosticTypes(AsmMatcherInfo &Info, raw_ostream &OS) { 2319 // Get the set of diagnostic types from all of the operand classes. 2320 std::set<StringRef> Types; 2321 for (const auto &OpClassEntry : Info.AsmOperandClasses) { 2322 if (!OpClassEntry.second->DiagnosticType.empty()) 2323 Types.insert(OpClassEntry.second->DiagnosticType); 2324 } 2325 2326 if (Types.empty()) return; 2327 2328 // Now emit the enum entries. 2329 for (StringRef Type : Types) 2330 OS << " Match_" << Type << ",\n"; 2331 OS << " END_OPERAND_DIAGNOSTIC_TYPES\n"; 2332 } 2333 2334 /// emitGetSubtargetFeatureName - Emit the helper function to get the 2335 /// user-level name for a subtarget feature. 2336 static void emitGetSubtargetFeatureName(AsmMatcherInfo &Info, raw_ostream &OS) { 2337 OS << "// User-level names for subtarget features that participate in\n" 2338 << "// instruction matching.\n" 2339 << "static const char *getSubtargetFeatureName(uint64_t Val) {\n"; 2340 if (!Info.SubtargetFeatures.empty()) { 2341 OS << " switch(Val) {\n"; 2342 for (const auto &SF : Info.SubtargetFeatures) { 2343 const SubtargetFeatureInfo &SFI = SF.second; 2344 // FIXME: Totally just a placeholder name to get the algorithm working. 2345 OS << " case " << SFI.getEnumName() << ": return \"" 2346 << SFI.TheDef->getValueAsString("PredicateName") << "\";\n"; 2347 } 2348 OS << " default: return \"(unknown)\";\n"; 2349 OS << " }\n"; 2350 } else { 2351 // Nothing to emit, so skip the switch 2352 OS << " return \"(unknown)\";\n"; 2353 } 2354 OS << "}\n\n"; 2355 } 2356 2357 /// emitComputeAvailableFeatures - Emit the function to compute the list of 2358 /// available features given a subtarget. 2359 static void emitComputeAvailableFeatures(AsmMatcherInfo &Info, 2360 raw_ostream &OS) { 2361 std::string ClassName = 2362 Info.AsmParser->getValueAsString("AsmParserClassName"); 2363 2364 OS << "uint64_t " << Info.Target.getName() << ClassName << "::\n" 2365 << "ComputeAvailableFeatures(const FeatureBitset& FB) const {\n"; 2366 OS << " uint64_t Features = 0;\n"; 2367 for (const auto &SF : Info.SubtargetFeatures) { 2368 const SubtargetFeatureInfo &SFI = SF.second; 2369 2370 OS << " if ("; 2371 std::string CondStorage = 2372 SFI.TheDef->getValueAsString("AssemblerCondString"); 2373 StringRef Conds = CondStorage; 2374 std::pair<StringRef,StringRef> Comma = Conds.split(','); 2375 bool First = true; 2376 do { 2377 if (!First) 2378 OS << " && "; 2379 2380 bool Neg = false; 2381 StringRef Cond = Comma.first; 2382 if (Cond[0] == '!') { 2383 Neg = true; 2384 Cond = Cond.substr(1); 2385 } 2386 2387 OS << "("; 2388 if (Neg) 2389 OS << "!"; 2390 OS << "FB[" << Info.Target.getName() << "::" << Cond << "])"; 2391 2392 if (Comma.second.empty()) 2393 break; 2394 2395 First = false; 2396 Comma = Comma.second.split(','); 2397 } while (true); 2398 2399 OS << ")\n"; 2400 OS << " Features |= " << SFI.getEnumName() << ";\n"; 2401 } 2402 OS << " return Features;\n"; 2403 OS << "}\n\n"; 2404 } 2405 2406 static std::string GetAliasRequiredFeatures(Record *R, 2407 const AsmMatcherInfo &Info) { 2408 std::vector<Record*> ReqFeatures = R->getValueAsListOfDefs("Predicates"); 2409 std::string Result; 2410 unsigned NumFeatures = 0; 2411 for (unsigned i = 0, e = ReqFeatures.size(); i != e; ++i) { 2412 const SubtargetFeatureInfo *F = Info.getSubtargetFeature(ReqFeatures[i]); 2413 2414 if (!F) 2415 PrintFatalError(R->getLoc(), "Predicate '" + ReqFeatures[i]->getName() + 2416 "' is not marked as an AssemblerPredicate!"); 2417 2418 if (NumFeatures) 2419 Result += '|'; 2420 2421 Result += F->getEnumName(); 2422 ++NumFeatures; 2423 } 2424 2425 if (NumFeatures > 1) 2426 Result = '(' + Result + ')'; 2427 return Result; 2428 } 2429 2430 static void emitMnemonicAliasVariant(raw_ostream &OS,const AsmMatcherInfo &Info, 2431 std::vector<Record*> &Aliases, 2432 unsigned Indent = 0, 2433 StringRef AsmParserVariantName = StringRef()){ 2434 // Keep track of all the aliases from a mnemonic. Use an std::map so that the 2435 // iteration order of the map is stable. 2436 std::map<std::string, std::vector<Record*> > AliasesFromMnemonic; 2437 2438 for (Record *R : Aliases) { 2439 // FIXME: Allow AssemblerVariantName to be a comma separated list. 2440 std::string AsmVariantName = R->getValueAsString("AsmVariantName"); 2441 if (AsmVariantName != AsmParserVariantName) 2442 continue; 2443 AliasesFromMnemonic[R->getValueAsString("FromMnemonic")].push_back(R); 2444 } 2445 if (AliasesFromMnemonic.empty()) 2446 return; 2447 2448 // Process each alias a "from" mnemonic at a time, building the code executed 2449 // by the string remapper. 2450 std::vector<StringMatcher::StringPair> Cases; 2451 for (const auto &AliasEntry : AliasesFromMnemonic) { 2452 const std::vector<Record*> &ToVec = AliasEntry.second; 2453 2454 // Loop through each alias and emit code that handles each case. If there 2455 // are two instructions without predicates, emit an error. If there is one, 2456 // emit it last. 2457 std::string MatchCode; 2458 int AliasWithNoPredicate = -1; 2459 2460 for (unsigned i = 0, e = ToVec.size(); i != e; ++i) { 2461 Record *R = ToVec[i]; 2462 std::string FeatureMask = GetAliasRequiredFeatures(R, Info); 2463 2464 // If this unconditionally matches, remember it for later and diagnose 2465 // duplicates. 2466 if (FeatureMask.empty()) { 2467 if (AliasWithNoPredicate != -1) { 2468 // We can't have two aliases from the same mnemonic with no predicate. 2469 PrintError(ToVec[AliasWithNoPredicate]->getLoc(), 2470 "two MnemonicAliases with the same 'from' mnemonic!"); 2471 PrintFatalError(R->getLoc(), "this is the other MnemonicAlias."); 2472 } 2473 2474 AliasWithNoPredicate = i; 2475 continue; 2476 } 2477 if (R->getValueAsString("ToMnemonic") == AliasEntry.first) 2478 PrintFatalError(R->getLoc(), "MnemonicAlias to the same string"); 2479 2480 if (!MatchCode.empty()) 2481 MatchCode += "else "; 2482 MatchCode += "if ((Features & " + FeatureMask + ") == "+FeatureMask+")\n"; 2483 MatchCode += " Mnemonic = \"" +R->getValueAsString("ToMnemonic")+"\";\n"; 2484 } 2485 2486 if (AliasWithNoPredicate != -1) { 2487 Record *R = ToVec[AliasWithNoPredicate]; 2488 if (!MatchCode.empty()) 2489 MatchCode += "else\n "; 2490 MatchCode += "Mnemonic = \"" + R->getValueAsString("ToMnemonic")+"\";\n"; 2491 } 2492 2493 MatchCode += "return;"; 2494 2495 Cases.push_back(std::make_pair(AliasEntry.first, MatchCode)); 2496 } 2497 StringMatcher("Mnemonic", Cases, OS).Emit(Indent); 2498 } 2499 2500 /// emitMnemonicAliases - If the target has any MnemonicAlias<> definitions, 2501 /// emit a function for them and return true, otherwise return false. 2502 static bool emitMnemonicAliases(raw_ostream &OS, const AsmMatcherInfo &Info, 2503 CodeGenTarget &Target) { 2504 // Ignore aliases when match-prefix is set. 2505 if (!MatchPrefix.empty()) 2506 return false; 2507 2508 std::vector<Record*> Aliases = 2509 Info.getRecords().getAllDerivedDefinitions("MnemonicAlias"); 2510 if (Aliases.empty()) return false; 2511 2512 OS << "static void applyMnemonicAliases(StringRef &Mnemonic, " 2513 "uint64_t Features, unsigned VariantID) {\n"; 2514 OS << " switch (VariantID) {\n"; 2515 unsigned VariantCount = Target.getAsmParserVariantCount(); 2516 for (unsigned VC = 0; VC != VariantCount; ++VC) { 2517 Record *AsmVariant = Target.getAsmParserVariant(VC); 2518 int AsmParserVariantNo = AsmVariant->getValueAsInt("Variant"); 2519 std::string AsmParserVariantName = AsmVariant->getValueAsString("Name"); 2520 OS << " case " << AsmParserVariantNo << ":\n"; 2521 emitMnemonicAliasVariant(OS, Info, Aliases, /*Indent=*/2, 2522 AsmParserVariantName); 2523 OS << " break;\n"; 2524 } 2525 OS << " }\n"; 2526 2527 // Emit aliases that apply to all variants. 2528 emitMnemonicAliasVariant(OS, Info, Aliases); 2529 2530 OS << "}\n\n"; 2531 2532 return true; 2533 } 2534 2535 static void emitCustomOperandParsing(raw_ostream &OS, CodeGenTarget &Target, 2536 const AsmMatcherInfo &Info, StringRef ClassName, 2537 StringToOffsetTable &StringTable, 2538 unsigned MaxMnemonicIndex, bool HasMnemonicFirst) { 2539 unsigned MaxMask = 0; 2540 for (const OperandMatchEntry &OMI : Info.OperandMatchInfo) { 2541 MaxMask |= OMI.OperandMask; 2542 } 2543 2544 // Emit the static custom operand parsing table; 2545 OS << "namespace {\n"; 2546 OS << " struct OperandMatchEntry {\n"; 2547 OS << " " << getMinimalRequiredFeaturesType(Info) 2548 << " RequiredFeatures;\n"; 2549 OS << " " << getMinimalTypeForRange(MaxMnemonicIndex) 2550 << " Mnemonic;\n"; 2551 OS << " " << getMinimalTypeForRange(std::distance( 2552 Info.Classes.begin(), Info.Classes.end())) << " Class;\n"; 2553 OS << " " << getMinimalTypeForRange(MaxMask) 2554 << " OperandMask;\n\n"; 2555 OS << " StringRef getMnemonic() const {\n"; 2556 OS << " return StringRef(MnemonicTable + Mnemonic + 1,\n"; 2557 OS << " MnemonicTable[Mnemonic]);\n"; 2558 OS << " }\n"; 2559 OS << " };\n\n"; 2560 2561 OS << " // Predicate for searching for an opcode.\n"; 2562 OS << " struct LessOpcodeOperand {\n"; 2563 OS << " bool operator()(const OperandMatchEntry &LHS, StringRef RHS) {\n"; 2564 OS << " return LHS.getMnemonic() < RHS;\n"; 2565 OS << " }\n"; 2566 OS << " bool operator()(StringRef LHS, const OperandMatchEntry &RHS) {\n"; 2567 OS << " return LHS < RHS.getMnemonic();\n"; 2568 OS << " }\n"; 2569 OS << " bool operator()(const OperandMatchEntry &LHS,"; 2570 OS << " const OperandMatchEntry &RHS) {\n"; 2571 OS << " return LHS.getMnemonic() < RHS.getMnemonic();\n"; 2572 OS << " }\n"; 2573 OS << " };\n"; 2574 2575 OS << "} // end anonymous namespace.\n\n"; 2576 2577 OS << "static const OperandMatchEntry OperandMatchTable[" 2578 << Info.OperandMatchInfo.size() << "] = {\n"; 2579 2580 OS << " /* Operand List Mask, Mnemonic, Operand Class, Features */\n"; 2581 for (const OperandMatchEntry &OMI : Info.OperandMatchInfo) { 2582 const MatchableInfo &II = *OMI.MI; 2583 2584 OS << " { "; 2585 2586 // Write the required features mask. 2587 if (!II.RequiredFeatures.empty()) { 2588 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) { 2589 if (i) OS << "|"; 2590 OS << II.RequiredFeatures[i]->getEnumName(); 2591 } 2592 } else 2593 OS << "0"; 2594 2595 // Store a pascal-style length byte in the mnemonic. 2596 std::string LenMnemonic = char(II.Mnemonic.size()) + II.Mnemonic.str(); 2597 OS << ", " << StringTable.GetOrAddStringOffset(LenMnemonic, false) 2598 << " /* " << II.Mnemonic << " */, "; 2599 2600 OS << OMI.CI->Name; 2601 2602 OS << ", " << OMI.OperandMask; 2603 OS << " /* "; 2604 bool printComma = false; 2605 for (int i = 0, e = 31; i !=e; ++i) 2606 if (OMI.OperandMask & (1 << i)) { 2607 if (printComma) 2608 OS << ", "; 2609 OS << i; 2610 printComma = true; 2611 } 2612 OS << " */"; 2613 2614 OS << " },\n"; 2615 } 2616 OS << "};\n\n"; 2617 2618 // Emit the operand class switch to call the correct custom parser for 2619 // the found operand class. 2620 OS << Target.getName() << ClassName << "::OperandMatchResultTy " 2621 << Target.getName() << ClassName << "::\n" 2622 << "tryCustomParseOperand(OperandVector" 2623 << " &Operands,\n unsigned MCK) {\n\n" 2624 << " switch(MCK) {\n"; 2625 2626 for (const auto &CI : Info.Classes) { 2627 if (CI.ParserMethod.empty()) 2628 continue; 2629 OS << " case " << CI.Name << ":\n" 2630 << " return " << CI.ParserMethod << "(Operands);\n"; 2631 } 2632 2633 OS << " default:\n"; 2634 OS << " return MatchOperand_NoMatch;\n"; 2635 OS << " }\n"; 2636 OS << " return MatchOperand_NoMatch;\n"; 2637 OS << "}\n\n"; 2638 2639 // Emit the static custom operand parser. This code is very similar with 2640 // the other matcher. Also use MatchResultTy here just in case we go for 2641 // a better error handling. 2642 OS << Target.getName() << ClassName << "::OperandMatchResultTy " 2643 << Target.getName() << ClassName << "::\n" 2644 << "MatchOperandParserImpl(OperandVector" 2645 << " &Operands,\n StringRef Mnemonic) {\n"; 2646 2647 // Emit code to get the available features. 2648 OS << " // Get the current feature set.\n"; 2649 OS << " uint64_t AvailableFeatures = getAvailableFeatures();\n\n"; 2650 2651 OS << " // Get the next operand index.\n"; 2652 OS << " unsigned NextOpNum = Operands.size()" 2653 << (HasMnemonicFirst ? " - 1" : "") << ";\n"; 2654 2655 // Emit code to search the table. 2656 OS << " // Search the table.\n"; 2657 if (HasMnemonicFirst) { 2658 OS << " auto MnemonicRange =\n"; 2659 OS << " std::equal_range(std::begin(OperandMatchTable), " 2660 "std::end(OperandMatchTable),\n"; 2661 OS << " Mnemonic, LessOpcodeOperand());\n\n"; 2662 } else { 2663 OS << " auto MnemonicRange = std::make_pair(std::begin(OperandMatchTable)," 2664 " std::end(OperandMatchTable));\n"; 2665 OS << " if (!Mnemonic.empty())\n"; 2666 OS << " MnemonicRange =\n"; 2667 OS << " std::equal_range(std::begin(OperandMatchTable), " 2668 "std::end(OperandMatchTable),\n"; 2669 OS << " Mnemonic, LessOpcodeOperand());\n\n"; 2670 } 2671 2672 OS << " if (MnemonicRange.first == MnemonicRange.second)\n"; 2673 OS << " return MatchOperand_NoMatch;\n\n"; 2674 2675 OS << " for (const OperandMatchEntry *it = MnemonicRange.first,\n" 2676 << " *ie = MnemonicRange.second; it != ie; ++it) {\n"; 2677 2678 OS << " // equal_range guarantees that instruction mnemonic matches.\n"; 2679 OS << " assert(Mnemonic == it->getMnemonic());\n\n"; 2680 2681 // Emit check that the required features are available. 2682 OS << " // check if the available features match\n"; 2683 OS << " if ((AvailableFeatures & it->RequiredFeatures) " 2684 << "!= it->RequiredFeatures) {\n"; 2685 OS << " continue;\n"; 2686 OS << " }\n\n"; 2687 2688 // Emit check to ensure the operand number matches. 2689 OS << " // check if the operand in question has a custom parser.\n"; 2690 OS << " if (!(it->OperandMask & (1 << NextOpNum)))\n"; 2691 OS << " continue;\n\n"; 2692 2693 // Emit call to the custom parser method 2694 OS << " // call custom parse method to handle the operand\n"; 2695 OS << " OperandMatchResultTy Result = "; 2696 OS << "tryCustomParseOperand(Operands, it->Class);\n"; 2697 OS << " if (Result != MatchOperand_NoMatch)\n"; 2698 OS << " return Result;\n"; 2699 OS << " }\n\n"; 2700 2701 OS << " // Okay, we had no match.\n"; 2702 OS << " return MatchOperand_NoMatch;\n"; 2703 OS << "}\n\n"; 2704 } 2705 2706 void AsmMatcherEmitter::run(raw_ostream &OS) { 2707 CodeGenTarget Target(Records); 2708 Record *AsmParser = Target.getAsmParser(); 2709 std::string ClassName = AsmParser->getValueAsString("AsmParserClassName"); 2710 2711 // Compute the information on the instructions to match. 2712 AsmMatcherInfo Info(AsmParser, Target, Records); 2713 Info.buildInfo(); 2714 2715 // Sort the instruction table using the partial order on classes. We use 2716 // stable_sort to ensure that ambiguous instructions are still 2717 // deterministically ordered. 2718 std::stable_sort(Info.Matchables.begin(), Info.Matchables.end(), 2719 [](const std::unique_ptr<MatchableInfo> &a, 2720 const std::unique_ptr<MatchableInfo> &b){ 2721 return *a < *b;}); 2722 2723 #ifndef NDEBUG 2724 // Verify that the table is now sorted 2725 for (auto I = Info.Matchables.begin(), E = Info.Matchables.end(); I != E; 2726 ++I) { 2727 for (auto J = I; J != E; ++J) { 2728 assert(!(**J < **I)); 2729 } 2730 } 2731 #endif 2732 2733 DEBUG_WITH_TYPE("instruction_info", { 2734 for (const auto &MI : Info.Matchables) 2735 MI->dump(); 2736 }); 2737 2738 // Check for ambiguous matchables. 2739 DEBUG_WITH_TYPE("ambiguous_instrs", { 2740 unsigned NumAmbiguous = 0; 2741 for (auto I = Info.Matchables.begin(), E = Info.Matchables.end(); I != E; 2742 ++I) { 2743 for (auto J = std::next(I); J != E; ++J) { 2744 const MatchableInfo &A = **I; 2745 const MatchableInfo &B = **J; 2746 2747 if (A.couldMatchAmbiguouslyWith(B)) { 2748 errs() << "warning: ambiguous matchables:\n"; 2749 A.dump(); 2750 errs() << "\nis incomparable with:\n"; 2751 B.dump(); 2752 errs() << "\n\n"; 2753 ++NumAmbiguous; 2754 } 2755 } 2756 } 2757 if (NumAmbiguous) 2758 errs() << "warning: " << NumAmbiguous 2759 << " ambiguous matchables!\n"; 2760 }); 2761 2762 // Compute the information on the custom operand parsing. 2763 Info.buildOperandMatchInfo(); 2764 2765 bool HasMnemonicFirst = AsmParser->getValueAsBit("HasMnemonicFirst"); 2766 2767 // Write the output. 2768 2769 // Information for the class declaration. 2770 OS << "\n#ifdef GET_ASSEMBLER_HEADER\n"; 2771 OS << "#undef GET_ASSEMBLER_HEADER\n"; 2772 OS << " // This should be included into the middle of the declaration of\n"; 2773 OS << " // your subclasses implementation of MCTargetAsmParser.\n"; 2774 OS << " uint64_t ComputeAvailableFeatures(const FeatureBitset& FB) const;\n"; 2775 OS << " void convertToMCInst(unsigned Kind, MCInst &Inst, " 2776 << "unsigned Opcode,\n" 2777 << " const OperandVector " 2778 << "&Operands);\n"; 2779 OS << " void convertToMapAndConstraints(unsigned Kind,\n "; 2780 OS << " const OperandVector &Operands) override;\n"; 2781 if (HasMnemonicFirst) 2782 OS << " bool mnemonicIsValid(StringRef Mnemonic, unsigned VariantID);\n"; 2783 OS << " unsigned MatchInstructionImpl(const OperandVector &Operands,\n" 2784 << " MCInst &Inst,\n" 2785 << " uint64_t &ErrorInfo," 2786 << " bool matchingInlineAsm,\n" 2787 << " unsigned VariantID = 0);\n"; 2788 2789 if (!Info.OperandMatchInfo.empty()) { 2790 OS << "\n enum OperandMatchResultTy {\n"; 2791 OS << " MatchOperand_Success, // operand matched successfully\n"; 2792 OS << " MatchOperand_NoMatch, // operand did not match\n"; 2793 OS << " MatchOperand_ParseFail // operand matched but had errors\n"; 2794 OS << " };\n"; 2795 OS << " OperandMatchResultTy MatchOperandParserImpl(\n"; 2796 OS << " OperandVector &Operands,\n"; 2797 OS << " StringRef Mnemonic);\n"; 2798 2799 OS << " OperandMatchResultTy tryCustomParseOperand(\n"; 2800 OS << " OperandVector &Operands,\n"; 2801 OS << " unsigned MCK);\n\n"; 2802 } 2803 2804 OS << "#endif // GET_ASSEMBLER_HEADER_INFO\n\n"; 2805 2806 // Emit the operand match diagnostic enum names. 2807 OS << "\n#ifdef GET_OPERAND_DIAGNOSTIC_TYPES\n"; 2808 OS << "#undef GET_OPERAND_DIAGNOSTIC_TYPES\n\n"; 2809 emitOperandDiagnosticTypes(Info, OS); 2810 OS << "#endif // GET_OPERAND_DIAGNOSTIC_TYPES\n\n"; 2811 2812 2813 OS << "\n#ifdef GET_REGISTER_MATCHER\n"; 2814 OS << "#undef GET_REGISTER_MATCHER\n\n"; 2815 2816 // Emit the subtarget feature enumeration. 2817 emitSubtargetFeatureFlagEnumeration(Info, OS); 2818 2819 // Emit the function to match a register name to number. 2820 // This should be omitted for Mips target 2821 if (AsmParser->getValueAsBit("ShouldEmitMatchRegisterName")) 2822 emitMatchRegisterName(Target, AsmParser, OS); 2823 2824 OS << "#endif // GET_REGISTER_MATCHER\n\n"; 2825 2826 OS << "\n#ifdef GET_SUBTARGET_FEATURE_NAME\n"; 2827 OS << "#undef GET_SUBTARGET_FEATURE_NAME\n\n"; 2828 2829 // Generate the helper function to get the names for subtarget features. 2830 emitGetSubtargetFeatureName(Info, OS); 2831 2832 OS << "#endif // GET_SUBTARGET_FEATURE_NAME\n\n"; 2833 2834 OS << "\n#ifdef GET_MATCHER_IMPLEMENTATION\n"; 2835 OS << "#undef GET_MATCHER_IMPLEMENTATION\n\n"; 2836 2837 // Generate the function that remaps for mnemonic aliases. 2838 bool HasMnemonicAliases = emitMnemonicAliases(OS, Info, Target); 2839 2840 // Generate the convertToMCInst function to convert operands into an MCInst. 2841 // Also, generate the convertToMapAndConstraints function for MS-style inline 2842 // assembly. The latter doesn't actually generate a MCInst. 2843 emitConvertFuncs(Target, ClassName, Info.Matchables, HasMnemonicFirst, OS); 2844 2845 // Emit the enumeration for classes which participate in matching. 2846 emitMatchClassEnumeration(Target, Info.Classes, OS); 2847 2848 // Emit the routine to match token strings to their match class. 2849 emitMatchTokenString(Target, Info.Classes, OS); 2850 2851 // Emit the subclass predicate routine. 2852 emitIsSubclass(Target, Info.Classes, OS); 2853 2854 // Emit the routine to validate an operand against a match class. 2855 emitValidateOperandClass(Info, OS); 2856 2857 // Emit the available features compute function. 2858 emitComputeAvailableFeatures(Info, OS); 2859 2860 2861 StringToOffsetTable StringTable; 2862 2863 size_t MaxNumOperands = 0; 2864 unsigned MaxMnemonicIndex = 0; 2865 bool HasDeprecation = false; 2866 for (const auto &MI : Info.Matchables) { 2867 MaxNumOperands = std::max(MaxNumOperands, MI->AsmOperands.size()); 2868 HasDeprecation |= MI->HasDeprecation; 2869 2870 // Store a pascal-style length byte in the mnemonic. 2871 std::string LenMnemonic = char(MI->Mnemonic.size()) + MI->Mnemonic.str(); 2872 MaxMnemonicIndex = std::max(MaxMnemonicIndex, 2873 StringTable.GetOrAddStringOffset(LenMnemonic, false)); 2874 } 2875 2876 OS << "static const char *const MnemonicTable =\n"; 2877 StringTable.EmitString(OS); 2878 OS << ";\n\n"; 2879 2880 // Emit the static match table; unused classes get initalized to 0 which is 2881 // guaranteed to be InvalidMatchClass. 2882 // 2883 // FIXME: We can reduce the size of this table very easily. First, we change 2884 // it so that store the kinds in separate bit-fields for each index, which 2885 // only needs to be the max width used for classes at that index (we also need 2886 // to reject based on this during classification). If we then make sure to 2887 // order the match kinds appropriately (putting mnemonics last), then we 2888 // should only end up using a few bits for each class, especially the ones 2889 // following the mnemonic. 2890 OS << "namespace {\n"; 2891 OS << " struct MatchEntry {\n"; 2892 OS << " " << getMinimalTypeForRange(MaxMnemonicIndex) 2893 << " Mnemonic;\n"; 2894 OS << " uint16_t Opcode;\n"; 2895 OS << " " << getMinimalTypeForRange(Info.Matchables.size()) 2896 << " ConvertFn;\n"; 2897 OS << " " << getMinimalRequiredFeaturesType(Info) 2898 << " RequiredFeatures;\n"; 2899 OS << " " << getMinimalTypeForRange( 2900 std::distance(Info.Classes.begin(), Info.Classes.end())) 2901 << " Classes[" << MaxNumOperands << "];\n"; 2902 OS << " StringRef getMnemonic() const {\n"; 2903 OS << " return StringRef(MnemonicTable + Mnemonic + 1,\n"; 2904 OS << " MnemonicTable[Mnemonic]);\n"; 2905 OS << " }\n"; 2906 OS << " };\n\n"; 2907 2908 OS << " // Predicate for searching for an opcode.\n"; 2909 OS << " struct LessOpcode {\n"; 2910 OS << " bool operator()(const MatchEntry &LHS, StringRef RHS) {\n"; 2911 OS << " return LHS.getMnemonic() < RHS;\n"; 2912 OS << " }\n"; 2913 OS << " bool operator()(StringRef LHS, const MatchEntry &RHS) {\n"; 2914 OS << " return LHS < RHS.getMnemonic();\n"; 2915 OS << " }\n"; 2916 OS << " bool operator()(const MatchEntry &LHS, const MatchEntry &RHS) {\n"; 2917 OS << " return LHS.getMnemonic() < RHS.getMnemonic();\n"; 2918 OS << " }\n"; 2919 OS << " };\n"; 2920 2921 OS << "} // end anonymous namespace.\n\n"; 2922 2923 unsigned VariantCount = Target.getAsmParserVariantCount(); 2924 for (unsigned VC = 0; VC != VariantCount; ++VC) { 2925 Record *AsmVariant = Target.getAsmParserVariant(VC); 2926 int AsmVariantNo = AsmVariant->getValueAsInt("Variant"); 2927 2928 OS << "static const MatchEntry MatchTable" << VC << "[] = {\n"; 2929 2930 for (const auto &MI : Info.Matchables) { 2931 if (MI->AsmVariantID != AsmVariantNo) 2932 continue; 2933 2934 // Store a pascal-style length byte in the mnemonic. 2935 std::string LenMnemonic = char(MI->Mnemonic.size()) + MI->Mnemonic.str(); 2936 OS << " { " << StringTable.GetOrAddStringOffset(LenMnemonic, false) 2937 << " /* " << MI->Mnemonic << " */, " 2938 << Target.getName() << "::" 2939 << MI->getResultInst()->TheDef->getName() << ", " 2940 << MI->ConversionFnKind << ", "; 2941 2942 // Write the required features mask. 2943 if (!MI->RequiredFeatures.empty()) { 2944 for (unsigned i = 0, e = MI->RequiredFeatures.size(); i != e; ++i) { 2945 if (i) OS << "|"; 2946 OS << MI->RequiredFeatures[i]->getEnumName(); 2947 } 2948 } else 2949 OS << "0"; 2950 2951 OS << ", { "; 2952 for (unsigned i = 0, e = MI->AsmOperands.size(); i != e; ++i) { 2953 const MatchableInfo::AsmOperand &Op = MI->AsmOperands[i]; 2954 2955 if (i) OS << ", "; 2956 OS << Op.Class->Name; 2957 } 2958 OS << " }, },\n"; 2959 } 2960 2961 OS << "};\n\n"; 2962 } 2963 2964 // A method to determine if a mnemonic is in the list. 2965 if (HasMnemonicFirst) { 2966 OS << "bool " << Target.getName() << ClassName << "::\n" 2967 << "mnemonicIsValid(StringRef Mnemonic, unsigned VariantID) {\n"; 2968 OS << " // Find the appropriate table for this asm variant.\n"; 2969 OS << " const MatchEntry *Start, *End;\n"; 2970 OS << " switch (VariantID) {\n"; 2971 OS << " default: llvm_unreachable(\"invalid variant!\");\n"; 2972 for (unsigned VC = 0; VC != VariantCount; ++VC) { 2973 Record *AsmVariant = Target.getAsmParserVariant(VC); 2974 int AsmVariantNo = AsmVariant->getValueAsInt("Variant"); 2975 OS << " case " << AsmVariantNo << ": Start = std::begin(MatchTable" << VC 2976 << "); End = std::end(MatchTable" << VC << "); break;\n"; 2977 } 2978 OS << " }\n"; 2979 OS << " // Search the table.\n"; 2980 OS << " auto MnemonicRange = "; 2981 OS << "std::equal_range(Start, End, Mnemonic, LessOpcode());\n"; 2982 OS << " return MnemonicRange.first != MnemonicRange.second;\n"; 2983 OS << "}\n\n"; 2984 } 2985 2986 // Finally, build the match function. 2987 OS << "unsigned " << Target.getName() << ClassName << "::\n" 2988 << "MatchInstructionImpl(const OperandVector &Operands,\n"; 2989 OS << " MCInst &Inst, uint64_t &ErrorInfo,\n" 2990 << " bool matchingInlineAsm, unsigned VariantID) {\n"; 2991 2992 OS << " // Eliminate obvious mismatches.\n"; 2993 OS << " if (Operands.size() > " 2994 << (MaxNumOperands + HasMnemonicFirst) << ") {\n"; 2995 OS << " ErrorInfo = " 2996 << (MaxNumOperands + HasMnemonicFirst) << ";\n"; 2997 OS << " return Match_InvalidOperand;\n"; 2998 OS << " }\n\n"; 2999 3000 // Emit code to get the available features. 3001 OS << " // Get the current feature set.\n"; 3002 OS << " uint64_t AvailableFeatures = getAvailableFeatures();\n\n"; 3003 3004 OS << " // Get the instruction mnemonic, which is the first token.\n"; 3005 if (HasMnemonicFirst) { 3006 OS << " StringRef Mnemonic = ((" << Target.getName() 3007 << "Operand&)*Operands[0]).getToken();\n\n"; 3008 } else { 3009 OS << " StringRef Mnemonic;\n"; 3010 OS << " if (Operands[0]->isToken())\n"; 3011 OS << " Mnemonic = ((" << Target.getName() 3012 << "Operand&)*Operands[0]).getToken();\n\n"; 3013 } 3014 3015 if (HasMnemonicAliases) { 3016 OS << " // Process all MnemonicAliases to remap the mnemonic.\n"; 3017 OS << " applyMnemonicAliases(Mnemonic, AvailableFeatures, VariantID);\n\n"; 3018 } 3019 3020 // Emit code to compute the class list for this operand vector. 3021 OS << " // Some state to try to produce better error messages.\n"; 3022 OS << " bool HadMatchOtherThanFeatures = false;\n"; 3023 OS << " bool HadMatchOtherThanPredicate = false;\n"; 3024 OS << " unsigned RetCode = Match_InvalidOperand;\n"; 3025 OS << " uint64_t MissingFeatures = ~0ULL;\n"; 3026 OS << " // Set ErrorInfo to the operand that mismatches if it is\n"; 3027 OS << " // wrong for all instances of the instruction.\n"; 3028 OS << " ErrorInfo = ~0ULL;\n"; 3029 3030 // Emit code to search the table. 3031 OS << " // Find the appropriate table for this asm variant.\n"; 3032 OS << " const MatchEntry *Start, *End;\n"; 3033 OS << " switch (VariantID) {\n"; 3034 OS << " default: llvm_unreachable(\"invalid variant!\");\n"; 3035 for (unsigned VC = 0; VC != VariantCount; ++VC) { 3036 Record *AsmVariant = Target.getAsmParserVariant(VC); 3037 int AsmVariantNo = AsmVariant->getValueAsInt("Variant"); 3038 OS << " case " << AsmVariantNo << ": Start = std::begin(MatchTable" << VC 3039 << "); End = std::end(MatchTable" << VC << "); break;\n"; 3040 } 3041 OS << " }\n"; 3042 3043 OS << " // Search the table.\n"; 3044 if (HasMnemonicFirst) { 3045 OS << " auto MnemonicRange = " 3046 "std::equal_range(Start, End, Mnemonic, LessOpcode());\n\n"; 3047 } else { 3048 OS << " auto MnemonicRange = std::make_pair(Start, End);\n"; 3049 OS << " unsigned SIndex = Mnemonic.empty() ? 0 : 1;\n"; 3050 OS << " if (!Mnemonic.empty())\n"; 3051 OS << " MnemonicRange = " 3052 "std::equal_range(Start, End, Mnemonic.lower(), LessOpcode());\n\n"; 3053 } 3054 3055 OS << " // Return a more specific error code if no mnemonics match.\n"; 3056 OS << " if (MnemonicRange.first == MnemonicRange.second)\n"; 3057 OS << " return Match_MnemonicFail;\n\n"; 3058 3059 OS << " for (const MatchEntry *it = MnemonicRange.first, " 3060 << "*ie = MnemonicRange.second;\n"; 3061 OS << " it != ie; ++it) {\n"; 3062 3063 if (HasMnemonicFirst) { 3064 OS << " // equal_range guarantees that instruction mnemonic matches.\n"; 3065 OS << " assert(Mnemonic == it->getMnemonic());\n"; 3066 } 3067 3068 // Emit check that the subclasses match. 3069 OS << " bool OperandsValid = true;\n"; 3070 OS << " for (unsigned i = " << (HasMnemonicFirst ? "0" : "SIndex") 3071 << "; i != " << MaxNumOperands << "; ++i) {\n"; 3072 OS << " auto Formal = static_cast<MatchClassKind>(it->Classes[i]);\n"; 3073 OS << " if (i" << (HasMnemonicFirst ? "+1" : "") 3074 << " >= Operands.size()) {\n"; 3075 OS << " OperandsValid = (Formal == " <<"InvalidMatchClass);\n"; 3076 OS << " if (!OperandsValid) ErrorInfo = i" 3077 << (HasMnemonicFirst ? "+1" : "") << ";\n"; 3078 OS << " break;\n"; 3079 OS << " }\n"; 3080 OS << " MCParsedAsmOperand &Actual = *Operands[i" 3081 << (HasMnemonicFirst ? "+1" : "") << "];\n"; 3082 OS << " unsigned Diag = validateOperandClass(Actual, Formal);\n"; 3083 OS << " if (Diag == Match_Success)\n"; 3084 OS << " continue;\n"; 3085 OS << " // If the generic handler indicates an invalid operand\n"; 3086 OS << " // failure, check for a special case.\n"; 3087 OS << " if (Diag == Match_InvalidOperand) {\n"; 3088 OS << " Diag = validateTargetOperandClass(Actual, Formal);\n"; 3089 OS << " if (Diag == Match_Success)\n"; 3090 OS << " continue;\n"; 3091 OS << " }\n"; 3092 OS << " // If this operand is broken for all of the instances of this\n"; 3093 OS << " // mnemonic, keep track of it so we can report loc info.\n"; 3094 OS << " // If we already had a match that only failed due to a\n"; 3095 OS << " // target predicate, that diagnostic is preferred.\n"; 3096 OS << " if (!HadMatchOtherThanPredicate &&\n"; 3097 OS << " (it == MnemonicRange.first || ErrorInfo <= i" 3098 << (HasMnemonicFirst ? "+1" : "") << ")) {\n"; 3099 OS << " ErrorInfo = i" << (HasMnemonicFirst ? "+1" : "") << ";\n"; 3100 OS << " // InvalidOperand is the default. Prefer specificity.\n"; 3101 OS << " if (Diag != Match_InvalidOperand)\n"; 3102 OS << " RetCode = Diag;\n"; 3103 OS << " }\n"; 3104 OS << " // Otherwise, just reject this instance of the mnemonic.\n"; 3105 OS << " OperandsValid = false;\n"; 3106 OS << " break;\n"; 3107 OS << " }\n\n"; 3108 3109 OS << " if (!OperandsValid) continue;\n"; 3110 3111 // Emit check that the required features are available. 3112 OS << " if ((AvailableFeatures & it->RequiredFeatures) " 3113 << "!= it->RequiredFeatures) {\n"; 3114 OS << " HadMatchOtherThanFeatures = true;\n"; 3115 OS << " uint64_t NewMissingFeatures = it->RequiredFeatures & " 3116 "~AvailableFeatures;\n"; 3117 OS << " if (countPopulation(NewMissingFeatures) <=\n" 3118 " countPopulation(MissingFeatures))\n"; 3119 OS << " MissingFeatures = NewMissingFeatures;\n"; 3120 OS << " continue;\n"; 3121 OS << " }\n"; 3122 OS << "\n"; 3123 OS << " Inst.clear();\n\n"; 3124 OS << " if (matchingInlineAsm) {\n"; 3125 OS << " Inst.setOpcode(it->Opcode);\n"; 3126 OS << " convertToMapAndConstraints(it->ConvertFn, Operands);\n"; 3127 OS << " return Match_Success;\n"; 3128 OS << " }\n\n"; 3129 OS << " // We have selected a definite instruction, convert the parsed\n" 3130 << " // operands into the appropriate MCInst.\n"; 3131 OS << " convertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands);\n"; 3132 OS << "\n"; 3133 3134 // Verify the instruction with the target-specific match predicate function. 3135 OS << " // We have a potential match. Check the target predicate to\n" 3136 << " // handle any context sensitive constraints.\n" 3137 << " unsigned MatchResult;\n" 3138 << " if ((MatchResult = checkTargetMatchPredicate(Inst)) !=" 3139 << " Match_Success) {\n" 3140 << " Inst.clear();\n" 3141 << " RetCode = MatchResult;\n" 3142 << " HadMatchOtherThanPredicate = true;\n" 3143 << " continue;\n" 3144 << " }\n\n"; 3145 3146 // Call the post-processing function, if used. 3147 std::string InsnCleanupFn = 3148 AsmParser->getValueAsString("AsmParserInstCleanup"); 3149 if (!InsnCleanupFn.empty()) 3150 OS << " " << InsnCleanupFn << "(Inst);\n"; 3151 3152 if (HasDeprecation) { 3153 OS << " std::string Info;\n"; 3154 OS << " if (MII.get(Inst.getOpcode()).getDeprecatedInfo(Inst, getSTI(), Info)) {\n"; 3155 OS << " SMLoc Loc = ((" << Target.getName() 3156 << "Operand&)*Operands[0]).getStartLoc();\n"; 3157 OS << " getParser().Warning(Loc, Info, None);\n"; 3158 OS << " }\n"; 3159 } 3160 3161 OS << " return Match_Success;\n"; 3162 OS << " }\n\n"; 3163 3164 OS << " // Okay, we had no match. Try to return a useful error code.\n"; 3165 OS << " if (HadMatchOtherThanPredicate || !HadMatchOtherThanFeatures)\n"; 3166 OS << " return RetCode;\n\n"; 3167 OS << " // Missing feature matches return which features were missing\n"; 3168 OS << " ErrorInfo = MissingFeatures;\n"; 3169 OS << " return Match_MissingFeature;\n"; 3170 OS << "}\n\n"; 3171 3172 if (!Info.OperandMatchInfo.empty()) 3173 emitCustomOperandParsing(OS, Target, Info, ClassName, StringTable, 3174 MaxMnemonicIndex, HasMnemonicFirst); 3175 3176 OS << "#endif // GET_MATCHER_IMPLEMENTATION\n\n"; 3177 } 3178 3179 namespace llvm { 3180 3181 void EmitAsmMatcher(RecordKeeper &RK, raw_ostream &OS) { 3182 emitSourceFileHeader("Assembly Matcher Source Fragment", OS); 3183 AsmMatcherEmitter(RK).run(OS); 3184 } 3185 3186 } // End llvm namespace 3187