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/MachineModuleInfo.h"
25 #include "llvm/IR/Instructions.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/IR/ModuleSlotTracker.h"
29 #include "llvm/IR/ValueSymbolTable.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Support/SourceMgr.h"
32 #include "llvm/Target/TargetSubtargetInfo.h"
33 #include "llvm/Target/TargetInstrInfo.h"
39 struct StringValueUtility {
41 std::string UnescapedString;
43 StringValueUtility(const MIToken &Token) {
44 if (Token.isStringValueQuoted()) {
45 Token.unescapeQuotedStringValue(UnescapedString);
46 String = UnescapedString;
49 String = Token.stringValue();
52 operator StringRef() const { return String; }
55 /// A wrapper struct around the 'MachineOperand' struct that includes a source
57 struct MachineOperandWithLocation {
58 MachineOperand Operand;
59 StringRef::iterator Begin;
60 StringRef::iterator End;
62 MachineOperandWithLocation(const MachineOperand &Operand,
63 StringRef::iterator Begin, StringRef::iterator End)
64 : Operand(Operand), Begin(Begin), End(End) {}
71 StringRef Source, CurrentSource;
73 const PerFunctionMIParsingState &PFS;
74 /// Maps from indices to unnamed global values and metadata nodes.
75 const SlotMapping &IRSlots;
76 /// Maps from instruction names to op codes.
77 StringMap<unsigned> Names2InstrOpCodes;
78 /// Maps from register names to registers.
79 StringMap<unsigned> Names2Regs;
80 /// Maps from register mask names to register masks.
81 StringMap<const uint32_t *> Names2RegMasks;
82 /// Maps from subregister names to subregister indices.
83 StringMap<unsigned> Names2SubRegIndices;
84 /// Maps from slot numbers to function's unnamed basic blocks.
85 DenseMap<unsigned, const BasicBlock *> Slots2BasicBlocks;
86 /// Maps from target index names to target indices.
87 StringMap<int> Names2TargetIndices;
90 MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
91 StringRef Source, const PerFunctionMIParsingState &PFS,
92 const SlotMapping &IRSlots);
96 /// Report an error at the current location with the given message.
98 /// This function always return true.
99 bool error(const Twine &Msg);
101 /// Report an error at the given location with the given message.
103 /// This function always return true.
104 bool error(StringRef::iterator Loc, const Twine &Msg);
106 bool parse(MachineInstr *&MI);
107 bool parseStandaloneMBB(MachineBasicBlock *&MBB);
108 bool parseStandaloneNamedRegister(unsigned &Reg);
109 bool parseStandaloneVirtualRegister(unsigned &Reg);
110 bool parseStandaloneIRBlockReference(const BasicBlock *&BB);
112 bool parseRegister(unsigned &Reg);
113 bool parseRegisterFlag(unsigned &Flags);
114 bool parseSubRegisterIndex(unsigned &SubReg);
115 bool parseRegisterOperand(MachineOperand &Dest, bool IsDef = false);
116 bool parseImmediateOperand(MachineOperand &Dest);
117 bool parseFPImmediateOperand(MachineOperand &Dest);
118 bool parseMBBReference(MachineBasicBlock *&MBB);
119 bool parseMBBOperand(MachineOperand &Dest);
120 bool parseStackObjectOperand(MachineOperand &Dest);
121 bool parseFixedStackObjectOperand(MachineOperand &Dest);
122 bool parseGlobalValue(GlobalValue *&GV);
123 bool parseGlobalAddressOperand(MachineOperand &Dest);
124 bool parseConstantPoolIndexOperand(MachineOperand &Dest);
125 bool parseJumpTableIndexOperand(MachineOperand &Dest);
126 bool parseExternalSymbolOperand(MachineOperand &Dest);
127 bool parseMDNode(MDNode *&Node);
128 bool parseMetadataOperand(MachineOperand &Dest);
129 bool parseCFIOffset(int &Offset);
130 bool parseCFIRegister(unsigned &Reg);
131 bool parseCFIOperand(MachineOperand &Dest);
132 bool parseIRBlock(BasicBlock *&BB, const Function &F);
133 bool parseBlockAddressOperand(MachineOperand &Dest);
134 bool parseTargetIndexOperand(MachineOperand &Dest);
135 bool parseMachineOperand(MachineOperand &Dest);
138 /// Convert the integer literal in the current token into an unsigned integer.
140 /// Return true if an error occurred.
141 bool getUnsigned(unsigned &Result);
143 /// If the current token is of the given kind, consume it and return false.
144 /// Otherwise report an error and return true.
145 bool expectAndConsume(MIToken::TokenKind TokenKind);
147 void initNames2InstrOpCodes();
149 /// Try to convert an instruction name to an opcode. Return true if the
150 /// instruction name is invalid.
151 bool parseInstrName(StringRef InstrName, unsigned &OpCode);
153 bool parseInstruction(unsigned &OpCode, unsigned &Flags);
155 bool verifyImplicitOperands(ArrayRef<MachineOperandWithLocation> Operands,
156 const MCInstrDesc &MCID);
158 void initNames2Regs();
160 /// Try to convert a register name to a register number. Return true if the
161 /// register name is invalid.
162 bool getRegisterByName(StringRef RegName, unsigned &Reg);
164 void initNames2RegMasks();
166 /// Check if the given identifier is a name of a register mask.
168 /// Return null if the identifier isn't a register mask.
169 const uint32_t *getRegMask(StringRef Identifier);
171 void initNames2SubRegIndices();
173 /// Check if the given identifier is a name of a subregister index.
175 /// Return 0 if the name isn't a subregister index class.
176 unsigned getSubRegIndex(StringRef Name);
178 void initSlots2BasicBlocks();
180 const BasicBlock *getIRBlock(unsigned Slot);
182 void initNames2TargetIndices();
184 /// Try to convert a name of target index to the corresponding target index.
186 /// Return true if the name isn't a name of a target index.
187 bool getTargetIndex(StringRef Name, int &Index);
190 } // end anonymous namespace
192 MIParser::MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
193 StringRef Source, const PerFunctionMIParsingState &PFS,
194 const SlotMapping &IRSlots)
195 : SM(SM), MF(MF), Error(Error), Source(Source), CurrentSource(Source),
196 Token(MIToken::Error, StringRef()), PFS(PFS), IRSlots(IRSlots) {}
198 void MIParser::lex() {
199 CurrentSource = lexMIToken(
200 CurrentSource, Token,
201 [this](StringRef::iterator Loc, const Twine &Msg) { error(Loc, Msg); });
204 bool MIParser::error(const Twine &Msg) { return error(Token.location(), Msg); }
206 bool MIParser::error(StringRef::iterator Loc, const Twine &Msg) {
207 assert(Loc >= Source.data() && Loc <= (Source.data() + Source.size()));
208 Error = SMDiagnostic(
210 SM.getMemoryBuffer(SM.getMainFileID())->getBufferIdentifier(), 1,
211 Loc - Source.data(), SourceMgr::DK_Error, Msg.str(), Source, None, None);
215 static const char *toString(MIToken::TokenKind TokenKind) {
221 case MIToken::lparen:
223 case MIToken::rparen:
226 return "<unknown token>";
230 bool MIParser::expectAndConsume(MIToken::TokenKind TokenKind) {
231 if (Token.isNot(TokenKind))
232 return error(Twine("expected ") + toString(TokenKind));
237 bool MIParser::parse(MachineInstr *&MI) {
240 // Parse any register operands before '='
241 MachineOperand MO = MachineOperand::CreateImm(0);
242 SmallVector<MachineOperandWithLocation, 8> Operands;
243 while (Token.isRegister() || Token.isRegisterFlag()) {
244 auto Loc = Token.location();
245 if (parseRegisterOperand(MO, /*IsDef=*/true))
247 Operands.push_back(MachineOperandWithLocation(MO, Loc, Token.location()));
248 if (Token.isNot(MIToken::comma))
252 if (!Operands.empty() && expectAndConsume(MIToken::equal))
255 unsigned OpCode, Flags = 0;
256 if (Token.isError() || parseInstruction(OpCode, Flags))
259 // TODO: Parse the bundle instruction flags and memory operands.
261 // Parse the remaining machine operands.
262 while (Token.isNot(MIToken::Eof) && Token.isNot(MIToken::kw_debug_location)) {
263 auto Loc = Token.location();
264 if (parseMachineOperand(MO))
266 Operands.push_back(MachineOperandWithLocation(MO, Loc, Token.location()));
267 if (Token.is(MIToken::Eof))
269 if (Token.isNot(MIToken::comma))
270 return error("expected ',' before the next machine operand");
274 DebugLoc DebugLocation;
275 if (Token.is(MIToken::kw_debug_location)) {
277 if (Token.isNot(MIToken::exclaim))
278 return error("expected a metadata node after 'debug-location'");
279 MDNode *Node = nullptr;
280 if (parseMDNode(Node))
282 DebugLocation = DebugLoc(Node);
285 const auto &MCID = MF.getSubtarget().getInstrInfo()->get(OpCode);
286 if (!MCID.isVariadic()) {
287 // FIXME: Move the implicit operand verification to the machine verifier.
288 if (verifyImplicitOperands(Operands, MCID))
292 // TODO: Check for extraneous machine operands.
293 MI = MF.CreateMachineInstr(MCID, DebugLocation, /*NoImplicit=*/true);
295 for (const auto &Operand : Operands)
296 MI->addOperand(MF, Operand.Operand);
300 bool MIParser::parseStandaloneMBB(MachineBasicBlock *&MBB) {
302 if (Token.isNot(MIToken::MachineBasicBlock))
303 return error("expected a machine basic block reference");
304 if (parseMBBReference(MBB))
307 if (Token.isNot(MIToken::Eof))
309 "expected end of string after the machine basic block reference");
313 bool MIParser::parseStandaloneNamedRegister(unsigned &Reg) {
315 if (Token.isNot(MIToken::NamedRegister))
316 return error("expected a named register");
317 if (parseRegister(Reg))
320 if (Token.isNot(MIToken::Eof))
321 return error("expected end of string after the register reference");
325 bool MIParser::parseStandaloneVirtualRegister(unsigned &Reg) {
327 if (Token.isNot(MIToken::VirtualRegister))
328 return error("expected a virtual register");
329 if (parseRegister(Reg))
332 if (Token.isNot(MIToken::Eof))
333 return error("expected end of string after the register reference");
337 bool MIParser::parseStandaloneIRBlockReference(const BasicBlock *&BB) {
339 if (Token.isNot(MIToken::IRBlock))
340 return error("expected an IR block reference");
341 unsigned SlotNumber = 0;
342 if (getUnsigned(SlotNumber))
344 BB = getIRBlock(SlotNumber);
346 return error(Twine("use of undefined IR block '%ir-block.") +
347 Twine(SlotNumber) + "'");
349 if (Token.isNot(MIToken::Eof))
350 return error("expected end of string after the IR block reference");
354 static const char *printImplicitRegisterFlag(const MachineOperand &MO) {
355 assert(MO.isImplicit());
356 return MO.isDef() ? "implicit-def" : "implicit";
359 static std::string getRegisterName(const TargetRegisterInfo *TRI,
361 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "expected phys reg");
362 return StringRef(TRI->getName(Reg)).lower();
365 bool MIParser::verifyImplicitOperands(
366 ArrayRef<MachineOperandWithLocation> Operands, const MCInstrDesc &MCID) {
368 // We can't verify call instructions as they can contain arbitrary implicit
369 // register and register mask operands.
372 // Gather all the expected implicit operands.
373 SmallVector<MachineOperand, 4> ImplicitOperands;
374 if (MCID.ImplicitDefs)
375 for (const uint16_t *ImpDefs = MCID.getImplicitDefs(); *ImpDefs; ++ImpDefs)
376 ImplicitOperands.push_back(
377 MachineOperand::CreateReg(*ImpDefs, true, true));
378 if (MCID.ImplicitUses)
379 for (const uint16_t *ImpUses = MCID.getImplicitUses(); *ImpUses; ++ImpUses)
380 ImplicitOperands.push_back(
381 MachineOperand::CreateReg(*ImpUses, false, true));
383 const auto *TRI = MF.getSubtarget().getRegisterInfo();
384 assert(TRI && "Expected target register info");
385 size_t I = ImplicitOperands.size(), J = Operands.size();
390 const auto &ImplicitOperand = ImplicitOperands[I];
391 const auto &Operand = Operands[J].Operand;
392 if (ImplicitOperand.isIdenticalTo(Operand))
394 if (Operand.isReg() && Operand.isImplicit()) {
395 return error(Operands[J].Begin,
396 Twine("expected an implicit register operand '") +
397 printImplicitRegisterFlag(ImplicitOperand) + " %" +
398 getRegisterName(TRI, ImplicitOperand.getReg()) + "'");
401 // TODO: Fix source location when Operands[J].end is right before '=', i.e:
402 // insead of reporting an error at this location:
405 // report the error at the following location:
408 return error(J < Operands.size() ? Operands[J].End : Token.location(),
409 Twine("missing implicit register operand '") +
410 printImplicitRegisterFlag(ImplicitOperands[I]) + " %" +
411 getRegisterName(TRI, ImplicitOperands[I].getReg()) + "'");
416 bool MIParser::parseInstruction(unsigned &OpCode, unsigned &Flags) {
417 if (Token.is(MIToken::kw_frame_setup)) {
418 Flags |= MachineInstr::FrameSetup;
421 if (Token.isNot(MIToken::Identifier))
422 return error("expected a machine instruction");
423 StringRef InstrName = Token.stringValue();
424 if (parseInstrName(InstrName, OpCode))
425 return error(Twine("unknown machine instruction name '") + InstrName + "'");
430 bool MIParser::parseRegister(unsigned &Reg) {
431 switch (Token.kind()) {
432 case MIToken::underscore:
435 case MIToken::NamedRegister: {
436 StringRef Name = Token.stringValue();
437 if (getRegisterByName(Name, Reg))
438 return error(Twine("unknown register name '") + Name + "'");
441 case MIToken::VirtualRegister: {
445 const auto RegInfo = PFS.VirtualRegisterSlots.find(ID);
446 if (RegInfo == PFS.VirtualRegisterSlots.end())
447 return error(Twine("use of undefined virtual register '%") + Twine(ID) +
449 Reg = RegInfo->second;
452 // TODO: Parse other register kinds.
454 llvm_unreachable("The current token should be a register");
459 bool MIParser::parseRegisterFlag(unsigned &Flags) {
460 switch (Token.kind()) {
461 case MIToken::kw_implicit:
462 Flags |= RegState::Implicit;
464 case MIToken::kw_implicit_define:
465 Flags |= RegState::ImplicitDefine;
467 case MIToken::kw_dead:
468 Flags |= RegState::Dead;
470 case MIToken::kw_killed:
471 Flags |= RegState::Kill;
473 case MIToken::kw_undef:
474 Flags |= RegState::Undef;
476 // TODO: report an error when we specify the same flag more than once.
477 // TODO: parse the other register flags.
479 llvm_unreachable("The current token should be a register flag");
485 bool MIParser::parseSubRegisterIndex(unsigned &SubReg) {
486 assert(Token.is(MIToken::colon));
488 if (Token.isNot(MIToken::Identifier))
489 return error("expected a subregister index after ':'");
490 auto Name = Token.stringValue();
491 SubReg = getSubRegIndex(Name);
493 return error(Twine("use of unknown subregister index '") + Name + "'");
498 bool MIParser::parseRegisterOperand(MachineOperand &Dest, bool IsDef) {
500 unsigned Flags = IsDef ? RegState::Define : 0;
501 while (Token.isRegisterFlag()) {
502 if (parseRegisterFlag(Flags))
505 if (!Token.isRegister())
506 return error("expected a register after register flags");
507 if (parseRegister(Reg))
511 if (Token.is(MIToken::colon)) {
512 if (parseSubRegisterIndex(SubReg))
515 Dest = MachineOperand::CreateReg(
516 Reg, Flags & RegState::Define, Flags & RegState::Implicit,
517 Flags & RegState::Kill, Flags & RegState::Dead, Flags & RegState::Undef,
518 /*isEarlyClobber=*/false, SubReg);
522 bool MIParser::parseImmediateOperand(MachineOperand &Dest) {
523 assert(Token.is(MIToken::IntegerLiteral));
524 const APSInt &Int = Token.integerValue();
525 if (Int.getMinSignedBits() > 64)
526 // TODO: Replace this with an error when we can parse CIMM Machine Operands.
527 llvm_unreachable("Can't parse large integer literals yet!");
528 Dest = MachineOperand::CreateImm(Int.getExtValue());
533 bool MIParser::parseFPImmediateOperand(MachineOperand &Dest) {
534 auto Loc = Token.location();
536 if (Token.isNot(MIToken::FloatingPointLiteral))
537 return error("expected a floating point literal");
538 auto Source = StringRef(Loc, Token.stringValue().end() - Loc).str();
542 parseConstantValue(Source.c_str(), Err, *MF.getFunction()->getParent());
544 return error(Loc + Err.getColumnNo(), Err.getMessage());
545 Dest = MachineOperand::CreateFPImm(cast<ConstantFP>(C));
549 bool MIParser::getUnsigned(unsigned &Result) {
550 assert(Token.hasIntegerValue() && "Expected a token with an integer value");
551 const uint64_t Limit = uint64_t(std::numeric_limits<unsigned>::max()) + 1;
552 uint64_t Val64 = Token.integerValue().getLimitedValue(Limit);
554 return error("expected 32-bit integer (too large)");
559 bool MIParser::parseMBBReference(MachineBasicBlock *&MBB) {
560 assert(Token.is(MIToken::MachineBasicBlock));
562 if (getUnsigned(Number))
564 auto MBBInfo = PFS.MBBSlots.find(Number);
565 if (MBBInfo == PFS.MBBSlots.end())
566 return error(Twine("use of undefined machine basic block #") +
568 MBB = MBBInfo->second;
569 if (!Token.stringValue().empty() && Token.stringValue() != MBB->getName())
570 return error(Twine("the name of machine basic block #") + Twine(Number) +
571 " isn't '" + Token.stringValue() + "'");
575 bool MIParser::parseMBBOperand(MachineOperand &Dest) {
576 MachineBasicBlock *MBB;
577 if (parseMBBReference(MBB))
579 Dest = MachineOperand::CreateMBB(MBB);
584 bool MIParser::parseStackObjectOperand(MachineOperand &Dest) {
585 assert(Token.is(MIToken::StackObject));
589 auto ObjectInfo = PFS.StackObjectSlots.find(ID);
590 if (ObjectInfo == PFS.StackObjectSlots.end())
591 return error(Twine("use of undefined stack object '%stack.") + Twine(ID) +
594 if (const auto *Alloca =
595 MF.getFrameInfo()->getObjectAllocation(ObjectInfo->second))
596 Name = Alloca->getName();
597 if (!Token.stringValue().empty() && Token.stringValue() != Name)
598 return error(Twine("the name of the stack object '%stack.") + Twine(ID) +
599 "' isn't '" + Token.stringValue() + "'");
601 Dest = MachineOperand::CreateFI(ObjectInfo->second);
605 bool MIParser::parseFixedStackObjectOperand(MachineOperand &Dest) {
606 assert(Token.is(MIToken::FixedStackObject));
610 auto ObjectInfo = PFS.FixedStackObjectSlots.find(ID);
611 if (ObjectInfo == PFS.FixedStackObjectSlots.end())
612 return error(Twine("use of undefined fixed stack object '%fixed-stack.") +
615 Dest = MachineOperand::CreateFI(ObjectInfo->second);
619 bool MIParser::parseGlobalValue(GlobalValue *&GV) {
620 switch (Token.kind()) {
621 case MIToken::NamedGlobalValue:
622 case MIToken::QuotedNamedGlobalValue: {
623 StringValueUtility Name(Token);
624 const Module *M = MF.getFunction()->getParent();
625 GV = M->getNamedValue(Name);
627 return error(Twine("use of undefined global value '@") +
628 Token.rawStringValue() + "'");
631 case MIToken::GlobalValue: {
633 if (getUnsigned(GVIdx))
635 if (GVIdx >= IRSlots.GlobalValues.size())
636 return error(Twine("use of undefined global value '@") + Twine(GVIdx) +
638 GV = IRSlots.GlobalValues[GVIdx];
642 llvm_unreachable("The current token should be a global value");
647 bool MIParser::parseGlobalAddressOperand(MachineOperand &Dest) {
648 GlobalValue *GV = nullptr;
649 if (parseGlobalValue(GV))
651 Dest = MachineOperand::CreateGA(GV, /*Offset=*/0);
652 // TODO: Parse offset and target flags.
657 bool MIParser::parseConstantPoolIndexOperand(MachineOperand &Dest) {
658 assert(Token.is(MIToken::ConstantPoolItem));
662 auto ConstantInfo = PFS.ConstantPoolSlots.find(ID);
663 if (ConstantInfo == PFS.ConstantPoolSlots.end())
664 return error("use of undefined constant '%const." + Twine(ID) + "'");
666 // TODO: Parse offset and target flags.
667 Dest = MachineOperand::CreateCPI(ID, /*Offset=*/0);
671 bool MIParser::parseJumpTableIndexOperand(MachineOperand &Dest) {
672 assert(Token.is(MIToken::JumpTableIndex));
676 auto JumpTableEntryInfo = PFS.JumpTableSlots.find(ID);
677 if (JumpTableEntryInfo == PFS.JumpTableSlots.end())
678 return error("use of undefined jump table '%jump-table." + Twine(ID) + "'");
680 // TODO: Parse target flags.
681 Dest = MachineOperand::CreateJTI(JumpTableEntryInfo->second);
685 bool MIParser::parseExternalSymbolOperand(MachineOperand &Dest) {
686 assert(Token.is(MIToken::ExternalSymbol) ||
687 Token.is(MIToken::QuotedExternalSymbol));
688 StringValueUtility Name(Token);
689 const char *Symbol = MF.createExternalSymbolName(Name);
691 // TODO: Parse the target flags.
692 Dest = MachineOperand::CreateES(Symbol);
696 bool MIParser::parseMDNode(MDNode *&Node) {
697 assert(Token.is(MIToken::exclaim));
698 auto Loc = Token.location();
700 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
701 return error("expected metadata id after '!'");
705 auto NodeInfo = IRSlots.MetadataNodes.find(ID);
706 if (NodeInfo == IRSlots.MetadataNodes.end())
707 return error(Loc, "use of undefined metadata '!" + Twine(ID) + "'");
709 Node = NodeInfo->second.get();
713 bool MIParser::parseMetadataOperand(MachineOperand &Dest) {
714 MDNode *Node = nullptr;
715 if (parseMDNode(Node))
717 Dest = MachineOperand::CreateMetadata(Node);
721 bool MIParser::parseCFIOffset(int &Offset) {
722 if (Token.isNot(MIToken::IntegerLiteral))
723 return error("expected a cfi offset");
724 if (Token.integerValue().getMinSignedBits() > 32)
725 return error("expected a 32 bit integer (the cfi offset is too large)");
726 Offset = (int)Token.integerValue().getExtValue();
731 bool MIParser::parseCFIRegister(unsigned &Reg) {
732 if (Token.isNot(MIToken::NamedRegister))
733 return error("expected a cfi register");
735 if (parseRegister(LLVMReg))
737 const auto *TRI = MF.getSubtarget().getRegisterInfo();
738 assert(TRI && "Expected target register info");
739 int DwarfReg = TRI->getDwarfRegNum(LLVMReg, true);
741 return error("invalid DWARF register");
742 Reg = (unsigned)DwarfReg;
747 bool MIParser::parseCFIOperand(MachineOperand &Dest) {
748 auto Kind = Token.kind();
750 auto &MMI = MF.getMMI();
755 case MIToken::kw_cfi_offset:
756 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
757 parseCFIOffset(Offset))
760 MMI.addFrameInst(MCCFIInstruction::createOffset(nullptr, Reg, Offset));
762 case MIToken::kw_cfi_def_cfa_register:
763 if (parseCFIRegister(Reg))
766 MMI.addFrameInst(MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
768 case MIToken::kw_cfi_def_cfa_offset:
769 if (parseCFIOffset(Offset))
771 // NB: MCCFIInstruction::createDefCfaOffset negates the offset.
772 CFIIndex = MMI.addFrameInst(
773 MCCFIInstruction::createDefCfaOffset(nullptr, -Offset));
775 case MIToken::kw_cfi_def_cfa:
776 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
777 parseCFIOffset(Offset))
779 // NB: MCCFIInstruction::createDefCfa negates the offset.
781 MMI.addFrameInst(MCCFIInstruction::createDefCfa(nullptr, Reg, -Offset));
784 // TODO: Parse the other CFI operands.
785 llvm_unreachable("The current token should be a cfi operand");
787 Dest = MachineOperand::CreateCFIIndex(CFIIndex);
791 bool MIParser::parseIRBlock(BasicBlock *&BB, const Function &F) {
792 switch (Token.kind()) {
793 case MIToken::NamedIRBlock:
794 case MIToken::QuotedNamedIRBlock: {
795 StringValueUtility Name(Token);
796 BB = dyn_cast_or_null<BasicBlock>(F.getValueSymbolTable().lookup(Name));
798 return error(Twine("use of undefined IR block '%ir-block.") +
799 Token.rawStringValue() + "'");
802 case MIToken::IRBlock: {
803 unsigned SlotNumber = 0;
804 if (getUnsigned(SlotNumber))
806 BB = const_cast<BasicBlock *>(getIRBlock(SlotNumber));
808 return error(Twine("use of undefined IR block '%ir-block.") +
809 Twine(SlotNumber) + "'");
813 llvm_unreachable("The current token should be an IR block reference");
818 bool MIParser::parseBlockAddressOperand(MachineOperand &Dest) {
819 assert(Token.is(MIToken::kw_blockaddress));
821 if (expectAndConsume(MIToken::lparen))
823 if (Token.isNot(MIToken::GlobalValue) &&
824 Token.isNot(MIToken::NamedGlobalValue) &&
825 Token.isNot(MIToken::QuotedNamedGlobalValue))
826 return error("expected a global value");
827 GlobalValue *GV = nullptr;
828 if (parseGlobalValue(GV))
830 auto *F = dyn_cast<Function>(GV);
832 return error("expected an IR function reference");
834 if (expectAndConsume(MIToken::comma))
836 BasicBlock *BB = nullptr;
837 if (Token.isNot(MIToken::IRBlock) && Token.isNot(MIToken::NamedIRBlock) &&
838 Token.isNot(MIToken::QuotedNamedIRBlock))
839 return error("expected an IR block reference");
840 if (parseIRBlock(BB, *F))
843 if (expectAndConsume(MIToken::rparen))
845 // TODO: parse offset and target flags.
846 Dest = MachineOperand::CreateBA(BlockAddress::get(F, BB), /*Offset=*/0);
850 bool MIParser::parseTargetIndexOperand(MachineOperand &Dest) {
851 assert(Token.is(MIToken::kw_target_index));
853 if (expectAndConsume(MIToken::lparen))
855 if (Token.isNot(MIToken::Identifier))
856 return error("expected the name of the target index");
858 if (getTargetIndex(Token.stringValue(), Index))
859 return error("use of undefined target index '" + Token.stringValue() + "'");
861 if (expectAndConsume(MIToken::rparen))
863 // TODO: Parse the offset and target flags.
864 Dest = MachineOperand::CreateTargetIndex(unsigned(Index), /*Offset=*/0);
868 bool MIParser::parseMachineOperand(MachineOperand &Dest) {
869 switch (Token.kind()) {
870 case MIToken::kw_implicit:
871 case MIToken::kw_implicit_define:
872 case MIToken::kw_dead:
873 case MIToken::kw_killed:
874 case MIToken::kw_undef:
875 case MIToken::underscore:
876 case MIToken::NamedRegister:
877 case MIToken::VirtualRegister:
878 return parseRegisterOperand(Dest);
879 case MIToken::IntegerLiteral:
880 return parseImmediateOperand(Dest);
881 case MIToken::kw_half:
882 case MIToken::kw_float:
883 case MIToken::kw_double:
884 case MIToken::kw_x86_fp80:
885 case MIToken::kw_fp128:
886 case MIToken::kw_ppc_fp128:
887 return parseFPImmediateOperand(Dest);
888 case MIToken::MachineBasicBlock:
889 return parseMBBOperand(Dest);
890 case MIToken::StackObject:
891 return parseStackObjectOperand(Dest);
892 case MIToken::FixedStackObject:
893 return parseFixedStackObjectOperand(Dest);
894 case MIToken::GlobalValue:
895 case MIToken::NamedGlobalValue:
896 case MIToken::QuotedNamedGlobalValue:
897 return parseGlobalAddressOperand(Dest);
898 case MIToken::ConstantPoolItem:
899 return parseConstantPoolIndexOperand(Dest);
900 case MIToken::JumpTableIndex:
901 return parseJumpTableIndexOperand(Dest);
902 case MIToken::ExternalSymbol:
903 case MIToken::QuotedExternalSymbol:
904 return parseExternalSymbolOperand(Dest);
905 case MIToken::exclaim:
906 return parseMetadataOperand(Dest);
907 case MIToken::kw_cfi_offset:
908 case MIToken::kw_cfi_def_cfa_register:
909 case MIToken::kw_cfi_def_cfa_offset:
910 case MIToken::kw_cfi_def_cfa:
911 return parseCFIOperand(Dest);
912 case MIToken::kw_blockaddress:
913 return parseBlockAddressOperand(Dest);
914 case MIToken::kw_target_index:
915 return parseTargetIndexOperand(Dest);
918 case MIToken::Identifier:
919 if (const auto *RegMask = getRegMask(Token.stringValue())) {
920 Dest = MachineOperand::CreateRegMask(RegMask);
926 // TODO: parse the other machine operands.
927 return error("expected a machine operand");
932 void MIParser::initNames2InstrOpCodes() {
933 if (!Names2InstrOpCodes.empty())
935 const auto *TII = MF.getSubtarget().getInstrInfo();
936 assert(TII && "Expected target instruction info");
937 for (unsigned I = 0, E = TII->getNumOpcodes(); I < E; ++I)
938 Names2InstrOpCodes.insert(std::make_pair(StringRef(TII->getName(I)), I));
941 bool MIParser::parseInstrName(StringRef InstrName, unsigned &OpCode) {
942 initNames2InstrOpCodes();
943 auto InstrInfo = Names2InstrOpCodes.find(InstrName);
944 if (InstrInfo == Names2InstrOpCodes.end())
946 OpCode = InstrInfo->getValue();
950 void MIParser::initNames2Regs() {
951 if (!Names2Regs.empty())
953 // The '%noreg' register is the register 0.
954 Names2Regs.insert(std::make_pair("noreg", 0));
955 const auto *TRI = MF.getSubtarget().getRegisterInfo();
956 assert(TRI && "Expected target register info");
957 for (unsigned I = 0, E = TRI->getNumRegs(); I < E; ++I) {
959 Names2Regs.insert(std::make_pair(StringRef(TRI->getName(I)).lower(), I))
962 assert(WasInserted && "Expected registers to be unique case-insensitively");
966 bool MIParser::getRegisterByName(StringRef RegName, unsigned &Reg) {
968 auto RegInfo = Names2Regs.find(RegName);
969 if (RegInfo == Names2Regs.end())
971 Reg = RegInfo->getValue();
975 void MIParser::initNames2RegMasks() {
976 if (!Names2RegMasks.empty())
978 const auto *TRI = MF.getSubtarget().getRegisterInfo();
979 assert(TRI && "Expected target register info");
980 ArrayRef<const uint32_t *> RegMasks = TRI->getRegMasks();
981 ArrayRef<const char *> RegMaskNames = TRI->getRegMaskNames();
982 assert(RegMasks.size() == RegMaskNames.size());
983 for (size_t I = 0, E = RegMasks.size(); I < E; ++I)
984 Names2RegMasks.insert(
985 std::make_pair(StringRef(RegMaskNames[I]).lower(), RegMasks[I]));
988 const uint32_t *MIParser::getRegMask(StringRef Identifier) {
989 initNames2RegMasks();
990 auto RegMaskInfo = Names2RegMasks.find(Identifier);
991 if (RegMaskInfo == Names2RegMasks.end())
993 return RegMaskInfo->getValue();
996 void MIParser::initNames2SubRegIndices() {
997 if (!Names2SubRegIndices.empty())
999 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1000 for (unsigned I = 1, E = TRI->getNumSubRegIndices(); I < E; ++I)
1001 Names2SubRegIndices.insert(
1002 std::make_pair(StringRef(TRI->getSubRegIndexName(I)).lower(), I));
1005 unsigned MIParser::getSubRegIndex(StringRef Name) {
1006 initNames2SubRegIndices();
1007 auto SubRegInfo = Names2SubRegIndices.find(Name);
1008 if (SubRegInfo == Names2SubRegIndices.end())
1010 return SubRegInfo->getValue();
1013 void MIParser::initSlots2BasicBlocks() {
1014 if (!Slots2BasicBlocks.empty())
1016 const auto &F = *MF.getFunction();
1017 ModuleSlotTracker MST(F.getParent());
1018 MST.incorporateFunction(F);
1019 for (auto &BB : F) {
1022 int Slot = MST.getLocalSlot(&BB);
1025 Slots2BasicBlocks.insert(std::make_pair(unsigned(Slot), &BB));
1029 const BasicBlock *MIParser::getIRBlock(unsigned Slot) {
1030 initSlots2BasicBlocks();
1031 auto BlockInfo = Slots2BasicBlocks.find(Slot);
1032 if (BlockInfo == Slots2BasicBlocks.end())
1034 return BlockInfo->second;
1037 void MIParser::initNames2TargetIndices() {
1038 if (!Names2TargetIndices.empty())
1040 const auto *TII = MF.getSubtarget().getInstrInfo();
1041 assert(TII && "Expected target instruction info");
1042 auto Indices = TII->getSerializableTargetIndices();
1043 for (const auto &I : Indices)
1044 Names2TargetIndices.insert(std::make_pair(StringRef(I.second), I.first));
1047 bool MIParser::getTargetIndex(StringRef Name, int &Index) {
1048 initNames2TargetIndices();
1049 auto IndexInfo = Names2TargetIndices.find(Name);
1050 if (IndexInfo == Names2TargetIndices.end())
1052 Index = IndexInfo->second;
1056 bool llvm::parseMachineInstr(MachineInstr *&MI, SourceMgr &SM,
1057 MachineFunction &MF, StringRef Src,
1058 const PerFunctionMIParsingState &PFS,
1059 const SlotMapping &IRSlots, SMDiagnostic &Error) {
1060 return MIParser(SM, MF, Error, Src, PFS, IRSlots).parse(MI);
1063 bool llvm::parseMBBReference(MachineBasicBlock *&MBB, SourceMgr &SM,
1064 MachineFunction &MF, StringRef Src,
1065 const PerFunctionMIParsingState &PFS,
1066 const SlotMapping &IRSlots, SMDiagnostic &Error) {
1067 return MIParser(SM, MF, Error, Src, PFS, IRSlots).parseStandaloneMBB(MBB);
1070 bool llvm::parseNamedRegisterReference(unsigned &Reg, SourceMgr &SM,
1071 MachineFunction &MF, StringRef Src,
1072 const PerFunctionMIParsingState &PFS,
1073 const SlotMapping &IRSlots,
1074 SMDiagnostic &Error) {
1075 return MIParser(SM, MF, Error, Src, PFS, IRSlots)
1076 .parseStandaloneNamedRegister(Reg);
1079 bool llvm::parseVirtualRegisterReference(unsigned &Reg, SourceMgr &SM,
1080 MachineFunction &MF, StringRef Src,
1081 const PerFunctionMIParsingState &PFS,
1082 const SlotMapping &IRSlots,
1083 SMDiagnostic &Error) {
1084 return MIParser(SM, MF, Error, Src, PFS, IRSlots)
1085 .parseStandaloneVirtualRegister(Reg);
1088 bool llvm::parseIRBlockReference(const BasicBlock *&BB, SourceMgr &SM,
1089 MachineFunction &MF, StringRef Src,
1090 const PerFunctionMIParsingState &PFS,
1091 const SlotMapping &IRSlots,
1092 SMDiagnostic &Error) {
1093 return MIParser(SM, MF, Error, Src, PFS, IRSlots)
1094 .parseStandaloneIRBlockReference(BB);