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