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