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