MIR Parser: Extract the parsing of the operand's offset into a new method. NFC.
[oota-llvm.git] / lib / CodeGen / MIRParser / MIParser.cpp
1 //===- MIParser.cpp - Machine instructions parser implementation ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the parsing of machine instructions.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "MIParser.h"
15 #include "MILexer.h"
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"
35
36 using namespace llvm;
37
38 namespace {
39
40 /// A wrapper struct around the 'MachineOperand' struct that includes a source
41 /// range.
42 struct MachineOperandWithLocation {
43   MachineOperand Operand;
44   StringRef::iterator Begin;
45   StringRef::iterator End;
46
47   MachineOperandWithLocation(const MachineOperand &Operand,
48                              StringRef::iterator Begin, StringRef::iterator End)
49       : Operand(Operand), Begin(Begin), End(End) {}
50 };
51
52 class MIParser {
53   SourceMgr &SM;
54   MachineFunction &MF;
55   SMDiagnostic &Error;
56   StringRef Source, CurrentSource;
57   MIToken Token;
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;
75
76 public:
77   MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
78            StringRef Source, const PerFunctionMIParsingState &PFS,
79            const SlotMapping &IRSlots);
80
81   void lex();
82
83   /// Report an error at the current location with the given message.
84   ///
85   /// This function always return true.
86   bool error(const Twine &Msg);
87
88   /// Report an error at the given location with the given message.
89   ///
90   /// This function always return true.
91   bool error(StringRef::iterator Loc, const Twine &Msg);
92
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);
98
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 parseMachineOperand(MachineOperand &Dest);
125   bool parseMachineOperandAndTargetFlags(MachineOperand &Dest);
126   bool parseOffset(int64_t &Offset);
127   bool parseOperandsOffset(MachineOperand &Op);
128   bool parseIRValue(Value *&V);
129   bool parseMemoryOperandFlag(unsigned &Flags);
130   bool parseMachineMemoryOperand(MachineMemOperand *&Dest);
131
132 private:
133   /// Convert the integer literal in the current token into an unsigned integer.
134   ///
135   /// Return true if an error occurred.
136   bool getUnsigned(unsigned &Result);
137
138   /// Convert the integer literal in the current token into an uint64.
139   ///
140   /// Return true if an error occurred.
141   bool getUint64(uint64_t &Result);
142
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);
146
147   void initNames2InstrOpCodes();
148
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);
152
153   bool parseInstruction(unsigned &OpCode, unsigned &Flags);
154
155   bool verifyImplicitOperands(ArrayRef<MachineOperandWithLocation> Operands,
156                               const MCInstrDesc &MCID);
157
158   void initNames2Regs();
159
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);
163
164   void initNames2RegMasks();
165
166   /// Check if the given identifier is a name of a register mask.
167   ///
168   /// Return null if the identifier isn't a register mask.
169   const uint32_t *getRegMask(StringRef Identifier);
170
171   void initNames2SubRegIndices();
172
173   /// Check if the given identifier is a name of a subregister index.
174   ///
175   /// Return 0 if the name isn't a subregister index class.
176   unsigned getSubRegIndex(StringRef Name);
177
178   const BasicBlock *getIRBlock(unsigned Slot);
179   const BasicBlock *getIRBlock(unsigned Slot, const Function &F);
180
181   void initNames2TargetIndices();
182
183   /// Try to convert a name of target index to the corresponding target index.
184   ///
185   /// Return true if the name isn't a name of a target index.
186   bool getTargetIndex(StringRef Name, int &Index);
187
188   void initNames2DirectTargetFlags();
189
190   /// Try to convert a name of a direct target flag to the corresponding
191   /// target flag.
192   ///
193   /// Return true if the name isn't a name of a direct flag.
194   bool getDirectTargetFlag(StringRef Name, unsigned &Flag);
195 };
196
197 } // end anonymous namespace
198
199 MIParser::MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
200                    StringRef Source, const PerFunctionMIParsingState &PFS,
201                    const SlotMapping &IRSlots)
202     : SM(SM), MF(MF), Error(Error), Source(Source), CurrentSource(Source),
203       PFS(PFS), IRSlots(IRSlots) {}
204
205 void MIParser::lex() {
206   CurrentSource = lexMIToken(
207       CurrentSource, Token,
208       [this](StringRef::iterator Loc, const Twine &Msg) { error(Loc, Msg); });
209 }
210
211 bool MIParser::error(const Twine &Msg) { return error(Token.location(), Msg); }
212
213 bool MIParser::error(StringRef::iterator Loc, const Twine &Msg) {
214   assert(Loc >= Source.data() && Loc <= (Source.data() + Source.size()));
215   Error = SMDiagnostic(
216       SM, SMLoc(),
217       SM.getMemoryBuffer(SM.getMainFileID())->getBufferIdentifier(), 1,
218       Loc - Source.data(), SourceMgr::DK_Error, Msg.str(), Source, None, None);
219   return true;
220 }
221
222 static const char *toString(MIToken::TokenKind TokenKind) {
223   switch (TokenKind) {
224   case MIToken::comma:
225     return "','";
226   case MIToken::equal:
227     return "'='";
228   case MIToken::lparen:
229     return "'('";
230   case MIToken::rparen:
231     return "')'";
232   default:
233     return "<unknown token>";
234   }
235 }
236
237 bool MIParser::expectAndConsume(MIToken::TokenKind TokenKind) {
238   if (Token.isNot(TokenKind))
239     return error(Twine("expected ") + toString(TokenKind));
240   lex();
241   return false;
242 }
243
244 bool MIParser::parse(MachineInstr *&MI) {
245   lex();
246
247   // Parse any register operands before '='
248   MachineOperand MO = MachineOperand::CreateImm(0);
249   SmallVector<MachineOperandWithLocation, 8> Operands;
250   while (Token.isRegister() || Token.isRegisterFlag()) {
251     auto Loc = Token.location();
252     if (parseRegisterOperand(MO, /*IsDef=*/true))
253       return true;
254     Operands.push_back(MachineOperandWithLocation(MO, Loc, Token.location()));
255     if (Token.isNot(MIToken::comma))
256       break;
257     lex();
258   }
259   if (!Operands.empty() && expectAndConsume(MIToken::equal))
260     return true;
261
262   unsigned OpCode, Flags = 0;
263   if (Token.isError() || parseInstruction(OpCode, Flags))
264     return true;
265
266   // TODO: Parse the bundle instruction flags.
267
268   // Parse the remaining machine operands.
269   while (Token.isNot(MIToken::Eof) && Token.isNot(MIToken::kw_debug_location) &&
270          Token.isNot(MIToken::coloncolon)) {
271     auto Loc = Token.location();
272     if (parseMachineOperandAndTargetFlags(MO))
273       return true;
274     Operands.push_back(MachineOperandWithLocation(MO, Loc, Token.location()));
275     if (Token.is(MIToken::Eof) || Token.is(MIToken::coloncolon))
276       break;
277     if (Token.isNot(MIToken::comma))
278       return error("expected ',' before the next machine operand");
279     lex();
280   }
281
282   DebugLoc DebugLocation;
283   if (Token.is(MIToken::kw_debug_location)) {
284     lex();
285     if (Token.isNot(MIToken::exclaim))
286       return error("expected a metadata node after 'debug-location'");
287     MDNode *Node = nullptr;
288     if (parseMDNode(Node))
289       return true;
290     DebugLocation = DebugLoc(Node);
291   }
292
293   // Parse the machine memory operands.
294   SmallVector<MachineMemOperand *, 2> MemOperands;
295   if (Token.is(MIToken::coloncolon)) {
296     lex();
297     while (Token.isNot(MIToken::Eof)) {
298       MachineMemOperand *MemOp = nullptr;
299       if (parseMachineMemoryOperand(MemOp))
300         return true;
301       MemOperands.push_back(MemOp);
302       if (Token.is(MIToken::Eof))
303         break;
304       if (Token.isNot(MIToken::comma))
305         return error("expected ',' before the next machine memory operand");
306       lex();
307     }
308   }
309
310   const auto &MCID = MF.getSubtarget().getInstrInfo()->get(OpCode);
311   if (!MCID.isVariadic()) {
312     // FIXME: Move the implicit operand verification to the machine verifier.
313     if (verifyImplicitOperands(Operands, MCID))
314       return true;
315   }
316
317   // TODO: Check for extraneous machine operands.
318   MI = MF.CreateMachineInstr(MCID, DebugLocation, /*NoImplicit=*/true);
319   MI->setFlags(Flags);
320   for (const auto &Operand : Operands)
321     MI->addOperand(MF, Operand.Operand);
322   if (MemOperands.empty())
323     return false;
324   MachineInstr::mmo_iterator MemRefs =
325       MF.allocateMemRefsArray(MemOperands.size());
326   std::copy(MemOperands.begin(), MemOperands.end(), MemRefs);
327   MI->setMemRefs(MemRefs, MemRefs + MemOperands.size());
328   return false;
329 }
330
331 bool MIParser::parseStandaloneMBB(MachineBasicBlock *&MBB) {
332   lex();
333   if (Token.isNot(MIToken::MachineBasicBlock))
334     return error("expected a machine basic block reference");
335   if (parseMBBReference(MBB))
336     return true;
337   lex();
338   if (Token.isNot(MIToken::Eof))
339     return error(
340         "expected end of string after the machine basic block reference");
341   return false;
342 }
343
344 bool MIParser::parseStandaloneNamedRegister(unsigned &Reg) {
345   lex();
346   if (Token.isNot(MIToken::NamedRegister))
347     return error("expected a named register");
348   if (parseRegister(Reg))
349     return 0;
350   lex();
351   if (Token.isNot(MIToken::Eof))
352     return error("expected end of string after the register reference");
353   return false;
354 }
355
356 bool MIParser::parseStandaloneVirtualRegister(unsigned &Reg) {
357   lex();
358   if (Token.isNot(MIToken::VirtualRegister))
359     return error("expected a virtual register");
360   if (parseRegister(Reg))
361     return 0;
362   lex();
363   if (Token.isNot(MIToken::Eof))
364     return error("expected end of string after the register reference");
365   return false;
366 }
367
368 bool MIParser::parseStandaloneIRBlockReference(const BasicBlock *&BB) {
369   lex();
370   if (Token.isNot(MIToken::IRBlock))
371     return error("expected an IR block reference");
372   unsigned SlotNumber = 0;
373   if (getUnsigned(SlotNumber))
374     return true;
375   BB = getIRBlock(SlotNumber);
376   if (!BB)
377     return error(Twine("use of undefined IR block '%ir-block.") +
378                  Twine(SlotNumber) + "'");
379   lex();
380   if (Token.isNot(MIToken::Eof))
381     return error("expected end of string after the IR block reference");
382   return false;
383 }
384
385 static const char *printImplicitRegisterFlag(const MachineOperand &MO) {
386   assert(MO.isImplicit());
387   return MO.isDef() ? "implicit-def" : "implicit";
388 }
389
390 static std::string getRegisterName(const TargetRegisterInfo *TRI,
391                                    unsigned Reg) {
392   assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "expected phys reg");
393   return StringRef(TRI->getName(Reg)).lower();
394 }
395
396 bool MIParser::verifyImplicitOperands(
397     ArrayRef<MachineOperandWithLocation> Operands, const MCInstrDesc &MCID) {
398   if (MCID.isCall())
399     // We can't verify call instructions as they can contain arbitrary implicit
400     // register and register mask operands.
401     return false;
402
403   // Gather all the expected implicit operands.
404   SmallVector<MachineOperand, 4> ImplicitOperands;
405   if (MCID.ImplicitDefs)
406     for (const uint16_t *ImpDefs = MCID.getImplicitDefs(); *ImpDefs; ++ImpDefs)
407       ImplicitOperands.push_back(
408           MachineOperand::CreateReg(*ImpDefs, true, true));
409   if (MCID.ImplicitUses)
410     for (const uint16_t *ImpUses = MCID.getImplicitUses(); *ImpUses; ++ImpUses)
411       ImplicitOperands.push_back(
412           MachineOperand::CreateReg(*ImpUses, false, true));
413
414   const auto *TRI = MF.getSubtarget().getRegisterInfo();
415   assert(TRI && "Expected target register info");
416   size_t I = ImplicitOperands.size(), J = Operands.size();
417   while (I) {
418     --I;
419     if (J) {
420       --J;
421       const auto &ImplicitOperand = ImplicitOperands[I];
422       const auto &Operand = Operands[J].Operand;
423       if (ImplicitOperand.isIdenticalTo(Operand))
424         continue;
425       if (Operand.isReg() && Operand.isImplicit()) {
426         return error(Operands[J].Begin,
427                      Twine("expected an implicit register operand '") +
428                          printImplicitRegisterFlag(ImplicitOperand) + " %" +
429                          getRegisterName(TRI, ImplicitOperand.getReg()) + "'");
430       }
431     }
432     // TODO: Fix source location when Operands[J].end is right before '=', i.e:
433     // insead of reporting an error at this location:
434     //            %eax = MOV32r0
435     //                 ^
436     // report the error at the following location:
437     //            %eax = MOV32r0
438     //                          ^
439     return error(J < Operands.size() ? Operands[J].End : Token.location(),
440                  Twine("missing implicit register operand '") +
441                      printImplicitRegisterFlag(ImplicitOperands[I]) + " %" +
442                      getRegisterName(TRI, ImplicitOperands[I].getReg()) + "'");
443   }
444   return false;
445 }
446
447 bool MIParser::parseInstruction(unsigned &OpCode, unsigned &Flags) {
448   if (Token.is(MIToken::kw_frame_setup)) {
449     Flags |= MachineInstr::FrameSetup;
450     lex();
451   }
452   if (Token.isNot(MIToken::Identifier))
453     return error("expected a machine instruction");
454   StringRef InstrName = Token.stringValue();
455   if (parseInstrName(InstrName, OpCode))
456     return error(Twine("unknown machine instruction name '") + InstrName + "'");
457   lex();
458   return false;
459 }
460
461 bool MIParser::parseRegister(unsigned &Reg) {
462   switch (Token.kind()) {
463   case MIToken::underscore:
464     Reg = 0;
465     break;
466   case MIToken::NamedRegister: {
467     StringRef Name = Token.stringValue();
468     if (getRegisterByName(Name, Reg))
469       return error(Twine("unknown register name '") + Name + "'");
470     break;
471   }
472   case MIToken::VirtualRegister: {
473     unsigned ID;
474     if (getUnsigned(ID))
475       return true;
476     const auto RegInfo = PFS.VirtualRegisterSlots.find(ID);
477     if (RegInfo == PFS.VirtualRegisterSlots.end())
478       return error(Twine("use of undefined virtual register '%") + Twine(ID) +
479                    "'");
480     Reg = RegInfo->second;
481     break;
482   }
483   // TODO: Parse other register kinds.
484   default:
485     llvm_unreachable("The current token should be a register");
486   }
487   return false;
488 }
489
490 bool MIParser::parseRegisterFlag(unsigned &Flags) {
491   const unsigned OldFlags = Flags;
492   switch (Token.kind()) {
493   case MIToken::kw_implicit:
494     Flags |= RegState::Implicit;
495     break;
496   case MIToken::kw_implicit_define:
497     Flags |= RegState::ImplicitDefine;
498     break;
499   case MIToken::kw_dead:
500     Flags |= RegState::Dead;
501     break;
502   case MIToken::kw_killed:
503     Flags |= RegState::Kill;
504     break;
505   case MIToken::kw_undef:
506     Flags |= RegState::Undef;
507     break;
508   case MIToken::kw_early_clobber:
509     Flags |= RegState::EarlyClobber;
510     break;
511   case MIToken::kw_debug_use:
512     Flags |= RegState::Debug;
513     break;
514   // TODO: parse the other register flags.
515   default:
516     llvm_unreachable("The current token should be a register flag");
517   }
518   if (OldFlags == Flags)
519     // We know that the same flag is specified more than once when the flags
520     // weren't modified.
521     return error("duplicate '" + Token.stringValue() + "' register flag");
522   lex();
523   return false;
524 }
525
526 bool MIParser::parseSubRegisterIndex(unsigned &SubReg) {
527   assert(Token.is(MIToken::colon));
528   lex();
529   if (Token.isNot(MIToken::Identifier))
530     return error("expected a subregister index after ':'");
531   auto Name = Token.stringValue();
532   SubReg = getSubRegIndex(Name);
533   if (!SubReg)
534     return error(Twine("use of unknown subregister index '") + Name + "'");
535   lex();
536   return false;
537 }
538
539 bool MIParser::parseRegisterOperand(MachineOperand &Dest, bool IsDef) {
540   unsigned Reg;
541   unsigned Flags = IsDef ? RegState::Define : 0;
542   while (Token.isRegisterFlag()) {
543     if (parseRegisterFlag(Flags))
544       return true;
545   }
546   if (!Token.isRegister())
547     return error("expected a register after register flags");
548   if (parseRegister(Reg))
549     return true;
550   lex();
551   unsigned SubReg = 0;
552   if (Token.is(MIToken::colon)) {
553     if (parseSubRegisterIndex(SubReg))
554       return true;
555   }
556   Dest = MachineOperand::CreateReg(
557       Reg, Flags & RegState::Define, Flags & RegState::Implicit,
558       Flags & RegState::Kill, Flags & RegState::Dead, Flags & RegState::Undef,
559       Flags & RegState::EarlyClobber, SubReg, Flags & RegState::Debug);
560   return false;
561 }
562
563 bool MIParser::parseImmediateOperand(MachineOperand &Dest) {
564   assert(Token.is(MIToken::IntegerLiteral));
565   const APSInt &Int = Token.integerValue();
566   if (Int.getMinSignedBits() > 64)
567     return error("integer literal is too large to be an immediate operand");
568   Dest = MachineOperand::CreateImm(Int.getExtValue());
569   lex();
570   return false;
571 }
572
573 bool MIParser::parseIRConstant(StringRef::iterator Loc, const Constant *&C) {
574   auto Source = StringRef(Loc, Token.range().end() - Loc).str();
575   lex();
576   SMDiagnostic Err;
577   C = parseConstantValue(Source.c_str(), Err, *MF.getFunction()->getParent());
578   if (!C)
579     return error(Loc + Err.getColumnNo(), Err.getMessage());
580   return false;
581 }
582
583 bool MIParser::parseTypedImmediateOperand(MachineOperand &Dest) {
584   assert(Token.is(MIToken::IntegerType));
585   auto Loc = Token.location();
586   lex();
587   if (Token.isNot(MIToken::IntegerLiteral))
588     return error("expected an integer literal");
589   const Constant *C = nullptr;
590   if (parseIRConstant(Loc, C))
591     return true;
592   Dest = MachineOperand::CreateCImm(cast<ConstantInt>(C));
593   return false;
594 }
595
596 bool MIParser::parseFPImmediateOperand(MachineOperand &Dest) {
597   auto Loc = Token.location();
598   lex();
599   if (Token.isNot(MIToken::FloatingPointLiteral))
600     return error("expected a floating point literal");
601   const Constant *C = nullptr;
602   if (parseIRConstant(Loc, C))
603     return true;
604   Dest = MachineOperand::CreateFPImm(cast<ConstantFP>(C));
605   return false;
606 }
607
608 bool MIParser::getUnsigned(unsigned &Result) {
609   assert(Token.hasIntegerValue() && "Expected a token with an integer value");
610   const uint64_t Limit = uint64_t(std::numeric_limits<unsigned>::max()) + 1;
611   uint64_t Val64 = Token.integerValue().getLimitedValue(Limit);
612   if (Val64 == Limit)
613     return error("expected 32-bit integer (too large)");
614   Result = Val64;
615   return false;
616 }
617
618 bool MIParser::parseMBBReference(MachineBasicBlock *&MBB) {
619   assert(Token.is(MIToken::MachineBasicBlock));
620   unsigned Number;
621   if (getUnsigned(Number))
622     return true;
623   auto MBBInfo = PFS.MBBSlots.find(Number);
624   if (MBBInfo == PFS.MBBSlots.end())
625     return error(Twine("use of undefined machine basic block #") +
626                  Twine(Number));
627   MBB = MBBInfo->second;
628   if (!Token.stringValue().empty() && Token.stringValue() != MBB->getName())
629     return error(Twine("the name of machine basic block #") + Twine(Number) +
630                  " isn't '" + Token.stringValue() + "'");
631   return false;
632 }
633
634 bool MIParser::parseMBBOperand(MachineOperand &Dest) {
635   MachineBasicBlock *MBB;
636   if (parseMBBReference(MBB))
637     return true;
638   Dest = MachineOperand::CreateMBB(MBB);
639   lex();
640   return false;
641 }
642
643 bool MIParser::parseStackObjectOperand(MachineOperand &Dest) {
644   assert(Token.is(MIToken::StackObject));
645   unsigned ID;
646   if (getUnsigned(ID))
647     return true;
648   auto ObjectInfo = PFS.StackObjectSlots.find(ID);
649   if (ObjectInfo == PFS.StackObjectSlots.end())
650     return error(Twine("use of undefined stack object '%stack.") + Twine(ID) +
651                  "'");
652   StringRef Name;
653   if (const auto *Alloca =
654           MF.getFrameInfo()->getObjectAllocation(ObjectInfo->second))
655     Name = Alloca->getName();
656   if (!Token.stringValue().empty() && Token.stringValue() != Name)
657     return error(Twine("the name of the stack object '%stack.") + Twine(ID) +
658                  "' isn't '" + Token.stringValue() + "'");
659   lex();
660   Dest = MachineOperand::CreateFI(ObjectInfo->second);
661   return false;
662 }
663
664 bool MIParser::parseFixedStackObjectOperand(MachineOperand &Dest) {
665   assert(Token.is(MIToken::FixedStackObject));
666   unsigned ID;
667   if (getUnsigned(ID))
668     return true;
669   auto ObjectInfo = PFS.FixedStackObjectSlots.find(ID);
670   if (ObjectInfo == PFS.FixedStackObjectSlots.end())
671     return error(Twine("use of undefined fixed stack object '%fixed-stack.") +
672                  Twine(ID) + "'");
673   lex();
674   Dest = MachineOperand::CreateFI(ObjectInfo->second);
675   return false;
676 }
677
678 bool MIParser::parseGlobalValue(GlobalValue *&GV) {
679   switch (Token.kind()) {
680   case MIToken::NamedGlobalValue: {
681     const Module *M = MF.getFunction()->getParent();
682     GV = M->getNamedValue(Token.stringValue());
683     if (!GV)
684       return error(Twine("use of undefined global value '") + Token.range() +
685                    "'");
686     break;
687   }
688   case MIToken::GlobalValue: {
689     unsigned GVIdx;
690     if (getUnsigned(GVIdx))
691       return true;
692     if (GVIdx >= IRSlots.GlobalValues.size())
693       return error(Twine("use of undefined global value '@") + Twine(GVIdx) +
694                    "'");
695     GV = IRSlots.GlobalValues[GVIdx];
696     break;
697   }
698   default:
699     llvm_unreachable("The current token should be a global value");
700   }
701   return false;
702 }
703
704 bool MIParser::parseGlobalAddressOperand(MachineOperand &Dest) {
705   GlobalValue *GV = nullptr;
706   if (parseGlobalValue(GV))
707     return true;
708   lex();
709   Dest = MachineOperand::CreateGA(GV, /*Offset=*/0);
710   if (parseOperandsOffset(Dest))
711     return true;
712   return false;
713 }
714
715 bool MIParser::parseConstantPoolIndexOperand(MachineOperand &Dest) {
716   assert(Token.is(MIToken::ConstantPoolItem));
717   unsigned ID;
718   if (getUnsigned(ID))
719     return true;
720   auto ConstantInfo = PFS.ConstantPoolSlots.find(ID);
721   if (ConstantInfo == PFS.ConstantPoolSlots.end())
722     return error("use of undefined constant '%const." + Twine(ID) + "'");
723   lex();
724   Dest = MachineOperand::CreateCPI(ID, /*Offset=*/0);
725   if (parseOperandsOffset(Dest))
726     return true;
727   return false;
728 }
729
730 bool MIParser::parseJumpTableIndexOperand(MachineOperand &Dest) {
731   assert(Token.is(MIToken::JumpTableIndex));
732   unsigned ID;
733   if (getUnsigned(ID))
734     return true;
735   auto JumpTableEntryInfo = PFS.JumpTableSlots.find(ID);
736   if (JumpTableEntryInfo == PFS.JumpTableSlots.end())
737     return error("use of undefined jump table '%jump-table." + Twine(ID) + "'");
738   lex();
739   Dest = MachineOperand::CreateJTI(JumpTableEntryInfo->second);
740   return false;
741 }
742
743 bool MIParser::parseExternalSymbolOperand(MachineOperand &Dest) {
744   assert(Token.is(MIToken::ExternalSymbol));
745   const char *Symbol = MF.createExternalSymbolName(Token.stringValue());
746   lex();
747   Dest = MachineOperand::CreateES(Symbol);
748   if (parseOperandsOffset(Dest))
749     return true;
750   return false;
751 }
752
753 bool MIParser::parseMDNode(MDNode *&Node) {
754   assert(Token.is(MIToken::exclaim));
755   auto Loc = Token.location();
756   lex();
757   if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
758     return error("expected metadata id after '!'");
759   unsigned ID;
760   if (getUnsigned(ID))
761     return true;
762   auto NodeInfo = IRSlots.MetadataNodes.find(ID);
763   if (NodeInfo == IRSlots.MetadataNodes.end())
764     return error(Loc, "use of undefined metadata '!" + Twine(ID) + "'");
765   lex();
766   Node = NodeInfo->second.get();
767   return false;
768 }
769
770 bool MIParser::parseMetadataOperand(MachineOperand &Dest) {
771   MDNode *Node = nullptr;
772   if (parseMDNode(Node))
773     return true;
774   Dest = MachineOperand::CreateMetadata(Node);
775   return false;
776 }
777
778 bool MIParser::parseCFIOffset(int &Offset) {
779   if (Token.isNot(MIToken::IntegerLiteral))
780     return error("expected a cfi offset");
781   if (Token.integerValue().getMinSignedBits() > 32)
782     return error("expected a 32 bit integer (the cfi offset is too large)");
783   Offset = (int)Token.integerValue().getExtValue();
784   lex();
785   return false;
786 }
787
788 bool MIParser::parseCFIRegister(unsigned &Reg) {
789   if (Token.isNot(MIToken::NamedRegister))
790     return error("expected a cfi register");
791   unsigned LLVMReg;
792   if (parseRegister(LLVMReg))
793     return true;
794   const auto *TRI = MF.getSubtarget().getRegisterInfo();
795   assert(TRI && "Expected target register info");
796   int DwarfReg = TRI->getDwarfRegNum(LLVMReg, true);
797   if (DwarfReg < 0)
798     return error("invalid DWARF register");
799   Reg = (unsigned)DwarfReg;
800   lex();
801   return false;
802 }
803
804 bool MIParser::parseCFIOperand(MachineOperand &Dest) {
805   auto Kind = Token.kind();
806   lex();
807   auto &MMI = MF.getMMI();
808   int Offset;
809   unsigned Reg;
810   unsigned CFIIndex;
811   switch (Kind) {
812   case MIToken::kw_cfi_offset:
813     if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
814         parseCFIOffset(Offset))
815       return true;
816     CFIIndex =
817         MMI.addFrameInst(MCCFIInstruction::createOffset(nullptr, Reg, Offset));
818     break;
819   case MIToken::kw_cfi_def_cfa_register:
820     if (parseCFIRegister(Reg))
821       return true;
822     CFIIndex =
823         MMI.addFrameInst(MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
824     break;
825   case MIToken::kw_cfi_def_cfa_offset:
826     if (parseCFIOffset(Offset))
827       return true;
828     // NB: MCCFIInstruction::createDefCfaOffset negates the offset.
829     CFIIndex = MMI.addFrameInst(
830         MCCFIInstruction::createDefCfaOffset(nullptr, -Offset));
831     break;
832   case MIToken::kw_cfi_def_cfa:
833     if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
834         parseCFIOffset(Offset))
835       return true;
836     // NB: MCCFIInstruction::createDefCfa negates the offset.
837     CFIIndex =
838         MMI.addFrameInst(MCCFIInstruction::createDefCfa(nullptr, Reg, -Offset));
839     break;
840   default:
841     // TODO: Parse the other CFI operands.
842     llvm_unreachable("The current token should be a cfi operand");
843   }
844   Dest = MachineOperand::CreateCFIIndex(CFIIndex);
845   return false;
846 }
847
848 bool MIParser::parseIRBlock(BasicBlock *&BB, const Function &F) {
849   switch (Token.kind()) {
850   case MIToken::NamedIRBlock: {
851     BB = dyn_cast_or_null<BasicBlock>(
852         F.getValueSymbolTable().lookup(Token.stringValue()));
853     if (!BB)
854       return error(Twine("use of undefined IR block '") + Token.range() + "'");
855     break;
856   }
857   case MIToken::IRBlock: {
858     unsigned SlotNumber = 0;
859     if (getUnsigned(SlotNumber))
860       return true;
861     BB = const_cast<BasicBlock *>(getIRBlock(SlotNumber, F));
862     if (!BB)
863       return error(Twine("use of undefined IR block '%ir-block.") +
864                    Twine(SlotNumber) + "'");
865     break;
866   }
867   default:
868     llvm_unreachable("The current token should be an IR block reference");
869   }
870   return false;
871 }
872
873 bool MIParser::parseBlockAddressOperand(MachineOperand &Dest) {
874   assert(Token.is(MIToken::kw_blockaddress));
875   lex();
876   if (expectAndConsume(MIToken::lparen))
877     return true;
878   if (Token.isNot(MIToken::GlobalValue) &&
879       Token.isNot(MIToken::NamedGlobalValue))
880     return error("expected a global value");
881   GlobalValue *GV = nullptr;
882   if (parseGlobalValue(GV))
883     return true;
884   auto *F = dyn_cast<Function>(GV);
885   if (!F)
886     return error("expected an IR function reference");
887   lex();
888   if (expectAndConsume(MIToken::comma))
889     return true;
890   BasicBlock *BB = nullptr;
891   if (Token.isNot(MIToken::IRBlock) && Token.isNot(MIToken::NamedIRBlock))
892     return error("expected an IR block reference");
893   if (parseIRBlock(BB, *F))
894     return true;
895   lex();
896   if (expectAndConsume(MIToken::rparen))
897     return true;
898   Dest = MachineOperand::CreateBA(BlockAddress::get(F, BB), /*Offset=*/0);
899   if (parseOperandsOffset(Dest))
900     return true;
901   return false;
902 }
903
904 bool MIParser::parseTargetIndexOperand(MachineOperand &Dest) {
905   assert(Token.is(MIToken::kw_target_index));
906   lex();
907   if (expectAndConsume(MIToken::lparen))
908     return true;
909   if (Token.isNot(MIToken::Identifier))
910     return error("expected the name of the target index");
911   int Index = 0;
912   if (getTargetIndex(Token.stringValue(), Index))
913     return error("use of undefined target index '" + Token.stringValue() + "'");
914   lex();
915   if (expectAndConsume(MIToken::rparen))
916     return true;
917   Dest = MachineOperand::CreateTargetIndex(unsigned(Index), /*Offset=*/0);
918   if (parseOperandsOffset(Dest))
919     return true;
920   return false;
921 }
922
923 bool MIParser::parseMachineOperand(MachineOperand &Dest) {
924   switch (Token.kind()) {
925   case MIToken::kw_implicit:
926   case MIToken::kw_implicit_define:
927   case MIToken::kw_dead:
928   case MIToken::kw_killed:
929   case MIToken::kw_undef:
930   case MIToken::kw_early_clobber:
931   case MIToken::kw_debug_use:
932   case MIToken::underscore:
933   case MIToken::NamedRegister:
934   case MIToken::VirtualRegister:
935     return parseRegisterOperand(Dest);
936   case MIToken::IntegerLiteral:
937     return parseImmediateOperand(Dest);
938   case MIToken::IntegerType:
939     return parseTypedImmediateOperand(Dest);
940   case MIToken::kw_half:
941   case MIToken::kw_float:
942   case MIToken::kw_double:
943   case MIToken::kw_x86_fp80:
944   case MIToken::kw_fp128:
945   case MIToken::kw_ppc_fp128:
946     return parseFPImmediateOperand(Dest);
947   case MIToken::MachineBasicBlock:
948     return parseMBBOperand(Dest);
949   case MIToken::StackObject:
950     return parseStackObjectOperand(Dest);
951   case MIToken::FixedStackObject:
952     return parseFixedStackObjectOperand(Dest);
953   case MIToken::GlobalValue:
954   case MIToken::NamedGlobalValue:
955     return parseGlobalAddressOperand(Dest);
956   case MIToken::ConstantPoolItem:
957     return parseConstantPoolIndexOperand(Dest);
958   case MIToken::JumpTableIndex:
959     return parseJumpTableIndexOperand(Dest);
960   case MIToken::ExternalSymbol:
961     return parseExternalSymbolOperand(Dest);
962   case MIToken::exclaim:
963     return parseMetadataOperand(Dest);
964   case MIToken::kw_cfi_offset:
965   case MIToken::kw_cfi_def_cfa_register:
966   case MIToken::kw_cfi_def_cfa_offset:
967   case MIToken::kw_cfi_def_cfa:
968     return parseCFIOperand(Dest);
969   case MIToken::kw_blockaddress:
970     return parseBlockAddressOperand(Dest);
971   case MIToken::kw_target_index:
972     return parseTargetIndexOperand(Dest);
973   case MIToken::Error:
974     return true;
975   case MIToken::Identifier:
976     if (const auto *RegMask = getRegMask(Token.stringValue())) {
977       Dest = MachineOperand::CreateRegMask(RegMask);
978       lex();
979       break;
980     }
981   // fallthrough
982   default:
983     // TODO: parse the other machine operands.
984     return error("expected a machine operand");
985   }
986   return false;
987 }
988
989 bool MIParser::parseMachineOperandAndTargetFlags(MachineOperand &Dest) {
990   unsigned TF = 0;
991   bool HasTargetFlags = false;
992   if (Token.is(MIToken::kw_target_flags)) {
993     HasTargetFlags = true;
994     lex();
995     if (expectAndConsume(MIToken::lparen))
996       return true;
997     if (Token.isNot(MIToken::Identifier))
998       return error("expected the name of the target flag");
999     if (getDirectTargetFlag(Token.stringValue(), TF))
1000       return error("use of undefined target flag '" + Token.stringValue() +
1001                    "'");
1002     lex();
1003     // TODO: Parse target's bit target flags.
1004     if (expectAndConsume(MIToken::rparen))
1005       return true;
1006   }
1007   auto Loc = Token.location();
1008   if (parseMachineOperand(Dest))
1009     return true;
1010   if (!HasTargetFlags)
1011     return false;
1012   if (Dest.isReg())
1013     return error(Loc, "register operands can't have target flags");
1014   Dest.setTargetFlags(TF);
1015   return false;
1016 }
1017
1018 bool MIParser::parseOffset(int64_t &Offset) {
1019   if (Token.isNot(MIToken::plus) && Token.isNot(MIToken::minus))
1020     return false;
1021   StringRef Sign = Token.range();
1022   bool IsNegative = Token.is(MIToken::minus);
1023   lex();
1024   if (Token.isNot(MIToken::IntegerLiteral))
1025     return error("expected an integer literal after '" + Sign + "'");
1026   if (Token.integerValue().getMinSignedBits() > 64)
1027     return error("expected 64-bit integer (too large)");
1028   Offset = Token.integerValue().getExtValue();
1029   if (IsNegative)
1030     Offset = -Offset;
1031   lex();
1032   return false;
1033 }
1034
1035 bool MIParser::parseOperandsOffset(MachineOperand &Op) {
1036   int64_t Offset = 0;
1037   if (parseOffset(Offset))
1038     return true;
1039   Op.setOffset(Offset);
1040   return false;
1041 }
1042
1043 bool MIParser::parseIRValue(Value *&V) {
1044   switch (Token.kind()) {
1045   case MIToken::NamedIRValue: {
1046     V = MF.getFunction()->getValueSymbolTable().lookup(Token.stringValue());
1047     if (!V)
1048       return error(Twine("use of undefined IR value '") + Token.range() + "'");
1049     break;
1050   }
1051   // TODO: Parse unnamed IR value references.
1052   default:
1053     llvm_unreachable("The current token should be an IR block reference");
1054   }
1055   return false;
1056 }
1057
1058 bool MIParser::getUint64(uint64_t &Result) {
1059   assert(Token.hasIntegerValue());
1060   if (Token.integerValue().getActiveBits() > 64)
1061     return error("expected 64-bit integer (too large)");
1062   Result = Token.integerValue().getZExtValue();
1063   return false;
1064 }
1065
1066 bool MIParser::parseMemoryOperandFlag(unsigned &Flags) {
1067   const unsigned OldFlags = Flags;
1068   switch (Token.kind()) {
1069   case MIToken::kw_volatile:
1070     Flags |= MachineMemOperand::MOVolatile;
1071     break;
1072   case MIToken::kw_non_temporal:
1073     Flags |= MachineMemOperand::MONonTemporal;
1074     break;
1075   case MIToken::kw_invariant:
1076     Flags |= MachineMemOperand::MOInvariant;
1077     break;
1078   // TODO: parse the target specific memory operand flags.
1079   default:
1080     llvm_unreachable("The current token should be a memory operand flag");
1081   }
1082   if (OldFlags == Flags)
1083     // We know that the same flag is specified more than once when the flags
1084     // weren't modified.
1085     return error("duplicate '" + Token.stringValue() + "' memory operand flag");
1086   lex();
1087   return false;
1088 }
1089
1090 bool MIParser::parseMachineMemoryOperand(MachineMemOperand *&Dest) {
1091   if (expectAndConsume(MIToken::lparen))
1092     return true;
1093   unsigned Flags = 0;
1094   while (Token.isMemoryOperandFlag()) {
1095     if (parseMemoryOperandFlag(Flags))
1096       return true;
1097   }
1098   if (Token.isNot(MIToken::Identifier) ||
1099       (Token.stringValue() != "load" && Token.stringValue() != "store"))
1100     return error("expected 'load' or 'store' memory operation");
1101   if (Token.stringValue() == "load")
1102     Flags |= MachineMemOperand::MOLoad;
1103   else
1104     Flags |= MachineMemOperand::MOStore;
1105   lex();
1106
1107   if (Token.isNot(MIToken::IntegerLiteral))
1108     return error("expected the size integer literal after memory operation");
1109   uint64_t Size;
1110   if (getUint64(Size))
1111     return true;
1112   lex();
1113
1114   const char *Word = Flags & MachineMemOperand::MOLoad ? "from" : "into";
1115   if (Token.isNot(MIToken::Identifier) || Token.stringValue() != Word)
1116     return error(Twine("expected '") + Word + "'");
1117   lex();
1118
1119   // TODO: Parse pseudo source values.
1120   if (Token.isNot(MIToken::NamedIRValue))
1121     return error("expected an IR value reference");
1122   Value *V = nullptr;
1123   if (parseIRValue(V))
1124     return true;
1125   if (!V->getType()->isPointerTy())
1126     return error("expected a pointer IR value");
1127   lex();
1128   // TODO: Parse the base alignment.
1129   // TODO: Parse the attached metadata nodes.
1130   if (expectAndConsume(MIToken::rparen))
1131     return true;
1132
1133   Dest = MF.getMachineMemOperand(MachinePointerInfo(V), Flags, Size, Size);
1134   return false;
1135 }
1136
1137 void MIParser::initNames2InstrOpCodes() {
1138   if (!Names2InstrOpCodes.empty())
1139     return;
1140   const auto *TII = MF.getSubtarget().getInstrInfo();
1141   assert(TII && "Expected target instruction info");
1142   for (unsigned I = 0, E = TII->getNumOpcodes(); I < E; ++I)
1143     Names2InstrOpCodes.insert(std::make_pair(StringRef(TII->getName(I)), I));
1144 }
1145
1146 bool MIParser::parseInstrName(StringRef InstrName, unsigned &OpCode) {
1147   initNames2InstrOpCodes();
1148   auto InstrInfo = Names2InstrOpCodes.find(InstrName);
1149   if (InstrInfo == Names2InstrOpCodes.end())
1150     return true;
1151   OpCode = InstrInfo->getValue();
1152   return false;
1153 }
1154
1155 void MIParser::initNames2Regs() {
1156   if (!Names2Regs.empty())
1157     return;
1158   // The '%noreg' register is the register 0.
1159   Names2Regs.insert(std::make_pair("noreg", 0));
1160   const auto *TRI = MF.getSubtarget().getRegisterInfo();
1161   assert(TRI && "Expected target register info");
1162   for (unsigned I = 0, E = TRI->getNumRegs(); I < E; ++I) {
1163     bool WasInserted =
1164         Names2Regs.insert(std::make_pair(StringRef(TRI->getName(I)).lower(), I))
1165             .second;
1166     (void)WasInserted;
1167     assert(WasInserted && "Expected registers to be unique case-insensitively");
1168   }
1169 }
1170
1171 bool MIParser::getRegisterByName(StringRef RegName, unsigned &Reg) {
1172   initNames2Regs();
1173   auto RegInfo = Names2Regs.find(RegName);
1174   if (RegInfo == Names2Regs.end())
1175     return true;
1176   Reg = RegInfo->getValue();
1177   return false;
1178 }
1179
1180 void MIParser::initNames2RegMasks() {
1181   if (!Names2RegMasks.empty())
1182     return;
1183   const auto *TRI = MF.getSubtarget().getRegisterInfo();
1184   assert(TRI && "Expected target register info");
1185   ArrayRef<const uint32_t *> RegMasks = TRI->getRegMasks();
1186   ArrayRef<const char *> RegMaskNames = TRI->getRegMaskNames();
1187   assert(RegMasks.size() == RegMaskNames.size());
1188   for (size_t I = 0, E = RegMasks.size(); I < E; ++I)
1189     Names2RegMasks.insert(
1190         std::make_pair(StringRef(RegMaskNames[I]).lower(), RegMasks[I]));
1191 }
1192
1193 const uint32_t *MIParser::getRegMask(StringRef Identifier) {
1194   initNames2RegMasks();
1195   auto RegMaskInfo = Names2RegMasks.find(Identifier);
1196   if (RegMaskInfo == Names2RegMasks.end())
1197     return nullptr;
1198   return RegMaskInfo->getValue();
1199 }
1200
1201 void MIParser::initNames2SubRegIndices() {
1202   if (!Names2SubRegIndices.empty())
1203     return;
1204   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1205   for (unsigned I = 1, E = TRI->getNumSubRegIndices(); I < E; ++I)
1206     Names2SubRegIndices.insert(
1207         std::make_pair(StringRef(TRI->getSubRegIndexName(I)).lower(), I));
1208 }
1209
1210 unsigned MIParser::getSubRegIndex(StringRef Name) {
1211   initNames2SubRegIndices();
1212   auto SubRegInfo = Names2SubRegIndices.find(Name);
1213   if (SubRegInfo == Names2SubRegIndices.end())
1214     return 0;
1215   return SubRegInfo->getValue();
1216 }
1217
1218 static void initSlots2BasicBlocks(
1219     const Function &F,
1220     DenseMap<unsigned, const BasicBlock *> &Slots2BasicBlocks) {
1221   ModuleSlotTracker MST(F.getParent(), /*ShouldInitializeAllMetadata=*/false);
1222   MST.incorporateFunction(F);
1223   for (auto &BB : F) {
1224     if (BB.hasName())
1225       continue;
1226     int Slot = MST.getLocalSlot(&BB);
1227     if (Slot == -1)
1228       continue;
1229     Slots2BasicBlocks.insert(std::make_pair(unsigned(Slot), &BB));
1230   }
1231 }
1232
1233 static const BasicBlock *getIRBlockFromSlot(
1234     unsigned Slot,
1235     const DenseMap<unsigned, const BasicBlock *> &Slots2BasicBlocks) {
1236   auto BlockInfo = Slots2BasicBlocks.find(Slot);
1237   if (BlockInfo == Slots2BasicBlocks.end())
1238     return nullptr;
1239   return BlockInfo->second;
1240 }
1241
1242 const BasicBlock *MIParser::getIRBlock(unsigned Slot) {
1243   if (Slots2BasicBlocks.empty())
1244     initSlots2BasicBlocks(*MF.getFunction(), Slots2BasicBlocks);
1245   return getIRBlockFromSlot(Slot, Slots2BasicBlocks);
1246 }
1247
1248 const BasicBlock *MIParser::getIRBlock(unsigned Slot, const Function &F) {
1249   if (&F == MF.getFunction())
1250     return getIRBlock(Slot);
1251   DenseMap<unsigned, const BasicBlock *> CustomSlots2BasicBlocks;
1252   initSlots2BasicBlocks(F, CustomSlots2BasicBlocks);
1253   return getIRBlockFromSlot(Slot, CustomSlots2BasicBlocks);
1254 }
1255
1256 void MIParser::initNames2TargetIndices() {
1257   if (!Names2TargetIndices.empty())
1258     return;
1259   const auto *TII = MF.getSubtarget().getInstrInfo();
1260   assert(TII && "Expected target instruction info");
1261   auto Indices = TII->getSerializableTargetIndices();
1262   for (const auto &I : Indices)
1263     Names2TargetIndices.insert(std::make_pair(StringRef(I.second), I.first));
1264 }
1265
1266 bool MIParser::getTargetIndex(StringRef Name, int &Index) {
1267   initNames2TargetIndices();
1268   auto IndexInfo = Names2TargetIndices.find(Name);
1269   if (IndexInfo == Names2TargetIndices.end())
1270     return true;
1271   Index = IndexInfo->second;
1272   return false;
1273 }
1274
1275 void MIParser::initNames2DirectTargetFlags() {
1276   if (!Names2DirectTargetFlags.empty())
1277     return;
1278   const auto *TII = MF.getSubtarget().getInstrInfo();
1279   assert(TII && "Expected target instruction info");
1280   auto Flags = TII->getSerializableDirectMachineOperandTargetFlags();
1281   for (const auto &I : Flags)
1282     Names2DirectTargetFlags.insert(
1283         std::make_pair(StringRef(I.second), I.first));
1284 }
1285
1286 bool MIParser::getDirectTargetFlag(StringRef Name, unsigned &Flag) {
1287   initNames2DirectTargetFlags();
1288   auto FlagInfo = Names2DirectTargetFlags.find(Name);
1289   if (FlagInfo == Names2DirectTargetFlags.end())
1290     return true;
1291   Flag = FlagInfo->second;
1292   return false;
1293 }
1294
1295 bool llvm::parseMachineInstr(MachineInstr *&MI, SourceMgr &SM,
1296                              MachineFunction &MF, StringRef Src,
1297                              const PerFunctionMIParsingState &PFS,
1298                              const SlotMapping &IRSlots, SMDiagnostic &Error) {
1299   return MIParser(SM, MF, Error, Src, PFS, IRSlots).parse(MI);
1300 }
1301
1302 bool llvm::parseMBBReference(MachineBasicBlock *&MBB, SourceMgr &SM,
1303                              MachineFunction &MF, StringRef Src,
1304                              const PerFunctionMIParsingState &PFS,
1305                              const SlotMapping &IRSlots, SMDiagnostic &Error) {
1306   return MIParser(SM, MF, Error, Src, PFS, IRSlots).parseStandaloneMBB(MBB);
1307 }
1308
1309 bool llvm::parseNamedRegisterReference(unsigned &Reg, SourceMgr &SM,
1310                                        MachineFunction &MF, StringRef Src,
1311                                        const PerFunctionMIParsingState &PFS,
1312                                        const SlotMapping &IRSlots,
1313                                        SMDiagnostic &Error) {
1314   return MIParser(SM, MF, Error, Src, PFS, IRSlots)
1315       .parseStandaloneNamedRegister(Reg);
1316 }
1317
1318 bool llvm::parseVirtualRegisterReference(unsigned &Reg, SourceMgr &SM,
1319                                          MachineFunction &MF, StringRef Src,
1320                                          const PerFunctionMIParsingState &PFS,
1321                                          const SlotMapping &IRSlots,
1322                                          SMDiagnostic &Error) {
1323   return MIParser(SM, MF, Error, Src, PFS, IRSlots)
1324       .parseStandaloneVirtualRegister(Reg);
1325 }
1326
1327 bool llvm::parseIRBlockReference(const BasicBlock *&BB, SourceMgr &SM,
1328                                  MachineFunction &MF, StringRef Src,
1329                                  const PerFunctionMIParsingState &PFS,
1330                                  const SlotMapping &IRSlots,
1331                                  SMDiagnostic &Error) {
1332   return MIParser(SM, MF, Error, Src, PFS, IRSlots)
1333       .parseStandaloneIRBlockReference(BB);
1334 }