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