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