MIR Serialization: Change MIR syntax - use custom syntax for MBBs.
[oota-llvm.git] / lib / CodeGen / MIRParser / MIRParser.cpp
1 //===- MIRParser.cpp - MIR serialization format 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 class that parses the optional LLVM IR and machine
11 // functions that are stored in MIR files.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/CodeGen/MIRParser/MIRParser.h"
16 #include "MIParser.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/AsmParser/Parser.h"
22 #include "llvm/AsmParser/SlotMapping.h"
23 #include "llvm/CodeGen/MachineConstantPool.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/CodeGen/MIRYamlMapping.h"
28 #include "llvm/IR/BasicBlock.h"
29 #include "llvm/IR/DiagnosticInfo.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/LLVMContext.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/ValueSymbolTable.h"
34 #include "llvm/Support/LineIterator.h"
35 #include "llvm/Support/SMLoc.h"
36 #include "llvm/Support/SourceMgr.h"
37 #include "llvm/Support/MemoryBuffer.h"
38 #include "llvm/Support/YAMLTraits.h"
39 #include <memory>
40
41 using namespace llvm;
42
43 namespace llvm {
44
45 /// This class implements the parsing of LLVM IR that's embedded inside a MIR
46 /// file.
47 class MIRParserImpl {
48   SourceMgr SM;
49   StringRef Filename;
50   LLVMContext &Context;
51   StringMap<std::unique_ptr<yaml::MachineFunction>> Functions;
52   SlotMapping IRSlots;
53   /// Maps from register class names to register classes.
54   StringMap<const TargetRegisterClass *> Names2RegClasses;
55
56 public:
57   MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents, StringRef Filename,
58                 LLVMContext &Context);
59
60   void reportDiagnostic(const SMDiagnostic &Diag);
61
62   /// Report an error with the given message at unknown location.
63   ///
64   /// Always returns true.
65   bool error(const Twine &Message);
66
67   /// Report an error with the given message at the given location.
68   ///
69   /// Always returns true.
70   bool error(SMLoc Loc, const Twine &Message);
71
72   /// Report a given error with the location translated from the location in an
73   /// embedded string literal to a location in the MIR file.
74   ///
75   /// Always returns true.
76   bool error(const SMDiagnostic &Error, SMRange SourceRange);
77
78   /// Try to parse the optional LLVM module and the machine functions in the MIR
79   /// file.
80   ///
81   /// Return null if an error occurred.
82   std::unique_ptr<Module> parse();
83
84   /// Parse the machine function in the current YAML document.
85   ///
86   /// \param NoLLVMIR - set to true when the MIR file doesn't have LLVM IR.
87   /// A dummy IR function is created and inserted into the given module when
88   /// this parameter is true.
89   ///
90   /// Return true if an error occurred.
91   bool parseMachineFunction(yaml::Input &In, Module &M, bool NoLLVMIR);
92
93   /// Initialize the machine function to the state that's described in the MIR
94   /// file.
95   ///
96   /// Return true if error occurred.
97   bool initializeMachineFunction(MachineFunction &MF);
98
99   bool initializeRegisterInfo(MachineFunction &MF,
100                               const yaml::MachineFunction &YamlMF,
101                               PerFunctionMIParsingState &PFS);
102
103   void inferRegisterInfo(MachineFunction &MF,
104                          const yaml::MachineFunction &YamlMF);
105
106   bool initializeFrameInfo(MachineFunction &MF,
107                            const yaml::MachineFunction &YamlMF,
108                            PerFunctionMIParsingState &PFS);
109
110   bool parseCalleeSavedRegister(MachineFunction &MF,
111                                 PerFunctionMIParsingState &PFS,
112                                 std::vector<CalleeSavedInfo> &CSIInfo,
113                                 const yaml::StringValue &RegisterSource,
114                                 int FrameIdx);
115
116   bool initializeConstantPool(MachineConstantPool &ConstantPool,
117                               const yaml::MachineFunction &YamlMF,
118                               const MachineFunction &MF,
119                               DenseMap<unsigned, unsigned> &ConstantPoolSlots);
120
121   bool initializeJumpTableInfo(MachineFunction &MF,
122                                const yaml::MachineJumpTable &YamlJTI,
123                                PerFunctionMIParsingState &PFS);
124
125 private:
126   bool parseMBBReference(MachineBasicBlock *&MBB,
127                          const yaml::StringValue &Source, MachineFunction &MF,
128                          const PerFunctionMIParsingState &PFS);
129
130   /// Return a MIR diagnostic converted from an MI string diagnostic.
131   SMDiagnostic diagFromMIStringDiag(const SMDiagnostic &Error,
132                                     SMRange SourceRange);
133
134   /// Return a MIR diagnostic converted from a diagnostic located in a YAML
135   /// block scalar string.
136   SMDiagnostic diagFromBlockStringDiag(const SMDiagnostic &Error,
137                                        SMRange SourceRange);
138
139   /// Create an empty function with the given name.
140   void createDummyFunction(StringRef Name, Module &M);
141
142   void initNames2RegClasses(const MachineFunction &MF);
143
144   /// Check if the given identifier is a name of a register class.
145   ///
146   /// Return null if the name isn't a register class.
147   const TargetRegisterClass *getRegClass(const MachineFunction &MF,
148                                          StringRef Name);
149 };
150
151 } // end namespace llvm
152
153 MIRParserImpl::MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents,
154                              StringRef Filename, LLVMContext &Context)
155     : SM(), Filename(Filename), Context(Context) {
156   SM.AddNewSourceBuffer(std::move(Contents), SMLoc());
157 }
158
159 bool MIRParserImpl::error(const Twine &Message) {
160   Context.diagnose(DiagnosticInfoMIRParser(
161       DS_Error, SMDiagnostic(Filename, SourceMgr::DK_Error, Message.str())));
162   return true;
163 }
164
165 bool MIRParserImpl::error(SMLoc Loc, const Twine &Message) {
166   Context.diagnose(DiagnosticInfoMIRParser(
167       DS_Error, SM.GetMessage(Loc, SourceMgr::DK_Error, Message)));
168   return true;
169 }
170
171 bool MIRParserImpl::error(const SMDiagnostic &Error, SMRange SourceRange) {
172   assert(Error.getKind() == SourceMgr::DK_Error && "Expected an error");
173   reportDiagnostic(diagFromMIStringDiag(Error, SourceRange));
174   return true;
175 }
176
177 void MIRParserImpl::reportDiagnostic(const SMDiagnostic &Diag) {
178   DiagnosticSeverity Kind;
179   switch (Diag.getKind()) {
180   case SourceMgr::DK_Error:
181     Kind = DS_Error;
182     break;
183   case SourceMgr::DK_Warning:
184     Kind = DS_Warning;
185     break;
186   case SourceMgr::DK_Note:
187     Kind = DS_Note;
188     break;
189   }
190   Context.diagnose(DiagnosticInfoMIRParser(Kind, Diag));
191 }
192
193 static void handleYAMLDiag(const SMDiagnostic &Diag, void *Context) {
194   reinterpret_cast<MIRParserImpl *>(Context)->reportDiagnostic(Diag);
195 }
196
197 std::unique_ptr<Module> MIRParserImpl::parse() {
198   yaml::Input In(SM.getMemoryBuffer(SM.getMainFileID())->getBuffer(),
199                  /*Ctxt=*/nullptr, handleYAMLDiag, this);
200   In.setContext(&In);
201
202   if (!In.setCurrentDocument()) {
203     if (In.error())
204       return nullptr;
205     // Create an empty module when the MIR file is empty.
206     return llvm::make_unique<Module>(Filename, Context);
207   }
208
209   std::unique_ptr<Module> M;
210   bool NoLLVMIR = false;
211   // Parse the block scalar manually so that we can return unique pointer
212   // without having to go trough YAML traits.
213   if (const auto *BSN =
214           dyn_cast_or_null<yaml::BlockScalarNode>(In.getCurrentNode())) {
215     SMDiagnostic Error;
216     M = parseAssembly(MemoryBufferRef(BSN->getValue(), Filename), Error,
217                       Context, &IRSlots);
218     if (!M) {
219       reportDiagnostic(diagFromBlockStringDiag(Error, BSN->getSourceRange()));
220       return M;
221     }
222     In.nextDocument();
223     if (!In.setCurrentDocument())
224       return M;
225   } else {
226     // Create an new, empty module.
227     M = llvm::make_unique<Module>(Filename, Context);
228     NoLLVMIR = true;
229   }
230
231   // Parse the machine functions.
232   do {
233     if (parseMachineFunction(In, *M, NoLLVMIR))
234       return nullptr;
235     In.nextDocument();
236   } while (In.setCurrentDocument());
237
238   return M;
239 }
240
241 bool MIRParserImpl::parseMachineFunction(yaml::Input &In, Module &M,
242                                          bool NoLLVMIR) {
243   auto MF = llvm::make_unique<yaml::MachineFunction>();
244   yaml::yamlize(In, *MF, false);
245   if (In.error())
246     return true;
247   auto FunctionName = MF->Name;
248   if (Functions.find(FunctionName) != Functions.end())
249     return error(Twine("redefinition of machine function '") + FunctionName +
250                  "'");
251   Functions.insert(std::make_pair(FunctionName, std::move(MF)));
252   if (NoLLVMIR)
253     createDummyFunction(FunctionName, M);
254   else if (!M.getFunction(FunctionName))
255     return error(Twine("function '") + FunctionName +
256                  "' isn't defined in the provided LLVM IR");
257   return false;
258 }
259
260 void MIRParserImpl::createDummyFunction(StringRef Name, Module &M) {
261   auto &Context = M.getContext();
262   Function *F = cast<Function>(M.getOrInsertFunction(
263       Name, FunctionType::get(Type::getVoidTy(Context), false)));
264   BasicBlock *BB = BasicBlock::Create(Context, "entry", F);
265   new UnreachableInst(Context, BB);
266 }
267
268 bool MIRParserImpl::initializeMachineFunction(MachineFunction &MF) {
269   auto It = Functions.find(MF.getName());
270   if (It == Functions.end())
271     return error(Twine("no machine function information for function '") +
272                  MF.getName() + "' in the MIR file");
273   // TODO: Recreate the machine function.
274   const yaml::MachineFunction &YamlMF = *It->getValue();
275   if (YamlMF.Alignment)
276     MF.setAlignment(YamlMF.Alignment);
277   MF.setExposesReturnsTwice(YamlMF.ExposesReturnsTwice);
278   MF.setHasInlineAsm(YamlMF.HasInlineAsm);
279   PerFunctionMIParsingState PFS;
280   if (initializeRegisterInfo(MF, YamlMF, PFS))
281     return true;
282   if (!YamlMF.Constants.empty()) {
283     auto *ConstantPool = MF.getConstantPool();
284     assert(ConstantPool && "Constant pool must be created");
285     if (initializeConstantPool(*ConstantPool, YamlMF, MF,
286                                PFS.ConstantPoolSlots))
287       return true;
288   }
289
290   SMDiagnostic Error;
291   if (parseMachineBasicBlockDefinitions(MF, YamlMF.Body.Value.Value, PFS,
292                                         IRSlots, Error)) {
293     reportDiagnostic(
294         diagFromBlockStringDiag(Error, YamlMF.Body.Value.SourceRange));
295     return true;
296   }
297
298   if (MF.empty())
299     return error(Twine("machine function '") + Twine(MF.getName()) +
300                  "' requires at least one machine basic block in its body");
301   // Initialize the frame information after creating all the MBBs so that the
302   // MBB references in the frame information can be resolved.
303   if (initializeFrameInfo(MF, YamlMF, PFS))
304     return true;
305   // Initialize the jump table after creating all the MBBs so that the MBB
306   // references can be resolved.
307   if (!YamlMF.JumpTableInfo.Entries.empty() &&
308       initializeJumpTableInfo(MF, YamlMF.JumpTableInfo, PFS))
309     return true;
310   // Parse the machine instructions after creating all of the MBBs so that the
311   // parser can resolve the MBB references.
312   if (parseMachineInstructions(MF, YamlMF.Body.Value.Value, PFS, IRSlots,
313                                Error)) {
314     reportDiagnostic(
315         diagFromBlockStringDiag(Error, YamlMF.Body.Value.SourceRange));
316     return true;
317   }
318   inferRegisterInfo(MF, YamlMF);
319   // FIXME: This is a temporary workaround until the reserved registers can be
320   // serialized.
321   MF.getRegInfo().freezeReservedRegs(MF);
322   MF.verify();
323   return false;
324 }
325
326 bool MIRParserImpl::initializeRegisterInfo(MachineFunction &MF,
327                                            const yaml::MachineFunction &YamlMF,
328                                            PerFunctionMIParsingState &PFS) {
329   MachineRegisterInfo &RegInfo = MF.getRegInfo();
330   assert(RegInfo.isSSA());
331   if (!YamlMF.IsSSA)
332     RegInfo.leaveSSA();
333   assert(RegInfo.tracksLiveness());
334   if (!YamlMF.TracksRegLiveness)
335     RegInfo.invalidateLiveness();
336   RegInfo.enableSubRegLiveness(YamlMF.TracksSubRegLiveness);
337
338   SMDiagnostic Error;
339   // Parse the virtual register information.
340   for (const auto &VReg : YamlMF.VirtualRegisters) {
341     const auto *RC = getRegClass(MF, VReg.Class.Value);
342     if (!RC)
343       return error(VReg.Class.SourceRange.Start,
344                    Twine("use of undefined register class '") +
345                        VReg.Class.Value + "'");
346     unsigned Reg = RegInfo.createVirtualRegister(RC);
347     if (!PFS.VirtualRegisterSlots.insert(std::make_pair(VReg.ID.Value, Reg))
348              .second)
349       return error(VReg.ID.SourceRange.Start,
350                    Twine("redefinition of virtual register '%") +
351                        Twine(VReg.ID.Value) + "'");
352     if (!VReg.PreferredRegister.Value.empty()) {
353       unsigned PreferredReg = 0;
354       if (parseNamedRegisterReference(PreferredReg, SM, MF,
355                                       VReg.PreferredRegister.Value, PFS,
356                                       IRSlots, Error))
357         return error(Error, VReg.PreferredRegister.SourceRange);
358       RegInfo.setSimpleHint(Reg, PreferredReg);
359     }
360   }
361
362   // Parse the liveins.
363   for (const auto &LiveIn : YamlMF.LiveIns) {
364     unsigned Reg = 0;
365     if (parseNamedRegisterReference(Reg, SM, MF, LiveIn.Register.Value, PFS,
366                                     IRSlots, Error))
367       return error(Error, LiveIn.Register.SourceRange);
368     unsigned VReg = 0;
369     if (!LiveIn.VirtualRegister.Value.empty()) {
370       if (parseVirtualRegisterReference(
371               VReg, SM, MF, LiveIn.VirtualRegister.Value, PFS, IRSlots, Error))
372         return error(Error, LiveIn.VirtualRegister.SourceRange);
373     }
374     RegInfo.addLiveIn(Reg, VReg);
375   }
376
377   // Parse the callee saved register mask.
378   BitVector CalleeSavedRegisterMask(RegInfo.getUsedPhysRegsMask().size());
379   if (!YamlMF.CalleeSavedRegisters)
380     return false;
381   for (const auto &RegSource : YamlMF.CalleeSavedRegisters.getValue()) {
382     unsigned Reg = 0;
383     if (parseNamedRegisterReference(Reg, SM, MF, RegSource.Value, PFS, IRSlots,
384                                     Error))
385       return error(Error, RegSource.SourceRange);
386     CalleeSavedRegisterMask[Reg] = true;
387   }
388   RegInfo.setUsedPhysRegMask(CalleeSavedRegisterMask.flip());
389   return false;
390 }
391
392 void MIRParserImpl::inferRegisterInfo(MachineFunction &MF,
393                                       const yaml::MachineFunction &YamlMF) {
394   if (YamlMF.CalleeSavedRegisters)
395     return;
396   for (const MachineBasicBlock &MBB : MF) {
397     for (const MachineInstr &MI : MBB) {
398       for (const MachineOperand &MO : MI.operands()) {
399         if (!MO.isRegMask())
400           continue;
401         MF.getRegInfo().addPhysRegsUsedFromRegMask(MO.getRegMask());
402       }
403     }
404   }
405 }
406
407 bool MIRParserImpl::initializeFrameInfo(MachineFunction &MF,
408                                         const yaml::MachineFunction &YamlMF,
409                                         PerFunctionMIParsingState &PFS) {
410   MachineFrameInfo &MFI = *MF.getFrameInfo();
411   const Function &F = *MF.getFunction();
412   const yaml::MachineFrameInfo &YamlMFI = YamlMF.FrameInfo;
413   MFI.setFrameAddressIsTaken(YamlMFI.IsFrameAddressTaken);
414   MFI.setReturnAddressIsTaken(YamlMFI.IsReturnAddressTaken);
415   MFI.setHasStackMap(YamlMFI.HasStackMap);
416   MFI.setHasPatchPoint(YamlMFI.HasPatchPoint);
417   MFI.setStackSize(YamlMFI.StackSize);
418   MFI.setOffsetAdjustment(YamlMFI.OffsetAdjustment);
419   if (YamlMFI.MaxAlignment)
420     MFI.ensureMaxAlignment(YamlMFI.MaxAlignment);
421   MFI.setAdjustsStack(YamlMFI.AdjustsStack);
422   MFI.setHasCalls(YamlMFI.HasCalls);
423   MFI.setMaxCallFrameSize(YamlMFI.MaxCallFrameSize);
424   MFI.setHasOpaqueSPAdjustment(YamlMFI.HasOpaqueSPAdjustment);
425   MFI.setHasVAStart(YamlMFI.HasVAStart);
426   MFI.setHasMustTailInVarArgFunc(YamlMFI.HasMustTailInVarArgFunc);
427   if (!YamlMFI.SavePoint.Value.empty()) {
428     MachineBasicBlock *MBB = nullptr;
429     if (parseMBBReference(MBB, YamlMFI.SavePoint, MF, PFS))
430       return true;
431     MFI.setSavePoint(MBB);
432   }
433   if (!YamlMFI.RestorePoint.Value.empty()) {
434     MachineBasicBlock *MBB = nullptr;
435     if (parseMBBReference(MBB, YamlMFI.RestorePoint, MF, PFS))
436       return true;
437     MFI.setRestorePoint(MBB);
438   }
439
440   std::vector<CalleeSavedInfo> CSIInfo;
441   // Initialize the fixed frame objects.
442   for (const auto &Object : YamlMF.FixedStackObjects) {
443     int ObjectIdx;
444     if (Object.Type != yaml::FixedMachineStackObject::SpillSlot)
445       ObjectIdx = MFI.CreateFixedObject(Object.Size, Object.Offset,
446                                         Object.IsImmutable, Object.IsAliased);
447     else
448       ObjectIdx = MFI.CreateFixedSpillStackObject(Object.Size, Object.Offset);
449     MFI.setObjectAlignment(ObjectIdx, Object.Alignment);
450     if (!PFS.FixedStackObjectSlots.insert(std::make_pair(Object.ID.Value,
451                                                          ObjectIdx))
452              .second)
453       return error(Object.ID.SourceRange.Start,
454                    Twine("redefinition of fixed stack object '%fixed-stack.") +
455                        Twine(Object.ID.Value) + "'");
456     if (parseCalleeSavedRegister(MF, PFS, CSIInfo, Object.CalleeSavedRegister,
457                                  ObjectIdx))
458       return true;
459   }
460
461   // Initialize the ordinary frame objects.
462   for (const auto &Object : YamlMF.StackObjects) {
463     int ObjectIdx;
464     const AllocaInst *Alloca = nullptr;
465     const yaml::StringValue &Name = Object.Name;
466     if (!Name.Value.empty()) {
467       Alloca = dyn_cast_or_null<AllocaInst>(
468           F.getValueSymbolTable().lookup(Name.Value));
469       if (!Alloca)
470         return error(Name.SourceRange.Start,
471                      "alloca instruction named '" + Name.Value +
472                          "' isn't defined in the function '" + F.getName() +
473                          "'");
474     }
475     if (Object.Type == yaml::MachineStackObject::VariableSized)
476       ObjectIdx = MFI.CreateVariableSizedObject(Object.Alignment, Alloca);
477     else
478       ObjectIdx = MFI.CreateStackObject(
479           Object.Size, Object.Alignment,
480           Object.Type == yaml::MachineStackObject::SpillSlot, Alloca);
481     MFI.setObjectOffset(ObjectIdx, Object.Offset);
482     if (!PFS.StackObjectSlots.insert(std::make_pair(Object.ID.Value, ObjectIdx))
483              .second)
484       return error(Object.ID.SourceRange.Start,
485                    Twine("redefinition of stack object '%stack.") +
486                        Twine(Object.ID.Value) + "'");
487     if (parseCalleeSavedRegister(MF, PFS, CSIInfo, Object.CalleeSavedRegister,
488                                  ObjectIdx))
489       return true;
490   }
491   MFI.setCalleeSavedInfo(CSIInfo);
492   if (!CSIInfo.empty())
493     MFI.setCalleeSavedInfoValid(true);
494   return false;
495 }
496
497 bool MIRParserImpl::parseCalleeSavedRegister(
498     MachineFunction &MF, PerFunctionMIParsingState &PFS,
499     std::vector<CalleeSavedInfo> &CSIInfo,
500     const yaml::StringValue &RegisterSource, int FrameIdx) {
501   if (RegisterSource.Value.empty())
502     return false;
503   unsigned Reg = 0;
504   SMDiagnostic Error;
505   if (parseNamedRegisterReference(Reg, SM, MF, RegisterSource.Value, PFS,
506                                   IRSlots, Error))
507     return error(Error, RegisterSource.SourceRange);
508   CSIInfo.push_back(CalleeSavedInfo(Reg, FrameIdx));
509   return false;
510 }
511
512 bool MIRParserImpl::initializeConstantPool(
513     MachineConstantPool &ConstantPool, const yaml::MachineFunction &YamlMF,
514     const MachineFunction &MF,
515     DenseMap<unsigned, unsigned> &ConstantPoolSlots) {
516   const auto &M = *MF.getFunction()->getParent();
517   SMDiagnostic Error;
518   for (const auto &YamlConstant : YamlMF.Constants) {
519     const Constant *Value = dyn_cast_or_null<Constant>(
520         parseConstantValue(YamlConstant.Value.Value, Error, M));
521     if (!Value)
522       return error(Error, YamlConstant.Value.SourceRange);
523     unsigned Alignment =
524         YamlConstant.Alignment
525             ? YamlConstant.Alignment
526             : M.getDataLayout().getPrefTypeAlignment(Value->getType());
527     unsigned Index = ConstantPool.getConstantPoolIndex(Value, Alignment);
528     if (!ConstantPoolSlots.insert(std::make_pair(YamlConstant.ID.Value, Index))
529              .second)
530       return error(YamlConstant.ID.SourceRange.Start,
531                    Twine("redefinition of constant pool item '%const.") +
532                        Twine(YamlConstant.ID.Value) + "'");
533   }
534   return false;
535 }
536
537 bool MIRParserImpl::initializeJumpTableInfo(
538     MachineFunction &MF, const yaml::MachineJumpTable &YamlJTI,
539     PerFunctionMIParsingState &PFS) {
540   MachineJumpTableInfo *JTI = MF.getOrCreateJumpTableInfo(YamlJTI.Kind);
541   for (const auto &Entry : YamlJTI.Entries) {
542     std::vector<MachineBasicBlock *> Blocks;
543     for (const auto &MBBSource : Entry.Blocks) {
544       MachineBasicBlock *MBB = nullptr;
545       if (parseMBBReference(MBB, MBBSource.Value, MF, PFS))
546         return true;
547       Blocks.push_back(MBB);
548     }
549     unsigned Index = JTI->createJumpTableIndex(Blocks);
550     if (!PFS.JumpTableSlots.insert(std::make_pair(Entry.ID.Value, Index))
551              .second)
552       return error(Entry.ID.SourceRange.Start,
553                    Twine("redefinition of jump table entry '%jump-table.") +
554                        Twine(Entry.ID.Value) + "'");
555   }
556   return false;
557 }
558
559 bool MIRParserImpl::parseMBBReference(MachineBasicBlock *&MBB,
560                                       const yaml::StringValue &Source,
561                                       MachineFunction &MF,
562                                       const PerFunctionMIParsingState &PFS) {
563   SMDiagnostic Error;
564   if (llvm::parseMBBReference(MBB, SM, MF, Source.Value, PFS, IRSlots, Error))
565     return error(Error, Source.SourceRange);
566   return false;
567 }
568
569 SMDiagnostic MIRParserImpl::diagFromMIStringDiag(const SMDiagnostic &Error,
570                                                  SMRange SourceRange) {
571   assert(SourceRange.isValid() && "Invalid source range");
572   SMLoc Loc = SourceRange.Start;
573   bool HasQuote = Loc.getPointer() < SourceRange.End.getPointer() &&
574                   *Loc.getPointer() == '\'';
575   // Translate the location of the error from the location in the MI string to
576   // the corresponding location in the MIR file.
577   Loc = Loc.getFromPointer(Loc.getPointer() + Error.getColumnNo() +
578                            (HasQuote ? 1 : 0));
579
580   // TODO: Translate any source ranges as well.
581   return SM.GetMessage(Loc, Error.getKind(), Error.getMessage(), None,
582                        Error.getFixIts());
583 }
584
585 SMDiagnostic MIRParserImpl::diagFromBlockStringDiag(const SMDiagnostic &Error,
586                                                     SMRange SourceRange) {
587   assert(SourceRange.isValid());
588
589   // Translate the location of the error from the location in the llvm IR string
590   // to the corresponding location in the MIR file.
591   auto LineAndColumn = SM.getLineAndColumn(SourceRange.Start);
592   unsigned Line = LineAndColumn.first + Error.getLineNo() - 1;
593   unsigned Column = Error.getColumnNo();
594   StringRef LineStr = Error.getLineContents();
595   SMLoc Loc = Error.getLoc();
596
597   // Get the full line and adjust the column number by taking the indentation of
598   // LLVM IR into account.
599   for (line_iterator L(*SM.getMemoryBuffer(SM.getMainFileID()), false), E;
600        L != E; ++L) {
601     if (L.line_number() == Line) {
602       LineStr = *L;
603       Loc = SMLoc::getFromPointer(LineStr.data());
604       auto Indent = LineStr.find(Error.getLineContents());
605       if (Indent != StringRef::npos)
606         Column += Indent;
607       break;
608     }
609   }
610
611   return SMDiagnostic(SM, Loc, Filename, Line, Column, Error.getKind(),
612                       Error.getMessage(), LineStr, Error.getRanges(),
613                       Error.getFixIts());
614 }
615
616 void MIRParserImpl::initNames2RegClasses(const MachineFunction &MF) {
617   if (!Names2RegClasses.empty())
618     return;
619   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
620   for (unsigned I = 0, E = TRI->getNumRegClasses(); I < E; ++I) {
621     const auto *RC = TRI->getRegClass(I);
622     Names2RegClasses.insert(
623         std::make_pair(StringRef(TRI->getRegClassName(RC)).lower(), RC));
624   }
625 }
626
627 const TargetRegisterClass *MIRParserImpl::getRegClass(const MachineFunction &MF,
628                                                       StringRef Name) {
629   initNames2RegClasses(MF);
630   auto RegClassInfo = Names2RegClasses.find(Name);
631   if (RegClassInfo == Names2RegClasses.end())
632     return nullptr;
633   return RegClassInfo->getValue();
634 }
635
636 MIRParser::MIRParser(std::unique_ptr<MIRParserImpl> Impl)
637     : Impl(std::move(Impl)) {}
638
639 MIRParser::~MIRParser() {}
640
641 std::unique_ptr<Module> MIRParser::parseLLVMModule() { return Impl->parse(); }
642
643 bool MIRParser::initializeMachineFunction(MachineFunction &MF) {
644   return Impl->initializeMachineFunction(MF);
645 }
646
647 std::unique_ptr<MIRParser> llvm::createMIRParserFromFile(StringRef Filename,
648                                                          SMDiagnostic &Error,
649                                                          LLVMContext &Context) {
650   auto FileOrErr = MemoryBuffer::getFile(Filename);
651   if (std::error_code EC = FileOrErr.getError()) {
652     Error = SMDiagnostic(Filename, SourceMgr::DK_Error,
653                          "Could not open input file: " + EC.message());
654     return nullptr;
655   }
656   return createMIRParser(std::move(FileOrErr.get()), Context);
657 }
658
659 std::unique_ptr<MIRParser>
660 llvm::createMIRParser(std::unique_ptr<MemoryBuffer> Contents,
661                       LLVMContext &Context) {
662   auto Filename = Contents->getBufferIdentifier();
663   return llvm::make_unique<MIRParser>(
664       llvm::make_unique<MIRParserImpl>(std::move(Contents), Filename, Context));
665 }