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