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