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