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 parseTypedImmediateOperand(MachineOperand &Dest);
104 bool parseFPImmediateOperand(MachineOperand &Dest);
105 bool parseMBBReference(MachineBasicBlock *&MBB);
106 bool parseMBBOperand(MachineOperand &Dest);
107 bool parseStackObjectOperand(MachineOperand &Dest);
108 bool parseFixedStackObjectOperand(MachineOperand &Dest);
109 bool parseGlobalValue(GlobalValue *&GV);
110 bool parseGlobalAddressOperand(MachineOperand &Dest);
111 bool parseConstantPoolIndexOperand(MachineOperand &Dest);
112 bool parseJumpTableIndexOperand(MachineOperand &Dest);
113 bool parseExternalSymbolOperand(MachineOperand &Dest);
114 bool parseMDNode(MDNode *&Node);
115 bool parseMetadataOperand(MachineOperand &Dest);
116 bool parseCFIOffset(int &Offset);
117 bool parseCFIRegister(unsigned &Reg);
118 bool parseCFIOperand(MachineOperand &Dest);
119 bool parseIRBlock(BasicBlock *&BB, const Function &F);
120 bool parseBlockAddressOperand(MachineOperand &Dest);
121 bool parseTargetIndexOperand(MachineOperand &Dest);
122 bool parseMachineOperand(MachineOperand &Dest);
123 bool parseIRValue(Value *&V);
124 bool parseMemoryOperandFlag(unsigned &Flags);
125 bool parseMachineMemoryOperand(MachineMemOperand *&Dest);
128 /// Convert the integer literal in the current token into an unsigned integer.
130 /// Return true if an error occurred.
131 bool getUnsigned(unsigned &Result);
133 /// Convert the integer literal in the current token into an uint64.
135 /// Return true if an error occurred.
136 bool getUint64(uint64_t &Result);
138 /// If the current token is of the given kind, consume it and return false.
139 /// Otherwise report an error and return true.
140 bool expectAndConsume(MIToken::TokenKind TokenKind);
142 void initNames2InstrOpCodes();
144 /// Try to convert an instruction name to an opcode. Return true if the
145 /// instruction name is invalid.
146 bool parseInstrName(StringRef InstrName, unsigned &OpCode);
148 bool parseInstruction(unsigned &OpCode, unsigned &Flags);
150 bool verifyImplicitOperands(ArrayRef<MachineOperandWithLocation> Operands,
151 const MCInstrDesc &MCID);
153 void initNames2Regs();
155 /// Try to convert a register name to a register number. Return true if the
156 /// register name is invalid.
157 bool getRegisterByName(StringRef RegName, unsigned &Reg);
159 void initNames2RegMasks();
161 /// Check if the given identifier is a name of a register mask.
163 /// Return null if the identifier isn't a register mask.
164 const uint32_t *getRegMask(StringRef Identifier);
166 void initNames2SubRegIndices();
168 /// Check if the given identifier is a name of a subregister index.
170 /// Return 0 if the name isn't a subregister index class.
171 unsigned getSubRegIndex(StringRef Name);
173 void initSlots2BasicBlocks();
175 const BasicBlock *getIRBlock(unsigned Slot);
177 void initNames2TargetIndices();
179 /// Try to convert a name of target index to the corresponding target index.
181 /// Return true if the name isn't a name of a target index.
182 bool getTargetIndex(StringRef Name, int &Index);
185 } // end anonymous namespace
187 MIParser::MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
188 StringRef Source, const PerFunctionMIParsingState &PFS,
189 const SlotMapping &IRSlots)
190 : SM(SM), MF(MF), Error(Error), Source(Source), CurrentSource(Source),
191 Token(MIToken::Error, StringRef()), PFS(PFS), IRSlots(IRSlots) {}
193 void MIParser::lex() {
194 CurrentSource = lexMIToken(
195 CurrentSource, Token,
196 [this](StringRef::iterator Loc, const Twine &Msg) { error(Loc, Msg); });
199 bool MIParser::error(const Twine &Msg) { return error(Token.location(), Msg); }
201 bool MIParser::error(StringRef::iterator Loc, const Twine &Msg) {
202 assert(Loc >= Source.data() && Loc <= (Source.data() + Source.size()));
203 Error = SMDiagnostic(
205 SM.getMemoryBuffer(SM.getMainFileID())->getBufferIdentifier(), 1,
206 Loc - Source.data(), SourceMgr::DK_Error, Msg.str(), Source, None, None);
210 static const char *toString(MIToken::TokenKind TokenKind) {
216 case MIToken::lparen:
218 case MIToken::rparen:
221 return "<unknown token>";
225 bool MIParser::expectAndConsume(MIToken::TokenKind TokenKind) {
226 if (Token.isNot(TokenKind))
227 return error(Twine("expected ") + toString(TokenKind));
232 bool MIParser::parse(MachineInstr *&MI) {
235 // Parse any register operands before '='
236 MachineOperand MO = MachineOperand::CreateImm(0);
237 SmallVector<MachineOperandWithLocation, 8> Operands;
238 while (Token.isRegister() || Token.isRegisterFlag()) {
239 auto Loc = Token.location();
240 if (parseRegisterOperand(MO, /*IsDef=*/true))
242 Operands.push_back(MachineOperandWithLocation(MO, Loc, Token.location()));
243 if (Token.isNot(MIToken::comma))
247 if (!Operands.empty() && expectAndConsume(MIToken::equal))
250 unsigned OpCode, Flags = 0;
251 if (Token.isError() || parseInstruction(OpCode, Flags))
254 // TODO: Parse the bundle instruction flags.
256 // Parse the remaining machine operands.
257 while (Token.isNot(MIToken::Eof) && Token.isNot(MIToken::kw_debug_location) &&
258 Token.isNot(MIToken::coloncolon)) {
259 auto Loc = Token.location();
260 if (parseMachineOperand(MO))
262 Operands.push_back(MachineOperandWithLocation(MO, Loc, Token.location()));
263 if (Token.is(MIToken::Eof) || Token.is(MIToken::coloncolon))
265 if (Token.isNot(MIToken::comma))
266 return error("expected ',' before the next machine operand");
270 DebugLoc DebugLocation;
271 if (Token.is(MIToken::kw_debug_location)) {
273 if (Token.isNot(MIToken::exclaim))
274 return error("expected a metadata node after 'debug-location'");
275 MDNode *Node = nullptr;
276 if (parseMDNode(Node))
278 DebugLocation = DebugLoc(Node);
281 // Parse the machine memory operands.
282 SmallVector<MachineMemOperand *, 2> MemOperands;
283 if (Token.is(MIToken::coloncolon)) {
285 while (Token.isNot(MIToken::Eof)) {
286 MachineMemOperand *MemOp = nullptr;
287 if (parseMachineMemoryOperand(MemOp))
289 MemOperands.push_back(MemOp);
290 if (Token.is(MIToken::Eof))
292 if (Token.isNot(MIToken::comma))
293 return error("expected ',' before the next machine memory operand");
298 const auto &MCID = MF.getSubtarget().getInstrInfo()->get(OpCode);
299 if (!MCID.isVariadic()) {
300 // FIXME: Move the implicit operand verification to the machine verifier.
301 if (verifyImplicitOperands(Operands, MCID))
305 // TODO: Check for extraneous machine operands.
306 MI = MF.CreateMachineInstr(MCID, DebugLocation, /*NoImplicit=*/true);
308 for (const auto &Operand : Operands)
309 MI->addOperand(MF, Operand.Operand);
310 if (MemOperands.empty())
312 MachineInstr::mmo_iterator MemRefs =
313 MF.allocateMemRefsArray(MemOperands.size());
314 std::copy(MemOperands.begin(), MemOperands.end(), MemRefs);
315 MI->setMemRefs(MemRefs, MemRefs + MemOperands.size());
319 bool MIParser::parseStandaloneMBB(MachineBasicBlock *&MBB) {
321 if (Token.isNot(MIToken::MachineBasicBlock))
322 return error("expected a machine basic block reference");
323 if (parseMBBReference(MBB))
326 if (Token.isNot(MIToken::Eof))
328 "expected end of string after the machine basic block reference");
332 bool MIParser::parseStandaloneNamedRegister(unsigned &Reg) {
334 if (Token.isNot(MIToken::NamedRegister))
335 return error("expected a named register");
336 if (parseRegister(Reg))
339 if (Token.isNot(MIToken::Eof))
340 return error("expected end of string after the register reference");
344 bool MIParser::parseStandaloneVirtualRegister(unsigned &Reg) {
346 if (Token.isNot(MIToken::VirtualRegister))
347 return error("expected a virtual register");
348 if (parseRegister(Reg))
351 if (Token.isNot(MIToken::Eof))
352 return error("expected end of string after the register reference");
356 bool MIParser::parseStandaloneIRBlockReference(const BasicBlock *&BB) {
358 if (Token.isNot(MIToken::IRBlock))
359 return error("expected an IR block reference");
360 unsigned SlotNumber = 0;
361 if (getUnsigned(SlotNumber))
363 BB = getIRBlock(SlotNumber);
365 return error(Twine("use of undefined IR block '%ir-block.") +
366 Twine(SlotNumber) + "'");
368 if (Token.isNot(MIToken::Eof))
369 return error("expected end of string after the IR block reference");
373 static const char *printImplicitRegisterFlag(const MachineOperand &MO) {
374 assert(MO.isImplicit());
375 return MO.isDef() ? "implicit-def" : "implicit";
378 static std::string getRegisterName(const TargetRegisterInfo *TRI,
380 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "expected phys reg");
381 return StringRef(TRI->getName(Reg)).lower();
384 bool MIParser::verifyImplicitOperands(
385 ArrayRef<MachineOperandWithLocation> Operands, const MCInstrDesc &MCID) {
387 // We can't verify call instructions as they can contain arbitrary implicit
388 // register and register mask operands.
391 // Gather all the expected implicit operands.
392 SmallVector<MachineOperand, 4> ImplicitOperands;
393 if (MCID.ImplicitDefs)
394 for (const uint16_t *ImpDefs = MCID.getImplicitDefs(); *ImpDefs; ++ImpDefs)
395 ImplicitOperands.push_back(
396 MachineOperand::CreateReg(*ImpDefs, true, true));
397 if (MCID.ImplicitUses)
398 for (const uint16_t *ImpUses = MCID.getImplicitUses(); *ImpUses; ++ImpUses)
399 ImplicitOperands.push_back(
400 MachineOperand::CreateReg(*ImpUses, false, true));
402 const auto *TRI = MF.getSubtarget().getRegisterInfo();
403 assert(TRI && "Expected target register info");
404 size_t I = ImplicitOperands.size(), J = Operands.size();
409 const auto &ImplicitOperand = ImplicitOperands[I];
410 const auto &Operand = Operands[J].Operand;
411 if (ImplicitOperand.isIdenticalTo(Operand))
413 if (Operand.isReg() && Operand.isImplicit()) {
414 return error(Operands[J].Begin,
415 Twine("expected an implicit register operand '") +
416 printImplicitRegisterFlag(ImplicitOperand) + " %" +
417 getRegisterName(TRI, ImplicitOperand.getReg()) + "'");
420 // TODO: Fix source location when Operands[J].end is right before '=', i.e:
421 // insead of reporting an error at this location:
424 // report the error at the following location:
427 return error(J < Operands.size() ? Operands[J].End : Token.location(),
428 Twine("missing implicit register operand '") +
429 printImplicitRegisterFlag(ImplicitOperands[I]) + " %" +
430 getRegisterName(TRI, ImplicitOperands[I].getReg()) + "'");
435 bool MIParser::parseInstruction(unsigned &OpCode, unsigned &Flags) {
436 if (Token.is(MIToken::kw_frame_setup)) {
437 Flags |= MachineInstr::FrameSetup;
440 if (Token.isNot(MIToken::Identifier))
441 return error("expected a machine instruction");
442 StringRef InstrName = Token.stringValue();
443 if (parseInstrName(InstrName, OpCode))
444 return error(Twine("unknown machine instruction name '") + InstrName + "'");
449 bool MIParser::parseRegister(unsigned &Reg) {
450 switch (Token.kind()) {
451 case MIToken::underscore:
454 case MIToken::NamedRegister: {
455 StringRef Name = Token.stringValue();
456 if (getRegisterByName(Name, Reg))
457 return error(Twine("unknown register name '") + Name + "'");
460 case MIToken::VirtualRegister: {
464 const auto RegInfo = PFS.VirtualRegisterSlots.find(ID);
465 if (RegInfo == PFS.VirtualRegisterSlots.end())
466 return error(Twine("use of undefined virtual register '%") + Twine(ID) +
468 Reg = RegInfo->second;
471 // TODO: Parse other register kinds.
473 llvm_unreachable("The current token should be a register");
478 bool MIParser::parseRegisterFlag(unsigned &Flags) {
479 const unsigned OldFlags = Flags;
480 switch (Token.kind()) {
481 case MIToken::kw_implicit:
482 Flags |= RegState::Implicit;
484 case MIToken::kw_implicit_define:
485 Flags |= RegState::ImplicitDefine;
487 case MIToken::kw_dead:
488 Flags |= RegState::Dead;
490 case MIToken::kw_killed:
491 Flags |= RegState::Kill;
493 case MIToken::kw_undef:
494 Flags |= RegState::Undef;
496 case MIToken::kw_early_clobber:
497 Flags |= RegState::EarlyClobber;
499 case MIToken::kw_debug_use:
500 Flags |= RegState::Debug;
502 // TODO: parse the other register flags.
504 llvm_unreachable("The current token should be a register flag");
506 if (OldFlags == Flags)
507 // We know that the same flag is specified more than once when the flags
509 return error("duplicate '" + Token.stringValue() + "' register flag");
514 bool MIParser::parseSubRegisterIndex(unsigned &SubReg) {
515 assert(Token.is(MIToken::colon));
517 if (Token.isNot(MIToken::Identifier))
518 return error("expected a subregister index after ':'");
519 auto Name = Token.stringValue();
520 SubReg = getSubRegIndex(Name);
522 return error(Twine("use of unknown subregister index '") + Name + "'");
527 bool MIParser::parseRegisterOperand(MachineOperand &Dest, bool IsDef) {
529 unsigned Flags = IsDef ? RegState::Define : 0;
530 while (Token.isRegisterFlag()) {
531 if (parseRegisterFlag(Flags))
534 if (!Token.isRegister())
535 return error("expected a register after register flags");
536 if (parseRegister(Reg))
540 if (Token.is(MIToken::colon)) {
541 if (parseSubRegisterIndex(SubReg))
544 Dest = MachineOperand::CreateReg(
545 Reg, Flags & RegState::Define, Flags & RegState::Implicit,
546 Flags & RegState::Kill, Flags & RegState::Dead, Flags & RegState::Undef,
547 Flags & RegState::EarlyClobber, SubReg, Flags & RegState::Debug);
551 bool MIParser::parseImmediateOperand(MachineOperand &Dest) {
552 assert(Token.is(MIToken::IntegerLiteral));
553 const APSInt &Int = Token.integerValue();
554 if (Int.getMinSignedBits() > 64)
555 return error("integer literal is too large to be an immediate operand");
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::parseTypedImmediateOperand(MachineOperand &Dest) {
572 assert(Token.is(MIToken::IntegerType));
573 auto Loc = Token.location();
575 if (Token.isNot(MIToken::IntegerLiteral))
576 return error("expected an integer literal");
577 const Constant *C = nullptr;
578 if (parseIRConstant(Loc, C))
580 Dest = MachineOperand::CreateCImm(cast<ConstantInt>(C));
584 bool MIParser::parseFPImmediateOperand(MachineOperand &Dest) {
585 auto Loc = Token.location();
587 if (Token.isNot(MIToken::FloatingPointLiteral))
588 return error("expected a floating point literal");
589 const Constant *C = nullptr;
590 if (parseIRConstant(Loc, C))
592 Dest = MachineOperand::CreateFPImm(cast<ConstantFP>(C));
596 bool MIParser::getUnsigned(unsigned &Result) {
597 assert(Token.hasIntegerValue() && "Expected a token with an integer value");
598 const uint64_t Limit = uint64_t(std::numeric_limits<unsigned>::max()) + 1;
599 uint64_t Val64 = Token.integerValue().getLimitedValue(Limit);
601 return error("expected 32-bit integer (too large)");
606 bool MIParser::parseMBBReference(MachineBasicBlock *&MBB) {
607 assert(Token.is(MIToken::MachineBasicBlock));
609 if (getUnsigned(Number))
611 auto MBBInfo = PFS.MBBSlots.find(Number);
612 if (MBBInfo == PFS.MBBSlots.end())
613 return error(Twine("use of undefined machine basic block #") +
615 MBB = MBBInfo->second;
616 if (!Token.stringValue().empty() && Token.stringValue() != MBB->getName())
617 return error(Twine("the name of machine basic block #") + Twine(Number) +
618 " isn't '" + Token.stringValue() + "'");
622 bool MIParser::parseMBBOperand(MachineOperand &Dest) {
623 MachineBasicBlock *MBB;
624 if (parseMBBReference(MBB))
626 Dest = MachineOperand::CreateMBB(MBB);
631 bool MIParser::parseStackObjectOperand(MachineOperand &Dest) {
632 assert(Token.is(MIToken::StackObject));
636 auto ObjectInfo = PFS.StackObjectSlots.find(ID);
637 if (ObjectInfo == PFS.StackObjectSlots.end())
638 return error(Twine("use of undefined stack object '%stack.") + Twine(ID) +
641 if (const auto *Alloca =
642 MF.getFrameInfo()->getObjectAllocation(ObjectInfo->second))
643 Name = Alloca->getName();
644 if (!Token.stringValue().empty() && Token.stringValue() != Name)
645 return error(Twine("the name of the stack object '%stack.") + Twine(ID) +
646 "' isn't '" + Token.stringValue() + "'");
648 Dest = MachineOperand::CreateFI(ObjectInfo->second);
652 bool MIParser::parseFixedStackObjectOperand(MachineOperand &Dest) {
653 assert(Token.is(MIToken::FixedStackObject));
657 auto ObjectInfo = PFS.FixedStackObjectSlots.find(ID);
658 if (ObjectInfo == PFS.FixedStackObjectSlots.end())
659 return error(Twine("use of undefined fixed stack object '%fixed-stack.") +
662 Dest = MachineOperand::CreateFI(ObjectInfo->second);
666 bool MIParser::parseGlobalValue(GlobalValue *&GV) {
667 switch (Token.kind()) {
668 case MIToken::NamedGlobalValue: {
669 const Module *M = MF.getFunction()->getParent();
670 GV = M->getNamedValue(Token.stringValue());
672 return error(Twine("use of undefined global value '@") +
673 Token.rawStringValue() + "'");
676 case MIToken::GlobalValue: {
678 if (getUnsigned(GVIdx))
680 if (GVIdx >= IRSlots.GlobalValues.size())
681 return error(Twine("use of undefined global value '@") + Twine(GVIdx) +
683 GV = IRSlots.GlobalValues[GVIdx];
687 llvm_unreachable("The current token should be a global value");
692 bool MIParser::parseGlobalAddressOperand(MachineOperand &Dest) {
693 GlobalValue *GV = nullptr;
694 if (parseGlobalValue(GV))
696 Dest = MachineOperand::CreateGA(GV, /*Offset=*/0);
697 // TODO: Parse offset and target flags.
702 bool MIParser::parseConstantPoolIndexOperand(MachineOperand &Dest) {
703 assert(Token.is(MIToken::ConstantPoolItem));
707 auto ConstantInfo = PFS.ConstantPoolSlots.find(ID);
708 if (ConstantInfo == PFS.ConstantPoolSlots.end())
709 return error("use of undefined constant '%const." + Twine(ID) + "'");
711 // TODO: Parse offset and target flags.
712 Dest = MachineOperand::CreateCPI(ID, /*Offset=*/0);
716 bool MIParser::parseJumpTableIndexOperand(MachineOperand &Dest) {
717 assert(Token.is(MIToken::JumpTableIndex));
721 auto JumpTableEntryInfo = PFS.JumpTableSlots.find(ID);
722 if (JumpTableEntryInfo == PFS.JumpTableSlots.end())
723 return error("use of undefined jump table '%jump-table." + Twine(ID) + "'");
725 // TODO: Parse target flags.
726 Dest = MachineOperand::CreateJTI(JumpTableEntryInfo->second);
730 bool MIParser::parseExternalSymbolOperand(MachineOperand &Dest) {
731 assert(Token.is(MIToken::ExternalSymbol));
732 const char *Symbol = MF.createExternalSymbolName(Token.stringValue());
734 // TODO: Parse the target flags.
735 Dest = MachineOperand::CreateES(Symbol);
739 bool MIParser::parseMDNode(MDNode *&Node) {
740 assert(Token.is(MIToken::exclaim));
741 auto Loc = Token.location();
743 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
744 return error("expected metadata id after '!'");
748 auto NodeInfo = IRSlots.MetadataNodes.find(ID);
749 if (NodeInfo == IRSlots.MetadataNodes.end())
750 return error(Loc, "use of undefined metadata '!" + Twine(ID) + "'");
752 Node = NodeInfo->second.get();
756 bool MIParser::parseMetadataOperand(MachineOperand &Dest) {
757 MDNode *Node = nullptr;
758 if (parseMDNode(Node))
760 Dest = MachineOperand::CreateMetadata(Node);
764 bool MIParser::parseCFIOffset(int &Offset) {
765 if (Token.isNot(MIToken::IntegerLiteral))
766 return error("expected a cfi offset");
767 if (Token.integerValue().getMinSignedBits() > 32)
768 return error("expected a 32 bit integer (the cfi offset is too large)");
769 Offset = (int)Token.integerValue().getExtValue();
774 bool MIParser::parseCFIRegister(unsigned &Reg) {
775 if (Token.isNot(MIToken::NamedRegister))
776 return error("expected a cfi register");
778 if (parseRegister(LLVMReg))
780 const auto *TRI = MF.getSubtarget().getRegisterInfo();
781 assert(TRI && "Expected target register info");
782 int DwarfReg = TRI->getDwarfRegNum(LLVMReg, true);
784 return error("invalid DWARF register");
785 Reg = (unsigned)DwarfReg;
790 bool MIParser::parseCFIOperand(MachineOperand &Dest) {
791 auto Kind = Token.kind();
793 auto &MMI = MF.getMMI();
798 case MIToken::kw_cfi_offset:
799 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
800 parseCFIOffset(Offset))
803 MMI.addFrameInst(MCCFIInstruction::createOffset(nullptr, Reg, Offset));
805 case MIToken::kw_cfi_def_cfa_register:
806 if (parseCFIRegister(Reg))
809 MMI.addFrameInst(MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
811 case MIToken::kw_cfi_def_cfa_offset:
812 if (parseCFIOffset(Offset))
814 // NB: MCCFIInstruction::createDefCfaOffset negates the offset.
815 CFIIndex = MMI.addFrameInst(
816 MCCFIInstruction::createDefCfaOffset(nullptr, -Offset));
818 case MIToken::kw_cfi_def_cfa:
819 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
820 parseCFIOffset(Offset))
822 // NB: MCCFIInstruction::createDefCfa negates the offset.
824 MMI.addFrameInst(MCCFIInstruction::createDefCfa(nullptr, Reg, -Offset));
827 // TODO: Parse the other CFI operands.
828 llvm_unreachable("The current token should be a cfi operand");
830 Dest = MachineOperand::CreateCFIIndex(CFIIndex);
834 bool MIParser::parseIRBlock(BasicBlock *&BB, const Function &F) {
835 switch (Token.kind()) {
836 case MIToken::NamedIRBlock: {
837 BB = dyn_cast_or_null<BasicBlock>(
838 F.getValueSymbolTable().lookup(Token.stringValue()));
840 return error(Twine("use of undefined IR block '%ir-block.") +
841 Token.rawStringValue() + "'");
844 case MIToken::IRBlock: {
845 unsigned SlotNumber = 0;
846 if (getUnsigned(SlotNumber))
848 BB = const_cast<BasicBlock *>(getIRBlock(SlotNumber));
850 return error(Twine("use of undefined IR block '%ir-block.") +
851 Twine(SlotNumber) + "'");
855 llvm_unreachable("The current token should be an IR block reference");
860 bool MIParser::parseBlockAddressOperand(MachineOperand &Dest) {
861 assert(Token.is(MIToken::kw_blockaddress));
863 if (expectAndConsume(MIToken::lparen))
865 if (Token.isNot(MIToken::GlobalValue) &&
866 Token.isNot(MIToken::NamedGlobalValue))
867 return error("expected a global value");
868 GlobalValue *GV = nullptr;
869 if (parseGlobalValue(GV))
871 auto *F = dyn_cast<Function>(GV);
873 return error("expected an IR function reference");
875 if (expectAndConsume(MIToken::comma))
877 BasicBlock *BB = nullptr;
878 if (Token.isNot(MIToken::IRBlock) && Token.isNot(MIToken::NamedIRBlock))
879 return error("expected an IR block reference");
880 if (parseIRBlock(BB, *F))
883 if (expectAndConsume(MIToken::rparen))
885 // TODO: parse offset and target flags.
886 Dest = MachineOperand::CreateBA(BlockAddress::get(F, BB), /*Offset=*/0);
890 bool MIParser::parseTargetIndexOperand(MachineOperand &Dest) {
891 assert(Token.is(MIToken::kw_target_index));
893 if (expectAndConsume(MIToken::lparen))
895 if (Token.isNot(MIToken::Identifier))
896 return error("expected the name of the target index");
898 if (getTargetIndex(Token.stringValue(), Index))
899 return error("use of undefined target index '" + Token.stringValue() + "'");
901 if (expectAndConsume(MIToken::rparen))
903 // TODO: Parse the offset and target flags.
904 Dest = MachineOperand::CreateTargetIndex(unsigned(Index), /*Offset=*/0);
908 bool MIParser::parseMachineOperand(MachineOperand &Dest) {
909 switch (Token.kind()) {
910 case MIToken::kw_implicit:
911 case MIToken::kw_implicit_define:
912 case MIToken::kw_dead:
913 case MIToken::kw_killed:
914 case MIToken::kw_undef:
915 case MIToken::kw_early_clobber:
916 case MIToken::kw_debug_use:
917 case MIToken::underscore:
918 case MIToken::NamedRegister:
919 case MIToken::VirtualRegister:
920 return parseRegisterOperand(Dest);
921 case MIToken::IntegerLiteral:
922 return parseImmediateOperand(Dest);
923 case MIToken::IntegerType:
924 return parseTypedImmediateOperand(Dest);
925 case MIToken::kw_half:
926 case MIToken::kw_float:
927 case MIToken::kw_double:
928 case MIToken::kw_x86_fp80:
929 case MIToken::kw_fp128:
930 case MIToken::kw_ppc_fp128:
931 return parseFPImmediateOperand(Dest);
932 case MIToken::MachineBasicBlock:
933 return parseMBBOperand(Dest);
934 case MIToken::StackObject:
935 return parseStackObjectOperand(Dest);
936 case MIToken::FixedStackObject:
937 return parseFixedStackObjectOperand(Dest);
938 case MIToken::GlobalValue:
939 case MIToken::NamedGlobalValue:
940 return parseGlobalAddressOperand(Dest);
941 case MIToken::ConstantPoolItem:
942 return parseConstantPoolIndexOperand(Dest);
943 case MIToken::JumpTableIndex:
944 return parseJumpTableIndexOperand(Dest);
945 case MIToken::ExternalSymbol:
946 return parseExternalSymbolOperand(Dest);
947 case MIToken::exclaim:
948 return parseMetadataOperand(Dest);
949 case MIToken::kw_cfi_offset:
950 case MIToken::kw_cfi_def_cfa_register:
951 case MIToken::kw_cfi_def_cfa_offset:
952 case MIToken::kw_cfi_def_cfa:
953 return parseCFIOperand(Dest);
954 case MIToken::kw_blockaddress:
955 return parseBlockAddressOperand(Dest);
956 case MIToken::kw_target_index:
957 return parseTargetIndexOperand(Dest);
960 case MIToken::Identifier:
961 if (const auto *RegMask = getRegMask(Token.stringValue())) {
962 Dest = MachineOperand::CreateRegMask(RegMask);
968 // TODO: parse the other machine operands.
969 return error("expected a machine operand");
974 bool MIParser::parseIRValue(Value *&V) {
975 switch (Token.kind()) {
976 case MIToken::NamedIRValue: {
977 V = MF.getFunction()->getValueSymbolTable().lookup(Token.stringValue());
979 return error(Twine("use of undefined IR value '%ir.") +
980 Token.rawStringValue() + "'");
983 // TODO: Parse unnamed IR value references.
985 llvm_unreachable("The current token should be an IR block reference");
990 bool MIParser::getUint64(uint64_t &Result) {
991 assert(Token.hasIntegerValue());
992 if (Token.integerValue().getActiveBits() > 64)
993 return error("expected 64-bit integer (too large)");
994 Result = Token.integerValue().getZExtValue();
998 bool MIParser::parseMemoryOperandFlag(unsigned &Flags) {
999 switch (Token.kind()) {
1000 case MIToken::kw_volatile:
1001 Flags |= MachineMemOperand::MOVolatile;
1003 // TODO: report an error when we specify the same flag more than once.
1004 // TODO: parse the other memory operand flags.
1006 llvm_unreachable("The current token should be a memory operand flag");
1012 bool MIParser::parseMachineMemoryOperand(MachineMemOperand *&Dest) {
1013 if (expectAndConsume(MIToken::lparen))
1016 while (Token.isMemoryOperandFlag()) {
1017 if (parseMemoryOperandFlag(Flags))
1020 if (Token.isNot(MIToken::Identifier) ||
1021 (Token.stringValue() != "load" && Token.stringValue() != "store"))
1022 return error("expected 'load' or 'store' memory operation");
1023 if (Token.stringValue() == "load")
1024 Flags |= MachineMemOperand::MOLoad;
1026 Flags |= MachineMemOperand::MOStore;
1029 if (Token.isNot(MIToken::IntegerLiteral))
1030 return error("expected the size integer literal after memory operation");
1032 if (getUint64(Size))
1036 const char *Word = Flags & MachineMemOperand::MOLoad ? "from" : "into";
1037 if (Token.isNot(MIToken::Identifier) || Token.stringValue() != Word)
1038 return error(Twine("expected '") + Word + "'");
1041 // TODO: Parse pseudo source values.
1042 if (Token.isNot(MIToken::NamedIRValue))
1043 return error("expected an IR value reference");
1045 if (parseIRValue(V))
1047 if (!V->getType()->isPointerTy())
1048 return error("expected a pointer IR value");
1050 // TODO: Parse the base alignment.
1051 // TODO: Parse the attached metadata nodes.
1052 if (expectAndConsume(MIToken::rparen))
1055 Dest = MF.getMachineMemOperand(MachinePointerInfo(V), Flags, Size, Size);
1059 void MIParser::initNames2InstrOpCodes() {
1060 if (!Names2InstrOpCodes.empty())
1062 const auto *TII = MF.getSubtarget().getInstrInfo();
1063 assert(TII && "Expected target instruction info");
1064 for (unsigned I = 0, E = TII->getNumOpcodes(); I < E; ++I)
1065 Names2InstrOpCodes.insert(std::make_pair(StringRef(TII->getName(I)), I));
1068 bool MIParser::parseInstrName(StringRef InstrName, unsigned &OpCode) {
1069 initNames2InstrOpCodes();
1070 auto InstrInfo = Names2InstrOpCodes.find(InstrName);
1071 if (InstrInfo == Names2InstrOpCodes.end())
1073 OpCode = InstrInfo->getValue();
1077 void MIParser::initNames2Regs() {
1078 if (!Names2Regs.empty())
1080 // The '%noreg' register is the register 0.
1081 Names2Regs.insert(std::make_pair("noreg", 0));
1082 const auto *TRI = MF.getSubtarget().getRegisterInfo();
1083 assert(TRI && "Expected target register info");
1084 for (unsigned I = 0, E = TRI->getNumRegs(); I < E; ++I) {
1086 Names2Regs.insert(std::make_pair(StringRef(TRI->getName(I)).lower(), I))
1089 assert(WasInserted && "Expected registers to be unique case-insensitively");
1093 bool MIParser::getRegisterByName(StringRef RegName, unsigned &Reg) {
1095 auto RegInfo = Names2Regs.find(RegName);
1096 if (RegInfo == Names2Regs.end())
1098 Reg = RegInfo->getValue();
1102 void MIParser::initNames2RegMasks() {
1103 if (!Names2RegMasks.empty())
1105 const auto *TRI = MF.getSubtarget().getRegisterInfo();
1106 assert(TRI && "Expected target register info");
1107 ArrayRef<const uint32_t *> RegMasks = TRI->getRegMasks();
1108 ArrayRef<const char *> RegMaskNames = TRI->getRegMaskNames();
1109 assert(RegMasks.size() == RegMaskNames.size());
1110 for (size_t I = 0, E = RegMasks.size(); I < E; ++I)
1111 Names2RegMasks.insert(
1112 std::make_pair(StringRef(RegMaskNames[I]).lower(), RegMasks[I]));
1115 const uint32_t *MIParser::getRegMask(StringRef Identifier) {
1116 initNames2RegMasks();
1117 auto RegMaskInfo = Names2RegMasks.find(Identifier);
1118 if (RegMaskInfo == Names2RegMasks.end())
1120 return RegMaskInfo->getValue();
1123 void MIParser::initNames2SubRegIndices() {
1124 if (!Names2SubRegIndices.empty())
1126 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1127 for (unsigned I = 1, E = TRI->getNumSubRegIndices(); I < E; ++I)
1128 Names2SubRegIndices.insert(
1129 std::make_pair(StringRef(TRI->getSubRegIndexName(I)).lower(), I));
1132 unsigned MIParser::getSubRegIndex(StringRef Name) {
1133 initNames2SubRegIndices();
1134 auto SubRegInfo = Names2SubRegIndices.find(Name);
1135 if (SubRegInfo == Names2SubRegIndices.end())
1137 return SubRegInfo->getValue();
1140 void MIParser::initSlots2BasicBlocks() {
1141 if (!Slots2BasicBlocks.empty())
1143 const auto &F = *MF.getFunction();
1144 ModuleSlotTracker MST(F.getParent());
1145 MST.incorporateFunction(F);
1146 for (auto &BB : F) {
1149 int Slot = MST.getLocalSlot(&BB);
1152 Slots2BasicBlocks.insert(std::make_pair(unsigned(Slot), &BB));
1156 const BasicBlock *MIParser::getIRBlock(unsigned Slot) {
1157 initSlots2BasicBlocks();
1158 auto BlockInfo = Slots2BasicBlocks.find(Slot);
1159 if (BlockInfo == Slots2BasicBlocks.end())
1161 return BlockInfo->second;
1164 void MIParser::initNames2TargetIndices() {
1165 if (!Names2TargetIndices.empty())
1167 const auto *TII = MF.getSubtarget().getInstrInfo();
1168 assert(TII && "Expected target instruction info");
1169 auto Indices = TII->getSerializableTargetIndices();
1170 for (const auto &I : Indices)
1171 Names2TargetIndices.insert(std::make_pair(StringRef(I.second), I.first));
1174 bool MIParser::getTargetIndex(StringRef Name, int &Index) {
1175 initNames2TargetIndices();
1176 auto IndexInfo = Names2TargetIndices.find(Name);
1177 if (IndexInfo == Names2TargetIndices.end())
1179 Index = IndexInfo->second;
1183 bool llvm::parseMachineInstr(MachineInstr *&MI, SourceMgr &SM,
1184 MachineFunction &MF, StringRef Src,
1185 const PerFunctionMIParsingState &PFS,
1186 const SlotMapping &IRSlots, SMDiagnostic &Error) {
1187 return MIParser(SM, MF, Error, Src, PFS, IRSlots).parse(MI);
1190 bool llvm::parseMBBReference(MachineBasicBlock *&MBB, SourceMgr &SM,
1191 MachineFunction &MF, StringRef Src,
1192 const PerFunctionMIParsingState &PFS,
1193 const SlotMapping &IRSlots, SMDiagnostic &Error) {
1194 return MIParser(SM, MF, Error, Src, PFS, IRSlots).parseStandaloneMBB(MBB);
1197 bool llvm::parseNamedRegisterReference(unsigned &Reg, SourceMgr &SM,
1198 MachineFunction &MF, StringRef Src,
1199 const PerFunctionMIParsingState &PFS,
1200 const SlotMapping &IRSlots,
1201 SMDiagnostic &Error) {
1202 return MIParser(SM, MF, Error, Src, PFS, IRSlots)
1203 .parseStandaloneNamedRegister(Reg);
1206 bool llvm::parseVirtualRegisterReference(unsigned &Reg, SourceMgr &SM,
1207 MachineFunction &MF, StringRef Src,
1208 const PerFunctionMIParsingState &PFS,
1209 const SlotMapping &IRSlots,
1210 SMDiagnostic &Error) {
1211 return MIParser(SM, MF, Error, Src, PFS, IRSlots)
1212 .parseStandaloneVirtualRegister(Reg);
1215 bool llvm::parseIRBlockReference(const BasicBlock *&BB, SourceMgr &SM,
1216 MachineFunction &MF, StringRef Src,
1217 const PerFunctionMIParsingState &PFS,
1218 const SlotMapping &IRSlots,
1219 SMDiagnostic &Error) {
1220 return MIParser(SM, MF, Error, Src, PFS, IRSlots)
1221 .parseStandaloneIRBlockReference(BB);