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;
75 MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
76 StringRef Source, const PerFunctionMIParsingState &PFS,
77 const SlotMapping &IRSlots);
81 /// Report an error at the current location with the given message.
83 /// This function always return true.
84 bool error(const Twine &Msg);
86 /// Report an error at the given location with the given message.
88 /// This function always return true.
89 bool error(StringRef::iterator Loc, const Twine &Msg);
91 bool parse(MachineInstr *&MI);
92 bool parseStandaloneMBB(MachineBasicBlock *&MBB);
93 bool parseStandaloneNamedRegister(unsigned &Reg);
94 bool parseStandaloneVirtualRegister(unsigned &Reg);
95 bool parseStandaloneIRBlockReference(const BasicBlock *&BB);
97 bool parseRegister(unsigned &Reg);
98 bool parseRegisterFlag(unsigned &Flags);
99 bool parseSubRegisterIndex(unsigned &SubReg);
100 bool parseRegisterOperand(MachineOperand &Dest, bool IsDef = false);
101 bool parseImmediateOperand(MachineOperand &Dest);
102 bool parseIRConstant(StringRef::iterator Loc, const Constant *&C);
103 bool parseFPImmediateOperand(MachineOperand &Dest);
104 bool parseMBBReference(MachineBasicBlock *&MBB);
105 bool parseMBBOperand(MachineOperand &Dest);
106 bool parseStackObjectOperand(MachineOperand &Dest);
107 bool parseFixedStackObjectOperand(MachineOperand &Dest);
108 bool parseGlobalValue(GlobalValue *&GV);
109 bool parseGlobalAddressOperand(MachineOperand &Dest);
110 bool parseConstantPoolIndexOperand(MachineOperand &Dest);
111 bool parseJumpTableIndexOperand(MachineOperand &Dest);
112 bool parseExternalSymbolOperand(MachineOperand &Dest);
113 bool parseMDNode(MDNode *&Node);
114 bool parseMetadataOperand(MachineOperand &Dest);
115 bool parseCFIOffset(int &Offset);
116 bool parseCFIRegister(unsigned &Reg);
117 bool parseCFIOperand(MachineOperand &Dest);
118 bool parseIRBlock(BasicBlock *&BB, const Function &F);
119 bool parseBlockAddressOperand(MachineOperand &Dest);
120 bool parseTargetIndexOperand(MachineOperand &Dest);
121 bool parseMachineOperand(MachineOperand &Dest);
122 bool parseIRValue(Value *&V);
123 bool parseMemoryOperandFlag(unsigned &Flags);
124 bool parseMachineMemoryOperand(MachineMemOperand *&Dest);
127 /// Convert the integer literal in the current token into an unsigned integer.
129 /// Return true if an error occurred.
130 bool getUnsigned(unsigned &Result);
132 /// Convert the integer literal in the current token into an uint64.
134 /// Return true if an error occurred.
135 bool getUint64(uint64_t &Result);
137 /// If the current token is of the given kind, consume it and return false.
138 /// Otherwise report an error and return true.
139 bool expectAndConsume(MIToken::TokenKind TokenKind);
141 void initNames2InstrOpCodes();
143 /// Try to convert an instruction name to an opcode. Return true if the
144 /// instruction name is invalid.
145 bool parseInstrName(StringRef InstrName, unsigned &OpCode);
147 bool parseInstruction(unsigned &OpCode, unsigned &Flags);
149 bool verifyImplicitOperands(ArrayRef<MachineOperandWithLocation> Operands,
150 const MCInstrDesc &MCID);
152 void initNames2Regs();
154 /// Try to convert a register name to a register number. Return true if the
155 /// register name is invalid.
156 bool getRegisterByName(StringRef RegName, unsigned &Reg);
158 void initNames2RegMasks();
160 /// Check if the given identifier is a name of a register mask.
162 /// Return null if the identifier isn't a register mask.
163 const uint32_t *getRegMask(StringRef Identifier);
165 void initNames2SubRegIndices();
167 /// Check if the given identifier is a name of a subregister index.
169 /// Return 0 if the name isn't a subregister index class.
170 unsigned getSubRegIndex(StringRef Name);
172 void initSlots2BasicBlocks();
174 const BasicBlock *getIRBlock(unsigned Slot);
176 void initNames2TargetIndices();
178 /// Try to convert a name of target index to the corresponding target index.
180 /// Return true if the name isn't a name of a target index.
181 bool getTargetIndex(StringRef Name, int &Index);
184 } // end anonymous namespace
186 MIParser::MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
187 StringRef Source, const PerFunctionMIParsingState &PFS,
188 const SlotMapping &IRSlots)
189 : SM(SM), MF(MF), Error(Error), Source(Source), CurrentSource(Source),
190 Token(MIToken::Error, StringRef()), PFS(PFS), IRSlots(IRSlots) {}
192 void MIParser::lex() {
193 CurrentSource = lexMIToken(
194 CurrentSource, Token,
195 [this](StringRef::iterator Loc, const Twine &Msg) { error(Loc, Msg); });
198 bool MIParser::error(const Twine &Msg) { return error(Token.location(), Msg); }
200 bool MIParser::error(StringRef::iterator Loc, const Twine &Msg) {
201 assert(Loc >= Source.data() && Loc <= (Source.data() + Source.size()));
202 Error = SMDiagnostic(
204 SM.getMemoryBuffer(SM.getMainFileID())->getBufferIdentifier(), 1,
205 Loc - Source.data(), SourceMgr::DK_Error, Msg.str(), Source, None, None);
209 static const char *toString(MIToken::TokenKind TokenKind) {
215 case MIToken::lparen:
217 case MIToken::rparen:
220 return "<unknown token>";
224 bool MIParser::expectAndConsume(MIToken::TokenKind TokenKind) {
225 if (Token.isNot(TokenKind))
226 return error(Twine("expected ") + toString(TokenKind));
231 bool MIParser::parse(MachineInstr *&MI) {
234 // Parse any register operands before '='
235 MachineOperand MO = MachineOperand::CreateImm(0);
236 SmallVector<MachineOperandWithLocation, 8> Operands;
237 while (Token.isRegister() || Token.isRegisterFlag()) {
238 auto Loc = Token.location();
239 if (parseRegisterOperand(MO, /*IsDef=*/true))
241 Operands.push_back(MachineOperandWithLocation(MO, Loc, Token.location()));
242 if (Token.isNot(MIToken::comma))
246 if (!Operands.empty() && expectAndConsume(MIToken::equal))
249 unsigned OpCode, Flags = 0;
250 if (Token.isError() || parseInstruction(OpCode, Flags))
253 // TODO: Parse the bundle instruction flags.
255 // Parse the remaining machine operands.
256 while (Token.isNot(MIToken::Eof) && Token.isNot(MIToken::kw_debug_location) &&
257 Token.isNot(MIToken::coloncolon)) {
258 auto Loc = Token.location();
259 if (parseMachineOperand(MO))
261 Operands.push_back(MachineOperandWithLocation(MO, Loc, Token.location()));
262 if (Token.is(MIToken::Eof) || Token.is(MIToken::coloncolon))
264 if (Token.isNot(MIToken::comma))
265 return error("expected ',' before the next machine operand");
269 DebugLoc DebugLocation;
270 if (Token.is(MIToken::kw_debug_location)) {
272 if (Token.isNot(MIToken::exclaim))
273 return error("expected a metadata node after 'debug-location'");
274 MDNode *Node = nullptr;
275 if (parseMDNode(Node))
277 DebugLocation = DebugLoc(Node);
280 // Parse the machine memory operands.
281 SmallVector<MachineMemOperand *, 2> MemOperands;
282 if (Token.is(MIToken::coloncolon)) {
284 while (Token.isNot(MIToken::Eof)) {
285 MachineMemOperand *MemOp = nullptr;
286 if (parseMachineMemoryOperand(MemOp))
288 MemOperands.push_back(MemOp);
289 if (Token.is(MIToken::Eof))
291 if (Token.isNot(MIToken::comma))
292 return error("expected ',' before the next machine memory operand");
297 const auto &MCID = MF.getSubtarget().getInstrInfo()->get(OpCode);
298 if (!MCID.isVariadic()) {
299 // FIXME: Move the implicit operand verification to the machine verifier.
300 if (verifyImplicitOperands(Operands, MCID))
304 // TODO: Check for extraneous machine operands.
305 MI = MF.CreateMachineInstr(MCID, DebugLocation, /*NoImplicit=*/true);
307 for (const auto &Operand : Operands)
308 MI->addOperand(MF, Operand.Operand);
309 if (MemOperands.empty())
311 MachineInstr::mmo_iterator MemRefs =
312 MF.allocateMemRefsArray(MemOperands.size());
313 std::copy(MemOperands.begin(), MemOperands.end(), MemRefs);
314 MI->setMemRefs(MemRefs, MemRefs + MemOperands.size());
318 bool MIParser::parseStandaloneMBB(MachineBasicBlock *&MBB) {
320 if (Token.isNot(MIToken::MachineBasicBlock))
321 return error("expected a machine basic block reference");
322 if (parseMBBReference(MBB))
325 if (Token.isNot(MIToken::Eof))
327 "expected end of string after the machine basic block reference");
331 bool MIParser::parseStandaloneNamedRegister(unsigned &Reg) {
333 if (Token.isNot(MIToken::NamedRegister))
334 return error("expected a named register");
335 if (parseRegister(Reg))
338 if (Token.isNot(MIToken::Eof))
339 return error("expected end of string after the register reference");
343 bool MIParser::parseStandaloneVirtualRegister(unsigned &Reg) {
345 if (Token.isNot(MIToken::VirtualRegister))
346 return error("expected a virtual register");
347 if (parseRegister(Reg))
350 if (Token.isNot(MIToken::Eof))
351 return error("expected end of string after the register reference");
355 bool MIParser::parseStandaloneIRBlockReference(const BasicBlock *&BB) {
357 if (Token.isNot(MIToken::IRBlock))
358 return error("expected an IR block reference");
359 unsigned SlotNumber = 0;
360 if (getUnsigned(SlotNumber))
362 BB = getIRBlock(SlotNumber);
364 return error(Twine("use of undefined IR block '%ir-block.") +
365 Twine(SlotNumber) + "'");
367 if (Token.isNot(MIToken::Eof))
368 return error("expected end of string after the IR block reference");
372 static const char *printImplicitRegisterFlag(const MachineOperand &MO) {
373 assert(MO.isImplicit());
374 return MO.isDef() ? "implicit-def" : "implicit";
377 static std::string getRegisterName(const TargetRegisterInfo *TRI,
379 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "expected phys reg");
380 return StringRef(TRI->getName(Reg)).lower();
383 bool MIParser::verifyImplicitOperands(
384 ArrayRef<MachineOperandWithLocation> Operands, const MCInstrDesc &MCID) {
386 // We can't verify call instructions as they can contain arbitrary implicit
387 // register and register mask operands.
390 // Gather all the expected implicit operands.
391 SmallVector<MachineOperand, 4> ImplicitOperands;
392 if (MCID.ImplicitDefs)
393 for (const uint16_t *ImpDefs = MCID.getImplicitDefs(); *ImpDefs; ++ImpDefs)
394 ImplicitOperands.push_back(
395 MachineOperand::CreateReg(*ImpDefs, true, true));
396 if (MCID.ImplicitUses)
397 for (const uint16_t *ImpUses = MCID.getImplicitUses(); *ImpUses; ++ImpUses)
398 ImplicitOperands.push_back(
399 MachineOperand::CreateReg(*ImpUses, false, true));
401 const auto *TRI = MF.getSubtarget().getRegisterInfo();
402 assert(TRI && "Expected target register info");
403 size_t I = ImplicitOperands.size(), J = Operands.size();
408 const auto &ImplicitOperand = ImplicitOperands[I];
409 const auto &Operand = Operands[J].Operand;
410 if (ImplicitOperand.isIdenticalTo(Operand))
412 if (Operand.isReg() && Operand.isImplicit()) {
413 return error(Operands[J].Begin,
414 Twine("expected an implicit register operand '") +
415 printImplicitRegisterFlag(ImplicitOperand) + " %" +
416 getRegisterName(TRI, ImplicitOperand.getReg()) + "'");
419 // TODO: Fix source location when Operands[J].end is right before '=', i.e:
420 // insead of reporting an error at this location:
423 // report the error at the following location:
426 return error(J < Operands.size() ? Operands[J].End : Token.location(),
427 Twine("missing implicit register operand '") +
428 printImplicitRegisterFlag(ImplicitOperands[I]) + " %" +
429 getRegisterName(TRI, ImplicitOperands[I].getReg()) + "'");
434 bool MIParser::parseInstruction(unsigned &OpCode, unsigned &Flags) {
435 if (Token.is(MIToken::kw_frame_setup)) {
436 Flags |= MachineInstr::FrameSetup;
439 if (Token.isNot(MIToken::Identifier))
440 return error("expected a machine instruction");
441 StringRef InstrName = Token.stringValue();
442 if (parseInstrName(InstrName, OpCode))
443 return error(Twine("unknown machine instruction name '") + InstrName + "'");
448 bool MIParser::parseRegister(unsigned &Reg) {
449 switch (Token.kind()) {
450 case MIToken::underscore:
453 case MIToken::NamedRegister: {
454 StringRef Name = Token.stringValue();
455 if (getRegisterByName(Name, Reg))
456 return error(Twine("unknown register name '") + Name + "'");
459 case MIToken::VirtualRegister: {
463 const auto RegInfo = PFS.VirtualRegisterSlots.find(ID);
464 if (RegInfo == PFS.VirtualRegisterSlots.end())
465 return error(Twine("use of undefined virtual register '%") + Twine(ID) +
467 Reg = RegInfo->second;
470 // TODO: Parse other register kinds.
472 llvm_unreachable("The current token should be a register");
477 bool MIParser::parseRegisterFlag(unsigned &Flags) {
478 const unsigned OldFlags = Flags;
479 switch (Token.kind()) {
480 case MIToken::kw_implicit:
481 Flags |= RegState::Implicit;
483 case MIToken::kw_implicit_define:
484 Flags |= RegState::ImplicitDefine;
486 case MIToken::kw_dead:
487 Flags |= RegState::Dead;
489 case MIToken::kw_killed:
490 Flags |= RegState::Kill;
492 case MIToken::kw_undef:
493 Flags |= RegState::Undef;
495 case MIToken::kw_early_clobber:
496 Flags |= RegState::EarlyClobber;
498 case MIToken::kw_debug_use:
499 Flags |= RegState::Debug;
501 // TODO: parse the other register flags.
503 llvm_unreachable("The current token should be a register flag");
505 if (OldFlags == Flags)
506 // We know that the same flag is specified more than once when the flags
508 return error("duplicate '" + Token.stringValue() + "' register flag");
513 bool MIParser::parseSubRegisterIndex(unsigned &SubReg) {
514 assert(Token.is(MIToken::colon));
516 if (Token.isNot(MIToken::Identifier))
517 return error("expected a subregister index after ':'");
518 auto Name = Token.stringValue();
519 SubReg = getSubRegIndex(Name);
521 return error(Twine("use of unknown subregister index '") + Name + "'");
526 bool MIParser::parseRegisterOperand(MachineOperand &Dest, bool IsDef) {
528 unsigned Flags = IsDef ? RegState::Define : 0;
529 while (Token.isRegisterFlag()) {
530 if (parseRegisterFlag(Flags))
533 if (!Token.isRegister())
534 return error("expected a register after register flags");
535 if (parseRegister(Reg))
539 if (Token.is(MIToken::colon)) {
540 if (parseSubRegisterIndex(SubReg))
543 Dest = MachineOperand::CreateReg(
544 Reg, Flags & RegState::Define, Flags & RegState::Implicit,
545 Flags & RegState::Kill, Flags & RegState::Dead, Flags & RegState::Undef,
546 Flags & RegState::EarlyClobber, SubReg, Flags & RegState::Debug);
550 bool MIParser::parseImmediateOperand(MachineOperand &Dest) {
551 assert(Token.is(MIToken::IntegerLiteral));
552 const APSInt &Int = Token.integerValue();
553 if (Int.getMinSignedBits() > 64)
554 // TODO: Replace this with an error when we can parse CIMM Machine Operands.
555 llvm_unreachable("Can't parse large integer literals yet!");
556 Dest = MachineOperand::CreateImm(Int.getExtValue());
561 bool MIParser::parseIRConstant(StringRef::iterator Loc, const Constant *&C) {
562 auto Source = StringRef(Loc, Token.stringValue().end() - Loc).str();
565 C = parseConstantValue(Source.c_str(), Err, *MF.getFunction()->getParent());
567 return error(Loc + Err.getColumnNo(), Err.getMessage());
571 bool MIParser::parseFPImmediateOperand(MachineOperand &Dest) {
572 auto Loc = Token.location();
574 if (Token.isNot(MIToken::FloatingPointLiteral))
575 return error("expected a floating point literal");
576 const Constant *C = nullptr;
577 if (parseIRConstant(Loc, C))
579 Dest = MachineOperand::CreateFPImm(cast<ConstantFP>(C));
583 bool MIParser::getUnsigned(unsigned &Result) {
584 assert(Token.hasIntegerValue() && "Expected a token with an integer value");
585 const uint64_t Limit = uint64_t(std::numeric_limits<unsigned>::max()) + 1;
586 uint64_t Val64 = Token.integerValue().getLimitedValue(Limit);
588 return error("expected 32-bit integer (too large)");
593 bool MIParser::parseMBBReference(MachineBasicBlock *&MBB) {
594 assert(Token.is(MIToken::MachineBasicBlock));
596 if (getUnsigned(Number))
598 auto MBBInfo = PFS.MBBSlots.find(Number);
599 if (MBBInfo == PFS.MBBSlots.end())
600 return error(Twine("use of undefined machine basic block #") +
602 MBB = MBBInfo->second;
603 if (!Token.stringValue().empty() && Token.stringValue() != MBB->getName())
604 return error(Twine("the name of machine basic block #") + Twine(Number) +
605 " isn't '" + Token.stringValue() + "'");
609 bool MIParser::parseMBBOperand(MachineOperand &Dest) {
610 MachineBasicBlock *MBB;
611 if (parseMBBReference(MBB))
613 Dest = MachineOperand::CreateMBB(MBB);
618 bool MIParser::parseStackObjectOperand(MachineOperand &Dest) {
619 assert(Token.is(MIToken::StackObject));
623 auto ObjectInfo = PFS.StackObjectSlots.find(ID);
624 if (ObjectInfo == PFS.StackObjectSlots.end())
625 return error(Twine("use of undefined stack object '%stack.") + Twine(ID) +
628 if (const auto *Alloca =
629 MF.getFrameInfo()->getObjectAllocation(ObjectInfo->second))
630 Name = Alloca->getName();
631 if (!Token.stringValue().empty() && Token.stringValue() != Name)
632 return error(Twine("the name of the stack object '%stack.") + Twine(ID) +
633 "' isn't '" + Token.stringValue() + "'");
635 Dest = MachineOperand::CreateFI(ObjectInfo->second);
639 bool MIParser::parseFixedStackObjectOperand(MachineOperand &Dest) {
640 assert(Token.is(MIToken::FixedStackObject));
644 auto ObjectInfo = PFS.FixedStackObjectSlots.find(ID);
645 if (ObjectInfo == PFS.FixedStackObjectSlots.end())
646 return error(Twine("use of undefined fixed stack object '%fixed-stack.") +
649 Dest = MachineOperand::CreateFI(ObjectInfo->second);
653 bool MIParser::parseGlobalValue(GlobalValue *&GV) {
654 switch (Token.kind()) {
655 case MIToken::NamedGlobalValue: {
656 const Module *M = MF.getFunction()->getParent();
657 GV = M->getNamedValue(Token.stringValue());
659 return error(Twine("use of undefined global value '@") +
660 Token.rawStringValue() + "'");
663 case MIToken::GlobalValue: {
665 if (getUnsigned(GVIdx))
667 if (GVIdx >= IRSlots.GlobalValues.size())
668 return error(Twine("use of undefined global value '@") + Twine(GVIdx) +
670 GV = IRSlots.GlobalValues[GVIdx];
674 llvm_unreachable("The current token should be a global value");
679 bool MIParser::parseGlobalAddressOperand(MachineOperand &Dest) {
680 GlobalValue *GV = nullptr;
681 if (parseGlobalValue(GV))
683 Dest = MachineOperand::CreateGA(GV, /*Offset=*/0);
684 // TODO: Parse offset and target flags.
689 bool MIParser::parseConstantPoolIndexOperand(MachineOperand &Dest) {
690 assert(Token.is(MIToken::ConstantPoolItem));
694 auto ConstantInfo = PFS.ConstantPoolSlots.find(ID);
695 if (ConstantInfo == PFS.ConstantPoolSlots.end())
696 return error("use of undefined constant '%const." + Twine(ID) + "'");
698 // TODO: Parse offset and target flags.
699 Dest = MachineOperand::CreateCPI(ID, /*Offset=*/0);
703 bool MIParser::parseJumpTableIndexOperand(MachineOperand &Dest) {
704 assert(Token.is(MIToken::JumpTableIndex));
708 auto JumpTableEntryInfo = PFS.JumpTableSlots.find(ID);
709 if (JumpTableEntryInfo == PFS.JumpTableSlots.end())
710 return error("use of undefined jump table '%jump-table." + Twine(ID) + "'");
712 // TODO: Parse target flags.
713 Dest = MachineOperand::CreateJTI(JumpTableEntryInfo->second);
717 bool MIParser::parseExternalSymbolOperand(MachineOperand &Dest) {
718 assert(Token.is(MIToken::ExternalSymbol));
719 const char *Symbol = MF.createExternalSymbolName(Token.stringValue());
721 // TODO: Parse the target flags.
722 Dest = MachineOperand::CreateES(Symbol);
726 bool MIParser::parseMDNode(MDNode *&Node) {
727 assert(Token.is(MIToken::exclaim));
728 auto Loc = Token.location();
730 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
731 return error("expected metadata id after '!'");
735 auto NodeInfo = IRSlots.MetadataNodes.find(ID);
736 if (NodeInfo == IRSlots.MetadataNodes.end())
737 return error(Loc, "use of undefined metadata '!" + Twine(ID) + "'");
739 Node = NodeInfo->second.get();
743 bool MIParser::parseMetadataOperand(MachineOperand &Dest) {
744 MDNode *Node = nullptr;
745 if (parseMDNode(Node))
747 Dest = MachineOperand::CreateMetadata(Node);
751 bool MIParser::parseCFIOffset(int &Offset) {
752 if (Token.isNot(MIToken::IntegerLiteral))
753 return error("expected a cfi offset");
754 if (Token.integerValue().getMinSignedBits() > 32)
755 return error("expected a 32 bit integer (the cfi offset is too large)");
756 Offset = (int)Token.integerValue().getExtValue();
761 bool MIParser::parseCFIRegister(unsigned &Reg) {
762 if (Token.isNot(MIToken::NamedRegister))
763 return error("expected a cfi register");
765 if (parseRegister(LLVMReg))
767 const auto *TRI = MF.getSubtarget().getRegisterInfo();
768 assert(TRI && "Expected target register info");
769 int DwarfReg = TRI->getDwarfRegNum(LLVMReg, true);
771 return error("invalid DWARF register");
772 Reg = (unsigned)DwarfReg;
777 bool MIParser::parseCFIOperand(MachineOperand &Dest) {
778 auto Kind = Token.kind();
780 auto &MMI = MF.getMMI();
785 case MIToken::kw_cfi_offset:
786 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
787 parseCFIOffset(Offset))
790 MMI.addFrameInst(MCCFIInstruction::createOffset(nullptr, Reg, Offset));
792 case MIToken::kw_cfi_def_cfa_register:
793 if (parseCFIRegister(Reg))
796 MMI.addFrameInst(MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
798 case MIToken::kw_cfi_def_cfa_offset:
799 if (parseCFIOffset(Offset))
801 // NB: MCCFIInstruction::createDefCfaOffset negates the offset.
802 CFIIndex = MMI.addFrameInst(
803 MCCFIInstruction::createDefCfaOffset(nullptr, -Offset));
805 case MIToken::kw_cfi_def_cfa:
806 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
807 parseCFIOffset(Offset))
809 // NB: MCCFIInstruction::createDefCfa negates the offset.
811 MMI.addFrameInst(MCCFIInstruction::createDefCfa(nullptr, Reg, -Offset));
814 // TODO: Parse the other CFI operands.
815 llvm_unreachable("The current token should be a cfi operand");
817 Dest = MachineOperand::CreateCFIIndex(CFIIndex);
821 bool MIParser::parseIRBlock(BasicBlock *&BB, const Function &F) {
822 switch (Token.kind()) {
823 case MIToken::NamedIRBlock: {
824 BB = dyn_cast_or_null<BasicBlock>(
825 F.getValueSymbolTable().lookup(Token.stringValue()));
827 return error(Twine("use of undefined IR block '%ir-block.") +
828 Token.rawStringValue() + "'");
831 case MIToken::IRBlock: {
832 unsigned SlotNumber = 0;
833 if (getUnsigned(SlotNumber))
835 BB = const_cast<BasicBlock *>(getIRBlock(SlotNumber));
837 return error(Twine("use of undefined IR block '%ir-block.") +
838 Twine(SlotNumber) + "'");
842 llvm_unreachable("The current token should be an IR block reference");
847 bool MIParser::parseBlockAddressOperand(MachineOperand &Dest) {
848 assert(Token.is(MIToken::kw_blockaddress));
850 if (expectAndConsume(MIToken::lparen))
852 if (Token.isNot(MIToken::GlobalValue) &&
853 Token.isNot(MIToken::NamedGlobalValue))
854 return error("expected a global value");
855 GlobalValue *GV = nullptr;
856 if (parseGlobalValue(GV))
858 auto *F = dyn_cast<Function>(GV);
860 return error("expected an IR function reference");
862 if (expectAndConsume(MIToken::comma))
864 BasicBlock *BB = nullptr;
865 if (Token.isNot(MIToken::IRBlock) && Token.isNot(MIToken::NamedIRBlock))
866 return error("expected an IR block reference");
867 if (parseIRBlock(BB, *F))
870 if (expectAndConsume(MIToken::rparen))
872 // TODO: parse offset and target flags.
873 Dest = MachineOperand::CreateBA(BlockAddress::get(F, BB), /*Offset=*/0);
877 bool MIParser::parseTargetIndexOperand(MachineOperand &Dest) {
878 assert(Token.is(MIToken::kw_target_index));
880 if (expectAndConsume(MIToken::lparen))
882 if (Token.isNot(MIToken::Identifier))
883 return error("expected the name of the target index");
885 if (getTargetIndex(Token.stringValue(), Index))
886 return error("use of undefined target index '" + Token.stringValue() + "'");
888 if (expectAndConsume(MIToken::rparen))
890 // TODO: Parse the offset and target flags.
891 Dest = MachineOperand::CreateTargetIndex(unsigned(Index), /*Offset=*/0);
895 bool MIParser::parseMachineOperand(MachineOperand &Dest) {
896 switch (Token.kind()) {
897 case MIToken::kw_implicit:
898 case MIToken::kw_implicit_define:
899 case MIToken::kw_dead:
900 case MIToken::kw_killed:
901 case MIToken::kw_undef:
902 case MIToken::kw_early_clobber:
903 case MIToken::kw_debug_use:
904 case MIToken::underscore:
905 case MIToken::NamedRegister:
906 case MIToken::VirtualRegister:
907 return parseRegisterOperand(Dest);
908 case MIToken::IntegerLiteral:
909 return parseImmediateOperand(Dest);
910 case MIToken::kw_half:
911 case MIToken::kw_float:
912 case MIToken::kw_double:
913 case MIToken::kw_x86_fp80:
914 case MIToken::kw_fp128:
915 case MIToken::kw_ppc_fp128:
916 return parseFPImmediateOperand(Dest);
917 case MIToken::MachineBasicBlock:
918 return parseMBBOperand(Dest);
919 case MIToken::StackObject:
920 return parseStackObjectOperand(Dest);
921 case MIToken::FixedStackObject:
922 return parseFixedStackObjectOperand(Dest);
923 case MIToken::GlobalValue:
924 case MIToken::NamedGlobalValue:
925 return parseGlobalAddressOperand(Dest);
926 case MIToken::ConstantPoolItem:
927 return parseConstantPoolIndexOperand(Dest);
928 case MIToken::JumpTableIndex:
929 return parseJumpTableIndexOperand(Dest);
930 case MIToken::ExternalSymbol:
931 return parseExternalSymbolOperand(Dest);
932 case MIToken::exclaim:
933 return parseMetadataOperand(Dest);
934 case MIToken::kw_cfi_offset:
935 case MIToken::kw_cfi_def_cfa_register:
936 case MIToken::kw_cfi_def_cfa_offset:
937 case MIToken::kw_cfi_def_cfa:
938 return parseCFIOperand(Dest);
939 case MIToken::kw_blockaddress:
940 return parseBlockAddressOperand(Dest);
941 case MIToken::kw_target_index:
942 return parseTargetIndexOperand(Dest);
945 case MIToken::Identifier:
946 if (const auto *RegMask = getRegMask(Token.stringValue())) {
947 Dest = MachineOperand::CreateRegMask(RegMask);
953 // TODO: parse the other machine operands.
954 return error("expected a machine operand");
959 bool MIParser::parseIRValue(Value *&V) {
960 switch (Token.kind()) {
961 case MIToken::NamedIRValue: {
962 V = MF.getFunction()->getValueSymbolTable().lookup(Token.stringValue());
964 return error(Twine("use of undefined IR value '%ir.") +
965 Token.rawStringValue() + "'");
968 // TODO: Parse unnamed IR value references.
970 llvm_unreachable("The current token should be an IR block reference");
975 bool MIParser::getUint64(uint64_t &Result) {
976 assert(Token.hasIntegerValue());
977 if (Token.integerValue().getActiveBits() > 64)
978 return error("expected 64-bit integer (too large)");
979 Result = Token.integerValue().getZExtValue();
983 bool MIParser::parseMemoryOperandFlag(unsigned &Flags) {
984 switch (Token.kind()) {
985 case MIToken::kw_volatile:
986 Flags |= MachineMemOperand::MOVolatile;
988 // TODO: report an error when we specify the same flag more than once.
989 // TODO: parse the other memory operand flags.
991 llvm_unreachable("The current token should be a memory operand flag");
997 bool MIParser::parseMachineMemoryOperand(MachineMemOperand *&Dest) {
998 if (expectAndConsume(MIToken::lparen))
1001 while (Token.isMemoryOperandFlag()) {
1002 if (parseMemoryOperandFlag(Flags))
1005 if (Token.isNot(MIToken::Identifier) ||
1006 (Token.stringValue() != "load" && Token.stringValue() != "store"))
1007 return error("expected 'load' or 'store' memory operation");
1008 if (Token.stringValue() == "load")
1009 Flags |= MachineMemOperand::MOLoad;
1011 Flags |= MachineMemOperand::MOStore;
1014 if (Token.isNot(MIToken::IntegerLiteral))
1015 return error("expected the size integer literal after memory operation");
1017 if (getUint64(Size))
1021 const char *Word = Flags & MachineMemOperand::MOLoad ? "from" : "into";
1022 if (Token.isNot(MIToken::Identifier) || Token.stringValue() != Word)
1023 return error(Twine("expected '") + Word + "'");
1026 // TODO: Parse pseudo source values.
1027 if (Token.isNot(MIToken::NamedIRValue))
1028 return error("expected an IR value reference");
1030 if (parseIRValue(V))
1032 if (!V->getType()->isPointerTy())
1033 return error("expected a pointer IR value");
1035 // TODO: Parse the base alignment.
1036 // TODO: Parse the attached metadata nodes.
1037 if (expectAndConsume(MIToken::rparen))
1040 Dest = MF.getMachineMemOperand(MachinePointerInfo(V), Flags, Size, Size);
1044 void MIParser::initNames2InstrOpCodes() {
1045 if (!Names2InstrOpCodes.empty())
1047 const auto *TII = MF.getSubtarget().getInstrInfo();
1048 assert(TII && "Expected target instruction info");
1049 for (unsigned I = 0, E = TII->getNumOpcodes(); I < E; ++I)
1050 Names2InstrOpCodes.insert(std::make_pair(StringRef(TII->getName(I)), I));
1053 bool MIParser::parseInstrName(StringRef InstrName, unsigned &OpCode) {
1054 initNames2InstrOpCodes();
1055 auto InstrInfo = Names2InstrOpCodes.find(InstrName);
1056 if (InstrInfo == Names2InstrOpCodes.end())
1058 OpCode = InstrInfo->getValue();
1062 void MIParser::initNames2Regs() {
1063 if (!Names2Regs.empty())
1065 // The '%noreg' register is the register 0.
1066 Names2Regs.insert(std::make_pair("noreg", 0));
1067 const auto *TRI = MF.getSubtarget().getRegisterInfo();
1068 assert(TRI && "Expected target register info");
1069 for (unsigned I = 0, E = TRI->getNumRegs(); I < E; ++I) {
1071 Names2Regs.insert(std::make_pair(StringRef(TRI->getName(I)).lower(), I))
1074 assert(WasInserted && "Expected registers to be unique case-insensitively");
1078 bool MIParser::getRegisterByName(StringRef RegName, unsigned &Reg) {
1080 auto RegInfo = Names2Regs.find(RegName);
1081 if (RegInfo == Names2Regs.end())
1083 Reg = RegInfo->getValue();
1087 void MIParser::initNames2RegMasks() {
1088 if (!Names2RegMasks.empty())
1090 const auto *TRI = MF.getSubtarget().getRegisterInfo();
1091 assert(TRI && "Expected target register info");
1092 ArrayRef<const uint32_t *> RegMasks = TRI->getRegMasks();
1093 ArrayRef<const char *> RegMaskNames = TRI->getRegMaskNames();
1094 assert(RegMasks.size() == RegMaskNames.size());
1095 for (size_t I = 0, E = RegMasks.size(); I < E; ++I)
1096 Names2RegMasks.insert(
1097 std::make_pair(StringRef(RegMaskNames[I]).lower(), RegMasks[I]));
1100 const uint32_t *MIParser::getRegMask(StringRef Identifier) {
1101 initNames2RegMasks();
1102 auto RegMaskInfo = Names2RegMasks.find(Identifier);
1103 if (RegMaskInfo == Names2RegMasks.end())
1105 return RegMaskInfo->getValue();
1108 void MIParser::initNames2SubRegIndices() {
1109 if (!Names2SubRegIndices.empty())
1111 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1112 for (unsigned I = 1, E = TRI->getNumSubRegIndices(); I < E; ++I)
1113 Names2SubRegIndices.insert(
1114 std::make_pair(StringRef(TRI->getSubRegIndexName(I)).lower(), I));
1117 unsigned MIParser::getSubRegIndex(StringRef Name) {
1118 initNames2SubRegIndices();
1119 auto SubRegInfo = Names2SubRegIndices.find(Name);
1120 if (SubRegInfo == Names2SubRegIndices.end())
1122 return SubRegInfo->getValue();
1125 void MIParser::initSlots2BasicBlocks() {
1126 if (!Slots2BasicBlocks.empty())
1128 const auto &F = *MF.getFunction();
1129 ModuleSlotTracker MST(F.getParent());
1130 MST.incorporateFunction(F);
1131 for (auto &BB : F) {
1134 int Slot = MST.getLocalSlot(&BB);
1137 Slots2BasicBlocks.insert(std::make_pair(unsigned(Slot), &BB));
1141 const BasicBlock *MIParser::getIRBlock(unsigned Slot) {
1142 initSlots2BasicBlocks();
1143 auto BlockInfo = Slots2BasicBlocks.find(Slot);
1144 if (BlockInfo == Slots2BasicBlocks.end())
1146 return BlockInfo->second;
1149 void MIParser::initNames2TargetIndices() {
1150 if (!Names2TargetIndices.empty())
1152 const auto *TII = MF.getSubtarget().getInstrInfo();
1153 assert(TII && "Expected target instruction info");
1154 auto Indices = TII->getSerializableTargetIndices();
1155 for (const auto &I : Indices)
1156 Names2TargetIndices.insert(std::make_pair(StringRef(I.second), I.first));
1159 bool MIParser::getTargetIndex(StringRef Name, int &Index) {
1160 initNames2TargetIndices();
1161 auto IndexInfo = Names2TargetIndices.find(Name);
1162 if (IndexInfo == Names2TargetIndices.end())
1164 Index = IndexInfo->second;
1168 bool llvm::parseMachineInstr(MachineInstr *&MI, SourceMgr &SM,
1169 MachineFunction &MF, StringRef Src,
1170 const PerFunctionMIParsingState &PFS,
1171 const SlotMapping &IRSlots, SMDiagnostic &Error) {
1172 return MIParser(SM, MF, Error, Src, PFS, IRSlots).parse(MI);
1175 bool llvm::parseMBBReference(MachineBasicBlock *&MBB, SourceMgr &SM,
1176 MachineFunction &MF, StringRef Src,
1177 const PerFunctionMIParsingState &PFS,
1178 const SlotMapping &IRSlots, SMDiagnostic &Error) {
1179 return MIParser(SM, MF, Error, Src, PFS, IRSlots).parseStandaloneMBB(MBB);
1182 bool llvm::parseNamedRegisterReference(unsigned &Reg, SourceMgr &SM,
1183 MachineFunction &MF, StringRef Src,
1184 const PerFunctionMIParsingState &PFS,
1185 const SlotMapping &IRSlots,
1186 SMDiagnostic &Error) {
1187 return MIParser(SM, MF, Error, Src, PFS, IRSlots)
1188 .parseStandaloneNamedRegister(Reg);
1191 bool llvm::parseVirtualRegisterReference(unsigned &Reg, SourceMgr &SM,
1192 MachineFunction &MF, StringRef Src,
1193 const PerFunctionMIParsingState &PFS,
1194 const SlotMapping &IRSlots,
1195 SMDiagnostic &Error) {
1196 return MIParser(SM, MF, Error, Src, PFS, IRSlots)
1197 .parseStandaloneVirtualRegister(Reg);
1200 bool llvm::parseIRBlockReference(const BasicBlock *&BB, SourceMgr &SM,
1201 MachineFunction &MF, StringRef Src,
1202 const PerFunctionMIParsingState &PFS,
1203 const SlotMapping &IRSlots,
1204 SMDiagnostic &Error) {
1205 return MIParser(SM, MF, Error, Src, PFS, IRSlots)
1206 .parseStandaloneIRBlockReference(BB);