1 //===- MIParser.cpp - Machine instructions parser implementation ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the parsing of machine instructions.
12 //===----------------------------------------------------------------------===//
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/MachineFunction.h"
21 #include "llvm/CodeGen/MachineFrameInfo.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/IR/Instructions.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/IR/ModuleSlotTracker.h"
30 #include "llvm/IR/ValueSymbolTable.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/Support/SourceMgr.h"
33 #include "llvm/Target/TargetSubtargetInfo.h"
34 #include "llvm/Target/TargetInstrInfo.h"
40 /// A wrapper struct around the 'MachineOperand' struct that includes a source
42 struct MachineOperandWithLocation {
43 MachineOperand Operand;
44 StringRef::iterator Begin;
45 StringRef::iterator End;
47 MachineOperandWithLocation(const MachineOperand &Operand,
48 StringRef::iterator Begin, StringRef::iterator End)
49 : Operand(Operand), Begin(Begin), End(End) {}
56 StringRef Source, CurrentSource;
58 const PerFunctionMIParsingState &PFS;
59 /// Maps from indices to unnamed global values and metadata nodes.
60 const SlotMapping &IRSlots;
61 /// Maps from instruction names to op codes.
62 StringMap<unsigned> Names2InstrOpCodes;
63 /// Maps from register names to registers.
64 StringMap<unsigned> Names2Regs;
65 /// Maps from register mask names to register masks.
66 StringMap<const uint32_t *> Names2RegMasks;
67 /// Maps from subregister names to subregister indices.
68 StringMap<unsigned> Names2SubRegIndices;
69 /// Maps from slot numbers to function's unnamed basic blocks.
70 DenseMap<unsigned, const BasicBlock *> Slots2BasicBlocks;
71 /// Maps from target index names to target indices.
72 StringMap<int> Names2TargetIndices;
73 /// Maps from direct target flag names to the direct target flag values.
74 StringMap<unsigned> Names2DirectTargetFlags;
77 MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
78 StringRef Source, const PerFunctionMIParsingState &PFS,
79 const SlotMapping &IRSlots);
83 /// Report an error at the current location with the given message.
85 /// This function always return true.
86 bool error(const Twine &Msg);
88 /// Report an error at the given location with the given message.
90 /// This function always return true.
91 bool error(StringRef::iterator Loc, const Twine &Msg);
94 parseBasicBlockDefinitions(DenseMap<unsigned, MachineBasicBlock *> &MBBSlots);
95 bool parseBasicBlocks();
96 bool parse(MachineInstr *&MI);
97 bool parseStandaloneMBB(MachineBasicBlock *&MBB);
98 bool parseStandaloneNamedRegister(unsigned &Reg);
99 bool parseStandaloneVirtualRegister(unsigned &Reg);
102 parseBasicBlockDefinition(DenseMap<unsigned, MachineBasicBlock *> &MBBSlots);
103 bool parseBasicBlock(MachineBasicBlock &MBB);
104 bool parseBasicBlockLiveins(MachineBasicBlock &MBB);
105 bool parseBasicBlockSuccessors(MachineBasicBlock &MBB);
107 bool parseRegister(unsigned &Reg);
108 bool parseRegisterFlag(unsigned &Flags);
109 bool parseSubRegisterIndex(unsigned &SubReg);
110 bool parseRegisterOperand(MachineOperand &Dest, bool IsDef = false);
111 bool parseImmediateOperand(MachineOperand &Dest);
112 bool parseIRConstant(StringRef::iterator Loc, const Constant *&C);
113 bool parseTypedImmediateOperand(MachineOperand &Dest);
114 bool parseFPImmediateOperand(MachineOperand &Dest);
115 bool parseMBBReference(MachineBasicBlock *&MBB);
116 bool parseMBBOperand(MachineOperand &Dest);
117 bool parseStackFrameIndex(int &FI);
118 bool parseStackObjectOperand(MachineOperand &Dest);
119 bool parseFixedStackFrameIndex(int &FI);
120 bool parseFixedStackObjectOperand(MachineOperand &Dest);
121 bool parseGlobalValue(GlobalValue *&GV);
122 bool parseGlobalAddressOperand(MachineOperand &Dest);
123 bool parseConstantPoolIndexOperand(MachineOperand &Dest);
124 bool parseJumpTableIndexOperand(MachineOperand &Dest);
125 bool parseExternalSymbolOperand(MachineOperand &Dest);
126 bool parseMDNode(MDNode *&Node);
127 bool parseMetadataOperand(MachineOperand &Dest);
128 bool parseCFIOffset(int &Offset);
129 bool parseCFIRegister(unsigned &Reg);
130 bool parseCFIOperand(MachineOperand &Dest);
131 bool parseIRBlock(BasicBlock *&BB, const Function &F);
132 bool parseBlockAddressOperand(MachineOperand &Dest);
133 bool parseTargetIndexOperand(MachineOperand &Dest);
134 bool parseLiveoutRegisterMaskOperand(MachineOperand &Dest);
135 bool parseMachineOperand(MachineOperand &Dest);
136 bool parseMachineOperandAndTargetFlags(MachineOperand &Dest);
137 bool parseOffset(int64_t &Offset);
138 bool parseAlignment(unsigned &Alignment);
139 bool parseOperandsOffset(MachineOperand &Op);
140 bool parseIRValue(Value *&V);
141 bool parseMemoryOperandFlag(unsigned &Flags);
142 bool parseMemoryPseudoSourceValue(const PseudoSourceValue *&PSV);
143 bool parseMachinePointerInfo(MachinePointerInfo &Dest);
144 bool parseMachineMemoryOperand(MachineMemOperand *&Dest);
147 /// Convert the integer literal in the current token into an unsigned integer.
149 /// Return true if an error occurred.
150 bool getUnsigned(unsigned &Result);
152 /// Convert the integer literal in the current token into an uint64.
154 /// Return true if an error occurred.
155 bool getUint64(uint64_t &Result);
157 /// If the current token is of the given kind, consume it and return false.
158 /// Otherwise report an error and return true.
159 bool expectAndConsume(MIToken::TokenKind TokenKind);
161 /// If the current token is of the given kind, consume it and return true.
162 /// Otherwise return false.
163 bool consumeIfPresent(MIToken::TokenKind TokenKind);
165 void initNames2InstrOpCodes();
167 /// Try to convert an instruction name to an opcode. Return true if the
168 /// instruction name is invalid.
169 bool parseInstrName(StringRef InstrName, unsigned &OpCode);
171 bool parseInstruction(unsigned &OpCode, unsigned &Flags);
173 bool verifyImplicitOperands(ArrayRef<MachineOperandWithLocation> Operands,
174 const MCInstrDesc &MCID);
176 void initNames2Regs();
178 /// Try to convert a register name to a register number. Return true if the
179 /// register name is invalid.
180 bool getRegisterByName(StringRef RegName, unsigned &Reg);
182 void initNames2RegMasks();
184 /// Check if the given identifier is a name of a register mask.
186 /// Return null if the identifier isn't a register mask.
187 const uint32_t *getRegMask(StringRef Identifier);
189 void initNames2SubRegIndices();
191 /// Check if the given identifier is a name of a subregister index.
193 /// Return 0 if the name isn't a subregister index class.
194 unsigned getSubRegIndex(StringRef Name);
196 const BasicBlock *getIRBlock(unsigned Slot);
197 const BasicBlock *getIRBlock(unsigned Slot, const Function &F);
199 void initNames2TargetIndices();
201 /// Try to convert a name of target index to the corresponding target index.
203 /// Return true if the name isn't a name of a target index.
204 bool getTargetIndex(StringRef Name, int &Index);
206 void initNames2DirectTargetFlags();
208 /// Try to convert a name of a direct target flag to the corresponding
211 /// Return true if the name isn't a name of a direct flag.
212 bool getDirectTargetFlag(StringRef Name, unsigned &Flag);
215 } // end anonymous namespace
217 MIParser::MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
218 StringRef Source, const PerFunctionMIParsingState &PFS,
219 const SlotMapping &IRSlots)
220 : SM(SM), MF(MF), Error(Error), Source(Source), CurrentSource(Source),
221 PFS(PFS), IRSlots(IRSlots) {}
223 void MIParser::lex() {
224 CurrentSource = lexMIToken(
225 CurrentSource, Token,
226 [this](StringRef::iterator Loc, const Twine &Msg) { error(Loc, Msg); });
229 bool MIParser::error(const Twine &Msg) { return error(Token.location(), Msg); }
231 bool MIParser::error(StringRef::iterator Loc, const Twine &Msg) {
232 assert(Loc >= Source.data() && Loc <= (Source.data() + Source.size()));
233 const MemoryBuffer &Buffer = *SM.getMemoryBuffer(SM.getMainFileID());
234 if (Loc >= Buffer.getBufferStart() && Loc <= Buffer.getBufferEnd()) {
235 // Create an ordinary diagnostic when the source manager's buffer is the
237 Error = SM.GetMessage(SMLoc::getFromPointer(Loc), SourceMgr::DK_Error, Msg);
240 // Create a diagnostic for a YAML string literal.
241 Error = SMDiagnostic(SM, SMLoc(), Buffer.getBufferIdentifier(), 1,
242 Loc - Source.data(), SourceMgr::DK_Error, Msg.str(),
247 static const char *toString(MIToken::TokenKind TokenKind) {
255 case MIToken::lparen:
257 case MIToken::rparen:
260 return "<unknown token>";
264 bool MIParser::expectAndConsume(MIToken::TokenKind TokenKind) {
265 if (Token.isNot(TokenKind))
266 return error(Twine("expected ") + toString(TokenKind));
271 bool MIParser::consumeIfPresent(MIToken::TokenKind TokenKind) {
272 if (Token.isNot(TokenKind))
278 bool MIParser::parseBasicBlockDefinition(
279 DenseMap<unsigned, MachineBasicBlock *> &MBBSlots) {
280 assert(Token.is(MIToken::MachineBasicBlockLabel));
284 auto Loc = Token.location();
285 auto Name = Token.stringValue();
287 bool HasAddressTaken = false;
288 bool IsLandingPad = false;
289 unsigned Alignment = 0;
290 BasicBlock *BB = nullptr;
291 if (consumeIfPresent(MIToken::lparen)) {
293 // TODO: Report an error when multiple same attributes are specified.
294 switch (Token.kind()) {
295 case MIToken::kw_address_taken:
296 HasAddressTaken = true;
299 case MIToken::kw_landing_pad:
303 case MIToken::kw_align:
304 if (parseAlignment(Alignment))
307 case MIToken::IRBlock:
308 // TODO: Report an error when both name and ir block are specified.
309 if (parseIRBlock(BB, *MF.getFunction()))
316 } while (consumeIfPresent(MIToken::comma));
317 if (expectAndConsume(MIToken::rparen))
320 if (expectAndConsume(MIToken::colon))
324 BB = dyn_cast_or_null<BasicBlock>(
325 MF.getFunction()->getValueSymbolTable().lookup(Name));
327 return error(Loc, Twine("basic block '") + Name +
328 "' is not defined in the function '" +
331 auto *MBB = MF.CreateMachineBasicBlock(BB);
332 MF.insert(MF.end(), MBB);
333 bool WasInserted = MBBSlots.insert(std::make_pair(ID, MBB)).second;
335 return error(Loc, Twine("redefinition of machine basic block with id #") +
338 MBB->setAlignment(Alignment);
340 MBB->setHasAddressTaken();
341 MBB->setIsLandingPad(IsLandingPad);
345 bool MIParser::parseBasicBlockDefinitions(
346 DenseMap<unsigned, MachineBasicBlock *> &MBBSlots) {
348 // Skip until the first machine basic block.
349 while (Token.is(MIToken::Newline))
351 if (Token.isErrorOrEOF())
352 return Token.isError();
353 if (Token.isNot(MIToken::MachineBasicBlockLabel))
354 return error("expected a basic block definition before instructions");
355 unsigned BraceDepth = 0;
357 if (parseBasicBlockDefinition(MBBSlots))
359 bool IsAfterNewline = false;
360 // Skip until the next machine basic block.
362 if ((Token.is(MIToken::MachineBasicBlockLabel) && IsAfterNewline) ||
363 Token.isErrorOrEOF())
365 else if (Token.is(MIToken::MachineBasicBlockLabel))
366 return error("basic block definition should be located at the start of "
368 else if (consumeIfPresent(MIToken::Newline)) {
369 IsAfterNewline = true;
372 IsAfterNewline = false;
373 if (Token.is(MIToken::lbrace))
375 if (Token.is(MIToken::rbrace)) {
377 return error("extraneous closing brace ('}')");
382 // Verify that we closed all of the '{' at the end of a file or a block.
383 if (!Token.isError() && BraceDepth)
384 return error("expected '}'"); // FIXME: Report a note that shows '{'.
385 } while (!Token.isErrorOrEOF());
386 return Token.isError();
389 bool MIParser::parseBasicBlockLiveins(MachineBasicBlock &MBB) {
390 assert(Token.is(MIToken::kw_liveins));
392 if (expectAndConsume(MIToken::colon))
394 if (Token.isNewlineOrEOF()) // Allow an empty list of liveins.
397 if (Token.isNot(MIToken::NamedRegister))
398 return error("expected a named register");
400 if (parseRegister(Reg))
404 } while (consumeIfPresent(MIToken::comma));
408 bool MIParser::parseBasicBlockSuccessors(MachineBasicBlock &MBB) {
409 assert(Token.is(MIToken::kw_successors));
411 if (expectAndConsume(MIToken::colon))
413 if (Token.isNewlineOrEOF()) // Allow an empty list of successors.
416 if (Token.isNot(MIToken::MachineBasicBlock))
417 return error("expected a machine basic block reference");
418 MachineBasicBlock *SuccMBB = nullptr;
419 if (parseMBBReference(SuccMBB))
423 if (consumeIfPresent(MIToken::lparen)) {
424 if (Token.isNot(MIToken::IntegerLiteral))
425 return error("expected an integer literal after '('");
426 if (getUnsigned(Weight))
429 if (expectAndConsume(MIToken::rparen))
432 MBB.addSuccessor(SuccMBB, Weight);
433 } while (consumeIfPresent(MIToken::comma));
437 bool MIParser::parseBasicBlock(MachineBasicBlock &MBB) {
438 // Skip the definition.
439 assert(Token.is(MIToken::MachineBasicBlockLabel));
441 if (consumeIfPresent(MIToken::lparen)) {
442 while (Token.isNot(MIToken::rparen) && !Token.isErrorOrEOF())
444 consumeIfPresent(MIToken::rparen);
446 consumeIfPresent(MIToken::colon);
448 // Parse the liveins and successors.
449 // N.B: Multiple lists of successors and liveins are allowed and they're
456 // liveins: %edi, %esi
458 if (Token.is(MIToken::kw_successors)) {
459 if (parseBasicBlockSuccessors(MBB))
461 } else if (Token.is(MIToken::kw_liveins)) {
462 if (parseBasicBlockLiveins(MBB))
464 } else if (consumeIfPresent(MIToken::Newline)) {
468 if (!Token.isNewlineOrEOF())
469 return error("expected line break at the end of a list");
473 // Parse the instructions.
474 bool IsInBundle = false;
475 MachineInstr *PrevMI = nullptr;
477 if (Token.is(MIToken::MachineBasicBlockLabel) || Token.is(MIToken::Eof))
479 else if (consumeIfPresent(MIToken::Newline))
481 if (consumeIfPresent(MIToken::rbrace)) {
482 // The first parsing pass should verify that all closing '}' have an
488 MachineInstr *MI = nullptr;
491 MBB.insert(MBB.end(), MI);
493 PrevMI->setFlag(MachineInstr::BundledSucc);
494 MI->setFlag(MachineInstr::BundledPred);
497 if (Token.is(MIToken::lbrace)) {
499 return error("nested instruction bundles are not allowed");
501 // This instruction is the start of the bundle.
502 MI->setFlag(MachineInstr::BundledSucc);
504 if (!Token.is(MIToken::Newline))
505 // The next instruction can be on the same line.
508 assert(Token.isNewlineOrEOF() && "MI is not fully parsed");
514 bool MIParser::parseBasicBlocks() {
516 // Skip until the first machine basic block.
517 while (Token.is(MIToken::Newline))
519 if (Token.isErrorOrEOF())
520 return Token.isError();
521 // The first parsing pass should have verified that this token is a MBB label
522 // in the 'parseBasicBlockDefinitions' method.
523 assert(Token.is(MIToken::MachineBasicBlockLabel));
525 MachineBasicBlock *MBB = nullptr;
526 if (parseMBBReference(MBB))
528 if (parseBasicBlock(*MBB))
530 // The method 'parseBasicBlock' should parse the whole block until the next
531 // block or the end of file.
532 assert(Token.is(MIToken::MachineBasicBlockLabel) || Token.is(MIToken::Eof));
533 } while (Token.isNot(MIToken::Eof));
537 bool MIParser::parse(MachineInstr *&MI) {
538 // Parse any register operands before '='
539 MachineOperand MO = MachineOperand::CreateImm(0);
540 SmallVector<MachineOperandWithLocation, 8> Operands;
541 while (Token.isRegister() || Token.isRegisterFlag()) {
542 auto Loc = Token.location();
543 if (parseRegisterOperand(MO, /*IsDef=*/true))
545 Operands.push_back(MachineOperandWithLocation(MO, Loc, Token.location()));
546 if (Token.isNot(MIToken::comma))
550 if (!Operands.empty() && expectAndConsume(MIToken::equal))
553 unsigned OpCode, Flags = 0;
554 if (Token.isError() || parseInstruction(OpCode, Flags))
557 // Parse the remaining machine operands.
558 while (!Token.isNewlineOrEOF() && Token.isNot(MIToken::kw_debug_location) &&
559 Token.isNot(MIToken::coloncolon) && Token.isNot(MIToken::lbrace)) {
560 auto Loc = Token.location();
561 if (parseMachineOperandAndTargetFlags(MO))
563 Operands.push_back(MachineOperandWithLocation(MO, Loc, Token.location()));
564 if (Token.isNewlineOrEOF() || Token.is(MIToken::coloncolon) ||
565 Token.is(MIToken::lbrace))
567 if (Token.isNot(MIToken::comma))
568 return error("expected ',' before the next machine operand");
572 DebugLoc DebugLocation;
573 if (Token.is(MIToken::kw_debug_location)) {
575 if (Token.isNot(MIToken::exclaim))
576 return error("expected a metadata node after 'debug-location'");
577 MDNode *Node = nullptr;
578 if (parseMDNode(Node))
580 DebugLocation = DebugLoc(Node);
583 // Parse the machine memory operands.
584 SmallVector<MachineMemOperand *, 2> MemOperands;
585 if (Token.is(MIToken::coloncolon)) {
587 while (!Token.isNewlineOrEOF()) {
588 MachineMemOperand *MemOp = nullptr;
589 if (parseMachineMemoryOperand(MemOp))
591 MemOperands.push_back(MemOp);
592 if (Token.isNewlineOrEOF())
594 if (Token.isNot(MIToken::comma))
595 return error("expected ',' before the next machine memory operand");
600 const auto &MCID = MF.getSubtarget().getInstrInfo()->get(OpCode);
601 if (!MCID.isVariadic()) {
602 // FIXME: Move the implicit operand verification to the machine verifier.
603 if (verifyImplicitOperands(Operands, MCID))
607 // TODO: Check for extraneous machine operands.
608 MI = MF.CreateMachineInstr(MCID, DebugLocation, /*NoImplicit=*/true);
610 for (const auto &Operand : Operands)
611 MI->addOperand(MF, Operand.Operand);
612 if (MemOperands.empty())
614 MachineInstr::mmo_iterator MemRefs =
615 MF.allocateMemRefsArray(MemOperands.size());
616 std::copy(MemOperands.begin(), MemOperands.end(), MemRefs);
617 MI->setMemRefs(MemRefs, MemRefs + MemOperands.size());
621 bool MIParser::parseStandaloneMBB(MachineBasicBlock *&MBB) {
623 if (Token.isNot(MIToken::MachineBasicBlock))
624 return error("expected a machine basic block reference");
625 if (parseMBBReference(MBB))
628 if (Token.isNot(MIToken::Eof))
630 "expected end of string after the machine basic block reference");
634 bool MIParser::parseStandaloneNamedRegister(unsigned &Reg) {
636 if (Token.isNot(MIToken::NamedRegister))
637 return error("expected a named register");
638 if (parseRegister(Reg))
641 if (Token.isNot(MIToken::Eof))
642 return error("expected end of string after the register reference");
646 bool MIParser::parseStandaloneVirtualRegister(unsigned &Reg) {
648 if (Token.isNot(MIToken::VirtualRegister))
649 return error("expected a virtual register");
650 if (parseRegister(Reg))
653 if (Token.isNot(MIToken::Eof))
654 return error("expected end of string after the register reference");
658 static const char *printImplicitRegisterFlag(const MachineOperand &MO) {
659 assert(MO.isImplicit());
660 return MO.isDef() ? "implicit-def" : "implicit";
663 static std::string getRegisterName(const TargetRegisterInfo *TRI,
665 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "expected phys reg");
666 return StringRef(TRI->getName(Reg)).lower();
669 bool MIParser::verifyImplicitOperands(
670 ArrayRef<MachineOperandWithLocation> Operands, const MCInstrDesc &MCID) {
672 // We can't verify call instructions as they can contain arbitrary implicit
673 // register and register mask operands.
676 // Gather all the expected implicit operands.
677 SmallVector<MachineOperand, 4> ImplicitOperands;
678 if (MCID.ImplicitDefs)
679 for (const uint16_t *ImpDefs = MCID.getImplicitDefs(); *ImpDefs; ++ImpDefs)
680 ImplicitOperands.push_back(
681 MachineOperand::CreateReg(*ImpDefs, true, true));
682 if (MCID.ImplicitUses)
683 for (const uint16_t *ImpUses = MCID.getImplicitUses(); *ImpUses; ++ImpUses)
684 ImplicitOperands.push_back(
685 MachineOperand::CreateReg(*ImpUses, false, true));
687 const auto *TRI = MF.getSubtarget().getRegisterInfo();
688 assert(TRI && "Expected target register info");
689 size_t I = ImplicitOperands.size(), J = Operands.size();
694 const auto &ImplicitOperand = ImplicitOperands[I];
695 const auto &Operand = Operands[J].Operand;
696 if (ImplicitOperand.isIdenticalTo(Operand))
698 if (Operand.isReg() && Operand.isImplicit()) {
699 // Check if this implicit register is a subregister of an explicit
701 bool IsImplicitSubRegister = false;
702 for (size_t K = 0, E = Operands.size(); K < E; ++K) {
703 const auto &Op = Operands[K].Operand;
704 if (Op.isReg() && !Op.isImplicit() &&
705 TRI->isSubRegister(Op.getReg(), Operand.getReg())) {
706 IsImplicitSubRegister = true;
710 if (IsImplicitSubRegister)
712 return error(Operands[J].Begin,
713 Twine("expected an implicit register operand '") +
714 printImplicitRegisterFlag(ImplicitOperand) + " %" +
715 getRegisterName(TRI, ImplicitOperand.getReg()) + "'");
718 // TODO: Fix source location when Operands[J].end is right before '=', i.e:
719 // insead of reporting an error at this location:
722 // report the error at the following location:
725 return error(J < Operands.size() ? Operands[J].End : Token.location(),
726 Twine("missing implicit register operand '") +
727 printImplicitRegisterFlag(ImplicitOperands[I]) + " %" +
728 getRegisterName(TRI, ImplicitOperands[I].getReg()) + "'");
733 bool MIParser::parseInstruction(unsigned &OpCode, unsigned &Flags) {
734 if (Token.is(MIToken::kw_frame_setup)) {
735 Flags |= MachineInstr::FrameSetup;
738 if (Token.isNot(MIToken::Identifier))
739 return error("expected a machine instruction");
740 StringRef InstrName = Token.stringValue();
741 if (parseInstrName(InstrName, OpCode))
742 return error(Twine("unknown machine instruction name '") + InstrName + "'");
747 bool MIParser::parseRegister(unsigned &Reg) {
748 switch (Token.kind()) {
749 case MIToken::underscore:
752 case MIToken::NamedRegister: {
753 StringRef Name = Token.stringValue();
754 if (getRegisterByName(Name, Reg))
755 return error(Twine("unknown register name '") + Name + "'");
758 case MIToken::VirtualRegister: {
762 const auto RegInfo = PFS.VirtualRegisterSlots.find(ID);
763 if (RegInfo == PFS.VirtualRegisterSlots.end())
764 return error(Twine("use of undefined virtual register '%") + Twine(ID) +
766 Reg = RegInfo->second;
769 // TODO: Parse other register kinds.
771 llvm_unreachable("The current token should be a register");
776 bool MIParser::parseRegisterFlag(unsigned &Flags) {
777 const unsigned OldFlags = Flags;
778 switch (Token.kind()) {
779 case MIToken::kw_implicit:
780 Flags |= RegState::Implicit;
782 case MIToken::kw_implicit_define:
783 Flags |= RegState::ImplicitDefine;
785 case MIToken::kw_dead:
786 Flags |= RegState::Dead;
788 case MIToken::kw_killed:
789 Flags |= RegState::Kill;
791 case MIToken::kw_undef:
792 Flags |= RegState::Undef;
794 case MIToken::kw_internal:
795 Flags |= RegState::InternalRead;
797 case MIToken::kw_early_clobber:
798 Flags |= RegState::EarlyClobber;
800 case MIToken::kw_debug_use:
801 Flags |= RegState::Debug;
804 llvm_unreachable("The current token should be a register flag");
806 if (OldFlags == Flags)
807 // We know that the same flag is specified more than once when the flags
809 return error("duplicate '" + Token.stringValue() + "' register flag");
814 bool MIParser::parseSubRegisterIndex(unsigned &SubReg) {
815 assert(Token.is(MIToken::colon));
817 if (Token.isNot(MIToken::Identifier))
818 return error("expected a subregister index after ':'");
819 auto Name = Token.stringValue();
820 SubReg = getSubRegIndex(Name);
822 return error(Twine("use of unknown subregister index '") + Name + "'");
827 bool MIParser::parseRegisterOperand(MachineOperand &Dest, bool IsDef) {
829 unsigned Flags = IsDef ? RegState::Define : 0;
830 while (Token.isRegisterFlag()) {
831 if (parseRegisterFlag(Flags))
834 if (!Token.isRegister())
835 return error("expected a register after register flags");
836 if (parseRegister(Reg))
840 if (Token.is(MIToken::colon)) {
841 if (parseSubRegisterIndex(SubReg))
844 Dest = MachineOperand::CreateReg(
845 Reg, Flags & RegState::Define, Flags & RegState::Implicit,
846 Flags & RegState::Kill, Flags & RegState::Dead, Flags & RegState::Undef,
847 Flags & RegState::EarlyClobber, SubReg, Flags & RegState::Debug,
848 Flags & RegState::InternalRead);
852 bool MIParser::parseImmediateOperand(MachineOperand &Dest) {
853 assert(Token.is(MIToken::IntegerLiteral));
854 const APSInt &Int = Token.integerValue();
855 if (Int.getMinSignedBits() > 64)
856 return error("integer literal is too large to be an immediate operand");
857 Dest = MachineOperand::CreateImm(Int.getExtValue());
862 bool MIParser::parseIRConstant(StringRef::iterator Loc, const Constant *&C) {
863 auto Source = StringRef(Loc, Token.range().end() - Loc).str();
866 C = parseConstantValue(Source.c_str(), Err, *MF.getFunction()->getParent());
868 return error(Loc + Err.getColumnNo(), Err.getMessage());
872 bool MIParser::parseTypedImmediateOperand(MachineOperand &Dest) {
873 assert(Token.is(MIToken::IntegerType));
874 auto Loc = Token.location();
876 if (Token.isNot(MIToken::IntegerLiteral))
877 return error("expected an integer literal");
878 const Constant *C = nullptr;
879 if (parseIRConstant(Loc, C))
881 Dest = MachineOperand::CreateCImm(cast<ConstantInt>(C));
885 bool MIParser::parseFPImmediateOperand(MachineOperand &Dest) {
886 auto Loc = Token.location();
888 if (Token.isNot(MIToken::FloatingPointLiteral))
889 return error("expected a floating point literal");
890 const Constant *C = nullptr;
891 if (parseIRConstant(Loc, C))
893 Dest = MachineOperand::CreateFPImm(cast<ConstantFP>(C));
897 bool MIParser::getUnsigned(unsigned &Result) {
898 assert(Token.hasIntegerValue() && "Expected a token with an integer value");
899 const uint64_t Limit = uint64_t(std::numeric_limits<unsigned>::max()) + 1;
900 uint64_t Val64 = Token.integerValue().getLimitedValue(Limit);
902 return error("expected 32-bit integer (too large)");
907 bool MIParser::parseMBBReference(MachineBasicBlock *&MBB) {
908 assert(Token.is(MIToken::MachineBasicBlock) ||
909 Token.is(MIToken::MachineBasicBlockLabel));
911 if (getUnsigned(Number))
913 auto MBBInfo = PFS.MBBSlots.find(Number);
914 if (MBBInfo == PFS.MBBSlots.end())
915 return error(Twine("use of undefined machine basic block #") +
917 MBB = MBBInfo->second;
918 if (!Token.stringValue().empty() && Token.stringValue() != MBB->getName())
919 return error(Twine("the name of machine basic block #") + Twine(Number) +
920 " isn't '" + Token.stringValue() + "'");
924 bool MIParser::parseMBBOperand(MachineOperand &Dest) {
925 MachineBasicBlock *MBB;
926 if (parseMBBReference(MBB))
928 Dest = MachineOperand::CreateMBB(MBB);
933 bool MIParser::parseStackFrameIndex(int &FI) {
934 assert(Token.is(MIToken::StackObject));
938 auto ObjectInfo = PFS.StackObjectSlots.find(ID);
939 if (ObjectInfo == PFS.StackObjectSlots.end())
940 return error(Twine("use of undefined stack object '%stack.") + Twine(ID) +
943 if (const auto *Alloca =
944 MF.getFrameInfo()->getObjectAllocation(ObjectInfo->second))
945 Name = Alloca->getName();
946 if (!Token.stringValue().empty() && Token.stringValue() != Name)
947 return error(Twine("the name of the stack object '%stack.") + Twine(ID) +
948 "' isn't '" + Token.stringValue() + "'");
950 FI = ObjectInfo->second;
954 bool MIParser::parseStackObjectOperand(MachineOperand &Dest) {
956 if (parseStackFrameIndex(FI))
958 Dest = MachineOperand::CreateFI(FI);
962 bool MIParser::parseFixedStackFrameIndex(int &FI) {
963 assert(Token.is(MIToken::FixedStackObject));
967 auto ObjectInfo = PFS.FixedStackObjectSlots.find(ID);
968 if (ObjectInfo == PFS.FixedStackObjectSlots.end())
969 return error(Twine("use of undefined fixed stack object '%fixed-stack.") +
972 FI = ObjectInfo->second;
976 bool MIParser::parseFixedStackObjectOperand(MachineOperand &Dest) {
978 if (parseFixedStackFrameIndex(FI))
980 Dest = MachineOperand::CreateFI(FI);
984 bool MIParser::parseGlobalValue(GlobalValue *&GV) {
985 switch (Token.kind()) {
986 case MIToken::NamedGlobalValue: {
987 const Module *M = MF.getFunction()->getParent();
988 GV = M->getNamedValue(Token.stringValue());
990 return error(Twine("use of undefined global value '") + Token.range() +
994 case MIToken::GlobalValue: {
996 if (getUnsigned(GVIdx))
998 if (GVIdx >= IRSlots.GlobalValues.size())
999 return error(Twine("use of undefined global value '@") + Twine(GVIdx) +
1001 GV = IRSlots.GlobalValues[GVIdx];
1005 llvm_unreachable("The current token should be a global value");
1010 bool MIParser::parseGlobalAddressOperand(MachineOperand &Dest) {
1011 GlobalValue *GV = nullptr;
1012 if (parseGlobalValue(GV))
1015 Dest = MachineOperand::CreateGA(GV, /*Offset=*/0);
1016 if (parseOperandsOffset(Dest))
1021 bool MIParser::parseConstantPoolIndexOperand(MachineOperand &Dest) {
1022 assert(Token.is(MIToken::ConstantPoolItem));
1024 if (getUnsigned(ID))
1026 auto ConstantInfo = PFS.ConstantPoolSlots.find(ID);
1027 if (ConstantInfo == PFS.ConstantPoolSlots.end())
1028 return error("use of undefined constant '%const." + Twine(ID) + "'");
1030 Dest = MachineOperand::CreateCPI(ID, /*Offset=*/0);
1031 if (parseOperandsOffset(Dest))
1036 bool MIParser::parseJumpTableIndexOperand(MachineOperand &Dest) {
1037 assert(Token.is(MIToken::JumpTableIndex));
1039 if (getUnsigned(ID))
1041 auto JumpTableEntryInfo = PFS.JumpTableSlots.find(ID);
1042 if (JumpTableEntryInfo == PFS.JumpTableSlots.end())
1043 return error("use of undefined jump table '%jump-table." + Twine(ID) + "'");
1045 Dest = MachineOperand::CreateJTI(JumpTableEntryInfo->second);
1049 bool MIParser::parseExternalSymbolOperand(MachineOperand &Dest) {
1050 assert(Token.is(MIToken::ExternalSymbol));
1051 const char *Symbol = MF.createExternalSymbolName(Token.stringValue());
1053 Dest = MachineOperand::CreateES(Symbol);
1054 if (parseOperandsOffset(Dest))
1059 bool MIParser::parseMDNode(MDNode *&Node) {
1060 assert(Token.is(MIToken::exclaim));
1061 auto Loc = Token.location();
1063 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
1064 return error("expected metadata id after '!'");
1066 if (getUnsigned(ID))
1068 auto NodeInfo = IRSlots.MetadataNodes.find(ID);
1069 if (NodeInfo == IRSlots.MetadataNodes.end())
1070 return error(Loc, "use of undefined metadata '!" + Twine(ID) + "'");
1072 Node = NodeInfo->second.get();
1076 bool MIParser::parseMetadataOperand(MachineOperand &Dest) {
1077 MDNode *Node = nullptr;
1078 if (parseMDNode(Node))
1080 Dest = MachineOperand::CreateMetadata(Node);
1084 bool MIParser::parseCFIOffset(int &Offset) {
1085 if (Token.isNot(MIToken::IntegerLiteral))
1086 return error("expected a cfi offset");
1087 if (Token.integerValue().getMinSignedBits() > 32)
1088 return error("expected a 32 bit integer (the cfi offset is too large)");
1089 Offset = (int)Token.integerValue().getExtValue();
1094 bool MIParser::parseCFIRegister(unsigned &Reg) {
1095 if (Token.isNot(MIToken::NamedRegister))
1096 return error("expected a cfi register");
1098 if (parseRegister(LLVMReg))
1100 const auto *TRI = MF.getSubtarget().getRegisterInfo();
1101 assert(TRI && "Expected target register info");
1102 int DwarfReg = TRI->getDwarfRegNum(LLVMReg, true);
1104 return error("invalid DWARF register");
1105 Reg = (unsigned)DwarfReg;
1110 bool MIParser::parseCFIOperand(MachineOperand &Dest) {
1111 auto Kind = Token.kind();
1113 auto &MMI = MF.getMMI();
1118 case MIToken::kw_cfi_same_value:
1119 if (parseCFIRegister(Reg))
1122 MMI.addFrameInst(MCCFIInstruction::createSameValue(nullptr, Reg));
1124 case MIToken::kw_cfi_offset:
1125 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
1126 parseCFIOffset(Offset))
1129 MMI.addFrameInst(MCCFIInstruction::createOffset(nullptr, Reg, Offset));
1131 case MIToken::kw_cfi_def_cfa_register:
1132 if (parseCFIRegister(Reg))
1135 MMI.addFrameInst(MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
1137 case MIToken::kw_cfi_def_cfa_offset:
1138 if (parseCFIOffset(Offset))
1140 // NB: MCCFIInstruction::createDefCfaOffset negates the offset.
1141 CFIIndex = MMI.addFrameInst(
1142 MCCFIInstruction::createDefCfaOffset(nullptr, -Offset));
1144 case MIToken::kw_cfi_def_cfa:
1145 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
1146 parseCFIOffset(Offset))
1148 // NB: MCCFIInstruction::createDefCfa negates the offset.
1150 MMI.addFrameInst(MCCFIInstruction::createDefCfa(nullptr, Reg, -Offset));
1153 // TODO: Parse the other CFI operands.
1154 llvm_unreachable("The current token should be a cfi operand");
1156 Dest = MachineOperand::CreateCFIIndex(CFIIndex);
1160 bool MIParser::parseIRBlock(BasicBlock *&BB, const Function &F) {
1161 switch (Token.kind()) {
1162 case MIToken::NamedIRBlock: {
1163 BB = dyn_cast_or_null<BasicBlock>(
1164 F.getValueSymbolTable().lookup(Token.stringValue()));
1166 return error(Twine("use of undefined IR block '") + Token.range() + "'");
1169 case MIToken::IRBlock: {
1170 unsigned SlotNumber = 0;
1171 if (getUnsigned(SlotNumber))
1173 BB = const_cast<BasicBlock *>(getIRBlock(SlotNumber, F));
1175 return error(Twine("use of undefined IR block '%ir-block.") +
1176 Twine(SlotNumber) + "'");
1180 llvm_unreachable("The current token should be an IR block reference");
1185 bool MIParser::parseBlockAddressOperand(MachineOperand &Dest) {
1186 assert(Token.is(MIToken::kw_blockaddress));
1188 if (expectAndConsume(MIToken::lparen))
1190 if (Token.isNot(MIToken::GlobalValue) &&
1191 Token.isNot(MIToken::NamedGlobalValue))
1192 return error("expected a global value");
1193 GlobalValue *GV = nullptr;
1194 if (parseGlobalValue(GV))
1196 auto *F = dyn_cast<Function>(GV);
1198 return error("expected an IR function reference");
1200 if (expectAndConsume(MIToken::comma))
1202 BasicBlock *BB = nullptr;
1203 if (Token.isNot(MIToken::IRBlock) && Token.isNot(MIToken::NamedIRBlock))
1204 return error("expected an IR block reference");
1205 if (parseIRBlock(BB, *F))
1208 if (expectAndConsume(MIToken::rparen))
1210 Dest = MachineOperand::CreateBA(BlockAddress::get(F, BB), /*Offset=*/0);
1211 if (parseOperandsOffset(Dest))
1216 bool MIParser::parseTargetIndexOperand(MachineOperand &Dest) {
1217 assert(Token.is(MIToken::kw_target_index));
1219 if (expectAndConsume(MIToken::lparen))
1221 if (Token.isNot(MIToken::Identifier))
1222 return error("expected the name of the target index");
1224 if (getTargetIndex(Token.stringValue(), Index))
1225 return error("use of undefined target index '" + Token.stringValue() + "'");
1227 if (expectAndConsume(MIToken::rparen))
1229 Dest = MachineOperand::CreateTargetIndex(unsigned(Index), /*Offset=*/0);
1230 if (parseOperandsOffset(Dest))
1235 bool MIParser::parseLiveoutRegisterMaskOperand(MachineOperand &Dest) {
1236 assert(Token.is(MIToken::kw_liveout));
1237 const auto *TRI = MF.getSubtarget().getRegisterInfo();
1238 assert(TRI && "Expected target register info");
1239 uint32_t *Mask = MF.allocateRegisterMask(TRI->getNumRegs());
1241 if (expectAndConsume(MIToken::lparen))
1244 if (Token.isNot(MIToken::NamedRegister))
1245 return error("expected a named register");
1247 if (parseRegister(Reg))
1250 Mask[Reg / 32] |= 1U << (Reg % 32);
1251 // TODO: Report an error if the same register is used more than once.
1252 if (Token.isNot(MIToken::comma))
1256 if (expectAndConsume(MIToken::rparen))
1258 Dest = MachineOperand::CreateRegLiveOut(Mask);
1262 bool MIParser::parseMachineOperand(MachineOperand &Dest) {
1263 switch (Token.kind()) {
1264 case MIToken::kw_implicit:
1265 case MIToken::kw_implicit_define:
1266 case MIToken::kw_dead:
1267 case MIToken::kw_killed:
1268 case MIToken::kw_undef:
1269 case MIToken::kw_internal:
1270 case MIToken::kw_early_clobber:
1271 case MIToken::kw_debug_use:
1272 case MIToken::underscore:
1273 case MIToken::NamedRegister:
1274 case MIToken::VirtualRegister:
1275 return parseRegisterOperand(Dest);
1276 case MIToken::IntegerLiteral:
1277 return parseImmediateOperand(Dest);
1278 case MIToken::IntegerType:
1279 return parseTypedImmediateOperand(Dest);
1280 case MIToken::kw_half:
1281 case MIToken::kw_float:
1282 case MIToken::kw_double:
1283 case MIToken::kw_x86_fp80:
1284 case MIToken::kw_fp128:
1285 case MIToken::kw_ppc_fp128:
1286 return parseFPImmediateOperand(Dest);
1287 case MIToken::MachineBasicBlock:
1288 return parseMBBOperand(Dest);
1289 case MIToken::StackObject:
1290 return parseStackObjectOperand(Dest);
1291 case MIToken::FixedStackObject:
1292 return parseFixedStackObjectOperand(Dest);
1293 case MIToken::GlobalValue:
1294 case MIToken::NamedGlobalValue:
1295 return parseGlobalAddressOperand(Dest);
1296 case MIToken::ConstantPoolItem:
1297 return parseConstantPoolIndexOperand(Dest);
1298 case MIToken::JumpTableIndex:
1299 return parseJumpTableIndexOperand(Dest);
1300 case MIToken::ExternalSymbol:
1301 return parseExternalSymbolOperand(Dest);
1302 case MIToken::exclaim:
1303 return parseMetadataOperand(Dest);
1304 case MIToken::kw_cfi_same_value:
1305 case MIToken::kw_cfi_offset:
1306 case MIToken::kw_cfi_def_cfa_register:
1307 case MIToken::kw_cfi_def_cfa_offset:
1308 case MIToken::kw_cfi_def_cfa:
1309 return parseCFIOperand(Dest);
1310 case MIToken::kw_blockaddress:
1311 return parseBlockAddressOperand(Dest);
1312 case MIToken::kw_target_index:
1313 return parseTargetIndexOperand(Dest);
1314 case MIToken::kw_liveout:
1315 return parseLiveoutRegisterMaskOperand(Dest);
1316 case MIToken::Error:
1318 case MIToken::Identifier:
1319 if (const auto *RegMask = getRegMask(Token.stringValue())) {
1320 Dest = MachineOperand::CreateRegMask(RegMask);
1326 // TODO: parse the other machine operands.
1327 return error("expected a machine operand");
1332 bool MIParser::parseMachineOperandAndTargetFlags(MachineOperand &Dest) {
1334 bool HasTargetFlags = false;
1335 if (Token.is(MIToken::kw_target_flags)) {
1336 HasTargetFlags = true;
1338 if (expectAndConsume(MIToken::lparen))
1340 if (Token.isNot(MIToken::Identifier))
1341 return error("expected the name of the target flag");
1342 if (getDirectTargetFlag(Token.stringValue(), TF))
1343 return error("use of undefined target flag '" + Token.stringValue() +
1346 // TODO: Parse target's bit target flags.
1347 if (expectAndConsume(MIToken::rparen))
1350 auto Loc = Token.location();
1351 if (parseMachineOperand(Dest))
1353 if (!HasTargetFlags)
1356 return error(Loc, "register operands can't have target flags");
1357 Dest.setTargetFlags(TF);
1361 bool MIParser::parseOffset(int64_t &Offset) {
1362 if (Token.isNot(MIToken::plus) && Token.isNot(MIToken::minus))
1364 StringRef Sign = Token.range();
1365 bool IsNegative = Token.is(MIToken::minus);
1367 if (Token.isNot(MIToken::IntegerLiteral))
1368 return error("expected an integer literal after '" + Sign + "'");
1369 if (Token.integerValue().getMinSignedBits() > 64)
1370 return error("expected 64-bit integer (too large)");
1371 Offset = Token.integerValue().getExtValue();
1378 bool MIParser::parseAlignment(unsigned &Alignment) {
1379 assert(Token.is(MIToken::kw_align));
1381 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
1382 return error("expected an integer literal after 'align'");
1383 if (getUnsigned(Alignment))
1389 bool MIParser::parseOperandsOffset(MachineOperand &Op) {
1391 if (parseOffset(Offset))
1393 Op.setOffset(Offset);
1397 bool MIParser::parseIRValue(Value *&V) {
1398 switch (Token.kind()) {
1399 case MIToken::NamedIRValue: {
1400 V = MF.getFunction()->getValueSymbolTable().lookup(Token.stringValue());
1402 V = MF.getFunction()->getParent()->getValueSymbolTable().lookup(
1403 Token.stringValue());
1405 return error(Twine("use of undefined IR value '") + Token.range() + "'");
1408 // TODO: Parse unnamed IR value references.
1410 llvm_unreachable("The current token should be an IR block reference");
1415 bool MIParser::getUint64(uint64_t &Result) {
1416 assert(Token.hasIntegerValue());
1417 if (Token.integerValue().getActiveBits() > 64)
1418 return error("expected 64-bit integer (too large)");
1419 Result = Token.integerValue().getZExtValue();
1423 bool MIParser::parseMemoryOperandFlag(unsigned &Flags) {
1424 const unsigned OldFlags = Flags;
1425 switch (Token.kind()) {
1426 case MIToken::kw_volatile:
1427 Flags |= MachineMemOperand::MOVolatile;
1429 case MIToken::kw_non_temporal:
1430 Flags |= MachineMemOperand::MONonTemporal;
1432 case MIToken::kw_invariant:
1433 Flags |= MachineMemOperand::MOInvariant;
1435 // TODO: parse the target specific memory operand flags.
1437 llvm_unreachable("The current token should be a memory operand flag");
1439 if (OldFlags == Flags)
1440 // We know that the same flag is specified more than once when the flags
1441 // weren't modified.
1442 return error("duplicate '" + Token.stringValue() + "' memory operand flag");
1447 bool MIParser::parseMemoryPseudoSourceValue(const PseudoSourceValue *&PSV) {
1448 switch (Token.kind()) {
1449 case MIToken::kw_stack:
1450 PSV = MF.getPSVManager().getStack();
1452 case MIToken::kw_got:
1453 PSV = MF.getPSVManager().getGOT();
1455 case MIToken::kw_jump_table:
1456 PSV = MF.getPSVManager().getJumpTable();
1458 case MIToken::kw_constant_pool:
1459 PSV = MF.getPSVManager().getConstantPool();
1461 case MIToken::FixedStackObject: {
1463 if (parseFixedStackFrameIndex(FI))
1465 PSV = MF.getPSVManager().getFixedStack(FI);
1466 // The token was already consumed, so use return here instead of break.
1469 case MIToken::GlobalValue:
1470 case MIToken::NamedGlobalValue: {
1471 GlobalValue *GV = nullptr;
1472 if (parseGlobalValue(GV))
1474 PSV = MF.getPSVManager().getGlobalValueCallEntry(GV);
1477 case MIToken::ExternalSymbol:
1478 PSV = MF.getPSVManager().getExternalSymbolCallEntry(
1479 MF.createExternalSymbolName(Token.stringValue()));
1482 llvm_unreachable("The current token should be pseudo source value");
1488 bool MIParser::parseMachinePointerInfo(MachinePointerInfo &Dest) {
1489 if (Token.is(MIToken::kw_constant_pool) || Token.is(MIToken::kw_stack) ||
1490 Token.is(MIToken::kw_got) || Token.is(MIToken::kw_jump_table) ||
1491 Token.is(MIToken::FixedStackObject) || Token.is(MIToken::GlobalValue) ||
1492 Token.is(MIToken::NamedGlobalValue) ||
1493 Token.is(MIToken::ExternalSymbol)) {
1494 const PseudoSourceValue *PSV = nullptr;
1495 if (parseMemoryPseudoSourceValue(PSV))
1498 if (parseOffset(Offset))
1500 Dest = MachinePointerInfo(PSV, Offset);
1503 if (Token.isNot(MIToken::NamedIRValue))
1504 return error("expected an IR value reference");
1506 if (parseIRValue(V))
1508 if (!V->getType()->isPointerTy())
1509 return error("expected a pointer IR value");
1512 if (parseOffset(Offset))
1514 Dest = MachinePointerInfo(V, Offset);
1518 bool MIParser::parseMachineMemoryOperand(MachineMemOperand *&Dest) {
1519 if (expectAndConsume(MIToken::lparen))
1522 while (Token.isMemoryOperandFlag()) {
1523 if (parseMemoryOperandFlag(Flags))
1526 if (Token.isNot(MIToken::Identifier) ||
1527 (Token.stringValue() != "load" && Token.stringValue() != "store"))
1528 return error("expected 'load' or 'store' memory operation");
1529 if (Token.stringValue() == "load")
1530 Flags |= MachineMemOperand::MOLoad;
1532 Flags |= MachineMemOperand::MOStore;
1535 if (Token.isNot(MIToken::IntegerLiteral))
1536 return error("expected the size integer literal after memory operation");
1538 if (getUint64(Size))
1542 const char *Word = Flags & MachineMemOperand::MOLoad ? "from" : "into";
1543 if (Token.isNot(MIToken::Identifier) || Token.stringValue() != Word)
1544 return error(Twine("expected '") + Word + "'");
1547 MachinePointerInfo Ptr = MachinePointerInfo();
1548 if (parseMachinePointerInfo(Ptr))
1550 unsigned BaseAlignment = Size;
1552 MDNode *Range = nullptr;
1553 while (consumeIfPresent(MIToken::comma)) {
1554 switch (Token.kind()) {
1555 case MIToken::kw_align:
1556 if (parseAlignment(BaseAlignment))
1559 case MIToken::md_tbaa:
1561 if (parseMDNode(AAInfo.TBAA))
1564 case MIToken::md_alias_scope:
1566 if (parseMDNode(AAInfo.Scope))
1569 case MIToken::md_noalias:
1571 if (parseMDNode(AAInfo.NoAlias))
1574 case MIToken::md_range:
1576 if (parseMDNode(Range))
1579 // TODO: Report an error on duplicate metadata nodes.
1581 return error("expected 'align' or '!tbaa' or '!alias.scope' or "
1582 "'!noalias' or '!range'");
1585 if (expectAndConsume(MIToken::rparen))
1588 MF.getMachineMemOperand(Ptr, Flags, Size, BaseAlignment, AAInfo, Range);
1592 void MIParser::initNames2InstrOpCodes() {
1593 if (!Names2InstrOpCodes.empty())
1595 const auto *TII = MF.getSubtarget().getInstrInfo();
1596 assert(TII && "Expected target instruction info");
1597 for (unsigned I = 0, E = TII->getNumOpcodes(); I < E; ++I)
1598 Names2InstrOpCodes.insert(std::make_pair(StringRef(TII->getName(I)), I));
1601 bool MIParser::parseInstrName(StringRef InstrName, unsigned &OpCode) {
1602 initNames2InstrOpCodes();
1603 auto InstrInfo = Names2InstrOpCodes.find(InstrName);
1604 if (InstrInfo == Names2InstrOpCodes.end())
1606 OpCode = InstrInfo->getValue();
1610 void MIParser::initNames2Regs() {
1611 if (!Names2Regs.empty())
1613 // The '%noreg' register is the register 0.
1614 Names2Regs.insert(std::make_pair("noreg", 0));
1615 const auto *TRI = MF.getSubtarget().getRegisterInfo();
1616 assert(TRI && "Expected target register info");
1617 for (unsigned I = 0, E = TRI->getNumRegs(); I < E; ++I) {
1619 Names2Regs.insert(std::make_pair(StringRef(TRI->getName(I)).lower(), I))
1622 assert(WasInserted && "Expected registers to be unique case-insensitively");
1626 bool MIParser::getRegisterByName(StringRef RegName, unsigned &Reg) {
1628 auto RegInfo = Names2Regs.find(RegName);
1629 if (RegInfo == Names2Regs.end())
1631 Reg = RegInfo->getValue();
1635 void MIParser::initNames2RegMasks() {
1636 if (!Names2RegMasks.empty())
1638 const auto *TRI = MF.getSubtarget().getRegisterInfo();
1639 assert(TRI && "Expected target register info");
1640 ArrayRef<const uint32_t *> RegMasks = TRI->getRegMasks();
1641 ArrayRef<const char *> RegMaskNames = TRI->getRegMaskNames();
1642 assert(RegMasks.size() == RegMaskNames.size());
1643 for (size_t I = 0, E = RegMasks.size(); I < E; ++I)
1644 Names2RegMasks.insert(
1645 std::make_pair(StringRef(RegMaskNames[I]).lower(), RegMasks[I]));
1648 const uint32_t *MIParser::getRegMask(StringRef Identifier) {
1649 initNames2RegMasks();
1650 auto RegMaskInfo = Names2RegMasks.find(Identifier);
1651 if (RegMaskInfo == Names2RegMasks.end())
1653 return RegMaskInfo->getValue();
1656 void MIParser::initNames2SubRegIndices() {
1657 if (!Names2SubRegIndices.empty())
1659 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1660 for (unsigned I = 1, E = TRI->getNumSubRegIndices(); I < E; ++I)
1661 Names2SubRegIndices.insert(
1662 std::make_pair(StringRef(TRI->getSubRegIndexName(I)).lower(), I));
1665 unsigned MIParser::getSubRegIndex(StringRef Name) {
1666 initNames2SubRegIndices();
1667 auto SubRegInfo = Names2SubRegIndices.find(Name);
1668 if (SubRegInfo == Names2SubRegIndices.end())
1670 return SubRegInfo->getValue();
1673 static void initSlots2BasicBlocks(
1675 DenseMap<unsigned, const BasicBlock *> &Slots2BasicBlocks) {
1676 ModuleSlotTracker MST(F.getParent(), /*ShouldInitializeAllMetadata=*/false);
1677 MST.incorporateFunction(F);
1678 for (auto &BB : F) {
1681 int Slot = MST.getLocalSlot(&BB);
1684 Slots2BasicBlocks.insert(std::make_pair(unsigned(Slot), &BB));
1688 static const BasicBlock *getIRBlockFromSlot(
1690 const DenseMap<unsigned, const BasicBlock *> &Slots2BasicBlocks) {
1691 auto BlockInfo = Slots2BasicBlocks.find(Slot);
1692 if (BlockInfo == Slots2BasicBlocks.end())
1694 return BlockInfo->second;
1697 const BasicBlock *MIParser::getIRBlock(unsigned Slot) {
1698 if (Slots2BasicBlocks.empty())
1699 initSlots2BasicBlocks(*MF.getFunction(), Slots2BasicBlocks);
1700 return getIRBlockFromSlot(Slot, Slots2BasicBlocks);
1703 const BasicBlock *MIParser::getIRBlock(unsigned Slot, const Function &F) {
1704 if (&F == MF.getFunction())
1705 return getIRBlock(Slot);
1706 DenseMap<unsigned, const BasicBlock *> CustomSlots2BasicBlocks;
1707 initSlots2BasicBlocks(F, CustomSlots2BasicBlocks);
1708 return getIRBlockFromSlot(Slot, CustomSlots2BasicBlocks);
1711 void MIParser::initNames2TargetIndices() {
1712 if (!Names2TargetIndices.empty())
1714 const auto *TII = MF.getSubtarget().getInstrInfo();
1715 assert(TII && "Expected target instruction info");
1716 auto Indices = TII->getSerializableTargetIndices();
1717 for (const auto &I : Indices)
1718 Names2TargetIndices.insert(std::make_pair(StringRef(I.second), I.first));
1721 bool MIParser::getTargetIndex(StringRef Name, int &Index) {
1722 initNames2TargetIndices();
1723 auto IndexInfo = Names2TargetIndices.find(Name);
1724 if (IndexInfo == Names2TargetIndices.end())
1726 Index = IndexInfo->second;
1730 void MIParser::initNames2DirectTargetFlags() {
1731 if (!Names2DirectTargetFlags.empty())
1733 const auto *TII = MF.getSubtarget().getInstrInfo();
1734 assert(TII && "Expected target instruction info");
1735 auto Flags = TII->getSerializableDirectMachineOperandTargetFlags();
1736 for (const auto &I : Flags)
1737 Names2DirectTargetFlags.insert(
1738 std::make_pair(StringRef(I.second), I.first));
1741 bool MIParser::getDirectTargetFlag(StringRef Name, unsigned &Flag) {
1742 initNames2DirectTargetFlags();
1743 auto FlagInfo = Names2DirectTargetFlags.find(Name);
1744 if (FlagInfo == Names2DirectTargetFlags.end())
1746 Flag = FlagInfo->second;
1750 bool llvm::parseMachineBasicBlockDefinitions(MachineFunction &MF, StringRef Src,
1751 PerFunctionMIParsingState &PFS,
1752 const SlotMapping &IRSlots,
1753 SMDiagnostic &Error) {
1755 SM.AddNewSourceBuffer(
1756 MemoryBuffer::getMemBuffer(Src, "", /*RequiresNullTerminator=*/false),
1758 return MIParser(SM, MF, Error, Src, PFS, IRSlots)
1759 .parseBasicBlockDefinitions(PFS.MBBSlots);
1762 bool llvm::parseMachineInstructions(MachineFunction &MF, StringRef Src,
1763 const PerFunctionMIParsingState &PFS,
1764 const SlotMapping &IRSlots,
1765 SMDiagnostic &Error) {
1767 SM.AddNewSourceBuffer(
1768 MemoryBuffer::getMemBuffer(Src, "", /*RequiresNullTerminator=*/false),
1770 return MIParser(SM, MF, Error, Src, PFS, IRSlots).parseBasicBlocks();
1773 bool llvm::parseMBBReference(MachineBasicBlock *&MBB, SourceMgr &SM,
1774 MachineFunction &MF, StringRef Src,
1775 const PerFunctionMIParsingState &PFS,
1776 const SlotMapping &IRSlots, SMDiagnostic &Error) {
1777 return MIParser(SM, MF, Error, Src, PFS, IRSlots).parseStandaloneMBB(MBB);
1780 bool llvm::parseNamedRegisterReference(unsigned &Reg, SourceMgr &SM,
1781 MachineFunction &MF, StringRef Src,
1782 const PerFunctionMIParsingState &PFS,
1783 const SlotMapping &IRSlots,
1784 SMDiagnostic &Error) {
1785 return MIParser(SM, MF, Error, Src, PFS, IRSlots)
1786 .parseStandaloneNamedRegister(Reg);
1789 bool llvm::parseVirtualRegisterReference(unsigned &Reg, SourceMgr &SM,
1790 MachineFunction &MF, StringRef Src,
1791 const PerFunctionMIParsingState &PFS,
1792 const SlotMapping &IRSlots,
1793 SMDiagnostic &Error) {
1794 return MIParser(SM, MF, Error, Src, PFS, IRSlots)
1795 .parseStandaloneVirtualRegister(Reg);