1 //===- MIParser.cpp - Machine instructions parser implementation ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the parsing of machine instructions.
12 //===----------------------------------------------------------------------===//
16 #include "llvm/ADT/StringMap.h"
17 #include "llvm/AsmParser/Parser.h"
18 #include "llvm/AsmParser/SlotMapping.h"
19 #include "llvm/CodeGen/MachineBasicBlock.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineInstr.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/CodeGen/MachineMemOperand.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/IR/Instructions.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/IR/ModuleSlotTracker.h"
30 #include "llvm/IR/ValueSymbolTable.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/Support/SourceMgr.h"
33 #include "llvm/Target/TargetSubtargetInfo.h"
34 #include "llvm/Target/TargetInstrInfo.h"
40 /// A wrapper struct around the 'MachineOperand' struct that includes a source
42 struct MachineOperandWithLocation {
43 MachineOperand Operand;
44 StringRef::iterator Begin;
45 StringRef::iterator End;
47 MachineOperandWithLocation(const MachineOperand &Operand,
48 StringRef::iterator Begin, StringRef::iterator End)
49 : Operand(Operand), Begin(Begin), End(End) {}
56 StringRef Source, CurrentSource;
58 const PerFunctionMIParsingState &PFS;
59 /// Maps from indices to unnamed global values and metadata nodes.
60 const SlotMapping &IRSlots;
61 /// Maps from instruction names to op codes.
62 StringMap<unsigned> Names2InstrOpCodes;
63 /// Maps from register names to registers.
64 StringMap<unsigned> Names2Regs;
65 /// Maps from register mask names to register masks.
66 StringMap<const uint32_t *> Names2RegMasks;
67 /// Maps from subregister names to subregister indices.
68 StringMap<unsigned> Names2SubRegIndices;
69 /// Maps from slot numbers to function's unnamed basic blocks.
70 DenseMap<unsigned, const BasicBlock *> Slots2BasicBlocks;
71 /// Maps from target index names to target indices.
72 StringMap<int> Names2TargetIndices;
73 /// Maps from direct target flag names to the direct target flag values.
74 StringMap<unsigned> Names2DirectTargetFlags;
77 MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
78 StringRef Source, const PerFunctionMIParsingState &PFS,
79 const SlotMapping &IRSlots);
83 /// Report an error at the current location with the given message.
85 /// This function always return true.
86 bool error(const Twine &Msg);
88 /// Report an error at the given location with the given message.
90 /// This function always return true.
91 bool error(StringRef::iterator Loc, const Twine &Msg);
94 parseBasicBlockDefinitions(DenseMap<unsigned, MachineBasicBlock *> &MBBSlots);
95 bool parseBasicBlocks();
96 bool parse(MachineInstr *&MI);
97 bool parseStandaloneMBB(MachineBasicBlock *&MBB);
98 bool parseStandaloneNamedRegister(unsigned &Reg);
99 bool parseStandaloneVirtualRegister(unsigned &Reg);
102 parseBasicBlockDefinition(DenseMap<unsigned, MachineBasicBlock *> &MBBSlots);
103 bool parseBasicBlock(MachineBasicBlock &MBB);
104 bool parseBasicBlockLiveins(MachineBasicBlock &MBB);
105 bool parseBasicBlockSuccessors(MachineBasicBlock &MBB);
107 bool parseRegister(unsigned &Reg);
108 bool parseRegisterFlag(unsigned &Flags);
109 bool parseSubRegisterIndex(unsigned &SubReg);
110 bool parseRegisterOperand(MachineOperand &Dest, bool IsDef = false);
111 bool parseImmediateOperand(MachineOperand &Dest);
112 bool parseIRConstant(StringRef::iterator Loc, const Constant *&C);
113 bool parseTypedImmediateOperand(MachineOperand &Dest);
114 bool parseFPImmediateOperand(MachineOperand &Dest);
115 bool parseMBBReference(MachineBasicBlock *&MBB);
116 bool parseMBBOperand(MachineOperand &Dest);
117 bool parseStackObjectOperand(MachineOperand &Dest);
118 bool parseFixedStackFrameIndex(int &FI);
119 bool parseFixedStackObjectOperand(MachineOperand &Dest);
120 bool parseGlobalValue(GlobalValue *&GV);
121 bool parseGlobalAddressOperand(MachineOperand &Dest);
122 bool parseConstantPoolIndexOperand(MachineOperand &Dest);
123 bool parseJumpTableIndexOperand(MachineOperand &Dest);
124 bool parseExternalSymbolOperand(MachineOperand &Dest);
125 bool parseMDNode(MDNode *&Node);
126 bool parseMetadataOperand(MachineOperand &Dest);
127 bool parseCFIOffset(int &Offset);
128 bool parseCFIRegister(unsigned &Reg);
129 bool parseCFIOperand(MachineOperand &Dest);
130 bool parseIRBlock(BasicBlock *&BB, const Function &F);
131 bool parseBlockAddressOperand(MachineOperand &Dest);
132 bool parseTargetIndexOperand(MachineOperand &Dest);
133 bool parseLiveoutRegisterMaskOperand(MachineOperand &Dest);
134 bool parseMachineOperand(MachineOperand &Dest);
135 bool parseMachineOperandAndTargetFlags(MachineOperand &Dest);
136 bool parseOffset(int64_t &Offset);
137 bool parseAlignment(unsigned &Alignment);
138 bool parseOperandsOffset(MachineOperand &Op);
139 bool parseIRValue(Value *&V);
140 bool parseMemoryOperandFlag(unsigned &Flags);
141 bool parseMemoryPseudoSourceValue(const PseudoSourceValue *&PSV);
142 bool parseMachinePointerInfo(MachinePointerInfo &Dest);
143 bool parseMachineMemoryOperand(MachineMemOperand *&Dest);
146 /// Convert the integer literal in the current token into an unsigned integer.
148 /// Return true if an error occurred.
149 bool getUnsigned(unsigned &Result);
151 /// Convert the integer literal in the current token into an uint64.
153 /// Return true if an error occurred.
154 bool getUint64(uint64_t &Result);
156 /// If the current token is of the given kind, consume it and return false.
157 /// Otherwise report an error and return true.
158 bool expectAndConsume(MIToken::TokenKind TokenKind);
160 /// If the current token is of the given kind, consume it and return true.
161 /// Otherwise return false.
162 bool consumeIfPresent(MIToken::TokenKind TokenKind);
164 void initNames2InstrOpCodes();
166 /// Try to convert an instruction name to an opcode. Return true if the
167 /// instruction name is invalid.
168 bool parseInstrName(StringRef InstrName, unsigned &OpCode);
170 bool parseInstruction(unsigned &OpCode, unsigned &Flags);
172 bool verifyImplicitOperands(ArrayRef<MachineOperandWithLocation> Operands,
173 const MCInstrDesc &MCID);
175 void initNames2Regs();
177 /// Try to convert a register name to a register number. Return true if the
178 /// register name is invalid.
179 bool getRegisterByName(StringRef RegName, unsigned &Reg);
181 void initNames2RegMasks();
183 /// Check if the given identifier is a name of a register mask.
185 /// Return null if the identifier isn't a register mask.
186 const uint32_t *getRegMask(StringRef Identifier);
188 void initNames2SubRegIndices();
190 /// Check if the given identifier is a name of a subregister index.
192 /// Return 0 if the name isn't a subregister index class.
193 unsigned getSubRegIndex(StringRef Name);
195 const BasicBlock *getIRBlock(unsigned Slot);
196 const BasicBlock *getIRBlock(unsigned Slot, const Function &F);
198 void initNames2TargetIndices();
200 /// Try to convert a name of target index to the corresponding target index.
202 /// Return true if the name isn't a name of a target index.
203 bool getTargetIndex(StringRef Name, int &Index);
205 void initNames2DirectTargetFlags();
207 /// Try to convert a name of a direct target flag to the corresponding
210 /// Return true if the name isn't a name of a direct flag.
211 bool getDirectTargetFlag(StringRef Name, unsigned &Flag);
214 } // end anonymous namespace
216 MIParser::MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
217 StringRef Source, const PerFunctionMIParsingState &PFS,
218 const SlotMapping &IRSlots)
219 : SM(SM), MF(MF), Error(Error), Source(Source), CurrentSource(Source),
220 PFS(PFS), IRSlots(IRSlots) {}
222 void MIParser::lex() {
223 CurrentSource = lexMIToken(
224 CurrentSource, Token,
225 [this](StringRef::iterator Loc, const Twine &Msg) { error(Loc, Msg); });
228 bool MIParser::error(const Twine &Msg) { return error(Token.location(), Msg); }
230 bool MIParser::error(StringRef::iterator Loc, const Twine &Msg) {
231 assert(Loc >= Source.data() && Loc <= (Source.data() + Source.size()));
232 const MemoryBuffer &Buffer = *SM.getMemoryBuffer(SM.getMainFileID());
233 if (Loc >= Buffer.getBufferStart() && Loc <= Buffer.getBufferEnd()) {
234 // Create an ordinary diagnostic when the source manager's buffer is the
236 Error = SM.GetMessage(SMLoc::getFromPointer(Loc), SourceMgr::DK_Error, Msg);
239 // Create a diagnostic for a YAML string literal.
240 Error = SMDiagnostic(SM, SMLoc(), Buffer.getBufferIdentifier(), 1,
241 Loc - Source.data(), SourceMgr::DK_Error, Msg.str(),
246 static const char *toString(MIToken::TokenKind TokenKind) {
254 case MIToken::lparen:
256 case MIToken::rparen:
259 return "<unknown token>";
263 bool MIParser::expectAndConsume(MIToken::TokenKind TokenKind) {
264 if (Token.isNot(TokenKind))
265 return error(Twine("expected ") + toString(TokenKind));
270 bool MIParser::consumeIfPresent(MIToken::TokenKind TokenKind) {
271 if (Token.isNot(TokenKind))
277 bool MIParser::parseBasicBlockDefinition(
278 DenseMap<unsigned, MachineBasicBlock *> &MBBSlots) {
279 assert(Token.is(MIToken::MachineBasicBlockLabel));
283 auto Loc = Token.location();
284 auto Name = Token.stringValue();
286 bool HasAddressTaken = false;
287 bool IsLandingPad = false;
288 unsigned Alignment = 0;
289 BasicBlock *BB = nullptr;
290 if (consumeIfPresent(MIToken::lparen)) {
292 // TODO: Report an error when multiple same attributes are specified.
293 switch (Token.kind()) {
294 case MIToken::kw_address_taken:
295 HasAddressTaken = true;
298 case MIToken::kw_landing_pad:
302 case MIToken::kw_align:
303 if (parseAlignment(Alignment))
306 case MIToken::IRBlock:
307 // TODO: Report an error when both name and ir block are specified.
308 if (parseIRBlock(BB, *MF.getFunction()))
315 } while (consumeIfPresent(MIToken::comma));
316 if (expectAndConsume(MIToken::rparen))
319 if (expectAndConsume(MIToken::colon))
323 BB = dyn_cast_or_null<BasicBlock>(
324 MF.getFunction()->getValueSymbolTable().lookup(Name));
326 return error(Loc, Twine("basic block '") + Name +
327 "' is not defined in the function '" +
330 auto *MBB = MF.CreateMachineBasicBlock(BB);
331 MF.insert(MF.end(), MBB);
332 bool WasInserted = MBBSlots.insert(std::make_pair(ID, MBB)).second;
334 return error(Loc, Twine("redefinition of machine basic block with id #") +
337 MBB->setAlignment(Alignment);
339 MBB->setHasAddressTaken();
340 MBB->setIsLandingPad(IsLandingPad);
344 bool MIParser::parseBasicBlockDefinitions(
345 DenseMap<unsigned, MachineBasicBlock *> &MBBSlots) {
347 // Skip until the first machine basic block.
348 while (Token.is(MIToken::Newline))
350 if (Token.isErrorOrEOF())
351 return Token.isError();
352 if (Token.isNot(MIToken::MachineBasicBlockLabel))
353 return error("expected a basic block definition before instructions");
355 if (parseBasicBlockDefinition(MBBSlots))
357 bool IsAfterNewline = false;
358 // Skip until the next machine basic block.
360 if ((Token.is(MIToken::MachineBasicBlockLabel) && IsAfterNewline) ||
361 Token.isErrorOrEOF())
363 else if (Token.is(MIToken::MachineBasicBlockLabel))
364 return error("basic block definition should be located at the start of "
366 if (Token.is(MIToken::Newline))
367 IsAfterNewline = true;
369 IsAfterNewline = false;
372 } while (!Token.isErrorOrEOF());
373 return Token.isError();
376 bool MIParser::parseBasicBlockLiveins(MachineBasicBlock &MBB) {
377 assert(Token.is(MIToken::kw_liveins));
379 if (expectAndConsume(MIToken::colon))
381 if (Token.isNewlineOrEOF()) // Allow an empty list of liveins.
384 if (Token.isNot(MIToken::NamedRegister))
385 return error("expected a named register");
387 if (parseRegister(Reg))
391 } while (consumeIfPresent(MIToken::comma));
395 bool MIParser::parseBasicBlockSuccessors(MachineBasicBlock &MBB) {
396 assert(Token.is(MIToken::kw_successors));
398 if (expectAndConsume(MIToken::colon))
400 if (Token.isNewlineOrEOF()) // Allow an empty list of successors.
403 if (Token.isNot(MIToken::MachineBasicBlock))
404 return error("expected a machine basic block reference");
405 MachineBasicBlock *SuccMBB = nullptr;
406 if (parseMBBReference(SuccMBB))
410 if (consumeIfPresent(MIToken::lparen)) {
411 if (Token.isNot(MIToken::IntegerLiteral))
412 return error("expected an integer literal after '('");
413 if (getUnsigned(Weight))
416 if (expectAndConsume(MIToken::rparen))
419 MBB.addSuccessor(SuccMBB, Weight);
420 } while (consumeIfPresent(MIToken::comma));
424 bool MIParser::parseBasicBlock(MachineBasicBlock &MBB) {
425 // Skip the definition.
426 assert(Token.is(MIToken::MachineBasicBlockLabel));
428 if (consumeIfPresent(MIToken::lparen)) {
429 while (Token.isNot(MIToken::rparen) && !Token.isErrorOrEOF())
431 consumeIfPresent(MIToken::rparen);
433 consumeIfPresent(MIToken::colon);
435 // Parse the liveins and successors.
436 // N.B: Multiple lists of successors and liveins are allowed and they're
443 // liveins: %edi, %esi
445 if (Token.is(MIToken::kw_successors)) {
446 if (parseBasicBlockSuccessors(MBB))
448 } else if (Token.is(MIToken::kw_liveins)) {
449 if (parseBasicBlockLiveins(MBB))
451 } else if (consumeIfPresent(MIToken::Newline)) {
455 if (!Token.isNewlineOrEOF())
456 return error("expected line break at the end of a list");
460 // Parse the instructions.
462 if (Token.is(MIToken::MachineBasicBlockLabel) || Token.is(MIToken::Eof))
464 else if (consumeIfPresent(MIToken::Newline))
466 MachineInstr *MI = nullptr;
469 MBB.insert(MBB.end(), MI);
470 assert(Token.isNewlineOrEOF() && "MI is not fully parsed");
476 bool MIParser::parseBasicBlocks() {
478 // Skip until the first machine basic block.
479 while (Token.is(MIToken::Newline))
481 if (Token.isErrorOrEOF())
482 return Token.isError();
483 // The first parsing pass should have verified that this token is a MBB label
484 // in the 'parseBasicBlockDefinitions' method.
485 assert(Token.is(MIToken::MachineBasicBlockLabel));
487 MachineBasicBlock *MBB = nullptr;
488 if (parseMBBReference(MBB))
490 if (parseBasicBlock(*MBB))
492 // The method 'parseBasicBlock' should parse the whole block until the next
493 // block or the end of file.
494 assert(Token.is(MIToken::MachineBasicBlockLabel) || Token.is(MIToken::Eof));
495 } while (Token.isNot(MIToken::Eof));
499 bool MIParser::parse(MachineInstr *&MI) {
500 // Parse any register operands before '='
501 MachineOperand MO = MachineOperand::CreateImm(0);
502 SmallVector<MachineOperandWithLocation, 8> Operands;
503 while (Token.isRegister() || Token.isRegisterFlag()) {
504 auto Loc = Token.location();
505 if (parseRegisterOperand(MO, /*IsDef=*/true))
507 Operands.push_back(MachineOperandWithLocation(MO, Loc, Token.location()));
508 if (Token.isNot(MIToken::comma))
512 if (!Operands.empty() && expectAndConsume(MIToken::equal))
515 unsigned OpCode, Flags = 0;
516 if (Token.isError() || parseInstruction(OpCode, Flags))
519 // TODO: Parse the bundle instruction flags.
521 // Parse the remaining machine operands.
522 while (!Token.isNewlineOrEOF() && Token.isNot(MIToken::kw_debug_location) &&
523 Token.isNot(MIToken::coloncolon)) {
524 auto Loc = Token.location();
525 if (parseMachineOperandAndTargetFlags(MO))
527 Operands.push_back(MachineOperandWithLocation(MO, Loc, Token.location()));
528 if (Token.isNewlineOrEOF() || Token.is(MIToken::coloncolon))
530 if (Token.isNot(MIToken::comma))
531 return error("expected ',' before the next machine operand");
535 DebugLoc DebugLocation;
536 if (Token.is(MIToken::kw_debug_location)) {
538 if (Token.isNot(MIToken::exclaim))
539 return error("expected a metadata node after 'debug-location'");
540 MDNode *Node = nullptr;
541 if (parseMDNode(Node))
543 DebugLocation = DebugLoc(Node);
546 // Parse the machine memory operands.
547 SmallVector<MachineMemOperand *, 2> MemOperands;
548 if (Token.is(MIToken::coloncolon)) {
550 while (!Token.isNewlineOrEOF()) {
551 MachineMemOperand *MemOp = nullptr;
552 if (parseMachineMemoryOperand(MemOp))
554 MemOperands.push_back(MemOp);
555 if (Token.isNewlineOrEOF())
557 if (Token.isNot(MIToken::comma))
558 return error("expected ',' before the next machine memory operand");
563 const auto &MCID = MF.getSubtarget().getInstrInfo()->get(OpCode);
564 if (!MCID.isVariadic()) {
565 // FIXME: Move the implicit operand verification to the machine verifier.
566 if (verifyImplicitOperands(Operands, MCID))
570 // TODO: Check for extraneous machine operands.
571 MI = MF.CreateMachineInstr(MCID, DebugLocation, /*NoImplicit=*/true);
573 for (const auto &Operand : Operands)
574 MI->addOperand(MF, Operand.Operand);
575 if (MemOperands.empty())
577 MachineInstr::mmo_iterator MemRefs =
578 MF.allocateMemRefsArray(MemOperands.size());
579 std::copy(MemOperands.begin(), MemOperands.end(), MemRefs);
580 MI->setMemRefs(MemRefs, MemRefs + MemOperands.size());
584 bool MIParser::parseStandaloneMBB(MachineBasicBlock *&MBB) {
586 if (Token.isNot(MIToken::MachineBasicBlock))
587 return error("expected a machine basic block reference");
588 if (parseMBBReference(MBB))
591 if (Token.isNot(MIToken::Eof))
593 "expected end of string after the machine basic block reference");
597 bool MIParser::parseStandaloneNamedRegister(unsigned &Reg) {
599 if (Token.isNot(MIToken::NamedRegister))
600 return error("expected a named register");
601 if (parseRegister(Reg))
604 if (Token.isNot(MIToken::Eof))
605 return error("expected end of string after the register reference");
609 bool MIParser::parseStandaloneVirtualRegister(unsigned &Reg) {
611 if (Token.isNot(MIToken::VirtualRegister))
612 return error("expected a virtual register");
613 if (parseRegister(Reg))
616 if (Token.isNot(MIToken::Eof))
617 return error("expected end of string after the register reference");
621 static const char *printImplicitRegisterFlag(const MachineOperand &MO) {
622 assert(MO.isImplicit());
623 return MO.isDef() ? "implicit-def" : "implicit";
626 static std::string getRegisterName(const TargetRegisterInfo *TRI,
628 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "expected phys reg");
629 return StringRef(TRI->getName(Reg)).lower();
632 bool MIParser::verifyImplicitOperands(
633 ArrayRef<MachineOperandWithLocation> Operands, const MCInstrDesc &MCID) {
635 // We can't verify call instructions as they can contain arbitrary implicit
636 // register and register mask operands.
639 // Gather all the expected implicit operands.
640 SmallVector<MachineOperand, 4> ImplicitOperands;
641 if (MCID.ImplicitDefs)
642 for (const uint16_t *ImpDefs = MCID.getImplicitDefs(); *ImpDefs; ++ImpDefs)
643 ImplicitOperands.push_back(
644 MachineOperand::CreateReg(*ImpDefs, true, true));
645 if (MCID.ImplicitUses)
646 for (const uint16_t *ImpUses = MCID.getImplicitUses(); *ImpUses; ++ImpUses)
647 ImplicitOperands.push_back(
648 MachineOperand::CreateReg(*ImpUses, false, true));
650 const auto *TRI = MF.getSubtarget().getRegisterInfo();
651 assert(TRI && "Expected target register info");
652 size_t I = ImplicitOperands.size(), J = Operands.size();
657 const auto &ImplicitOperand = ImplicitOperands[I];
658 const auto &Operand = Operands[J].Operand;
659 if (ImplicitOperand.isIdenticalTo(Operand))
661 if (Operand.isReg() && Operand.isImplicit()) {
662 return error(Operands[J].Begin,
663 Twine("expected an implicit register operand '") +
664 printImplicitRegisterFlag(ImplicitOperand) + " %" +
665 getRegisterName(TRI, ImplicitOperand.getReg()) + "'");
668 // TODO: Fix source location when Operands[J].end is right before '=', i.e:
669 // insead of reporting an error at this location:
672 // report the error at the following location:
675 return error(J < Operands.size() ? Operands[J].End : Token.location(),
676 Twine("missing implicit register operand '") +
677 printImplicitRegisterFlag(ImplicitOperands[I]) + " %" +
678 getRegisterName(TRI, ImplicitOperands[I].getReg()) + "'");
683 bool MIParser::parseInstruction(unsigned &OpCode, unsigned &Flags) {
684 if (Token.is(MIToken::kw_frame_setup)) {
685 Flags |= MachineInstr::FrameSetup;
688 if (Token.isNot(MIToken::Identifier))
689 return error("expected a machine instruction");
690 StringRef InstrName = Token.stringValue();
691 if (parseInstrName(InstrName, OpCode))
692 return error(Twine("unknown machine instruction name '") + InstrName + "'");
697 bool MIParser::parseRegister(unsigned &Reg) {
698 switch (Token.kind()) {
699 case MIToken::underscore:
702 case MIToken::NamedRegister: {
703 StringRef Name = Token.stringValue();
704 if (getRegisterByName(Name, Reg))
705 return error(Twine("unknown register name '") + Name + "'");
708 case MIToken::VirtualRegister: {
712 const auto RegInfo = PFS.VirtualRegisterSlots.find(ID);
713 if (RegInfo == PFS.VirtualRegisterSlots.end())
714 return error(Twine("use of undefined virtual register '%") + Twine(ID) +
716 Reg = RegInfo->second;
719 // TODO: Parse other register kinds.
721 llvm_unreachable("The current token should be a register");
726 bool MIParser::parseRegisterFlag(unsigned &Flags) {
727 const unsigned OldFlags = Flags;
728 switch (Token.kind()) {
729 case MIToken::kw_implicit:
730 Flags |= RegState::Implicit;
732 case MIToken::kw_implicit_define:
733 Flags |= RegState::ImplicitDefine;
735 case MIToken::kw_dead:
736 Flags |= RegState::Dead;
738 case MIToken::kw_killed:
739 Flags |= RegState::Kill;
741 case MIToken::kw_undef:
742 Flags |= RegState::Undef;
744 case MIToken::kw_early_clobber:
745 Flags |= RegState::EarlyClobber;
747 case MIToken::kw_debug_use:
748 Flags |= RegState::Debug;
750 // TODO: parse the other register flags.
752 llvm_unreachable("The current token should be a register flag");
754 if (OldFlags == Flags)
755 // We know that the same flag is specified more than once when the flags
757 return error("duplicate '" + Token.stringValue() + "' register flag");
762 bool MIParser::parseSubRegisterIndex(unsigned &SubReg) {
763 assert(Token.is(MIToken::colon));
765 if (Token.isNot(MIToken::Identifier))
766 return error("expected a subregister index after ':'");
767 auto Name = Token.stringValue();
768 SubReg = getSubRegIndex(Name);
770 return error(Twine("use of unknown subregister index '") + Name + "'");
775 bool MIParser::parseRegisterOperand(MachineOperand &Dest, bool IsDef) {
777 unsigned Flags = IsDef ? RegState::Define : 0;
778 while (Token.isRegisterFlag()) {
779 if (parseRegisterFlag(Flags))
782 if (!Token.isRegister())
783 return error("expected a register after register flags");
784 if (parseRegister(Reg))
788 if (Token.is(MIToken::colon)) {
789 if (parseSubRegisterIndex(SubReg))
792 Dest = MachineOperand::CreateReg(
793 Reg, Flags & RegState::Define, Flags & RegState::Implicit,
794 Flags & RegState::Kill, Flags & RegState::Dead, Flags & RegState::Undef,
795 Flags & RegState::EarlyClobber, SubReg, Flags & RegState::Debug);
799 bool MIParser::parseImmediateOperand(MachineOperand &Dest) {
800 assert(Token.is(MIToken::IntegerLiteral));
801 const APSInt &Int = Token.integerValue();
802 if (Int.getMinSignedBits() > 64)
803 return error("integer literal is too large to be an immediate operand");
804 Dest = MachineOperand::CreateImm(Int.getExtValue());
809 bool MIParser::parseIRConstant(StringRef::iterator Loc, const Constant *&C) {
810 auto Source = StringRef(Loc, Token.range().end() - Loc).str();
813 C = parseConstantValue(Source.c_str(), Err, *MF.getFunction()->getParent());
815 return error(Loc + Err.getColumnNo(), Err.getMessage());
819 bool MIParser::parseTypedImmediateOperand(MachineOperand &Dest) {
820 assert(Token.is(MIToken::IntegerType));
821 auto Loc = Token.location();
823 if (Token.isNot(MIToken::IntegerLiteral))
824 return error("expected an integer literal");
825 const Constant *C = nullptr;
826 if (parseIRConstant(Loc, C))
828 Dest = MachineOperand::CreateCImm(cast<ConstantInt>(C));
832 bool MIParser::parseFPImmediateOperand(MachineOperand &Dest) {
833 auto Loc = Token.location();
835 if (Token.isNot(MIToken::FloatingPointLiteral))
836 return error("expected a floating point literal");
837 const Constant *C = nullptr;
838 if (parseIRConstant(Loc, C))
840 Dest = MachineOperand::CreateFPImm(cast<ConstantFP>(C));
844 bool MIParser::getUnsigned(unsigned &Result) {
845 assert(Token.hasIntegerValue() && "Expected a token with an integer value");
846 const uint64_t Limit = uint64_t(std::numeric_limits<unsigned>::max()) + 1;
847 uint64_t Val64 = Token.integerValue().getLimitedValue(Limit);
849 return error("expected 32-bit integer (too large)");
854 bool MIParser::parseMBBReference(MachineBasicBlock *&MBB) {
855 assert(Token.is(MIToken::MachineBasicBlock) ||
856 Token.is(MIToken::MachineBasicBlockLabel));
858 if (getUnsigned(Number))
860 auto MBBInfo = PFS.MBBSlots.find(Number);
861 if (MBBInfo == PFS.MBBSlots.end())
862 return error(Twine("use of undefined machine basic block #") +
864 MBB = MBBInfo->second;
865 if (!Token.stringValue().empty() && Token.stringValue() != MBB->getName())
866 return error(Twine("the name of machine basic block #") + Twine(Number) +
867 " isn't '" + Token.stringValue() + "'");
871 bool MIParser::parseMBBOperand(MachineOperand &Dest) {
872 MachineBasicBlock *MBB;
873 if (parseMBBReference(MBB))
875 Dest = MachineOperand::CreateMBB(MBB);
880 bool MIParser::parseStackObjectOperand(MachineOperand &Dest) {
881 assert(Token.is(MIToken::StackObject));
885 auto ObjectInfo = PFS.StackObjectSlots.find(ID);
886 if (ObjectInfo == PFS.StackObjectSlots.end())
887 return error(Twine("use of undefined stack object '%stack.") + Twine(ID) +
890 if (const auto *Alloca =
891 MF.getFrameInfo()->getObjectAllocation(ObjectInfo->second))
892 Name = Alloca->getName();
893 if (!Token.stringValue().empty() && Token.stringValue() != Name)
894 return error(Twine("the name of the stack object '%stack.") + Twine(ID) +
895 "' isn't '" + Token.stringValue() + "'");
897 Dest = MachineOperand::CreateFI(ObjectInfo->second);
901 bool MIParser::parseFixedStackFrameIndex(int &FI) {
902 assert(Token.is(MIToken::FixedStackObject));
906 auto ObjectInfo = PFS.FixedStackObjectSlots.find(ID);
907 if (ObjectInfo == PFS.FixedStackObjectSlots.end())
908 return error(Twine("use of undefined fixed stack object '%fixed-stack.") +
911 FI = ObjectInfo->second;
915 bool MIParser::parseFixedStackObjectOperand(MachineOperand &Dest) {
917 if (parseFixedStackFrameIndex(FI))
919 Dest = MachineOperand::CreateFI(FI);
923 bool MIParser::parseGlobalValue(GlobalValue *&GV) {
924 switch (Token.kind()) {
925 case MIToken::NamedGlobalValue: {
926 const Module *M = MF.getFunction()->getParent();
927 GV = M->getNamedValue(Token.stringValue());
929 return error(Twine("use of undefined global value '") + Token.range() +
933 case MIToken::GlobalValue: {
935 if (getUnsigned(GVIdx))
937 if (GVIdx >= IRSlots.GlobalValues.size())
938 return error(Twine("use of undefined global value '@") + Twine(GVIdx) +
940 GV = IRSlots.GlobalValues[GVIdx];
944 llvm_unreachable("The current token should be a global value");
949 bool MIParser::parseGlobalAddressOperand(MachineOperand &Dest) {
950 GlobalValue *GV = nullptr;
951 if (parseGlobalValue(GV))
954 Dest = MachineOperand::CreateGA(GV, /*Offset=*/0);
955 if (parseOperandsOffset(Dest))
960 bool MIParser::parseConstantPoolIndexOperand(MachineOperand &Dest) {
961 assert(Token.is(MIToken::ConstantPoolItem));
965 auto ConstantInfo = PFS.ConstantPoolSlots.find(ID);
966 if (ConstantInfo == PFS.ConstantPoolSlots.end())
967 return error("use of undefined constant '%const." + Twine(ID) + "'");
969 Dest = MachineOperand::CreateCPI(ID, /*Offset=*/0);
970 if (parseOperandsOffset(Dest))
975 bool MIParser::parseJumpTableIndexOperand(MachineOperand &Dest) {
976 assert(Token.is(MIToken::JumpTableIndex));
980 auto JumpTableEntryInfo = PFS.JumpTableSlots.find(ID);
981 if (JumpTableEntryInfo == PFS.JumpTableSlots.end())
982 return error("use of undefined jump table '%jump-table." + Twine(ID) + "'");
984 Dest = MachineOperand::CreateJTI(JumpTableEntryInfo->second);
988 bool MIParser::parseExternalSymbolOperand(MachineOperand &Dest) {
989 assert(Token.is(MIToken::ExternalSymbol));
990 const char *Symbol = MF.createExternalSymbolName(Token.stringValue());
992 Dest = MachineOperand::CreateES(Symbol);
993 if (parseOperandsOffset(Dest))
998 bool MIParser::parseMDNode(MDNode *&Node) {
999 assert(Token.is(MIToken::exclaim));
1000 auto Loc = Token.location();
1002 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
1003 return error("expected metadata id after '!'");
1005 if (getUnsigned(ID))
1007 auto NodeInfo = IRSlots.MetadataNodes.find(ID);
1008 if (NodeInfo == IRSlots.MetadataNodes.end())
1009 return error(Loc, "use of undefined metadata '!" + Twine(ID) + "'");
1011 Node = NodeInfo->second.get();
1015 bool MIParser::parseMetadataOperand(MachineOperand &Dest) {
1016 MDNode *Node = nullptr;
1017 if (parseMDNode(Node))
1019 Dest = MachineOperand::CreateMetadata(Node);
1023 bool MIParser::parseCFIOffset(int &Offset) {
1024 if (Token.isNot(MIToken::IntegerLiteral))
1025 return error("expected a cfi offset");
1026 if (Token.integerValue().getMinSignedBits() > 32)
1027 return error("expected a 32 bit integer (the cfi offset is too large)");
1028 Offset = (int)Token.integerValue().getExtValue();
1033 bool MIParser::parseCFIRegister(unsigned &Reg) {
1034 if (Token.isNot(MIToken::NamedRegister))
1035 return error("expected a cfi register");
1037 if (parseRegister(LLVMReg))
1039 const auto *TRI = MF.getSubtarget().getRegisterInfo();
1040 assert(TRI && "Expected target register info");
1041 int DwarfReg = TRI->getDwarfRegNum(LLVMReg, true);
1043 return error("invalid DWARF register");
1044 Reg = (unsigned)DwarfReg;
1049 bool MIParser::parseCFIOperand(MachineOperand &Dest) {
1050 auto Kind = Token.kind();
1052 auto &MMI = MF.getMMI();
1057 case MIToken::kw_cfi_offset:
1058 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
1059 parseCFIOffset(Offset))
1062 MMI.addFrameInst(MCCFIInstruction::createOffset(nullptr, Reg, Offset));
1064 case MIToken::kw_cfi_def_cfa_register:
1065 if (parseCFIRegister(Reg))
1068 MMI.addFrameInst(MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
1070 case MIToken::kw_cfi_def_cfa_offset:
1071 if (parseCFIOffset(Offset))
1073 // NB: MCCFIInstruction::createDefCfaOffset negates the offset.
1074 CFIIndex = MMI.addFrameInst(
1075 MCCFIInstruction::createDefCfaOffset(nullptr, -Offset));
1077 case MIToken::kw_cfi_def_cfa:
1078 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
1079 parseCFIOffset(Offset))
1081 // NB: MCCFIInstruction::createDefCfa negates the offset.
1083 MMI.addFrameInst(MCCFIInstruction::createDefCfa(nullptr, Reg, -Offset));
1086 // TODO: Parse the other CFI operands.
1087 llvm_unreachable("The current token should be a cfi operand");
1089 Dest = MachineOperand::CreateCFIIndex(CFIIndex);
1093 bool MIParser::parseIRBlock(BasicBlock *&BB, const Function &F) {
1094 switch (Token.kind()) {
1095 case MIToken::NamedIRBlock: {
1096 BB = dyn_cast_or_null<BasicBlock>(
1097 F.getValueSymbolTable().lookup(Token.stringValue()));
1099 return error(Twine("use of undefined IR block '") + Token.range() + "'");
1102 case MIToken::IRBlock: {
1103 unsigned SlotNumber = 0;
1104 if (getUnsigned(SlotNumber))
1106 BB = const_cast<BasicBlock *>(getIRBlock(SlotNumber, F));
1108 return error(Twine("use of undefined IR block '%ir-block.") +
1109 Twine(SlotNumber) + "'");
1113 llvm_unreachable("The current token should be an IR block reference");
1118 bool MIParser::parseBlockAddressOperand(MachineOperand &Dest) {
1119 assert(Token.is(MIToken::kw_blockaddress));
1121 if (expectAndConsume(MIToken::lparen))
1123 if (Token.isNot(MIToken::GlobalValue) &&
1124 Token.isNot(MIToken::NamedGlobalValue))
1125 return error("expected a global value");
1126 GlobalValue *GV = nullptr;
1127 if (parseGlobalValue(GV))
1129 auto *F = dyn_cast<Function>(GV);
1131 return error("expected an IR function reference");
1133 if (expectAndConsume(MIToken::comma))
1135 BasicBlock *BB = nullptr;
1136 if (Token.isNot(MIToken::IRBlock) && Token.isNot(MIToken::NamedIRBlock))
1137 return error("expected an IR block reference");
1138 if (parseIRBlock(BB, *F))
1141 if (expectAndConsume(MIToken::rparen))
1143 Dest = MachineOperand::CreateBA(BlockAddress::get(F, BB), /*Offset=*/0);
1144 if (parseOperandsOffset(Dest))
1149 bool MIParser::parseTargetIndexOperand(MachineOperand &Dest) {
1150 assert(Token.is(MIToken::kw_target_index));
1152 if (expectAndConsume(MIToken::lparen))
1154 if (Token.isNot(MIToken::Identifier))
1155 return error("expected the name of the target index");
1157 if (getTargetIndex(Token.stringValue(), Index))
1158 return error("use of undefined target index '" + Token.stringValue() + "'");
1160 if (expectAndConsume(MIToken::rparen))
1162 Dest = MachineOperand::CreateTargetIndex(unsigned(Index), /*Offset=*/0);
1163 if (parseOperandsOffset(Dest))
1168 bool MIParser::parseLiveoutRegisterMaskOperand(MachineOperand &Dest) {
1169 assert(Token.is(MIToken::kw_liveout));
1170 const auto *TRI = MF.getSubtarget().getRegisterInfo();
1171 assert(TRI && "Expected target register info");
1172 uint32_t *Mask = MF.allocateRegisterMask(TRI->getNumRegs());
1174 if (expectAndConsume(MIToken::lparen))
1177 if (Token.isNot(MIToken::NamedRegister))
1178 return error("expected a named register");
1180 if (parseRegister(Reg))
1183 Mask[Reg / 32] |= 1U << (Reg % 32);
1184 // TODO: Report an error if the same register is used more than once.
1185 if (Token.isNot(MIToken::comma))
1189 if (expectAndConsume(MIToken::rparen))
1191 Dest = MachineOperand::CreateRegLiveOut(Mask);
1195 bool MIParser::parseMachineOperand(MachineOperand &Dest) {
1196 switch (Token.kind()) {
1197 case MIToken::kw_implicit:
1198 case MIToken::kw_implicit_define:
1199 case MIToken::kw_dead:
1200 case MIToken::kw_killed:
1201 case MIToken::kw_undef:
1202 case MIToken::kw_early_clobber:
1203 case MIToken::kw_debug_use:
1204 case MIToken::underscore:
1205 case MIToken::NamedRegister:
1206 case MIToken::VirtualRegister:
1207 return parseRegisterOperand(Dest);
1208 case MIToken::IntegerLiteral:
1209 return parseImmediateOperand(Dest);
1210 case MIToken::IntegerType:
1211 return parseTypedImmediateOperand(Dest);
1212 case MIToken::kw_half:
1213 case MIToken::kw_float:
1214 case MIToken::kw_double:
1215 case MIToken::kw_x86_fp80:
1216 case MIToken::kw_fp128:
1217 case MIToken::kw_ppc_fp128:
1218 return parseFPImmediateOperand(Dest);
1219 case MIToken::MachineBasicBlock:
1220 return parseMBBOperand(Dest);
1221 case MIToken::StackObject:
1222 return parseStackObjectOperand(Dest);
1223 case MIToken::FixedStackObject:
1224 return parseFixedStackObjectOperand(Dest);
1225 case MIToken::GlobalValue:
1226 case MIToken::NamedGlobalValue:
1227 return parseGlobalAddressOperand(Dest);
1228 case MIToken::ConstantPoolItem:
1229 return parseConstantPoolIndexOperand(Dest);
1230 case MIToken::JumpTableIndex:
1231 return parseJumpTableIndexOperand(Dest);
1232 case MIToken::ExternalSymbol:
1233 return parseExternalSymbolOperand(Dest);
1234 case MIToken::exclaim:
1235 return parseMetadataOperand(Dest);
1236 case MIToken::kw_cfi_offset:
1237 case MIToken::kw_cfi_def_cfa_register:
1238 case MIToken::kw_cfi_def_cfa_offset:
1239 case MIToken::kw_cfi_def_cfa:
1240 return parseCFIOperand(Dest);
1241 case MIToken::kw_blockaddress:
1242 return parseBlockAddressOperand(Dest);
1243 case MIToken::kw_target_index:
1244 return parseTargetIndexOperand(Dest);
1245 case MIToken::kw_liveout:
1246 return parseLiveoutRegisterMaskOperand(Dest);
1247 case MIToken::Error:
1249 case MIToken::Identifier:
1250 if (const auto *RegMask = getRegMask(Token.stringValue())) {
1251 Dest = MachineOperand::CreateRegMask(RegMask);
1257 // TODO: parse the other machine operands.
1258 return error("expected a machine operand");
1263 bool MIParser::parseMachineOperandAndTargetFlags(MachineOperand &Dest) {
1265 bool HasTargetFlags = false;
1266 if (Token.is(MIToken::kw_target_flags)) {
1267 HasTargetFlags = true;
1269 if (expectAndConsume(MIToken::lparen))
1271 if (Token.isNot(MIToken::Identifier))
1272 return error("expected the name of the target flag");
1273 if (getDirectTargetFlag(Token.stringValue(), TF))
1274 return error("use of undefined target flag '" + Token.stringValue() +
1277 // TODO: Parse target's bit target flags.
1278 if (expectAndConsume(MIToken::rparen))
1281 auto Loc = Token.location();
1282 if (parseMachineOperand(Dest))
1284 if (!HasTargetFlags)
1287 return error(Loc, "register operands can't have target flags");
1288 Dest.setTargetFlags(TF);
1292 bool MIParser::parseOffset(int64_t &Offset) {
1293 if (Token.isNot(MIToken::plus) && Token.isNot(MIToken::minus))
1295 StringRef Sign = Token.range();
1296 bool IsNegative = Token.is(MIToken::minus);
1298 if (Token.isNot(MIToken::IntegerLiteral))
1299 return error("expected an integer literal after '" + Sign + "'");
1300 if (Token.integerValue().getMinSignedBits() > 64)
1301 return error("expected 64-bit integer (too large)");
1302 Offset = Token.integerValue().getExtValue();
1309 bool MIParser::parseAlignment(unsigned &Alignment) {
1310 assert(Token.is(MIToken::kw_align));
1312 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
1313 return error("expected an integer literal after 'align'");
1314 if (getUnsigned(Alignment))
1320 bool MIParser::parseOperandsOffset(MachineOperand &Op) {
1322 if (parseOffset(Offset))
1324 Op.setOffset(Offset);
1328 bool MIParser::parseIRValue(Value *&V) {
1329 switch (Token.kind()) {
1330 case MIToken::NamedIRValue: {
1331 V = MF.getFunction()->getValueSymbolTable().lookup(Token.stringValue());
1333 V = MF.getFunction()->getParent()->getValueSymbolTable().lookup(
1334 Token.stringValue());
1336 return error(Twine("use of undefined IR value '") + Token.range() + "'");
1339 // TODO: Parse unnamed IR value references.
1341 llvm_unreachable("The current token should be an IR block reference");
1346 bool MIParser::getUint64(uint64_t &Result) {
1347 assert(Token.hasIntegerValue());
1348 if (Token.integerValue().getActiveBits() > 64)
1349 return error("expected 64-bit integer (too large)");
1350 Result = Token.integerValue().getZExtValue();
1354 bool MIParser::parseMemoryOperandFlag(unsigned &Flags) {
1355 const unsigned OldFlags = Flags;
1356 switch (Token.kind()) {
1357 case MIToken::kw_volatile:
1358 Flags |= MachineMemOperand::MOVolatile;
1360 case MIToken::kw_non_temporal:
1361 Flags |= MachineMemOperand::MONonTemporal;
1363 case MIToken::kw_invariant:
1364 Flags |= MachineMemOperand::MOInvariant;
1366 // TODO: parse the target specific memory operand flags.
1368 llvm_unreachable("The current token should be a memory operand flag");
1370 if (OldFlags == Flags)
1371 // We know that the same flag is specified more than once when the flags
1372 // weren't modified.
1373 return error("duplicate '" + Token.stringValue() + "' memory operand flag");
1378 bool MIParser::parseMemoryPseudoSourceValue(const PseudoSourceValue *&PSV) {
1379 switch (Token.kind()) {
1380 case MIToken::kw_stack:
1381 PSV = MF.getPSVManager().getStack();
1383 case MIToken::kw_got:
1384 PSV = MF.getPSVManager().getGOT();
1386 case MIToken::kw_jump_table:
1387 PSV = MF.getPSVManager().getJumpTable();
1389 case MIToken::kw_constant_pool:
1390 PSV = MF.getPSVManager().getConstantPool();
1392 case MIToken::FixedStackObject: {
1394 if (parseFixedStackFrameIndex(FI))
1396 PSV = MF.getPSVManager().getFixedStack(FI);
1397 // The token was already consumed, so use return here instead of break.
1400 // TODO: Parse the other pseudo source values.
1402 llvm_unreachable("The current token should be pseudo source value");
1408 bool MIParser::parseMachinePointerInfo(MachinePointerInfo &Dest) {
1409 if (Token.is(MIToken::kw_constant_pool) || Token.is(MIToken::kw_stack) ||
1410 Token.is(MIToken::kw_got) || Token.is(MIToken::kw_jump_table) ||
1411 Token.is(MIToken::FixedStackObject)) {
1412 const PseudoSourceValue *PSV = nullptr;
1413 if (parseMemoryPseudoSourceValue(PSV))
1416 if (parseOffset(Offset))
1418 Dest = MachinePointerInfo(PSV, Offset);
1421 if (Token.isNot(MIToken::NamedIRValue))
1422 return error("expected an IR value reference");
1424 if (parseIRValue(V))
1426 if (!V->getType()->isPointerTy())
1427 return error("expected a pointer IR value");
1430 if (parseOffset(Offset))
1432 Dest = MachinePointerInfo(V, Offset);
1436 bool MIParser::parseMachineMemoryOperand(MachineMemOperand *&Dest) {
1437 if (expectAndConsume(MIToken::lparen))
1440 while (Token.isMemoryOperandFlag()) {
1441 if (parseMemoryOperandFlag(Flags))
1444 if (Token.isNot(MIToken::Identifier) ||
1445 (Token.stringValue() != "load" && Token.stringValue() != "store"))
1446 return error("expected 'load' or 'store' memory operation");
1447 if (Token.stringValue() == "load")
1448 Flags |= MachineMemOperand::MOLoad;
1450 Flags |= MachineMemOperand::MOStore;
1453 if (Token.isNot(MIToken::IntegerLiteral))
1454 return error("expected the size integer literal after memory operation");
1456 if (getUint64(Size))
1460 const char *Word = Flags & MachineMemOperand::MOLoad ? "from" : "into";
1461 if (Token.isNot(MIToken::Identifier) || Token.stringValue() != Word)
1462 return error(Twine("expected '") + Word + "'");
1465 MachinePointerInfo Ptr = MachinePointerInfo();
1466 if (parseMachinePointerInfo(Ptr))
1468 unsigned BaseAlignment = Size;
1469 if (Token.is(MIToken::comma)) {
1471 if (Token.isNot(MIToken::kw_align))
1472 return error("expected 'align'");
1473 if (parseAlignment(BaseAlignment))
1476 // TODO: Parse the attached metadata nodes.
1477 if (expectAndConsume(MIToken::rparen))
1479 Dest = MF.getMachineMemOperand(Ptr, Flags, Size, BaseAlignment);
1483 void MIParser::initNames2InstrOpCodes() {
1484 if (!Names2InstrOpCodes.empty())
1486 const auto *TII = MF.getSubtarget().getInstrInfo();
1487 assert(TII && "Expected target instruction info");
1488 for (unsigned I = 0, E = TII->getNumOpcodes(); I < E; ++I)
1489 Names2InstrOpCodes.insert(std::make_pair(StringRef(TII->getName(I)), I));
1492 bool MIParser::parseInstrName(StringRef InstrName, unsigned &OpCode) {
1493 initNames2InstrOpCodes();
1494 auto InstrInfo = Names2InstrOpCodes.find(InstrName);
1495 if (InstrInfo == Names2InstrOpCodes.end())
1497 OpCode = InstrInfo->getValue();
1501 void MIParser::initNames2Regs() {
1502 if (!Names2Regs.empty())
1504 // The '%noreg' register is the register 0.
1505 Names2Regs.insert(std::make_pair("noreg", 0));
1506 const auto *TRI = MF.getSubtarget().getRegisterInfo();
1507 assert(TRI && "Expected target register info");
1508 for (unsigned I = 0, E = TRI->getNumRegs(); I < E; ++I) {
1510 Names2Regs.insert(std::make_pair(StringRef(TRI->getName(I)).lower(), I))
1513 assert(WasInserted && "Expected registers to be unique case-insensitively");
1517 bool MIParser::getRegisterByName(StringRef RegName, unsigned &Reg) {
1519 auto RegInfo = Names2Regs.find(RegName);
1520 if (RegInfo == Names2Regs.end())
1522 Reg = RegInfo->getValue();
1526 void MIParser::initNames2RegMasks() {
1527 if (!Names2RegMasks.empty())
1529 const auto *TRI = MF.getSubtarget().getRegisterInfo();
1530 assert(TRI && "Expected target register info");
1531 ArrayRef<const uint32_t *> RegMasks = TRI->getRegMasks();
1532 ArrayRef<const char *> RegMaskNames = TRI->getRegMaskNames();
1533 assert(RegMasks.size() == RegMaskNames.size());
1534 for (size_t I = 0, E = RegMasks.size(); I < E; ++I)
1535 Names2RegMasks.insert(
1536 std::make_pair(StringRef(RegMaskNames[I]).lower(), RegMasks[I]));
1539 const uint32_t *MIParser::getRegMask(StringRef Identifier) {
1540 initNames2RegMasks();
1541 auto RegMaskInfo = Names2RegMasks.find(Identifier);
1542 if (RegMaskInfo == Names2RegMasks.end())
1544 return RegMaskInfo->getValue();
1547 void MIParser::initNames2SubRegIndices() {
1548 if (!Names2SubRegIndices.empty())
1550 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1551 for (unsigned I = 1, E = TRI->getNumSubRegIndices(); I < E; ++I)
1552 Names2SubRegIndices.insert(
1553 std::make_pair(StringRef(TRI->getSubRegIndexName(I)).lower(), I));
1556 unsigned MIParser::getSubRegIndex(StringRef Name) {
1557 initNames2SubRegIndices();
1558 auto SubRegInfo = Names2SubRegIndices.find(Name);
1559 if (SubRegInfo == Names2SubRegIndices.end())
1561 return SubRegInfo->getValue();
1564 static void initSlots2BasicBlocks(
1566 DenseMap<unsigned, const BasicBlock *> &Slots2BasicBlocks) {
1567 ModuleSlotTracker MST(F.getParent(), /*ShouldInitializeAllMetadata=*/false);
1568 MST.incorporateFunction(F);
1569 for (auto &BB : F) {
1572 int Slot = MST.getLocalSlot(&BB);
1575 Slots2BasicBlocks.insert(std::make_pair(unsigned(Slot), &BB));
1579 static const BasicBlock *getIRBlockFromSlot(
1581 const DenseMap<unsigned, const BasicBlock *> &Slots2BasicBlocks) {
1582 auto BlockInfo = Slots2BasicBlocks.find(Slot);
1583 if (BlockInfo == Slots2BasicBlocks.end())
1585 return BlockInfo->second;
1588 const BasicBlock *MIParser::getIRBlock(unsigned Slot) {
1589 if (Slots2BasicBlocks.empty())
1590 initSlots2BasicBlocks(*MF.getFunction(), Slots2BasicBlocks);
1591 return getIRBlockFromSlot(Slot, Slots2BasicBlocks);
1594 const BasicBlock *MIParser::getIRBlock(unsigned Slot, const Function &F) {
1595 if (&F == MF.getFunction())
1596 return getIRBlock(Slot);
1597 DenseMap<unsigned, const BasicBlock *> CustomSlots2BasicBlocks;
1598 initSlots2BasicBlocks(F, CustomSlots2BasicBlocks);
1599 return getIRBlockFromSlot(Slot, CustomSlots2BasicBlocks);
1602 void MIParser::initNames2TargetIndices() {
1603 if (!Names2TargetIndices.empty())
1605 const auto *TII = MF.getSubtarget().getInstrInfo();
1606 assert(TII && "Expected target instruction info");
1607 auto Indices = TII->getSerializableTargetIndices();
1608 for (const auto &I : Indices)
1609 Names2TargetIndices.insert(std::make_pair(StringRef(I.second), I.first));
1612 bool MIParser::getTargetIndex(StringRef Name, int &Index) {
1613 initNames2TargetIndices();
1614 auto IndexInfo = Names2TargetIndices.find(Name);
1615 if (IndexInfo == Names2TargetIndices.end())
1617 Index = IndexInfo->second;
1621 void MIParser::initNames2DirectTargetFlags() {
1622 if (!Names2DirectTargetFlags.empty())
1624 const auto *TII = MF.getSubtarget().getInstrInfo();
1625 assert(TII && "Expected target instruction info");
1626 auto Flags = TII->getSerializableDirectMachineOperandTargetFlags();
1627 for (const auto &I : Flags)
1628 Names2DirectTargetFlags.insert(
1629 std::make_pair(StringRef(I.second), I.first));
1632 bool MIParser::getDirectTargetFlag(StringRef Name, unsigned &Flag) {
1633 initNames2DirectTargetFlags();
1634 auto FlagInfo = Names2DirectTargetFlags.find(Name);
1635 if (FlagInfo == Names2DirectTargetFlags.end())
1637 Flag = FlagInfo->second;
1641 bool llvm::parseMachineBasicBlockDefinitions(MachineFunction &MF, StringRef Src,
1642 PerFunctionMIParsingState &PFS,
1643 const SlotMapping &IRSlots,
1644 SMDiagnostic &Error) {
1646 SM.AddNewSourceBuffer(
1647 MemoryBuffer::getMemBuffer(Src, "", /*RequiresNullTerminator=*/false),
1649 return MIParser(SM, MF, Error, Src, PFS, IRSlots)
1650 .parseBasicBlockDefinitions(PFS.MBBSlots);
1653 bool llvm::parseMachineInstructions(MachineFunction &MF, StringRef Src,
1654 const PerFunctionMIParsingState &PFS,
1655 const SlotMapping &IRSlots,
1656 SMDiagnostic &Error) {
1658 SM.AddNewSourceBuffer(
1659 MemoryBuffer::getMemBuffer(Src, "", /*RequiresNullTerminator=*/false),
1661 return MIParser(SM, MF, Error, Src, PFS, IRSlots).parseBasicBlocks();
1664 bool llvm::parseMBBReference(MachineBasicBlock *&MBB, SourceMgr &SM,
1665 MachineFunction &MF, StringRef Src,
1666 const PerFunctionMIParsingState &PFS,
1667 const SlotMapping &IRSlots, SMDiagnostic &Error) {
1668 return MIParser(SM, MF, Error, Src, PFS, IRSlots).parseStandaloneMBB(MBB);
1671 bool llvm::parseNamedRegisterReference(unsigned &Reg, SourceMgr &SM,
1672 MachineFunction &MF, StringRef Src,
1673 const PerFunctionMIParsingState &PFS,
1674 const SlotMapping &IRSlots,
1675 SMDiagnostic &Error) {
1676 return MIParser(SM, MF, Error, Src, PFS, IRSlots)
1677 .parseStandaloneNamedRegister(Reg);
1680 bool llvm::parseVirtualRegisterReference(unsigned &Reg, SourceMgr &SM,
1681 MachineFunction &MF, StringRef Src,
1682 const PerFunctionMIParsingState &PFS,
1683 const SlotMapping &IRSlots,
1684 SMDiagnostic &Error) {
1685 return MIParser(SM, MF, Error, Src, PFS, IRSlots)
1686 .parseStandaloneVirtualRegister(Reg);