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