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