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
46using namespace llvm;
47
48namespace llvm {
49
50/// This class implements the parsing of LLVM IR that's embedded inside a MIR
51/// file.
52class 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
69public:
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
146private:
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
168static void handleYAMLDiag(const SMDiagnostic &Diag, void *Context) {
169  reinterpret_cast<MIRParserImpl *>(Context)->reportDiagnostic(Diag);
170}
171
172MIRParserImpl::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
183bool MIRParserImpl::error(const Twine &Message) {
184  Context.diagnose(DiagnosticInfoMIRParser(
185      DS_Error, SMDiagnostic(Filename, SourceMgr::DK_Error, Message.str())));
186  return true;
187}
188
189bool 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
195bool 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
201void 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
220std::unique_ptr<Module>
221MIRParserImpl::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
258bool 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
272Function *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
286bool 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
322static bool isSSA(const MachineFunction &MF) {
323  const MachineRegisterInfo &MRI = MF.getRegInfo();
324  for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
325    unsigned Reg = Register::index2VirtReg(I);
326    if (!MRI.hasOneDef(Reg) && !MRI.def_empty(Reg))
327      return false;
328  }
329  return true;
330}
331
332void MIRParserImpl::computeFunctionProperties(MachineFunction &MF) {
333  MachineFunctionProperties &Properties = MF.getProperties();
334
335  bool HasPHI = false;
336  bool HasInlineAsm = false;
337  for (const MachineBasicBlock &MBB : MF) {
338    for (const MachineInstr &MI : MBB) {
339      if (MI.isPHI())
340        HasPHI = true;
341      if (MI.isInlineAsm())
342        HasInlineAsm = true;
343    }
344  }
345  if (!HasPHI)
346    Properties.set(MachineFunctionProperties::Property::NoPHIs);
347  MF.setHasInlineAsm(HasInlineAsm);
348
349  if (isSSA(MF))
350    Properties.set(MachineFunctionProperties::Property::IsSSA);
351  else
352    Properties.reset(MachineFunctionProperties::Property::IsSSA);
353
354  const MachineRegisterInfo &MRI = MF.getRegInfo();
355  if (MRI.getNumVirtRegs() == 0)
356    Properties.set(MachineFunctionProperties::Property::NoVRegs);
357}
358
359bool MIRParserImpl::initializeCallSiteInfo(
360    PerFunctionMIParsingState &PFS, const yaml::MachineFunction &YamlMF) {
361  MachineFunction &MF = PFS.MF;
362  SMDiagnostic Error;
363  const LLVMTargetMachine &TM = MF.getTarget();
364  for (auto YamlCSInfo : YamlMF.CallSitesInfo) {
365    yaml::CallSiteInfo::MachineInstrLoc MILoc = YamlCSInfo.CallLocation;
366    if (MILoc.BlockNum >= MF.size())
367      return error(Twine(MF.getName()) +
368                   Twine(" call instruction block out of range.") +
369                   " Unable to reference bb:" + Twine(MILoc.BlockNum));
370    auto CallB = std::next(MF.begin(), MILoc.BlockNum);
371    if (MILoc.Offset >= CallB->size())
372      return error(Twine(MF.getName()) +
373                   Twine(" call instruction offset out of range.") +
374                   " Unable to reference instruction at bb: " +
375                   Twine(MILoc.BlockNum) + " at offset:" + Twine(MILoc.Offset));
376    auto CallI = std::next(CallB->instr_begin(), MILoc.Offset);
377    if (!CallI->isCall(MachineInstr::IgnoreBundle))
378      return error(Twine(MF.getName()) +
379                   Twine(" call site info should reference call "
380                         "instruction. Instruction at bb:") +
381                   Twine(MILoc.BlockNum) + " at offset:" + Twine(MILoc.Offset) +
382                   " is not a call instruction");
383    MachineFunction::CallSiteInfo CSInfo;
384    for (auto ArgRegPair : YamlCSInfo.ArgForwardingRegs) {
385      Register Reg;
386      if (parseNamedRegisterReference(PFS, Reg, ArgRegPair.Reg.Value, Error))
387        return error(Error, ArgRegPair.Reg.SourceRange);
388      CSInfo.emplace_back(Reg, ArgRegPair.ArgNo);
389    }
390
391    if (TM.Options.EmitCallSiteInfo)
392      MF.addCallArgsForwardingRegs(&*CallI, std::move(CSInfo));
393  }
394
395  if (YamlMF.CallSitesInfo.size() && !TM.Options.EmitCallSiteInfo)
396    return error(Twine("Call site info provided but not used"));
397  return false;
398}
399
400bool
401MIRParserImpl::initializeMachineFunction(const yaml::MachineFunction &YamlMF,
402                                         MachineFunction &MF) {
403  // TODO: Recreate the machine function.
404  if (Target) {
405    // Avoid clearing state if we're using the same subtarget again.
406    Target->setTarget(MF.getSubtarget());
407  } else {
408    Target.reset(new PerTargetMIParsingState(MF.getSubtarget()));
409  }
410
411  MF.setAlignment(YamlMF.Alignment.valueOrOne());
412  MF.setExposesReturnsTwice(YamlMF.ExposesReturnsTwice);
413  MF.setHasWinCFI(YamlMF.HasWinCFI);
414
415  if (YamlMF.Legalized)
416    MF.getProperties().set(MachineFunctionProperties::Property::Legalized);
417  if (YamlMF.RegBankSelected)
418    MF.getProperties().set(
419        MachineFunctionProperties::Property::RegBankSelected);
420  if (YamlMF.Selected)
421    MF.getProperties().set(MachineFunctionProperties::Property::Selected);
422  if (YamlMF.FailedISel)
423    MF.getProperties().set(MachineFunctionProperties::Property::FailedISel);
424
425  PerFunctionMIParsingState PFS(MF, SM, IRSlots, *Target);
426  if (parseRegisterInfo(PFS, YamlMF))
427    return true;
428  if (!YamlMF.Constants.empty()) {
429    auto *ConstantPool = MF.getConstantPool();
430    assert(ConstantPool && "Constant pool must be created");
431    if (initializeConstantPool(PFS, *ConstantPool, YamlMF))
432      return true;
433  }
434
435  StringRef BlockStr = YamlMF.Body.Value.Value;
436  SMDiagnostic Error;
437  SourceMgr BlockSM;
438  BlockSM.AddNewSourceBuffer(
439      MemoryBuffer::getMemBuffer(BlockStr, "",/*RequiresNullTerminator=*/false),
440      SMLoc());
441  PFS.SM = &BlockSM;
442  if (parseMachineBasicBlockDefinitions(PFS, BlockStr, Error)) {
443    reportDiagnostic(
444        diagFromBlockStringDiag(Error, YamlMF.Body.Value.SourceRange));
445    return true;
446  }
447  // Check Basic Block Section Flags.
448  if (MF.getTarget().getBBSectionsType() == BasicBlockSection::Labels) {
449    MF.createBBLabels();
450    MF.setBBSectionsType(BasicBlockSection::Labels);
451  } else if (MF.hasBBSections()) {
452    MF.createBBLabels();
453    MF.assignBeginEndSections();
454  }
455  PFS.SM = &SM;
456
457  // Initialize the frame information after creating all the MBBs so that the
458  // MBB references in the frame information can be resolved.
459  if (initializeFrameInfo(PFS, YamlMF))
460    return true;
461  // Initialize the jump table after creating all the MBBs so that the MBB
462  // references can be resolved.
463  if (!YamlMF.JumpTableInfo.Entries.empty() &&
464      initializeJumpTableInfo(PFS, YamlMF.JumpTableInfo))
465    return true;
466  // Parse the machine instructions after creating all of the MBBs so that the
467  // parser can resolve the MBB references.
468  StringRef InsnStr = YamlMF.Body.Value.Value;
469  SourceMgr InsnSM;
470  InsnSM.AddNewSourceBuffer(
471      MemoryBuffer::getMemBuffer(InsnStr, "", /*RequiresNullTerminator=*/false),
472      SMLoc());
473  PFS.SM = &InsnSM;
474  if (parseMachineInstructions(PFS, InsnStr, Error)) {
475    reportDiagnostic(
476        diagFromBlockStringDiag(Error, YamlMF.Body.Value.SourceRange));
477    return true;
478  }
479  PFS.SM = &SM;
480
481  if (setupRegisterInfo(PFS, YamlMF))
482    return true;
483
484  if (YamlMF.MachineFuncInfo) {
485    const LLVMTargetMachine &TM = MF.getTarget();
486    // Note this is called after the initial constructor of the
487    // MachineFunctionInfo based on the MachineFunction, which may depend on the
488    // IR.
489
490    SMRange SrcRange;
491    if (TM.parseMachineFunctionInfo(*YamlMF.MachineFuncInfo, PFS, Error,
492                                    SrcRange)) {
493      return error(Error, SrcRange);
494    }
495  }
496
497  // Set the reserved registers after parsing MachineFuncInfo. The target may
498  // have been recording information used to select the reserved registers
499  // there.
500  // FIXME: This is a temporary workaround until the reserved registers can be
501  // serialized.
502  MachineRegisterInfo &MRI = MF.getRegInfo();
503  MRI.freezeReservedRegs(MF);
504
505  computeFunctionProperties(MF);
506
507  if (initializeCallSiteInfo(PFS, YamlMF))
508    return false;
509
510  MF.getSubtarget().mirFileLoaded(MF);
511
512  MF.verify();
513  return false;
514}
515
516bool MIRParserImpl::parseRegisterInfo(PerFunctionMIParsingState &PFS,
517                                      const yaml::MachineFunction &YamlMF) {
518  MachineFunction &MF = PFS.MF;
519  MachineRegisterInfo &RegInfo = MF.getRegInfo();
520  assert(RegInfo.tracksLiveness());
521  if (!YamlMF.TracksRegLiveness)
522    RegInfo.invalidateLiveness();
523
524  SMDiagnostic Error;
525  // Parse the virtual register information.
526  for (const auto &VReg : YamlMF.VirtualRegisters) {
527    VRegInfo &Info = PFS.getVRegInfo(VReg.ID.Value);
528    if (Info.Explicit)
529      return error(VReg.ID.SourceRange.Start,
530                   Twine("redefinition of virtual register '%") +
531                       Twine(VReg.ID.Value) + "'");
532    Info.Explicit = true;
533
534    if (StringRef(VReg.Class.Value).equals("_")) {
535      Info.Kind = VRegInfo::GENERIC;
536      Info.D.RegBank = nullptr;
537    } else {
538      const auto *RC = Target->getRegClass(VReg.Class.Value);
539      if (RC) {
540        Info.Kind = VRegInfo::NORMAL;
541        Info.D.RC = RC;
542      } else {
543        const RegisterBank *RegBank = Target->getRegBank(VReg.Class.Value);
544        if (!RegBank)
545          return error(
546              VReg.Class.SourceRange.Start,
547              Twine("use of undefined register class or register bank '") +
548                  VReg.Class.Value + "'");
549        Info.Kind = VRegInfo::REGBANK;
550        Info.D.RegBank = RegBank;
551      }
552    }
553
554    if (!VReg.PreferredRegister.Value.empty()) {
555      if (Info.Kind != VRegInfo::NORMAL)
556        return error(VReg.Class.SourceRange.Start,
557              Twine("preferred register can only be set for normal vregs"));
558
559      if (parseRegisterReference(PFS, Info.PreferredReg,
560                                 VReg.PreferredRegister.Value, Error))
561        return error(Error, VReg.PreferredRegister.SourceRange);
562    }
563  }
564
565  // Parse the liveins.
566  for (const auto &LiveIn : YamlMF.LiveIns) {
567    Register Reg;
568    if (parseNamedRegisterReference(PFS, Reg, LiveIn.Register.Value, Error))
569      return error(Error, LiveIn.Register.SourceRange);
570    Register VReg;
571    if (!LiveIn.VirtualRegister.Value.empty()) {
572      VRegInfo *Info;
573      if (parseVirtualRegisterReference(PFS, Info, LiveIn.VirtualRegister.Value,
574                                        Error))
575        return error(Error, LiveIn.VirtualRegister.SourceRange);
576      VReg = Info->VReg;
577    }
578    RegInfo.addLiveIn(Reg, VReg);
579  }
580
581  // Parse the callee saved registers (Registers that will
582  // be saved for the caller).
583  if (YamlMF.CalleeSavedRegisters) {
584    SmallVector<MCPhysReg, 16> CalleeSavedRegisters;
585    for (const auto &RegSource : YamlMF.CalleeSavedRegisters.getValue()) {
586      Register Reg;
587      if (parseNamedRegisterReference(PFS, Reg, RegSource.Value, Error))
588        return error(Error, RegSource.SourceRange);
589      CalleeSavedRegisters.push_back(Reg);
590    }
591    RegInfo.setCalleeSavedRegs(CalleeSavedRegisters);
592  }
593
594  return false;
595}
596
597bool MIRParserImpl::setupRegisterInfo(const PerFunctionMIParsingState &PFS,
598                                      const yaml::MachineFunction &YamlMF) {
599  MachineFunction &MF = PFS.MF;
600  MachineRegisterInfo &MRI = MF.getRegInfo();
601  bool Error = false;
602  // Create VRegs
603  auto populateVRegInfo = [&] (const VRegInfo &Info, Twine Name) {
604    Register Reg = Info.VReg;
605    switch (Info.Kind) {
606    case VRegInfo::UNKNOWN:
607      error(Twine("Cannot determine class/bank of virtual register ") +
608            Name + " in function '" + MF.getName() + "'");
609      Error = true;
610      break;
611    case VRegInfo::NORMAL:
612      MRI.setRegClass(Reg, Info.D.RC);
613      if (Info.PreferredReg != 0)
614        MRI.setSimpleHint(Reg, Info.PreferredReg);
615      break;
616    case VRegInfo::GENERIC:
617      break;
618    case VRegInfo::REGBANK:
619      MRI.setRegBank(Reg, *Info.D.RegBank);
620      break;
621    }
622  };
623
624  for (auto I = PFS.VRegInfosNamed.begin(), E = PFS.VRegInfosNamed.end();
625       I != E; I++) {
626    const VRegInfo &Info = *I->second;
627    populateVRegInfo(Info, Twine(I->first()));
628  }
629
630  for (auto P : PFS.VRegInfos) {
631    const VRegInfo &Info = *P.second;
632    populateVRegInfo(Info, Twine(P.first));
633  }
634
635  // Compute MachineRegisterInfo::UsedPhysRegMask
636  for (const MachineBasicBlock &MBB : MF) {
637    for (const MachineInstr &MI : MBB) {
638      for (const MachineOperand &MO : MI.operands()) {
639        if (!MO.isRegMask())
640          continue;
641        MRI.addPhysRegsUsedFromRegMask(MO.getRegMask());
642      }
643    }
644  }
645
646  return Error;
647}
648
649bool MIRParserImpl::initializeFrameInfo(PerFunctionMIParsingState &PFS,
650                                        const yaml::MachineFunction &YamlMF) {
651  MachineFunction &MF = PFS.MF;
652  MachineFrameInfo &MFI = MF.getFrameInfo();
653  const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
654  const Function &F = MF.getFunction();
655  const yaml::MachineFrameInfo &YamlMFI = YamlMF.FrameInfo;
656  MFI.setFrameAddressIsTaken(YamlMFI.IsFrameAddressTaken);
657  MFI.setReturnAddressIsTaken(YamlMFI.IsReturnAddressTaken);
658  MFI.setHasStackMap(YamlMFI.HasStackMap);
659  MFI.setHasPatchPoint(YamlMFI.HasPatchPoint);
660  MFI.setStackSize(YamlMFI.StackSize);
661  MFI.setOffsetAdjustment(YamlMFI.OffsetAdjustment);
662  if (YamlMFI.MaxAlignment)
663    MFI.ensureMaxAlignment(Align(YamlMFI.MaxAlignment));
664  MFI.setAdjustsStack(YamlMFI.AdjustsStack);
665  MFI.setHasCalls(YamlMFI.HasCalls);
666  if (YamlMFI.MaxCallFrameSize != ~0u)
667    MFI.setMaxCallFrameSize(YamlMFI.MaxCallFrameSize);
668  MFI.setCVBytesOfCalleeSavedRegisters(YamlMFI.CVBytesOfCalleeSavedRegisters);
669  MFI.setHasOpaqueSPAdjustment(YamlMFI.HasOpaqueSPAdjustment);
670  MFI.setHasVAStart(YamlMFI.HasVAStart);
671  MFI.setHasMustTailInVarArgFunc(YamlMFI.HasMustTailInVarArgFunc);
672  MFI.setLocalFrameSize(YamlMFI.LocalFrameSize);
673  if (!YamlMFI.SavePoint.Value.empty()) {
674    MachineBasicBlock *MBB = nullptr;
675    if (parseMBBReference(PFS, MBB, YamlMFI.SavePoint))
676      return true;
677    MFI.setSavePoint(MBB);
678  }
679  if (!YamlMFI.RestorePoint.Value.empty()) {
680    MachineBasicBlock *MBB = nullptr;
681    if (parseMBBReference(PFS, MBB, YamlMFI.RestorePoint))
682      return true;
683    MFI.setRestorePoint(MBB);
684  }
685
686  std::vector<CalleeSavedInfo> CSIInfo;
687  // Initialize the fixed frame objects.
688  for (const auto &Object : YamlMF.FixedStackObjects) {
689    int ObjectIdx;
690    if (Object.Type != yaml::FixedMachineStackObject::SpillSlot)
691      ObjectIdx = MFI.CreateFixedObject(Object.Size, Object.Offset,
692                                        Object.IsImmutable, Object.IsAliased);
693    else
694      ObjectIdx = MFI.CreateFixedSpillStackObject(Object.Size, Object.Offset);
695
696    if (!TFI->isSupportedStackID(Object.StackID))
697      return error(Object.ID.SourceRange.Start,
698                   Twine("StackID is not supported by target"));
699    MFI.setStackID(ObjectIdx, Object.StackID);
700    MFI.setObjectAlignment(ObjectIdx, Object.Alignment.valueOrOne());
701    if (!PFS.FixedStackObjectSlots.insert(std::make_pair(Object.ID.Value,
702                                                         ObjectIdx))
703             .second)
704      return error(Object.ID.SourceRange.Start,
705                   Twine("redefinition of fixed stack object '%fixed-stack.") +
706                       Twine(Object.ID.Value) + "'");
707    if (parseCalleeSavedRegister(PFS, CSIInfo, Object.CalleeSavedRegister,
708                                 Object.CalleeSavedRestored, ObjectIdx))
709      return true;
710    if (parseStackObjectsDebugInfo(PFS, Object, ObjectIdx))
711      return true;
712  }
713
714  // Initialize the ordinary frame objects.
715  for (const auto &Object : YamlMF.StackObjects) {
716    int ObjectIdx;
717    const AllocaInst *Alloca = nullptr;
718    const yaml::StringValue &Name = Object.Name;
719    if (!Name.Value.empty()) {
720      Alloca = dyn_cast_or_null<AllocaInst>(
721          F.getValueSymbolTable()->lookup(Name.Value));
722      if (!Alloca)
723        return error(Name.SourceRange.Start,
724                     "alloca instruction named '" + Name.Value +
725                         "' isn't defined in the function '" + F.getName() +
726                         "'");
727    }
728    if (!TFI->isSupportedStackID(Object.StackID))
729      return error(Object.ID.SourceRange.Start,
730                   Twine("StackID is not supported by target"));
731    if (Object.Type == yaml::MachineStackObject::VariableSized)
732      ObjectIdx =
733          MFI.CreateVariableSizedObject(Object.Alignment.valueOrOne(), Alloca);
734    else
735      ObjectIdx = MFI.CreateStackObject(
736          Object.Size, Object.Alignment.valueOrOne(),
737          Object.Type == yaml::MachineStackObject::SpillSlot, Alloca,
738          Object.StackID);
739    MFI.setObjectOffset(ObjectIdx, Object.Offset);
740
741    if (!PFS.StackObjectSlots.insert(std::make_pair(Object.ID.Value, ObjectIdx))
742             .second)
743      return error(Object.ID.SourceRange.Start,
744                   Twine("redefinition of stack object '%stack.") +
745                       Twine(Object.ID.Value) + "'");
746    if (parseCalleeSavedRegister(PFS, CSIInfo, Object.CalleeSavedRegister,
747                                 Object.CalleeSavedRestored, ObjectIdx))
748      return true;
749    if (Object.LocalOffset)
750      MFI.mapLocalFrameObject(ObjectIdx, Object.LocalOffset.getValue());
751    if (parseStackObjectsDebugInfo(PFS, Object, ObjectIdx))
752      return true;
753  }
754  MFI.setCalleeSavedInfo(CSIInfo);
755  if (!CSIInfo.empty())
756    MFI.setCalleeSavedInfoValid(true);
757
758  // Initialize the various stack object references after initializing the
759  // stack objects.
760  if (!YamlMFI.StackProtector.Value.empty()) {
761    SMDiagnostic Error;
762    int FI;
763    if (parseStackObjectReference(PFS, FI, YamlMFI.StackProtector.Value, Error))
764      return error(Error, YamlMFI.StackProtector.SourceRange);
765    MFI.setStackProtectorIndex(FI);
766  }
767  return false;
768}
769
770bool MIRParserImpl::parseCalleeSavedRegister(PerFunctionMIParsingState &PFS,
771    std::vector<CalleeSavedInfo> &CSIInfo,
772    const yaml::StringValue &RegisterSource, bool IsRestored, int FrameIdx) {
773  if (RegisterSource.Value.empty())
774    return false;
775  Register Reg;
776  SMDiagnostic Error;
777  if (parseNamedRegisterReference(PFS, Reg, RegisterSource.Value, Error))
778    return error(Error, RegisterSource.SourceRange);
779  CalleeSavedInfo CSI(Reg, FrameIdx);
780  CSI.setRestored(IsRestored);
781  CSIInfo.push_back(CSI);
782  return false;
783}
784
785/// Verify that given node is of a certain type. Return true on error.
786template <typename T>
787static bool typecheckMDNode(T *&Result, MDNode *Node,
788                            const yaml::StringValue &Source,
789                            StringRef TypeString, MIRParserImpl &Parser) {
790  if (!Node)
791    return false;
792  Result = dyn_cast<T>(Node);
793  if (!Result)
794    return Parser.error(Source.SourceRange.Start,
795                        "expected a reference to a '" + TypeString +
796                            "' metadata node");
797  return false;
798}
799
800template <typename T>
801bool MIRParserImpl::parseStackObjectsDebugInfo(PerFunctionMIParsingState &PFS,
802    const T &Object, int FrameIdx) {
803  // Debug information can only be attached to stack objects; Fixed stack
804  // objects aren't supported.
805  MDNode *Var = nullptr, *Expr = nullptr, *Loc = nullptr;
806  if (parseMDNode(PFS, Var, Object.DebugVar) ||
807      parseMDNode(PFS, Expr, Object.DebugExpr) ||
808      parseMDNode(PFS, Loc, Object.DebugLoc))
809    return true;
810  if (!Var && !Expr && !Loc)
811    return false;
812  DILocalVariable *DIVar = nullptr;
813  DIExpression *DIExpr = nullptr;
814  DILocation *DILoc = nullptr;
815  if (typecheckMDNode(DIVar, Var, Object.DebugVar, "DILocalVariable", *this) ||
816      typecheckMDNode(DIExpr, Expr, Object.DebugExpr, "DIExpression", *this) ||
817      typecheckMDNode(DILoc, Loc, Object.DebugLoc, "DILocation", *this))
818    return true;
819  PFS.MF.setVariableDbgInfo(DIVar, DIExpr, FrameIdx, DILoc);
820  return false;
821}
822
823bool MIRParserImpl::parseMDNode(PerFunctionMIParsingState &PFS,
824    MDNode *&Node, const yaml::StringValue &Source) {
825  if (Source.Value.empty())
826    return false;
827  SMDiagnostic Error;
828  if (llvm::parseMDNode(PFS, Node, Source.Value, Error))
829    return error(Error, Source.SourceRange);
830  return false;
831}
832
833bool MIRParserImpl::initializeConstantPool(PerFunctionMIParsingState &PFS,
834    MachineConstantPool &ConstantPool, const yaml::MachineFunction &YamlMF) {
835  DenseMap<unsigned, unsigned> &ConstantPoolSlots = PFS.ConstantPoolSlots;
836  const MachineFunction &MF = PFS.MF;
837  const auto &M = *MF.getFunction().getParent();
838  SMDiagnostic Error;
839  for (const auto &YamlConstant : YamlMF.Constants) {
840    if (YamlConstant.IsTargetSpecific)
841      // FIXME: Support target-specific constant pools
842      return error(YamlConstant.Value.SourceRange.Start,
843                   "Can't parse target-specific constant pool entries yet");
844    const Constant *Value = dyn_cast_or_null<Constant>(
845        parseConstantValue(YamlConstant.Value.Value, Error, M));
846    if (!Value)
847      return error(Error, YamlConstant.Value.SourceRange);
848    const Align PrefTypeAlign =
849        M.getDataLayout().getPrefTypeAlign(Value->getType());
850    const Align Alignment = YamlConstant.Alignment.getValueOr(PrefTypeAlign);
851    unsigned Index = ConstantPool.getConstantPoolIndex(Value, Alignment);
852    if (!ConstantPoolSlots.insert(std::make_pair(YamlConstant.ID.Value, Index))
853             .second)
854      return error(YamlConstant.ID.SourceRange.Start,
855                   Twine("redefinition of constant pool item '%const.") +
856                       Twine(YamlConstant.ID.Value) + "'");
857  }
858  return false;
859}
860
861bool MIRParserImpl::initializeJumpTableInfo(PerFunctionMIParsingState &PFS,
862    const yaml::MachineJumpTable &YamlJTI) {
863  MachineJumpTableInfo *JTI = PFS.MF.getOrCreateJumpTableInfo(YamlJTI.Kind);
864  for (const auto &Entry : YamlJTI.Entries) {
865    std::vector<MachineBasicBlock *> Blocks;
866    for (const auto &MBBSource : Entry.Blocks) {
867      MachineBasicBlock *MBB = nullptr;
868      if (parseMBBReference(PFS, MBB, MBBSource.Value))
869        return true;
870      Blocks.push_back(MBB);
871    }
872    unsigned Index = JTI->createJumpTableIndex(Blocks);
873    if (!PFS.JumpTableSlots.insert(std::make_pair(Entry.ID.Value, Index))
874             .second)
875      return error(Entry.ID.SourceRange.Start,
876                   Twine("redefinition of jump table entry '%jump-table.") +
877                       Twine(Entry.ID.Value) + "'");
878  }
879  return false;
880}
881
882bool MIRParserImpl::parseMBBReference(PerFunctionMIParsingState &PFS,
883                                      MachineBasicBlock *&MBB,
884                                      const yaml::StringValue &Source) {
885  SMDiagnostic Error;
886  if (llvm::parseMBBReference(PFS, MBB, Source.Value, Error))
887    return error(Error, Source.SourceRange);
888  return false;
889}
890
891SMDiagnostic MIRParserImpl::diagFromMIStringDiag(const SMDiagnostic &Error,
892                                                 SMRange SourceRange) {
893  assert(SourceRange.isValid() && "Invalid source range");
894  SMLoc Loc = SourceRange.Start;
895  bool HasQuote = Loc.getPointer() < SourceRange.End.getPointer() &&
896                  *Loc.getPointer() == '\'';
897  // Translate the location of the error from the location in the MI string to
898  // the corresponding location in the MIR file.
899  Loc = Loc.getFromPointer(Loc.getPointer() + Error.getColumnNo() +
900                           (HasQuote ? 1 : 0));
901
902  // TODO: Translate any source ranges as well.
903  return SM.GetMessage(Loc, Error.getKind(), Error.getMessage(), None,
904                       Error.getFixIts());
905}
906
907SMDiagnostic MIRParserImpl::diagFromBlockStringDiag(const SMDiagnostic &Error,
908                                                    SMRange SourceRange) {
909  assert(SourceRange.isValid());
910
911  // Translate the location of the error from the location in the llvm IR string
912  // to the corresponding location in the MIR file.
913  auto LineAndColumn = SM.getLineAndColumn(SourceRange.Start);
914  unsigned Line = LineAndColumn.first + Error.getLineNo() - 1;
915  unsigned Column = Error.getColumnNo();
916  StringRef LineStr = Error.getLineContents();
917  SMLoc Loc = Error.getLoc();
918
919  // Get the full line and adjust the column number by taking the indentation of
920  // LLVM IR into account.
921  for (line_iterator L(*SM.getMemoryBuffer(SM.getMainFileID()), false), E;
922       L != E; ++L) {
923    if (L.line_number() == Line) {
924      LineStr = *L;
925      Loc = SMLoc::getFromPointer(LineStr.data());
926      auto Indent = LineStr.find(Error.getLineContents());
927      if (Indent != StringRef::npos)
928        Column += Indent;
929      break;
930    }
931  }
932
933  return SMDiagnostic(SM, Loc, Filename, Line, Column, Error.getKind(),
934                      Error.getMessage(), LineStr, Error.getRanges(),
935                      Error.getFixIts());
936}
937
938MIRParser::MIRParser(std::unique_ptr<MIRParserImpl> Impl)
939    : Impl(std::move(Impl)) {}
940
941MIRParser::~MIRParser() {}
942
943std::unique_ptr<Module>
944MIRParser::parseIRModule(DataLayoutCallbackTy DataLayoutCallback) {
945  return Impl->parseIRModule(DataLayoutCallback);
946}
947
948bool MIRParser::parseMachineFunctions(Module &M, MachineModuleInfo &MMI) {
949  return Impl->parseMachineFunctions(M, MMI);
950}
951
952std::unique_ptr<MIRParser> llvm::createMIRParserFromFile(
953    StringRef Filename, SMDiagnostic &Error, LLVMContext &Context,
954    std::function<void(Function &)> ProcessIRFunction) {
955  auto FileOrErr = MemoryBuffer::getFileOrSTDIN(Filename);
956  if (std::error_code EC = FileOrErr.getError()) {
957    Error = SMDiagnostic(Filename, SourceMgr::DK_Error,
958                         "Could not open input file: " + EC.message());
959    return nullptr;
960  }
961  return createMIRParser(std::move(FileOrErr.get()), Context,
962                         ProcessIRFunction);
963}
964
965std::unique_ptr<MIRParser>
966llvm::createMIRParser(std::unique_ptr<MemoryBuffer> Contents,
967                      LLVMContext &Context,
968                      std::function<void(Function &)> ProcessIRFunction) {
969  auto Filename = Contents->getBufferIdentifier();
970  if (Context.shouldDiscardValueNames()) {
971    Context.diagnose(DiagnosticInfoMIRParser(
972        DS_Error,
973        SMDiagnostic(
974            Filename, SourceMgr::DK_Error,
975            "Can't read MIR with a Context that discards named Values")));
976    return nullptr;
977  }
978  return std::make_unique<MIRParser>(std::make_unique<MIRParserImpl>(
979      std::move(Contents), Filename, Context, ProcessIRFunction));
980}
981