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