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