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