AsmMatcherEmitter.cpp revision 4dbfdfba6c92b6224bf58364371569f5780844d3
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 valeus 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 "StringToOffsetTable.h" 101#include "llvm/ADT/OwningPtr.h" 102#include "llvm/ADT/PointerUnion.h" 103#include "llvm/ADT/SmallPtrSet.h" 104#include "llvm/ADT/SmallVector.h" 105#include "llvm/ADT/STLExtras.h" 106#include "llvm/ADT/StringExtras.h" 107#include "llvm/Support/CommandLine.h" 108#include "llvm/Support/Debug.h" 109#include "llvm/Support/ErrorHandling.h" 110#include "llvm/TableGen/Error.h" 111#include "llvm/TableGen/Record.h" 112#include "llvm/TableGen/StringMatcher.h" 113#include "llvm/TableGen/TableGenBackend.h" 114#include <cassert> 115#include <map> 116#include <set> 117using namespace llvm; 118 119static cl::opt<std::string> 120MatchPrefix("match-prefix", cl::init(""), 121 cl::desc("Only match instructions with the given prefix")); 122 123namespace { 124class AsmMatcherInfo; 125struct SubtargetFeatureInfo; 126 127class AsmMatcherEmitter { 128 RecordKeeper &Records; 129public: 130 AsmMatcherEmitter(RecordKeeper &R) : Records(R) {} 131 132 void run(raw_ostream &o); 133}; 134 135/// ClassInfo - Helper class for storing the information about a particular 136/// class of operands which can be matched. 137struct ClassInfo { 138 enum ClassInfoKind { 139 /// Invalid kind, for use as a sentinel value. 140 Invalid = 0, 141 142 /// The class for a particular token. 143 Token, 144 145 /// The (first) register class, subsequent register classes are 146 /// RegisterClass0+1, and so on. 147 RegisterClass0, 148 149 /// The (first) user defined class, subsequent user defined classes are 150 /// UserClass0+1, and so on. 151 UserClass0 = 1<<16 152 }; 153 154 /// Kind - The class kind, which is either a predefined kind, or (UserClass0 + 155 /// N) for the Nth user defined class. 156 unsigned Kind; 157 158 /// SuperClasses - The super classes of this class. Note that for simplicities 159 /// sake user operands only record their immediate super class, while register 160 /// operands include all superclasses. 161 std::vector<ClassInfo*> SuperClasses; 162 163 /// Name - The full class name, suitable for use in an enum. 164 std::string Name; 165 166 /// ClassName - The unadorned generic name for this class (e.g., Token). 167 std::string ClassName; 168 169 /// ValueName - The name of the value this class represents; for a token this 170 /// is the literal token string, for an operand it is the TableGen class (or 171 /// empty if this is a derived class). 172 std::string ValueName; 173 174 /// PredicateMethod - The name of the operand method to test whether the 175 /// operand matches this class; this is not valid for Token or register kinds. 176 std::string PredicateMethod; 177 178 /// RenderMethod - The name of the operand method to add this operand to an 179 /// MCInst; this is not valid for Token or register kinds. 180 std::string RenderMethod; 181 182 /// ParserMethod - The name of the operand method to do a target specific 183 /// parsing on the operand. 184 std::string ParserMethod; 185 186 /// For register classes, the records for all the registers in this class. 187 std::set<Record*> Registers; 188 189 /// For custom match classes, he diagnostic kind for when the predicate fails. 190 std::string DiagnosticType; 191public: 192 /// isRegisterClass() - Check if this is a register class. 193 bool isRegisterClass() const { 194 return Kind >= RegisterClass0 && Kind < UserClass0; 195 } 196 197 /// isUserClass() - Check if this is a user defined class. 198 bool isUserClass() const { 199 return Kind >= UserClass0; 200 } 201 202 /// isRelatedTo - Check whether this class is "related" to \arg RHS. Classes 203 /// are related if they are in the same class hierarchy. 204 bool isRelatedTo(const ClassInfo &RHS) const { 205 // Tokens are only related to tokens. 206 if (Kind == Token || RHS.Kind == Token) 207 return Kind == Token && RHS.Kind == Token; 208 209 // Registers classes are only related to registers classes, and only if 210 // their intersection is non-empty. 211 if (isRegisterClass() || RHS.isRegisterClass()) { 212 if (!isRegisterClass() || !RHS.isRegisterClass()) 213 return false; 214 215 std::set<Record*> Tmp; 216 std::insert_iterator< std::set<Record*> > II(Tmp, Tmp.begin()); 217 std::set_intersection(Registers.begin(), Registers.end(), 218 RHS.Registers.begin(), RHS.Registers.end(), 219 II); 220 221 return !Tmp.empty(); 222 } 223 224 // Otherwise we have two users operands; they are related if they are in the 225 // same class hierarchy. 226 // 227 // FIXME: This is an oversimplification, they should only be related if they 228 // intersect, however we don't have that information. 229 assert(isUserClass() && RHS.isUserClass() && "Unexpected class!"); 230 const ClassInfo *Root = this; 231 while (!Root->SuperClasses.empty()) 232 Root = Root->SuperClasses.front(); 233 234 const ClassInfo *RHSRoot = &RHS; 235 while (!RHSRoot->SuperClasses.empty()) 236 RHSRoot = RHSRoot->SuperClasses.front(); 237 238 return Root == RHSRoot; 239 } 240 241 /// isSubsetOf - Test whether this class is a subset of \arg RHS; 242 bool isSubsetOf(const ClassInfo &RHS) const { 243 // This is a subset of RHS if it is the same class... 244 if (this == &RHS) 245 return true; 246 247 // ... or if any of its super classes are a subset of RHS. 248 for (std::vector<ClassInfo*>::const_iterator it = SuperClasses.begin(), 249 ie = SuperClasses.end(); it != ie; ++it) 250 if ((*it)->isSubsetOf(RHS)) 251 return true; 252 253 return false; 254 } 255 256 /// operator< - Compare two classes. 257 bool operator<(const ClassInfo &RHS) const { 258 if (this == &RHS) 259 return false; 260 261 // Unrelated classes can be ordered by kind. 262 if (!isRelatedTo(RHS)) 263 return Kind < RHS.Kind; 264 265 switch (Kind) { 266 case Invalid: 267 llvm_unreachable("Invalid kind!"); 268 269 default: 270 // This class precedes the RHS if it is a proper subset of the RHS. 271 if (isSubsetOf(RHS)) 272 return true; 273 if (RHS.isSubsetOf(*this)) 274 return false; 275 276 // Otherwise, order by name to ensure we have a total ordering. 277 return ValueName < RHS.ValueName; 278 } 279 } 280}; 281 282/// MatchableInfo - Helper class for storing the necessary information for an 283/// instruction or alias which is capable of being matched. 284struct MatchableInfo { 285 struct AsmOperand { 286 /// Token - This is the token that the operand came from. 287 StringRef Token; 288 289 /// The unique class instance this operand should match. 290 ClassInfo *Class; 291 292 /// The operand name this is, if anything. 293 StringRef SrcOpName; 294 295 /// The suboperand index within SrcOpName, or -1 for the entire operand. 296 int SubOpIdx; 297 298 /// Register record if this token is singleton register. 299 Record *SingletonReg; 300 301 explicit AsmOperand(StringRef T) : Token(T), Class(0), SubOpIdx(-1), 302 SingletonReg(0) {} 303 }; 304 305 /// ResOperand - This represents a single operand in the result instruction 306 /// generated by the match. In cases (like addressing modes) where a single 307 /// assembler operand expands to multiple MCOperands, this represents the 308 /// single assembler operand, not the MCOperand. 309 struct ResOperand { 310 enum { 311 /// RenderAsmOperand - This represents an operand result that is 312 /// generated by calling the render method on the assembly operand. The 313 /// corresponding AsmOperand is specified by AsmOperandNum. 314 RenderAsmOperand, 315 316 /// TiedOperand - This represents a result operand that is a duplicate of 317 /// a previous result operand. 318 TiedOperand, 319 320 /// ImmOperand - This represents an immediate value that is dumped into 321 /// the operand. 322 ImmOperand, 323 324 /// RegOperand - This represents a fixed register that is dumped in. 325 RegOperand 326 } Kind; 327 328 union { 329 /// This is the operand # in the AsmOperands list that this should be 330 /// copied from. 331 unsigned AsmOperandNum; 332 333 /// TiedOperandNum - This is the (earlier) result operand that should be 334 /// copied from. 335 unsigned TiedOperandNum; 336 337 /// ImmVal - This is the immediate value added to the instruction. 338 int64_t ImmVal; 339 340 /// Register - This is the register record. 341 Record *Register; 342 }; 343 344 /// MINumOperands - The number of MCInst operands populated by this 345 /// operand. 346 unsigned MINumOperands; 347 348 static ResOperand getRenderedOp(unsigned AsmOpNum, unsigned NumOperands) { 349 ResOperand X; 350 X.Kind = RenderAsmOperand; 351 X.AsmOperandNum = AsmOpNum; 352 X.MINumOperands = NumOperands; 353 return X; 354 } 355 356 static ResOperand getTiedOp(unsigned TiedOperandNum) { 357 ResOperand X; 358 X.Kind = TiedOperand; 359 X.TiedOperandNum = TiedOperandNum; 360 X.MINumOperands = 1; 361 return X; 362 } 363 364 static ResOperand getImmOp(int64_t Val) { 365 ResOperand X; 366 X.Kind = ImmOperand; 367 X.ImmVal = Val; 368 X.MINumOperands = 1; 369 return X; 370 } 371 372 static ResOperand getRegOp(Record *Reg) { 373 ResOperand X; 374 X.Kind = RegOperand; 375 X.Register = Reg; 376 X.MINumOperands = 1; 377 return X; 378 } 379 }; 380 381 /// AsmVariantID - Target's assembly syntax variant no. 382 int AsmVariantID; 383 384 /// TheDef - This is the definition of the instruction or InstAlias that this 385 /// matchable came from. 386 Record *const TheDef; 387 388 /// DefRec - This is the definition that it came from. 389 PointerUnion<const CodeGenInstruction*, const CodeGenInstAlias*> DefRec; 390 391 const CodeGenInstruction *getResultInst() const { 392 if (DefRec.is<const CodeGenInstruction*>()) 393 return DefRec.get<const CodeGenInstruction*>(); 394 return DefRec.get<const CodeGenInstAlias*>()->ResultInst; 395 } 396 397 /// ResOperands - This is the operand list that should be built for the result 398 /// MCInst. 399 SmallVector<ResOperand, 8> ResOperands; 400 401 /// AsmString - The assembly string for this instruction (with variants 402 /// removed), e.g. "movsx $src, $dst". 403 std::string AsmString; 404 405 /// Mnemonic - This is the first token of the matched instruction, its 406 /// mnemonic. 407 StringRef Mnemonic; 408 409 /// AsmOperands - The textual operands that this instruction matches, 410 /// annotated with a class and where in the OperandList they were defined. 411 /// This directly corresponds to the tokenized AsmString after the mnemonic is 412 /// removed. 413 SmallVector<AsmOperand, 8> AsmOperands; 414 415 /// Predicates - The required subtarget features to match this instruction. 416 SmallVector<SubtargetFeatureInfo*, 4> RequiredFeatures; 417 418 /// ConversionFnKind - The enum value which is passed to the generated 419 /// ConvertToMCInst to convert parsed operands into an MCInst for this 420 /// function. 421 std::string ConversionFnKind; 422 423 MatchableInfo(const CodeGenInstruction &CGI) 424 : AsmVariantID(0), TheDef(CGI.TheDef), DefRec(&CGI), 425 AsmString(CGI.AsmString) { 426 } 427 428 MatchableInfo(const CodeGenInstAlias *Alias) 429 : AsmVariantID(0), TheDef(Alias->TheDef), DefRec(Alias), 430 AsmString(Alias->AsmString) { 431 } 432 433 // Two-operand aliases clone from the main matchable, but mark the second 434 // operand as a tied operand of the first for purposes of the assembler. 435 void formTwoOperandAlias(StringRef Constraint); 436 437 void initialize(const AsmMatcherInfo &Info, 438 SmallPtrSet<Record*, 16> &SingletonRegisters, 439 int AsmVariantNo, std::string &RegisterPrefix); 440 441 /// validate - Return true if this matchable is a valid thing to match against 442 /// and perform a bunch of validity checking. 443 bool validate(StringRef CommentDelimiter, bool Hack) const; 444 445 /// extractSingletonRegisterForAsmOperand - Extract singleton register, 446 /// if present, from specified token. 447 void 448 extractSingletonRegisterForAsmOperand(unsigned i, const AsmMatcherInfo &Info, 449 std::string &RegisterPrefix); 450 451 /// findAsmOperand - Find the AsmOperand with the specified name and 452 /// suboperand index. 453 int findAsmOperand(StringRef N, int SubOpIdx) const { 454 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) 455 if (N == AsmOperands[i].SrcOpName && 456 SubOpIdx == AsmOperands[i].SubOpIdx) 457 return i; 458 return -1; 459 } 460 461 /// findAsmOperandNamed - Find the first AsmOperand with the specified name. 462 /// This does not check the suboperand index. 463 int findAsmOperandNamed(StringRef N) const { 464 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) 465 if (N == AsmOperands[i].SrcOpName) 466 return i; 467 return -1; 468 } 469 470 void buildInstructionResultOperands(); 471 void buildAliasResultOperands(); 472 473 /// operator< - Compare two matchables. 474 bool operator<(const MatchableInfo &RHS) const { 475 // The primary comparator is the instruction mnemonic. 476 if (Mnemonic != RHS.Mnemonic) 477 return Mnemonic < RHS.Mnemonic; 478 479 if (AsmOperands.size() != RHS.AsmOperands.size()) 480 return AsmOperands.size() < RHS.AsmOperands.size(); 481 482 // Compare lexicographically by operand. The matcher validates that other 483 // orderings wouldn't be ambiguous using \see couldMatchAmbiguouslyWith(). 484 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) { 485 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class) 486 return true; 487 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class) 488 return false; 489 } 490 491 return false; 492 } 493 494 /// couldMatchAmbiguouslyWith - Check whether this matchable could 495 /// ambiguously match the same set of operands as \arg RHS (without being a 496 /// strictly superior match). 497 bool couldMatchAmbiguouslyWith(const MatchableInfo &RHS) { 498 // The primary comparator is the instruction mnemonic. 499 if (Mnemonic != RHS.Mnemonic) 500 return false; 501 502 // The number of operands is unambiguous. 503 if (AsmOperands.size() != RHS.AsmOperands.size()) 504 return false; 505 506 // Otherwise, make sure the ordering of the two instructions is unambiguous 507 // by checking that either (a) a token or operand kind discriminates them, 508 // or (b) the ordering among equivalent kinds is consistent. 509 510 // Tokens and operand kinds are unambiguous (assuming a correct target 511 // specific parser). 512 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) 513 if (AsmOperands[i].Class->Kind != RHS.AsmOperands[i].Class->Kind || 514 AsmOperands[i].Class->Kind == ClassInfo::Token) 515 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class || 516 *RHS.AsmOperands[i].Class < *AsmOperands[i].Class) 517 return false; 518 519 // Otherwise, this operand could commute if all operands are equivalent, or 520 // there is a pair of operands that compare less than and a pair that 521 // compare greater than. 522 bool HasLT = false, HasGT = false; 523 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) { 524 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class) 525 HasLT = true; 526 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class) 527 HasGT = true; 528 } 529 530 return !(HasLT ^ HasGT); 531 } 532 533 void dump(); 534 535private: 536 void tokenizeAsmString(const AsmMatcherInfo &Info); 537}; 538 539/// SubtargetFeatureInfo - Helper class for storing information on a subtarget 540/// feature which participates in instruction matching. 541struct SubtargetFeatureInfo { 542 /// \brief The predicate record for this feature. 543 Record *TheDef; 544 545 /// \brief An unique index assigned to represent this feature. 546 unsigned Index; 547 548 SubtargetFeatureInfo(Record *D, unsigned Idx) : TheDef(D), Index(Idx) {} 549 550 /// \brief The name of the enumerated constant identifying this feature. 551 std::string getEnumName() const { 552 return "Feature_" + TheDef->getName(); 553 } 554}; 555 556struct OperandMatchEntry { 557 unsigned OperandMask; 558 MatchableInfo* MI; 559 ClassInfo *CI; 560 561 static OperandMatchEntry create(MatchableInfo* mi, ClassInfo *ci, 562 unsigned opMask) { 563 OperandMatchEntry X; 564 X.OperandMask = opMask; 565 X.CI = ci; 566 X.MI = mi; 567 return X; 568 } 569}; 570 571 572class AsmMatcherInfo { 573public: 574 /// Tracked Records 575 RecordKeeper &Records; 576 577 /// The tablegen AsmParser record. 578 Record *AsmParser; 579 580 /// Target - The target information. 581 CodeGenTarget &Target; 582 583 /// The classes which are needed for matching. 584 std::vector<ClassInfo*> Classes; 585 586 /// The information on the matchables to match. 587 std::vector<MatchableInfo*> Matchables; 588 589 /// Info for custom matching operands by user defined methods. 590 std::vector<OperandMatchEntry> OperandMatchInfo; 591 592 /// Map of Register records to their class information. 593 std::map<Record*, ClassInfo*> RegisterClasses; 594 595 /// Map of Predicate records to their subtarget information. 596 std::map<Record*, SubtargetFeatureInfo*> SubtargetFeatures; 597 598 /// Map of AsmOperandClass records to their class information. 599 std::map<Record*, ClassInfo*> AsmOperandClasses; 600 601private: 602 /// Map of token to class information which has already been constructed. 603 std::map<std::string, ClassInfo*> TokenClasses; 604 605 /// Map of RegisterClass records to their class information. 606 std::map<Record*, ClassInfo*> RegisterClassClasses; 607 608private: 609 /// getTokenClass - Lookup or create the class for the given token. 610 ClassInfo *getTokenClass(StringRef Token); 611 612 /// getOperandClass - Lookup or create the class for the given operand. 613 ClassInfo *getOperandClass(const CGIOperandList::OperandInfo &OI, 614 int SubOpIdx); 615 ClassInfo *getOperandClass(Record *Rec, int SubOpIdx); 616 617 /// buildRegisterClasses - Build the ClassInfo* instances for register 618 /// classes. 619 void buildRegisterClasses(SmallPtrSet<Record*, 16> &SingletonRegisters); 620 621 /// buildOperandClasses - Build the ClassInfo* instances for user defined 622 /// operand classes. 623 void buildOperandClasses(); 624 625 void buildInstructionOperandReference(MatchableInfo *II, StringRef OpName, 626 unsigned AsmOpIdx); 627 void buildAliasOperandReference(MatchableInfo *II, StringRef OpName, 628 MatchableInfo::AsmOperand &Op); 629 630public: 631 AsmMatcherInfo(Record *AsmParser, 632 CodeGenTarget &Target, 633 RecordKeeper &Records); 634 635 /// buildInfo - Construct the various tables used during matching. 636 void buildInfo(); 637 638 /// buildOperandMatchInfo - Build the necessary information to handle user 639 /// defined operand parsing methods. 640 void buildOperandMatchInfo(); 641 642 /// getSubtargetFeature - Lookup or create the subtarget feature info for the 643 /// given operand. 644 SubtargetFeatureInfo *getSubtargetFeature(Record *Def) const { 645 assert(Def->isSubClassOf("Predicate") && "Invalid predicate type!"); 646 std::map<Record*, SubtargetFeatureInfo*>::const_iterator I = 647 SubtargetFeatures.find(Def); 648 return I == SubtargetFeatures.end() ? 0 : I->second; 649 } 650 651 RecordKeeper &getRecords() const { 652 return Records; 653 } 654}; 655 656} // End anonymous namespace 657 658void MatchableInfo::dump() { 659 errs() << TheDef->getName() << " -- " << "flattened:\"" << AsmString <<"\"\n"; 660 661 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) { 662 AsmOperand &Op = AsmOperands[i]; 663 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - "; 664 errs() << '\"' << Op.Token << "\"\n"; 665 } 666} 667 668static std::pair<StringRef, StringRef> 669parseTwoOperandConstraint(StringRef S, SMLoc Loc) { 670 // Split via the '='. 671 std::pair<StringRef, StringRef> Ops = S.split('='); 672 if (Ops.second == "") 673 throw TGError(Loc, "missing '=' in two-operand alias constraint"); 674 // Trim whitespace and the leading '$' on the operand names. 675 size_t start = Ops.first.find_first_of('$'); 676 if (start == std::string::npos) 677 throw TGError(Loc, "expected '$' prefix on asm operand name"); 678 Ops.first = Ops.first.slice(start + 1, std::string::npos); 679 size_t end = Ops.first.find_last_of(" \t"); 680 Ops.first = Ops.first.slice(0, end); 681 // Now the second operand. 682 start = Ops.second.find_first_of('$'); 683 if (start == std::string::npos) 684 throw TGError(Loc, "expected '$' prefix on asm operand name"); 685 Ops.second = Ops.second.slice(start + 1, std::string::npos); 686 end = Ops.second.find_last_of(" \t"); 687 Ops.first = Ops.first.slice(0, end); 688 return Ops; 689} 690 691void MatchableInfo::formTwoOperandAlias(StringRef Constraint) { 692 // Figure out which operands are aliased and mark them as tied. 693 std::pair<StringRef, StringRef> Ops = 694 parseTwoOperandConstraint(Constraint, TheDef->getLoc()); 695 696 // Find the AsmOperands that refer to the operands we're aliasing. 697 int SrcAsmOperand = findAsmOperandNamed(Ops.first); 698 int DstAsmOperand = findAsmOperandNamed(Ops.second); 699 if (SrcAsmOperand == -1) 700 throw TGError(TheDef->getLoc(), 701 "unknown source two-operand alias operand '" + 702 Ops.first.str() + "'."); 703 if (DstAsmOperand == -1) 704 throw TGError(TheDef->getLoc(), 705 "unknown destination two-operand alias operand '" + 706 Ops.second.str() + "'."); 707 708 // Find the ResOperand that refers to the operand we're aliasing away 709 // and update it to refer to the combined operand instead. 710 for (unsigned i = 0, e = ResOperands.size(); i != e; ++i) { 711 ResOperand &Op = ResOperands[i]; 712 if (Op.Kind == ResOperand::RenderAsmOperand && 713 Op.AsmOperandNum == (unsigned)SrcAsmOperand) { 714 Op.AsmOperandNum = DstAsmOperand; 715 break; 716 } 717 } 718 // Remove the AsmOperand for the alias operand. 719 AsmOperands.erase(AsmOperands.begin() + SrcAsmOperand); 720 // Adjust the ResOperand references to any AsmOperands that followed 721 // the one we just deleted. 722 for (unsigned i = 0, e = ResOperands.size(); i != e; ++i) { 723 ResOperand &Op = ResOperands[i]; 724 switch(Op.Kind) { 725 default: 726 // Nothing to do for operands that don't reference AsmOperands. 727 break; 728 case ResOperand::RenderAsmOperand: 729 if (Op.AsmOperandNum > (unsigned)SrcAsmOperand) 730 --Op.AsmOperandNum; 731 break; 732 case ResOperand::TiedOperand: 733 if (Op.TiedOperandNum > (unsigned)SrcAsmOperand) 734 --Op.TiedOperandNum; 735 break; 736 } 737 } 738} 739 740void MatchableInfo::initialize(const AsmMatcherInfo &Info, 741 SmallPtrSet<Record*, 16> &SingletonRegisters, 742 int AsmVariantNo, std::string &RegisterPrefix) { 743 AsmVariantID = AsmVariantNo; 744 AsmString = 745 CodeGenInstruction::FlattenAsmStringVariants(AsmString, AsmVariantNo); 746 747 tokenizeAsmString(Info); 748 749 // Compute the require features. 750 std::vector<Record*> Predicates =TheDef->getValueAsListOfDefs("Predicates"); 751 for (unsigned i = 0, e = Predicates.size(); i != e; ++i) 752 if (SubtargetFeatureInfo *Feature = 753 Info.getSubtargetFeature(Predicates[i])) 754 RequiredFeatures.push_back(Feature); 755 756 // Collect singleton registers, if used. 757 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) { 758 extractSingletonRegisterForAsmOperand(i, Info, RegisterPrefix); 759 if (Record *Reg = AsmOperands[i].SingletonReg) 760 SingletonRegisters.insert(Reg); 761 } 762} 763 764/// tokenizeAsmString - Tokenize a simplified assembly string. 765void MatchableInfo::tokenizeAsmString(const AsmMatcherInfo &Info) { 766 StringRef String = AsmString; 767 unsigned Prev = 0; 768 bool InTok = true; 769 for (unsigned i = 0, e = String.size(); i != e; ++i) { 770 switch (String[i]) { 771 case '[': 772 case ']': 773 case '*': 774 case '!': 775 case ' ': 776 case '\t': 777 case ',': 778 if (InTok) { 779 AsmOperands.push_back(AsmOperand(String.slice(Prev, i))); 780 InTok = false; 781 } 782 if (!isspace(String[i]) && String[i] != ',') 783 AsmOperands.push_back(AsmOperand(String.substr(i, 1))); 784 Prev = i + 1; 785 break; 786 787 case '\\': 788 if (InTok) { 789 AsmOperands.push_back(AsmOperand(String.slice(Prev, i))); 790 InTok = false; 791 } 792 ++i; 793 assert(i != String.size() && "Invalid quoted character"); 794 AsmOperands.push_back(AsmOperand(String.substr(i, 1))); 795 Prev = i + 1; 796 break; 797 798 case '$': { 799 if (InTok) { 800 AsmOperands.push_back(AsmOperand(String.slice(Prev, i))); 801 InTok = false; 802 } 803 804 // If this isn't "${", treat like a normal token. 805 if (i + 1 == String.size() || String[i + 1] != '{') { 806 Prev = i; 807 break; 808 } 809 810 StringRef::iterator End = std::find(String.begin() + i, String.end(),'}'); 811 assert(End != String.end() && "Missing brace in operand reference!"); 812 size_t EndPos = End - String.begin(); 813 AsmOperands.push_back(AsmOperand(String.slice(i, EndPos+1))); 814 Prev = EndPos + 1; 815 i = EndPos; 816 break; 817 } 818 819 case '.': 820 if (InTok) 821 AsmOperands.push_back(AsmOperand(String.slice(Prev, i))); 822 Prev = i; 823 InTok = true; 824 break; 825 826 default: 827 InTok = true; 828 } 829 } 830 if (InTok && Prev != String.size()) 831 AsmOperands.push_back(AsmOperand(String.substr(Prev))); 832 833 // The first token of the instruction is the mnemonic, which must be a 834 // simple string, not a $foo variable or a singleton register. 835 if (AsmOperands.empty()) 836 throw TGError(TheDef->getLoc(), 837 "Instruction '" + TheDef->getName() + "' has no tokens"); 838 Mnemonic = AsmOperands[0].Token; 839 if (Mnemonic.empty()) 840 throw TGError(TheDef->getLoc(), 841 "Missing instruction mnemonic"); 842 // FIXME : Check and raise an error if it is a register. 843 if (Mnemonic[0] == '$') 844 throw TGError(TheDef->getLoc(), 845 "Invalid instruction mnemonic '" + Mnemonic.str() + "'!"); 846 847 // Remove the first operand, it is tracked in the mnemonic field. 848 AsmOperands.erase(AsmOperands.begin()); 849} 850 851bool MatchableInfo::validate(StringRef CommentDelimiter, bool Hack) const { 852 // Reject matchables with no .s string. 853 if (AsmString.empty()) 854 throw TGError(TheDef->getLoc(), "instruction with empty asm string"); 855 856 // Reject any matchables with a newline in them, they should be marked 857 // isCodeGenOnly if they are pseudo instructions. 858 if (AsmString.find('\n') != std::string::npos) 859 throw TGError(TheDef->getLoc(), 860 "multiline instruction is not valid for the asmparser, " 861 "mark it isCodeGenOnly"); 862 863 // Remove comments from the asm string. We know that the asmstring only 864 // has one line. 865 if (!CommentDelimiter.empty() && 866 StringRef(AsmString).find(CommentDelimiter) != StringRef::npos) 867 throw TGError(TheDef->getLoc(), 868 "asmstring for instruction has comment character in it, " 869 "mark it isCodeGenOnly"); 870 871 // Reject matchables with operand modifiers, these aren't something we can 872 // handle, the target should be refactored to use operands instead of 873 // modifiers. 874 // 875 // Also, check for instructions which reference the operand multiple times; 876 // this implies a constraint we would not honor. 877 std::set<std::string> OperandNames; 878 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) { 879 StringRef Tok = AsmOperands[i].Token; 880 if (Tok[0] == '$' && Tok.find(':') != StringRef::npos) 881 throw TGError(TheDef->getLoc(), 882 "matchable with operand modifier '" + Tok.str() + 883 "' not supported by asm matcher. Mark isCodeGenOnly!"); 884 885 // Verify that any operand is only mentioned once. 886 // We reject aliases and ignore instructions for now. 887 if (Tok[0] == '$' && !OperandNames.insert(Tok).second) { 888 if (!Hack) 889 throw TGError(TheDef->getLoc(), 890 "ERROR: matchable with tied operand '" + Tok.str() + 891 "' can never be matched!"); 892 // FIXME: Should reject these. The ARM backend hits this with $lane in a 893 // bunch of instructions. It is unclear what the right answer is. 894 DEBUG({ 895 errs() << "warning: '" << TheDef->getName() << "': " 896 << "ignoring instruction with tied operand '" 897 << Tok.str() << "'\n"; 898 }); 899 return false; 900 } 901 } 902 903 return true; 904} 905 906/// extractSingletonRegisterForAsmOperand - Extract singleton register, 907/// if present, from specified token. 908void MatchableInfo:: 909extractSingletonRegisterForAsmOperand(unsigned OperandNo, 910 const AsmMatcherInfo &Info, 911 std::string &RegisterPrefix) { 912 StringRef Tok = AsmOperands[OperandNo].Token; 913 if (RegisterPrefix.empty()) { 914 std::string LoweredTok = Tok.lower(); 915 if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(LoweredTok)) 916 AsmOperands[OperandNo].SingletonReg = Reg->TheDef; 917 return; 918 } 919 920 if (!Tok.startswith(RegisterPrefix)) 921 return; 922 923 StringRef RegName = Tok.substr(RegisterPrefix.size()); 924 if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(RegName)) 925 AsmOperands[OperandNo].SingletonReg = Reg->TheDef; 926 927 // If there is no register prefix (i.e. "%" in "%eax"), then this may 928 // be some random non-register token, just ignore it. 929 return; 930} 931 932static std::string getEnumNameForToken(StringRef Str) { 933 std::string Res; 934 935 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) { 936 switch (*it) { 937 case '*': Res += "_STAR_"; break; 938 case '%': Res += "_PCT_"; break; 939 case ':': Res += "_COLON_"; break; 940 case '!': Res += "_EXCLAIM_"; break; 941 case '.': Res += "_DOT_"; break; 942 default: 943 if (isalnum(*it)) 944 Res += *it; 945 else 946 Res += "_" + utostr((unsigned) *it) + "_"; 947 } 948 } 949 950 return Res; 951} 952 953ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) { 954 ClassInfo *&Entry = TokenClasses[Token]; 955 956 if (!Entry) { 957 Entry = new ClassInfo(); 958 Entry->Kind = ClassInfo::Token; 959 Entry->ClassName = "Token"; 960 Entry->Name = "MCK_" + getEnumNameForToken(Token); 961 Entry->ValueName = Token; 962 Entry->PredicateMethod = "<invalid>"; 963 Entry->RenderMethod = "<invalid>"; 964 Entry->ParserMethod = ""; 965 Entry->DiagnosticType = ""; 966 Classes.push_back(Entry); 967 } 968 969 return Entry; 970} 971 972ClassInfo * 973AsmMatcherInfo::getOperandClass(const CGIOperandList::OperandInfo &OI, 974 int SubOpIdx) { 975 Record *Rec = OI.Rec; 976 if (SubOpIdx != -1) 977 Rec = dynamic_cast<DefInit*>(OI.MIOperandInfo->getArg(SubOpIdx))->getDef(); 978 return getOperandClass(Rec, SubOpIdx); 979} 980 981ClassInfo * 982AsmMatcherInfo::getOperandClass(Record *Rec, int SubOpIdx) { 983 if (Rec->isSubClassOf("RegisterOperand")) { 984 // RegisterOperand may have an associated ParserMatchClass. If it does, 985 // use it, else just fall back to the underlying register class. 986 const RecordVal *R = Rec->getValue("ParserMatchClass"); 987 if (R == 0 || R->getValue() == 0) 988 throw "Record `" + Rec->getName() + 989 "' does not have a ParserMatchClass!\n"; 990 991 if (DefInit *DI= dynamic_cast<DefInit*>(R->getValue())) { 992 Record *MatchClass = DI->getDef(); 993 if (ClassInfo *CI = AsmOperandClasses[MatchClass]) 994 return CI; 995 } 996 997 // No custom match class. Just use the register class. 998 Record *ClassRec = Rec->getValueAsDef("RegClass"); 999 if (!ClassRec) 1000 throw TGError(Rec->getLoc(), "RegisterOperand `" + Rec->getName() + 1001 "' has no associated register class!\n"); 1002 if (ClassInfo *CI = RegisterClassClasses[ClassRec]) 1003 return CI; 1004 throw TGError(Rec->getLoc(), "register class has no class info!"); 1005 } 1006 1007 1008 if (Rec->isSubClassOf("RegisterClass")) { 1009 if (ClassInfo *CI = RegisterClassClasses[Rec]) 1010 return CI; 1011 throw TGError(Rec->getLoc(), "register class has no class info!"); 1012 } 1013 1014 assert(Rec->isSubClassOf("Operand") && "Unexpected operand!"); 1015 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass"); 1016 if (ClassInfo *CI = AsmOperandClasses[MatchClass]) 1017 return CI; 1018 1019 throw TGError(Rec->getLoc(), "operand has no match class!"); 1020} 1021 1022void AsmMatcherInfo:: 1023buildRegisterClasses(SmallPtrSet<Record*, 16> &SingletonRegisters) { 1024 const std::vector<CodeGenRegister*> &Registers = 1025 Target.getRegBank().getRegisters(); 1026 ArrayRef<CodeGenRegisterClass*> RegClassList = 1027 Target.getRegBank().getRegClasses(); 1028 1029 // The register sets used for matching. 1030 std::set< std::set<Record*> > RegisterSets; 1031 1032 // Gather the defined sets. 1033 for (ArrayRef<CodeGenRegisterClass*>::const_iterator it = 1034 RegClassList.begin(), ie = RegClassList.end(); it != ie; ++it) 1035 RegisterSets.insert(std::set<Record*>( 1036 (*it)->getOrder().begin(), (*it)->getOrder().end())); 1037 1038 // Add any required singleton sets. 1039 for (SmallPtrSet<Record*, 16>::iterator it = SingletonRegisters.begin(), 1040 ie = SingletonRegisters.end(); it != ie; ++it) { 1041 Record *Rec = *it; 1042 RegisterSets.insert(std::set<Record*>(&Rec, &Rec + 1)); 1043 } 1044 1045 // Introduce derived sets where necessary (when a register does not determine 1046 // a unique register set class), and build the mapping of registers to the set 1047 // they should classify to. 1048 std::map<Record*, std::set<Record*> > RegisterMap; 1049 for (std::vector<CodeGenRegister*>::const_iterator it = Registers.begin(), 1050 ie = Registers.end(); it != ie; ++it) { 1051 const CodeGenRegister &CGR = **it; 1052 // Compute the intersection of all sets containing this register. 1053 std::set<Record*> ContainingSet; 1054 1055 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(), 1056 ie = RegisterSets.end(); it != ie; ++it) { 1057 if (!it->count(CGR.TheDef)) 1058 continue; 1059 1060 if (ContainingSet.empty()) { 1061 ContainingSet = *it; 1062 continue; 1063 } 1064 1065 std::set<Record*> Tmp; 1066 std::swap(Tmp, ContainingSet); 1067 std::insert_iterator< std::set<Record*> > II(ContainingSet, 1068 ContainingSet.begin()); 1069 std::set_intersection(Tmp.begin(), Tmp.end(), it->begin(), it->end(), II); 1070 } 1071 1072 if (!ContainingSet.empty()) { 1073 RegisterSets.insert(ContainingSet); 1074 RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet)); 1075 } 1076 } 1077 1078 // Construct the register classes. 1079 std::map<std::set<Record*>, ClassInfo*> RegisterSetClasses; 1080 unsigned Index = 0; 1081 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(), 1082 ie = RegisterSets.end(); it != ie; ++it, ++Index) { 1083 ClassInfo *CI = new ClassInfo(); 1084 CI->Kind = ClassInfo::RegisterClass0 + Index; 1085 CI->ClassName = "Reg" + utostr(Index); 1086 CI->Name = "MCK_Reg" + utostr(Index); 1087 CI->ValueName = ""; 1088 CI->PredicateMethod = ""; // unused 1089 CI->RenderMethod = "addRegOperands"; 1090 CI->Registers = *it; 1091 // FIXME: diagnostic type. 1092 CI->DiagnosticType = ""; 1093 Classes.push_back(CI); 1094 RegisterSetClasses.insert(std::make_pair(*it, CI)); 1095 } 1096 1097 // Find the superclasses; we could compute only the subgroup lattice edges, 1098 // but there isn't really a point. 1099 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(), 1100 ie = RegisterSets.end(); it != ie; ++it) { 1101 ClassInfo *CI = RegisterSetClasses[*it]; 1102 for (std::set< std::set<Record*> >::iterator it2 = RegisterSets.begin(), 1103 ie2 = RegisterSets.end(); it2 != ie2; ++it2) 1104 if (*it != *it2 && 1105 std::includes(it2->begin(), it2->end(), it->begin(), it->end())) 1106 CI->SuperClasses.push_back(RegisterSetClasses[*it2]); 1107 } 1108 1109 // Name the register classes which correspond to a user defined RegisterClass. 1110 for (ArrayRef<CodeGenRegisterClass*>::const_iterator 1111 it = RegClassList.begin(), ie = RegClassList.end(); it != ie; ++it) { 1112 const CodeGenRegisterClass &RC = **it; 1113 // Def will be NULL for non-user defined register classes. 1114 Record *Def = RC.getDef(); 1115 if (!Def) 1116 continue; 1117 ClassInfo *CI = RegisterSetClasses[std::set<Record*>(RC.getOrder().begin(), 1118 RC.getOrder().end())]; 1119 if (CI->ValueName.empty()) { 1120 CI->ClassName = RC.getName(); 1121 CI->Name = "MCK_" + RC.getName(); 1122 CI->ValueName = RC.getName(); 1123 } else 1124 CI->ValueName = CI->ValueName + "," + RC.getName(); 1125 1126 RegisterClassClasses.insert(std::make_pair(Def, CI)); 1127 } 1128 1129 // Populate the map for individual registers. 1130 for (std::map<Record*, std::set<Record*> >::iterator it = RegisterMap.begin(), 1131 ie = RegisterMap.end(); it != ie; ++it) 1132 RegisterClasses[it->first] = RegisterSetClasses[it->second]; 1133 1134 // Name the register classes which correspond to singleton registers. 1135 for (SmallPtrSet<Record*, 16>::iterator it = SingletonRegisters.begin(), 1136 ie = SingletonRegisters.end(); it != ie; ++it) { 1137 Record *Rec = *it; 1138 ClassInfo *CI = RegisterClasses[Rec]; 1139 assert(CI && "Missing singleton register class info!"); 1140 1141 if (CI->ValueName.empty()) { 1142 CI->ClassName = Rec->getName(); 1143 CI->Name = "MCK_" + Rec->getName(); 1144 CI->ValueName = Rec->getName(); 1145 } else 1146 CI->ValueName = CI->ValueName + "," + Rec->getName(); 1147 } 1148} 1149 1150void AsmMatcherInfo::buildOperandClasses() { 1151 std::vector<Record*> AsmOperands = 1152 Records.getAllDerivedDefinitions("AsmOperandClass"); 1153 1154 // Pre-populate AsmOperandClasses map. 1155 for (std::vector<Record*>::iterator it = AsmOperands.begin(), 1156 ie = AsmOperands.end(); it != ie; ++it) 1157 AsmOperandClasses[*it] = new ClassInfo(); 1158 1159 unsigned Index = 0; 1160 for (std::vector<Record*>::iterator it = AsmOperands.begin(), 1161 ie = AsmOperands.end(); it != ie; ++it, ++Index) { 1162 ClassInfo *CI = AsmOperandClasses[*it]; 1163 CI->Kind = ClassInfo::UserClass0 + Index; 1164 1165 ListInit *Supers = (*it)->getValueAsListInit("SuperClasses"); 1166 for (unsigned i = 0, e = Supers->getSize(); i != e; ++i) { 1167 DefInit *DI = dynamic_cast<DefInit*>(Supers->getElement(i)); 1168 if (!DI) { 1169 PrintError((*it)->getLoc(), "Invalid super class reference!"); 1170 continue; 1171 } 1172 1173 ClassInfo *SC = AsmOperandClasses[DI->getDef()]; 1174 if (!SC) 1175 PrintError((*it)->getLoc(), "Invalid super class reference!"); 1176 else 1177 CI->SuperClasses.push_back(SC); 1178 } 1179 CI->ClassName = (*it)->getValueAsString("Name"); 1180 CI->Name = "MCK_" + CI->ClassName; 1181 CI->ValueName = (*it)->getName(); 1182 1183 // Get or construct the predicate method name. 1184 Init *PMName = (*it)->getValueInit("PredicateMethod"); 1185 if (StringInit *SI = dynamic_cast<StringInit*>(PMName)) { 1186 CI->PredicateMethod = SI->getValue(); 1187 } else { 1188 assert(dynamic_cast<UnsetInit*>(PMName) && 1189 "Unexpected PredicateMethod field!"); 1190 CI->PredicateMethod = "is" + CI->ClassName; 1191 } 1192 1193 // Get or construct the render method name. 1194 Init *RMName = (*it)->getValueInit("RenderMethod"); 1195 if (StringInit *SI = dynamic_cast<StringInit*>(RMName)) { 1196 CI->RenderMethod = SI->getValue(); 1197 } else { 1198 assert(dynamic_cast<UnsetInit*>(RMName) && 1199 "Unexpected RenderMethod field!"); 1200 CI->RenderMethod = "add" + CI->ClassName + "Operands"; 1201 } 1202 1203 // Get the parse method name or leave it as empty. 1204 Init *PRMName = (*it)->getValueInit("ParserMethod"); 1205 if (StringInit *SI = dynamic_cast<StringInit*>(PRMName)) 1206 CI->ParserMethod = SI->getValue(); 1207 1208 // Get the diagnostic type or leave it as empty. 1209 // Get the parse method name or leave it as empty. 1210 Init *DiagnosticType = (*it)->getValueInit("DiagnosticType"); 1211 if (StringInit *SI = dynamic_cast<StringInit*>(DiagnosticType)) 1212 CI->DiagnosticType = SI->getValue(); 1213 1214 AsmOperandClasses[*it] = CI; 1215 Classes.push_back(CI); 1216 } 1217} 1218 1219AsmMatcherInfo::AsmMatcherInfo(Record *asmParser, 1220 CodeGenTarget &target, 1221 RecordKeeper &records) 1222 : Records(records), AsmParser(asmParser), Target(target) { 1223} 1224 1225/// buildOperandMatchInfo - Build the necessary information to handle user 1226/// defined operand parsing methods. 1227void AsmMatcherInfo::buildOperandMatchInfo() { 1228 1229 /// Map containing a mask with all operands indices that can be found for 1230 /// that class inside a instruction. 1231 std::map<ClassInfo*, unsigned> OpClassMask; 1232 1233 for (std::vector<MatchableInfo*>::const_iterator it = 1234 Matchables.begin(), ie = Matchables.end(); 1235 it != ie; ++it) { 1236 MatchableInfo &II = **it; 1237 OpClassMask.clear(); 1238 1239 // Keep track of all operands of this instructions which belong to the 1240 // same class. 1241 for (unsigned i = 0, e = II.AsmOperands.size(); i != e; ++i) { 1242 MatchableInfo::AsmOperand &Op = II.AsmOperands[i]; 1243 if (Op.Class->ParserMethod.empty()) 1244 continue; 1245 unsigned &OperandMask = OpClassMask[Op.Class]; 1246 OperandMask |= (1 << i); 1247 } 1248 1249 // Generate operand match info for each mnemonic/operand class pair. 1250 for (std::map<ClassInfo*, unsigned>::iterator iit = OpClassMask.begin(), 1251 iie = OpClassMask.end(); iit != iie; ++iit) { 1252 unsigned OpMask = iit->second; 1253 ClassInfo *CI = iit->first; 1254 OperandMatchInfo.push_back(OperandMatchEntry::create(&II, CI, OpMask)); 1255 } 1256 } 1257} 1258 1259void AsmMatcherInfo::buildInfo() { 1260 // Build information about all of the AssemblerPredicates. 1261 std::vector<Record*> AllPredicates = 1262 Records.getAllDerivedDefinitions("Predicate"); 1263 for (unsigned i = 0, e = AllPredicates.size(); i != e; ++i) { 1264 Record *Pred = AllPredicates[i]; 1265 // Ignore predicates that are not intended for the assembler. 1266 if (!Pred->getValueAsBit("AssemblerMatcherPredicate")) 1267 continue; 1268 1269 if (Pred->getName().empty()) 1270 throw TGError(Pred->getLoc(), "Predicate has no name!"); 1271 1272 unsigned FeatureNo = SubtargetFeatures.size(); 1273 SubtargetFeatures[Pred] = new SubtargetFeatureInfo(Pred, FeatureNo); 1274 assert(FeatureNo < 32 && "Too many subtarget features!"); 1275 } 1276 1277 // Parse the instructions; we need to do this first so that we can gather the 1278 // singleton register classes. 1279 SmallPtrSet<Record*, 16> SingletonRegisters; 1280 unsigned VariantCount = Target.getAsmParserVariantCount(); 1281 for (unsigned VC = 0; VC != VariantCount; ++VC) { 1282 Record *AsmVariant = Target.getAsmParserVariant(VC); 1283 std::string CommentDelimiter = 1284 AsmVariant->getValueAsString("CommentDelimiter"); 1285 std::string RegisterPrefix = AsmVariant->getValueAsString("RegisterPrefix"); 1286 int AsmVariantNo = AsmVariant->getValueAsInt("Variant"); 1287 1288 for (CodeGenTarget::inst_iterator I = Target.inst_begin(), 1289 E = Target.inst_end(); I != E; ++I) { 1290 const CodeGenInstruction &CGI = **I; 1291 1292 // If the tblgen -match-prefix option is specified (for tblgen hackers), 1293 // filter the set of instructions we consider. 1294 if (!StringRef(CGI.TheDef->getName()).startswith(MatchPrefix)) 1295 continue; 1296 1297 // Ignore "codegen only" instructions. 1298 if (CGI.TheDef->getValueAsBit("isCodeGenOnly")) 1299 continue; 1300 1301 // Validate the operand list to ensure we can handle this instruction. 1302 for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) { 1303 const CGIOperandList::OperandInfo &OI = CGI.Operands[i]; 1304 1305 // Validate tied operands. 1306 if (OI.getTiedRegister() != -1) { 1307 // If we have a tied operand that consists of multiple MCOperands, 1308 // reject it. We reject aliases and ignore instructions for now. 1309 if (OI.MINumOperands != 1) { 1310 // FIXME: Should reject these. The ARM backend hits this with $lane 1311 // in a bunch of instructions. The right answer is unclear. 1312 DEBUG({ 1313 errs() << "warning: '" << CGI.TheDef->getName() << "': " 1314 << "ignoring instruction with multi-operand tied operand '" 1315 << OI.Name << "'\n"; 1316 }); 1317 continue; 1318 } 1319 } 1320 } 1321 1322 OwningPtr<MatchableInfo> II(new MatchableInfo(CGI)); 1323 1324 II->initialize(*this, SingletonRegisters, AsmVariantNo, RegisterPrefix); 1325 1326 // Ignore instructions which shouldn't be matched and diagnose invalid 1327 // instruction definitions with an error. 1328 if (!II->validate(CommentDelimiter, true)) 1329 continue; 1330 1331 // Ignore "Int_*" and "*_Int" instructions, which are internal aliases. 1332 // 1333 // FIXME: This is a total hack. 1334 if (StringRef(II->TheDef->getName()).startswith("Int_") || 1335 StringRef(II->TheDef->getName()).endswith("_Int")) 1336 continue; 1337 1338 Matchables.push_back(II.take()); 1339 } 1340 1341 // Parse all of the InstAlias definitions and stick them in the list of 1342 // matchables. 1343 std::vector<Record*> AllInstAliases = 1344 Records.getAllDerivedDefinitions("InstAlias"); 1345 for (unsigned i = 0, e = AllInstAliases.size(); i != e; ++i) { 1346 CodeGenInstAlias *Alias = new CodeGenInstAlias(AllInstAliases[i], Target); 1347 1348 // If the tblgen -match-prefix option is specified (for tblgen hackers), 1349 // filter the set of instruction aliases we consider, based on the target 1350 // instruction. 1351 if (!StringRef(Alias->ResultInst->TheDef->getName()) 1352 .startswith( MatchPrefix)) 1353 continue; 1354 1355 OwningPtr<MatchableInfo> II(new MatchableInfo(Alias)); 1356 1357 II->initialize(*this, SingletonRegisters, AsmVariantNo, RegisterPrefix); 1358 1359 // Validate the alias definitions. 1360 II->validate(CommentDelimiter, false); 1361 1362 Matchables.push_back(II.take()); 1363 } 1364 } 1365 1366 // Build info for the register classes. 1367 buildRegisterClasses(SingletonRegisters); 1368 1369 // Build info for the user defined assembly operand classes. 1370 buildOperandClasses(); 1371 1372 // Build the information about matchables, now that we have fully formed 1373 // classes. 1374 std::vector<MatchableInfo*> NewMatchables; 1375 for (std::vector<MatchableInfo*>::iterator it = Matchables.begin(), 1376 ie = Matchables.end(); it != ie; ++it) { 1377 MatchableInfo *II = *it; 1378 1379 // Parse the tokens after the mnemonic. 1380 // Note: buildInstructionOperandReference may insert new AsmOperands, so 1381 // don't precompute the loop bound. 1382 for (unsigned i = 0; i != II->AsmOperands.size(); ++i) { 1383 MatchableInfo::AsmOperand &Op = II->AsmOperands[i]; 1384 StringRef Token = Op.Token; 1385 1386 // Check for singleton registers. 1387 if (Record *RegRecord = II->AsmOperands[i].SingletonReg) { 1388 Op.Class = RegisterClasses[RegRecord]; 1389 assert(Op.Class && Op.Class->Registers.size() == 1 && 1390 "Unexpected class for singleton register"); 1391 continue; 1392 } 1393 1394 // Check for simple tokens. 1395 if (Token[0] != '$') { 1396 Op.Class = getTokenClass(Token); 1397 continue; 1398 } 1399 1400 if (Token.size() > 1 && isdigit(Token[1])) { 1401 Op.Class = getTokenClass(Token); 1402 continue; 1403 } 1404 1405 // Otherwise this is an operand reference. 1406 StringRef OperandName; 1407 if (Token[1] == '{') 1408 OperandName = Token.substr(2, Token.size() - 3); 1409 else 1410 OperandName = Token.substr(1); 1411 1412 if (II->DefRec.is<const CodeGenInstruction*>()) 1413 buildInstructionOperandReference(II, OperandName, i); 1414 else 1415 buildAliasOperandReference(II, OperandName, Op); 1416 } 1417 1418 if (II->DefRec.is<const CodeGenInstruction*>()) { 1419 II->buildInstructionResultOperands(); 1420 // If the instruction has a two-operand alias, build up the 1421 // matchable here. We'll add them in bulk at the end to avoid 1422 // confusing this loop. 1423 std::string Constraint = 1424 II->TheDef->getValueAsString("TwoOperandAliasConstraint"); 1425 if (Constraint != "") { 1426 // Start by making a copy of the original matchable. 1427 OwningPtr<MatchableInfo> AliasII(new MatchableInfo(*II)); 1428 1429 // Adjust it to be a two-operand alias. 1430 AliasII->formTwoOperandAlias(Constraint); 1431 1432 // Add the alias to the matchables list. 1433 NewMatchables.push_back(AliasII.take()); 1434 } 1435 } else 1436 II->buildAliasResultOperands(); 1437 } 1438 if (!NewMatchables.empty()) 1439 Matchables.insert(Matchables.end(), NewMatchables.begin(), 1440 NewMatchables.end()); 1441 1442 // Process token alias definitions and set up the associated superclass 1443 // information. 1444 std::vector<Record*> AllTokenAliases = 1445 Records.getAllDerivedDefinitions("TokenAlias"); 1446 for (unsigned i = 0, e = AllTokenAliases.size(); i != e; ++i) { 1447 Record *Rec = AllTokenAliases[i]; 1448 ClassInfo *FromClass = getTokenClass(Rec->getValueAsString("FromToken")); 1449 ClassInfo *ToClass = getTokenClass(Rec->getValueAsString("ToToken")); 1450 if (FromClass == ToClass) 1451 throw TGError(Rec->getLoc(), 1452 "error: Destination value identical to source value."); 1453 FromClass->SuperClasses.push_back(ToClass); 1454 } 1455 1456 // Reorder classes so that classes precede super classes. 1457 std::sort(Classes.begin(), Classes.end(), less_ptr<ClassInfo>()); 1458} 1459 1460/// buildInstructionOperandReference - The specified operand is a reference to a 1461/// named operand such as $src. Resolve the Class and OperandInfo pointers. 1462void AsmMatcherInfo:: 1463buildInstructionOperandReference(MatchableInfo *II, 1464 StringRef OperandName, 1465 unsigned AsmOpIdx) { 1466 const CodeGenInstruction &CGI = *II->DefRec.get<const CodeGenInstruction*>(); 1467 const CGIOperandList &Operands = CGI.Operands; 1468 MatchableInfo::AsmOperand *Op = &II->AsmOperands[AsmOpIdx]; 1469 1470 // Map this token to an operand. 1471 unsigned Idx; 1472 if (!Operands.hasOperandNamed(OperandName, Idx)) 1473 throw TGError(II->TheDef->getLoc(), "error: unable to find operand: '" + 1474 OperandName.str() + "'"); 1475 1476 // If the instruction operand has multiple suboperands, but the parser 1477 // match class for the asm operand is still the default "ImmAsmOperand", 1478 // then handle each suboperand separately. 1479 if (Op->SubOpIdx == -1 && Operands[Idx].MINumOperands > 1) { 1480 Record *Rec = Operands[Idx].Rec; 1481 assert(Rec->isSubClassOf("Operand") && "Unexpected operand!"); 1482 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass"); 1483 if (MatchClass && MatchClass->getValueAsString("Name") == "Imm") { 1484 // Insert remaining suboperands after AsmOpIdx in II->AsmOperands. 1485 StringRef Token = Op->Token; // save this in case Op gets moved 1486 for (unsigned SI = 1, SE = Operands[Idx].MINumOperands; SI != SE; ++SI) { 1487 MatchableInfo::AsmOperand NewAsmOp(Token); 1488 NewAsmOp.SubOpIdx = SI; 1489 II->AsmOperands.insert(II->AsmOperands.begin()+AsmOpIdx+SI, NewAsmOp); 1490 } 1491 // Replace Op with first suboperand. 1492 Op = &II->AsmOperands[AsmOpIdx]; // update the pointer in case it moved 1493 Op->SubOpIdx = 0; 1494 } 1495 } 1496 1497 // Set up the operand class. 1498 Op->Class = getOperandClass(Operands[Idx], Op->SubOpIdx); 1499 1500 // If the named operand is tied, canonicalize it to the untied operand. 1501 // For example, something like: 1502 // (outs GPR:$dst), (ins GPR:$src) 1503 // with an asmstring of 1504 // "inc $src" 1505 // we want to canonicalize to: 1506 // "inc $dst" 1507 // so that we know how to provide the $dst operand when filling in the result. 1508 int OITied = Operands[Idx].getTiedRegister(); 1509 if (OITied != -1) { 1510 // The tied operand index is an MIOperand index, find the operand that 1511 // contains it. 1512 std::pair<unsigned, unsigned> Idx = Operands.getSubOperandNumber(OITied); 1513 OperandName = Operands[Idx.first].Name; 1514 Op->SubOpIdx = Idx.second; 1515 } 1516 1517 Op->SrcOpName = OperandName; 1518} 1519 1520/// buildAliasOperandReference - When parsing an operand reference out of the 1521/// matching string (e.g. "movsx $src, $dst"), determine what the class of the 1522/// operand reference is by looking it up in the result pattern definition. 1523void AsmMatcherInfo::buildAliasOperandReference(MatchableInfo *II, 1524 StringRef OperandName, 1525 MatchableInfo::AsmOperand &Op) { 1526 const CodeGenInstAlias &CGA = *II->DefRec.get<const CodeGenInstAlias*>(); 1527 1528 // Set up the operand class. 1529 for (unsigned i = 0, e = CGA.ResultOperands.size(); i != e; ++i) 1530 if (CGA.ResultOperands[i].isRecord() && 1531 CGA.ResultOperands[i].getName() == OperandName) { 1532 // It's safe to go with the first one we find, because CodeGenInstAlias 1533 // validates that all operands with the same name have the same record. 1534 Op.SubOpIdx = CGA.ResultInstOperandIndex[i].second; 1535 // Use the match class from the Alias definition, not the 1536 // destination instruction, as we may have an immediate that's 1537 // being munged by the match class. 1538 Op.Class = getOperandClass(CGA.ResultOperands[i].getRecord(), 1539 Op.SubOpIdx); 1540 Op.SrcOpName = OperandName; 1541 return; 1542 } 1543 1544 throw TGError(II->TheDef->getLoc(), "error: unable to find operand: '" + 1545 OperandName.str() + "'"); 1546} 1547 1548void MatchableInfo::buildInstructionResultOperands() { 1549 const CodeGenInstruction *ResultInst = getResultInst(); 1550 1551 // Loop over all operands of the result instruction, determining how to 1552 // populate them. 1553 for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) { 1554 const CGIOperandList::OperandInfo &OpInfo = ResultInst->Operands[i]; 1555 1556 // If this is a tied operand, just copy from the previously handled operand. 1557 int TiedOp = OpInfo.getTiedRegister(); 1558 if (TiedOp != -1) { 1559 ResOperands.push_back(ResOperand::getTiedOp(TiedOp)); 1560 continue; 1561 } 1562 1563 // Find out what operand from the asmparser this MCInst operand comes from. 1564 int SrcOperand = findAsmOperandNamed(OpInfo.Name); 1565 if (OpInfo.Name.empty() || SrcOperand == -1) 1566 throw TGError(TheDef->getLoc(), "Instruction '" + 1567 TheDef->getName() + "' has operand '" + OpInfo.Name + 1568 "' that doesn't appear in asm string!"); 1569 1570 // Check if the one AsmOperand populates the entire operand. 1571 unsigned NumOperands = OpInfo.MINumOperands; 1572 if (AsmOperands[SrcOperand].SubOpIdx == -1) { 1573 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand, NumOperands)); 1574 continue; 1575 } 1576 1577 // Add a separate ResOperand for each suboperand. 1578 for (unsigned AI = 0; AI < NumOperands; ++AI) { 1579 assert(AsmOperands[SrcOperand+AI].SubOpIdx == (int)AI && 1580 AsmOperands[SrcOperand+AI].SrcOpName == OpInfo.Name && 1581 "unexpected AsmOperands for suboperands"); 1582 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand + AI, 1)); 1583 } 1584 } 1585} 1586 1587void MatchableInfo::buildAliasResultOperands() { 1588 const CodeGenInstAlias &CGA = *DefRec.get<const CodeGenInstAlias*>(); 1589 const CodeGenInstruction *ResultInst = getResultInst(); 1590 1591 // Loop over all operands of the result instruction, determining how to 1592 // populate them. 1593 unsigned AliasOpNo = 0; 1594 unsigned LastOpNo = CGA.ResultInstOperandIndex.size(); 1595 for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) { 1596 const CGIOperandList::OperandInfo *OpInfo = &ResultInst->Operands[i]; 1597 1598 // If this is a tied operand, just copy from the previously handled operand. 1599 int TiedOp = OpInfo->getTiedRegister(); 1600 if (TiedOp != -1) { 1601 ResOperands.push_back(ResOperand::getTiedOp(TiedOp)); 1602 continue; 1603 } 1604 1605 // Handle all the suboperands for this operand. 1606 const std::string &OpName = OpInfo->Name; 1607 for ( ; AliasOpNo < LastOpNo && 1608 CGA.ResultInstOperandIndex[AliasOpNo].first == i; ++AliasOpNo) { 1609 int SubIdx = CGA.ResultInstOperandIndex[AliasOpNo].second; 1610 1611 // Find out what operand from the asmparser that this MCInst operand 1612 // comes from. 1613 switch (CGA.ResultOperands[AliasOpNo].Kind) { 1614 case CodeGenInstAlias::ResultOperand::K_Record: { 1615 StringRef Name = CGA.ResultOperands[AliasOpNo].getName(); 1616 int SrcOperand = findAsmOperand(Name, SubIdx); 1617 if (SrcOperand == -1) 1618 throw TGError(TheDef->getLoc(), "Instruction '" + 1619 TheDef->getName() + "' has operand '" + OpName + 1620 "' that doesn't appear in asm string!"); 1621 unsigned NumOperands = (SubIdx == -1 ? OpInfo->MINumOperands : 1); 1622 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand, 1623 NumOperands)); 1624 break; 1625 } 1626 case CodeGenInstAlias::ResultOperand::K_Imm: { 1627 int64_t ImmVal = CGA.ResultOperands[AliasOpNo].getImm(); 1628 ResOperands.push_back(ResOperand::getImmOp(ImmVal)); 1629 break; 1630 } 1631 case CodeGenInstAlias::ResultOperand::K_Reg: { 1632 Record *Reg = CGA.ResultOperands[AliasOpNo].getRegister(); 1633 ResOperands.push_back(ResOperand::getRegOp(Reg)); 1634 break; 1635 } 1636 } 1637 } 1638 } 1639} 1640 1641static void emitConvertToMCInst(CodeGenTarget &Target, StringRef ClassName, 1642 std::vector<MatchableInfo*> &Infos, 1643 raw_ostream &OS) { 1644 // Write the convert function to a separate stream, so we can drop it after 1645 // the enum. 1646 std::string ConvertFnBody; 1647 raw_string_ostream CvtOS(ConvertFnBody); 1648 1649 // Function we have already generated. 1650 std::set<std::string> GeneratedFns; 1651 1652 // Start the unified conversion function. 1653 CvtOS << "bool " << Target.getName() << ClassName << "::\n"; 1654 CvtOS << "ConvertToMCInst(unsigned Kind, MCInst &Inst, " 1655 << "unsigned Opcode,\n" 1656 << " const SmallVectorImpl<MCParsedAsmOperand*" 1657 << "> &Operands) {\n"; 1658 CvtOS << " Inst.setOpcode(Opcode);\n"; 1659 CvtOS << " switch (Kind) {\n"; 1660 CvtOS << " default:\n"; 1661 1662 // Start the enum, which we will generate inline. 1663 1664 OS << "// Unified function for converting operands to MCInst instances.\n\n"; 1665 OS << "enum ConversionKind {\n"; 1666 1667 // TargetOperandClass - This is the target's operand class, like X86Operand. 1668 std::string TargetOperandClass = Target.getName() + "Operand"; 1669 1670 for (std::vector<MatchableInfo*>::const_iterator it = Infos.begin(), 1671 ie = Infos.end(); it != ie; ++it) { 1672 MatchableInfo &II = **it; 1673 1674 // Check if we have a custom match function. 1675 std::string AsmMatchConverter = 1676 II.getResultInst()->TheDef->getValueAsString("AsmMatchConverter"); 1677 if (!AsmMatchConverter.empty()) { 1678 std::string Signature = "ConvertCustom_" + AsmMatchConverter; 1679 II.ConversionFnKind = Signature; 1680 1681 // Check if we have already generated this signature. 1682 if (!GeneratedFns.insert(Signature).second) 1683 continue; 1684 1685 // If not, emit it now. Add to the enum list. 1686 OS << " " << Signature << ",\n"; 1687 1688 CvtOS << " case " << Signature << ":\n"; 1689 CvtOS << " return " << AsmMatchConverter 1690 << "(Inst, Opcode, Operands);\n"; 1691 continue; 1692 } 1693 1694 // Build the conversion function signature. 1695 std::string Signature = "Convert"; 1696 std::string CaseBody; 1697 raw_string_ostream CaseOS(CaseBody); 1698 1699 // Compute the convert enum and the case body. 1700 for (unsigned i = 0, e = II.ResOperands.size(); i != e; ++i) { 1701 const MatchableInfo::ResOperand &OpInfo = II.ResOperands[i]; 1702 1703 // Generate code to populate each result operand. 1704 switch (OpInfo.Kind) { 1705 case MatchableInfo::ResOperand::RenderAsmOperand: { 1706 // This comes from something we parsed. 1707 MatchableInfo::AsmOperand &Op = II.AsmOperands[OpInfo.AsmOperandNum]; 1708 1709 // Registers are always converted the same, don't duplicate the 1710 // conversion function based on them. 1711 Signature += "__"; 1712 if (Op.Class->isRegisterClass()) 1713 Signature += "Reg"; 1714 else 1715 Signature += Op.Class->ClassName; 1716 Signature += utostr(OpInfo.MINumOperands); 1717 Signature += "_" + itostr(OpInfo.AsmOperandNum); 1718 1719 CaseOS << " ((" << TargetOperandClass << "*)Operands[" 1720 << (OpInfo.AsmOperandNum+1) << "])->" << Op.Class->RenderMethod 1721 << "(Inst, " << OpInfo.MINumOperands << ");\n"; 1722 break; 1723 } 1724 1725 case MatchableInfo::ResOperand::TiedOperand: { 1726 // If this operand is tied to a previous one, just copy the MCInst 1727 // operand from the earlier one.We can only tie single MCOperand values. 1728 //assert(OpInfo.MINumOperands == 1 && "Not a singular MCOperand"); 1729 unsigned TiedOp = OpInfo.TiedOperandNum; 1730 assert(i > TiedOp && "Tied operand precedes its target!"); 1731 CaseOS << " Inst.addOperand(Inst.getOperand(" << TiedOp << "));\n"; 1732 Signature += "__Tie" + utostr(TiedOp); 1733 break; 1734 } 1735 case MatchableInfo::ResOperand::ImmOperand: { 1736 int64_t Val = OpInfo.ImmVal; 1737 CaseOS << " Inst.addOperand(MCOperand::CreateImm(" << Val << "));\n"; 1738 Signature += "__imm" + itostr(Val); 1739 break; 1740 } 1741 case MatchableInfo::ResOperand::RegOperand: { 1742 if (OpInfo.Register == 0) { 1743 CaseOS << " Inst.addOperand(MCOperand::CreateReg(0));\n"; 1744 Signature += "__reg0"; 1745 } else { 1746 std::string N = getQualifiedName(OpInfo.Register); 1747 CaseOS << " Inst.addOperand(MCOperand::CreateReg(" << N << "));\n"; 1748 Signature += "__reg" + OpInfo.Register->getName(); 1749 } 1750 } 1751 } 1752 } 1753 1754 II.ConversionFnKind = Signature; 1755 1756 // Check if we have already generated this signature. 1757 if (!GeneratedFns.insert(Signature).second) 1758 continue; 1759 1760 // If not, emit it now. Add to the enum list. 1761 OS << " " << Signature << ",\n"; 1762 1763 CvtOS << " case " << Signature << ":\n"; 1764 CvtOS << CaseOS.str(); 1765 CvtOS << " return true;\n"; 1766 } 1767 1768 // Finish the convert function. 1769 1770 CvtOS << " }\n"; 1771 CvtOS << " return false;\n"; 1772 CvtOS << "}\n\n"; 1773 1774 // Finish the enum, and drop the convert function after it. 1775 1776 OS << " NumConversionVariants\n"; 1777 OS << "};\n\n"; 1778 1779 OS << CvtOS.str(); 1780} 1781 1782/// emitMatchClassEnumeration - Emit the enumeration for match class kinds. 1783static void emitMatchClassEnumeration(CodeGenTarget &Target, 1784 std::vector<ClassInfo*> &Infos, 1785 raw_ostream &OS) { 1786 OS << "namespace {\n\n"; 1787 1788 OS << "/// MatchClassKind - The kinds of classes which participate in\n" 1789 << "/// instruction matching.\n"; 1790 OS << "enum MatchClassKind {\n"; 1791 OS << " InvalidMatchClass = 0,\n"; 1792 for (std::vector<ClassInfo*>::iterator it = Infos.begin(), 1793 ie = Infos.end(); it != ie; ++it) { 1794 ClassInfo &CI = **it; 1795 OS << " " << CI.Name << ", // "; 1796 if (CI.Kind == ClassInfo::Token) { 1797 OS << "'" << CI.ValueName << "'\n"; 1798 } else if (CI.isRegisterClass()) { 1799 if (!CI.ValueName.empty()) 1800 OS << "register class '" << CI.ValueName << "'\n"; 1801 else 1802 OS << "derived register class\n"; 1803 } else { 1804 OS << "user defined class '" << CI.ValueName << "'\n"; 1805 } 1806 } 1807 OS << " NumMatchClassKinds\n"; 1808 OS << "};\n\n"; 1809 1810 OS << "}\n\n"; 1811} 1812 1813/// emitValidateOperandClass - Emit the function to validate an operand class. 1814static void emitValidateOperandClass(AsmMatcherInfo &Info, 1815 raw_ostream &OS) { 1816 OS << "static unsigned validateOperandClass(MCParsedAsmOperand *GOp, " 1817 << "MatchClassKind Kind) {\n"; 1818 OS << " " << Info.Target.getName() << "Operand &Operand = *(" 1819 << Info.Target.getName() << "Operand*)GOp;\n"; 1820 1821 // The InvalidMatchClass is not to match any operand. 1822 OS << " if (Kind == InvalidMatchClass)\n"; 1823 OS << " return MCTargetAsmParser::Match_InvalidOperand;\n\n"; 1824 1825 // Check for Token operands first. 1826 // FIXME: Use a more specific diagnostic type. 1827 OS << " if (Operand.isToken())\n"; 1828 OS << " return isSubclass(matchTokenString(Operand.getToken()), Kind) ?\n" 1829 << " MCTargetAsmParser::Match_Success :\n" 1830 << " MCTargetAsmParser::Match_InvalidOperand;\n\n"; 1831 1832 // Check for register operands, including sub-classes. 1833 OS << " if (Operand.isReg()) {\n"; 1834 OS << " MatchClassKind OpKind;\n"; 1835 OS << " switch (Operand.getReg()) {\n"; 1836 OS << " default: OpKind = InvalidMatchClass; break;\n"; 1837 for (std::map<Record*, ClassInfo*>::iterator 1838 it = Info.RegisterClasses.begin(), ie = Info.RegisterClasses.end(); 1839 it != ie; ++it) 1840 OS << " case " << Info.Target.getName() << "::" 1841 << it->first->getName() << ": OpKind = " << it->second->Name 1842 << "; break;\n"; 1843 OS << " }\n"; 1844 OS << " return isSubclass(OpKind, Kind) ? " 1845 << "MCTargetAsmParser::Match_Success :\n " 1846 << " MCTargetAsmParser::Match_InvalidOperand;\n }\n\n"; 1847 1848 // Check the user classes. We don't care what order since we're only 1849 // actually matching against one of them. 1850 for (std::vector<ClassInfo*>::iterator it = Info.Classes.begin(), 1851 ie = Info.Classes.end(); it != ie; ++it) { 1852 ClassInfo &CI = **it; 1853 1854 if (!CI.isUserClass()) 1855 continue; 1856 1857 OS << " // '" << CI.ClassName << "' class\n"; 1858 OS << " if (Kind == " << CI.Name << ") {\n"; 1859 OS << " if (Operand." << CI.PredicateMethod << "())\n"; 1860 OS << " return MCTargetAsmParser::Match_Success;\n"; 1861 if (!CI.DiagnosticType.empty()) 1862 OS << " return " << Info.Target.getName() << "AsmParser::Match_" 1863 << CI.DiagnosticType << ";\n"; 1864 OS << " }\n\n"; 1865 } 1866 1867 // Generic fallthrough match failure case for operands that don't have 1868 // specialized diagnostic types. 1869 OS << " return MCTargetAsmParser::Match_InvalidOperand;\n"; 1870 OS << "}\n\n"; 1871} 1872 1873/// emitIsSubclass - Emit the subclass predicate function. 1874static void emitIsSubclass(CodeGenTarget &Target, 1875 std::vector<ClassInfo*> &Infos, 1876 raw_ostream &OS) { 1877 OS << "/// isSubclass - Compute whether \\arg A is a subclass of \\arg B.\n"; 1878 OS << "static bool isSubclass(MatchClassKind A, MatchClassKind B) {\n"; 1879 OS << " if (A == B)\n"; 1880 OS << " return true;\n\n"; 1881 1882 OS << " switch (A) {\n"; 1883 OS << " default:\n"; 1884 OS << " return false;\n"; 1885 for (std::vector<ClassInfo*>::iterator it = Infos.begin(), 1886 ie = Infos.end(); it != ie; ++it) { 1887 ClassInfo &A = **it; 1888 1889 std::vector<StringRef> SuperClasses; 1890 for (std::vector<ClassInfo*>::iterator it = Infos.begin(), 1891 ie = Infos.end(); it != ie; ++it) { 1892 ClassInfo &B = **it; 1893 1894 if (&A != &B && A.isSubsetOf(B)) 1895 SuperClasses.push_back(B.Name); 1896 } 1897 1898 if (SuperClasses.empty()) 1899 continue; 1900 1901 OS << "\n case " << A.Name << ":\n"; 1902 1903 if (SuperClasses.size() == 1) { 1904 OS << " return B == " << SuperClasses.back() << ";\n"; 1905 continue; 1906 } 1907 1908 OS << " switch (B) {\n"; 1909 OS << " default: return false;\n"; 1910 for (unsigned i = 0, e = SuperClasses.size(); i != e; ++i) 1911 OS << " case " << SuperClasses[i] << ": return true;\n"; 1912 OS << " }\n"; 1913 } 1914 OS << " }\n"; 1915 OS << "}\n\n"; 1916} 1917 1918/// emitMatchTokenString - Emit the function to match a token string to the 1919/// appropriate match class value. 1920static void emitMatchTokenString(CodeGenTarget &Target, 1921 std::vector<ClassInfo*> &Infos, 1922 raw_ostream &OS) { 1923 // Construct the match list. 1924 std::vector<StringMatcher::StringPair> Matches; 1925 for (std::vector<ClassInfo*>::iterator it = Infos.begin(), 1926 ie = Infos.end(); it != ie; ++it) { 1927 ClassInfo &CI = **it; 1928 1929 if (CI.Kind == ClassInfo::Token) 1930 Matches.push_back(StringMatcher::StringPair(CI.ValueName, 1931 "return " + CI.Name + ";")); 1932 } 1933 1934 OS << "static MatchClassKind matchTokenString(StringRef Name) {\n"; 1935 1936 StringMatcher("Name", Matches, OS).Emit(); 1937 1938 OS << " return InvalidMatchClass;\n"; 1939 OS << "}\n\n"; 1940} 1941 1942/// emitMatchRegisterName - Emit the function to match a string to the target 1943/// specific register enum. 1944static void emitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser, 1945 raw_ostream &OS) { 1946 // Construct the match list. 1947 std::vector<StringMatcher::StringPair> Matches; 1948 const std::vector<CodeGenRegister*> &Regs = 1949 Target.getRegBank().getRegisters(); 1950 for (unsigned i = 0, e = Regs.size(); i != e; ++i) { 1951 const CodeGenRegister *Reg = Regs[i]; 1952 if (Reg->TheDef->getValueAsString("AsmName").empty()) 1953 continue; 1954 1955 Matches.push_back(StringMatcher::StringPair( 1956 Reg->TheDef->getValueAsString("AsmName"), 1957 "return " + utostr(Reg->EnumValue) + ";")); 1958 } 1959 1960 OS << "static unsigned MatchRegisterName(StringRef Name) {\n"; 1961 1962 StringMatcher("Name", Matches, OS).Emit(); 1963 1964 OS << " return 0;\n"; 1965 OS << "}\n\n"; 1966} 1967 1968/// emitSubtargetFeatureFlagEnumeration - Emit the subtarget feature flag 1969/// definitions. 1970static void emitSubtargetFeatureFlagEnumeration(AsmMatcherInfo &Info, 1971 raw_ostream &OS) { 1972 OS << "// Flags for subtarget features that participate in " 1973 << "instruction matching.\n"; 1974 OS << "enum SubtargetFeatureFlag {\n"; 1975 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator 1976 it = Info.SubtargetFeatures.begin(), 1977 ie = Info.SubtargetFeatures.end(); it != ie; ++it) { 1978 SubtargetFeatureInfo &SFI = *it->second; 1979 OS << " " << SFI.getEnumName() << " = (1 << " << SFI.Index << "),\n"; 1980 } 1981 OS << " Feature_None = 0\n"; 1982 OS << "};\n\n"; 1983} 1984 1985/// emitOperandDiagnosticTypes - Emit the operand matching diagnostic types. 1986static void emitOperandDiagnosticTypes(AsmMatcherInfo &Info, raw_ostream &OS) { 1987 // Get the set of diagnostic types from all of the operand classes. 1988 std::set<StringRef> Types; 1989 for (std::map<Record*, ClassInfo*>::const_iterator 1990 I = Info.AsmOperandClasses.begin(), 1991 E = Info.AsmOperandClasses.end(); I != E; ++I) { 1992 if (!I->second->DiagnosticType.empty()) 1993 Types.insert(I->second->DiagnosticType); 1994 } 1995 1996 if (Types.empty()) return; 1997 1998 // Now emit the enum entries. 1999 for (std::set<StringRef>::const_iterator I = Types.begin(), E = Types.end(); 2000 I != E; ++I) 2001 OS << " Match_" << *I << ",\n"; 2002 OS << " END_OPERAND_DIAGNOSTIC_TYPES\n"; 2003} 2004 2005/// emitGetSubtargetFeatureName - Emit the helper function to get the 2006/// user-level name for a subtarget feature. 2007static void emitGetSubtargetFeatureName(AsmMatcherInfo &Info, raw_ostream &OS) { 2008 OS << "// User-level names for subtarget features that participate in\n" 2009 << "// instruction matching.\n" 2010 << "static const char *getSubtargetFeatureName(unsigned Val) {\n" 2011 << " switch(Val) {\n"; 2012 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator 2013 it = Info.SubtargetFeatures.begin(), 2014 ie = Info.SubtargetFeatures.end(); it != ie; ++it) { 2015 SubtargetFeatureInfo &SFI = *it->second; 2016 // FIXME: Totally just a placeholder name to get the algorithm working. 2017 OS << " case " << SFI.getEnumName() << ": return \"" 2018 << SFI.TheDef->getValueAsString("PredicateName") << "\";\n"; 2019 } 2020 OS << " default: return \"(unknown)\";\n"; 2021 OS << " }\n}\n\n"; 2022} 2023 2024/// emitComputeAvailableFeatures - Emit the function to compute the list of 2025/// available features given a subtarget. 2026static void emitComputeAvailableFeatures(AsmMatcherInfo &Info, 2027 raw_ostream &OS) { 2028 std::string ClassName = 2029 Info.AsmParser->getValueAsString("AsmParserClassName"); 2030 2031 OS << "unsigned " << Info.Target.getName() << ClassName << "::\n" 2032 << "ComputeAvailableFeatures(uint64_t FB) const {\n"; 2033 OS << " unsigned Features = 0;\n"; 2034 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator 2035 it = Info.SubtargetFeatures.begin(), 2036 ie = Info.SubtargetFeatures.end(); it != ie; ++it) { 2037 SubtargetFeatureInfo &SFI = *it->second; 2038 2039 OS << " if ("; 2040 std::string CondStorage = 2041 SFI.TheDef->getValueAsString("AssemblerCondString"); 2042 StringRef Conds = CondStorage; 2043 std::pair<StringRef,StringRef> Comma = Conds.split(','); 2044 bool First = true; 2045 do { 2046 if (!First) 2047 OS << " && "; 2048 2049 bool Neg = false; 2050 StringRef Cond = Comma.first; 2051 if (Cond[0] == '!') { 2052 Neg = true; 2053 Cond = Cond.substr(1); 2054 } 2055 2056 OS << "((FB & " << Info.Target.getName() << "::" << Cond << ")"; 2057 if (Neg) 2058 OS << " == 0"; 2059 else 2060 OS << " != 0"; 2061 OS << ")"; 2062 2063 if (Comma.second.empty()) 2064 break; 2065 2066 First = false; 2067 Comma = Comma.second.split(','); 2068 } while (true); 2069 2070 OS << ")\n"; 2071 OS << " Features |= " << SFI.getEnumName() << ";\n"; 2072 } 2073 OS << " return Features;\n"; 2074 OS << "}\n\n"; 2075} 2076 2077static std::string GetAliasRequiredFeatures(Record *R, 2078 const AsmMatcherInfo &Info) { 2079 std::vector<Record*> ReqFeatures = R->getValueAsListOfDefs("Predicates"); 2080 std::string Result; 2081 unsigned NumFeatures = 0; 2082 for (unsigned i = 0, e = ReqFeatures.size(); i != e; ++i) { 2083 SubtargetFeatureInfo *F = Info.getSubtargetFeature(ReqFeatures[i]); 2084 2085 if (F == 0) 2086 throw TGError(R->getLoc(), "Predicate '" + ReqFeatures[i]->getName() + 2087 "' is not marked as an AssemblerPredicate!"); 2088 2089 if (NumFeatures) 2090 Result += '|'; 2091 2092 Result += F->getEnumName(); 2093 ++NumFeatures; 2094 } 2095 2096 if (NumFeatures > 1) 2097 Result = '(' + Result + ')'; 2098 return Result; 2099} 2100 2101/// emitMnemonicAliases - If the target has any MnemonicAlias<> definitions, 2102/// emit a function for them and return true, otherwise return false. 2103static bool emitMnemonicAliases(raw_ostream &OS, const AsmMatcherInfo &Info) { 2104 // Ignore aliases when match-prefix is set. 2105 if (!MatchPrefix.empty()) 2106 return false; 2107 2108 std::vector<Record*> Aliases = 2109 Info.getRecords().getAllDerivedDefinitions("MnemonicAlias"); 2110 if (Aliases.empty()) return false; 2111 2112 OS << "static void applyMnemonicAliases(StringRef &Mnemonic, " 2113 "unsigned Features) {\n"; 2114 2115 // Keep track of all the aliases from a mnemonic. Use an std::map so that the 2116 // iteration order of the map is stable. 2117 std::map<std::string, std::vector<Record*> > AliasesFromMnemonic; 2118 2119 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) { 2120 Record *R = Aliases[i]; 2121 AliasesFromMnemonic[R->getValueAsString("FromMnemonic")].push_back(R); 2122 } 2123 2124 // Process each alias a "from" mnemonic at a time, building the code executed 2125 // by the string remapper. 2126 std::vector<StringMatcher::StringPair> Cases; 2127 for (std::map<std::string, std::vector<Record*> >::iterator 2128 I = AliasesFromMnemonic.begin(), E = AliasesFromMnemonic.end(); 2129 I != E; ++I) { 2130 const std::vector<Record*> &ToVec = I->second; 2131 2132 // Loop through each alias and emit code that handles each case. If there 2133 // are two instructions without predicates, emit an error. If there is one, 2134 // emit it last. 2135 std::string MatchCode; 2136 int AliasWithNoPredicate = -1; 2137 2138 for (unsigned i = 0, e = ToVec.size(); i != e; ++i) { 2139 Record *R = ToVec[i]; 2140 std::string FeatureMask = GetAliasRequiredFeatures(R, Info); 2141 2142 // If this unconditionally matches, remember it for later and diagnose 2143 // duplicates. 2144 if (FeatureMask.empty()) { 2145 if (AliasWithNoPredicate != -1) { 2146 // We can't have two aliases from the same mnemonic with no predicate. 2147 PrintError(ToVec[AliasWithNoPredicate]->getLoc(), 2148 "two MnemonicAliases with the same 'from' mnemonic!"); 2149 throw TGError(R->getLoc(), "this is the other MnemonicAlias."); 2150 } 2151 2152 AliasWithNoPredicate = i; 2153 continue; 2154 } 2155 if (R->getValueAsString("ToMnemonic") == I->first) 2156 throw TGError(R->getLoc(), "MnemonicAlias to the same string"); 2157 2158 if (!MatchCode.empty()) 2159 MatchCode += "else "; 2160 MatchCode += "if ((Features & " + FeatureMask + ") == "+FeatureMask+")\n"; 2161 MatchCode += " Mnemonic = \"" +R->getValueAsString("ToMnemonic")+"\";\n"; 2162 } 2163 2164 if (AliasWithNoPredicate != -1) { 2165 Record *R = ToVec[AliasWithNoPredicate]; 2166 if (!MatchCode.empty()) 2167 MatchCode += "else\n "; 2168 MatchCode += "Mnemonic = \"" + R->getValueAsString("ToMnemonic")+"\";\n"; 2169 } 2170 2171 MatchCode += "return;"; 2172 2173 Cases.push_back(std::make_pair(I->first, MatchCode)); 2174 } 2175 2176 StringMatcher("Mnemonic", Cases, OS).Emit(); 2177 OS << "}\n\n"; 2178 2179 return true; 2180} 2181 2182static const char *getMinimalTypeForRange(uint64_t Range) { 2183 assert(Range < 0xFFFFFFFFULL && "Enum too large"); 2184 if (Range > 0xFFFF) 2185 return "uint32_t"; 2186 if (Range > 0xFF) 2187 return "uint16_t"; 2188 return "uint8_t"; 2189} 2190 2191static void emitCustomOperandParsing(raw_ostream &OS, CodeGenTarget &Target, 2192 const AsmMatcherInfo &Info, StringRef ClassName) { 2193 // Emit the static custom operand parsing table; 2194 OS << "namespace {\n"; 2195 OS << " struct OperandMatchEntry {\n"; 2196 OS << " static const char *const MnemonicTable;\n"; 2197 OS << " uint32_t OperandMask;\n"; 2198 OS << " uint32_t Mnemonic;\n"; 2199 OS << " " << getMinimalTypeForRange(1ULL << Info.SubtargetFeatures.size()) 2200 << " RequiredFeatures;\n"; 2201 OS << " " << getMinimalTypeForRange(Info.Classes.size()) 2202 << " Class;\n\n"; 2203 OS << " StringRef getMnemonic() const {\n"; 2204 OS << " return StringRef(MnemonicTable + Mnemonic + 1,\n"; 2205 OS << " MnemonicTable[Mnemonic]);\n"; 2206 OS << " }\n"; 2207 OS << " };\n\n"; 2208 2209 OS << " // Predicate for searching for an opcode.\n"; 2210 OS << " struct LessOpcodeOperand {\n"; 2211 OS << " bool operator()(const OperandMatchEntry &LHS, StringRef RHS) {\n"; 2212 OS << " return LHS.getMnemonic() < RHS;\n"; 2213 OS << " }\n"; 2214 OS << " bool operator()(StringRef LHS, const OperandMatchEntry &RHS) {\n"; 2215 OS << " return LHS < RHS.getMnemonic();\n"; 2216 OS << " }\n"; 2217 OS << " bool operator()(const OperandMatchEntry &LHS,"; 2218 OS << " const OperandMatchEntry &RHS) {\n"; 2219 OS << " return LHS.getMnemonic() < RHS.getMnemonic();\n"; 2220 OS << " }\n"; 2221 OS << " };\n"; 2222 2223 OS << "} // end anonymous namespace.\n\n"; 2224 2225 StringToOffsetTable StringTable; 2226 2227 OS << "static const OperandMatchEntry OperandMatchTable[" 2228 << Info.OperandMatchInfo.size() << "] = {\n"; 2229 2230 OS << " /* Operand List Mask, Mnemonic, Operand Class, Features */\n"; 2231 for (std::vector<OperandMatchEntry>::const_iterator it = 2232 Info.OperandMatchInfo.begin(), ie = Info.OperandMatchInfo.end(); 2233 it != ie; ++it) { 2234 const OperandMatchEntry &OMI = *it; 2235 const MatchableInfo &II = *OMI.MI; 2236 2237 OS << " { " << OMI.OperandMask; 2238 2239 OS << " /* "; 2240 bool printComma = false; 2241 for (int i = 0, e = 31; i !=e; ++i) 2242 if (OMI.OperandMask & (1 << i)) { 2243 if (printComma) 2244 OS << ", "; 2245 OS << i; 2246 printComma = true; 2247 } 2248 OS << " */"; 2249 2250 // Store a pascal-style length byte in the mnemonic. 2251 std::string LenMnemonic = char(II.Mnemonic.size()) + II.Mnemonic.str(); 2252 OS << ", " << StringTable.GetOrAddStringOffset(LenMnemonic, false) 2253 << " /* " << II.Mnemonic << " */, "; 2254 2255 // Write the required features mask. 2256 if (!II.RequiredFeatures.empty()) { 2257 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) { 2258 if (i) OS << "|"; 2259 OS << II.RequiredFeatures[i]->getEnumName(); 2260 } 2261 } else 2262 OS << "0"; 2263 2264 OS << ", " << OMI.CI->Name; 2265 2266 OS << " },\n"; 2267 } 2268 OS << "};\n\n"; 2269 2270 OS << "const char *const OperandMatchEntry::MnemonicTable =\n"; 2271 StringTable.EmitString(OS); 2272 OS << ";\n\n"; 2273 2274 // Emit the operand class switch to call the correct custom parser for 2275 // the found operand class. 2276 OS << Target.getName() << ClassName << "::OperandMatchResultTy " 2277 << Target.getName() << ClassName << "::\n" 2278 << "tryCustomParseOperand(SmallVectorImpl<MCParsedAsmOperand*>" 2279 << " &Operands,\n unsigned MCK) {\n\n" 2280 << " switch(MCK) {\n"; 2281 2282 for (std::vector<ClassInfo*>::const_iterator it = Info.Classes.begin(), 2283 ie = Info.Classes.end(); it != ie; ++it) { 2284 ClassInfo *CI = *it; 2285 if (CI->ParserMethod.empty()) 2286 continue; 2287 OS << " case " << CI->Name << ":\n" 2288 << " return " << CI->ParserMethod << "(Operands);\n"; 2289 } 2290 2291 OS << " default:\n"; 2292 OS << " return MatchOperand_NoMatch;\n"; 2293 OS << " }\n"; 2294 OS << " return MatchOperand_NoMatch;\n"; 2295 OS << "}\n\n"; 2296 2297 // Emit the static custom operand parser. This code is very similar with 2298 // the other matcher. Also use MatchResultTy here just in case we go for 2299 // a better error handling. 2300 OS << Target.getName() << ClassName << "::OperandMatchResultTy " 2301 << Target.getName() << ClassName << "::\n" 2302 << "MatchOperandParserImpl(SmallVectorImpl<MCParsedAsmOperand*>" 2303 << " &Operands,\n StringRef Mnemonic) {\n"; 2304 2305 // Emit code to get the available features. 2306 OS << " // Get the current feature set.\n"; 2307 OS << " unsigned AvailableFeatures = getAvailableFeatures();\n\n"; 2308 2309 OS << " // Get the next operand index.\n"; 2310 OS << " unsigned NextOpNum = Operands.size()-1;\n"; 2311 2312 // Emit code to search the table. 2313 OS << " // Search the table.\n"; 2314 OS << " std::pair<const OperandMatchEntry*, const OperandMatchEntry*>"; 2315 OS << " MnemonicRange =\n"; 2316 OS << " std::equal_range(OperandMatchTable, OperandMatchTable+" 2317 << Info.OperandMatchInfo.size() << ", Mnemonic,\n" 2318 << " LessOpcodeOperand());\n\n"; 2319 2320 OS << " if (MnemonicRange.first == MnemonicRange.second)\n"; 2321 OS << " return MatchOperand_NoMatch;\n\n"; 2322 2323 OS << " for (const OperandMatchEntry *it = MnemonicRange.first,\n" 2324 << " *ie = MnemonicRange.second; it != ie; ++it) {\n"; 2325 2326 OS << " // equal_range guarantees that instruction mnemonic matches.\n"; 2327 OS << " assert(Mnemonic == it->getMnemonic());\n\n"; 2328 2329 // Emit check that the required features are available. 2330 OS << " // check if the available features match\n"; 2331 OS << " if ((AvailableFeatures & it->RequiredFeatures) " 2332 << "!= it->RequiredFeatures) {\n"; 2333 OS << " continue;\n"; 2334 OS << " }\n\n"; 2335 2336 // Emit check to ensure the operand number matches. 2337 OS << " // check if the operand in question has a custom parser.\n"; 2338 OS << " if (!(it->OperandMask & (1 << NextOpNum)))\n"; 2339 OS << " continue;\n\n"; 2340 2341 // Emit call to the custom parser method 2342 OS << " // call custom parse method to handle the operand\n"; 2343 OS << " OperandMatchResultTy Result = "; 2344 OS << "tryCustomParseOperand(Operands, it->Class);\n"; 2345 OS << " if (Result != MatchOperand_NoMatch)\n"; 2346 OS << " return Result;\n"; 2347 OS << " }\n\n"; 2348 2349 OS << " // Okay, we had no match.\n"; 2350 OS << " return MatchOperand_NoMatch;\n"; 2351 OS << "}\n\n"; 2352} 2353 2354void AsmMatcherEmitter::run(raw_ostream &OS) { 2355 CodeGenTarget Target(Records); 2356 Record *AsmParser = Target.getAsmParser(); 2357 std::string ClassName = AsmParser->getValueAsString("AsmParserClassName"); 2358 2359 // Compute the information on the instructions to match. 2360 AsmMatcherInfo Info(AsmParser, Target, Records); 2361 Info.buildInfo(); 2362 2363 // Sort the instruction table using the partial order on classes. We use 2364 // stable_sort to ensure that ambiguous instructions are still 2365 // deterministically ordered. 2366 std::stable_sort(Info.Matchables.begin(), Info.Matchables.end(), 2367 less_ptr<MatchableInfo>()); 2368 2369 DEBUG_WITH_TYPE("instruction_info", { 2370 for (std::vector<MatchableInfo*>::iterator 2371 it = Info.Matchables.begin(), ie = Info.Matchables.end(); 2372 it != ie; ++it) 2373 (*it)->dump(); 2374 }); 2375 2376 // Check for ambiguous matchables. 2377 DEBUG_WITH_TYPE("ambiguous_instrs", { 2378 unsigned NumAmbiguous = 0; 2379 for (unsigned i = 0, e = Info.Matchables.size(); i != e; ++i) { 2380 for (unsigned j = i + 1; j != e; ++j) { 2381 MatchableInfo &A = *Info.Matchables[i]; 2382 MatchableInfo &B = *Info.Matchables[j]; 2383 2384 if (A.couldMatchAmbiguouslyWith(B)) { 2385 errs() << "warning: ambiguous matchables:\n"; 2386 A.dump(); 2387 errs() << "\nis incomparable with:\n"; 2388 B.dump(); 2389 errs() << "\n\n"; 2390 ++NumAmbiguous; 2391 } 2392 } 2393 } 2394 if (NumAmbiguous) 2395 errs() << "warning: " << NumAmbiguous 2396 << " ambiguous matchables!\n"; 2397 }); 2398 2399 // Compute the information on the custom operand parsing. 2400 Info.buildOperandMatchInfo(); 2401 2402 // Write the output. 2403 2404 // Information for the class declaration. 2405 OS << "\n#ifdef GET_ASSEMBLER_HEADER\n"; 2406 OS << "#undef GET_ASSEMBLER_HEADER\n"; 2407 OS << " // This should be included into the middle of the declaration of\n"; 2408 OS << " // your subclasses implementation of MCTargetAsmParser.\n"; 2409 OS << " unsigned ComputeAvailableFeatures(uint64_t FeatureBits) const;\n"; 2410 OS << " bool ConvertToMCInst(unsigned Kind, MCInst &Inst, " 2411 << "unsigned Opcode,\n" 2412 << " const SmallVectorImpl<MCParsedAsmOperand*> " 2413 << "&Operands);\n"; 2414 OS << " bool MnemonicIsValid(StringRef Mnemonic);\n"; 2415 OS << " unsigned MatchInstructionImpl(\n"; 2416 OS << " const SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n"; 2417 OS << " MCInst &Inst, unsigned &ErrorInfo, unsigned VariantID = 0);\n"; 2418 2419 if (Info.OperandMatchInfo.size()) { 2420 OS << "\n enum OperandMatchResultTy {\n"; 2421 OS << " MatchOperand_Success, // operand matched successfully\n"; 2422 OS << " MatchOperand_NoMatch, // operand did not match\n"; 2423 OS << " MatchOperand_ParseFail // operand matched but had errors\n"; 2424 OS << " };\n"; 2425 OS << " OperandMatchResultTy MatchOperandParserImpl(\n"; 2426 OS << " SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n"; 2427 OS << " StringRef Mnemonic);\n"; 2428 2429 OS << " OperandMatchResultTy tryCustomParseOperand(\n"; 2430 OS << " SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n"; 2431 OS << " unsigned MCK);\n\n"; 2432 } 2433 2434 OS << "#endif // GET_ASSEMBLER_HEADER_INFO\n\n"; 2435 2436 // Emit the operand match diagnostic enum names. 2437 OS << "\n#ifdef GET_OPERAND_DIAGNOSTIC_TYPES\n"; 2438 OS << "#undef GET_OPERAND_DIAGNOSTIC_TYPES\n\n"; 2439 emitOperandDiagnosticTypes(Info, OS); 2440 OS << "#endif // GET_OPERAND_DIAGNOSTIC_TYPES\n\n"; 2441 2442 2443 OS << "\n#ifdef GET_REGISTER_MATCHER\n"; 2444 OS << "#undef GET_REGISTER_MATCHER\n\n"; 2445 2446 // Emit the subtarget feature enumeration. 2447 emitSubtargetFeatureFlagEnumeration(Info, OS); 2448 2449 // Emit the function to match a register name to number. 2450 emitMatchRegisterName(Target, AsmParser, OS); 2451 2452 OS << "#endif // GET_REGISTER_MATCHER\n\n"; 2453 2454 OS << "\n#ifdef GET_SUBTARGET_FEATURE_NAME\n"; 2455 OS << "#undef GET_SUBTARGET_FEATURE_NAME\n\n"; 2456 2457 // Generate the helper function to get the names for subtarget features. 2458 emitGetSubtargetFeatureName(Info, OS); 2459 2460 OS << "#endif // GET_SUBTARGET_FEATURE_NAME\n\n"; 2461 2462 OS << "\n#ifdef GET_MATCHER_IMPLEMENTATION\n"; 2463 OS << "#undef GET_MATCHER_IMPLEMENTATION\n\n"; 2464 2465 // Generate the function that remaps for mnemonic aliases. 2466 bool HasMnemonicAliases = emitMnemonicAliases(OS, Info); 2467 2468 // Generate the unified function to convert operands into an MCInst. 2469 emitConvertToMCInst(Target, ClassName, Info.Matchables, OS); 2470 2471 // Emit the enumeration for classes which participate in matching. 2472 emitMatchClassEnumeration(Target, Info.Classes, OS); 2473 2474 // Emit the routine to match token strings to their match class. 2475 emitMatchTokenString(Target, Info.Classes, OS); 2476 2477 // Emit the subclass predicate routine. 2478 emitIsSubclass(Target, Info.Classes, OS); 2479 2480 // Emit the routine to validate an operand against a match class. 2481 emitValidateOperandClass(Info, OS); 2482 2483 // Emit the available features compute function. 2484 emitComputeAvailableFeatures(Info, OS); 2485 2486 2487 size_t MaxNumOperands = 0; 2488 for (std::vector<MatchableInfo*>::const_iterator it = 2489 Info.Matchables.begin(), ie = Info.Matchables.end(); 2490 it != ie; ++it) 2491 MaxNumOperands = std::max(MaxNumOperands, (*it)->AsmOperands.size()); 2492 2493 // Emit the static match table; unused classes get initalized to 0 which is 2494 // guaranteed to be InvalidMatchClass. 2495 // 2496 // FIXME: We can reduce the size of this table very easily. First, we change 2497 // it so that store the kinds in separate bit-fields for each index, which 2498 // only needs to be the max width used for classes at that index (we also need 2499 // to reject based on this during classification). If we then make sure to 2500 // order the match kinds appropriately (putting mnemonics last), then we 2501 // should only end up using a few bits for each class, especially the ones 2502 // following the mnemonic. 2503 OS << "namespace {\n"; 2504 OS << " struct MatchEntry {\n"; 2505 OS << " static const char *const MnemonicTable;\n"; 2506 OS << " uint32_t Mnemonic;\n"; 2507 OS << " uint16_t Opcode;\n"; 2508 OS << " " << getMinimalTypeForRange(Info.Matchables.size()) 2509 << " ConvertFn;\n"; 2510 OS << " " << getMinimalTypeForRange(1ULL << Info.SubtargetFeatures.size()) 2511 << " RequiredFeatures;\n"; 2512 OS << " " << getMinimalTypeForRange(Info.Classes.size()) 2513 << " Classes[" << MaxNumOperands << "];\n"; 2514 OS << " uint8_t AsmVariantID;\n\n"; 2515 OS << " StringRef getMnemonic() const {\n"; 2516 OS << " return StringRef(MnemonicTable + Mnemonic + 1,\n"; 2517 OS << " MnemonicTable[Mnemonic]);\n"; 2518 OS << " }\n"; 2519 OS << " };\n\n"; 2520 2521 OS << " // Predicate for searching for an opcode.\n"; 2522 OS << " struct LessOpcode {\n"; 2523 OS << " bool operator()(const MatchEntry &LHS, StringRef RHS) {\n"; 2524 OS << " return LHS.getMnemonic() < RHS;\n"; 2525 OS << " }\n"; 2526 OS << " bool operator()(StringRef LHS, const MatchEntry &RHS) {\n"; 2527 OS << " return LHS < RHS.getMnemonic();\n"; 2528 OS << " }\n"; 2529 OS << " bool operator()(const MatchEntry &LHS, const MatchEntry &RHS) {\n"; 2530 OS << " return LHS.getMnemonic() < RHS.getMnemonic();\n"; 2531 OS << " }\n"; 2532 OS << " };\n"; 2533 2534 OS << "} // end anonymous namespace.\n\n"; 2535 2536 StringToOffsetTable StringTable; 2537 2538 OS << "static const MatchEntry MatchTable[" 2539 << Info.Matchables.size() << "] = {\n"; 2540 2541 for (std::vector<MatchableInfo*>::const_iterator it = 2542 Info.Matchables.begin(), ie = Info.Matchables.end(); 2543 it != ie; ++it) { 2544 MatchableInfo &II = **it; 2545 2546 // Store a pascal-style length byte in the mnemonic. 2547 std::string LenMnemonic = char(II.Mnemonic.size()) + II.Mnemonic.str(); 2548 OS << " { " << StringTable.GetOrAddStringOffset(LenMnemonic, false) 2549 << " /* " << II.Mnemonic << " */, " 2550 << Target.getName() << "::" 2551 << II.getResultInst()->TheDef->getName() << ", " 2552 << II.ConversionFnKind << ", "; 2553 2554 // Write the required features mask. 2555 if (!II.RequiredFeatures.empty()) { 2556 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) { 2557 if (i) OS << "|"; 2558 OS << II.RequiredFeatures[i]->getEnumName(); 2559 } 2560 } else 2561 OS << "0"; 2562 2563 OS << ", { "; 2564 for (unsigned i = 0, e = II.AsmOperands.size(); i != e; ++i) { 2565 MatchableInfo::AsmOperand &Op = II.AsmOperands[i]; 2566 2567 if (i) OS << ", "; 2568 OS << Op.Class->Name; 2569 } 2570 OS << " }, " << II.AsmVariantID; 2571 OS << "},\n"; 2572 } 2573 2574 OS << "};\n\n"; 2575 2576 OS << "const char *const MatchEntry::MnemonicTable =\n"; 2577 StringTable.EmitString(OS); 2578 OS << ";\n\n"; 2579 2580 // A method to determine if a mnemonic is in the list. 2581 OS << "bool " << Target.getName() << ClassName << "::\n" 2582 << "MnemonicIsValid(StringRef Mnemonic) {\n"; 2583 OS << " // Search the table.\n"; 2584 OS << " std::pair<const MatchEntry*, const MatchEntry*> MnemonicRange =\n"; 2585 OS << " std::equal_range(MatchTable, MatchTable+" 2586 << Info.Matchables.size() << ", Mnemonic, LessOpcode());\n"; 2587 OS << " return MnemonicRange.first != MnemonicRange.second;\n"; 2588 OS << "}\n\n"; 2589 2590 // Finally, build the match function. 2591 OS << "unsigned " 2592 << Target.getName() << ClassName << "::\n" 2593 << "MatchInstructionImpl(const SmallVectorImpl<MCParsedAsmOperand*>" 2594 << " &Operands,\n"; 2595 OS << " MCInst &Inst, unsigned &ErrorInfo, "; 2596 OS << "unsigned VariantID) {\n"; 2597 2598 // Emit code to get the available features. 2599 OS << " // Get the current feature set.\n"; 2600 OS << " unsigned AvailableFeatures = getAvailableFeatures();\n\n"; 2601 2602 OS << " // Get the instruction mnemonic, which is the first token.\n"; 2603 OS << " StringRef Mnemonic = ((" << Target.getName() 2604 << "Operand*)Operands[0])->getToken();\n\n"; 2605 2606 if (HasMnemonicAliases) { 2607 OS << " // Process all MnemonicAliases to remap the mnemonic.\n"; 2608 OS << " // FIXME : Add an entry in AsmParserVariant to check this.\n"; 2609 OS << " if (!VariantID)\n"; 2610 OS << " applyMnemonicAliases(Mnemonic, AvailableFeatures);\n\n"; 2611 } 2612 2613 // Emit code to compute the class list for this operand vector. 2614 OS << " // Eliminate obvious mismatches.\n"; 2615 OS << " if (Operands.size() > " << (MaxNumOperands+1) << ") {\n"; 2616 OS << " ErrorInfo = " << (MaxNumOperands+1) << ";\n"; 2617 OS << " return Match_InvalidOperand;\n"; 2618 OS << " }\n\n"; 2619 2620 OS << " // Some state to try to produce better error messages.\n"; 2621 OS << " bool HadMatchOtherThanFeatures = false;\n"; 2622 OS << " bool HadMatchOtherThanPredicate = false;\n"; 2623 OS << " unsigned RetCode = Match_InvalidOperand;\n"; 2624 OS << " unsigned MissingFeatures = ~0U;\n"; 2625 OS << " // Set ErrorInfo to the operand that mismatches if it is\n"; 2626 OS << " // wrong for all instances of the instruction.\n"; 2627 OS << " ErrorInfo = ~0U;\n"; 2628 2629 // Emit code to search the table. 2630 OS << " // Search the table.\n"; 2631 OS << " std::pair<const MatchEntry*, const MatchEntry*> MnemonicRange =\n"; 2632 OS << " std::equal_range(MatchTable, MatchTable+" 2633 << Info.Matchables.size() << ", Mnemonic, LessOpcode());\n\n"; 2634 2635 OS << " // Return a more specific error code if no mnemonics match.\n"; 2636 OS << " if (MnemonicRange.first == MnemonicRange.second)\n"; 2637 OS << " return Match_MnemonicFail;\n\n"; 2638 2639 OS << " for (const MatchEntry *it = MnemonicRange.first, " 2640 << "*ie = MnemonicRange.second;\n"; 2641 OS << " it != ie; ++it) {\n"; 2642 2643 OS << " // equal_range guarantees that instruction mnemonic matches.\n"; 2644 OS << " assert(Mnemonic == it->getMnemonic());\n"; 2645 2646 // Emit check that the subclasses match. 2647 OS << " if (VariantID != it->AsmVariantID) continue;\n"; 2648 OS << " bool OperandsValid = true;\n"; 2649 OS << " for (unsigned i = 0; i != " << MaxNumOperands << "; ++i) {\n"; 2650 OS << " if (i + 1 >= Operands.size()) {\n"; 2651 OS << " OperandsValid = (it->Classes[i] == " <<"InvalidMatchClass);\n"; 2652 OS << " break;\n"; 2653 OS << " }\n"; 2654 OS << " unsigned Diag = validateOperandClass(Operands[i+1],\n"; 2655 OS.indent(43); 2656 OS << "(MatchClassKind)it->Classes[i]);\n"; 2657 OS << " if (Diag == Match_Success)\n"; 2658 OS << " continue;\n"; 2659 OS << " // If this operand is broken for all of the instances of this\n"; 2660 OS << " // mnemonic, keep track of it so we can report loc info.\n"; 2661 OS << " // If we already had a match that only failed due to a\n"; 2662 OS << " // target predicate, that diagnostic is preferred.\n"; 2663 OS << " if (!HadMatchOtherThanPredicate &&\n"; 2664 OS << " (it == MnemonicRange.first || ErrorInfo <= i+1)) {\n"; 2665 OS << " ErrorInfo = i+1;\n"; 2666 OS << " RetCode = Diag;\n"; 2667 OS << " }\n"; 2668 OS << " // Otherwise, just reject this instance of the mnemonic.\n"; 2669 OS << " OperandsValid = false;\n"; 2670 OS << " break;\n"; 2671 OS << " }\n\n"; 2672 2673 OS << " if (!OperandsValid) continue;\n"; 2674 2675 // Emit check that the required features are available. 2676 OS << " if ((AvailableFeatures & it->RequiredFeatures) " 2677 << "!= it->RequiredFeatures) {\n"; 2678 OS << " HadMatchOtherThanFeatures = true;\n"; 2679 OS << " unsigned NewMissingFeatures = it->RequiredFeatures & " 2680 "~AvailableFeatures;\n"; 2681 OS << " if (CountPopulation_32(NewMissingFeatures) <= " 2682 "CountPopulation_32(MissingFeatures))\n"; 2683 OS << " MissingFeatures = NewMissingFeatures;\n"; 2684 OS << " continue;\n"; 2685 OS << " }\n"; 2686 OS << "\n"; 2687 OS << " // We have selected a definite instruction, convert the parsed\n" 2688 << " // operands into the appropriate MCInst.\n"; 2689 OS << " if (!ConvertToMCInst(it->ConvertFn, Inst,\n" 2690 << " it->Opcode, Operands))\n"; 2691 OS << " return Match_ConversionFail;\n"; 2692 OS << "\n"; 2693 2694 // Verify the instruction with the target-specific match predicate function. 2695 OS << " // We have a potential match. Check the target predicate to\n" 2696 << " // handle any context sensitive constraints.\n" 2697 << " unsigned MatchResult;\n" 2698 << " if ((MatchResult = checkTargetMatchPredicate(Inst)) !=" 2699 << " Match_Success) {\n" 2700 << " Inst.clear();\n" 2701 << " RetCode = MatchResult;\n" 2702 << " HadMatchOtherThanPredicate = true;\n" 2703 << " continue;\n" 2704 << " }\n\n"; 2705 2706 // Call the post-processing function, if used. 2707 std::string InsnCleanupFn = 2708 AsmParser->getValueAsString("AsmParserInstCleanup"); 2709 if (!InsnCleanupFn.empty()) 2710 OS << " " << InsnCleanupFn << "(Inst);\n"; 2711 2712 OS << " return Match_Success;\n"; 2713 OS << " }\n\n"; 2714 2715 OS << " // Okay, we had no match. Try to return a useful error code.\n"; 2716 OS << " if (HadMatchOtherThanPredicate || !HadMatchOtherThanFeatures)"; 2717 OS << " return RetCode;\n"; 2718 OS << " // Missing feature matches return which features were missing\n"; 2719 OS << " ErrorInfo = MissingFeatures;\n"; 2720 OS << " return Match_MissingFeature;\n"; 2721 OS << "}\n\n"; 2722 2723 if (Info.OperandMatchInfo.size()) 2724 emitCustomOperandParsing(OS, Target, Info, ClassName); 2725 2726 OS << "#endif // GET_MATCHER_IMPLEMENTATION\n\n"; 2727} 2728 2729namespace llvm { 2730 2731void EmitAsmMatcher(RecordKeeper &RK, raw_ostream &OS) { 2732 emitSourceFileHeader("Assembly Matcher Source Fragment", OS); 2733 AsmMatcherEmitter(RK).run(OS); 2734} 2735 2736} // End llvm namespace 2737