1 //===- MIParser.cpp - Machine instructions parser implementation ----------===// 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 file implements the parsing of machine instructions. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "MIParser.h" 15 #include "MILexer.h" 16 #include "llvm/ADT/StringMap.h" 17 #include "llvm/AsmParser/Parser.h" 18 #include "llvm/AsmParser/SlotMapping.h" 19 #include "llvm/CodeGen/MachineBasicBlock.h" 20 #include "llvm/CodeGen/MachineFrameInfo.h" 21 #include "llvm/CodeGen/MachineFunction.h" 22 #include "llvm/CodeGen/MachineInstr.h" 23 #include "llvm/CodeGen/MachineInstrBuilder.h" 24 #include "llvm/CodeGen/MachineMemOperand.h" 25 #include "llvm/CodeGen/MachineModuleInfo.h" 26 #include "llvm/CodeGen/MachineRegisterInfo.h" 27 #include "llvm/IR/Constants.h" 28 #include "llvm/IR/Instructions.h" 29 #include "llvm/IR/Module.h" 30 #include "llvm/IR/ModuleSlotTracker.h" 31 #include "llvm/IR/ValueSymbolTable.h" 32 #include "llvm/Support/SourceMgr.h" 33 #include "llvm/Support/raw_ostream.h" 34 #include "llvm/Target/TargetInstrInfo.h" 35 #include "llvm/Target/TargetSubtargetInfo.h" 36 37 using namespace llvm; 38 39 PerFunctionMIParsingState::PerFunctionMIParsingState(MachineFunction &MF, 40 SourceMgr &SM, const SlotMapping &IRSlots) 41 : MF(MF), SM(&SM), IRSlots(IRSlots) { 42 } 43 44 namespace { 45 46 /// A wrapper struct around the 'MachineOperand' struct that includes a source 47 /// range and other attributes. 48 struct ParsedMachineOperand { 49 MachineOperand Operand; 50 StringRef::iterator Begin; 51 StringRef::iterator End; 52 Optional<unsigned> TiedDefIdx; 53 54 ParsedMachineOperand(const MachineOperand &Operand, StringRef::iterator Begin, 55 StringRef::iterator End, Optional<unsigned> &TiedDefIdx) 56 : Operand(Operand), Begin(Begin), End(End), TiedDefIdx(TiedDefIdx) { 57 if (TiedDefIdx) 58 assert(Operand.isReg() && Operand.isUse() && 59 "Only used register operands can be tied"); 60 } 61 }; 62 63 class MIParser { 64 MachineFunction &MF; 65 SMDiagnostic &Error; 66 StringRef Source, CurrentSource; 67 MIToken Token; 68 const PerFunctionMIParsingState &PFS; 69 /// Maps from instruction names to op codes. 70 StringMap<unsigned> Names2InstrOpCodes; 71 /// Maps from register names to registers. 72 StringMap<unsigned> Names2Regs; 73 /// Maps from register mask names to register masks. 74 StringMap<const uint32_t *> Names2RegMasks; 75 /// Maps from subregister names to subregister indices. 76 StringMap<unsigned> Names2SubRegIndices; 77 /// Maps from slot numbers to function's unnamed basic blocks. 78 DenseMap<unsigned, const BasicBlock *> Slots2BasicBlocks; 79 /// Maps from slot numbers to function's unnamed values. 80 DenseMap<unsigned, const Value *> Slots2Values; 81 /// Maps from target index names to target indices. 82 StringMap<int> Names2TargetIndices; 83 /// Maps from direct target flag names to the direct target flag values. 84 StringMap<unsigned> Names2DirectTargetFlags; 85 /// Maps from direct target flag names to the bitmask target flag values. 86 StringMap<unsigned> Names2BitmaskTargetFlags; 87 88 public: 89 MIParser(const PerFunctionMIParsingState &PFS, SMDiagnostic &Error, 90 StringRef Source); 91 92 /// \p SkipChar gives the number of characters to skip before looking 93 /// for the next token. 94 void lex(unsigned SkipChar = 0); 95 96 /// Report an error at the current location with the given message. 97 /// 98 /// This function always return true. 99 bool error(const Twine &Msg); 100 101 /// Report an error at the given location with the given message. 102 /// 103 /// This function always return true. 104 bool error(StringRef::iterator Loc, const Twine &Msg); 105 106 bool 107 parseBasicBlockDefinitions(DenseMap<unsigned, MachineBasicBlock *> &MBBSlots); 108 bool parseBasicBlocks(); 109 bool parse(MachineInstr *&MI); 110 bool parseStandaloneMBB(MachineBasicBlock *&MBB); 111 bool parseStandaloneNamedRegister(unsigned &Reg); 112 bool parseStandaloneVirtualRegister(unsigned &Reg); 113 bool parseStandaloneStackObject(int &FI); 114 bool parseStandaloneMDNode(MDNode *&Node); 115 116 bool 117 parseBasicBlockDefinition(DenseMap<unsigned, MachineBasicBlock *> &MBBSlots); 118 bool parseBasicBlock(MachineBasicBlock &MBB); 119 bool parseBasicBlockLiveins(MachineBasicBlock &MBB); 120 bool parseBasicBlockSuccessors(MachineBasicBlock &MBB); 121 122 bool parseRegister(unsigned &Reg); 123 bool parseRegisterFlag(unsigned &Flags); 124 bool parseSubRegisterIndex(unsigned &SubReg); 125 bool parseRegisterTiedDefIndex(unsigned &TiedDefIdx); 126 bool parseSize(unsigned &Size); 127 bool parseRegisterOperand(MachineOperand &Dest, 128 Optional<unsigned> &TiedDefIdx, bool IsDef = false); 129 bool parseImmediateOperand(MachineOperand &Dest); 130 bool parseIRConstant(StringRef::iterator Loc, StringRef Source, 131 const Constant *&C); 132 bool parseIRConstant(StringRef::iterator Loc, const Constant *&C); 133 bool parseLowLevelType(StringRef::iterator Loc, LLT &Ty, 134 bool MustBeSized = true); 135 bool parseTypedImmediateOperand(MachineOperand &Dest); 136 bool parseFPImmediateOperand(MachineOperand &Dest); 137 bool parseMBBReference(MachineBasicBlock *&MBB); 138 bool parseMBBOperand(MachineOperand &Dest); 139 bool parseStackFrameIndex(int &FI); 140 bool parseStackObjectOperand(MachineOperand &Dest); 141 bool parseFixedStackFrameIndex(int &FI); 142 bool parseFixedStackObjectOperand(MachineOperand &Dest); 143 bool parseGlobalValue(GlobalValue *&GV); 144 bool parseGlobalAddressOperand(MachineOperand &Dest); 145 bool parseConstantPoolIndexOperand(MachineOperand &Dest); 146 bool parseSubRegisterIndexOperand(MachineOperand &Dest); 147 bool parseJumpTableIndexOperand(MachineOperand &Dest); 148 bool parseExternalSymbolOperand(MachineOperand &Dest); 149 bool parseMDNode(MDNode *&Node); 150 bool parseMetadataOperand(MachineOperand &Dest); 151 bool parseCFIOffset(int &Offset); 152 bool parseCFIRegister(unsigned &Reg); 153 bool parseCFIOperand(MachineOperand &Dest); 154 bool parseIRBlock(BasicBlock *&BB, const Function &F); 155 bool parseBlockAddressOperand(MachineOperand &Dest); 156 bool parseTargetIndexOperand(MachineOperand &Dest); 157 bool parseLiveoutRegisterMaskOperand(MachineOperand &Dest); 158 bool parseMachineOperand(MachineOperand &Dest, 159 Optional<unsigned> &TiedDefIdx); 160 bool parseMachineOperandAndTargetFlags(MachineOperand &Dest, 161 Optional<unsigned> &TiedDefIdx); 162 bool parseOffset(int64_t &Offset); 163 bool parseAlignment(unsigned &Alignment); 164 bool parseOperandsOffset(MachineOperand &Op); 165 bool parseIRValue(const Value *&V); 166 bool parseMemoryOperandFlag(MachineMemOperand::Flags &Flags); 167 bool parseMemoryPseudoSourceValue(const PseudoSourceValue *&PSV); 168 bool parseMachinePointerInfo(MachinePointerInfo &Dest); 169 bool parseMachineMemoryOperand(MachineMemOperand *&Dest); 170 171 private: 172 /// Convert the integer literal in the current token into an unsigned integer. 173 /// 174 /// Return true if an error occurred. 175 bool getUnsigned(unsigned &Result); 176 177 /// Convert the integer literal in the current token into an uint64. 178 /// 179 /// Return true if an error occurred. 180 bool getUint64(uint64_t &Result); 181 182 /// If the current token is of the given kind, consume it and return false. 183 /// Otherwise report an error and return true. 184 bool expectAndConsume(MIToken::TokenKind TokenKind); 185 186 /// If the current token is of the given kind, consume it and return true. 187 /// Otherwise return false. 188 bool consumeIfPresent(MIToken::TokenKind TokenKind); 189 190 void initNames2InstrOpCodes(); 191 192 /// Try to convert an instruction name to an opcode. Return true if the 193 /// instruction name is invalid. 194 bool parseInstrName(StringRef InstrName, unsigned &OpCode); 195 196 bool parseInstruction(unsigned &OpCode, unsigned &Flags); 197 198 bool assignRegisterTies(MachineInstr &MI, 199 ArrayRef<ParsedMachineOperand> Operands); 200 201 bool verifyImplicitOperands(ArrayRef<ParsedMachineOperand> Operands, 202 const MCInstrDesc &MCID); 203 204 void initNames2Regs(); 205 206 /// Try to convert a register name to a register number. Return true if the 207 /// register name is invalid. 208 bool getRegisterByName(StringRef RegName, unsigned &Reg); 209 210 void initNames2RegMasks(); 211 212 /// Check if the given identifier is a name of a register mask. 213 /// 214 /// Return null if the identifier isn't a register mask. 215 const uint32_t *getRegMask(StringRef Identifier); 216 217 void initNames2SubRegIndices(); 218 219 /// Check if the given identifier is a name of a subregister index. 220 /// 221 /// Return 0 if the name isn't a subregister index class. 222 unsigned getSubRegIndex(StringRef Name); 223 224 const BasicBlock *getIRBlock(unsigned Slot); 225 const BasicBlock *getIRBlock(unsigned Slot, const Function &F); 226 227 const Value *getIRValue(unsigned Slot); 228 229 void initNames2TargetIndices(); 230 231 /// Try to convert a name of target index to the corresponding target index. 232 /// 233 /// Return true if the name isn't a name of a target index. 234 bool getTargetIndex(StringRef Name, int &Index); 235 236 void initNames2DirectTargetFlags(); 237 238 /// Try to convert a name of a direct target flag to the corresponding 239 /// target flag. 240 /// 241 /// Return true if the name isn't a name of a direct flag. 242 bool getDirectTargetFlag(StringRef Name, unsigned &Flag); 243 244 void initNames2BitmaskTargetFlags(); 245 246 /// Try to convert a name of a bitmask target flag to the corresponding 247 /// target flag. 248 /// 249 /// Return true if the name isn't a name of a bitmask target flag. 250 bool getBitmaskTargetFlag(StringRef Name, unsigned &Flag); 251 }; 252 253 } // end anonymous namespace 254 255 MIParser::MIParser(const PerFunctionMIParsingState &PFS, SMDiagnostic &Error, 256 StringRef Source) 257 : MF(PFS.MF), Error(Error), Source(Source), CurrentSource(Source), PFS(PFS) 258 {} 259 260 void MIParser::lex(unsigned SkipChar) { 261 CurrentSource = lexMIToken( 262 CurrentSource.data() + SkipChar, Token, 263 [this](StringRef::iterator Loc, const Twine &Msg) { error(Loc, Msg); }); 264 } 265 266 bool MIParser::error(const Twine &Msg) { return error(Token.location(), Msg); } 267 268 bool MIParser::error(StringRef::iterator Loc, const Twine &Msg) { 269 const SourceMgr &SM = *PFS.SM; 270 assert(Loc >= Source.data() && Loc <= (Source.data() + Source.size())); 271 const MemoryBuffer &Buffer = *SM.getMemoryBuffer(SM.getMainFileID()); 272 if (Loc >= Buffer.getBufferStart() && Loc <= Buffer.getBufferEnd()) { 273 // Create an ordinary diagnostic when the source manager's buffer is the 274 // source string. 275 Error = SM.GetMessage(SMLoc::getFromPointer(Loc), SourceMgr::DK_Error, Msg); 276 return true; 277 } 278 // Create a diagnostic for a YAML string literal. 279 Error = SMDiagnostic(SM, SMLoc(), Buffer.getBufferIdentifier(), 1, 280 Loc - Source.data(), SourceMgr::DK_Error, Msg.str(), 281 Source, None, None); 282 return true; 283 } 284 285 static const char *toString(MIToken::TokenKind TokenKind) { 286 switch (TokenKind) { 287 case MIToken::comma: 288 return "','"; 289 case MIToken::equal: 290 return "'='"; 291 case MIToken::colon: 292 return "':'"; 293 case MIToken::lparen: 294 return "'('"; 295 case MIToken::rparen: 296 return "')'"; 297 default: 298 return "<unknown token>"; 299 } 300 } 301 302 bool MIParser::expectAndConsume(MIToken::TokenKind TokenKind) { 303 if (Token.isNot(TokenKind)) 304 return error(Twine("expected ") + toString(TokenKind)); 305 lex(); 306 return false; 307 } 308 309 bool MIParser::consumeIfPresent(MIToken::TokenKind TokenKind) { 310 if (Token.isNot(TokenKind)) 311 return false; 312 lex(); 313 return true; 314 } 315 316 bool MIParser::parseBasicBlockDefinition( 317 DenseMap<unsigned, MachineBasicBlock *> &MBBSlots) { 318 assert(Token.is(MIToken::MachineBasicBlockLabel)); 319 unsigned ID = 0; 320 if (getUnsigned(ID)) 321 return true; 322 auto Loc = Token.location(); 323 auto Name = Token.stringValue(); 324 lex(); 325 bool HasAddressTaken = false; 326 bool IsLandingPad = false; 327 unsigned Alignment = 0; 328 BasicBlock *BB = nullptr; 329 if (consumeIfPresent(MIToken::lparen)) { 330 do { 331 // TODO: Report an error when multiple same attributes are specified. 332 switch (Token.kind()) { 333 case MIToken::kw_address_taken: 334 HasAddressTaken = true; 335 lex(); 336 break; 337 case MIToken::kw_landing_pad: 338 IsLandingPad = true; 339 lex(); 340 break; 341 case MIToken::kw_align: 342 if (parseAlignment(Alignment)) 343 return true; 344 break; 345 case MIToken::IRBlock: 346 // TODO: Report an error when both name and ir block are specified. 347 if (parseIRBlock(BB, *MF.getFunction())) 348 return true; 349 lex(); 350 break; 351 default: 352 break; 353 } 354 } while (consumeIfPresent(MIToken::comma)); 355 if (expectAndConsume(MIToken::rparen)) 356 return true; 357 } 358 if (expectAndConsume(MIToken::colon)) 359 return true; 360 361 if (!Name.empty()) { 362 BB = dyn_cast_or_null<BasicBlock>( 363 MF.getFunction()->getValueSymbolTable().lookup(Name)); 364 if (!BB) 365 return error(Loc, Twine("basic block '") + Name + 366 "' is not defined in the function '" + 367 MF.getName() + "'"); 368 } 369 auto *MBB = MF.CreateMachineBasicBlock(BB); 370 MF.insert(MF.end(), MBB); 371 bool WasInserted = MBBSlots.insert(std::make_pair(ID, MBB)).second; 372 if (!WasInserted) 373 return error(Loc, Twine("redefinition of machine basic block with id #") + 374 Twine(ID)); 375 if (Alignment) 376 MBB->setAlignment(Alignment); 377 if (HasAddressTaken) 378 MBB->setHasAddressTaken(); 379 MBB->setIsEHPad(IsLandingPad); 380 return false; 381 } 382 383 bool MIParser::parseBasicBlockDefinitions( 384 DenseMap<unsigned, MachineBasicBlock *> &MBBSlots) { 385 lex(); 386 // Skip until the first machine basic block. 387 while (Token.is(MIToken::Newline)) 388 lex(); 389 if (Token.isErrorOrEOF()) 390 return Token.isError(); 391 if (Token.isNot(MIToken::MachineBasicBlockLabel)) 392 return error("expected a basic block definition before instructions"); 393 unsigned BraceDepth = 0; 394 do { 395 if (parseBasicBlockDefinition(MBBSlots)) 396 return true; 397 bool IsAfterNewline = false; 398 // Skip until the next machine basic block. 399 while (true) { 400 if ((Token.is(MIToken::MachineBasicBlockLabel) && IsAfterNewline) || 401 Token.isErrorOrEOF()) 402 break; 403 else if (Token.is(MIToken::MachineBasicBlockLabel)) 404 return error("basic block definition should be located at the start of " 405 "the line"); 406 else if (consumeIfPresent(MIToken::Newline)) { 407 IsAfterNewline = true; 408 continue; 409 } 410 IsAfterNewline = false; 411 if (Token.is(MIToken::lbrace)) 412 ++BraceDepth; 413 if (Token.is(MIToken::rbrace)) { 414 if (!BraceDepth) 415 return error("extraneous closing brace ('}')"); 416 --BraceDepth; 417 } 418 lex(); 419 } 420 // Verify that we closed all of the '{' at the end of a file or a block. 421 if (!Token.isError() && BraceDepth) 422 return error("expected '}'"); // FIXME: Report a note that shows '{'. 423 } while (!Token.isErrorOrEOF()); 424 return Token.isError(); 425 } 426 427 bool MIParser::parseBasicBlockLiveins(MachineBasicBlock &MBB) { 428 assert(Token.is(MIToken::kw_liveins)); 429 lex(); 430 if (expectAndConsume(MIToken::colon)) 431 return true; 432 if (Token.isNewlineOrEOF()) // Allow an empty list of liveins. 433 return false; 434 do { 435 if (Token.isNot(MIToken::NamedRegister)) 436 return error("expected a named register"); 437 unsigned Reg = 0; 438 if (parseRegister(Reg)) 439 return true; 440 MBB.addLiveIn(Reg); 441 lex(); 442 } while (consumeIfPresent(MIToken::comma)); 443 return false; 444 } 445 446 bool MIParser::parseBasicBlockSuccessors(MachineBasicBlock &MBB) { 447 assert(Token.is(MIToken::kw_successors)); 448 lex(); 449 if (expectAndConsume(MIToken::colon)) 450 return true; 451 if (Token.isNewlineOrEOF()) // Allow an empty list of successors. 452 return false; 453 do { 454 if (Token.isNot(MIToken::MachineBasicBlock)) 455 return error("expected a machine basic block reference"); 456 MachineBasicBlock *SuccMBB = nullptr; 457 if (parseMBBReference(SuccMBB)) 458 return true; 459 lex(); 460 unsigned Weight = 0; 461 if (consumeIfPresent(MIToken::lparen)) { 462 if (Token.isNot(MIToken::IntegerLiteral)) 463 return error("expected an integer literal after '('"); 464 if (getUnsigned(Weight)) 465 return true; 466 lex(); 467 if (expectAndConsume(MIToken::rparen)) 468 return true; 469 } 470 MBB.addSuccessor(SuccMBB, BranchProbability::getRaw(Weight)); 471 } while (consumeIfPresent(MIToken::comma)); 472 MBB.normalizeSuccProbs(); 473 return false; 474 } 475 476 bool MIParser::parseBasicBlock(MachineBasicBlock &MBB) { 477 // Skip the definition. 478 assert(Token.is(MIToken::MachineBasicBlockLabel)); 479 lex(); 480 if (consumeIfPresent(MIToken::lparen)) { 481 while (Token.isNot(MIToken::rparen) && !Token.isErrorOrEOF()) 482 lex(); 483 consumeIfPresent(MIToken::rparen); 484 } 485 consumeIfPresent(MIToken::colon); 486 487 // Parse the liveins and successors. 488 // N.B: Multiple lists of successors and liveins are allowed and they're 489 // merged into one. 490 // Example: 491 // liveins: %edi 492 // liveins: %esi 493 // 494 // is equivalent to 495 // liveins: %edi, %esi 496 while (true) { 497 if (Token.is(MIToken::kw_successors)) { 498 if (parseBasicBlockSuccessors(MBB)) 499 return true; 500 } else if (Token.is(MIToken::kw_liveins)) { 501 if (parseBasicBlockLiveins(MBB)) 502 return true; 503 } else if (consumeIfPresent(MIToken::Newline)) { 504 continue; 505 } else 506 break; 507 if (!Token.isNewlineOrEOF()) 508 return error("expected line break at the end of a list"); 509 lex(); 510 } 511 512 // Parse the instructions. 513 bool IsInBundle = false; 514 MachineInstr *PrevMI = nullptr; 515 while (true) { 516 if (Token.is(MIToken::MachineBasicBlockLabel) || Token.is(MIToken::Eof)) 517 return false; 518 else if (consumeIfPresent(MIToken::Newline)) 519 continue; 520 if (consumeIfPresent(MIToken::rbrace)) { 521 // The first parsing pass should verify that all closing '}' have an 522 // opening '{'. 523 assert(IsInBundle); 524 IsInBundle = false; 525 continue; 526 } 527 MachineInstr *MI = nullptr; 528 if (parse(MI)) 529 return true; 530 MBB.insert(MBB.end(), MI); 531 if (IsInBundle) { 532 PrevMI->setFlag(MachineInstr::BundledSucc); 533 MI->setFlag(MachineInstr::BundledPred); 534 } 535 PrevMI = MI; 536 if (Token.is(MIToken::lbrace)) { 537 if (IsInBundle) 538 return error("nested instruction bundles are not allowed"); 539 lex(); 540 // This instruction is the start of the bundle. 541 MI->setFlag(MachineInstr::BundledSucc); 542 IsInBundle = true; 543 if (!Token.is(MIToken::Newline)) 544 // The next instruction can be on the same line. 545 continue; 546 } 547 assert(Token.isNewlineOrEOF() && "MI is not fully parsed"); 548 lex(); 549 } 550 return false; 551 } 552 553 bool MIParser::parseBasicBlocks() { 554 lex(); 555 // Skip until the first machine basic block. 556 while (Token.is(MIToken::Newline)) 557 lex(); 558 if (Token.isErrorOrEOF()) 559 return Token.isError(); 560 // The first parsing pass should have verified that this token is a MBB label 561 // in the 'parseBasicBlockDefinitions' method. 562 assert(Token.is(MIToken::MachineBasicBlockLabel)); 563 do { 564 MachineBasicBlock *MBB = nullptr; 565 if (parseMBBReference(MBB)) 566 return true; 567 if (parseBasicBlock(*MBB)) 568 return true; 569 // The method 'parseBasicBlock' should parse the whole block until the next 570 // block or the end of file. 571 assert(Token.is(MIToken::MachineBasicBlockLabel) || Token.is(MIToken::Eof)); 572 } while (Token.isNot(MIToken::Eof)); 573 return false; 574 } 575 576 bool MIParser::parse(MachineInstr *&MI) { 577 // Parse any register operands before '=' 578 MachineOperand MO = MachineOperand::CreateImm(0); 579 SmallVector<ParsedMachineOperand, 8> Operands; 580 while (Token.isRegister() || Token.isRegisterFlag()) { 581 auto Loc = Token.location(); 582 Optional<unsigned> TiedDefIdx; 583 if (parseRegisterOperand(MO, TiedDefIdx, /*IsDef=*/true)) 584 return true; 585 Operands.push_back( 586 ParsedMachineOperand(MO, Loc, Token.location(), TiedDefIdx)); 587 if (Token.isNot(MIToken::comma)) 588 break; 589 lex(); 590 } 591 if (!Operands.empty() && expectAndConsume(MIToken::equal)) 592 return true; 593 594 unsigned OpCode, Flags = 0; 595 if (Token.isError() || parseInstruction(OpCode, Flags)) 596 return true; 597 598 SmallVector<LLT, 1> Tys; 599 if (isPreISelGenericOpcode(OpCode)) { 600 // For generic opcode, at least one type is mandatory. 601 auto Loc = Token.location(); 602 bool ManyTypes = Token.is(MIToken::lbrace); 603 if (ManyTypes) 604 lex(); 605 606 // Now actually parse the type(s). 607 do { 608 Tys.resize(Tys.size() + 1); 609 if (parseLowLevelType(Loc, Tys[Tys.size() - 1])) 610 return true; 611 } while (ManyTypes && consumeIfPresent(MIToken::comma)); 612 613 if (ManyTypes) 614 expectAndConsume(MIToken::rbrace); 615 } 616 617 // Parse the remaining machine operands. 618 while (!Token.isNewlineOrEOF() && Token.isNot(MIToken::kw_debug_location) && 619 Token.isNot(MIToken::coloncolon) && Token.isNot(MIToken::lbrace)) { 620 auto Loc = Token.location(); 621 Optional<unsigned> TiedDefIdx; 622 if (parseMachineOperandAndTargetFlags(MO, TiedDefIdx)) 623 return true; 624 Operands.push_back( 625 ParsedMachineOperand(MO, Loc, Token.location(), TiedDefIdx)); 626 if (Token.isNewlineOrEOF() || Token.is(MIToken::coloncolon) || 627 Token.is(MIToken::lbrace)) 628 break; 629 if (Token.isNot(MIToken::comma)) 630 return error("expected ',' before the next machine operand"); 631 lex(); 632 } 633 634 DebugLoc DebugLocation; 635 if (Token.is(MIToken::kw_debug_location)) { 636 lex(); 637 if (Token.isNot(MIToken::exclaim)) 638 return error("expected a metadata node after 'debug-location'"); 639 MDNode *Node = nullptr; 640 if (parseMDNode(Node)) 641 return true; 642 DebugLocation = DebugLoc(Node); 643 } 644 645 // Parse the machine memory operands. 646 SmallVector<MachineMemOperand *, 2> MemOperands; 647 if (Token.is(MIToken::coloncolon)) { 648 lex(); 649 while (!Token.isNewlineOrEOF()) { 650 MachineMemOperand *MemOp = nullptr; 651 if (parseMachineMemoryOperand(MemOp)) 652 return true; 653 MemOperands.push_back(MemOp); 654 if (Token.isNewlineOrEOF()) 655 break; 656 if (Token.isNot(MIToken::comma)) 657 return error("expected ',' before the next machine memory operand"); 658 lex(); 659 } 660 } 661 662 const auto &MCID = MF.getSubtarget().getInstrInfo()->get(OpCode); 663 if (!MCID.isVariadic()) { 664 // FIXME: Move the implicit operand verification to the machine verifier. 665 if (verifyImplicitOperands(Operands, MCID)) 666 return true; 667 } 668 669 // TODO: Check for extraneous machine operands. 670 MI = MF.CreateMachineInstr(MCID, DebugLocation, /*NoImplicit=*/true); 671 MI->setFlags(Flags); 672 if (Tys.size() > 0) { 673 for (unsigned i = 0; i < Tys.size(); ++i) 674 MI->setType(Tys[i], i); 675 } 676 for (const auto &Operand : Operands) 677 MI->addOperand(MF, Operand.Operand); 678 if (assignRegisterTies(*MI, Operands)) 679 return true; 680 if (MemOperands.empty()) 681 return false; 682 MachineInstr::mmo_iterator MemRefs = 683 MF.allocateMemRefsArray(MemOperands.size()); 684 std::copy(MemOperands.begin(), MemOperands.end(), MemRefs); 685 MI->setMemRefs(MemRefs, MemRefs + MemOperands.size()); 686 return false; 687 } 688 689 bool MIParser::parseStandaloneMBB(MachineBasicBlock *&MBB) { 690 lex(); 691 if (Token.isNot(MIToken::MachineBasicBlock)) 692 return error("expected a machine basic block reference"); 693 if (parseMBBReference(MBB)) 694 return true; 695 lex(); 696 if (Token.isNot(MIToken::Eof)) 697 return error( 698 "expected end of string after the machine basic block reference"); 699 return false; 700 } 701 702 bool MIParser::parseStandaloneNamedRegister(unsigned &Reg) { 703 lex(); 704 if (Token.isNot(MIToken::NamedRegister)) 705 return error("expected a named register"); 706 if (parseRegister(Reg)) 707 return true; 708 lex(); 709 if (Token.isNot(MIToken::Eof)) 710 return error("expected end of string after the register reference"); 711 return false; 712 } 713 714 bool MIParser::parseStandaloneVirtualRegister(unsigned &Reg) { 715 lex(); 716 if (Token.isNot(MIToken::VirtualRegister)) 717 return error("expected a virtual register"); 718 if (parseRegister(Reg)) 719 return true; 720 lex(); 721 if (Token.isNot(MIToken::Eof)) 722 return error("expected end of string after the register reference"); 723 return false; 724 } 725 726 bool MIParser::parseStandaloneStackObject(int &FI) { 727 lex(); 728 if (Token.isNot(MIToken::StackObject)) 729 return error("expected a stack object"); 730 if (parseStackFrameIndex(FI)) 731 return true; 732 if (Token.isNot(MIToken::Eof)) 733 return error("expected end of string after the stack object reference"); 734 return false; 735 } 736 737 bool MIParser::parseStandaloneMDNode(MDNode *&Node) { 738 lex(); 739 if (Token.isNot(MIToken::exclaim)) 740 return error("expected a metadata node"); 741 if (parseMDNode(Node)) 742 return true; 743 if (Token.isNot(MIToken::Eof)) 744 return error("expected end of string after the metadata node"); 745 return false; 746 } 747 748 static const char *printImplicitRegisterFlag(const MachineOperand &MO) { 749 assert(MO.isImplicit()); 750 return MO.isDef() ? "implicit-def" : "implicit"; 751 } 752 753 static std::string getRegisterName(const TargetRegisterInfo *TRI, 754 unsigned Reg) { 755 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "expected phys reg"); 756 return StringRef(TRI->getName(Reg)).lower(); 757 } 758 759 /// Return true if the parsed machine operands contain a given machine operand. 760 static bool isImplicitOperandIn(const MachineOperand &ImplicitOperand, 761 ArrayRef<ParsedMachineOperand> Operands) { 762 for (const auto &I : Operands) { 763 if (ImplicitOperand.isIdenticalTo(I.Operand)) 764 return true; 765 } 766 return false; 767 } 768 769 bool MIParser::verifyImplicitOperands(ArrayRef<ParsedMachineOperand> Operands, 770 const MCInstrDesc &MCID) { 771 if (MCID.isCall()) 772 // We can't verify call instructions as they can contain arbitrary implicit 773 // register and register mask operands. 774 return false; 775 776 // Gather all the expected implicit operands. 777 SmallVector<MachineOperand, 4> ImplicitOperands; 778 if (MCID.ImplicitDefs) 779 for (const MCPhysReg *ImpDefs = MCID.getImplicitDefs(); *ImpDefs; ++ImpDefs) 780 ImplicitOperands.push_back( 781 MachineOperand::CreateReg(*ImpDefs, true, true)); 782 if (MCID.ImplicitUses) 783 for (const MCPhysReg *ImpUses = MCID.getImplicitUses(); *ImpUses; ++ImpUses) 784 ImplicitOperands.push_back( 785 MachineOperand::CreateReg(*ImpUses, false, true)); 786 787 const auto *TRI = MF.getSubtarget().getRegisterInfo(); 788 assert(TRI && "Expected target register info"); 789 for (const auto &I : ImplicitOperands) { 790 if (isImplicitOperandIn(I, Operands)) 791 continue; 792 return error(Operands.empty() ? Token.location() : Operands.back().End, 793 Twine("missing implicit register operand '") + 794 printImplicitRegisterFlag(I) + " %" + 795 getRegisterName(TRI, I.getReg()) + "'"); 796 } 797 return false; 798 } 799 800 bool MIParser::parseInstruction(unsigned &OpCode, unsigned &Flags) { 801 if (Token.is(MIToken::kw_frame_setup)) { 802 Flags |= MachineInstr::FrameSetup; 803 lex(); 804 } 805 if (Token.isNot(MIToken::Identifier)) 806 return error("expected a machine instruction"); 807 StringRef InstrName = Token.stringValue(); 808 if (parseInstrName(InstrName, OpCode)) 809 return error(Twine("unknown machine instruction name '") + InstrName + "'"); 810 lex(); 811 return false; 812 } 813 814 bool MIParser::parseRegister(unsigned &Reg) { 815 switch (Token.kind()) { 816 case MIToken::underscore: 817 Reg = 0; 818 break; 819 case MIToken::NamedRegister: { 820 StringRef Name = Token.stringValue(); 821 if (getRegisterByName(Name, Reg)) 822 return error(Twine("unknown register name '") + Name + "'"); 823 break; 824 } 825 case MIToken::VirtualRegister: { 826 unsigned ID; 827 if (getUnsigned(ID)) 828 return true; 829 const auto RegInfo = PFS.VirtualRegisterSlots.find(ID); 830 if (RegInfo == PFS.VirtualRegisterSlots.end()) 831 return error(Twine("use of undefined virtual register '%") + Twine(ID) + 832 "'"); 833 Reg = RegInfo->second; 834 break; 835 } 836 // TODO: Parse other register kinds. 837 default: 838 llvm_unreachable("The current token should be a register"); 839 } 840 return false; 841 } 842 843 bool MIParser::parseRegisterFlag(unsigned &Flags) { 844 const unsigned OldFlags = Flags; 845 switch (Token.kind()) { 846 case MIToken::kw_implicit: 847 Flags |= RegState::Implicit; 848 break; 849 case MIToken::kw_implicit_define: 850 Flags |= RegState::ImplicitDefine; 851 break; 852 case MIToken::kw_def: 853 Flags |= RegState::Define; 854 break; 855 case MIToken::kw_dead: 856 Flags |= RegState::Dead; 857 break; 858 case MIToken::kw_killed: 859 Flags |= RegState::Kill; 860 break; 861 case MIToken::kw_undef: 862 Flags |= RegState::Undef; 863 break; 864 case MIToken::kw_internal: 865 Flags |= RegState::InternalRead; 866 break; 867 case MIToken::kw_early_clobber: 868 Flags |= RegState::EarlyClobber; 869 break; 870 case MIToken::kw_debug_use: 871 Flags |= RegState::Debug; 872 break; 873 default: 874 llvm_unreachable("The current token should be a register flag"); 875 } 876 if (OldFlags == Flags) 877 // We know that the same flag is specified more than once when the flags 878 // weren't modified. 879 return error("duplicate '" + Token.stringValue() + "' register flag"); 880 lex(); 881 return false; 882 } 883 884 bool MIParser::parseSubRegisterIndex(unsigned &SubReg) { 885 assert(Token.is(MIToken::dot)); 886 lex(); 887 if (Token.isNot(MIToken::Identifier)) 888 return error("expected a subregister index after '.'"); 889 auto Name = Token.stringValue(); 890 SubReg = getSubRegIndex(Name); 891 if (!SubReg) 892 return error(Twine("use of unknown subregister index '") + Name + "'"); 893 lex(); 894 return false; 895 } 896 897 bool MIParser::parseRegisterTiedDefIndex(unsigned &TiedDefIdx) { 898 if (!consumeIfPresent(MIToken::kw_tied_def)) 899 return error("expected 'tied-def' after '('"); 900 if (Token.isNot(MIToken::IntegerLiteral)) 901 return error("expected an integer literal after 'tied-def'"); 902 if (getUnsigned(TiedDefIdx)) 903 return true; 904 lex(); 905 if (expectAndConsume(MIToken::rparen)) 906 return true; 907 return false; 908 } 909 910 bool MIParser::parseSize(unsigned &Size) { 911 if (Token.isNot(MIToken::IntegerLiteral)) 912 return error("expected an integer literal for the size"); 913 if (getUnsigned(Size)) 914 return true; 915 lex(); 916 if (expectAndConsume(MIToken::rparen)) 917 return true; 918 return false; 919 } 920 921 bool MIParser::assignRegisterTies(MachineInstr &MI, 922 ArrayRef<ParsedMachineOperand> Operands) { 923 SmallVector<std::pair<unsigned, unsigned>, 4> TiedRegisterPairs; 924 for (unsigned I = 0, E = Operands.size(); I != E; ++I) { 925 if (!Operands[I].TiedDefIdx) 926 continue; 927 // The parser ensures that this operand is a register use, so we just have 928 // to check the tied-def operand. 929 unsigned DefIdx = Operands[I].TiedDefIdx.getValue(); 930 if (DefIdx >= E) 931 return error(Operands[I].Begin, 932 Twine("use of invalid tied-def operand index '" + 933 Twine(DefIdx) + "'; instruction has only ") + 934 Twine(E) + " operands"); 935 const auto &DefOperand = Operands[DefIdx].Operand; 936 if (!DefOperand.isReg() || !DefOperand.isDef()) 937 // FIXME: add note with the def operand. 938 return error(Operands[I].Begin, 939 Twine("use of invalid tied-def operand index '") + 940 Twine(DefIdx) + "'; the operand #" + Twine(DefIdx) + 941 " isn't a defined register"); 942 // Check that the tied-def operand wasn't tied elsewhere. 943 for (const auto &TiedPair : TiedRegisterPairs) { 944 if (TiedPair.first == DefIdx) 945 return error(Operands[I].Begin, 946 Twine("the tied-def operand #") + Twine(DefIdx) + 947 " is already tied with another register operand"); 948 } 949 TiedRegisterPairs.push_back(std::make_pair(DefIdx, I)); 950 } 951 // FIXME: Verify that for non INLINEASM instructions, the def and use tied 952 // indices must be less than tied max. 953 for (const auto &TiedPair : TiedRegisterPairs) 954 MI.tieOperands(TiedPair.first, TiedPair.second); 955 return false; 956 } 957 958 bool MIParser::parseRegisterOperand(MachineOperand &Dest, 959 Optional<unsigned> &TiedDefIdx, 960 bool IsDef) { 961 unsigned Reg; 962 unsigned Flags = IsDef ? RegState::Define : 0; 963 while (Token.isRegisterFlag()) { 964 if (parseRegisterFlag(Flags)) 965 return true; 966 } 967 if (!Token.isRegister()) 968 return error("expected a register after register flags"); 969 if (parseRegister(Reg)) 970 return true; 971 lex(); 972 unsigned SubReg = 0; 973 if (Token.is(MIToken::dot)) { 974 if (parseSubRegisterIndex(SubReg)) 975 return true; 976 if (!TargetRegisterInfo::isVirtualRegister(Reg)) 977 return error("subregister index expects a virtual register"); 978 } 979 if ((Flags & RegState::Define) == 0) { 980 if (consumeIfPresent(MIToken::lparen)) { 981 unsigned Idx; 982 if (parseRegisterTiedDefIndex(Idx)) 983 return true; 984 TiedDefIdx = Idx; 985 } 986 } else if (consumeIfPresent(MIToken::lparen)) { 987 MachineRegisterInfo &MRI = MF.getRegInfo(); 988 989 // Virtual registers may have a size with GlobalISel. 990 if (!TargetRegisterInfo::isVirtualRegister(Reg)) 991 return error("unexpected size on physical register"); 992 if (MRI.getRegClassOrRegBank(Reg).is<const TargetRegisterClass *>()) 993 return error("unexpected size on non-generic virtual register"); 994 995 unsigned Size; 996 if (parseSize(Size)) 997 return true; 998 999 MRI.setSize(Reg, Size); 1000 } else if (PFS.GenericVRegs.count(Reg)) { 1001 // Generic virtual registers must have a size. 1002 // If we end up here this means the size hasn't been specified and 1003 // this is bad! 1004 return error("generic virtual registers must have a size"); 1005 } 1006 Dest = MachineOperand::CreateReg( 1007 Reg, Flags & RegState::Define, Flags & RegState::Implicit, 1008 Flags & RegState::Kill, Flags & RegState::Dead, Flags & RegState::Undef, 1009 Flags & RegState::EarlyClobber, SubReg, Flags & RegState::Debug, 1010 Flags & RegState::InternalRead); 1011 return false; 1012 } 1013 1014 bool MIParser::parseImmediateOperand(MachineOperand &Dest) { 1015 assert(Token.is(MIToken::IntegerLiteral)); 1016 const APSInt &Int = Token.integerValue(); 1017 if (Int.getMinSignedBits() > 64) 1018 return error("integer literal is too large to be an immediate operand"); 1019 Dest = MachineOperand::CreateImm(Int.getExtValue()); 1020 lex(); 1021 return false; 1022 } 1023 1024 bool MIParser::parseIRConstant(StringRef::iterator Loc, StringRef StringValue, 1025 const Constant *&C) { 1026 auto Source = StringValue.str(); // The source has to be null terminated. 1027 SMDiagnostic Err; 1028 C = parseConstantValue(Source.c_str(), Err, *MF.getFunction()->getParent(), 1029 &PFS.IRSlots); 1030 if (!C) 1031 return error(Loc + Err.getColumnNo(), Err.getMessage()); 1032 return false; 1033 } 1034 1035 bool MIParser::parseIRConstant(StringRef::iterator Loc, const Constant *&C) { 1036 if (parseIRConstant(Loc, StringRef(Loc, Token.range().end() - Loc), C)) 1037 return true; 1038 lex(); 1039 return false; 1040 } 1041 1042 bool MIParser::parseLowLevelType(StringRef::iterator Loc, LLT &Ty, 1043 bool MustBeSized) { 1044 if (Token.is(MIToken::Identifier) && Token.stringValue() == "unsized") { 1045 if (MustBeSized) 1046 return error(Loc, "expected pN, sN or <N x sM> for sized GlobalISel type"); 1047 lex(); 1048 Ty = LLT::unsized(); 1049 return false; 1050 } else if (Token.is(MIToken::ScalarType)) { 1051 Ty = LLT::scalar(APSInt(Token.range().drop_front()).getZExtValue()); 1052 lex(); 1053 return false; 1054 } else if (Token.is(MIToken::PointerType)) { 1055 Ty = LLT::pointer(APSInt(Token.range().drop_front()).getZExtValue()); 1056 lex(); 1057 return false; 1058 } 1059 1060 // Now we're looking for a vector. 1061 if (Token.isNot(MIToken::less)) 1062 return error(Loc, 1063 "expected unsized, pN, sN or <N x sM> for GlobalISel type"); 1064 1065 lex(); 1066 1067 if (Token.isNot(MIToken::IntegerLiteral)) 1068 return error(Loc, "expected <N x sM> for vctor type"); 1069 uint64_t NumElements = Token.integerValue().getZExtValue(); 1070 lex(); 1071 1072 if (Token.isNot(MIToken::Identifier) || Token.stringValue() != "x") 1073 return error(Loc, "expected '<N x sM>' for vector type"); 1074 lex(); 1075 1076 if (Token.isNot(MIToken::ScalarType)) 1077 return error(Loc, "expected '<N x sM>' for vector type"); 1078 uint64_t ScalarSize = APSInt(Token.range().drop_front()).getZExtValue(); 1079 lex(); 1080 1081 if (Token.isNot(MIToken::greater)) 1082 return error(Loc, "expected '<N x sM>' for vector type"); 1083 lex(); 1084 1085 Ty = LLT::vector(NumElements, ScalarSize); 1086 return false; 1087 } 1088 1089 bool MIParser::parseTypedImmediateOperand(MachineOperand &Dest) { 1090 assert(Token.is(MIToken::IntegerType)); 1091 auto Loc = Token.location(); 1092 lex(); 1093 if (Token.isNot(MIToken::IntegerLiteral)) 1094 return error("expected an integer literal"); 1095 const Constant *C = nullptr; 1096 if (parseIRConstant(Loc, C)) 1097 return true; 1098 Dest = MachineOperand::CreateCImm(cast<ConstantInt>(C)); 1099 return false; 1100 } 1101 1102 bool MIParser::parseFPImmediateOperand(MachineOperand &Dest) { 1103 auto Loc = Token.location(); 1104 lex(); 1105 if (Token.isNot(MIToken::FloatingPointLiteral)) 1106 return error("expected a floating point literal"); 1107 const Constant *C = nullptr; 1108 if (parseIRConstant(Loc, C)) 1109 return true; 1110 Dest = MachineOperand::CreateFPImm(cast<ConstantFP>(C)); 1111 return false; 1112 } 1113 1114 bool MIParser::getUnsigned(unsigned &Result) { 1115 assert(Token.hasIntegerValue() && "Expected a token with an integer value"); 1116 const uint64_t Limit = uint64_t(std::numeric_limits<unsigned>::max()) + 1; 1117 uint64_t Val64 = Token.integerValue().getLimitedValue(Limit); 1118 if (Val64 == Limit) 1119 return error("expected 32-bit integer (too large)"); 1120 Result = Val64; 1121 return false; 1122 } 1123 1124 bool MIParser::parseMBBReference(MachineBasicBlock *&MBB) { 1125 assert(Token.is(MIToken::MachineBasicBlock) || 1126 Token.is(MIToken::MachineBasicBlockLabel)); 1127 unsigned Number; 1128 if (getUnsigned(Number)) 1129 return true; 1130 auto MBBInfo = PFS.MBBSlots.find(Number); 1131 if (MBBInfo == PFS.MBBSlots.end()) 1132 return error(Twine("use of undefined machine basic block #") + 1133 Twine(Number)); 1134 MBB = MBBInfo->second; 1135 if (!Token.stringValue().empty() && Token.stringValue() != MBB->getName()) 1136 return error(Twine("the name of machine basic block #") + Twine(Number) + 1137 " isn't '" + Token.stringValue() + "'"); 1138 return false; 1139 } 1140 1141 bool MIParser::parseMBBOperand(MachineOperand &Dest) { 1142 MachineBasicBlock *MBB; 1143 if (parseMBBReference(MBB)) 1144 return true; 1145 Dest = MachineOperand::CreateMBB(MBB); 1146 lex(); 1147 return false; 1148 } 1149 1150 bool MIParser::parseStackFrameIndex(int &FI) { 1151 assert(Token.is(MIToken::StackObject)); 1152 unsigned ID; 1153 if (getUnsigned(ID)) 1154 return true; 1155 auto ObjectInfo = PFS.StackObjectSlots.find(ID); 1156 if (ObjectInfo == PFS.StackObjectSlots.end()) 1157 return error(Twine("use of undefined stack object '%stack.") + Twine(ID) + 1158 "'"); 1159 StringRef Name; 1160 if (const auto *Alloca = 1161 MF.getFrameInfo()->getObjectAllocation(ObjectInfo->second)) 1162 Name = Alloca->getName(); 1163 if (!Token.stringValue().empty() && Token.stringValue() != Name) 1164 return error(Twine("the name of the stack object '%stack.") + Twine(ID) + 1165 "' isn't '" + Token.stringValue() + "'"); 1166 lex(); 1167 FI = ObjectInfo->second; 1168 return false; 1169 } 1170 1171 bool MIParser::parseStackObjectOperand(MachineOperand &Dest) { 1172 int FI; 1173 if (parseStackFrameIndex(FI)) 1174 return true; 1175 Dest = MachineOperand::CreateFI(FI); 1176 return false; 1177 } 1178 1179 bool MIParser::parseFixedStackFrameIndex(int &FI) { 1180 assert(Token.is(MIToken::FixedStackObject)); 1181 unsigned ID; 1182 if (getUnsigned(ID)) 1183 return true; 1184 auto ObjectInfo = PFS.FixedStackObjectSlots.find(ID); 1185 if (ObjectInfo == PFS.FixedStackObjectSlots.end()) 1186 return error(Twine("use of undefined fixed stack object '%fixed-stack.") + 1187 Twine(ID) + "'"); 1188 lex(); 1189 FI = ObjectInfo->second; 1190 return false; 1191 } 1192 1193 bool MIParser::parseFixedStackObjectOperand(MachineOperand &Dest) { 1194 int FI; 1195 if (parseFixedStackFrameIndex(FI)) 1196 return true; 1197 Dest = MachineOperand::CreateFI(FI); 1198 return false; 1199 } 1200 1201 bool MIParser::parseGlobalValue(GlobalValue *&GV) { 1202 switch (Token.kind()) { 1203 case MIToken::NamedGlobalValue: { 1204 const Module *M = MF.getFunction()->getParent(); 1205 GV = M->getNamedValue(Token.stringValue()); 1206 if (!GV) 1207 return error(Twine("use of undefined global value '") + Token.range() + 1208 "'"); 1209 break; 1210 } 1211 case MIToken::GlobalValue: { 1212 unsigned GVIdx; 1213 if (getUnsigned(GVIdx)) 1214 return true; 1215 if (GVIdx >= PFS.IRSlots.GlobalValues.size()) 1216 return error(Twine("use of undefined global value '@") + Twine(GVIdx) + 1217 "'"); 1218 GV = PFS.IRSlots.GlobalValues[GVIdx]; 1219 break; 1220 } 1221 default: 1222 llvm_unreachable("The current token should be a global value"); 1223 } 1224 return false; 1225 } 1226 1227 bool MIParser::parseGlobalAddressOperand(MachineOperand &Dest) { 1228 GlobalValue *GV = nullptr; 1229 if (parseGlobalValue(GV)) 1230 return true; 1231 lex(); 1232 Dest = MachineOperand::CreateGA(GV, /*Offset=*/0); 1233 if (parseOperandsOffset(Dest)) 1234 return true; 1235 return false; 1236 } 1237 1238 bool MIParser::parseConstantPoolIndexOperand(MachineOperand &Dest) { 1239 assert(Token.is(MIToken::ConstantPoolItem)); 1240 unsigned ID; 1241 if (getUnsigned(ID)) 1242 return true; 1243 auto ConstantInfo = PFS.ConstantPoolSlots.find(ID); 1244 if (ConstantInfo == PFS.ConstantPoolSlots.end()) 1245 return error("use of undefined constant '%const." + Twine(ID) + "'"); 1246 lex(); 1247 Dest = MachineOperand::CreateCPI(ID, /*Offset=*/0); 1248 if (parseOperandsOffset(Dest)) 1249 return true; 1250 return false; 1251 } 1252 1253 bool MIParser::parseJumpTableIndexOperand(MachineOperand &Dest) { 1254 assert(Token.is(MIToken::JumpTableIndex)); 1255 unsigned ID; 1256 if (getUnsigned(ID)) 1257 return true; 1258 auto JumpTableEntryInfo = PFS.JumpTableSlots.find(ID); 1259 if (JumpTableEntryInfo == PFS.JumpTableSlots.end()) 1260 return error("use of undefined jump table '%jump-table." + Twine(ID) + "'"); 1261 lex(); 1262 Dest = MachineOperand::CreateJTI(JumpTableEntryInfo->second); 1263 return false; 1264 } 1265 1266 bool MIParser::parseExternalSymbolOperand(MachineOperand &Dest) { 1267 assert(Token.is(MIToken::ExternalSymbol)); 1268 const char *Symbol = MF.createExternalSymbolName(Token.stringValue()); 1269 lex(); 1270 Dest = MachineOperand::CreateES(Symbol); 1271 if (parseOperandsOffset(Dest)) 1272 return true; 1273 return false; 1274 } 1275 1276 bool MIParser::parseSubRegisterIndexOperand(MachineOperand &Dest) { 1277 assert(Token.is(MIToken::SubRegisterIndex)); 1278 StringRef Name = Token.stringValue(); 1279 unsigned SubRegIndex = getSubRegIndex(Token.stringValue()); 1280 if (SubRegIndex == 0) 1281 return error(Twine("unknown subregister index '") + Name + "'"); 1282 lex(); 1283 Dest = MachineOperand::CreateImm(SubRegIndex); 1284 return false; 1285 } 1286 1287 bool MIParser::parseMDNode(MDNode *&Node) { 1288 assert(Token.is(MIToken::exclaim)); 1289 auto Loc = Token.location(); 1290 lex(); 1291 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned()) 1292 return error("expected metadata id after '!'"); 1293 unsigned ID; 1294 if (getUnsigned(ID)) 1295 return true; 1296 auto NodeInfo = PFS.IRSlots.MetadataNodes.find(ID); 1297 if (NodeInfo == PFS.IRSlots.MetadataNodes.end()) 1298 return error(Loc, "use of undefined metadata '!" + Twine(ID) + "'"); 1299 lex(); 1300 Node = NodeInfo->second.get(); 1301 return false; 1302 } 1303 1304 bool MIParser::parseMetadataOperand(MachineOperand &Dest) { 1305 MDNode *Node = nullptr; 1306 if (parseMDNode(Node)) 1307 return true; 1308 Dest = MachineOperand::CreateMetadata(Node); 1309 return false; 1310 } 1311 1312 bool MIParser::parseCFIOffset(int &Offset) { 1313 if (Token.isNot(MIToken::IntegerLiteral)) 1314 return error("expected a cfi offset"); 1315 if (Token.integerValue().getMinSignedBits() > 32) 1316 return error("expected a 32 bit integer (the cfi offset is too large)"); 1317 Offset = (int)Token.integerValue().getExtValue(); 1318 lex(); 1319 return false; 1320 } 1321 1322 bool MIParser::parseCFIRegister(unsigned &Reg) { 1323 if (Token.isNot(MIToken::NamedRegister)) 1324 return error("expected a cfi register"); 1325 unsigned LLVMReg; 1326 if (parseRegister(LLVMReg)) 1327 return true; 1328 const auto *TRI = MF.getSubtarget().getRegisterInfo(); 1329 assert(TRI && "Expected target register info"); 1330 int DwarfReg = TRI->getDwarfRegNum(LLVMReg, true); 1331 if (DwarfReg < 0) 1332 return error("invalid DWARF register"); 1333 Reg = (unsigned)DwarfReg; 1334 lex(); 1335 return false; 1336 } 1337 1338 bool MIParser::parseCFIOperand(MachineOperand &Dest) { 1339 auto Kind = Token.kind(); 1340 lex(); 1341 auto &MMI = MF.getMMI(); 1342 int Offset; 1343 unsigned Reg; 1344 unsigned CFIIndex; 1345 switch (Kind) { 1346 case MIToken::kw_cfi_same_value: 1347 if (parseCFIRegister(Reg)) 1348 return true; 1349 CFIIndex = 1350 MMI.addFrameInst(MCCFIInstruction::createSameValue(nullptr, Reg)); 1351 break; 1352 case MIToken::kw_cfi_offset: 1353 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) || 1354 parseCFIOffset(Offset)) 1355 return true; 1356 CFIIndex = 1357 MMI.addFrameInst(MCCFIInstruction::createOffset(nullptr, Reg, Offset)); 1358 break; 1359 case MIToken::kw_cfi_def_cfa_register: 1360 if (parseCFIRegister(Reg)) 1361 return true; 1362 CFIIndex = 1363 MMI.addFrameInst(MCCFIInstruction::createDefCfaRegister(nullptr, Reg)); 1364 break; 1365 case MIToken::kw_cfi_def_cfa_offset: 1366 if (parseCFIOffset(Offset)) 1367 return true; 1368 // NB: MCCFIInstruction::createDefCfaOffset negates the offset. 1369 CFIIndex = MMI.addFrameInst( 1370 MCCFIInstruction::createDefCfaOffset(nullptr, -Offset)); 1371 break; 1372 case MIToken::kw_cfi_def_cfa: 1373 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) || 1374 parseCFIOffset(Offset)) 1375 return true; 1376 // NB: MCCFIInstruction::createDefCfa negates the offset. 1377 CFIIndex = 1378 MMI.addFrameInst(MCCFIInstruction::createDefCfa(nullptr, Reg, -Offset)); 1379 break; 1380 default: 1381 // TODO: Parse the other CFI operands. 1382 llvm_unreachable("The current token should be a cfi operand"); 1383 } 1384 Dest = MachineOperand::CreateCFIIndex(CFIIndex); 1385 return false; 1386 } 1387 1388 bool MIParser::parseIRBlock(BasicBlock *&BB, const Function &F) { 1389 switch (Token.kind()) { 1390 case MIToken::NamedIRBlock: { 1391 BB = dyn_cast_or_null<BasicBlock>( 1392 F.getValueSymbolTable().lookup(Token.stringValue())); 1393 if (!BB) 1394 return error(Twine("use of undefined IR block '") + Token.range() + "'"); 1395 break; 1396 } 1397 case MIToken::IRBlock: { 1398 unsigned SlotNumber = 0; 1399 if (getUnsigned(SlotNumber)) 1400 return true; 1401 BB = const_cast<BasicBlock *>(getIRBlock(SlotNumber, F)); 1402 if (!BB) 1403 return error(Twine("use of undefined IR block '%ir-block.") + 1404 Twine(SlotNumber) + "'"); 1405 break; 1406 } 1407 default: 1408 llvm_unreachable("The current token should be an IR block reference"); 1409 } 1410 return false; 1411 } 1412 1413 bool MIParser::parseBlockAddressOperand(MachineOperand &Dest) { 1414 assert(Token.is(MIToken::kw_blockaddress)); 1415 lex(); 1416 if (expectAndConsume(MIToken::lparen)) 1417 return true; 1418 if (Token.isNot(MIToken::GlobalValue) && 1419 Token.isNot(MIToken::NamedGlobalValue)) 1420 return error("expected a global value"); 1421 GlobalValue *GV = nullptr; 1422 if (parseGlobalValue(GV)) 1423 return true; 1424 auto *F = dyn_cast<Function>(GV); 1425 if (!F) 1426 return error("expected an IR function reference"); 1427 lex(); 1428 if (expectAndConsume(MIToken::comma)) 1429 return true; 1430 BasicBlock *BB = nullptr; 1431 if (Token.isNot(MIToken::IRBlock) && Token.isNot(MIToken::NamedIRBlock)) 1432 return error("expected an IR block reference"); 1433 if (parseIRBlock(BB, *F)) 1434 return true; 1435 lex(); 1436 if (expectAndConsume(MIToken::rparen)) 1437 return true; 1438 Dest = MachineOperand::CreateBA(BlockAddress::get(F, BB), /*Offset=*/0); 1439 if (parseOperandsOffset(Dest)) 1440 return true; 1441 return false; 1442 } 1443 1444 bool MIParser::parseTargetIndexOperand(MachineOperand &Dest) { 1445 assert(Token.is(MIToken::kw_target_index)); 1446 lex(); 1447 if (expectAndConsume(MIToken::lparen)) 1448 return true; 1449 if (Token.isNot(MIToken::Identifier)) 1450 return error("expected the name of the target index"); 1451 int Index = 0; 1452 if (getTargetIndex(Token.stringValue(), Index)) 1453 return error("use of undefined target index '" + Token.stringValue() + "'"); 1454 lex(); 1455 if (expectAndConsume(MIToken::rparen)) 1456 return true; 1457 Dest = MachineOperand::CreateTargetIndex(unsigned(Index), /*Offset=*/0); 1458 if (parseOperandsOffset(Dest)) 1459 return true; 1460 return false; 1461 } 1462 1463 bool MIParser::parseLiveoutRegisterMaskOperand(MachineOperand &Dest) { 1464 assert(Token.is(MIToken::kw_liveout)); 1465 const auto *TRI = MF.getSubtarget().getRegisterInfo(); 1466 assert(TRI && "Expected target register info"); 1467 uint32_t *Mask = MF.allocateRegisterMask(TRI->getNumRegs()); 1468 lex(); 1469 if (expectAndConsume(MIToken::lparen)) 1470 return true; 1471 while (true) { 1472 if (Token.isNot(MIToken::NamedRegister)) 1473 return error("expected a named register"); 1474 unsigned Reg = 0; 1475 if (parseRegister(Reg)) 1476 return true; 1477 lex(); 1478 Mask[Reg / 32] |= 1U << (Reg % 32); 1479 // TODO: Report an error if the same register is used more than once. 1480 if (Token.isNot(MIToken::comma)) 1481 break; 1482 lex(); 1483 } 1484 if (expectAndConsume(MIToken::rparen)) 1485 return true; 1486 Dest = MachineOperand::CreateRegLiveOut(Mask); 1487 return false; 1488 } 1489 1490 bool MIParser::parseMachineOperand(MachineOperand &Dest, 1491 Optional<unsigned> &TiedDefIdx) { 1492 switch (Token.kind()) { 1493 case MIToken::kw_implicit: 1494 case MIToken::kw_implicit_define: 1495 case MIToken::kw_def: 1496 case MIToken::kw_dead: 1497 case MIToken::kw_killed: 1498 case MIToken::kw_undef: 1499 case MIToken::kw_internal: 1500 case MIToken::kw_early_clobber: 1501 case MIToken::kw_debug_use: 1502 case MIToken::underscore: 1503 case MIToken::NamedRegister: 1504 case MIToken::VirtualRegister: 1505 return parseRegisterOperand(Dest, TiedDefIdx); 1506 case MIToken::IntegerLiteral: 1507 return parseImmediateOperand(Dest); 1508 case MIToken::IntegerType: 1509 return parseTypedImmediateOperand(Dest); 1510 case MIToken::kw_half: 1511 case MIToken::kw_float: 1512 case MIToken::kw_double: 1513 case MIToken::kw_x86_fp80: 1514 case MIToken::kw_fp128: 1515 case MIToken::kw_ppc_fp128: 1516 return parseFPImmediateOperand(Dest); 1517 case MIToken::MachineBasicBlock: 1518 return parseMBBOperand(Dest); 1519 case MIToken::StackObject: 1520 return parseStackObjectOperand(Dest); 1521 case MIToken::FixedStackObject: 1522 return parseFixedStackObjectOperand(Dest); 1523 case MIToken::GlobalValue: 1524 case MIToken::NamedGlobalValue: 1525 return parseGlobalAddressOperand(Dest); 1526 case MIToken::ConstantPoolItem: 1527 return parseConstantPoolIndexOperand(Dest); 1528 case MIToken::JumpTableIndex: 1529 return parseJumpTableIndexOperand(Dest); 1530 case MIToken::ExternalSymbol: 1531 return parseExternalSymbolOperand(Dest); 1532 case MIToken::SubRegisterIndex: 1533 return parseSubRegisterIndexOperand(Dest); 1534 case MIToken::exclaim: 1535 return parseMetadataOperand(Dest); 1536 case MIToken::kw_cfi_same_value: 1537 case MIToken::kw_cfi_offset: 1538 case MIToken::kw_cfi_def_cfa_register: 1539 case MIToken::kw_cfi_def_cfa_offset: 1540 case MIToken::kw_cfi_def_cfa: 1541 return parseCFIOperand(Dest); 1542 case MIToken::kw_blockaddress: 1543 return parseBlockAddressOperand(Dest); 1544 case MIToken::kw_target_index: 1545 return parseTargetIndexOperand(Dest); 1546 case MIToken::kw_liveout: 1547 return parseLiveoutRegisterMaskOperand(Dest); 1548 case MIToken::Error: 1549 return true; 1550 case MIToken::Identifier: 1551 if (const auto *RegMask = getRegMask(Token.stringValue())) { 1552 Dest = MachineOperand::CreateRegMask(RegMask); 1553 lex(); 1554 break; 1555 } 1556 // fallthrough 1557 default: 1558 // FIXME: Parse the MCSymbol machine operand. 1559 return error("expected a machine operand"); 1560 } 1561 return false; 1562 } 1563 1564 bool MIParser::parseMachineOperandAndTargetFlags( 1565 MachineOperand &Dest, Optional<unsigned> &TiedDefIdx) { 1566 unsigned TF = 0; 1567 bool HasTargetFlags = false; 1568 if (Token.is(MIToken::kw_target_flags)) { 1569 HasTargetFlags = true; 1570 lex(); 1571 if (expectAndConsume(MIToken::lparen)) 1572 return true; 1573 if (Token.isNot(MIToken::Identifier)) 1574 return error("expected the name of the target flag"); 1575 if (getDirectTargetFlag(Token.stringValue(), TF)) { 1576 if (getBitmaskTargetFlag(Token.stringValue(), TF)) 1577 return error("use of undefined target flag '" + Token.stringValue() + 1578 "'"); 1579 } 1580 lex(); 1581 while (Token.is(MIToken::comma)) { 1582 lex(); 1583 if (Token.isNot(MIToken::Identifier)) 1584 return error("expected the name of the target flag"); 1585 unsigned BitFlag = 0; 1586 if (getBitmaskTargetFlag(Token.stringValue(), BitFlag)) 1587 return error("use of undefined target flag '" + Token.stringValue() + 1588 "'"); 1589 // TODO: Report an error when using a duplicate bit target flag. 1590 TF |= BitFlag; 1591 lex(); 1592 } 1593 if (expectAndConsume(MIToken::rparen)) 1594 return true; 1595 } 1596 auto Loc = Token.location(); 1597 if (parseMachineOperand(Dest, TiedDefIdx)) 1598 return true; 1599 if (!HasTargetFlags) 1600 return false; 1601 if (Dest.isReg()) 1602 return error(Loc, "register operands can't have target flags"); 1603 Dest.setTargetFlags(TF); 1604 return false; 1605 } 1606 1607 bool MIParser::parseOffset(int64_t &Offset) { 1608 if (Token.isNot(MIToken::plus) && Token.isNot(MIToken::minus)) 1609 return false; 1610 StringRef Sign = Token.range(); 1611 bool IsNegative = Token.is(MIToken::minus); 1612 lex(); 1613 if (Token.isNot(MIToken::IntegerLiteral)) 1614 return error("expected an integer literal after '" + Sign + "'"); 1615 if (Token.integerValue().getMinSignedBits() > 64) 1616 return error("expected 64-bit integer (too large)"); 1617 Offset = Token.integerValue().getExtValue(); 1618 if (IsNegative) 1619 Offset = -Offset; 1620 lex(); 1621 return false; 1622 } 1623 1624 bool MIParser::parseAlignment(unsigned &Alignment) { 1625 assert(Token.is(MIToken::kw_align)); 1626 lex(); 1627 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned()) 1628 return error("expected an integer literal after 'align'"); 1629 if (getUnsigned(Alignment)) 1630 return true; 1631 lex(); 1632 return false; 1633 } 1634 1635 bool MIParser::parseOperandsOffset(MachineOperand &Op) { 1636 int64_t Offset = 0; 1637 if (parseOffset(Offset)) 1638 return true; 1639 Op.setOffset(Offset); 1640 return false; 1641 } 1642 1643 bool MIParser::parseIRValue(const Value *&V) { 1644 switch (Token.kind()) { 1645 case MIToken::NamedIRValue: { 1646 V = MF.getFunction()->getValueSymbolTable().lookup(Token.stringValue()); 1647 break; 1648 } 1649 case MIToken::IRValue: { 1650 unsigned SlotNumber = 0; 1651 if (getUnsigned(SlotNumber)) 1652 return true; 1653 V = getIRValue(SlotNumber); 1654 break; 1655 } 1656 case MIToken::NamedGlobalValue: 1657 case MIToken::GlobalValue: { 1658 GlobalValue *GV = nullptr; 1659 if (parseGlobalValue(GV)) 1660 return true; 1661 V = GV; 1662 break; 1663 } 1664 case MIToken::QuotedIRValue: { 1665 const Constant *C = nullptr; 1666 if (parseIRConstant(Token.location(), Token.stringValue(), C)) 1667 return true; 1668 V = C; 1669 break; 1670 } 1671 default: 1672 llvm_unreachable("The current token should be an IR block reference"); 1673 } 1674 if (!V) 1675 return error(Twine("use of undefined IR value '") + Token.range() + "'"); 1676 return false; 1677 } 1678 1679 bool MIParser::getUint64(uint64_t &Result) { 1680 assert(Token.hasIntegerValue()); 1681 if (Token.integerValue().getActiveBits() > 64) 1682 return error("expected 64-bit integer (too large)"); 1683 Result = Token.integerValue().getZExtValue(); 1684 return false; 1685 } 1686 1687 bool MIParser::parseMemoryOperandFlag(MachineMemOperand::Flags &Flags) { 1688 const auto OldFlags = Flags; 1689 switch (Token.kind()) { 1690 case MIToken::kw_volatile: 1691 Flags |= MachineMemOperand::MOVolatile; 1692 break; 1693 case MIToken::kw_non_temporal: 1694 Flags |= MachineMemOperand::MONonTemporal; 1695 break; 1696 case MIToken::kw_invariant: 1697 Flags |= MachineMemOperand::MOInvariant; 1698 break; 1699 // TODO: parse the target specific memory operand flags. 1700 default: 1701 llvm_unreachable("The current token should be a memory operand flag"); 1702 } 1703 if (OldFlags == Flags) 1704 // We know that the same flag is specified more than once when the flags 1705 // weren't modified. 1706 return error("duplicate '" + Token.stringValue() + "' memory operand flag"); 1707 lex(); 1708 return false; 1709 } 1710 1711 bool MIParser::parseMemoryPseudoSourceValue(const PseudoSourceValue *&PSV) { 1712 switch (Token.kind()) { 1713 case MIToken::kw_stack: 1714 PSV = MF.getPSVManager().getStack(); 1715 break; 1716 case MIToken::kw_got: 1717 PSV = MF.getPSVManager().getGOT(); 1718 break; 1719 case MIToken::kw_jump_table: 1720 PSV = MF.getPSVManager().getJumpTable(); 1721 break; 1722 case MIToken::kw_constant_pool: 1723 PSV = MF.getPSVManager().getConstantPool(); 1724 break; 1725 case MIToken::FixedStackObject: { 1726 int FI; 1727 if (parseFixedStackFrameIndex(FI)) 1728 return true; 1729 PSV = MF.getPSVManager().getFixedStack(FI); 1730 // The token was already consumed, so use return here instead of break. 1731 return false; 1732 } 1733 case MIToken::StackObject: { 1734 int FI; 1735 if (parseStackFrameIndex(FI)) 1736 return true; 1737 PSV = MF.getPSVManager().getFixedStack(FI); 1738 // The token was already consumed, so use return here instead of break. 1739 return false; 1740 } 1741 case MIToken::kw_call_entry: { 1742 lex(); 1743 switch (Token.kind()) { 1744 case MIToken::GlobalValue: 1745 case MIToken::NamedGlobalValue: { 1746 GlobalValue *GV = nullptr; 1747 if (parseGlobalValue(GV)) 1748 return true; 1749 PSV = MF.getPSVManager().getGlobalValueCallEntry(GV); 1750 break; 1751 } 1752 case MIToken::ExternalSymbol: 1753 PSV = MF.getPSVManager().getExternalSymbolCallEntry( 1754 MF.createExternalSymbolName(Token.stringValue())); 1755 break; 1756 default: 1757 return error( 1758 "expected a global value or an external symbol after 'call-entry'"); 1759 } 1760 break; 1761 } 1762 default: 1763 llvm_unreachable("The current token should be pseudo source value"); 1764 } 1765 lex(); 1766 return false; 1767 } 1768 1769 bool MIParser::parseMachinePointerInfo(MachinePointerInfo &Dest) { 1770 if (Token.is(MIToken::kw_constant_pool) || Token.is(MIToken::kw_stack) || 1771 Token.is(MIToken::kw_got) || Token.is(MIToken::kw_jump_table) || 1772 Token.is(MIToken::FixedStackObject) || Token.is(MIToken::StackObject) || 1773 Token.is(MIToken::kw_call_entry)) { 1774 const PseudoSourceValue *PSV = nullptr; 1775 if (parseMemoryPseudoSourceValue(PSV)) 1776 return true; 1777 int64_t Offset = 0; 1778 if (parseOffset(Offset)) 1779 return true; 1780 Dest = MachinePointerInfo(PSV, Offset); 1781 return false; 1782 } 1783 if (Token.isNot(MIToken::NamedIRValue) && Token.isNot(MIToken::IRValue) && 1784 Token.isNot(MIToken::GlobalValue) && 1785 Token.isNot(MIToken::NamedGlobalValue) && 1786 Token.isNot(MIToken::QuotedIRValue)) 1787 return error("expected an IR value reference"); 1788 const Value *V = nullptr; 1789 if (parseIRValue(V)) 1790 return true; 1791 if (!V->getType()->isPointerTy()) 1792 return error("expected a pointer IR value"); 1793 lex(); 1794 int64_t Offset = 0; 1795 if (parseOffset(Offset)) 1796 return true; 1797 Dest = MachinePointerInfo(V, Offset); 1798 return false; 1799 } 1800 1801 bool MIParser::parseMachineMemoryOperand(MachineMemOperand *&Dest) { 1802 if (expectAndConsume(MIToken::lparen)) 1803 return true; 1804 MachineMemOperand::Flags Flags = MachineMemOperand::MONone; 1805 while (Token.isMemoryOperandFlag()) { 1806 if (parseMemoryOperandFlag(Flags)) 1807 return true; 1808 } 1809 if (Token.isNot(MIToken::Identifier) || 1810 (Token.stringValue() != "load" && Token.stringValue() != "store")) 1811 return error("expected 'load' or 'store' memory operation"); 1812 if (Token.stringValue() == "load") 1813 Flags |= MachineMemOperand::MOLoad; 1814 else 1815 Flags |= MachineMemOperand::MOStore; 1816 lex(); 1817 1818 if (Token.isNot(MIToken::IntegerLiteral)) 1819 return error("expected the size integer literal after memory operation"); 1820 uint64_t Size; 1821 if (getUint64(Size)) 1822 return true; 1823 lex(); 1824 1825 MachinePointerInfo Ptr = MachinePointerInfo(); 1826 if (Token.is(MIToken::Identifier)) { 1827 const char *Word = Flags & MachineMemOperand::MOLoad ? "from" : "into"; 1828 if (Token.stringValue() != Word) 1829 return error(Twine("expected '") + Word + "'"); 1830 lex(); 1831 1832 if (parseMachinePointerInfo(Ptr)) 1833 return true; 1834 } 1835 unsigned BaseAlignment = Size; 1836 AAMDNodes AAInfo; 1837 MDNode *Range = nullptr; 1838 while (consumeIfPresent(MIToken::comma)) { 1839 switch (Token.kind()) { 1840 case MIToken::kw_align: 1841 if (parseAlignment(BaseAlignment)) 1842 return true; 1843 break; 1844 case MIToken::md_tbaa: 1845 lex(); 1846 if (parseMDNode(AAInfo.TBAA)) 1847 return true; 1848 break; 1849 case MIToken::md_alias_scope: 1850 lex(); 1851 if (parseMDNode(AAInfo.Scope)) 1852 return true; 1853 break; 1854 case MIToken::md_noalias: 1855 lex(); 1856 if (parseMDNode(AAInfo.NoAlias)) 1857 return true; 1858 break; 1859 case MIToken::md_range: 1860 lex(); 1861 if (parseMDNode(Range)) 1862 return true; 1863 break; 1864 // TODO: Report an error on duplicate metadata nodes. 1865 default: 1866 return error("expected 'align' or '!tbaa' or '!alias.scope' or " 1867 "'!noalias' or '!range'"); 1868 } 1869 } 1870 if (expectAndConsume(MIToken::rparen)) 1871 return true; 1872 Dest = 1873 MF.getMachineMemOperand(Ptr, Flags, Size, BaseAlignment, AAInfo, Range); 1874 return false; 1875 } 1876 1877 void MIParser::initNames2InstrOpCodes() { 1878 if (!Names2InstrOpCodes.empty()) 1879 return; 1880 const auto *TII = MF.getSubtarget().getInstrInfo(); 1881 assert(TII && "Expected target instruction info"); 1882 for (unsigned I = 0, E = TII->getNumOpcodes(); I < E; ++I) 1883 Names2InstrOpCodes.insert(std::make_pair(StringRef(TII->getName(I)), I)); 1884 } 1885 1886 bool MIParser::parseInstrName(StringRef InstrName, unsigned &OpCode) { 1887 initNames2InstrOpCodes(); 1888 auto InstrInfo = Names2InstrOpCodes.find(InstrName); 1889 if (InstrInfo == Names2InstrOpCodes.end()) 1890 return true; 1891 OpCode = InstrInfo->getValue(); 1892 return false; 1893 } 1894 1895 void MIParser::initNames2Regs() { 1896 if (!Names2Regs.empty()) 1897 return; 1898 // The '%noreg' register is the register 0. 1899 Names2Regs.insert(std::make_pair("noreg", 0)); 1900 const auto *TRI = MF.getSubtarget().getRegisterInfo(); 1901 assert(TRI && "Expected target register info"); 1902 for (unsigned I = 0, E = TRI->getNumRegs(); I < E; ++I) { 1903 bool WasInserted = 1904 Names2Regs.insert(std::make_pair(StringRef(TRI->getName(I)).lower(), I)) 1905 .second; 1906 (void)WasInserted; 1907 assert(WasInserted && "Expected registers to be unique case-insensitively"); 1908 } 1909 } 1910 1911 bool MIParser::getRegisterByName(StringRef RegName, unsigned &Reg) { 1912 initNames2Regs(); 1913 auto RegInfo = Names2Regs.find(RegName); 1914 if (RegInfo == Names2Regs.end()) 1915 return true; 1916 Reg = RegInfo->getValue(); 1917 return false; 1918 } 1919 1920 void MIParser::initNames2RegMasks() { 1921 if (!Names2RegMasks.empty()) 1922 return; 1923 const auto *TRI = MF.getSubtarget().getRegisterInfo(); 1924 assert(TRI && "Expected target register info"); 1925 ArrayRef<const uint32_t *> RegMasks = TRI->getRegMasks(); 1926 ArrayRef<const char *> RegMaskNames = TRI->getRegMaskNames(); 1927 assert(RegMasks.size() == RegMaskNames.size()); 1928 for (size_t I = 0, E = RegMasks.size(); I < E; ++I) 1929 Names2RegMasks.insert( 1930 std::make_pair(StringRef(RegMaskNames[I]).lower(), RegMasks[I])); 1931 } 1932 1933 const uint32_t *MIParser::getRegMask(StringRef Identifier) { 1934 initNames2RegMasks(); 1935 auto RegMaskInfo = Names2RegMasks.find(Identifier); 1936 if (RegMaskInfo == Names2RegMasks.end()) 1937 return nullptr; 1938 return RegMaskInfo->getValue(); 1939 } 1940 1941 void MIParser::initNames2SubRegIndices() { 1942 if (!Names2SubRegIndices.empty()) 1943 return; 1944 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 1945 for (unsigned I = 1, E = TRI->getNumSubRegIndices(); I < E; ++I) 1946 Names2SubRegIndices.insert( 1947 std::make_pair(StringRef(TRI->getSubRegIndexName(I)).lower(), I)); 1948 } 1949 1950 unsigned MIParser::getSubRegIndex(StringRef Name) { 1951 initNames2SubRegIndices(); 1952 auto SubRegInfo = Names2SubRegIndices.find(Name); 1953 if (SubRegInfo == Names2SubRegIndices.end()) 1954 return 0; 1955 return SubRegInfo->getValue(); 1956 } 1957 1958 static void initSlots2BasicBlocks( 1959 const Function &F, 1960 DenseMap<unsigned, const BasicBlock *> &Slots2BasicBlocks) { 1961 ModuleSlotTracker MST(F.getParent(), /*ShouldInitializeAllMetadata=*/false); 1962 MST.incorporateFunction(F); 1963 for (auto &BB : F) { 1964 if (BB.hasName()) 1965 continue; 1966 int Slot = MST.getLocalSlot(&BB); 1967 if (Slot == -1) 1968 continue; 1969 Slots2BasicBlocks.insert(std::make_pair(unsigned(Slot), &BB)); 1970 } 1971 } 1972 1973 static const BasicBlock *getIRBlockFromSlot( 1974 unsigned Slot, 1975 const DenseMap<unsigned, const BasicBlock *> &Slots2BasicBlocks) { 1976 auto BlockInfo = Slots2BasicBlocks.find(Slot); 1977 if (BlockInfo == Slots2BasicBlocks.end()) 1978 return nullptr; 1979 return BlockInfo->second; 1980 } 1981 1982 const BasicBlock *MIParser::getIRBlock(unsigned Slot) { 1983 if (Slots2BasicBlocks.empty()) 1984 initSlots2BasicBlocks(*MF.getFunction(), Slots2BasicBlocks); 1985 return getIRBlockFromSlot(Slot, Slots2BasicBlocks); 1986 } 1987 1988 const BasicBlock *MIParser::getIRBlock(unsigned Slot, const Function &F) { 1989 if (&F == MF.getFunction()) 1990 return getIRBlock(Slot); 1991 DenseMap<unsigned, const BasicBlock *> CustomSlots2BasicBlocks; 1992 initSlots2BasicBlocks(F, CustomSlots2BasicBlocks); 1993 return getIRBlockFromSlot(Slot, CustomSlots2BasicBlocks); 1994 } 1995 1996 static void mapValueToSlot(const Value *V, ModuleSlotTracker &MST, 1997 DenseMap<unsigned, const Value *> &Slots2Values) { 1998 int Slot = MST.getLocalSlot(V); 1999 if (Slot == -1) 2000 return; 2001 Slots2Values.insert(std::make_pair(unsigned(Slot), V)); 2002 } 2003 2004 /// Creates the mapping from slot numbers to function's unnamed IR values. 2005 static void initSlots2Values(const Function &F, 2006 DenseMap<unsigned, const Value *> &Slots2Values) { 2007 ModuleSlotTracker MST(F.getParent(), /*ShouldInitializeAllMetadata=*/false); 2008 MST.incorporateFunction(F); 2009 for (const auto &Arg : F.args()) 2010 mapValueToSlot(&Arg, MST, Slots2Values); 2011 for (const auto &BB : F) { 2012 mapValueToSlot(&BB, MST, Slots2Values); 2013 for (const auto &I : BB) 2014 mapValueToSlot(&I, MST, Slots2Values); 2015 } 2016 } 2017 2018 const Value *MIParser::getIRValue(unsigned Slot) { 2019 if (Slots2Values.empty()) 2020 initSlots2Values(*MF.getFunction(), Slots2Values); 2021 auto ValueInfo = Slots2Values.find(Slot); 2022 if (ValueInfo == Slots2Values.end()) 2023 return nullptr; 2024 return ValueInfo->second; 2025 } 2026 2027 void MIParser::initNames2TargetIndices() { 2028 if (!Names2TargetIndices.empty()) 2029 return; 2030 const auto *TII = MF.getSubtarget().getInstrInfo(); 2031 assert(TII && "Expected target instruction info"); 2032 auto Indices = TII->getSerializableTargetIndices(); 2033 for (const auto &I : Indices) 2034 Names2TargetIndices.insert(std::make_pair(StringRef(I.second), I.first)); 2035 } 2036 2037 bool MIParser::getTargetIndex(StringRef Name, int &Index) { 2038 initNames2TargetIndices(); 2039 auto IndexInfo = Names2TargetIndices.find(Name); 2040 if (IndexInfo == Names2TargetIndices.end()) 2041 return true; 2042 Index = IndexInfo->second; 2043 return false; 2044 } 2045 2046 void MIParser::initNames2DirectTargetFlags() { 2047 if (!Names2DirectTargetFlags.empty()) 2048 return; 2049 const auto *TII = MF.getSubtarget().getInstrInfo(); 2050 assert(TII && "Expected target instruction info"); 2051 auto Flags = TII->getSerializableDirectMachineOperandTargetFlags(); 2052 for (const auto &I : Flags) 2053 Names2DirectTargetFlags.insert( 2054 std::make_pair(StringRef(I.second), I.first)); 2055 } 2056 2057 bool MIParser::getDirectTargetFlag(StringRef Name, unsigned &Flag) { 2058 initNames2DirectTargetFlags(); 2059 auto FlagInfo = Names2DirectTargetFlags.find(Name); 2060 if (FlagInfo == Names2DirectTargetFlags.end()) 2061 return true; 2062 Flag = FlagInfo->second; 2063 return false; 2064 } 2065 2066 void MIParser::initNames2BitmaskTargetFlags() { 2067 if (!Names2BitmaskTargetFlags.empty()) 2068 return; 2069 const auto *TII = MF.getSubtarget().getInstrInfo(); 2070 assert(TII && "Expected target instruction info"); 2071 auto Flags = TII->getSerializableBitmaskMachineOperandTargetFlags(); 2072 for (const auto &I : Flags) 2073 Names2BitmaskTargetFlags.insert( 2074 std::make_pair(StringRef(I.second), I.first)); 2075 } 2076 2077 bool MIParser::getBitmaskTargetFlag(StringRef Name, unsigned &Flag) { 2078 initNames2BitmaskTargetFlags(); 2079 auto FlagInfo = Names2BitmaskTargetFlags.find(Name); 2080 if (FlagInfo == Names2BitmaskTargetFlags.end()) 2081 return true; 2082 Flag = FlagInfo->second; 2083 return false; 2084 } 2085 2086 bool llvm::parseMachineBasicBlockDefinitions(PerFunctionMIParsingState &PFS, 2087 StringRef Src, 2088 SMDiagnostic &Error) { 2089 return MIParser(PFS, Error, Src).parseBasicBlockDefinitions(PFS.MBBSlots); 2090 } 2091 2092 bool llvm::parseMachineInstructions(const PerFunctionMIParsingState &PFS, 2093 StringRef Src, SMDiagnostic &Error) { 2094 return MIParser(PFS, Error, Src).parseBasicBlocks(); 2095 } 2096 2097 bool llvm::parseMBBReference(const PerFunctionMIParsingState &PFS, 2098 MachineBasicBlock *&MBB, StringRef Src, 2099 SMDiagnostic &Error) { 2100 return MIParser(PFS, Error, Src).parseStandaloneMBB(MBB); 2101 } 2102 2103 bool llvm::parseNamedRegisterReference(const PerFunctionMIParsingState &PFS, 2104 unsigned &Reg, StringRef Src, 2105 SMDiagnostic &Error) { 2106 return MIParser(PFS, Error, Src).parseStandaloneNamedRegister(Reg); 2107 } 2108 2109 bool llvm::parseVirtualRegisterReference(const PerFunctionMIParsingState &PFS, 2110 unsigned &Reg, StringRef Src, 2111 SMDiagnostic &Error) { 2112 return MIParser(PFS, Error, Src).parseStandaloneVirtualRegister(Reg); 2113 } 2114 2115 bool llvm::parseStackObjectReference(const PerFunctionMIParsingState &PFS, 2116 int &FI, StringRef Src, 2117 SMDiagnostic &Error) { 2118 return MIParser(PFS, Error, Src).parseStandaloneStackObject(FI); 2119 } 2120 2121 bool llvm::parseMDNode(const PerFunctionMIParsingState &PFS, 2122 MDNode *&Node, StringRef Src, SMDiagnostic &Error) { 2123 return MIParser(PFS, Error, Src).parseStandaloneMDNode(Node); 2124 } 2125