MIR Serialization: Connect the machine function analysis pass to the MIR parser.
[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 "llvm/ADT/StringRef.h"
17 #include "llvm/ADT/StringMap.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/AsmParser/Parser.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MIRYamlMapping.h"
22 #include "llvm/IR/DiagnosticInfo.h"
23 #include "llvm/IR/LLVMContext.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/Support/LineIterator.h"
26 #include "llvm/Support/SMLoc.h"
27 #include "llvm/Support/SourceMgr.h"
28 #include "llvm/Support/MemoryBuffer.h"
29 #include "llvm/Support/YAMLTraits.h"
30 #include <memory>
31
32 using namespace llvm;
33
34 namespace llvm {
35
36 /// This class implements the parsing of LLVM IR that's embedded inside a MIR
37 /// file.
38 class MIRParserImpl {
39   SourceMgr SM;
40   StringRef Filename;
41   LLVMContext &Context;
42   StringMap<std::unique_ptr<yaml::MachineFunction>> Functions;
43
44 public:
45   MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents, StringRef Filename,
46                 LLVMContext &Context);
47
48   void reportDiagnostic(const SMDiagnostic &Diag);
49
50   /// Report an error with the given message at unknown location.
51   ///
52   /// Always returns true.
53   bool error(const Twine &Message);
54
55   /// Try to parse the optional LLVM module and the machine functions in the MIR
56   /// file.
57   ///
58   /// Return null if an error occurred.
59   std::unique_ptr<Module> parse();
60
61   /// Parse the machine function in the current YAML document.
62   ///
63   /// Return true if an error occurred.
64   bool parseMachineFunction(yaml::Input &In);
65
66   /// Initialize the machine function to the state that's described in the MIR
67   /// file.
68   ///
69   /// Return true if error occurred.
70   bool initializeMachineFunction(MachineFunction &MF);
71
72 private:
73   /// Return a MIR diagnostic converted from an LLVM assembly diagnostic.
74   SMDiagnostic diagFromLLVMAssemblyDiag(const SMDiagnostic &Error,
75                                         SMRange SourceRange);
76 };
77
78 } // end namespace llvm
79
80 MIRParserImpl::MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents,
81                              StringRef Filename, LLVMContext &Context)
82     : SM(), Filename(Filename), Context(Context) {
83   SM.AddNewSourceBuffer(std::move(Contents), SMLoc());
84 }
85
86 bool MIRParserImpl::error(const Twine &Message) {
87   Context.diagnose(DiagnosticInfoMIRParser(
88       DS_Error, SMDiagnostic(Filename, SourceMgr::DK_Error, Message.str())));
89   return true;
90 }
91
92 void MIRParserImpl::reportDiagnostic(const SMDiagnostic &Diag) {
93   DiagnosticSeverity Kind;
94   switch (Diag.getKind()) {
95   case SourceMgr::DK_Error:
96     Kind = DS_Error;
97     break;
98   case SourceMgr::DK_Warning:
99     Kind = DS_Warning;
100     break;
101   case SourceMgr::DK_Note:
102     Kind = DS_Note;
103     break;
104   }
105   Context.diagnose(DiagnosticInfoMIRParser(Kind, Diag));
106 }
107
108 static void handleYAMLDiag(const SMDiagnostic &Diag, void *Context) {
109   reinterpret_cast<MIRParserImpl *>(Context)->reportDiagnostic(Diag);
110 }
111
112 std::unique_ptr<Module> MIRParserImpl::parse() {
113   yaml::Input In(SM.getMemoryBuffer(SM.getMainFileID())->getBuffer(),
114                  /*Ctxt=*/nullptr, handleYAMLDiag, this);
115
116   if (!In.setCurrentDocument()) {
117     if (In.error())
118       return nullptr;
119     // Create an empty module when the MIR file is empty.
120     return llvm::make_unique<Module>(Filename, Context);
121   }
122
123   std::unique_ptr<Module> M;
124   // Parse the block scalar manually so that we can return unique pointer
125   // without having to go trough YAML traits.
126   if (const auto *BSN =
127           dyn_cast_or_null<yaml::BlockScalarNode>(In.getCurrentNode())) {
128     SMDiagnostic Error;
129     M = parseAssembly(MemoryBufferRef(BSN->getValue(), Filename), Error,
130                       Context);
131     if (!M) {
132       reportDiagnostic(diagFromLLVMAssemblyDiag(Error, BSN->getSourceRange()));
133       return M;
134     }
135     In.nextDocument();
136     if (!In.setCurrentDocument())
137       return M;
138   } else {
139     // Create an new, empty module.
140     M = llvm::make_unique<Module>(Filename, Context);
141   }
142
143   // Parse the machine functions.
144   do {
145     if (parseMachineFunction(In))
146       return nullptr;
147     In.nextDocument();
148   } while (In.setCurrentDocument());
149
150   return M;
151 }
152
153 bool MIRParserImpl::parseMachineFunction(yaml::Input &In) {
154   auto MF = llvm::make_unique<yaml::MachineFunction>();
155   yaml::yamlize(In, *MF, false);
156   if (In.error())
157     return true;
158   auto FunctionName = MF->Name;
159   Functions.insert(std::make_pair(FunctionName, std::move(MF)));
160   return false;
161 }
162
163 bool MIRParserImpl::initializeMachineFunction(MachineFunction &MF) {
164   auto It = Functions.find(MF.getName());
165   if (It == Functions.end())
166     return error(Twine("no machine function information for function '") +
167                  MF.getName() + "' in the MIR file");
168   // TODO: Recreate the machine function.
169   return false;
170 }
171
172 SMDiagnostic MIRParserImpl::diagFromLLVMAssemblyDiag(const SMDiagnostic &Error,
173                                                      SMRange SourceRange) {
174   assert(SourceRange.isValid());
175
176   // Translate the location of the error from the location in the llvm IR string
177   // to the corresponding location in the MIR file.
178   auto LineAndColumn = SM.getLineAndColumn(SourceRange.Start);
179   unsigned Line = LineAndColumn.first + Error.getLineNo() - 1;
180   unsigned Column = Error.getColumnNo();
181   StringRef LineStr = Error.getLineContents();
182   SMLoc Loc = Error.getLoc();
183
184   // Get the full line and adjust the column number by taking the indentation of
185   // LLVM IR into account.
186   for (line_iterator L(*SM.getMemoryBuffer(SM.getMainFileID()), false), E;
187        L != E; ++L) {
188     if (L.line_number() == Line) {
189       LineStr = *L;
190       Loc = SMLoc::getFromPointer(LineStr.data());
191       auto Indent = LineStr.find(Error.getLineContents());
192       if (Indent != StringRef::npos)
193         Column += Indent;
194       break;
195     }
196   }
197
198   return SMDiagnostic(SM, Loc, Filename, Line, Column, Error.getKind(),
199                       Error.getMessage(), LineStr, Error.getRanges(),
200                       Error.getFixIts());
201 }
202
203 MIRParser::MIRParser(std::unique_ptr<MIRParserImpl> Impl)
204     : Impl(std::move(Impl)) {}
205
206 MIRParser::~MIRParser() {}
207
208 std::unique_ptr<Module> MIRParser::parseLLVMModule() { return Impl->parse(); }
209
210 bool MIRParser::initializeMachineFunction(MachineFunction &MF) {
211   return Impl->initializeMachineFunction(MF);
212 }
213
214 std::unique_ptr<MIRParser> llvm::createMIRParserFromFile(StringRef Filename,
215                                                          SMDiagnostic &Error,
216                                                          LLVMContext &Context) {
217   auto FileOrErr = MemoryBuffer::getFile(Filename);
218   if (std::error_code EC = FileOrErr.getError()) {
219     Error = SMDiagnostic(Filename, SourceMgr::DK_Error,
220                          "Could not open input file: " + EC.message());
221     return nullptr;
222   }
223   return createMIRParser(std::move(FileOrErr.get()), Context);
224 }
225
226 std::unique_ptr<MIRParser>
227 llvm::createMIRParser(std::unique_ptr<MemoryBuffer> Contents,
228                       LLVMContext &Context) {
229   auto Filename = Contents->getBufferIdentifier();
230   return llvm::make_unique<MIRParser>(
231       llvm::make_unique<MIRParserImpl>(std::move(Contents), Filename, Context));
232 }