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