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