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