MIR Parser: Use source locations for MBB naming errors.
[oota-llvm.git] / lib / CodeGen / MIRParser / MIRParser.cpp
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/StringRef.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/AsmParser/Parser.h"
22 #include "llvm/AsmParser/SlotMapping.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/MIRYamlMapping.h"
26 #include "llvm/IR/BasicBlock.h"
27 #include "llvm/IR/DiagnosticInfo.h"
28 #include "llvm/IR/Instructions.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/ValueSymbolTable.h"
32 #include "llvm/Support/LineIterator.h"
33 #include "llvm/Support/SMLoc.h"
34 #include "llvm/Support/SourceMgr.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/YAMLTraits.h"
37 #include <memory>
38
39 using namespace llvm;
40
41 namespace llvm {
42
43 /// This class implements the parsing of LLVM IR that's embedded inside a MIR
44 /// file.
45 class MIRParserImpl {
46   SourceMgr SM;
47   StringRef Filename;
48   LLVMContext &Context;
49   StringMap<std::unique_ptr<yaml::MachineFunction>> Functions;
50   SlotMapping IRSlots;
51
52 public:
53   MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents, StringRef Filename,
54                 LLVMContext &Context);
55
56   void reportDiagnostic(const SMDiagnostic &Diag);
57
58   /// Report an error with the given message at unknown location.
59   ///
60   /// Always returns true.
61   bool error(const Twine &Message);
62
63   /// Report an error with the given message at the given location.
64   ///
65   /// Always returns true.
66   bool error(SMLoc Loc, const Twine &Message);
67
68   /// Report a given error with the location translated from the location in an
69   /// embedded string literal to a location in the MIR file.
70   ///
71   /// Always returns true.
72   bool error(const SMDiagnostic &Error, SMRange SourceRange);
73
74   /// Try to parse the optional LLVM module and the machine functions in the MIR
75   /// file.
76   ///
77   /// Return null if an error occurred.
78   std::unique_ptr<Module> parse();
79
80   /// Parse the machine function in the current YAML document.
81   ///
82   /// \param NoLLVMIR - set to true when the MIR file doesn't have LLVM IR.
83   /// A dummy IR function is created and inserted into the given module when
84   /// this parameter is true.
85   ///
86   /// Return true if an error occurred.
87   bool parseMachineFunction(yaml::Input &In, Module &M, bool NoLLVMIR);
88
89   /// Initialize the machine function to the state that's described in the MIR
90   /// file.
91   ///
92   /// Return true if error occurred.
93   bool initializeMachineFunction(MachineFunction &MF);
94
95   /// Initialize the machine basic block using it's YAML representation.
96   ///
97   /// Return true if an error occurred.
98   bool initializeMachineBasicBlock(MachineFunction &MF, MachineBasicBlock &MBB,
99                                    const yaml::MachineBasicBlock &YamlMBB,
100                                    const PerFunctionMIParsingState &PFS);
101
102   bool initializeRegisterInfo(MachineRegisterInfo &RegInfo,
103                               const yaml::MachineFunction &YamlMF);
104
105 private:
106   /// Return a MIR diagnostic converted from an MI string diagnostic.
107   SMDiagnostic diagFromMIStringDiag(const SMDiagnostic &Error,
108                                     SMRange SourceRange);
109
110   /// Return a MIR diagnostic converted from an LLVM assembly diagnostic.
111   SMDiagnostic diagFromLLVMAssemblyDiag(const SMDiagnostic &Error,
112                                         SMRange SourceRange);
113
114   /// Create an empty function with the given name.
115   void createDummyFunction(StringRef Name, Module &M);
116 };
117
118 } // end namespace llvm
119
120 MIRParserImpl::MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents,
121                              StringRef Filename, LLVMContext &Context)
122     : SM(), Filename(Filename), Context(Context) {
123   SM.AddNewSourceBuffer(std::move(Contents), SMLoc());
124 }
125
126 bool MIRParserImpl::error(const Twine &Message) {
127   Context.diagnose(DiagnosticInfoMIRParser(
128       DS_Error, SMDiagnostic(Filename, SourceMgr::DK_Error, Message.str())));
129   return true;
130 }
131
132 bool MIRParserImpl::error(SMLoc Loc, const Twine &Message) {
133   Context.diagnose(DiagnosticInfoMIRParser(
134       DS_Error, SM.GetMessage(Loc, SourceMgr::DK_Error, Message)));
135   return true;
136 }
137
138 bool MIRParserImpl::error(const SMDiagnostic &Error, SMRange SourceRange) {
139   assert(Error.getKind() == SourceMgr::DK_Error && "Expected an error");
140   reportDiagnostic(diagFromMIStringDiag(Error, SourceRange));
141   return true;
142 }
143
144 void MIRParserImpl::reportDiagnostic(const SMDiagnostic &Diag) {
145   DiagnosticSeverity Kind;
146   switch (Diag.getKind()) {
147   case SourceMgr::DK_Error:
148     Kind = DS_Error;
149     break;
150   case SourceMgr::DK_Warning:
151     Kind = DS_Warning;
152     break;
153   case SourceMgr::DK_Note:
154     Kind = DS_Note;
155     break;
156   }
157   Context.diagnose(DiagnosticInfoMIRParser(Kind, Diag));
158 }
159
160 static void handleYAMLDiag(const SMDiagnostic &Diag, void *Context) {
161   reinterpret_cast<MIRParserImpl *>(Context)->reportDiagnostic(Diag);
162 }
163
164 std::unique_ptr<Module> MIRParserImpl::parse() {
165   yaml::Input In(SM.getMemoryBuffer(SM.getMainFileID())->getBuffer(),
166                  /*Ctxt=*/nullptr, handleYAMLDiag, this);
167   In.setContext(&In);
168
169   if (!In.setCurrentDocument()) {
170     if (In.error())
171       return nullptr;
172     // Create an empty module when the MIR file is empty.
173     return llvm::make_unique<Module>(Filename, Context);
174   }
175
176   std::unique_ptr<Module> M;
177   bool NoLLVMIR = false;
178   // Parse the block scalar manually so that we can return unique pointer
179   // without having to go trough YAML traits.
180   if (const auto *BSN =
181           dyn_cast_or_null<yaml::BlockScalarNode>(In.getCurrentNode())) {
182     SMDiagnostic Error;
183     M = parseAssembly(MemoryBufferRef(BSN->getValue(), Filename), Error,
184                       Context, &IRSlots);
185     if (!M) {
186       reportDiagnostic(diagFromLLVMAssemblyDiag(Error, BSN->getSourceRange()));
187       return M;
188     }
189     In.nextDocument();
190     if (!In.setCurrentDocument())
191       return M;
192   } else {
193     // Create an new, empty module.
194     M = llvm::make_unique<Module>(Filename, Context);
195     NoLLVMIR = true;
196   }
197
198   // Parse the machine functions.
199   do {
200     if (parseMachineFunction(In, *M, NoLLVMIR))
201       return nullptr;
202     In.nextDocument();
203   } while (In.setCurrentDocument());
204
205   return M;
206 }
207
208 bool MIRParserImpl::parseMachineFunction(yaml::Input &In, Module &M,
209                                          bool NoLLVMIR) {
210   auto MF = llvm::make_unique<yaml::MachineFunction>();
211   yaml::yamlize(In, *MF, false);
212   if (In.error())
213     return true;
214   auto FunctionName = MF->Name;
215   if (Functions.find(FunctionName) != Functions.end())
216     return error(Twine("redefinition of machine function '") + FunctionName +
217                  "'");
218   Functions.insert(std::make_pair(FunctionName, std::move(MF)));
219   if (NoLLVMIR)
220     createDummyFunction(FunctionName, M);
221   else if (!M.getFunction(FunctionName))
222     return error(Twine("function '") + FunctionName +
223                  "' isn't defined in the provided LLVM IR");
224   return false;
225 }
226
227 void MIRParserImpl::createDummyFunction(StringRef Name, Module &M) {
228   auto &Context = M.getContext();
229   Function *F = cast<Function>(M.getOrInsertFunction(
230       Name, FunctionType::get(Type::getVoidTy(Context), false)));
231   BasicBlock *BB = BasicBlock::Create(Context, "entry", F);
232   new UnreachableInst(Context, BB);
233 }
234
235 bool MIRParserImpl::initializeMachineFunction(MachineFunction &MF) {
236   auto It = Functions.find(MF.getName());
237   if (It == Functions.end())
238     return error(Twine("no machine function information for function '") +
239                  MF.getName() + "' in the MIR file");
240   // TODO: Recreate the machine function.
241   const yaml::MachineFunction &YamlMF = *It->getValue();
242   if (YamlMF.Alignment)
243     MF.setAlignment(YamlMF.Alignment);
244   MF.setExposesReturnsTwice(YamlMF.ExposesReturnsTwice);
245   MF.setHasInlineAsm(YamlMF.HasInlineAsm);
246   if (initializeRegisterInfo(MF.getRegInfo(), YamlMF))
247     return true;
248
249   PerFunctionMIParsingState PFS;
250   const auto &F = *MF.getFunction();
251   for (const auto &YamlMBB : YamlMF.BasicBlocks) {
252     const BasicBlock *BB = nullptr;
253     const yaml::StringValue &Name = YamlMBB.Name;
254     if (!Name.Value.empty()) {
255       BB = dyn_cast_or_null<BasicBlock>(
256           F.getValueSymbolTable().lookup(Name.Value));
257       if (!BB)
258         return error(Name.SourceRange.Start,
259                      Twine("basic block '") + Name.Value +
260                          "' is not defined in the function '" + MF.getName() +
261                          "'");
262     }
263     auto *MBB = MF.CreateMachineBasicBlock(BB);
264     MF.insert(MF.end(), MBB);
265     bool WasInserted =
266         PFS.MBBSlots.insert(std::make_pair(YamlMBB.ID, MBB)).second;
267     if (!WasInserted)
268       return error(Twine("redefinition of machine basic block with id #") +
269                    Twine(YamlMBB.ID));
270   }
271
272   // Initialize the machine basic blocks after creating them all so that the
273   // machine instructions parser can resolve the MBB references.
274   unsigned I = 0;
275   for (const auto &YamlMBB : YamlMF.BasicBlocks) {
276     if (initializeMachineBasicBlock(MF, *MF.getBlockNumbered(I++), YamlMBB,
277                                     PFS))
278       return true;
279   }
280   return false;
281 }
282
283 bool MIRParserImpl::initializeMachineBasicBlock(
284     MachineFunction &MF, MachineBasicBlock &MBB,
285     const yaml::MachineBasicBlock &YamlMBB,
286     const PerFunctionMIParsingState &PFS) {
287   MBB.setAlignment(YamlMBB.Alignment);
288   if (YamlMBB.AddressTaken)
289     MBB.setHasAddressTaken();
290   MBB.setIsLandingPad(YamlMBB.IsLandingPad);
291   SMDiagnostic Error;
292   // Parse the successors.
293   for (const auto &MBBSource : YamlMBB.Successors) {
294     MachineBasicBlock *SuccMBB = nullptr;
295     if (parseMBBReference(SuccMBB, SM, MF, MBBSource.Value, PFS, IRSlots,
296                           Error))
297       return error(Error, MBBSource.SourceRange);
298     // TODO: Report an error when adding the same successor more than once.
299     MBB.addSuccessor(SuccMBB);
300   }
301   // Parse the instructions.
302   for (const auto &MISource : YamlMBB.Instructions) {
303     MachineInstr *MI = nullptr;
304     if (parseMachineInstr(MI, SM, MF, MISource.Value, PFS, IRSlots, Error))
305       return error(Error, MISource.SourceRange);
306     MBB.insert(MBB.end(), MI);
307   }
308   return false;
309 }
310
311 bool MIRParserImpl::initializeRegisterInfo(
312     MachineRegisterInfo &RegInfo, const yaml::MachineFunction &YamlMF) {
313   assert(RegInfo.isSSA());
314   if (!YamlMF.IsSSA)
315     RegInfo.leaveSSA();
316   assert(RegInfo.tracksLiveness());
317   if (!YamlMF.TracksRegLiveness)
318     RegInfo.invalidateLiveness();
319   RegInfo.enableSubRegLiveness(YamlMF.TracksSubRegLiveness);
320   return false;
321 }
322
323 SMDiagnostic MIRParserImpl::diagFromMIStringDiag(const SMDiagnostic &Error,
324                                                  SMRange SourceRange) {
325   assert(SourceRange.isValid() && "Invalid source range");
326   SMLoc Loc = SourceRange.Start;
327   bool HasQuote = Loc.getPointer() < SourceRange.End.getPointer() &&
328                   *Loc.getPointer() == '\'';
329   // Translate the location of the error from the location in the MI string to
330   // the corresponding location in the MIR file.
331   Loc = Loc.getFromPointer(Loc.getPointer() + Error.getColumnNo() +
332                            (HasQuote ? 1 : 0));
333
334   // TODO: Translate any source ranges as well.
335   return SM.GetMessage(Loc, Error.getKind(), Error.getMessage(), None,
336                        Error.getFixIts());
337 }
338
339 SMDiagnostic MIRParserImpl::diagFromLLVMAssemblyDiag(const SMDiagnostic &Error,
340                                                      SMRange SourceRange) {
341   assert(SourceRange.isValid());
342
343   // Translate the location of the error from the location in the llvm IR string
344   // to the corresponding location in the MIR file.
345   auto LineAndColumn = SM.getLineAndColumn(SourceRange.Start);
346   unsigned Line = LineAndColumn.first + Error.getLineNo() - 1;
347   unsigned Column = Error.getColumnNo();
348   StringRef LineStr = Error.getLineContents();
349   SMLoc Loc = Error.getLoc();
350
351   // Get the full line and adjust the column number by taking the indentation of
352   // LLVM IR into account.
353   for (line_iterator L(*SM.getMemoryBuffer(SM.getMainFileID()), false), E;
354        L != E; ++L) {
355     if (L.line_number() == Line) {
356       LineStr = *L;
357       Loc = SMLoc::getFromPointer(LineStr.data());
358       auto Indent = LineStr.find(Error.getLineContents());
359       if (Indent != StringRef::npos)
360         Column += Indent;
361       break;
362     }
363   }
364
365   return SMDiagnostic(SM, Loc, Filename, Line, Column, Error.getKind(),
366                       Error.getMessage(), LineStr, Error.getRanges(),
367                       Error.getFixIts());
368 }
369
370 MIRParser::MIRParser(std::unique_ptr<MIRParserImpl> Impl)
371     : Impl(std::move(Impl)) {}
372
373 MIRParser::~MIRParser() {}
374
375 std::unique_ptr<Module> MIRParser::parseLLVMModule() { return Impl->parse(); }
376
377 bool MIRParser::initializeMachineFunction(MachineFunction &MF) {
378   return Impl->initializeMachineFunction(MF);
379 }
380
381 std::unique_ptr<MIRParser> llvm::createMIRParserFromFile(StringRef Filename,
382                                                          SMDiagnostic &Error,
383                                                          LLVMContext &Context) {
384   auto FileOrErr = MemoryBuffer::getFile(Filename);
385   if (std::error_code EC = FileOrErr.getError()) {
386     Error = SMDiagnostic(Filename, SourceMgr::DK_Error,
387                          "Could not open input file: " + EC.message());
388     return nullptr;
389   }
390   return createMIRParser(std::move(FileOrErr.get()), Context);
391 }
392
393 std::unique_ptr<MIRParser>
394 llvm::createMIRParser(std::unique_ptr<MemoryBuffer> Contents,
395                       LLVMContext &Context) {
396   auto Filename = Contents->getBufferIdentifier();
397   return llvm::make_unique<MIRParser>(
398       llvm::make_unique<MIRParserImpl>(std::move(Contents), Filename, Context));
399 }