1 //===- MIParser.cpp - Machine instructions parser implementation ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the parsing of machine instructions.
12 //===----------------------------------------------------------------------===//
16 #include "llvm/ADT/StringMap.h"
17 #include "llvm/AsmParser/Parser.h"
18 #include "llvm/AsmParser/SlotMapping.h"
19 #include "llvm/CodeGen/MachineBasicBlock.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineInstr.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/CodeGen/MachineMemOperand.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/IR/Instructions.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/IR/ModuleSlotTracker.h"
30 #include "llvm/IR/ValueSymbolTable.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/Support/SourceMgr.h"
33 #include "llvm/Target/TargetSubtargetInfo.h"
34 #include "llvm/Target/TargetInstrInfo.h"
40 /// A wrapper struct around the 'MachineOperand' struct that includes a source
42 struct MachineOperandWithLocation {
43 MachineOperand Operand;
44 StringRef::iterator Begin;
45 StringRef::iterator End;
47 MachineOperandWithLocation(const MachineOperand &Operand,
48 StringRef::iterator Begin, StringRef::iterator End)
49 : Operand(Operand), Begin(Begin), End(End) {}
56 StringRef Source, CurrentSource;
58 const PerFunctionMIParsingState &PFS;
59 /// Maps from indices to unnamed global values and metadata nodes.
60 const SlotMapping &IRSlots;
61 /// Maps from instruction names to op codes.
62 StringMap<unsigned> Names2InstrOpCodes;
63 /// Maps from register names to registers.
64 StringMap<unsigned> Names2Regs;
65 /// Maps from register mask names to register masks.
66 StringMap<const uint32_t *> Names2RegMasks;
67 /// Maps from subregister names to subregister indices.
68 StringMap<unsigned> Names2SubRegIndices;
69 /// Maps from slot numbers to function's unnamed basic blocks.
70 DenseMap<unsigned, const BasicBlock *> Slots2BasicBlocks;
71 /// Maps from target index names to target indices.
72 StringMap<int> Names2TargetIndices;
73 /// Maps from direct target flag names to the direct target flag values.
74 StringMap<unsigned> Names2DirectTargetFlags;
77 MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
78 StringRef Source, const PerFunctionMIParsingState &PFS,
79 const SlotMapping &IRSlots);
83 /// Report an error at the current location with the given message.
85 /// This function always return true.
86 bool error(const Twine &Msg);
88 /// Report an error at the given location with the given message.
90 /// This function always return true.
91 bool error(StringRef::iterator Loc, const Twine &Msg);
93 bool parse(MachineInstr *&MI);
94 bool parseStandaloneMBB(MachineBasicBlock *&MBB);
95 bool parseStandaloneNamedRegister(unsigned &Reg);
96 bool parseStandaloneVirtualRegister(unsigned &Reg);
97 bool parseStandaloneIRBlockReference(const BasicBlock *&BB);
99 bool parseRegister(unsigned &Reg);
100 bool parseRegisterFlag(unsigned &Flags);
101 bool parseSubRegisterIndex(unsigned &SubReg);
102 bool parseRegisterOperand(MachineOperand &Dest, bool IsDef = false);
103 bool parseImmediateOperand(MachineOperand &Dest);
104 bool parseIRConstant(StringRef::iterator Loc, const Constant *&C);
105 bool parseTypedImmediateOperand(MachineOperand &Dest);
106 bool parseFPImmediateOperand(MachineOperand &Dest);
107 bool parseMBBReference(MachineBasicBlock *&MBB);
108 bool parseMBBOperand(MachineOperand &Dest);
109 bool parseStackObjectOperand(MachineOperand &Dest);
110 bool parseFixedStackObjectOperand(MachineOperand &Dest);
111 bool parseGlobalValue(GlobalValue *&GV);
112 bool parseGlobalAddressOperand(MachineOperand &Dest);
113 bool parseConstantPoolIndexOperand(MachineOperand &Dest);
114 bool parseJumpTableIndexOperand(MachineOperand &Dest);
115 bool parseExternalSymbolOperand(MachineOperand &Dest);
116 bool parseMDNode(MDNode *&Node);
117 bool parseMetadataOperand(MachineOperand &Dest);
118 bool parseCFIOffset(int &Offset);
119 bool parseCFIRegister(unsigned &Reg);
120 bool parseCFIOperand(MachineOperand &Dest);
121 bool parseIRBlock(BasicBlock *&BB, const Function &F);
122 bool parseBlockAddressOperand(MachineOperand &Dest);
123 bool parseTargetIndexOperand(MachineOperand &Dest);
124 bool parseLiveoutRegisterMaskOperand(MachineOperand &Dest);
125 bool parseMachineOperand(MachineOperand &Dest);
126 bool parseMachineOperandAndTargetFlags(MachineOperand &Dest);
127 bool parseOffset(int64_t &Offset);
128 bool parseOperandsOffset(MachineOperand &Op);
129 bool parseIRValue(Value *&V);
130 bool parseMemoryOperandFlag(unsigned &Flags);
131 bool parseMachineMemoryOperand(MachineMemOperand *&Dest);
134 /// Convert the integer literal in the current token into an unsigned integer.
136 /// Return true if an error occurred.
137 bool getUnsigned(unsigned &Result);
139 /// Convert the integer literal in the current token into an uint64.
141 /// Return true if an error occurred.
142 bool getUint64(uint64_t &Result);
144 /// If the current token is of the given kind, consume it and return false.
145 /// Otherwise report an error and return true.
146 bool expectAndConsume(MIToken::TokenKind TokenKind);
148 void initNames2InstrOpCodes();
150 /// Try to convert an instruction name to an opcode. Return true if the
151 /// instruction name is invalid.
152 bool parseInstrName(StringRef InstrName, unsigned &OpCode);
154 bool parseInstruction(unsigned &OpCode, unsigned &Flags);
156 bool verifyImplicitOperands(ArrayRef<MachineOperandWithLocation> Operands,
157 const MCInstrDesc &MCID);
159 void initNames2Regs();
161 /// Try to convert a register name to a register number. Return true if the
162 /// register name is invalid.
163 bool getRegisterByName(StringRef RegName, unsigned &Reg);
165 void initNames2RegMasks();
167 /// Check if the given identifier is a name of a register mask.
169 /// Return null if the identifier isn't a register mask.
170 const uint32_t *getRegMask(StringRef Identifier);
172 void initNames2SubRegIndices();
174 /// Check if the given identifier is a name of a subregister index.
176 /// Return 0 if the name isn't a subregister index class.
177 unsigned getSubRegIndex(StringRef Name);
179 const BasicBlock *getIRBlock(unsigned Slot);
180 const BasicBlock *getIRBlock(unsigned Slot, const Function &F);
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);
189 void initNames2DirectTargetFlags();
191 /// Try to convert a name of a direct target flag to the corresponding
194 /// Return true if the name isn't a name of a direct flag.
195 bool getDirectTargetFlag(StringRef Name, unsigned &Flag);
198 } // end anonymous namespace
200 MIParser::MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
201 StringRef Source, const PerFunctionMIParsingState &PFS,
202 const SlotMapping &IRSlots)
203 : SM(SM), MF(MF), Error(Error), Source(Source), CurrentSource(Source),
204 PFS(PFS), IRSlots(IRSlots) {}
206 void MIParser::lex() {
207 CurrentSource = lexMIToken(
208 CurrentSource, Token,
209 [this](StringRef::iterator Loc, const Twine &Msg) { error(Loc, Msg); });
212 bool MIParser::error(const Twine &Msg) { return error(Token.location(), Msg); }
214 bool MIParser::error(StringRef::iterator Loc, const Twine &Msg) {
215 assert(Loc >= Source.data() && Loc <= (Source.data() + Source.size()));
216 Error = SMDiagnostic(
218 SM.getMemoryBuffer(SM.getMainFileID())->getBufferIdentifier(), 1,
219 Loc - Source.data(), SourceMgr::DK_Error, Msg.str(), Source, None, None);
223 static const char *toString(MIToken::TokenKind TokenKind) {
229 case MIToken::lparen:
231 case MIToken::rparen:
234 return "<unknown token>";
238 bool MIParser::expectAndConsume(MIToken::TokenKind TokenKind) {
239 if (Token.isNot(TokenKind))
240 return error(Twine("expected ") + toString(TokenKind));
245 bool MIParser::parse(MachineInstr *&MI) {
248 // Parse any register operands before '='
249 MachineOperand MO = MachineOperand::CreateImm(0);
250 SmallVector<MachineOperandWithLocation, 8> Operands;
251 while (Token.isRegister() || Token.isRegisterFlag()) {
252 auto Loc = Token.location();
253 if (parseRegisterOperand(MO, /*IsDef=*/true))
255 Operands.push_back(MachineOperandWithLocation(MO, Loc, Token.location()));
256 if (Token.isNot(MIToken::comma))
260 if (!Operands.empty() && expectAndConsume(MIToken::equal))
263 unsigned OpCode, Flags = 0;
264 if (Token.isError() || parseInstruction(OpCode, Flags))
267 // TODO: Parse the bundle instruction flags.
269 // Parse the remaining machine operands.
270 while (Token.isNot(MIToken::Eof) && Token.isNot(MIToken::kw_debug_location) &&
271 Token.isNot(MIToken::coloncolon)) {
272 auto Loc = Token.location();
273 if (parseMachineOperandAndTargetFlags(MO))
275 Operands.push_back(MachineOperandWithLocation(MO, Loc, Token.location()));
276 if (Token.is(MIToken::Eof) || Token.is(MIToken::coloncolon))
278 if (Token.isNot(MIToken::comma))
279 return error("expected ',' before the next machine operand");
283 DebugLoc DebugLocation;
284 if (Token.is(MIToken::kw_debug_location)) {
286 if (Token.isNot(MIToken::exclaim))
287 return error("expected a metadata node after 'debug-location'");
288 MDNode *Node = nullptr;
289 if (parseMDNode(Node))
291 DebugLocation = DebugLoc(Node);
294 // Parse the machine memory operands.
295 SmallVector<MachineMemOperand *, 2> MemOperands;
296 if (Token.is(MIToken::coloncolon)) {
298 while (Token.isNot(MIToken::Eof)) {
299 MachineMemOperand *MemOp = nullptr;
300 if (parseMachineMemoryOperand(MemOp))
302 MemOperands.push_back(MemOp);
303 if (Token.is(MIToken::Eof))
305 if (Token.isNot(MIToken::comma))
306 return error("expected ',' before the next machine memory operand");
311 const auto &MCID = MF.getSubtarget().getInstrInfo()->get(OpCode);
312 if (!MCID.isVariadic()) {
313 // FIXME: Move the implicit operand verification to the machine verifier.
314 if (verifyImplicitOperands(Operands, MCID))
318 // TODO: Check for extraneous machine operands.
319 MI = MF.CreateMachineInstr(MCID, DebugLocation, /*NoImplicit=*/true);
321 for (const auto &Operand : Operands)
322 MI->addOperand(MF, Operand.Operand);
323 if (MemOperands.empty())
325 MachineInstr::mmo_iterator MemRefs =
326 MF.allocateMemRefsArray(MemOperands.size());
327 std::copy(MemOperands.begin(), MemOperands.end(), MemRefs);
328 MI->setMemRefs(MemRefs, MemRefs + MemOperands.size());
332 bool MIParser::parseStandaloneMBB(MachineBasicBlock *&MBB) {
334 if (Token.isNot(MIToken::MachineBasicBlock))
335 return error("expected a machine basic block reference");
336 if (parseMBBReference(MBB))
339 if (Token.isNot(MIToken::Eof))
341 "expected end of string after the machine basic block reference");
345 bool MIParser::parseStandaloneNamedRegister(unsigned &Reg) {
347 if (Token.isNot(MIToken::NamedRegister))
348 return error("expected a named register");
349 if (parseRegister(Reg))
352 if (Token.isNot(MIToken::Eof))
353 return error("expected end of string after the register reference");
357 bool MIParser::parseStandaloneVirtualRegister(unsigned &Reg) {
359 if (Token.isNot(MIToken::VirtualRegister))
360 return error("expected a virtual register");
361 if (parseRegister(Reg))
364 if (Token.isNot(MIToken::Eof))
365 return error("expected end of string after the register reference");
369 bool MIParser::parseStandaloneIRBlockReference(const BasicBlock *&BB) {
371 if (Token.isNot(MIToken::IRBlock))
372 return error("expected an IR block reference");
373 unsigned SlotNumber = 0;
374 if (getUnsigned(SlotNumber))
376 BB = getIRBlock(SlotNumber);
378 return error(Twine("use of undefined IR block '%ir-block.") +
379 Twine(SlotNumber) + "'");
381 if (Token.isNot(MIToken::Eof))
382 return error("expected end of string after the IR block reference");
386 static const char *printImplicitRegisterFlag(const MachineOperand &MO) {
387 assert(MO.isImplicit());
388 return MO.isDef() ? "implicit-def" : "implicit";
391 static std::string getRegisterName(const TargetRegisterInfo *TRI,
393 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "expected phys reg");
394 return StringRef(TRI->getName(Reg)).lower();
397 bool MIParser::verifyImplicitOperands(
398 ArrayRef<MachineOperandWithLocation> Operands, const MCInstrDesc &MCID) {
400 // We can't verify call instructions as they can contain arbitrary implicit
401 // register and register mask operands.
404 // Gather all the expected implicit operands.
405 SmallVector<MachineOperand, 4> ImplicitOperands;
406 if (MCID.ImplicitDefs)
407 for (const uint16_t *ImpDefs = MCID.getImplicitDefs(); *ImpDefs; ++ImpDefs)
408 ImplicitOperands.push_back(
409 MachineOperand::CreateReg(*ImpDefs, true, true));
410 if (MCID.ImplicitUses)
411 for (const uint16_t *ImpUses = MCID.getImplicitUses(); *ImpUses; ++ImpUses)
412 ImplicitOperands.push_back(
413 MachineOperand::CreateReg(*ImpUses, false, true));
415 const auto *TRI = MF.getSubtarget().getRegisterInfo();
416 assert(TRI && "Expected target register info");
417 size_t I = ImplicitOperands.size(), J = Operands.size();
422 const auto &ImplicitOperand = ImplicitOperands[I];
423 const auto &Operand = Operands[J].Operand;
424 if (ImplicitOperand.isIdenticalTo(Operand))
426 if (Operand.isReg() && Operand.isImplicit()) {
427 return error(Operands[J].Begin,
428 Twine("expected an implicit register operand '") +
429 printImplicitRegisterFlag(ImplicitOperand) + " %" +
430 getRegisterName(TRI, ImplicitOperand.getReg()) + "'");
433 // TODO: Fix source location when Operands[J].end is right before '=', i.e:
434 // insead of reporting an error at this location:
437 // report the error at the following location:
440 return error(J < Operands.size() ? Operands[J].End : Token.location(),
441 Twine("missing implicit register operand '") +
442 printImplicitRegisterFlag(ImplicitOperands[I]) + " %" +
443 getRegisterName(TRI, ImplicitOperands[I].getReg()) + "'");
448 bool MIParser::parseInstruction(unsigned &OpCode, unsigned &Flags) {
449 if (Token.is(MIToken::kw_frame_setup)) {
450 Flags |= MachineInstr::FrameSetup;
453 if (Token.isNot(MIToken::Identifier))
454 return error("expected a machine instruction");
455 StringRef InstrName = Token.stringValue();
456 if (parseInstrName(InstrName, OpCode))
457 return error(Twine("unknown machine instruction name '") + InstrName + "'");
462 bool MIParser::parseRegister(unsigned &Reg) {
463 switch (Token.kind()) {
464 case MIToken::underscore:
467 case MIToken::NamedRegister: {
468 StringRef Name = Token.stringValue();
469 if (getRegisterByName(Name, Reg))
470 return error(Twine("unknown register name '") + Name + "'");
473 case MIToken::VirtualRegister: {
477 const auto RegInfo = PFS.VirtualRegisterSlots.find(ID);
478 if (RegInfo == PFS.VirtualRegisterSlots.end())
479 return error(Twine("use of undefined virtual register '%") + Twine(ID) +
481 Reg = RegInfo->second;
484 // TODO: Parse other register kinds.
486 llvm_unreachable("The current token should be a register");
491 bool MIParser::parseRegisterFlag(unsigned &Flags) {
492 const unsigned OldFlags = Flags;
493 switch (Token.kind()) {
494 case MIToken::kw_implicit:
495 Flags |= RegState::Implicit;
497 case MIToken::kw_implicit_define:
498 Flags |= RegState::ImplicitDefine;
500 case MIToken::kw_dead:
501 Flags |= RegState::Dead;
503 case MIToken::kw_killed:
504 Flags |= RegState::Kill;
506 case MIToken::kw_undef:
507 Flags |= RegState::Undef;
509 case MIToken::kw_early_clobber:
510 Flags |= RegState::EarlyClobber;
512 case MIToken::kw_debug_use:
513 Flags |= RegState::Debug;
515 // TODO: parse the other register flags.
517 llvm_unreachable("The current token should be a register flag");
519 if (OldFlags == Flags)
520 // We know that the same flag is specified more than once when the flags
522 return error("duplicate '" + Token.stringValue() + "' register flag");
527 bool MIParser::parseSubRegisterIndex(unsigned &SubReg) {
528 assert(Token.is(MIToken::colon));
530 if (Token.isNot(MIToken::Identifier))
531 return error("expected a subregister index after ':'");
532 auto Name = Token.stringValue();
533 SubReg = getSubRegIndex(Name);
535 return error(Twine("use of unknown subregister index '") + Name + "'");
540 bool MIParser::parseRegisterOperand(MachineOperand &Dest, bool IsDef) {
542 unsigned Flags = IsDef ? RegState::Define : 0;
543 while (Token.isRegisterFlag()) {
544 if (parseRegisterFlag(Flags))
547 if (!Token.isRegister())
548 return error("expected a register after register flags");
549 if (parseRegister(Reg))
553 if (Token.is(MIToken::colon)) {
554 if (parseSubRegisterIndex(SubReg))
557 Dest = MachineOperand::CreateReg(
558 Reg, Flags & RegState::Define, Flags & RegState::Implicit,
559 Flags & RegState::Kill, Flags & RegState::Dead, Flags & RegState::Undef,
560 Flags & RegState::EarlyClobber, SubReg, Flags & RegState::Debug);
564 bool MIParser::parseImmediateOperand(MachineOperand &Dest) {
565 assert(Token.is(MIToken::IntegerLiteral));
566 const APSInt &Int = Token.integerValue();
567 if (Int.getMinSignedBits() > 64)
568 return error("integer literal is too large to be an immediate operand");
569 Dest = MachineOperand::CreateImm(Int.getExtValue());
574 bool MIParser::parseIRConstant(StringRef::iterator Loc, const Constant *&C) {
575 auto Source = StringRef(Loc, Token.range().end() - Loc).str();
578 C = parseConstantValue(Source.c_str(), Err, *MF.getFunction()->getParent());
580 return error(Loc + Err.getColumnNo(), Err.getMessage());
584 bool MIParser::parseTypedImmediateOperand(MachineOperand &Dest) {
585 assert(Token.is(MIToken::IntegerType));
586 auto Loc = Token.location();
588 if (Token.isNot(MIToken::IntegerLiteral))
589 return error("expected an integer literal");
590 const Constant *C = nullptr;
591 if (parseIRConstant(Loc, C))
593 Dest = MachineOperand::CreateCImm(cast<ConstantInt>(C));
597 bool MIParser::parseFPImmediateOperand(MachineOperand &Dest) {
598 auto Loc = Token.location();
600 if (Token.isNot(MIToken::FloatingPointLiteral))
601 return error("expected a floating point literal");
602 const Constant *C = nullptr;
603 if (parseIRConstant(Loc, C))
605 Dest = MachineOperand::CreateFPImm(cast<ConstantFP>(C));
609 bool MIParser::getUnsigned(unsigned &Result) {
610 assert(Token.hasIntegerValue() && "Expected a token with an integer value");
611 const uint64_t Limit = uint64_t(std::numeric_limits<unsigned>::max()) + 1;
612 uint64_t Val64 = Token.integerValue().getLimitedValue(Limit);
614 return error("expected 32-bit integer (too large)");
619 bool MIParser::parseMBBReference(MachineBasicBlock *&MBB) {
620 assert(Token.is(MIToken::MachineBasicBlock));
622 if (getUnsigned(Number))
624 auto MBBInfo = PFS.MBBSlots.find(Number);
625 if (MBBInfo == PFS.MBBSlots.end())
626 return error(Twine("use of undefined machine basic block #") +
628 MBB = MBBInfo->second;
629 if (!Token.stringValue().empty() && Token.stringValue() != MBB->getName())
630 return error(Twine("the name of machine basic block #") + Twine(Number) +
631 " isn't '" + Token.stringValue() + "'");
635 bool MIParser::parseMBBOperand(MachineOperand &Dest) {
636 MachineBasicBlock *MBB;
637 if (parseMBBReference(MBB))
639 Dest = MachineOperand::CreateMBB(MBB);
644 bool MIParser::parseStackObjectOperand(MachineOperand &Dest) {
645 assert(Token.is(MIToken::StackObject));
649 auto ObjectInfo = PFS.StackObjectSlots.find(ID);
650 if (ObjectInfo == PFS.StackObjectSlots.end())
651 return error(Twine("use of undefined stack object '%stack.") + Twine(ID) +
654 if (const auto *Alloca =
655 MF.getFrameInfo()->getObjectAllocation(ObjectInfo->second))
656 Name = Alloca->getName();
657 if (!Token.stringValue().empty() && Token.stringValue() != Name)
658 return error(Twine("the name of the stack object '%stack.") + Twine(ID) +
659 "' isn't '" + Token.stringValue() + "'");
661 Dest = MachineOperand::CreateFI(ObjectInfo->second);
665 bool MIParser::parseFixedStackObjectOperand(MachineOperand &Dest) {
666 assert(Token.is(MIToken::FixedStackObject));
670 auto ObjectInfo = PFS.FixedStackObjectSlots.find(ID);
671 if (ObjectInfo == PFS.FixedStackObjectSlots.end())
672 return error(Twine("use of undefined fixed stack object '%fixed-stack.") +
675 Dest = MachineOperand::CreateFI(ObjectInfo->second);
679 bool MIParser::parseGlobalValue(GlobalValue *&GV) {
680 switch (Token.kind()) {
681 case MIToken::NamedGlobalValue: {
682 const Module *M = MF.getFunction()->getParent();
683 GV = M->getNamedValue(Token.stringValue());
685 return error(Twine("use of undefined global value '") + Token.range() +
689 case MIToken::GlobalValue: {
691 if (getUnsigned(GVIdx))
693 if (GVIdx >= IRSlots.GlobalValues.size())
694 return error(Twine("use of undefined global value '@") + Twine(GVIdx) +
696 GV = IRSlots.GlobalValues[GVIdx];
700 llvm_unreachable("The current token should be a global value");
705 bool MIParser::parseGlobalAddressOperand(MachineOperand &Dest) {
706 GlobalValue *GV = nullptr;
707 if (parseGlobalValue(GV))
710 Dest = MachineOperand::CreateGA(GV, /*Offset=*/0);
711 if (parseOperandsOffset(Dest))
716 bool MIParser::parseConstantPoolIndexOperand(MachineOperand &Dest) {
717 assert(Token.is(MIToken::ConstantPoolItem));
721 auto ConstantInfo = PFS.ConstantPoolSlots.find(ID);
722 if (ConstantInfo == PFS.ConstantPoolSlots.end())
723 return error("use of undefined constant '%const." + Twine(ID) + "'");
725 Dest = MachineOperand::CreateCPI(ID, /*Offset=*/0);
726 if (parseOperandsOffset(Dest))
731 bool MIParser::parseJumpTableIndexOperand(MachineOperand &Dest) {
732 assert(Token.is(MIToken::JumpTableIndex));
736 auto JumpTableEntryInfo = PFS.JumpTableSlots.find(ID);
737 if (JumpTableEntryInfo == PFS.JumpTableSlots.end())
738 return error("use of undefined jump table '%jump-table." + Twine(ID) + "'");
740 Dest = MachineOperand::CreateJTI(JumpTableEntryInfo->second);
744 bool MIParser::parseExternalSymbolOperand(MachineOperand &Dest) {
745 assert(Token.is(MIToken::ExternalSymbol));
746 const char *Symbol = MF.createExternalSymbolName(Token.stringValue());
748 Dest = MachineOperand::CreateES(Symbol);
749 if (parseOperandsOffset(Dest))
754 bool MIParser::parseMDNode(MDNode *&Node) {
755 assert(Token.is(MIToken::exclaim));
756 auto Loc = Token.location();
758 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
759 return error("expected metadata id after '!'");
763 auto NodeInfo = IRSlots.MetadataNodes.find(ID);
764 if (NodeInfo == IRSlots.MetadataNodes.end())
765 return error(Loc, "use of undefined metadata '!" + Twine(ID) + "'");
767 Node = NodeInfo->second.get();
771 bool MIParser::parseMetadataOperand(MachineOperand &Dest) {
772 MDNode *Node = nullptr;
773 if (parseMDNode(Node))
775 Dest = MachineOperand::CreateMetadata(Node);
779 bool MIParser::parseCFIOffset(int &Offset) {
780 if (Token.isNot(MIToken::IntegerLiteral))
781 return error("expected a cfi offset");
782 if (Token.integerValue().getMinSignedBits() > 32)
783 return error("expected a 32 bit integer (the cfi offset is too large)");
784 Offset = (int)Token.integerValue().getExtValue();
789 bool MIParser::parseCFIRegister(unsigned &Reg) {
790 if (Token.isNot(MIToken::NamedRegister))
791 return error("expected a cfi register");
793 if (parseRegister(LLVMReg))
795 const auto *TRI = MF.getSubtarget().getRegisterInfo();
796 assert(TRI && "Expected target register info");
797 int DwarfReg = TRI->getDwarfRegNum(LLVMReg, true);
799 return error("invalid DWARF register");
800 Reg = (unsigned)DwarfReg;
805 bool MIParser::parseCFIOperand(MachineOperand &Dest) {
806 auto Kind = Token.kind();
808 auto &MMI = MF.getMMI();
813 case MIToken::kw_cfi_offset:
814 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
815 parseCFIOffset(Offset))
818 MMI.addFrameInst(MCCFIInstruction::createOffset(nullptr, Reg, Offset));
820 case MIToken::kw_cfi_def_cfa_register:
821 if (parseCFIRegister(Reg))
824 MMI.addFrameInst(MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
826 case MIToken::kw_cfi_def_cfa_offset:
827 if (parseCFIOffset(Offset))
829 // NB: MCCFIInstruction::createDefCfaOffset negates the offset.
830 CFIIndex = MMI.addFrameInst(
831 MCCFIInstruction::createDefCfaOffset(nullptr, -Offset));
833 case MIToken::kw_cfi_def_cfa:
834 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
835 parseCFIOffset(Offset))
837 // NB: MCCFIInstruction::createDefCfa negates the offset.
839 MMI.addFrameInst(MCCFIInstruction::createDefCfa(nullptr, Reg, -Offset));
842 // TODO: Parse the other CFI operands.
843 llvm_unreachable("The current token should be a cfi operand");
845 Dest = MachineOperand::CreateCFIIndex(CFIIndex);
849 bool MIParser::parseIRBlock(BasicBlock *&BB, const Function &F) {
850 switch (Token.kind()) {
851 case MIToken::NamedIRBlock: {
852 BB = dyn_cast_or_null<BasicBlock>(
853 F.getValueSymbolTable().lookup(Token.stringValue()));
855 return error(Twine("use of undefined IR block '") + Token.range() + "'");
858 case MIToken::IRBlock: {
859 unsigned SlotNumber = 0;
860 if (getUnsigned(SlotNumber))
862 BB = const_cast<BasicBlock *>(getIRBlock(SlotNumber, F));
864 return error(Twine("use of undefined IR block '%ir-block.") +
865 Twine(SlotNumber) + "'");
869 llvm_unreachable("The current token should be an IR block reference");
874 bool MIParser::parseBlockAddressOperand(MachineOperand &Dest) {
875 assert(Token.is(MIToken::kw_blockaddress));
877 if (expectAndConsume(MIToken::lparen))
879 if (Token.isNot(MIToken::GlobalValue) &&
880 Token.isNot(MIToken::NamedGlobalValue))
881 return error("expected a global value");
882 GlobalValue *GV = nullptr;
883 if (parseGlobalValue(GV))
885 auto *F = dyn_cast<Function>(GV);
887 return error("expected an IR function reference");
889 if (expectAndConsume(MIToken::comma))
891 BasicBlock *BB = nullptr;
892 if (Token.isNot(MIToken::IRBlock) && Token.isNot(MIToken::NamedIRBlock))
893 return error("expected an IR block reference");
894 if (parseIRBlock(BB, *F))
897 if (expectAndConsume(MIToken::rparen))
899 Dest = MachineOperand::CreateBA(BlockAddress::get(F, BB), /*Offset=*/0);
900 if (parseOperandsOffset(Dest))
905 bool MIParser::parseTargetIndexOperand(MachineOperand &Dest) {
906 assert(Token.is(MIToken::kw_target_index));
908 if (expectAndConsume(MIToken::lparen))
910 if (Token.isNot(MIToken::Identifier))
911 return error("expected the name of the target index");
913 if (getTargetIndex(Token.stringValue(), Index))
914 return error("use of undefined target index '" + Token.stringValue() + "'");
916 if (expectAndConsume(MIToken::rparen))
918 Dest = MachineOperand::CreateTargetIndex(unsigned(Index), /*Offset=*/0);
919 if (parseOperandsOffset(Dest))
924 bool MIParser::parseLiveoutRegisterMaskOperand(MachineOperand &Dest) {
925 assert(Token.is(MIToken::kw_liveout));
926 const auto *TRI = MF.getSubtarget().getRegisterInfo();
927 assert(TRI && "Expected target register info");
928 uint32_t *Mask = MF.allocateRegisterMask(TRI->getNumRegs());
930 if (expectAndConsume(MIToken::lparen))
933 if (Token.isNot(MIToken::NamedRegister))
934 return error("expected a named register");
936 if (parseRegister(Reg))
939 Mask[Reg / 32] |= 1U << (Reg % 32);
940 // TODO: Report an error if the same register is used more than once.
941 if (Token.isNot(MIToken::comma))
945 if (expectAndConsume(MIToken::rparen))
947 Dest = MachineOperand::CreateRegLiveOut(Mask);
951 bool MIParser::parseMachineOperand(MachineOperand &Dest) {
952 switch (Token.kind()) {
953 case MIToken::kw_implicit:
954 case MIToken::kw_implicit_define:
955 case MIToken::kw_dead:
956 case MIToken::kw_killed:
957 case MIToken::kw_undef:
958 case MIToken::kw_early_clobber:
959 case MIToken::kw_debug_use:
960 case MIToken::underscore:
961 case MIToken::NamedRegister:
962 case MIToken::VirtualRegister:
963 return parseRegisterOperand(Dest);
964 case MIToken::IntegerLiteral:
965 return parseImmediateOperand(Dest);
966 case MIToken::IntegerType:
967 return parseTypedImmediateOperand(Dest);
968 case MIToken::kw_half:
969 case MIToken::kw_float:
970 case MIToken::kw_double:
971 case MIToken::kw_x86_fp80:
972 case MIToken::kw_fp128:
973 case MIToken::kw_ppc_fp128:
974 return parseFPImmediateOperand(Dest);
975 case MIToken::MachineBasicBlock:
976 return parseMBBOperand(Dest);
977 case MIToken::StackObject:
978 return parseStackObjectOperand(Dest);
979 case MIToken::FixedStackObject:
980 return parseFixedStackObjectOperand(Dest);
981 case MIToken::GlobalValue:
982 case MIToken::NamedGlobalValue:
983 return parseGlobalAddressOperand(Dest);
984 case MIToken::ConstantPoolItem:
985 return parseConstantPoolIndexOperand(Dest);
986 case MIToken::JumpTableIndex:
987 return parseJumpTableIndexOperand(Dest);
988 case MIToken::ExternalSymbol:
989 return parseExternalSymbolOperand(Dest);
990 case MIToken::exclaim:
991 return parseMetadataOperand(Dest);
992 case MIToken::kw_cfi_offset:
993 case MIToken::kw_cfi_def_cfa_register:
994 case MIToken::kw_cfi_def_cfa_offset:
995 case MIToken::kw_cfi_def_cfa:
996 return parseCFIOperand(Dest);
997 case MIToken::kw_blockaddress:
998 return parseBlockAddressOperand(Dest);
999 case MIToken::kw_target_index:
1000 return parseTargetIndexOperand(Dest);
1001 case MIToken::kw_liveout:
1002 return parseLiveoutRegisterMaskOperand(Dest);
1003 case MIToken::Error:
1005 case MIToken::Identifier:
1006 if (const auto *RegMask = getRegMask(Token.stringValue())) {
1007 Dest = MachineOperand::CreateRegMask(RegMask);
1013 // TODO: parse the other machine operands.
1014 return error("expected a machine operand");
1019 bool MIParser::parseMachineOperandAndTargetFlags(MachineOperand &Dest) {
1021 bool HasTargetFlags = false;
1022 if (Token.is(MIToken::kw_target_flags)) {
1023 HasTargetFlags = true;
1025 if (expectAndConsume(MIToken::lparen))
1027 if (Token.isNot(MIToken::Identifier))
1028 return error("expected the name of the target flag");
1029 if (getDirectTargetFlag(Token.stringValue(), TF))
1030 return error("use of undefined target flag '" + Token.stringValue() +
1033 // TODO: Parse target's bit target flags.
1034 if (expectAndConsume(MIToken::rparen))
1037 auto Loc = Token.location();
1038 if (parseMachineOperand(Dest))
1040 if (!HasTargetFlags)
1043 return error(Loc, "register operands can't have target flags");
1044 Dest.setTargetFlags(TF);
1048 bool MIParser::parseOffset(int64_t &Offset) {
1049 if (Token.isNot(MIToken::plus) && Token.isNot(MIToken::minus))
1051 StringRef Sign = Token.range();
1052 bool IsNegative = Token.is(MIToken::minus);
1054 if (Token.isNot(MIToken::IntegerLiteral))
1055 return error("expected an integer literal after '" + Sign + "'");
1056 if (Token.integerValue().getMinSignedBits() > 64)
1057 return error("expected 64-bit integer (too large)");
1058 Offset = Token.integerValue().getExtValue();
1065 bool MIParser::parseOperandsOffset(MachineOperand &Op) {
1067 if (parseOffset(Offset))
1069 Op.setOffset(Offset);
1073 bool MIParser::parseIRValue(Value *&V) {
1074 switch (Token.kind()) {
1075 case MIToken::NamedIRValue: {
1076 V = MF.getFunction()->getValueSymbolTable().lookup(Token.stringValue());
1078 return error(Twine("use of undefined IR value '") + Token.range() + "'");
1081 // TODO: Parse unnamed IR value references.
1083 llvm_unreachable("The current token should be an IR block reference");
1088 bool MIParser::getUint64(uint64_t &Result) {
1089 assert(Token.hasIntegerValue());
1090 if (Token.integerValue().getActiveBits() > 64)
1091 return error("expected 64-bit integer (too large)");
1092 Result = Token.integerValue().getZExtValue();
1096 bool MIParser::parseMemoryOperandFlag(unsigned &Flags) {
1097 const unsigned OldFlags = Flags;
1098 switch (Token.kind()) {
1099 case MIToken::kw_volatile:
1100 Flags |= MachineMemOperand::MOVolatile;
1102 case MIToken::kw_non_temporal:
1103 Flags |= MachineMemOperand::MONonTemporal;
1105 case MIToken::kw_invariant:
1106 Flags |= MachineMemOperand::MOInvariant;
1108 // TODO: parse the target specific memory operand flags.
1110 llvm_unreachable("The current token should be a memory operand flag");
1112 if (OldFlags == Flags)
1113 // We know that the same flag is specified more than once when the flags
1114 // weren't modified.
1115 return error("duplicate '" + Token.stringValue() + "' memory operand flag");
1120 bool MIParser::parseMachineMemoryOperand(MachineMemOperand *&Dest) {
1121 if (expectAndConsume(MIToken::lparen))
1124 while (Token.isMemoryOperandFlag()) {
1125 if (parseMemoryOperandFlag(Flags))
1128 if (Token.isNot(MIToken::Identifier) ||
1129 (Token.stringValue() != "load" && Token.stringValue() != "store"))
1130 return error("expected 'load' or 'store' memory operation");
1131 if (Token.stringValue() == "load")
1132 Flags |= MachineMemOperand::MOLoad;
1134 Flags |= MachineMemOperand::MOStore;
1137 if (Token.isNot(MIToken::IntegerLiteral))
1138 return error("expected the size integer literal after memory operation");
1140 if (getUint64(Size))
1144 const char *Word = Flags & MachineMemOperand::MOLoad ? "from" : "into";
1145 if (Token.isNot(MIToken::Identifier) || Token.stringValue() != Word)
1146 return error(Twine("expected '") + Word + "'");
1149 // TODO: Parse pseudo source values.
1150 if (Token.isNot(MIToken::NamedIRValue))
1151 return error("expected an IR value reference");
1153 if (parseIRValue(V))
1155 if (!V->getType()->isPointerTy())
1156 return error("expected a pointer IR value");
1159 if (parseOffset(Offset))
1161 unsigned BaseAlignment = Size;
1162 if (Token.is(MIToken::comma)) {
1164 if (Token.isNot(MIToken::kw_align))
1165 return error("expected 'align'");
1167 if (Token.isNot(MIToken::IntegerLiteral))
1168 return error("expected an integer literal after 'align'");
1169 if (getUnsigned(BaseAlignment))
1173 // TODO: Parse the attached metadata nodes.
1174 if (expectAndConsume(MIToken::rparen))
1177 Dest = MF.getMachineMemOperand(MachinePointerInfo(V, Offset), Flags, Size,
1182 void MIParser::initNames2InstrOpCodes() {
1183 if (!Names2InstrOpCodes.empty())
1185 const auto *TII = MF.getSubtarget().getInstrInfo();
1186 assert(TII && "Expected target instruction info");
1187 for (unsigned I = 0, E = TII->getNumOpcodes(); I < E; ++I)
1188 Names2InstrOpCodes.insert(std::make_pair(StringRef(TII->getName(I)), I));
1191 bool MIParser::parseInstrName(StringRef InstrName, unsigned &OpCode) {
1192 initNames2InstrOpCodes();
1193 auto InstrInfo = Names2InstrOpCodes.find(InstrName);
1194 if (InstrInfo == Names2InstrOpCodes.end())
1196 OpCode = InstrInfo->getValue();
1200 void MIParser::initNames2Regs() {
1201 if (!Names2Regs.empty())
1203 // The '%noreg' register is the register 0.
1204 Names2Regs.insert(std::make_pair("noreg", 0));
1205 const auto *TRI = MF.getSubtarget().getRegisterInfo();
1206 assert(TRI && "Expected target register info");
1207 for (unsigned I = 0, E = TRI->getNumRegs(); I < E; ++I) {
1209 Names2Regs.insert(std::make_pair(StringRef(TRI->getName(I)).lower(), I))
1212 assert(WasInserted && "Expected registers to be unique case-insensitively");
1216 bool MIParser::getRegisterByName(StringRef RegName, unsigned &Reg) {
1218 auto RegInfo = Names2Regs.find(RegName);
1219 if (RegInfo == Names2Regs.end())
1221 Reg = RegInfo->getValue();
1225 void MIParser::initNames2RegMasks() {
1226 if (!Names2RegMasks.empty())
1228 const auto *TRI = MF.getSubtarget().getRegisterInfo();
1229 assert(TRI && "Expected target register info");
1230 ArrayRef<const uint32_t *> RegMasks = TRI->getRegMasks();
1231 ArrayRef<const char *> RegMaskNames = TRI->getRegMaskNames();
1232 assert(RegMasks.size() == RegMaskNames.size());
1233 for (size_t I = 0, E = RegMasks.size(); I < E; ++I)
1234 Names2RegMasks.insert(
1235 std::make_pair(StringRef(RegMaskNames[I]).lower(), RegMasks[I]));
1238 const uint32_t *MIParser::getRegMask(StringRef Identifier) {
1239 initNames2RegMasks();
1240 auto RegMaskInfo = Names2RegMasks.find(Identifier);
1241 if (RegMaskInfo == Names2RegMasks.end())
1243 return RegMaskInfo->getValue();
1246 void MIParser::initNames2SubRegIndices() {
1247 if (!Names2SubRegIndices.empty())
1249 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1250 for (unsigned I = 1, E = TRI->getNumSubRegIndices(); I < E; ++I)
1251 Names2SubRegIndices.insert(
1252 std::make_pair(StringRef(TRI->getSubRegIndexName(I)).lower(), I));
1255 unsigned MIParser::getSubRegIndex(StringRef Name) {
1256 initNames2SubRegIndices();
1257 auto SubRegInfo = Names2SubRegIndices.find(Name);
1258 if (SubRegInfo == Names2SubRegIndices.end())
1260 return SubRegInfo->getValue();
1263 static void initSlots2BasicBlocks(
1265 DenseMap<unsigned, const BasicBlock *> &Slots2BasicBlocks) {
1266 ModuleSlotTracker MST(F.getParent(), /*ShouldInitializeAllMetadata=*/false);
1267 MST.incorporateFunction(F);
1268 for (auto &BB : F) {
1271 int Slot = MST.getLocalSlot(&BB);
1274 Slots2BasicBlocks.insert(std::make_pair(unsigned(Slot), &BB));
1278 static const BasicBlock *getIRBlockFromSlot(
1280 const DenseMap<unsigned, const BasicBlock *> &Slots2BasicBlocks) {
1281 auto BlockInfo = Slots2BasicBlocks.find(Slot);
1282 if (BlockInfo == Slots2BasicBlocks.end())
1284 return BlockInfo->second;
1287 const BasicBlock *MIParser::getIRBlock(unsigned Slot) {
1288 if (Slots2BasicBlocks.empty())
1289 initSlots2BasicBlocks(*MF.getFunction(), Slots2BasicBlocks);
1290 return getIRBlockFromSlot(Slot, Slots2BasicBlocks);
1293 const BasicBlock *MIParser::getIRBlock(unsigned Slot, const Function &F) {
1294 if (&F == MF.getFunction())
1295 return getIRBlock(Slot);
1296 DenseMap<unsigned, const BasicBlock *> CustomSlots2BasicBlocks;
1297 initSlots2BasicBlocks(F, CustomSlots2BasicBlocks);
1298 return getIRBlockFromSlot(Slot, CustomSlots2BasicBlocks);
1301 void MIParser::initNames2TargetIndices() {
1302 if (!Names2TargetIndices.empty())
1304 const auto *TII = MF.getSubtarget().getInstrInfo();
1305 assert(TII && "Expected target instruction info");
1306 auto Indices = TII->getSerializableTargetIndices();
1307 for (const auto &I : Indices)
1308 Names2TargetIndices.insert(std::make_pair(StringRef(I.second), I.first));
1311 bool MIParser::getTargetIndex(StringRef Name, int &Index) {
1312 initNames2TargetIndices();
1313 auto IndexInfo = Names2TargetIndices.find(Name);
1314 if (IndexInfo == Names2TargetIndices.end())
1316 Index = IndexInfo->second;
1320 void MIParser::initNames2DirectTargetFlags() {
1321 if (!Names2DirectTargetFlags.empty())
1323 const auto *TII = MF.getSubtarget().getInstrInfo();
1324 assert(TII && "Expected target instruction info");
1325 auto Flags = TII->getSerializableDirectMachineOperandTargetFlags();
1326 for (const auto &I : Flags)
1327 Names2DirectTargetFlags.insert(
1328 std::make_pair(StringRef(I.second), I.first));
1331 bool MIParser::getDirectTargetFlag(StringRef Name, unsigned &Flag) {
1332 initNames2DirectTargetFlags();
1333 auto FlagInfo = Names2DirectTargetFlags.find(Name);
1334 if (FlagInfo == Names2DirectTargetFlags.end())
1336 Flag = FlagInfo->second;
1340 bool llvm::parseMachineInstr(MachineInstr *&MI, SourceMgr &SM,
1341 MachineFunction &MF, StringRef Src,
1342 const PerFunctionMIParsingState &PFS,
1343 const SlotMapping &IRSlots, SMDiagnostic &Error) {
1344 return MIParser(SM, MF, Error, Src, PFS, IRSlots).parse(MI);
1347 bool llvm::parseMBBReference(MachineBasicBlock *&MBB, SourceMgr &SM,
1348 MachineFunction &MF, StringRef Src,
1349 const PerFunctionMIParsingState &PFS,
1350 const SlotMapping &IRSlots, SMDiagnostic &Error) {
1351 return MIParser(SM, MF, Error, Src, PFS, IRSlots).parseStandaloneMBB(MBB);
1354 bool llvm::parseNamedRegisterReference(unsigned &Reg, SourceMgr &SM,
1355 MachineFunction &MF, StringRef Src,
1356 const PerFunctionMIParsingState &PFS,
1357 const SlotMapping &IRSlots,
1358 SMDiagnostic &Error) {
1359 return MIParser(SM, MF, Error, Src, PFS, IRSlots)
1360 .parseStandaloneNamedRegister(Reg);
1363 bool llvm::parseVirtualRegisterReference(unsigned &Reg, SourceMgr &SM,
1364 MachineFunction &MF, StringRef Src,
1365 const PerFunctionMIParsingState &PFS,
1366 const SlotMapping &IRSlots,
1367 SMDiagnostic &Error) {
1368 return MIParser(SM, MF, Error, Src, PFS, IRSlots)
1369 .parseStandaloneVirtualRegister(Reg);
1372 bool llvm::parseIRBlockReference(const BasicBlock *&BB, SourceMgr &SM,
1373 MachineFunction &MF, StringRef Src,
1374 const PerFunctionMIParsingState &PFS,
1375 const SlotMapping &IRSlots,
1376 SMDiagnostic &Error) {
1377 return MIParser(SM, MF, Error, Src, PFS, IRSlots)
1378 .parseStandaloneIRBlockReference(BB);