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   SmallVector<LLT, 1> Tys;
599   if (isPreISelGenericOpcode(OpCode)) {
600     // For generic opcode, at least one type is mandatory.
601     expectAndConsume(MIToken::lbrace);
602     do {
603       auto Loc = Token.location();
604       Tys.resize(Tys.size() + 1);
605       if (parseLowLevelType(Loc, Tys[Tys.size() - 1]))
606         return true;
607     } while (consumeIfPresent(MIToken::comma));
608     expectAndConsume(MIToken::rbrace);
609   }
610 
611   // Parse the remaining machine operands.
612   while (!Token.isNewlineOrEOF() && Token.isNot(MIToken::kw_debug_location) &&
613          Token.isNot(MIToken::coloncolon) && Token.isNot(MIToken::lbrace)) {
614     auto Loc = Token.location();
615     Optional<unsigned> TiedDefIdx;
616     if (parseMachineOperandAndTargetFlags(MO, TiedDefIdx))
617       return true;
618     Operands.push_back(
619         ParsedMachineOperand(MO, Loc, Token.location(), TiedDefIdx));
620     if (Token.isNewlineOrEOF() || Token.is(MIToken::coloncolon) ||
621         Token.is(MIToken::lbrace))
622       break;
623     if (Token.isNot(MIToken::comma))
624       return error("expected ',' before the next machine operand");
625     lex();
626   }
627 
628   DebugLoc DebugLocation;
629   if (Token.is(MIToken::kw_debug_location)) {
630     lex();
631     if (Token.isNot(MIToken::exclaim))
632       return error("expected a metadata node after 'debug-location'");
633     MDNode *Node = nullptr;
634     if (parseMDNode(Node))
635       return true;
636     DebugLocation = DebugLoc(Node);
637   }
638 
639   // Parse the machine memory operands.
640   SmallVector<MachineMemOperand *, 2> MemOperands;
641   if (Token.is(MIToken::coloncolon)) {
642     lex();
643     while (!Token.isNewlineOrEOF()) {
644       MachineMemOperand *MemOp = nullptr;
645       if (parseMachineMemoryOperand(MemOp))
646         return true;
647       MemOperands.push_back(MemOp);
648       if (Token.isNewlineOrEOF())
649         break;
650       if (Token.isNot(MIToken::comma))
651         return error("expected ',' before the next machine memory operand");
652       lex();
653     }
654   }
655 
656   const auto &MCID = MF.getSubtarget().getInstrInfo()->get(OpCode);
657   if (!MCID.isVariadic()) {
658     // FIXME: Move the implicit operand verification to the machine verifier.
659     if (verifyImplicitOperands(Operands, MCID))
660       return true;
661   }
662 
663   // TODO: Check for extraneous machine operands.
664   MI = MF.CreateMachineInstr(MCID, DebugLocation, /*NoImplicit=*/true);
665   MI->setFlags(Flags);
666   if (Tys.size() > 0) {
667     for (unsigned i = 0; i < Tys.size(); ++i)
668       MI->setType(Tys[i], i);
669   }
670   for (const auto &Operand : Operands)
671     MI->addOperand(MF, Operand.Operand);
672   if (assignRegisterTies(*MI, Operands))
673     return true;
674   if (MemOperands.empty())
675     return false;
676   MachineInstr::mmo_iterator MemRefs =
677       MF.allocateMemRefsArray(MemOperands.size());
678   std::copy(MemOperands.begin(), MemOperands.end(), MemRefs);
679   MI->setMemRefs(MemRefs, MemRefs + MemOperands.size());
680   return false;
681 }
682 
683 bool MIParser::parseStandaloneMBB(MachineBasicBlock *&MBB) {
684   lex();
685   if (Token.isNot(MIToken::MachineBasicBlock))
686     return error("expected a machine basic block reference");
687   if (parseMBBReference(MBB))
688     return true;
689   lex();
690   if (Token.isNot(MIToken::Eof))
691     return error(
692         "expected end of string after the machine basic block reference");
693   return false;
694 }
695 
696 bool MIParser::parseStandaloneNamedRegister(unsigned &Reg) {
697   lex();
698   if (Token.isNot(MIToken::NamedRegister))
699     return error("expected a named register");
700   if (parseRegister(Reg))
701     return true;
702   lex();
703   if (Token.isNot(MIToken::Eof))
704     return error("expected end of string after the register reference");
705   return false;
706 }
707 
708 bool MIParser::parseStandaloneVirtualRegister(unsigned &Reg) {
709   lex();
710   if (Token.isNot(MIToken::VirtualRegister))
711     return error("expected a virtual register");
712   if (parseRegister(Reg))
713     return true;
714   lex();
715   if (Token.isNot(MIToken::Eof))
716     return error("expected end of string after the register reference");
717   return false;
718 }
719 
720 bool MIParser::parseStandaloneStackObject(int &FI) {
721   lex();
722   if (Token.isNot(MIToken::StackObject))
723     return error("expected a stack object");
724   if (parseStackFrameIndex(FI))
725     return true;
726   if (Token.isNot(MIToken::Eof))
727     return error("expected end of string after the stack object reference");
728   return false;
729 }
730 
731 bool MIParser::parseStandaloneMDNode(MDNode *&Node) {
732   lex();
733   if (Token.isNot(MIToken::exclaim))
734     return error("expected a metadata node");
735   if (parseMDNode(Node))
736     return true;
737   if (Token.isNot(MIToken::Eof))
738     return error("expected end of string after the metadata node");
739   return false;
740 }
741 
742 static const char *printImplicitRegisterFlag(const MachineOperand &MO) {
743   assert(MO.isImplicit());
744   return MO.isDef() ? "implicit-def" : "implicit";
745 }
746 
747 static std::string getRegisterName(const TargetRegisterInfo *TRI,
748                                    unsigned Reg) {
749   assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "expected phys reg");
750   return StringRef(TRI->getName(Reg)).lower();
751 }
752 
753 /// Return true if the parsed machine operands contain a given machine operand.
754 static bool isImplicitOperandIn(const MachineOperand &ImplicitOperand,
755                                 ArrayRef<ParsedMachineOperand> Operands) {
756   for (const auto &I : Operands) {
757     if (ImplicitOperand.isIdenticalTo(I.Operand))
758       return true;
759   }
760   return false;
761 }
762 
763 bool MIParser::verifyImplicitOperands(ArrayRef<ParsedMachineOperand> Operands,
764                                       const MCInstrDesc &MCID) {
765   if (MCID.isCall())
766     // We can't verify call instructions as they can contain arbitrary implicit
767     // register and register mask operands.
768     return false;
769 
770   // Gather all the expected implicit operands.
771   SmallVector<MachineOperand, 4> ImplicitOperands;
772   if (MCID.ImplicitDefs)
773     for (const MCPhysReg *ImpDefs = MCID.getImplicitDefs(); *ImpDefs; ++ImpDefs)
774       ImplicitOperands.push_back(
775           MachineOperand::CreateReg(*ImpDefs, true, true));
776   if (MCID.ImplicitUses)
777     for (const MCPhysReg *ImpUses = MCID.getImplicitUses(); *ImpUses; ++ImpUses)
778       ImplicitOperands.push_back(
779           MachineOperand::CreateReg(*ImpUses, false, true));
780 
781   const auto *TRI = MF.getSubtarget().getRegisterInfo();
782   assert(TRI && "Expected target register info");
783   for (const auto &I : ImplicitOperands) {
784     if (isImplicitOperandIn(I, Operands))
785       continue;
786     return error(Operands.empty() ? Token.location() : Operands.back().End,
787                  Twine("missing implicit register operand '") +
788                      printImplicitRegisterFlag(I) + " %" +
789                      getRegisterName(TRI, I.getReg()) + "'");
790   }
791   return false;
792 }
793 
794 bool MIParser::parseInstruction(unsigned &OpCode, unsigned &Flags) {
795   if (Token.is(MIToken::kw_frame_setup)) {
796     Flags |= MachineInstr::FrameSetup;
797     lex();
798   }
799   if (Token.isNot(MIToken::Identifier))
800     return error("expected a machine instruction");
801   StringRef InstrName = Token.stringValue();
802   if (parseInstrName(InstrName, OpCode))
803     return error(Twine("unknown machine instruction name '") + InstrName + "'");
804   lex();
805   return false;
806 }
807 
808 bool MIParser::parseRegister(unsigned &Reg) {
809   switch (Token.kind()) {
810   case MIToken::underscore:
811     Reg = 0;
812     break;
813   case MIToken::NamedRegister: {
814     StringRef Name = Token.stringValue();
815     if (getRegisterByName(Name, Reg))
816       return error(Twine("unknown register name '") + Name + "'");
817     break;
818   }
819   case MIToken::VirtualRegister: {
820     unsigned ID;
821     if (getUnsigned(ID))
822       return true;
823     const auto RegInfo = PFS.VirtualRegisterSlots.find(ID);
824     if (RegInfo == PFS.VirtualRegisterSlots.end())
825       return error(Twine("use of undefined virtual register '%") + Twine(ID) +
826                    "'");
827     Reg = RegInfo->second;
828     break;
829   }
830   // TODO: Parse other register kinds.
831   default:
832     llvm_unreachable("The current token should be a register");
833   }
834   return false;
835 }
836 
837 bool MIParser::parseRegisterFlag(unsigned &Flags) {
838   const unsigned OldFlags = Flags;
839   switch (Token.kind()) {
840   case MIToken::kw_implicit:
841     Flags |= RegState::Implicit;
842     break;
843   case MIToken::kw_implicit_define:
844     Flags |= RegState::ImplicitDefine;
845     break;
846   case MIToken::kw_def:
847     Flags |= RegState::Define;
848     break;
849   case MIToken::kw_dead:
850     Flags |= RegState::Dead;
851     break;
852   case MIToken::kw_killed:
853     Flags |= RegState::Kill;
854     break;
855   case MIToken::kw_undef:
856     Flags |= RegState::Undef;
857     break;
858   case MIToken::kw_internal:
859     Flags |= RegState::InternalRead;
860     break;
861   case MIToken::kw_early_clobber:
862     Flags |= RegState::EarlyClobber;
863     break;
864   case MIToken::kw_debug_use:
865     Flags |= RegState::Debug;
866     break;
867   default:
868     llvm_unreachable("The current token should be a register flag");
869   }
870   if (OldFlags == Flags)
871     // We know that the same flag is specified more than once when the flags
872     // weren't modified.
873     return error("duplicate '" + Token.stringValue() + "' register flag");
874   lex();
875   return false;
876 }
877 
878 bool MIParser::parseSubRegisterIndex(unsigned &SubReg) {
879   assert(Token.is(MIToken::colon));
880   lex();
881   if (Token.isNot(MIToken::Identifier))
882     return error("expected a subregister index after ':'");
883   auto Name = Token.stringValue();
884   SubReg = getSubRegIndex(Name);
885   if (!SubReg)
886     return error(Twine("use of unknown subregister index '") + Name + "'");
887   lex();
888   return false;
889 }
890 
891 bool MIParser::parseRegisterTiedDefIndex(unsigned &TiedDefIdx) {
892   if (!consumeIfPresent(MIToken::kw_tied_def))
893     return error("expected 'tied-def' after '('");
894   if (Token.isNot(MIToken::IntegerLiteral))
895     return error("expected an integer literal after 'tied-def'");
896   if (getUnsigned(TiedDefIdx))
897     return true;
898   lex();
899   if (expectAndConsume(MIToken::rparen))
900     return true;
901   return false;
902 }
903 
904 bool MIParser::parseSize(unsigned &Size) {
905   if (Token.isNot(MIToken::IntegerLiteral))
906     return error("expected an integer literal for the size");
907   if (getUnsigned(Size))
908     return true;
909   lex();
910   if (expectAndConsume(MIToken::rparen))
911     return true;
912   return false;
913 }
914 
915 bool MIParser::assignRegisterTies(MachineInstr &MI,
916                                   ArrayRef<ParsedMachineOperand> Operands) {
917   SmallVector<std::pair<unsigned, unsigned>, 4> TiedRegisterPairs;
918   for (unsigned I = 0, E = Operands.size(); I != E; ++I) {
919     if (!Operands[I].TiedDefIdx)
920       continue;
921     // The parser ensures that this operand is a register use, so we just have
922     // to check the tied-def operand.
923     unsigned DefIdx = Operands[I].TiedDefIdx.getValue();
924     if (DefIdx >= E)
925       return error(Operands[I].Begin,
926                    Twine("use of invalid tied-def operand index '" +
927                          Twine(DefIdx) + "'; instruction has only ") +
928                        Twine(E) + " operands");
929     const auto &DefOperand = Operands[DefIdx].Operand;
930     if (!DefOperand.isReg() || !DefOperand.isDef())
931       // FIXME: add note with the def operand.
932       return error(Operands[I].Begin,
933                    Twine("use of invalid tied-def operand index '") +
934                        Twine(DefIdx) + "'; the operand #" + Twine(DefIdx) +
935                        " isn't a defined register");
936     // Check that the tied-def operand wasn't tied elsewhere.
937     for (const auto &TiedPair : TiedRegisterPairs) {
938       if (TiedPair.first == DefIdx)
939         return error(Operands[I].Begin,
940                      Twine("the tied-def operand #") + Twine(DefIdx) +
941                          " is already tied with another register operand");
942     }
943     TiedRegisterPairs.push_back(std::make_pair(DefIdx, I));
944   }
945   // FIXME: Verify that for non INLINEASM instructions, the def and use tied
946   // indices must be less than tied max.
947   for (const auto &TiedPair : TiedRegisterPairs)
948     MI.tieOperands(TiedPair.first, TiedPair.second);
949   return false;
950 }
951 
952 bool MIParser::parseRegisterOperand(MachineOperand &Dest,
953                                     Optional<unsigned> &TiedDefIdx,
954                                     bool IsDef) {
955   unsigned Reg;
956   unsigned Flags = IsDef ? RegState::Define : 0;
957   while (Token.isRegisterFlag()) {
958     if (parseRegisterFlag(Flags))
959       return true;
960   }
961   if (!Token.isRegister())
962     return error("expected a register after register flags");
963   if (parseRegister(Reg))
964     return true;
965   lex();
966   unsigned SubReg = 0;
967   if (Token.is(MIToken::colon)) {
968     if (parseSubRegisterIndex(SubReg))
969       return true;
970     if (!TargetRegisterInfo::isVirtualRegister(Reg))
971       return error("subregister index expects a virtual register");
972   }
973   if ((Flags & RegState::Define) == 0) {
974     if (consumeIfPresent(MIToken::lparen)) {
975       unsigned Idx;
976       if (parseRegisterTiedDefIndex(Idx))
977         return true;
978       TiedDefIdx = Idx;
979     }
980   } else if (consumeIfPresent(MIToken::lparen)) {
981     MachineRegisterInfo &MRI = MF.getRegInfo();
982 
983     // Virtual registers may have a size with GlobalISel.
984     if (!TargetRegisterInfo::isVirtualRegister(Reg))
985       return error("unexpected size on physical register");
986     if (MRI.getRegClassOrRegBank(Reg).is<const TargetRegisterClass *>())
987       return error("unexpected size on non-generic virtual register");
988 
989     unsigned Size;
990     if (parseSize(Size))
991       return true;
992 
993     MRI.setSize(Reg, Size);
994   } else if (PFS.GenericVRegs.count(Reg)) {
995     // Generic virtual registers must have a size.
996     // If we end up here this means the size hasn't been specified and
997     // this is bad!
998     return error("generic virtual registers must have a size");
999   }
1000   Dest = MachineOperand::CreateReg(
1001       Reg, Flags & RegState::Define, Flags & RegState::Implicit,
1002       Flags & RegState::Kill, Flags & RegState::Dead, Flags & RegState::Undef,
1003       Flags & RegState::EarlyClobber, SubReg, Flags & RegState::Debug,
1004       Flags & RegState::InternalRead);
1005   return false;
1006 }
1007 
1008 bool MIParser::parseImmediateOperand(MachineOperand &Dest) {
1009   assert(Token.is(MIToken::IntegerLiteral));
1010   const APSInt &Int = Token.integerValue();
1011   if (Int.getMinSignedBits() > 64)
1012     return error("integer literal is too large to be an immediate operand");
1013   Dest = MachineOperand::CreateImm(Int.getExtValue());
1014   lex();
1015   return false;
1016 }
1017 
1018 bool MIParser::parseIRConstant(StringRef::iterator Loc, StringRef StringValue,
1019                                const Constant *&C) {
1020   auto Source = StringValue.str(); // The source has to be null terminated.
1021   SMDiagnostic Err;
1022   C = parseConstantValue(Source.c_str(), Err, *MF.getFunction()->getParent(),
1023                          &PFS.IRSlots);
1024   if (!C)
1025     return error(Loc + Err.getColumnNo(), Err.getMessage());
1026   return false;
1027 }
1028 
1029 bool MIParser::parseIRConstant(StringRef::iterator Loc, const Constant *&C) {
1030   if (parseIRConstant(Loc, StringRef(Loc, Token.range().end() - Loc), C))
1031     return true;
1032   lex();
1033   return false;
1034 }
1035 
1036 bool MIParser::parseLowLevelType(StringRef::iterator Loc, LLT &Ty,
1037                                  bool MustBeSized) {
1038   if (Token.is(MIToken::Identifier) && Token.stringValue() == "unsized") {
1039     if (MustBeSized)
1040       return error(Loc, "expected pN, sN or <N x sM> for sized GlobalISel type");
1041     lex();
1042     Ty = LLT::unsized();
1043     return false;
1044   } else if (Token.is(MIToken::ScalarType)) {
1045     Ty = LLT::scalar(APSInt(Token.range().drop_front()).getZExtValue());
1046     lex();
1047     return false;
1048   } else if (Token.is(MIToken::PointerType)) {
1049     Ty = LLT::pointer(APSInt(Token.range().drop_front()).getZExtValue());
1050     lex();
1051     return false;
1052   }
1053 
1054   // Now we're looking for a vector.
1055   if (Token.isNot(MIToken::less))
1056     return error(Loc,
1057                  "expected unsized, pN, sN or <N x sM> for GlobalISel type");
1058 
1059   lex();
1060 
1061   if (Token.isNot(MIToken::IntegerLiteral))
1062     return error(Loc, "expected <N x sM> for vctor type");
1063   uint64_t NumElements = Token.integerValue().getZExtValue();
1064   lex();
1065 
1066   if (Token.isNot(MIToken::Identifier) || Token.stringValue() != "x")
1067     return error(Loc, "expected '<N x sM>' for vector type");
1068   lex();
1069 
1070   if (Token.isNot(MIToken::ScalarType))
1071     return error(Loc, "expected '<N x sM>' for vector type");
1072   uint64_t ScalarSize = APSInt(Token.range().drop_front()).getZExtValue();
1073   lex();
1074 
1075   if (Token.isNot(MIToken::greater))
1076     return error(Loc, "expected '<N x sM>' for vector type");
1077   lex();
1078 
1079   Ty = LLT::vector(NumElements, ScalarSize);
1080   return false;
1081 }
1082 
1083 bool MIParser::parseTypedImmediateOperand(MachineOperand &Dest) {
1084   assert(Token.is(MIToken::IntegerType));
1085   auto Loc = Token.location();
1086   lex();
1087   if (Token.isNot(MIToken::IntegerLiteral))
1088     return error("expected an integer literal");
1089   const Constant *C = nullptr;
1090   if (parseIRConstant(Loc, C))
1091     return true;
1092   Dest = MachineOperand::CreateCImm(cast<ConstantInt>(C));
1093   return false;
1094 }
1095 
1096 bool MIParser::parseFPImmediateOperand(MachineOperand &Dest) {
1097   auto Loc = Token.location();
1098   lex();
1099   if (Token.isNot(MIToken::FloatingPointLiteral))
1100     return error("expected a floating point literal");
1101   const Constant *C = nullptr;
1102   if (parseIRConstant(Loc, C))
1103     return true;
1104   Dest = MachineOperand::CreateFPImm(cast<ConstantFP>(C));
1105   return false;
1106 }
1107 
1108 bool MIParser::getUnsigned(unsigned &Result) {
1109   assert(Token.hasIntegerValue() && "Expected a token with an integer value");
1110   const uint64_t Limit = uint64_t(std::numeric_limits<unsigned>::max()) + 1;
1111   uint64_t Val64 = Token.integerValue().getLimitedValue(Limit);
1112   if (Val64 == Limit)
1113     return error("expected 32-bit integer (too large)");
1114   Result = Val64;
1115   return false;
1116 }
1117 
1118 bool MIParser::parseMBBReference(MachineBasicBlock *&MBB) {
1119   assert(Token.is(MIToken::MachineBasicBlock) ||
1120          Token.is(MIToken::MachineBasicBlockLabel));
1121   unsigned Number;
1122   if (getUnsigned(Number))
1123     return true;
1124   auto MBBInfo = PFS.MBBSlots.find(Number);
1125   if (MBBInfo == PFS.MBBSlots.end())
1126     return error(Twine("use of undefined machine basic block #") +
1127                  Twine(Number));
1128   MBB = MBBInfo->second;
1129   if (!Token.stringValue().empty() && Token.stringValue() != MBB->getName())
1130     return error(Twine("the name of machine basic block #") + Twine(Number) +
1131                  " isn't '" + Token.stringValue() + "'");
1132   return false;
1133 }
1134 
1135 bool MIParser::parseMBBOperand(MachineOperand &Dest) {
1136   MachineBasicBlock *MBB;
1137   if (parseMBBReference(MBB))
1138     return true;
1139   Dest = MachineOperand::CreateMBB(MBB);
1140   lex();
1141   return false;
1142 }
1143 
1144 bool MIParser::parseStackFrameIndex(int &FI) {
1145   assert(Token.is(MIToken::StackObject));
1146   unsigned ID;
1147   if (getUnsigned(ID))
1148     return true;
1149   auto ObjectInfo = PFS.StackObjectSlots.find(ID);
1150   if (ObjectInfo == PFS.StackObjectSlots.end())
1151     return error(Twine("use of undefined stack object '%stack.") + Twine(ID) +
1152                  "'");
1153   StringRef Name;
1154   if (const auto *Alloca =
1155           MF.getFrameInfo()->getObjectAllocation(ObjectInfo->second))
1156     Name = Alloca->getName();
1157   if (!Token.stringValue().empty() && Token.stringValue() != Name)
1158     return error(Twine("the name of the stack object '%stack.") + Twine(ID) +
1159                  "' isn't '" + Token.stringValue() + "'");
1160   lex();
1161   FI = ObjectInfo->second;
1162   return false;
1163 }
1164 
1165 bool MIParser::parseStackObjectOperand(MachineOperand &Dest) {
1166   int FI;
1167   if (parseStackFrameIndex(FI))
1168     return true;
1169   Dest = MachineOperand::CreateFI(FI);
1170   return false;
1171 }
1172 
1173 bool MIParser::parseFixedStackFrameIndex(int &FI) {
1174   assert(Token.is(MIToken::FixedStackObject));
1175   unsigned ID;
1176   if (getUnsigned(ID))
1177     return true;
1178   auto ObjectInfo = PFS.FixedStackObjectSlots.find(ID);
1179   if (ObjectInfo == PFS.FixedStackObjectSlots.end())
1180     return error(Twine("use of undefined fixed stack object '%fixed-stack.") +
1181                  Twine(ID) + "'");
1182   lex();
1183   FI = ObjectInfo->second;
1184   return false;
1185 }
1186 
1187 bool MIParser::parseFixedStackObjectOperand(MachineOperand &Dest) {
1188   int FI;
1189   if (parseFixedStackFrameIndex(FI))
1190     return true;
1191   Dest = MachineOperand::CreateFI(FI);
1192   return false;
1193 }
1194 
1195 bool MIParser::parseGlobalValue(GlobalValue *&GV) {
1196   switch (Token.kind()) {
1197   case MIToken::NamedGlobalValue: {
1198     const Module *M = MF.getFunction()->getParent();
1199     GV = M->getNamedValue(Token.stringValue());
1200     if (!GV)
1201       return error(Twine("use of undefined global value '") + Token.range() +
1202                    "'");
1203     break;
1204   }
1205   case MIToken::GlobalValue: {
1206     unsigned GVIdx;
1207     if (getUnsigned(GVIdx))
1208       return true;
1209     if (GVIdx >= PFS.IRSlots.GlobalValues.size())
1210       return error(Twine("use of undefined global value '@") + Twine(GVIdx) +
1211                    "'");
1212     GV = PFS.IRSlots.GlobalValues[GVIdx];
1213     break;
1214   }
1215   default:
1216     llvm_unreachable("The current token should be a global value");
1217   }
1218   return false;
1219 }
1220 
1221 bool MIParser::parseGlobalAddressOperand(MachineOperand &Dest) {
1222   GlobalValue *GV = nullptr;
1223   if (parseGlobalValue(GV))
1224     return true;
1225   lex();
1226   Dest = MachineOperand::CreateGA(GV, /*Offset=*/0);
1227   if (parseOperandsOffset(Dest))
1228     return true;
1229   return false;
1230 }
1231 
1232 bool MIParser::parseConstantPoolIndexOperand(MachineOperand &Dest) {
1233   assert(Token.is(MIToken::ConstantPoolItem));
1234   unsigned ID;
1235   if (getUnsigned(ID))
1236     return true;
1237   auto ConstantInfo = PFS.ConstantPoolSlots.find(ID);
1238   if (ConstantInfo == PFS.ConstantPoolSlots.end())
1239     return error("use of undefined constant '%const." + Twine(ID) + "'");
1240   lex();
1241   Dest = MachineOperand::CreateCPI(ID, /*Offset=*/0);
1242   if (parseOperandsOffset(Dest))
1243     return true;
1244   return false;
1245 }
1246 
1247 bool MIParser::parseJumpTableIndexOperand(MachineOperand &Dest) {
1248   assert(Token.is(MIToken::JumpTableIndex));
1249   unsigned ID;
1250   if (getUnsigned(ID))
1251     return true;
1252   auto JumpTableEntryInfo = PFS.JumpTableSlots.find(ID);
1253   if (JumpTableEntryInfo == PFS.JumpTableSlots.end())
1254     return error("use of undefined jump table '%jump-table." + Twine(ID) + "'");
1255   lex();
1256   Dest = MachineOperand::CreateJTI(JumpTableEntryInfo->second);
1257   return false;
1258 }
1259 
1260 bool MIParser::parseExternalSymbolOperand(MachineOperand &Dest) {
1261   assert(Token.is(MIToken::ExternalSymbol));
1262   const char *Symbol = MF.createExternalSymbolName(Token.stringValue());
1263   lex();
1264   Dest = MachineOperand::CreateES(Symbol);
1265   if (parseOperandsOffset(Dest))
1266     return true;
1267   return false;
1268 }
1269 
1270 bool MIParser::parseSubRegisterIndexOperand(MachineOperand &Dest) {
1271   assert(Token.is(MIToken::SubRegisterIndex));
1272   StringRef Name = Token.stringValue();
1273   unsigned SubRegIndex = getSubRegIndex(Token.stringValue());
1274   if (SubRegIndex == 0)
1275     return error(Twine("unknown subregister index '") + Name + "'");
1276   lex();
1277   Dest = MachineOperand::CreateImm(SubRegIndex);
1278   return false;
1279 }
1280 
1281 bool MIParser::parseMDNode(MDNode *&Node) {
1282   assert(Token.is(MIToken::exclaim));
1283   auto Loc = Token.location();
1284   lex();
1285   if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
1286     return error("expected metadata id after '!'");
1287   unsigned ID;
1288   if (getUnsigned(ID))
1289     return true;
1290   auto NodeInfo = PFS.IRSlots.MetadataNodes.find(ID);
1291   if (NodeInfo == PFS.IRSlots.MetadataNodes.end())
1292     return error(Loc, "use of undefined metadata '!" + Twine(ID) + "'");
1293   lex();
1294   Node = NodeInfo->second.get();
1295   return false;
1296 }
1297 
1298 bool MIParser::parseMetadataOperand(MachineOperand &Dest) {
1299   MDNode *Node = nullptr;
1300   if (parseMDNode(Node))
1301     return true;
1302   Dest = MachineOperand::CreateMetadata(Node);
1303   return false;
1304 }
1305 
1306 bool MIParser::parseCFIOffset(int &Offset) {
1307   if (Token.isNot(MIToken::IntegerLiteral))
1308     return error("expected a cfi offset");
1309   if (Token.integerValue().getMinSignedBits() > 32)
1310     return error("expected a 32 bit integer (the cfi offset is too large)");
1311   Offset = (int)Token.integerValue().getExtValue();
1312   lex();
1313   return false;
1314 }
1315 
1316 bool MIParser::parseCFIRegister(unsigned &Reg) {
1317   if (Token.isNot(MIToken::NamedRegister))
1318     return error("expected a cfi register");
1319   unsigned LLVMReg;
1320   if (parseRegister(LLVMReg))
1321     return true;
1322   const auto *TRI = MF.getSubtarget().getRegisterInfo();
1323   assert(TRI && "Expected target register info");
1324   int DwarfReg = TRI->getDwarfRegNum(LLVMReg, true);
1325   if (DwarfReg < 0)
1326     return error("invalid DWARF register");
1327   Reg = (unsigned)DwarfReg;
1328   lex();
1329   return false;
1330 }
1331 
1332 bool MIParser::parseCFIOperand(MachineOperand &Dest) {
1333   auto Kind = Token.kind();
1334   lex();
1335   auto &MMI = MF.getMMI();
1336   int Offset;
1337   unsigned Reg;
1338   unsigned CFIIndex;
1339   switch (Kind) {
1340   case MIToken::kw_cfi_same_value:
1341     if (parseCFIRegister(Reg))
1342       return true;
1343     CFIIndex =
1344         MMI.addFrameInst(MCCFIInstruction::createSameValue(nullptr, Reg));
1345     break;
1346   case MIToken::kw_cfi_offset:
1347     if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
1348         parseCFIOffset(Offset))
1349       return true;
1350     CFIIndex =
1351         MMI.addFrameInst(MCCFIInstruction::createOffset(nullptr, Reg, Offset));
1352     break;
1353   case MIToken::kw_cfi_def_cfa_register:
1354     if (parseCFIRegister(Reg))
1355       return true;
1356     CFIIndex =
1357         MMI.addFrameInst(MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
1358     break;
1359   case MIToken::kw_cfi_def_cfa_offset:
1360     if (parseCFIOffset(Offset))
1361       return true;
1362     // NB: MCCFIInstruction::createDefCfaOffset negates the offset.
1363     CFIIndex = MMI.addFrameInst(
1364         MCCFIInstruction::createDefCfaOffset(nullptr, -Offset));
1365     break;
1366   case MIToken::kw_cfi_def_cfa:
1367     if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
1368         parseCFIOffset(Offset))
1369       return true;
1370     // NB: MCCFIInstruction::createDefCfa negates the offset.
1371     CFIIndex =
1372         MMI.addFrameInst(MCCFIInstruction::createDefCfa(nullptr, Reg, -Offset));
1373     break;
1374   default:
1375     // TODO: Parse the other CFI operands.
1376     llvm_unreachable("The current token should be a cfi operand");
1377   }
1378   Dest = MachineOperand::CreateCFIIndex(CFIIndex);
1379   return false;
1380 }
1381 
1382 bool MIParser::parseIRBlock(BasicBlock *&BB, const Function &F) {
1383   switch (Token.kind()) {
1384   case MIToken::NamedIRBlock: {
1385     BB = dyn_cast_or_null<BasicBlock>(
1386         F.getValueSymbolTable().lookup(Token.stringValue()));
1387     if (!BB)
1388       return error(Twine("use of undefined IR block '") + Token.range() + "'");
1389     break;
1390   }
1391   case MIToken::IRBlock: {
1392     unsigned SlotNumber = 0;
1393     if (getUnsigned(SlotNumber))
1394       return true;
1395     BB = const_cast<BasicBlock *>(getIRBlock(SlotNumber, F));
1396     if (!BB)
1397       return error(Twine("use of undefined IR block '%ir-block.") +
1398                    Twine(SlotNumber) + "'");
1399     break;
1400   }
1401   default:
1402     llvm_unreachable("The current token should be an IR block reference");
1403   }
1404   return false;
1405 }
1406 
1407 bool MIParser::parseBlockAddressOperand(MachineOperand &Dest) {
1408   assert(Token.is(MIToken::kw_blockaddress));
1409   lex();
1410   if (expectAndConsume(MIToken::lparen))
1411     return true;
1412   if (Token.isNot(MIToken::GlobalValue) &&
1413       Token.isNot(MIToken::NamedGlobalValue))
1414     return error("expected a global value");
1415   GlobalValue *GV = nullptr;
1416   if (parseGlobalValue(GV))
1417     return true;
1418   auto *F = dyn_cast<Function>(GV);
1419   if (!F)
1420     return error("expected an IR function reference");
1421   lex();
1422   if (expectAndConsume(MIToken::comma))
1423     return true;
1424   BasicBlock *BB = nullptr;
1425   if (Token.isNot(MIToken::IRBlock) && Token.isNot(MIToken::NamedIRBlock))
1426     return error("expected an IR block reference");
1427   if (parseIRBlock(BB, *F))
1428     return true;
1429   lex();
1430   if (expectAndConsume(MIToken::rparen))
1431     return true;
1432   Dest = MachineOperand::CreateBA(BlockAddress::get(F, BB), /*Offset=*/0);
1433   if (parseOperandsOffset(Dest))
1434     return true;
1435   return false;
1436 }
1437 
1438 bool MIParser::parseTargetIndexOperand(MachineOperand &Dest) {
1439   assert(Token.is(MIToken::kw_target_index));
1440   lex();
1441   if (expectAndConsume(MIToken::lparen))
1442     return true;
1443   if (Token.isNot(MIToken::Identifier))
1444     return error("expected the name of the target index");
1445   int Index = 0;
1446   if (getTargetIndex(Token.stringValue(), Index))
1447     return error("use of undefined target index '" + Token.stringValue() + "'");
1448   lex();
1449   if (expectAndConsume(MIToken::rparen))
1450     return true;
1451   Dest = MachineOperand::CreateTargetIndex(unsigned(Index), /*Offset=*/0);
1452   if (parseOperandsOffset(Dest))
1453     return true;
1454   return false;
1455 }
1456 
1457 bool MIParser::parseLiveoutRegisterMaskOperand(MachineOperand &Dest) {
1458   assert(Token.is(MIToken::kw_liveout));
1459   const auto *TRI = MF.getSubtarget().getRegisterInfo();
1460   assert(TRI && "Expected target register info");
1461   uint32_t *Mask = MF.allocateRegisterMask(TRI->getNumRegs());
1462   lex();
1463   if (expectAndConsume(MIToken::lparen))
1464     return true;
1465   while (true) {
1466     if (Token.isNot(MIToken::NamedRegister))
1467       return error("expected a named register");
1468     unsigned Reg = 0;
1469     if (parseRegister(Reg))
1470       return true;
1471     lex();
1472     Mask[Reg / 32] |= 1U << (Reg % 32);
1473     // TODO: Report an error if the same register is used more than once.
1474     if (Token.isNot(MIToken::comma))
1475       break;
1476     lex();
1477   }
1478   if (expectAndConsume(MIToken::rparen))
1479     return true;
1480   Dest = MachineOperand::CreateRegLiveOut(Mask);
1481   return false;
1482 }
1483 
1484 bool MIParser::parseMachineOperand(MachineOperand &Dest,
1485                                    Optional<unsigned> &TiedDefIdx) {
1486   switch (Token.kind()) {
1487   case MIToken::kw_implicit:
1488   case MIToken::kw_implicit_define:
1489   case MIToken::kw_def:
1490   case MIToken::kw_dead:
1491   case MIToken::kw_killed:
1492   case MIToken::kw_undef:
1493   case MIToken::kw_internal:
1494   case MIToken::kw_early_clobber:
1495   case MIToken::kw_debug_use:
1496   case MIToken::underscore:
1497   case MIToken::NamedRegister:
1498   case MIToken::VirtualRegister:
1499     return parseRegisterOperand(Dest, TiedDefIdx);
1500   case MIToken::IntegerLiteral:
1501     return parseImmediateOperand(Dest);
1502   case MIToken::IntegerType:
1503     return parseTypedImmediateOperand(Dest);
1504   case MIToken::kw_half:
1505   case MIToken::kw_float:
1506   case MIToken::kw_double:
1507   case MIToken::kw_x86_fp80:
1508   case MIToken::kw_fp128:
1509   case MIToken::kw_ppc_fp128:
1510     return parseFPImmediateOperand(Dest);
1511   case MIToken::MachineBasicBlock:
1512     return parseMBBOperand(Dest);
1513   case MIToken::StackObject:
1514     return parseStackObjectOperand(Dest);
1515   case MIToken::FixedStackObject:
1516     return parseFixedStackObjectOperand(Dest);
1517   case MIToken::GlobalValue:
1518   case MIToken::NamedGlobalValue:
1519     return parseGlobalAddressOperand(Dest);
1520   case MIToken::ConstantPoolItem:
1521     return parseConstantPoolIndexOperand(Dest);
1522   case MIToken::JumpTableIndex:
1523     return parseJumpTableIndexOperand(Dest);
1524   case MIToken::ExternalSymbol:
1525     return parseExternalSymbolOperand(Dest);
1526   case MIToken::SubRegisterIndex:
1527     return parseSubRegisterIndexOperand(Dest);
1528   case MIToken::exclaim:
1529     return parseMetadataOperand(Dest);
1530   case MIToken::kw_cfi_same_value:
1531   case MIToken::kw_cfi_offset:
1532   case MIToken::kw_cfi_def_cfa_register:
1533   case MIToken::kw_cfi_def_cfa_offset:
1534   case MIToken::kw_cfi_def_cfa:
1535     return parseCFIOperand(Dest);
1536   case MIToken::kw_blockaddress:
1537     return parseBlockAddressOperand(Dest);
1538   case MIToken::kw_target_index:
1539     return parseTargetIndexOperand(Dest);
1540   case MIToken::kw_liveout:
1541     return parseLiveoutRegisterMaskOperand(Dest);
1542   case MIToken::Error:
1543     return true;
1544   case MIToken::Identifier:
1545     if (const auto *RegMask = getRegMask(Token.stringValue())) {
1546       Dest = MachineOperand::CreateRegMask(RegMask);
1547       lex();
1548       break;
1549     }
1550   // fallthrough
1551   default:
1552     // FIXME: Parse the MCSymbol machine operand.
1553     return error("expected a machine operand");
1554   }
1555   return false;
1556 }
1557 
1558 bool MIParser::parseMachineOperandAndTargetFlags(
1559     MachineOperand &Dest, Optional<unsigned> &TiedDefIdx) {
1560   unsigned TF = 0;
1561   bool HasTargetFlags = false;
1562   if (Token.is(MIToken::kw_target_flags)) {
1563     HasTargetFlags = true;
1564     lex();
1565     if (expectAndConsume(MIToken::lparen))
1566       return true;
1567     if (Token.isNot(MIToken::Identifier))
1568       return error("expected the name of the target flag");
1569     if (getDirectTargetFlag(Token.stringValue(), TF)) {
1570       if (getBitmaskTargetFlag(Token.stringValue(), TF))
1571         return error("use of undefined target flag '" + Token.stringValue() +
1572                      "'");
1573     }
1574     lex();
1575     while (Token.is(MIToken::comma)) {
1576       lex();
1577       if (Token.isNot(MIToken::Identifier))
1578         return error("expected the name of the target flag");
1579       unsigned BitFlag = 0;
1580       if (getBitmaskTargetFlag(Token.stringValue(), BitFlag))
1581         return error("use of undefined target flag '" + Token.stringValue() +
1582                      "'");
1583       // TODO: Report an error when using a duplicate bit target flag.
1584       TF |= BitFlag;
1585       lex();
1586     }
1587     if (expectAndConsume(MIToken::rparen))
1588       return true;
1589   }
1590   auto Loc = Token.location();
1591   if (parseMachineOperand(Dest, TiedDefIdx))
1592     return true;
1593   if (!HasTargetFlags)
1594     return false;
1595   if (Dest.isReg())
1596     return error(Loc, "register operands can't have target flags");
1597   Dest.setTargetFlags(TF);
1598   return false;
1599 }
1600 
1601 bool MIParser::parseOffset(int64_t &Offset) {
1602   if (Token.isNot(MIToken::plus) && Token.isNot(MIToken::minus))
1603     return false;
1604   StringRef Sign = Token.range();
1605   bool IsNegative = Token.is(MIToken::minus);
1606   lex();
1607   if (Token.isNot(MIToken::IntegerLiteral))
1608     return error("expected an integer literal after '" + Sign + "'");
1609   if (Token.integerValue().getMinSignedBits() > 64)
1610     return error("expected 64-bit integer (too large)");
1611   Offset = Token.integerValue().getExtValue();
1612   if (IsNegative)
1613     Offset = -Offset;
1614   lex();
1615   return false;
1616 }
1617 
1618 bool MIParser::parseAlignment(unsigned &Alignment) {
1619   assert(Token.is(MIToken::kw_align));
1620   lex();
1621   if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
1622     return error("expected an integer literal after 'align'");
1623   if (getUnsigned(Alignment))
1624     return true;
1625   lex();
1626   return false;
1627 }
1628 
1629 bool MIParser::parseOperandsOffset(MachineOperand &Op) {
1630   int64_t Offset = 0;
1631   if (parseOffset(Offset))
1632     return true;
1633   Op.setOffset(Offset);
1634   return false;
1635 }
1636 
1637 bool MIParser::parseIRValue(const Value *&V) {
1638   switch (Token.kind()) {
1639   case MIToken::NamedIRValue: {
1640     V = MF.getFunction()->getValueSymbolTable().lookup(Token.stringValue());
1641     break;
1642   }
1643   case MIToken::IRValue: {
1644     unsigned SlotNumber = 0;
1645     if (getUnsigned(SlotNumber))
1646       return true;
1647     V = getIRValue(SlotNumber);
1648     break;
1649   }
1650   case MIToken::NamedGlobalValue:
1651   case MIToken::GlobalValue: {
1652     GlobalValue *GV = nullptr;
1653     if (parseGlobalValue(GV))
1654       return true;
1655     V = GV;
1656     break;
1657   }
1658   case MIToken::QuotedIRValue: {
1659     const Constant *C = nullptr;
1660     if (parseIRConstant(Token.location(), Token.stringValue(), C))
1661       return true;
1662     V = C;
1663     break;
1664   }
1665   default:
1666     llvm_unreachable("The current token should be an IR block reference");
1667   }
1668   if (!V)
1669     return error(Twine("use of undefined IR value '") + Token.range() + "'");
1670   return false;
1671 }
1672 
1673 bool MIParser::getUint64(uint64_t &Result) {
1674   assert(Token.hasIntegerValue());
1675   if (Token.integerValue().getActiveBits() > 64)
1676     return error("expected 64-bit integer (too large)");
1677   Result = Token.integerValue().getZExtValue();
1678   return false;
1679 }
1680 
1681 bool MIParser::parseMemoryOperandFlag(MachineMemOperand::Flags &Flags) {
1682   const auto OldFlags = Flags;
1683   switch (Token.kind()) {
1684   case MIToken::kw_volatile:
1685     Flags |= MachineMemOperand::MOVolatile;
1686     break;
1687   case MIToken::kw_non_temporal:
1688     Flags |= MachineMemOperand::MONonTemporal;
1689     break;
1690   case MIToken::kw_invariant:
1691     Flags |= MachineMemOperand::MOInvariant;
1692     break;
1693   // TODO: parse the target specific memory operand flags.
1694   default:
1695     llvm_unreachable("The current token should be a memory operand flag");
1696   }
1697   if (OldFlags == Flags)
1698     // We know that the same flag is specified more than once when the flags
1699     // weren't modified.
1700     return error("duplicate '" + Token.stringValue() + "' memory operand flag");
1701   lex();
1702   return false;
1703 }
1704 
1705 bool MIParser::parseMemoryPseudoSourceValue(const PseudoSourceValue *&PSV) {
1706   switch (Token.kind()) {
1707   case MIToken::kw_stack:
1708     PSV = MF.getPSVManager().getStack();
1709     break;
1710   case MIToken::kw_got:
1711     PSV = MF.getPSVManager().getGOT();
1712     break;
1713   case MIToken::kw_jump_table:
1714     PSV = MF.getPSVManager().getJumpTable();
1715     break;
1716   case MIToken::kw_constant_pool:
1717     PSV = MF.getPSVManager().getConstantPool();
1718     break;
1719   case MIToken::FixedStackObject: {
1720     int FI;
1721     if (parseFixedStackFrameIndex(FI))
1722       return true;
1723     PSV = MF.getPSVManager().getFixedStack(FI);
1724     // The token was already consumed, so use return here instead of break.
1725     return false;
1726   }
1727   case MIToken::StackObject: {
1728     int FI;
1729     if (parseStackFrameIndex(FI))
1730       return true;
1731     PSV = MF.getPSVManager().getFixedStack(FI);
1732     // The token was already consumed, so use return here instead of break.
1733     return false;
1734   }
1735   case MIToken::kw_call_entry: {
1736     lex();
1737     switch (Token.kind()) {
1738     case MIToken::GlobalValue:
1739     case MIToken::NamedGlobalValue: {
1740       GlobalValue *GV = nullptr;
1741       if (parseGlobalValue(GV))
1742         return true;
1743       PSV = MF.getPSVManager().getGlobalValueCallEntry(GV);
1744       break;
1745     }
1746     case MIToken::ExternalSymbol:
1747       PSV = MF.getPSVManager().getExternalSymbolCallEntry(
1748           MF.createExternalSymbolName(Token.stringValue()));
1749       break;
1750     default:
1751       return error(
1752           "expected a global value or an external symbol after 'call-entry'");
1753     }
1754     break;
1755   }
1756   default:
1757     llvm_unreachable("The current token should be pseudo source value");
1758   }
1759   lex();
1760   return false;
1761 }
1762 
1763 bool MIParser::parseMachinePointerInfo(MachinePointerInfo &Dest) {
1764   if (Token.is(MIToken::kw_constant_pool) || Token.is(MIToken::kw_stack) ||
1765       Token.is(MIToken::kw_got) || Token.is(MIToken::kw_jump_table) ||
1766       Token.is(MIToken::FixedStackObject) || Token.is(MIToken::StackObject) ||
1767       Token.is(MIToken::kw_call_entry)) {
1768     const PseudoSourceValue *PSV = nullptr;
1769     if (parseMemoryPseudoSourceValue(PSV))
1770       return true;
1771     int64_t Offset = 0;
1772     if (parseOffset(Offset))
1773       return true;
1774     Dest = MachinePointerInfo(PSV, Offset);
1775     return false;
1776   }
1777   if (Token.isNot(MIToken::NamedIRValue) && Token.isNot(MIToken::IRValue) &&
1778       Token.isNot(MIToken::GlobalValue) &&
1779       Token.isNot(MIToken::NamedGlobalValue) &&
1780       Token.isNot(MIToken::QuotedIRValue))
1781     return error("expected an IR value reference");
1782   const Value *V = nullptr;
1783   if (parseIRValue(V))
1784     return true;
1785   if (!V->getType()->isPointerTy())
1786     return error("expected a pointer IR value");
1787   lex();
1788   int64_t Offset = 0;
1789   if (parseOffset(Offset))
1790     return true;
1791   Dest = MachinePointerInfo(V, Offset);
1792   return false;
1793 }
1794 
1795 bool MIParser::parseMachineMemoryOperand(MachineMemOperand *&Dest) {
1796   if (expectAndConsume(MIToken::lparen))
1797     return true;
1798   MachineMemOperand::Flags Flags = MachineMemOperand::MONone;
1799   while (Token.isMemoryOperandFlag()) {
1800     if (parseMemoryOperandFlag(Flags))
1801       return true;
1802   }
1803   if (Token.isNot(MIToken::Identifier) ||
1804       (Token.stringValue() != "load" && Token.stringValue() != "store"))
1805     return error("expected 'load' or 'store' memory operation");
1806   if (Token.stringValue() == "load")
1807     Flags |= MachineMemOperand::MOLoad;
1808   else
1809     Flags |= MachineMemOperand::MOStore;
1810   lex();
1811 
1812   if (Token.isNot(MIToken::IntegerLiteral))
1813     return error("expected the size integer literal after memory operation");
1814   uint64_t Size;
1815   if (getUint64(Size))
1816     return true;
1817   lex();
1818 
1819   MachinePointerInfo Ptr = MachinePointerInfo();
1820   if (Token.is(MIToken::Identifier)) {
1821     const char *Word = Flags & MachineMemOperand::MOLoad ? "from" : "into";
1822     if (Token.stringValue() != Word)
1823       return error(Twine("expected '") + Word + "'");
1824     lex();
1825 
1826     if (parseMachinePointerInfo(Ptr))
1827       return true;
1828   }
1829   unsigned BaseAlignment = Size;
1830   AAMDNodes AAInfo;
1831   MDNode *Range = nullptr;
1832   while (consumeIfPresent(MIToken::comma)) {
1833     switch (Token.kind()) {
1834     case MIToken::kw_align:
1835       if (parseAlignment(BaseAlignment))
1836         return true;
1837       break;
1838     case MIToken::md_tbaa:
1839       lex();
1840       if (parseMDNode(AAInfo.TBAA))
1841         return true;
1842       break;
1843     case MIToken::md_alias_scope:
1844       lex();
1845       if (parseMDNode(AAInfo.Scope))
1846         return true;
1847       break;
1848     case MIToken::md_noalias:
1849       lex();
1850       if (parseMDNode(AAInfo.NoAlias))
1851         return true;
1852       break;
1853     case MIToken::md_range:
1854       lex();
1855       if (parseMDNode(Range))
1856         return true;
1857       break;
1858     // TODO: Report an error on duplicate metadata nodes.
1859     default:
1860       return error("expected 'align' or '!tbaa' or '!alias.scope' or "
1861                    "'!noalias' or '!range'");
1862     }
1863   }
1864   if (expectAndConsume(MIToken::rparen))
1865     return true;
1866   Dest =
1867       MF.getMachineMemOperand(Ptr, Flags, Size, BaseAlignment, AAInfo, Range);
1868   return false;
1869 }
1870 
1871 void MIParser::initNames2InstrOpCodes() {
1872   if (!Names2InstrOpCodes.empty())
1873     return;
1874   const auto *TII = MF.getSubtarget().getInstrInfo();
1875   assert(TII && "Expected target instruction info");
1876   for (unsigned I = 0, E = TII->getNumOpcodes(); I < E; ++I)
1877     Names2InstrOpCodes.insert(std::make_pair(StringRef(TII->getName(I)), I));
1878 }
1879 
1880 bool MIParser::parseInstrName(StringRef InstrName, unsigned &OpCode) {
1881   initNames2InstrOpCodes();
1882   auto InstrInfo = Names2InstrOpCodes.find(InstrName);
1883   if (InstrInfo == Names2InstrOpCodes.end())
1884     return true;
1885   OpCode = InstrInfo->getValue();
1886   return false;
1887 }
1888 
1889 void MIParser::initNames2Regs() {
1890   if (!Names2Regs.empty())
1891     return;
1892   // The '%noreg' register is the register 0.
1893   Names2Regs.insert(std::make_pair("noreg", 0));
1894   const auto *TRI = MF.getSubtarget().getRegisterInfo();
1895   assert(TRI && "Expected target register info");
1896   for (unsigned I = 0, E = TRI->getNumRegs(); I < E; ++I) {
1897     bool WasInserted =
1898         Names2Regs.insert(std::make_pair(StringRef(TRI->getName(I)).lower(), I))
1899             .second;
1900     (void)WasInserted;
1901     assert(WasInserted && "Expected registers to be unique case-insensitively");
1902   }
1903 }
1904 
1905 bool MIParser::getRegisterByName(StringRef RegName, unsigned &Reg) {
1906   initNames2Regs();
1907   auto RegInfo = Names2Regs.find(RegName);
1908   if (RegInfo == Names2Regs.end())
1909     return true;
1910   Reg = RegInfo->getValue();
1911   return false;
1912 }
1913 
1914 void MIParser::initNames2RegMasks() {
1915   if (!Names2RegMasks.empty())
1916     return;
1917   const auto *TRI = MF.getSubtarget().getRegisterInfo();
1918   assert(TRI && "Expected target register info");
1919   ArrayRef<const uint32_t *> RegMasks = TRI->getRegMasks();
1920   ArrayRef<const char *> RegMaskNames = TRI->getRegMaskNames();
1921   assert(RegMasks.size() == RegMaskNames.size());
1922   for (size_t I = 0, E = RegMasks.size(); I < E; ++I)
1923     Names2RegMasks.insert(
1924         std::make_pair(StringRef(RegMaskNames[I]).lower(), RegMasks[I]));
1925 }
1926 
1927 const uint32_t *MIParser::getRegMask(StringRef Identifier) {
1928   initNames2RegMasks();
1929   auto RegMaskInfo = Names2RegMasks.find(Identifier);
1930   if (RegMaskInfo == Names2RegMasks.end())
1931     return nullptr;
1932   return RegMaskInfo->getValue();
1933 }
1934 
1935 void MIParser::initNames2SubRegIndices() {
1936   if (!Names2SubRegIndices.empty())
1937     return;
1938   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1939   for (unsigned I = 1, E = TRI->getNumSubRegIndices(); I < E; ++I)
1940     Names2SubRegIndices.insert(
1941         std::make_pair(StringRef(TRI->getSubRegIndexName(I)).lower(), I));
1942 }
1943 
1944 unsigned MIParser::getSubRegIndex(StringRef Name) {
1945   initNames2SubRegIndices();
1946   auto SubRegInfo = Names2SubRegIndices.find(Name);
1947   if (SubRegInfo == Names2SubRegIndices.end())
1948     return 0;
1949   return SubRegInfo->getValue();
1950 }
1951 
1952 static void initSlots2BasicBlocks(
1953     const Function &F,
1954     DenseMap<unsigned, const BasicBlock *> &Slots2BasicBlocks) {
1955   ModuleSlotTracker MST(F.getParent(), /*ShouldInitializeAllMetadata=*/false);
1956   MST.incorporateFunction(F);
1957   for (auto &BB : F) {
1958     if (BB.hasName())
1959       continue;
1960     int Slot = MST.getLocalSlot(&BB);
1961     if (Slot == -1)
1962       continue;
1963     Slots2BasicBlocks.insert(std::make_pair(unsigned(Slot), &BB));
1964   }
1965 }
1966 
1967 static const BasicBlock *getIRBlockFromSlot(
1968     unsigned Slot,
1969     const DenseMap<unsigned, const BasicBlock *> &Slots2BasicBlocks) {
1970   auto BlockInfo = Slots2BasicBlocks.find(Slot);
1971   if (BlockInfo == Slots2BasicBlocks.end())
1972     return nullptr;
1973   return BlockInfo->second;
1974 }
1975 
1976 const BasicBlock *MIParser::getIRBlock(unsigned Slot) {
1977   if (Slots2BasicBlocks.empty())
1978     initSlots2BasicBlocks(*MF.getFunction(), Slots2BasicBlocks);
1979   return getIRBlockFromSlot(Slot, Slots2BasicBlocks);
1980 }
1981 
1982 const BasicBlock *MIParser::getIRBlock(unsigned Slot, const Function &F) {
1983   if (&F == MF.getFunction())
1984     return getIRBlock(Slot);
1985   DenseMap<unsigned, const BasicBlock *> CustomSlots2BasicBlocks;
1986   initSlots2BasicBlocks(F, CustomSlots2BasicBlocks);
1987   return getIRBlockFromSlot(Slot, CustomSlots2BasicBlocks);
1988 }
1989 
1990 static void mapValueToSlot(const Value *V, ModuleSlotTracker &MST,
1991                            DenseMap<unsigned, const Value *> &Slots2Values) {
1992   int Slot = MST.getLocalSlot(V);
1993   if (Slot == -1)
1994     return;
1995   Slots2Values.insert(std::make_pair(unsigned(Slot), V));
1996 }
1997 
1998 /// Creates the mapping from slot numbers to function's unnamed IR values.
1999 static void initSlots2Values(const Function &F,
2000                              DenseMap<unsigned, const Value *> &Slots2Values) {
2001   ModuleSlotTracker MST(F.getParent(), /*ShouldInitializeAllMetadata=*/false);
2002   MST.incorporateFunction(F);
2003   for (const auto &Arg : F.args())
2004     mapValueToSlot(&Arg, MST, Slots2Values);
2005   for (const auto &BB : F) {
2006     mapValueToSlot(&BB, MST, Slots2Values);
2007     for (const auto &I : BB)
2008       mapValueToSlot(&I, MST, Slots2Values);
2009   }
2010 }
2011 
2012 const Value *MIParser::getIRValue(unsigned Slot) {
2013   if (Slots2Values.empty())
2014     initSlots2Values(*MF.getFunction(), Slots2Values);
2015   auto ValueInfo = Slots2Values.find(Slot);
2016   if (ValueInfo == Slots2Values.end())
2017     return nullptr;
2018   return ValueInfo->second;
2019 }
2020 
2021 void MIParser::initNames2TargetIndices() {
2022   if (!Names2TargetIndices.empty())
2023     return;
2024   const auto *TII = MF.getSubtarget().getInstrInfo();
2025   assert(TII && "Expected target instruction info");
2026   auto Indices = TII->getSerializableTargetIndices();
2027   for (const auto &I : Indices)
2028     Names2TargetIndices.insert(std::make_pair(StringRef(I.second), I.first));
2029 }
2030 
2031 bool MIParser::getTargetIndex(StringRef Name, int &Index) {
2032   initNames2TargetIndices();
2033   auto IndexInfo = Names2TargetIndices.find(Name);
2034   if (IndexInfo == Names2TargetIndices.end())
2035     return true;
2036   Index = IndexInfo->second;
2037   return false;
2038 }
2039 
2040 void MIParser::initNames2DirectTargetFlags() {
2041   if (!Names2DirectTargetFlags.empty())
2042     return;
2043   const auto *TII = MF.getSubtarget().getInstrInfo();
2044   assert(TII && "Expected target instruction info");
2045   auto Flags = TII->getSerializableDirectMachineOperandTargetFlags();
2046   for (const auto &I : Flags)
2047     Names2DirectTargetFlags.insert(
2048         std::make_pair(StringRef(I.second), I.first));
2049 }
2050 
2051 bool MIParser::getDirectTargetFlag(StringRef Name, unsigned &Flag) {
2052   initNames2DirectTargetFlags();
2053   auto FlagInfo = Names2DirectTargetFlags.find(Name);
2054   if (FlagInfo == Names2DirectTargetFlags.end())
2055     return true;
2056   Flag = FlagInfo->second;
2057   return false;
2058 }
2059 
2060 void MIParser::initNames2BitmaskTargetFlags() {
2061   if (!Names2BitmaskTargetFlags.empty())
2062     return;
2063   const auto *TII = MF.getSubtarget().getInstrInfo();
2064   assert(TII && "Expected target instruction info");
2065   auto Flags = TII->getSerializableBitmaskMachineOperandTargetFlags();
2066   for (const auto &I : Flags)
2067     Names2BitmaskTargetFlags.insert(
2068         std::make_pair(StringRef(I.second), I.first));
2069 }
2070 
2071 bool MIParser::getBitmaskTargetFlag(StringRef Name, unsigned &Flag) {
2072   initNames2BitmaskTargetFlags();
2073   auto FlagInfo = Names2BitmaskTargetFlags.find(Name);
2074   if (FlagInfo == Names2BitmaskTargetFlags.end())
2075     return true;
2076   Flag = FlagInfo->second;
2077   return false;
2078 }
2079 
2080 bool llvm::parseMachineBasicBlockDefinitions(PerFunctionMIParsingState &PFS,
2081                                              StringRef Src,
2082                                              SMDiagnostic &Error) {
2083   return MIParser(PFS, Error, Src).parseBasicBlockDefinitions(PFS.MBBSlots);
2084 }
2085 
2086 bool llvm::parseMachineInstructions(const PerFunctionMIParsingState &PFS,
2087                                     StringRef Src, SMDiagnostic &Error) {
2088   return MIParser(PFS, Error, Src).parseBasicBlocks();
2089 }
2090 
2091 bool llvm::parseMBBReference(const PerFunctionMIParsingState &PFS,
2092                              MachineBasicBlock *&MBB, StringRef Src,
2093                              SMDiagnostic &Error) {
2094   return MIParser(PFS, Error, Src).parseStandaloneMBB(MBB);
2095 }
2096 
2097 bool llvm::parseNamedRegisterReference(const PerFunctionMIParsingState &PFS,
2098                                        unsigned &Reg, StringRef Src,
2099                                        SMDiagnostic &Error) {
2100   return MIParser(PFS, Error, Src).parseStandaloneNamedRegister(Reg);
2101 }
2102 
2103 bool llvm::parseVirtualRegisterReference(const PerFunctionMIParsingState &PFS,
2104                                          unsigned &Reg, StringRef Src,
2105                                          SMDiagnostic &Error) {
2106   return MIParser(PFS, Error, Src).parseStandaloneVirtualRegister(Reg);
2107 }
2108 
2109 bool llvm::parseStackObjectReference(const PerFunctionMIParsingState &PFS,
2110                                      int &FI, StringRef Src,
2111                                      SMDiagnostic &Error) {
2112   return MIParser(PFS, Error, Src).parseStandaloneStackObject(FI);
2113 }
2114 
2115 bool llvm::parseMDNode(const PerFunctionMIParsingState &PFS,
2116                        MDNode *&Node, StringRef Src, SMDiagnostic &Error) {
2117   return MIParser(PFS, Error, Src).parseStandaloneMDNode(Node);
2118 }
2119