MIRParser: Split the 'parseIRConstant' method into two methods. 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 and other attributes.
42 struct ParsedMachineOperand {
43   MachineOperand Operand;
44   StringRef::iterator Begin;
45   StringRef::iterator End;
46   Optional<unsigned> TiedDefIdx;
47
48   ParsedMachineOperand(const MachineOperand &Operand, StringRef::iterator Begin,
49                        StringRef::iterator End, Optional<unsigned> &TiedDefIdx)
50       : Operand(Operand), Begin(Begin), End(End), TiedDefIdx(TiedDefIdx) {
51     if (TiedDefIdx)
52       assert(Operand.isReg() && Operand.isUse() &&
53              "Only used register operands can be tied");
54   }
55 };
56
57 class MIParser {
58   SourceMgr &SM;
59   MachineFunction &MF;
60   SMDiagnostic &Error;
61   StringRef Source, CurrentSource;
62   MIToken Token;
63   const PerFunctionMIParsingState &PFS;
64   /// Maps from indices to unnamed global values and metadata nodes.
65   const SlotMapping &IRSlots;
66   /// Maps from instruction names to op codes.
67   StringMap<unsigned> Names2InstrOpCodes;
68   /// Maps from register names to registers.
69   StringMap<unsigned> Names2Regs;
70   /// Maps from register mask names to register masks.
71   StringMap<const uint32_t *> Names2RegMasks;
72   /// Maps from subregister names to subregister indices.
73   StringMap<unsigned> Names2SubRegIndices;
74   /// Maps from slot numbers to function's unnamed basic blocks.
75   DenseMap<unsigned, const BasicBlock *> Slots2BasicBlocks;
76   /// Maps from slot numbers to function's unnamed values.
77   DenseMap<unsigned, const Value *> Slots2Values;
78   /// Maps from target index names to target indices.
79   StringMap<int> Names2TargetIndices;
80   /// Maps from direct target flag names to the direct target flag values.
81   StringMap<unsigned> Names2DirectTargetFlags;
82   /// Maps from direct target flag names to the bitmask target flag values.
83   StringMap<unsigned> Names2BitmaskTargetFlags;
84
85 public:
86   MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
87            StringRef Source, const PerFunctionMIParsingState &PFS,
88            const SlotMapping &IRSlots);
89
90   void lex();
91
92   /// Report an error at the current location with the given message.
93   ///
94   /// This function always return true.
95   bool error(const Twine &Msg);
96
97   /// Report an error at the given location with the given message.
98   ///
99   /// This function always return true.
100   bool error(StringRef::iterator Loc, const Twine &Msg);
101
102   bool
103   parseBasicBlockDefinitions(DenseMap<unsigned, MachineBasicBlock *> &MBBSlots);
104   bool parseBasicBlocks();
105   bool parse(MachineInstr *&MI);
106   bool parseStandaloneMBB(MachineBasicBlock *&MBB);
107   bool parseStandaloneNamedRegister(unsigned &Reg);
108   bool parseStandaloneVirtualRegister(unsigned &Reg);
109   bool parseStandaloneStackObject(int &FI);
110   bool parseStandaloneMDNode(MDNode *&Node);
111
112   bool
113   parseBasicBlockDefinition(DenseMap<unsigned, MachineBasicBlock *> &MBBSlots);
114   bool parseBasicBlock(MachineBasicBlock &MBB);
115   bool parseBasicBlockLiveins(MachineBasicBlock &MBB);
116   bool parseBasicBlockSuccessors(MachineBasicBlock &MBB);
117
118   bool parseRegister(unsigned &Reg);
119   bool parseRegisterFlag(unsigned &Flags);
120   bool parseSubRegisterIndex(unsigned &SubReg);
121   bool parseRegisterTiedDefIndex(unsigned &TiedDefIdx);
122   bool parseRegisterOperand(MachineOperand &Dest,
123                             Optional<unsigned> &TiedDefIdx, bool IsDef = false);
124   bool parseImmediateOperand(MachineOperand &Dest);
125   bool parseIRConstant(StringRef::iterator Loc, StringRef Source,
126                        const Constant *&C);
127   bool parseIRConstant(StringRef::iterator Loc, const Constant *&C);
128   bool parseTypedImmediateOperand(MachineOperand &Dest);
129   bool parseFPImmediateOperand(MachineOperand &Dest);
130   bool parseMBBReference(MachineBasicBlock *&MBB);
131   bool parseMBBOperand(MachineOperand &Dest);
132   bool parseStackFrameIndex(int &FI);
133   bool parseStackObjectOperand(MachineOperand &Dest);
134   bool parseFixedStackFrameIndex(int &FI);
135   bool parseFixedStackObjectOperand(MachineOperand &Dest);
136   bool parseGlobalValue(GlobalValue *&GV);
137   bool parseGlobalAddressOperand(MachineOperand &Dest);
138   bool parseConstantPoolIndexOperand(MachineOperand &Dest);
139   bool parseJumpTableIndexOperand(MachineOperand &Dest);
140   bool parseExternalSymbolOperand(MachineOperand &Dest);
141   bool parseMDNode(MDNode *&Node);
142   bool parseMetadataOperand(MachineOperand &Dest);
143   bool parseCFIOffset(int &Offset);
144   bool parseCFIRegister(unsigned &Reg);
145   bool parseCFIOperand(MachineOperand &Dest);
146   bool parseIRBlock(BasicBlock *&BB, const Function &F);
147   bool parseBlockAddressOperand(MachineOperand &Dest);
148   bool parseTargetIndexOperand(MachineOperand &Dest);
149   bool parseLiveoutRegisterMaskOperand(MachineOperand &Dest);
150   bool parseMachineOperand(MachineOperand &Dest,
151                            Optional<unsigned> &TiedDefIdx);
152   bool parseMachineOperandAndTargetFlags(MachineOperand &Dest,
153                                          Optional<unsigned> &TiedDefIdx);
154   bool parseOffset(int64_t &Offset);
155   bool parseAlignment(unsigned &Alignment);
156   bool parseOperandsOffset(MachineOperand &Op);
157   bool parseIRValue(const Value *&V);
158   bool parseMemoryOperandFlag(unsigned &Flags);
159   bool parseMemoryPseudoSourceValue(const PseudoSourceValue *&PSV);
160   bool parseMachinePointerInfo(MachinePointerInfo &Dest);
161   bool parseMachineMemoryOperand(MachineMemOperand *&Dest);
162
163 private:
164   /// Convert the integer literal in the current token into an unsigned integer.
165   ///
166   /// Return true if an error occurred.
167   bool getUnsigned(unsigned &Result);
168
169   /// Convert the integer literal in the current token into an uint64.
170   ///
171   /// Return true if an error occurred.
172   bool getUint64(uint64_t &Result);
173
174   /// If the current token is of the given kind, consume it and return false.
175   /// Otherwise report an error and return true.
176   bool expectAndConsume(MIToken::TokenKind TokenKind);
177
178   /// If the current token is of the given kind, consume it and return true.
179   /// Otherwise return false.
180   bool consumeIfPresent(MIToken::TokenKind TokenKind);
181
182   void initNames2InstrOpCodes();
183
184   /// Try to convert an instruction name to an opcode. Return true if the
185   /// instruction name is invalid.
186   bool parseInstrName(StringRef InstrName, unsigned &OpCode);
187
188   bool parseInstruction(unsigned &OpCode, unsigned &Flags);
189
190   bool assignRegisterTies(MachineInstr &MI,
191                           ArrayRef<ParsedMachineOperand> Operands);
192
193   bool verifyImplicitOperands(ArrayRef<ParsedMachineOperand> Operands,
194                               const MCInstrDesc &MCID);
195
196   void initNames2Regs();
197
198   /// Try to convert a register name to a register number. Return true if the
199   /// register name is invalid.
200   bool getRegisterByName(StringRef RegName, unsigned &Reg);
201
202   void initNames2RegMasks();
203
204   /// Check if the given identifier is a name of a register mask.
205   ///
206   /// Return null if the identifier isn't a register mask.
207   const uint32_t *getRegMask(StringRef Identifier);
208
209   void initNames2SubRegIndices();
210
211   /// Check if the given identifier is a name of a subregister index.
212   ///
213   /// Return 0 if the name isn't a subregister index class.
214   unsigned getSubRegIndex(StringRef Name);
215
216   const BasicBlock *getIRBlock(unsigned Slot);
217   const BasicBlock *getIRBlock(unsigned Slot, const Function &F);
218
219   const Value *getIRValue(unsigned Slot);
220
221   void initNames2TargetIndices();
222
223   /// Try to convert a name of target index to the corresponding target index.
224   ///
225   /// Return true if the name isn't a name of a target index.
226   bool getTargetIndex(StringRef Name, int &Index);
227
228   void initNames2DirectTargetFlags();
229
230   /// Try to convert a name of a direct target flag to the corresponding
231   /// target flag.
232   ///
233   /// Return true if the name isn't a name of a direct flag.
234   bool getDirectTargetFlag(StringRef Name, unsigned &Flag);
235
236   void initNames2BitmaskTargetFlags();
237
238   /// Try to convert a name of a bitmask target flag to the corresponding
239   /// target flag.
240   ///
241   /// Return true if the name isn't a name of a bitmask target flag.
242   bool getBitmaskTargetFlag(StringRef Name, unsigned &Flag);
243 };
244
245 } // end anonymous namespace
246
247 MIParser::MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
248                    StringRef Source, const PerFunctionMIParsingState &PFS,
249                    const SlotMapping &IRSlots)
250     : SM(SM), MF(MF), Error(Error), Source(Source), CurrentSource(Source),
251       PFS(PFS), IRSlots(IRSlots) {}
252
253 void MIParser::lex() {
254   CurrentSource = lexMIToken(
255       CurrentSource, Token,
256       [this](StringRef::iterator Loc, const Twine &Msg) { error(Loc, Msg); });
257 }
258
259 bool MIParser::error(const Twine &Msg) { return error(Token.location(), Msg); }
260
261 bool MIParser::error(StringRef::iterator Loc, const Twine &Msg) {
262   assert(Loc >= Source.data() && Loc <= (Source.data() + Source.size()));
263   const MemoryBuffer &Buffer = *SM.getMemoryBuffer(SM.getMainFileID());
264   if (Loc >= Buffer.getBufferStart() && Loc <= Buffer.getBufferEnd()) {
265     // Create an ordinary diagnostic when the source manager's buffer is the
266     // source string.
267     Error = SM.GetMessage(SMLoc::getFromPointer(Loc), SourceMgr::DK_Error, Msg);
268     return true;
269   }
270   // Create a diagnostic for a YAML string literal.
271   Error = SMDiagnostic(SM, SMLoc(), Buffer.getBufferIdentifier(), 1,
272                        Loc - Source.data(), SourceMgr::DK_Error, Msg.str(),
273                        Source, None, None);
274   return true;
275 }
276
277 static const char *toString(MIToken::TokenKind TokenKind) {
278   switch (TokenKind) {
279   case MIToken::comma:
280     return "','";
281   case MIToken::equal:
282     return "'='";
283   case MIToken::colon:
284     return "':'";
285   case MIToken::lparen:
286     return "'('";
287   case MIToken::rparen:
288     return "')'";
289   default:
290     return "<unknown token>";
291   }
292 }
293
294 bool MIParser::expectAndConsume(MIToken::TokenKind TokenKind) {
295   if (Token.isNot(TokenKind))
296     return error(Twine("expected ") + toString(TokenKind));
297   lex();
298   return false;
299 }
300
301 bool MIParser::consumeIfPresent(MIToken::TokenKind TokenKind) {
302   if (Token.isNot(TokenKind))
303     return false;
304   lex();
305   return true;
306 }
307
308 bool MIParser::parseBasicBlockDefinition(
309     DenseMap<unsigned, MachineBasicBlock *> &MBBSlots) {
310   assert(Token.is(MIToken::MachineBasicBlockLabel));
311   unsigned ID = 0;
312   if (getUnsigned(ID))
313     return true;
314   auto Loc = Token.location();
315   auto Name = Token.stringValue();
316   lex();
317   bool HasAddressTaken = false;
318   bool IsLandingPad = false;
319   unsigned Alignment = 0;
320   BasicBlock *BB = nullptr;
321   if (consumeIfPresent(MIToken::lparen)) {
322     do {
323       // TODO: Report an error when multiple same attributes are specified.
324       switch (Token.kind()) {
325       case MIToken::kw_address_taken:
326         HasAddressTaken = true;
327         lex();
328         break;
329       case MIToken::kw_landing_pad:
330         IsLandingPad = true;
331         lex();
332         break;
333       case MIToken::kw_align:
334         if (parseAlignment(Alignment))
335           return true;
336         break;
337       case MIToken::IRBlock:
338         // TODO: Report an error when both name and ir block are specified.
339         if (parseIRBlock(BB, *MF.getFunction()))
340           return true;
341         lex();
342         break;
343       default:
344         break;
345       }
346     } while (consumeIfPresent(MIToken::comma));
347     if (expectAndConsume(MIToken::rparen))
348       return true;
349   }
350   if (expectAndConsume(MIToken::colon))
351     return true;
352
353   if (!Name.empty()) {
354     BB = dyn_cast_or_null<BasicBlock>(
355         MF.getFunction()->getValueSymbolTable().lookup(Name));
356     if (!BB)
357       return error(Loc, Twine("basic block '") + Name +
358                             "' is not defined in the function '" +
359                             MF.getName() + "'");
360   }
361   auto *MBB = MF.CreateMachineBasicBlock(BB);
362   MF.insert(MF.end(), MBB);
363   bool WasInserted = MBBSlots.insert(std::make_pair(ID, MBB)).second;
364   if (!WasInserted)
365     return error(Loc, Twine("redefinition of machine basic block with id #") +
366                           Twine(ID));
367   if (Alignment)
368     MBB->setAlignment(Alignment);
369   if (HasAddressTaken)
370     MBB->setHasAddressTaken();
371   MBB->setIsLandingPad(IsLandingPad);
372   return false;
373 }
374
375 bool MIParser::parseBasicBlockDefinitions(
376     DenseMap<unsigned, MachineBasicBlock *> &MBBSlots) {
377   lex();
378   // Skip until the first machine basic block.
379   while (Token.is(MIToken::Newline))
380     lex();
381   if (Token.isErrorOrEOF())
382     return Token.isError();
383   if (Token.isNot(MIToken::MachineBasicBlockLabel))
384     return error("expected a basic block definition before instructions");
385   unsigned BraceDepth = 0;
386   do {
387     if (parseBasicBlockDefinition(MBBSlots))
388       return true;
389     bool IsAfterNewline = false;
390     // Skip until the next machine basic block.
391     while (true) {
392       if ((Token.is(MIToken::MachineBasicBlockLabel) && IsAfterNewline) ||
393           Token.isErrorOrEOF())
394         break;
395       else if (Token.is(MIToken::MachineBasicBlockLabel))
396         return error("basic block definition should be located at the start of "
397                      "the line");
398       else if (consumeIfPresent(MIToken::Newline)) {
399         IsAfterNewline = true;
400         continue;
401       }
402       IsAfterNewline = false;
403       if (Token.is(MIToken::lbrace))
404         ++BraceDepth;
405       if (Token.is(MIToken::rbrace)) {
406         if (!BraceDepth)
407           return error("extraneous closing brace ('}')");
408         --BraceDepth;
409       }
410       lex();
411     }
412     // Verify that we closed all of the '{' at the end of a file or a block.
413     if (!Token.isError() && BraceDepth)
414       return error("expected '}'"); // FIXME: Report a note that shows '{'.
415   } while (!Token.isErrorOrEOF());
416   return Token.isError();
417 }
418
419 bool MIParser::parseBasicBlockLiveins(MachineBasicBlock &MBB) {
420   assert(Token.is(MIToken::kw_liveins));
421   lex();
422   if (expectAndConsume(MIToken::colon))
423     return true;
424   if (Token.isNewlineOrEOF()) // Allow an empty list of liveins.
425     return false;
426   do {
427     if (Token.isNot(MIToken::NamedRegister))
428       return error("expected a named register");
429     unsigned Reg = 0;
430     if (parseRegister(Reg))
431       return true;
432     MBB.addLiveIn(Reg);
433     lex();
434   } while (consumeIfPresent(MIToken::comma));
435   return false;
436 }
437
438 bool MIParser::parseBasicBlockSuccessors(MachineBasicBlock &MBB) {
439   assert(Token.is(MIToken::kw_successors));
440   lex();
441   if (expectAndConsume(MIToken::colon))
442     return true;
443   if (Token.isNewlineOrEOF()) // Allow an empty list of successors.
444     return false;
445   do {
446     if (Token.isNot(MIToken::MachineBasicBlock))
447       return error("expected a machine basic block reference");
448     MachineBasicBlock *SuccMBB = nullptr;
449     if (parseMBBReference(SuccMBB))
450       return true;
451     lex();
452     unsigned Weight = 0;
453     if (consumeIfPresent(MIToken::lparen)) {
454       if (Token.isNot(MIToken::IntegerLiteral))
455         return error("expected an integer literal after '('");
456       if (getUnsigned(Weight))
457         return true;
458       lex();
459       if (expectAndConsume(MIToken::rparen))
460         return true;
461     }
462     MBB.addSuccessor(SuccMBB, Weight);
463   } while (consumeIfPresent(MIToken::comma));
464   return false;
465 }
466
467 bool MIParser::parseBasicBlock(MachineBasicBlock &MBB) {
468   // Skip the definition.
469   assert(Token.is(MIToken::MachineBasicBlockLabel));
470   lex();
471   if (consumeIfPresent(MIToken::lparen)) {
472     while (Token.isNot(MIToken::rparen) && !Token.isErrorOrEOF())
473       lex();
474     consumeIfPresent(MIToken::rparen);
475   }
476   consumeIfPresent(MIToken::colon);
477
478   // Parse the liveins and successors.
479   // N.B: Multiple lists of successors and liveins are allowed and they're
480   // merged into one.
481   // Example:
482   //   liveins: %edi
483   //   liveins: %esi
484   //
485   // is equivalent to
486   //   liveins: %edi, %esi
487   while (true) {
488     if (Token.is(MIToken::kw_successors)) {
489       if (parseBasicBlockSuccessors(MBB))
490         return true;
491     } else if (Token.is(MIToken::kw_liveins)) {
492       if (parseBasicBlockLiveins(MBB))
493         return true;
494     } else if (consumeIfPresent(MIToken::Newline)) {
495       continue;
496     } else
497       break;
498     if (!Token.isNewlineOrEOF())
499       return error("expected line break at the end of a list");
500     lex();
501   }
502
503   // Parse the instructions.
504   bool IsInBundle = false;
505   MachineInstr *PrevMI = nullptr;
506   while (true) {
507     if (Token.is(MIToken::MachineBasicBlockLabel) || Token.is(MIToken::Eof))
508       return false;
509     else if (consumeIfPresent(MIToken::Newline))
510       continue;
511     if (consumeIfPresent(MIToken::rbrace)) {
512       // The first parsing pass should verify that all closing '}' have an
513       // opening '{'.
514       assert(IsInBundle);
515       IsInBundle = false;
516       continue;
517     }
518     MachineInstr *MI = nullptr;
519     if (parse(MI))
520       return true;
521     MBB.insert(MBB.end(), MI);
522     if (IsInBundle) {
523       PrevMI->setFlag(MachineInstr::BundledSucc);
524       MI->setFlag(MachineInstr::BundledPred);
525     }
526     PrevMI = MI;
527     if (Token.is(MIToken::lbrace)) {
528       if (IsInBundle)
529         return error("nested instruction bundles are not allowed");
530       lex();
531       // This instruction is the start of the bundle.
532       MI->setFlag(MachineInstr::BundledSucc);
533       IsInBundle = true;
534       if (!Token.is(MIToken::Newline))
535         // The next instruction can be on the same line.
536         continue;
537     }
538     assert(Token.isNewlineOrEOF() && "MI is not fully parsed");
539     lex();
540   }
541   return false;
542 }
543
544 bool MIParser::parseBasicBlocks() {
545   lex();
546   // Skip until the first machine basic block.
547   while (Token.is(MIToken::Newline))
548     lex();
549   if (Token.isErrorOrEOF())
550     return Token.isError();
551   // The first parsing pass should have verified that this token is a MBB label
552   // in the 'parseBasicBlockDefinitions' method.
553   assert(Token.is(MIToken::MachineBasicBlockLabel));
554   do {
555     MachineBasicBlock *MBB = nullptr;
556     if (parseMBBReference(MBB))
557       return true;
558     if (parseBasicBlock(*MBB))
559       return true;
560     // The method 'parseBasicBlock' should parse the whole block until the next
561     // block or the end of file.
562     assert(Token.is(MIToken::MachineBasicBlockLabel) || Token.is(MIToken::Eof));
563   } while (Token.isNot(MIToken::Eof));
564   return false;
565 }
566
567 bool MIParser::parse(MachineInstr *&MI) {
568   // Parse any register operands before '='
569   MachineOperand MO = MachineOperand::CreateImm(0);
570   SmallVector<ParsedMachineOperand, 8> Operands;
571   while (Token.isRegister() || Token.isRegisterFlag()) {
572     auto Loc = Token.location();
573     Optional<unsigned> TiedDefIdx;
574     if (parseRegisterOperand(MO, TiedDefIdx, /*IsDef=*/true))
575       return true;
576     Operands.push_back(
577         ParsedMachineOperand(MO, Loc, Token.location(), TiedDefIdx));
578     if (Token.isNot(MIToken::comma))
579       break;
580     lex();
581   }
582   if (!Operands.empty() && expectAndConsume(MIToken::equal))
583     return true;
584
585   unsigned OpCode, Flags = 0;
586   if (Token.isError() || parseInstruction(OpCode, Flags))
587     return true;
588
589   // Parse the remaining machine operands.
590   while (!Token.isNewlineOrEOF() && Token.isNot(MIToken::kw_debug_location) &&
591          Token.isNot(MIToken::coloncolon) && Token.isNot(MIToken::lbrace)) {
592     auto Loc = Token.location();
593     Optional<unsigned> TiedDefIdx;
594     if (parseMachineOperandAndTargetFlags(MO, TiedDefIdx))
595       return true;
596     Operands.push_back(
597         ParsedMachineOperand(MO, Loc, Token.location(), TiedDefIdx));
598     if (Token.isNewlineOrEOF() || Token.is(MIToken::coloncolon) ||
599         Token.is(MIToken::lbrace))
600       break;
601     if (Token.isNot(MIToken::comma))
602       return error("expected ',' before the next machine operand");
603     lex();
604   }
605
606   DebugLoc DebugLocation;
607   if (Token.is(MIToken::kw_debug_location)) {
608     lex();
609     if (Token.isNot(MIToken::exclaim))
610       return error("expected a metadata node after 'debug-location'");
611     MDNode *Node = nullptr;
612     if (parseMDNode(Node))
613       return true;
614     DebugLocation = DebugLoc(Node);
615   }
616
617   // Parse the machine memory operands.
618   SmallVector<MachineMemOperand *, 2> MemOperands;
619   if (Token.is(MIToken::coloncolon)) {
620     lex();
621     while (!Token.isNewlineOrEOF()) {
622       MachineMemOperand *MemOp = nullptr;
623       if (parseMachineMemoryOperand(MemOp))
624         return true;
625       MemOperands.push_back(MemOp);
626       if (Token.isNewlineOrEOF())
627         break;
628       if (Token.isNot(MIToken::comma))
629         return error("expected ',' before the next machine memory operand");
630       lex();
631     }
632   }
633
634   const auto &MCID = MF.getSubtarget().getInstrInfo()->get(OpCode);
635   if (!MCID.isVariadic()) {
636     // FIXME: Move the implicit operand verification to the machine verifier.
637     if (verifyImplicitOperands(Operands, MCID))
638       return true;
639   }
640
641   // TODO: Check for extraneous machine operands.
642   MI = MF.CreateMachineInstr(MCID, DebugLocation, /*NoImplicit=*/true);
643   MI->setFlags(Flags);
644   for (const auto &Operand : Operands)
645     MI->addOperand(MF, Operand.Operand);
646   if (assignRegisterTies(*MI, Operands))
647     return true;
648   if (MemOperands.empty())
649     return false;
650   MachineInstr::mmo_iterator MemRefs =
651       MF.allocateMemRefsArray(MemOperands.size());
652   std::copy(MemOperands.begin(), MemOperands.end(), MemRefs);
653   MI->setMemRefs(MemRefs, MemRefs + MemOperands.size());
654   return false;
655 }
656
657 bool MIParser::parseStandaloneMBB(MachineBasicBlock *&MBB) {
658   lex();
659   if (Token.isNot(MIToken::MachineBasicBlock))
660     return error("expected a machine basic block reference");
661   if (parseMBBReference(MBB))
662     return true;
663   lex();
664   if (Token.isNot(MIToken::Eof))
665     return error(
666         "expected end of string after the machine basic block reference");
667   return false;
668 }
669
670 bool MIParser::parseStandaloneNamedRegister(unsigned &Reg) {
671   lex();
672   if (Token.isNot(MIToken::NamedRegister))
673     return error("expected a named register");
674   if (parseRegister(Reg))
675     return true;
676   lex();
677   if (Token.isNot(MIToken::Eof))
678     return error("expected end of string after the register reference");
679   return false;
680 }
681
682 bool MIParser::parseStandaloneVirtualRegister(unsigned &Reg) {
683   lex();
684   if (Token.isNot(MIToken::VirtualRegister))
685     return error("expected a virtual register");
686   if (parseRegister(Reg))
687     return true;
688   lex();
689   if (Token.isNot(MIToken::Eof))
690     return error("expected end of string after the register reference");
691   return false;
692 }
693
694 bool MIParser::parseStandaloneStackObject(int &FI) {
695   lex();
696   if (Token.isNot(MIToken::StackObject))
697     return error("expected a stack object");
698   if (parseStackFrameIndex(FI))
699     return true;
700   if (Token.isNot(MIToken::Eof))
701     return error("expected end of string after the stack object reference");
702   return false;
703 }
704
705 bool MIParser::parseStandaloneMDNode(MDNode *&Node) {
706   lex();
707   if (Token.isNot(MIToken::exclaim))
708     return error("expected a metadata node");
709   if (parseMDNode(Node))
710     return true;
711   if (Token.isNot(MIToken::Eof))
712     return error("expected end of string after the metadata node");
713   return false;
714 }
715
716 static const char *printImplicitRegisterFlag(const MachineOperand &MO) {
717   assert(MO.isImplicit());
718   return MO.isDef() ? "implicit-def" : "implicit";
719 }
720
721 static std::string getRegisterName(const TargetRegisterInfo *TRI,
722                                    unsigned Reg) {
723   assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "expected phys reg");
724   return StringRef(TRI->getName(Reg)).lower();
725 }
726
727 bool MIParser::verifyImplicitOperands(ArrayRef<ParsedMachineOperand> Operands,
728                                       const MCInstrDesc &MCID) {
729   if (MCID.isCall())
730     // We can't verify call instructions as they can contain arbitrary implicit
731     // register and register mask operands.
732     return false;
733
734   // Gather all the expected implicit operands.
735   SmallVector<MachineOperand, 4> ImplicitOperands;
736   if (MCID.ImplicitDefs)
737     for (const uint16_t *ImpDefs = MCID.getImplicitDefs(); *ImpDefs; ++ImpDefs)
738       ImplicitOperands.push_back(
739           MachineOperand::CreateReg(*ImpDefs, true, true));
740   if (MCID.ImplicitUses)
741     for (const uint16_t *ImpUses = MCID.getImplicitUses(); *ImpUses; ++ImpUses)
742       ImplicitOperands.push_back(
743           MachineOperand::CreateReg(*ImpUses, false, true));
744
745   const auto *TRI = MF.getSubtarget().getRegisterInfo();
746   assert(TRI && "Expected target register info");
747   size_t I = ImplicitOperands.size(), J = Operands.size();
748   while (I) {
749     --I;
750     if (J) {
751       --J;
752       const auto &ImplicitOperand = ImplicitOperands[I];
753       const auto &Operand = Operands[J].Operand;
754       if (ImplicitOperand.isIdenticalTo(Operand))
755         continue;
756       if (Operand.isReg() && Operand.isImplicit()) {
757         // Check if this implicit register is a subregister of an explicit
758         // register operand.
759         bool IsImplicitSubRegister = false;
760         for (size_t K = 0, E = Operands.size(); K < E; ++K) {
761           const auto &Op = Operands[K].Operand;
762           if (Op.isReg() && !Op.isImplicit() &&
763               TRI->isSubRegister(Op.getReg(), Operand.getReg())) {
764             IsImplicitSubRegister = true;
765             break;
766           }
767         }
768         if (IsImplicitSubRegister)
769           continue;
770         return error(Operands[J].Begin,
771                      Twine("expected an implicit register operand '") +
772                          printImplicitRegisterFlag(ImplicitOperand) + " %" +
773                          getRegisterName(TRI, ImplicitOperand.getReg()) + "'");
774       }
775     }
776     // TODO: Fix source location when Operands[J].end is right before '=', i.e:
777     // insead of reporting an error at this location:
778     //            %eax = MOV32r0
779     //                 ^
780     // report the error at the following location:
781     //            %eax = MOV32r0
782     //                          ^
783     return error(J < Operands.size() ? Operands[J].End : Token.location(),
784                  Twine("missing implicit register operand '") +
785                      printImplicitRegisterFlag(ImplicitOperands[I]) + " %" +
786                      getRegisterName(TRI, ImplicitOperands[I].getReg()) + "'");
787   }
788   return false;
789 }
790
791 bool MIParser::parseInstruction(unsigned &OpCode, unsigned &Flags) {
792   if (Token.is(MIToken::kw_frame_setup)) {
793     Flags |= MachineInstr::FrameSetup;
794     lex();
795   }
796   if (Token.isNot(MIToken::Identifier))
797     return error("expected a machine instruction");
798   StringRef InstrName = Token.stringValue();
799   if (parseInstrName(InstrName, OpCode))
800     return error(Twine("unknown machine instruction name '") + InstrName + "'");
801   lex();
802   return false;
803 }
804
805 bool MIParser::parseRegister(unsigned &Reg) {
806   switch (Token.kind()) {
807   case MIToken::underscore:
808     Reg = 0;
809     break;
810   case MIToken::NamedRegister: {
811     StringRef Name = Token.stringValue();
812     if (getRegisterByName(Name, Reg))
813       return error(Twine("unknown register name '") + Name + "'");
814     break;
815   }
816   case MIToken::VirtualRegister: {
817     unsigned ID;
818     if (getUnsigned(ID))
819       return true;
820     const auto RegInfo = PFS.VirtualRegisterSlots.find(ID);
821     if (RegInfo == PFS.VirtualRegisterSlots.end())
822       return error(Twine("use of undefined virtual register '%") + Twine(ID) +
823                    "'");
824     Reg = RegInfo->second;
825     break;
826   }
827   // TODO: Parse other register kinds.
828   default:
829     llvm_unreachable("The current token should be a register");
830   }
831   return false;
832 }
833
834 bool MIParser::parseRegisterFlag(unsigned &Flags) {
835   const unsigned OldFlags = Flags;
836   switch (Token.kind()) {
837   case MIToken::kw_implicit:
838     Flags |= RegState::Implicit;
839     break;
840   case MIToken::kw_implicit_define:
841     Flags |= RegState::ImplicitDefine;
842     break;
843   case MIToken::kw_def:
844     Flags |= RegState::Define;
845     break;
846   case MIToken::kw_dead:
847     Flags |= RegState::Dead;
848     break;
849   case MIToken::kw_killed:
850     Flags |= RegState::Kill;
851     break;
852   case MIToken::kw_undef:
853     Flags |= RegState::Undef;
854     break;
855   case MIToken::kw_internal:
856     Flags |= RegState::InternalRead;
857     break;
858   case MIToken::kw_early_clobber:
859     Flags |= RegState::EarlyClobber;
860     break;
861   case MIToken::kw_debug_use:
862     Flags |= RegState::Debug;
863     break;
864   default:
865     llvm_unreachable("The current token should be a register flag");
866   }
867   if (OldFlags == Flags)
868     // We know that the same flag is specified more than once when the flags
869     // weren't modified.
870     return error("duplicate '" + Token.stringValue() + "' register flag");
871   lex();
872   return false;
873 }
874
875 bool MIParser::parseSubRegisterIndex(unsigned &SubReg) {
876   assert(Token.is(MIToken::colon));
877   lex();
878   if (Token.isNot(MIToken::Identifier))
879     return error("expected a subregister index after ':'");
880   auto Name = Token.stringValue();
881   SubReg = getSubRegIndex(Name);
882   if (!SubReg)
883     return error(Twine("use of unknown subregister index '") + Name + "'");
884   lex();
885   return false;
886 }
887
888 bool MIParser::parseRegisterTiedDefIndex(unsigned &TiedDefIdx) {
889   if (!consumeIfPresent(MIToken::kw_tied_def))
890     return error("expected 'tied-def' after '('");
891   if (Token.isNot(MIToken::IntegerLiteral))
892     return error("expected an integer literal after 'tied-def'");
893   if (getUnsigned(TiedDefIdx))
894     return true;
895   lex();
896   if (expectAndConsume(MIToken::rparen))
897     return true;
898   return false;
899 }
900
901 bool MIParser::assignRegisterTies(MachineInstr &MI,
902                                   ArrayRef<ParsedMachineOperand> Operands) {
903   SmallVector<std::pair<unsigned, unsigned>, 4> TiedRegisterPairs;
904   for (unsigned I = 0, E = Operands.size(); I != E; ++I) {
905     if (!Operands[I].TiedDefIdx)
906       continue;
907     // The parser ensures that this operand is a register use, so we just have
908     // to check the tied-def operand.
909     unsigned DefIdx = Operands[I].TiedDefIdx.getValue();
910     if (DefIdx >= E)
911       return error(Operands[I].Begin,
912                    Twine("use of invalid tied-def operand index '" +
913                          Twine(DefIdx) + "'; instruction has only ") +
914                        Twine(E) + " operands");
915     const auto &DefOperand = Operands[DefIdx].Operand;
916     if (!DefOperand.isReg() || !DefOperand.isDef())
917       // FIXME: add note with the def operand.
918       return error(Operands[I].Begin,
919                    Twine("use of invalid tied-def operand index '") +
920                        Twine(DefIdx) + "'; the operand #" + Twine(DefIdx) +
921                        " isn't a defined register");
922     // Check that the tied-def operand wasn't tied elsewhere.
923     for (const auto &TiedPair : TiedRegisterPairs) {
924       if (TiedPair.first == DefIdx)
925         return error(Operands[I].Begin,
926                      Twine("the tied-def operand #") + Twine(DefIdx) +
927                          " is already tied with another register operand");
928     }
929     TiedRegisterPairs.push_back(std::make_pair(DefIdx, I));
930   }
931   // FIXME: Verify that for non INLINEASM instructions, the def and use tied
932   // indices must be less than tied max.
933   for (const auto &TiedPair : TiedRegisterPairs)
934     MI.tieOperands(TiedPair.first, TiedPair.second);
935   return false;
936 }
937
938 bool MIParser::parseRegisterOperand(MachineOperand &Dest,
939                                     Optional<unsigned> &TiedDefIdx,
940                                     bool IsDef) {
941   unsigned Reg;
942   unsigned Flags = IsDef ? RegState::Define : 0;
943   while (Token.isRegisterFlag()) {
944     if (parseRegisterFlag(Flags))
945       return true;
946   }
947   if (!Token.isRegister())
948     return error("expected a register after register flags");
949   if (parseRegister(Reg))
950     return true;
951   lex();
952   unsigned SubReg = 0;
953   if (Token.is(MIToken::colon)) {
954     if (parseSubRegisterIndex(SubReg))
955       return true;
956   }
957   if ((Flags & RegState::Define) == 0 && consumeIfPresent(MIToken::lparen)) {
958     unsigned Idx;
959     if (parseRegisterTiedDefIndex(Idx))
960       return true;
961     TiedDefIdx = Idx;
962   }
963   Dest = MachineOperand::CreateReg(
964       Reg, Flags & RegState::Define, Flags & RegState::Implicit,
965       Flags & RegState::Kill, Flags & RegState::Dead, Flags & RegState::Undef,
966       Flags & RegState::EarlyClobber, SubReg, Flags & RegState::Debug,
967       Flags & RegState::InternalRead);
968   return false;
969 }
970
971 bool MIParser::parseImmediateOperand(MachineOperand &Dest) {
972   assert(Token.is(MIToken::IntegerLiteral));
973   const APSInt &Int = Token.integerValue();
974   if (Int.getMinSignedBits() > 64)
975     return error("integer literal is too large to be an immediate operand");
976   Dest = MachineOperand::CreateImm(Int.getExtValue());
977   lex();
978   return false;
979 }
980
981 bool MIParser::parseIRConstant(StringRef::iterator Loc, StringRef StringValue,
982                                const Constant *&C) {
983   auto Source = StringValue.str(); // The source has to be null terminated.
984   SMDiagnostic Err;
985   C = parseConstantValue(Source.c_str(), Err, *MF.getFunction()->getParent());
986   if (!C)
987     return error(Loc + Err.getColumnNo(), Err.getMessage());
988   return false;
989 }
990
991 bool MIParser::parseIRConstant(StringRef::iterator Loc, const Constant *&C) {
992   if (parseIRConstant(Loc, StringRef(Loc, Token.range().end() - Loc), C))
993     return true;
994   lex();
995   return false;
996 }
997
998 bool MIParser::parseTypedImmediateOperand(MachineOperand &Dest) {
999   assert(Token.is(MIToken::IntegerType));
1000   auto Loc = Token.location();
1001   lex();
1002   if (Token.isNot(MIToken::IntegerLiteral))
1003     return error("expected an integer literal");
1004   const Constant *C = nullptr;
1005   if (parseIRConstant(Loc, C))
1006     return true;
1007   Dest = MachineOperand::CreateCImm(cast<ConstantInt>(C));
1008   return false;
1009 }
1010
1011 bool MIParser::parseFPImmediateOperand(MachineOperand &Dest) {
1012   auto Loc = Token.location();
1013   lex();
1014   if (Token.isNot(MIToken::FloatingPointLiteral))
1015     return error("expected a floating point literal");
1016   const Constant *C = nullptr;
1017   if (parseIRConstant(Loc, C))
1018     return true;
1019   Dest = MachineOperand::CreateFPImm(cast<ConstantFP>(C));
1020   return false;
1021 }
1022
1023 bool MIParser::getUnsigned(unsigned &Result) {
1024   assert(Token.hasIntegerValue() && "Expected a token with an integer value");
1025   const uint64_t Limit = uint64_t(std::numeric_limits<unsigned>::max()) + 1;
1026   uint64_t Val64 = Token.integerValue().getLimitedValue(Limit);
1027   if (Val64 == Limit)
1028     return error("expected 32-bit integer (too large)");
1029   Result = Val64;
1030   return false;
1031 }
1032
1033 bool MIParser::parseMBBReference(MachineBasicBlock *&MBB) {
1034   assert(Token.is(MIToken::MachineBasicBlock) ||
1035          Token.is(MIToken::MachineBasicBlockLabel));
1036   unsigned Number;
1037   if (getUnsigned(Number))
1038     return true;
1039   auto MBBInfo = PFS.MBBSlots.find(Number);
1040   if (MBBInfo == PFS.MBBSlots.end())
1041     return error(Twine("use of undefined machine basic block #") +
1042                  Twine(Number));
1043   MBB = MBBInfo->second;
1044   if (!Token.stringValue().empty() && Token.stringValue() != MBB->getName())
1045     return error(Twine("the name of machine basic block #") + Twine(Number) +
1046                  " isn't '" + Token.stringValue() + "'");
1047   return false;
1048 }
1049
1050 bool MIParser::parseMBBOperand(MachineOperand &Dest) {
1051   MachineBasicBlock *MBB;
1052   if (parseMBBReference(MBB))
1053     return true;
1054   Dest = MachineOperand::CreateMBB(MBB);
1055   lex();
1056   return false;
1057 }
1058
1059 bool MIParser::parseStackFrameIndex(int &FI) {
1060   assert(Token.is(MIToken::StackObject));
1061   unsigned ID;
1062   if (getUnsigned(ID))
1063     return true;
1064   auto ObjectInfo = PFS.StackObjectSlots.find(ID);
1065   if (ObjectInfo == PFS.StackObjectSlots.end())
1066     return error(Twine("use of undefined stack object '%stack.") + Twine(ID) +
1067                  "'");
1068   StringRef Name;
1069   if (const auto *Alloca =
1070           MF.getFrameInfo()->getObjectAllocation(ObjectInfo->second))
1071     Name = Alloca->getName();
1072   if (!Token.stringValue().empty() && Token.stringValue() != Name)
1073     return error(Twine("the name of the stack object '%stack.") + Twine(ID) +
1074                  "' isn't '" + Token.stringValue() + "'");
1075   lex();
1076   FI = ObjectInfo->second;
1077   return false;
1078 }
1079
1080 bool MIParser::parseStackObjectOperand(MachineOperand &Dest) {
1081   int FI;
1082   if (parseStackFrameIndex(FI))
1083     return true;
1084   Dest = MachineOperand::CreateFI(FI);
1085   return false;
1086 }
1087
1088 bool MIParser::parseFixedStackFrameIndex(int &FI) {
1089   assert(Token.is(MIToken::FixedStackObject));
1090   unsigned ID;
1091   if (getUnsigned(ID))
1092     return true;
1093   auto ObjectInfo = PFS.FixedStackObjectSlots.find(ID);
1094   if (ObjectInfo == PFS.FixedStackObjectSlots.end())
1095     return error(Twine("use of undefined fixed stack object '%fixed-stack.") +
1096                  Twine(ID) + "'");
1097   lex();
1098   FI = ObjectInfo->second;
1099   return false;
1100 }
1101
1102 bool MIParser::parseFixedStackObjectOperand(MachineOperand &Dest) {
1103   int FI;
1104   if (parseFixedStackFrameIndex(FI))
1105     return true;
1106   Dest = MachineOperand::CreateFI(FI);
1107   return false;
1108 }
1109
1110 bool MIParser::parseGlobalValue(GlobalValue *&GV) {
1111   switch (Token.kind()) {
1112   case MIToken::NamedGlobalValue: {
1113     const Module *M = MF.getFunction()->getParent();
1114     GV = M->getNamedValue(Token.stringValue());
1115     if (!GV)
1116       return error(Twine("use of undefined global value '") + Token.range() +
1117                    "'");
1118     break;
1119   }
1120   case MIToken::GlobalValue: {
1121     unsigned GVIdx;
1122     if (getUnsigned(GVIdx))
1123       return true;
1124     if (GVIdx >= IRSlots.GlobalValues.size())
1125       return error(Twine("use of undefined global value '@") + Twine(GVIdx) +
1126                    "'");
1127     GV = IRSlots.GlobalValues[GVIdx];
1128     break;
1129   }
1130   default:
1131     llvm_unreachable("The current token should be a global value");
1132   }
1133   return false;
1134 }
1135
1136 bool MIParser::parseGlobalAddressOperand(MachineOperand &Dest) {
1137   GlobalValue *GV = nullptr;
1138   if (parseGlobalValue(GV))
1139     return true;
1140   lex();
1141   Dest = MachineOperand::CreateGA(GV, /*Offset=*/0);
1142   if (parseOperandsOffset(Dest))
1143     return true;
1144   return false;
1145 }
1146
1147 bool MIParser::parseConstantPoolIndexOperand(MachineOperand &Dest) {
1148   assert(Token.is(MIToken::ConstantPoolItem));
1149   unsigned ID;
1150   if (getUnsigned(ID))
1151     return true;
1152   auto ConstantInfo = PFS.ConstantPoolSlots.find(ID);
1153   if (ConstantInfo == PFS.ConstantPoolSlots.end())
1154     return error("use of undefined constant '%const." + Twine(ID) + "'");
1155   lex();
1156   Dest = MachineOperand::CreateCPI(ID, /*Offset=*/0);
1157   if (parseOperandsOffset(Dest))
1158     return true;
1159   return false;
1160 }
1161
1162 bool MIParser::parseJumpTableIndexOperand(MachineOperand &Dest) {
1163   assert(Token.is(MIToken::JumpTableIndex));
1164   unsigned ID;
1165   if (getUnsigned(ID))
1166     return true;
1167   auto JumpTableEntryInfo = PFS.JumpTableSlots.find(ID);
1168   if (JumpTableEntryInfo == PFS.JumpTableSlots.end())
1169     return error("use of undefined jump table '%jump-table." + Twine(ID) + "'");
1170   lex();
1171   Dest = MachineOperand::CreateJTI(JumpTableEntryInfo->second);
1172   return false;
1173 }
1174
1175 bool MIParser::parseExternalSymbolOperand(MachineOperand &Dest) {
1176   assert(Token.is(MIToken::ExternalSymbol));
1177   const char *Symbol = MF.createExternalSymbolName(Token.stringValue());
1178   lex();
1179   Dest = MachineOperand::CreateES(Symbol);
1180   if (parseOperandsOffset(Dest))
1181     return true;
1182   return false;
1183 }
1184
1185 bool MIParser::parseMDNode(MDNode *&Node) {
1186   assert(Token.is(MIToken::exclaim));
1187   auto Loc = Token.location();
1188   lex();
1189   if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
1190     return error("expected metadata id after '!'");
1191   unsigned ID;
1192   if (getUnsigned(ID))
1193     return true;
1194   auto NodeInfo = IRSlots.MetadataNodes.find(ID);
1195   if (NodeInfo == IRSlots.MetadataNodes.end())
1196     return error(Loc, "use of undefined metadata '!" + Twine(ID) + "'");
1197   lex();
1198   Node = NodeInfo->second.get();
1199   return false;
1200 }
1201
1202 bool MIParser::parseMetadataOperand(MachineOperand &Dest) {
1203   MDNode *Node = nullptr;
1204   if (parseMDNode(Node))
1205     return true;
1206   Dest = MachineOperand::CreateMetadata(Node);
1207   return false;
1208 }
1209
1210 bool MIParser::parseCFIOffset(int &Offset) {
1211   if (Token.isNot(MIToken::IntegerLiteral))
1212     return error("expected a cfi offset");
1213   if (Token.integerValue().getMinSignedBits() > 32)
1214     return error("expected a 32 bit integer (the cfi offset is too large)");
1215   Offset = (int)Token.integerValue().getExtValue();
1216   lex();
1217   return false;
1218 }
1219
1220 bool MIParser::parseCFIRegister(unsigned &Reg) {
1221   if (Token.isNot(MIToken::NamedRegister))
1222     return error("expected a cfi register");
1223   unsigned LLVMReg;
1224   if (parseRegister(LLVMReg))
1225     return true;
1226   const auto *TRI = MF.getSubtarget().getRegisterInfo();
1227   assert(TRI && "Expected target register info");
1228   int DwarfReg = TRI->getDwarfRegNum(LLVMReg, true);
1229   if (DwarfReg < 0)
1230     return error("invalid DWARF register");
1231   Reg = (unsigned)DwarfReg;
1232   lex();
1233   return false;
1234 }
1235
1236 bool MIParser::parseCFIOperand(MachineOperand &Dest) {
1237   auto Kind = Token.kind();
1238   lex();
1239   auto &MMI = MF.getMMI();
1240   int Offset;
1241   unsigned Reg;
1242   unsigned CFIIndex;
1243   switch (Kind) {
1244   case MIToken::kw_cfi_same_value:
1245     if (parseCFIRegister(Reg))
1246       return true;
1247     CFIIndex =
1248         MMI.addFrameInst(MCCFIInstruction::createSameValue(nullptr, Reg));
1249     break;
1250   case MIToken::kw_cfi_offset:
1251     if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
1252         parseCFIOffset(Offset))
1253       return true;
1254     CFIIndex =
1255         MMI.addFrameInst(MCCFIInstruction::createOffset(nullptr, Reg, Offset));
1256     break;
1257   case MIToken::kw_cfi_def_cfa_register:
1258     if (parseCFIRegister(Reg))
1259       return true;
1260     CFIIndex =
1261         MMI.addFrameInst(MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
1262     break;
1263   case MIToken::kw_cfi_def_cfa_offset:
1264     if (parseCFIOffset(Offset))
1265       return true;
1266     // NB: MCCFIInstruction::createDefCfaOffset negates the offset.
1267     CFIIndex = MMI.addFrameInst(
1268         MCCFIInstruction::createDefCfaOffset(nullptr, -Offset));
1269     break;
1270   case MIToken::kw_cfi_def_cfa:
1271     if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
1272         parseCFIOffset(Offset))
1273       return true;
1274     // NB: MCCFIInstruction::createDefCfa negates the offset.
1275     CFIIndex =
1276         MMI.addFrameInst(MCCFIInstruction::createDefCfa(nullptr, Reg, -Offset));
1277     break;
1278   default:
1279     // TODO: Parse the other CFI operands.
1280     llvm_unreachable("The current token should be a cfi operand");
1281   }
1282   Dest = MachineOperand::CreateCFIIndex(CFIIndex);
1283   return false;
1284 }
1285
1286 bool MIParser::parseIRBlock(BasicBlock *&BB, const Function &F) {
1287   switch (Token.kind()) {
1288   case MIToken::NamedIRBlock: {
1289     BB = dyn_cast_or_null<BasicBlock>(
1290         F.getValueSymbolTable().lookup(Token.stringValue()));
1291     if (!BB)
1292       return error(Twine("use of undefined IR block '") + Token.range() + "'");
1293     break;
1294   }
1295   case MIToken::IRBlock: {
1296     unsigned SlotNumber = 0;
1297     if (getUnsigned(SlotNumber))
1298       return true;
1299     BB = const_cast<BasicBlock *>(getIRBlock(SlotNumber, F));
1300     if (!BB)
1301       return error(Twine("use of undefined IR block '%ir-block.") +
1302                    Twine(SlotNumber) + "'");
1303     break;
1304   }
1305   default:
1306     llvm_unreachable("The current token should be an IR block reference");
1307   }
1308   return false;
1309 }
1310
1311 bool MIParser::parseBlockAddressOperand(MachineOperand &Dest) {
1312   assert(Token.is(MIToken::kw_blockaddress));
1313   lex();
1314   if (expectAndConsume(MIToken::lparen))
1315     return true;
1316   if (Token.isNot(MIToken::GlobalValue) &&
1317       Token.isNot(MIToken::NamedGlobalValue))
1318     return error("expected a global value");
1319   GlobalValue *GV = nullptr;
1320   if (parseGlobalValue(GV))
1321     return true;
1322   auto *F = dyn_cast<Function>(GV);
1323   if (!F)
1324     return error("expected an IR function reference");
1325   lex();
1326   if (expectAndConsume(MIToken::comma))
1327     return true;
1328   BasicBlock *BB = nullptr;
1329   if (Token.isNot(MIToken::IRBlock) && Token.isNot(MIToken::NamedIRBlock))
1330     return error("expected an IR block reference");
1331   if (parseIRBlock(BB, *F))
1332     return true;
1333   lex();
1334   if (expectAndConsume(MIToken::rparen))
1335     return true;
1336   Dest = MachineOperand::CreateBA(BlockAddress::get(F, BB), /*Offset=*/0);
1337   if (parseOperandsOffset(Dest))
1338     return true;
1339   return false;
1340 }
1341
1342 bool MIParser::parseTargetIndexOperand(MachineOperand &Dest) {
1343   assert(Token.is(MIToken::kw_target_index));
1344   lex();
1345   if (expectAndConsume(MIToken::lparen))
1346     return true;
1347   if (Token.isNot(MIToken::Identifier))
1348     return error("expected the name of the target index");
1349   int Index = 0;
1350   if (getTargetIndex(Token.stringValue(), Index))
1351     return error("use of undefined target index '" + Token.stringValue() + "'");
1352   lex();
1353   if (expectAndConsume(MIToken::rparen))
1354     return true;
1355   Dest = MachineOperand::CreateTargetIndex(unsigned(Index), /*Offset=*/0);
1356   if (parseOperandsOffset(Dest))
1357     return true;
1358   return false;
1359 }
1360
1361 bool MIParser::parseLiveoutRegisterMaskOperand(MachineOperand &Dest) {
1362   assert(Token.is(MIToken::kw_liveout));
1363   const auto *TRI = MF.getSubtarget().getRegisterInfo();
1364   assert(TRI && "Expected target register info");
1365   uint32_t *Mask = MF.allocateRegisterMask(TRI->getNumRegs());
1366   lex();
1367   if (expectAndConsume(MIToken::lparen))
1368     return true;
1369   while (true) {
1370     if (Token.isNot(MIToken::NamedRegister))
1371       return error("expected a named register");
1372     unsigned Reg = 0;
1373     if (parseRegister(Reg))
1374       return true;
1375     lex();
1376     Mask[Reg / 32] |= 1U << (Reg % 32);
1377     // TODO: Report an error if the same register is used more than once.
1378     if (Token.isNot(MIToken::comma))
1379       break;
1380     lex();
1381   }
1382   if (expectAndConsume(MIToken::rparen))
1383     return true;
1384   Dest = MachineOperand::CreateRegLiveOut(Mask);
1385   return false;
1386 }
1387
1388 bool MIParser::parseMachineOperand(MachineOperand &Dest,
1389                                    Optional<unsigned> &TiedDefIdx) {
1390   switch (Token.kind()) {
1391   case MIToken::kw_implicit:
1392   case MIToken::kw_implicit_define:
1393   case MIToken::kw_def:
1394   case MIToken::kw_dead:
1395   case MIToken::kw_killed:
1396   case MIToken::kw_undef:
1397   case MIToken::kw_internal:
1398   case MIToken::kw_early_clobber:
1399   case MIToken::kw_debug_use:
1400   case MIToken::underscore:
1401   case MIToken::NamedRegister:
1402   case MIToken::VirtualRegister:
1403     return parseRegisterOperand(Dest, TiedDefIdx);
1404   case MIToken::IntegerLiteral:
1405     return parseImmediateOperand(Dest);
1406   case MIToken::IntegerType:
1407     return parseTypedImmediateOperand(Dest);
1408   case MIToken::kw_half:
1409   case MIToken::kw_float:
1410   case MIToken::kw_double:
1411   case MIToken::kw_x86_fp80:
1412   case MIToken::kw_fp128:
1413   case MIToken::kw_ppc_fp128:
1414     return parseFPImmediateOperand(Dest);
1415   case MIToken::MachineBasicBlock:
1416     return parseMBBOperand(Dest);
1417   case MIToken::StackObject:
1418     return parseStackObjectOperand(Dest);
1419   case MIToken::FixedStackObject:
1420     return parseFixedStackObjectOperand(Dest);
1421   case MIToken::GlobalValue:
1422   case MIToken::NamedGlobalValue:
1423     return parseGlobalAddressOperand(Dest);
1424   case MIToken::ConstantPoolItem:
1425     return parseConstantPoolIndexOperand(Dest);
1426   case MIToken::JumpTableIndex:
1427     return parseJumpTableIndexOperand(Dest);
1428   case MIToken::ExternalSymbol:
1429     return parseExternalSymbolOperand(Dest);
1430   case MIToken::exclaim:
1431     return parseMetadataOperand(Dest);
1432   case MIToken::kw_cfi_same_value:
1433   case MIToken::kw_cfi_offset:
1434   case MIToken::kw_cfi_def_cfa_register:
1435   case MIToken::kw_cfi_def_cfa_offset:
1436   case MIToken::kw_cfi_def_cfa:
1437     return parseCFIOperand(Dest);
1438   case MIToken::kw_blockaddress:
1439     return parseBlockAddressOperand(Dest);
1440   case MIToken::kw_target_index:
1441     return parseTargetIndexOperand(Dest);
1442   case MIToken::kw_liveout:
1443     return parseLiveoutRegisterMaskOperand(Dest);
1444   case MIToken::Error:
1445     return true;
1446   case MIToken::Identifier:
1447     if (const auto *RegMask = getRegMask(Token.stringValue())) {
1448       Dest = MachineOperand::CreateRegMask(RegMask);
1449       lex();
1450       break;
1451     }
1452   // fallthrough
1453   default:
1454     // FIXME: Parse the MCSymbol machine operand.
1455     return error("expected a machine operand");
1456   }
1457   return false;
1458 }
1459
1460 bool MIParser::parseMachineOperandAndTargetFlags(
1461     MachineOperand &Dest, Optional<unsigned> &TiedDefIdx) {
1462   unsigned TF = 0;
1463   bool HasTargetFlags = false;
1464   if (Token.is(MIToken::kw_target_flags)) {
1465     HasTargetFlags = true;
1466     lex();
1467     if (expectAndConsume(MIToken::lparen))
1468       return true;
1469     if (Token.isNot(MIToken::Identifier))
1470       return error("expected the name of the target flag");
1471     if (getDirectTargetFlag(Token.stringValue(), TF)) {
1472       if (getBitmaskTargetFlag(Token.stringValue(), TF))
1473         return error("use of undefined target flag '" + Token.stringValue() +
1474                      "'");
1475     }
1476     lex();
1477     while (Token.is(MIToken::comma)) {
1478       lex();
1479       if (Token.isNot(MIToken::Identifier))
1480         return error("expected the name of the target flag");
1481       unsigned BitFlag = 0;
1482       if (getBitmaskTargetFlag(Token.stringValue(), BitFlag))
1483         return error("use of undefined target flag '" + Token.stringValue() +
1484                      "'");
1485       // TODO: Report an error when using a duplicate bit target flag.
1486       TF |= BitFlag;
1487       lex();
1488     }
1489     if (expectAndConsume(MIToken::rparen))
1490       return true;
1491   }
1492   auto Loc = Token.location();
1493   if (parseMachineOperand(Dest, TiedDefIdx))
1494     return true;
1495   if (!HasTargetFlags)
1496     return false;
1497   if (Dest.isReg())
1498     return error(Loc, "register operands can't have target flags");
1499   Dest.setTargetFlags(TF);
1500   return false;
1501 }
1502
1503 bool MIParser::parseOffset(int64_t &Offset) {
1504   if (Token.isNot(MIToken::plus) && Token.isNot(MIToken::minus))
1505     return false;
1506   StringRef Sign = Token.range();
1507   bool IsNegative = Token.is(MIToken::minus);
1508   lex();
1509   if (Token.isNot(MIToken::IntegerLiteral))
1510     return error("expected an integer literal after '" + Sign + "'");
1511   if (Token.integerValue().getMinSignedBits() > 64)
1512     return error("expected 64-bit integer (too large)");
1513   Offset = Token.integerValue().getExtValue();
1514   if (IsNegative)
1515     Offset = -Offset;
1516   lex();
1517   return false;
1518 }
1519
1520 bool MIParser::parseAlignment(unsigned &Alignment) {
1521   assert(Token.is(MIToken::kw_align));
1522   lex();
1523   if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
1524     return error("expected an integer literal after 'align'");
1525   if (getUnsigned(Alignment))
1526     return true;
1527   lex();
1528   return false;
1529 }
1530
1531 bool MIParser::parseOperandsOffset(MachineOperand &Op) {
1532   int64_t Offset = 0;
1533   if (parseOffset(Offset))
1534     return true;
1535   Op.setOffset(Offset);
1536   return false;
1537 }
1538
1539 bool MIParser::parseIRValue(const Value *&V) {
1540   switch (Token.kind()) {
1541   case MIToken::NamedIRValue: {
1542     V = MF.getFunction()->getValueSymbolTable().lookup(Token.stringValue());
1543     break;
1544   }
1545   case MIToken::IRValue: {
1546     unsigned SlotNumber = 0;
1547     if (getUnsigned(SlotNumber))
1548       return true;
1549     V = getIRValue(SlotNumber);
1550     break;
1551   }
1552   case MIToken::NamedGlobalValue:
1553   case MIToken::GlobalValue: {
1554     GlobalValue *GV = nullptr;
1555     if (parseGlobalValue(GV))
1556       return true;
1557     V = GV;
1558     break;
1559   }
1560   default:
1561     llvm_unreachable("The current token should be an IR block reference");
1562   }
1563   if (!V)
1564     return error(Twine("use of undefined IR value '") + Token.range() + "'");
1565   return false;
1566 }
1567
1568 bool MIParser::getUint64(uint64_t &Result) {
1569   assert(Token.hasIntegerValue());
1570   if (Token.integerValue().getActiveBits() > 64)
1571     return error("expected 64-bit integer (too large)");
1572   Result = Token.integerValue().getZExtValue();
1573   return false;
1574 }
1575
1576 bool MIParser::parseMemoryOperandFlag(unsigned &Flags) {
1577   const unsigned OldFlags = Flags;
1578   switch (Token.kind()) {
1579   case MIToken::kw_volatile:
1580     Flags |= MachineMemOperand::MOVolatile;
1581     break;
1582   case MIToken::kw_non_temporal:
1583     Flags |= MachineMemOperand::MONonTemporal;
1584     break;
1585   case MIToken::kw_invariant:
1586     Flags |= MachineMemOperand::MOInvariant;
1587     break;
1588   // TODO: parse the target specific memory operand flags.
1589   default:
1590     llvm_unreachable("The current token should be a memory operand flag");
1591   }
1592   if (OldFlags == Flags)
1593     // We know that the same flag is specified more than once when the flags
1594     // weren't modified.
1595     return error("duplicate '" + Token.stringValue() + "' memory operand flag");
1596   lex();
1597   return false;
1598 }
1599
1600 bool MIParser::parseMemoryPseudoSourceValue(const PseudoSourceValue *&PSV) {
1601   switch (Token.kind()) {
1602   case MIToken::kw_stack:
1603     PSV = MF.getPSVManager().getStack();
1604     break;
1605   case MIToken::kw_got:
1606     PSV = MF.getPSVManager().getGOT();
1607     break;
1608   case MIToken::kw_jump_table:
1609     PSV = MF.getPSVManager().getJumpTable();
1610     break;
1611   case MIToken::kw_constant_pool:
1612     PSV = MF.getPSVManager().getConstantPool();
1613     break;
1614   case MIToken::FixedStackObject: {
1615     int FI;
1616     if (parseFixedStackFrameIndex(FI))
1617       return true;
1618     PSV = MF.getPSVManager().getFixedStack(FI);
1619     // The token was already consumed, so use return here instead of break.
1620     return false;
1621   }
1622   case MIToken::kw_call_entry: {
1623     lex();
1624     switch (Token.kind()) {
1625     case MIToken::GlobalValue:
1626     case MIToken::NamedGlobalValue: {
1627       GlobalValue *GV = nullptr;
1628       if (parseGlobalValue(GV))
1629         return true;
1630       PSV = MF.getPSVManager().getGlobalValueCallEntry(GV);
1631       break;
1632     }
1633     case MIToken::ExternalSymbol:
1634       PSV = MF.getPSVManager().getExternalSymbolCallEntry(
1635           MF.createExternalSymbolName(Token.stringValue()));
1636       break;
1637     default:
1638       return error(
1639           "expected a global value or an external symbol after 'call-entry'");
1640     }
1641     break;
1642   }
1643   default:
1644     llvm_unreachable("The current token should be pseudo source value");
1645   }
1646   lex();
1647   return false;
1648 }
1649
1650 bool MIParser::parseMachinePointerInfo(MachinePointerInfo &Dest) {
1651   if (Token.is(MIToken::kw_constant_pool) || Token.is(MIToken::kw_stack) ||
1652       Token.is(MIToken::kw_got) || Token.is(MIToken::kw_jump_table) ||
1653       Token.is(MIToken::FixedStackObject) || Token.is(MIToken::kw_call_entry)) {
1654     const PseudoSourceValue *PSV = nullptr;
1655     if (parseMemoryPseudoSourceValue(PSV))
1656       return true;
1657     int64_t Offset = 0;
1658     if (parseOffset(Offset))
1659       return true;
1660     Dest = MachinePointerInfo(PSV, Offset);
1661     return false;
1662   }
1663   if (Token.isNot(MIToken::NamedIRValue) && Token.isNot(MIToken::IRValue) &&
1664       Token.isNot(MIToken::GlobalValue) &&
1665       Token.isNot(MIToken::NamedGlobalValue))
1666     return error("expected an IR value reference");
1667   const Value *V = nullptr;
1668   if (parseIRValue(V))
1669     return true;
1670   if (!V->getType()->isPointerTy())
1671     return error("expected a pointer IR value");
1672   lex();
1673   int64_t Offset = 0;
1674   if (parseOffset(Offset))
1675     return true;
1676   Dest = MachinePointerInfo(V, Offset);
1677   return false;
1678 }
1679
1680 bool MIParser::parseMachineMemoryOperand(MachineMemOperand *&Dest) {
1681   if (expectAndConsume(MIToken::lparen))
1682     return true;
1683   unsigned Flags = 0;
1684   while (Token.isMemoryOperandFlag()) {
1685     if (parseMemoryOperandFlag(Flags))
1686       return true;
1687   }
1688   if (Token.isNot(MIToken::Identifier) ||
1689       (Token.stringValue() != "load" && Token.stringValue() != "store"))
1690     return error("expected 'load' or 'store' memory operation");
1691   if (Token.stringValue() == "load")
1692     Flags |= MachineMemOperand::MOLoad;
1693   else
1694     Flags |= MachineMemOperand::MOStore;
1695   lex();
1696
1697   if (Token.isNot(MIToken::IntegerLiteral))
1698     return error("expected the size integer literal after memory operation");
1699   uint64_t Size;
1700   if (getUint64(Size))
1701     return true;
1702   lex();
1703
1704   const char *Word = Flags & MachineMemOperand::MOLoad ? "from" : "into";
1705   if (Token.isNot(MIToken::Identifier) || Token.stringValue() != Word)
1706     return error(Twine("expected '") + Word + "'");
1707   lex();
1708
1709   MachinePointerInfo Ptr = MachinePointerInfo();
1710   if (parseMachinePointerInfo(Ptr))
1711     return true;
1712   unsigned BaseAlignment = Size;
1713   AAMDNodes AAInfo;
1714   MDNode *Range = nullptr;
1715   while (consumeIfPresent(MIToken::comma)) {
1716     switch (Token.kind()) {
1717     case MIToken::kw_align:
1718       if (parseAlignment(BaseAlignment))
1719         return true;
1720       break;
1721     case MIToken::md_tbaa:
1722       lex();
1723       if (parseMDNode(AAInfo.TBAA))
1724         return true;
1725       break;
1726     case MIToken::md_alias_scope:
1727       lex();
1728       if (parseMDNode(AAInfo.Scope))
1729         return true;
1730       break;
1731     case MIToken::md_noalias:
1732       lex();
1733       if (parseMDNode(AAInfo.NoAlias))
1734         return true;
1735       break;
1736     case MIToken::md_range:
1737       lex();
1738       if (parseMDNode(Range))
1739         return true;
1740       break;
1741     // TODO: Report an error on duplicate metadata nodes.
1742     default:
1743       return error("expected 'align' or '!tbaa' or '!alias.scope' or "
1744                    "'!noalias' or '!range'");
1745     }
1746   }
1747   if (expectAndConsume(MIToken::rparen))
1748     return true;
1749   Dest =
1750       MF.getMachineMemOperand(Ptr, Flags, Size, BaseAlignment, AAInfo, Range);
1751   return false;
1752 }
1753
1754 void MIParser::initNames2InstrOpCodes() {
1755   if (!Names2InstrOpCodes.empty())
1756     return;
1757   const auto *TII = MF.getSubtarget().getInstrInfo();
1758   assert(TII && "Expected target instruction info");
1759   for (unsigned I = 0, E = TII->getNumOpcodes(); I < E; ++I)
1760     Names2InstrOpCodes.insert(std::make_pair(StringRef(TII->getName(I)), I));
1761 }
1762
1763 bool MIParser::parseInstrName(StringRef InstrName, unsigned &OpCode) {
1764   initNames2InstrOpCodes();
1765   auto InstrInfo = Names2InstrOpCodes.find(InstrName);
1766   if (InstrInfo == Names2InstrOpCodes.end())
1767     return true;
1768   OpCode = InstrInfo->getValue();
1769   return false;
1770 }
1771
1772 void MIParser::initNames2Regs() {
1773   if (!Names2Regs.empty())
1774     return;
1775   // The '%noreg' register is the register 0.
1776   Names2Regs.insert(std::make_pair("noreg", 0));
1777   const auto *TRI = MF.getSubtarget().getRegisterInfo();
1778   assert(TRI && "Expected target register info");
1779   for (unsigned I = 0, E = TRI->getNumRegs(); I < E; ++I) {
1780     bool WasInserted =
1781         Names2Regs.insert(std::make_pair(StringRef(TRI->getName(I)).lower(), I))
1782             .second;
1783     (void)WasInserted;
1784     assert(WasInserted && "Expected registers to be unique case-insensitively");
1785   }
1786 }
1787
1788 bool MIParser::getRegisterByName(StringRef RegName, unsigned &Reg) {
1789   initNames2Regs();
1790   auto RegInfo = Names2Regs.find(RegName);
1791   if (RegInfo == Names2Regs.end())
1792     return true;
1793   Reg = RegInfo->getValue();
1794   return false;
1795 }
1796
1797 void MIParser::initNames2RegMasks() {
1798   if (!Names2RegMasks.empty())
1799     return;
1800   const auto *TRI = MF.getSubtarget().getRegisterInfo();
1801   assert(TRI && "Expected target register info");
1802   ArrayRef<const uint32_t *> RegMasks = TRI->getRegMasks();
1803   ArrayRef<const char *> RegMaskNames = TRI->getRegMaskNames();
1804   assert(RegMasks.size() == RegMaskNames.size());
1805   for (size_t I = 0, E = RegMasks.size(); I < E; ++I)
1806     Names2RegMasks.insert(
1807         std::make_pair(StringRef(RegMaskNames[I]).lower(), RegMasks[I]));
1808 }
1809
1810 const uint32_t *MIParser::getRegMask(StringRef Identifier) {
1811   initNames2RegMasks();
1812   auto RegMaskInfo = Names2RegMasks.find(Identifier);
1813   if (RegMaskInfo == Names2RegMasks.end())
1814     return nullptr;
1815   return RegMaskInfo->getValue();
1816 }
1817
1818 void MIParser::initNames2SubRegIndices() {
1819   if (!Names2SubRegIndices.empty())
1820     return;
1821   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1822   for (unsigned I = 1, E = TRI->getNumSubRegIndices(); I < E; ++I)
1823     Names2SubRegIndices.insert(
1824         std::make_pair(StringRef(TRI->getSubRegIndexName(I)).lower(), I));
1825 }
1826
1827 unsigned MIParser::getSubRegIndex(StringRef Name) {
1828   initNames2SubRegIndices();
1829   auto SubRegInfo = Names2SubRegIndices.find(Name);
1830   if (SubRegInfo == Names2SubRegIndices.end())
1831     return 0;
1832   return SubRegInfo->getValue();
1833 }
1834
1835 static void initSlots2BasicBlocks(
1836     const Function &F,
1837     DenseMap<unsigned, const BasicBlock *> &Slots2BasicBlocks) {
1838   ModuleSlotTracker MST(F.getParent(), /*ShouldInitializeAllMetadata=*/false);
1839   MST.incorporateFunction(F);
1840   for (auto &BB : F) {
1841     if (BB.hasName())
1842       continue;
1843     int Slot = MST.getLocalSlot(&BB);
1844     if (Slot == -1)
1845       continue;
1846     Slots2BasicBlocks.insert(std::make_pair(unsigned(Slot), &BB));
1847   }
1848 }
1849
1850 static const BasicBlock *getIRBlockFromSlot(
1851     unsigned Slot,
1852     const DenseMap<unsigned, const BasicBlock *> &Slots2BasicBlocks) {
1853   auto BlockInfo = Slots2BasicBlocks.find(Slot);
1854   if (BlockInfo == Slots2BasicBlocks.end())
1855     return nullptr;
1856   return BlockInfo->second;
1857 }
1858
1859 const BasicBlock *MIParser::getIRBlock(unsigned Slot) {
1860   if (Slots2BasicBlocks.empty())
1861     initSlots2BasicBlocks(*MF.getFunction(), Slots2BasicBlocks);
1862   return getIRBlockFromSlot(Slot, Slots2BasicBlocks);
1863 }
1864
1865 const BasicBlock *MIParser::getIRBlock(unsigned Slot, const Function &F) {
1866   if (&F == MF.getFunction())
1867     return getIRBlock(Slot);
1868   DenseMap<unsigned, const BasicBlock *> CustomSlots2BasicBlocks;
1869   initSlots2BasicBlocks(F, CustomSlots2BasicBlocks);
1870   return getIRBlockFromSlot(Slot, CustomSlots2BasicBlocks);
1871 }
1872
1873 static void mapValueToSlot(const Value *V, ModuleSlotTracker &MST,
1874                            DenseMap<unsigned, const Value *> &Slots2Values) {
1875   int Slot = MST.getLocalSlot(V);
1876   if (Slot == -1)
1877     return;
1878   Slots2Values.insert(std::make_pair(unsigned(Slot), V));
1879 }
1880
1881 /// Creates the mapping from slot numbers to function's unnamed IR values.
1882 static void initSlots2Values(const Function &F,
1883                              DenseMap<unsigned, const Value *> &Slots2Values) {
1884   ModuleSlotTracker MST(F.getParent(), /*ShouldInitializeAllMetadata=*/false);
1885   MST.incorporateFunction(F);
1886   for (const auto &Arg : F.args())
1887     mapValueToSlot(&Arg, MST, Slots2Values);
1888   for (const auto &BB : F) {
1889     mapValueToSlot(&BB, MST, Slots2Values);
1890     for (const auto &I : BB)
1891       mapValueToSlot(&I, MST, Slots2Values);
1892   }
1893 }
1894
1895 const Value *MIParser::getIRValue(unsigned Slot) {
1896   if (Slots2Values.empty())
1897     initSlots2Values(*MF.getFunction(), Slots2Values);
1898   auto ValueInfo = Slots2Values.find(Slot);
1899   if (ValueInfo == Slots2Values.end())
1900     return nullptr;
1901   return ValueInfo->second;
1902 }
1903
1904 void MIParser::initNames2TargetIndices() {
1905   if (!Names2TargetIndices.empty())
1906     return;
1907   const auto *TII = MF.getSubtarget().getInstrInfo();
1908   assert(TII && "Expected target instruction info");
1909   auto Indices = TII->getSerializableTargetIndices();
1910   for (const auto &I : Indices)
1911     Names2TargetIndices.insert(std::make_pair(StringRef(I.second), I.first));
1912 }
1913
1914 bool MIParser::getTargetIndex(StringRef Name, int &Index) {
1915   initNames2TargetIndices();
1916   auto IndexInfo = Names2TargetIndices.find(Name);
1917   if (IndexInfo == Names2TargetIndices.end())
1918     return true;
1919   Index = IndexInfo->second;
1920   return false;
1921 }
1922
1923 void MIParser::initNames2DirectTargetFlags() {
1924   if (!Names2DirectTargetFlags.empty())
1925     return;
1926   const auto *TII = MF.getSubtarget().getInstrInfo();
1927   assert(TII && "Expected target instruction info");
1928   auto Flags = TII->getSerializableDirectMachineOperandTargetFlags();
1929   for (const auto &I : Flags)
1930     Names2DirectTargetFlags.insert(
1931         std::make_pair(StringRef(I.second), I.first));
1932 }
1933
1934 bool MIParser::getDirectTargetFlag(StringRef Name, unsigned &Flag) {
1935   initNames2DirectTargetFlags();
1936   auto FlagInfo = Names2DirectTargetFlags.find(Name);
1937   if (FlagInfo == Names2DirectTargetFlags.end())
1938     return true;
1939   Flag = FlagInfo->second;
1940   return false;
1941 }
1942
1943 void MIParser::initNames2BitmaskTargetFlags() {
1944   if (!Names2BitmaskTargetFlags.empty())
1945     return;
1946   const auto *TII = MF.getSubtarget().getInstrInfo();
1947   assert(TII && "Expected target instruction info");
1948   auto Flags = TII->getSerializableBitmaskMachineOperandTargetFlags();
1949   for (const auto &I : Flags)
1950     Names2BitmaskTargetFlags.insert(
1951         std::make_pair(StringRef(I.second), I.first));
1952 }
1953
1954 bool MIParser::getBitmaskTargetFlag(StringRef Name, unsigned &Flag) {
1955   initNames2BitmaskTargetFlags();
1956   auto FlagInfo = Names2BitmaskTargetFlags.find(Name);
1957   if (FlagInfo == Names2BitmaskTargetFlags.end())
1958     return true;
1959   Flag = FlagInfo->second;
1960   return false;
1961 }
1962
1963 bool llvm::parseMachineBasicBlockDefinitions(MachineFunction &MF, StringRef Src,
1964                                              PerFunctionMIParsingState &PFS,
1965                                              const SlotMapping &IRSlots,
1966                                              SMDiagnostic &Error) {
1967   SourceMgr SM;
1968   SM.AddNewSourceBuffer(
1969       MemoryBuffer::getMemBuffer(Src, "", /*RequiresNullTerminator=*/false),
1970       SMLoc());
1971   return MIParser(SM, MF, Error, Src, PFS, IRSlots)
1972       .parseBasicBlockDefinitions(PFS.MBBSlots);
1973 }
1974
1975 bool llvm::parseMachineInstructions(MachineFunction &MF, StringRef Src,
1976                                     const PerFunctionMIParsingState &PFS,
1977                                     const SlotMapping &IRSlots,
1978                                     SMDiagnostic &Error) {
1979   SourceMgr SM;
1980   SM.AddNewSourceBuffer(
1981       MemoryBuffer::getMemBuffer(Src, "", /*RequiresNullTerminator=*/false),
1982       SMLoc());
1983   return MIParser(SM, MF, Error, Src, PFS, IRSlots).parseBasicBlocks();
1984 }
1985
1986 bool llvm::parseMBBReference(MachineBasicBlock *&MBB, SourceMgr &SM,
1987                              MachineFunction &MF, StringRef Src,
1988                              const PerFunctionMIParsingState &PFS,
1989                              const SlotMapping &IRSlots, SMDiagnostic &Error) {
1990   return MIParser(SM, MF, Error, Src, PFS, IRSlots).parseStandaloneMBB(MBB);
1991 }
1992
1993 bool llvm::parseNamedRegisterReference(unsigned &Reg, SourceMgr &SM,
1994                                        MachineFunction &MF, StringRef Src,
1995                                        const PerFunctionMIParsingState &PFS,
1996                                        const SlotMapping &IRSlots,
1997                                        SMDiagnostic &Error) {
1998   return MIParser(SM, MF, Error, Src, PFS, IRSlots)
1999       .parseStandaloneNamedRegister(Reg);
2000 }
2001
2002 bool llvm::parseVirtualRegisterReference(unsigned &Reg, SourceMgr &SM,
2003                                          MachineFunction &MF, StringRef Src,
2004                                          const PerFunctionMIParsingState &PFS,
2005                                          const SlotMapping &IRSlots,
2006                                          SMDiagnostic &Error) {
2007   return MIParser(SM, MF, Error, Src, PFS, IRSlots)
2008       .parseStandaloneVirtualRegister(Reg);
2009 }
2010
2011 bool llvm::parseStackObjectReference(int &FI, SourceMgr &SM,
2012                                      MachineFunction &MF, StringRef Src,
2013                                      const PerFunctionMIParsingState &PFS,
2014                                      const SlotMapping &IRSlots,
2015                                      SMDiagnostic &Error) {
2016   return MIParser(SM, MF, Error, Src, PFS, IRSlots)
2017       .parseStandaloneStackObject(FI);
2018 }
2019
2020 bool llvm::parseMDNode(MDNode *&Node, SourceMgr &SM, MachineFunction &MF,
2021                        StringRef Src, const PerFunctionMIParsingState &PFS,
2022                        const SlotMapping &IRSlots, SMDiagnostic &Error) {
2023   return MIParser(SM, MF, Error, Src, PFS, IRSlots).parseStandaloneMDNode(Node);
2024 }