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