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