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