blob: f10a9e7cf45e2ec624d0bf75ccf0dcdde7cd5089 [file] [log] [blame]
Alex Lorenz2bdb4e12015-05-27 18:02:19 +00001//===- 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"
Alex Lorenz8e0a1b42015-06-22 17:02:30 +000016#include "MIParser.h"
Alex Lorenz33f0aef2015-06-26 16:46:11 +000017#include "llvm/ADT/DenseMap.h"
Alex Lorenz2bdb4e12015-05-27 18:02:19 +000018#include "llvm/ADT/StringRef.h"
Alex Lorenz735c47e2015-06-15 20:30:22 +000019#include "llvm/ADT/StringMap.h"
Alex Lorenz2bdb4e12015-05-27 18:02:19 +000020#include "llvm/ADT/STLExtras.h"
21#include "llvm/AsmParser/Parser.h"
Alex Lorenz5d6108e2015-06-26 22:56:48 +000022#include "llvm/AsmParser/SlotMapping.h"
Alex Lorenz735c47e2015-06-15 20:30:22 +000023#include "llvm/CodeGen/MachineFunction.h"
Alex Lorenz54565cf2015-06-24 19:56:10 +000024#include "llvm/CodeGen/MachineRegisterInfo.h"
Alex Lorenz78d78312015-05-28 22:41:12 +000025#include "llvm/CodeGen/MIRYamlMapping.h"
Alex Lorenz4f093bf2015-06-19 17:43:07 +000026#include "llvm/IR/BasicBlock.h"
Alex Lorenz735c47e2015-06-15 20:30:22 +000027#include "llvm/IR/DiagnosticInfo.h"
Alex Lorenz8e7a58d72015-06-15 23:07:38 +000028#include "llvm/IR/Instructions.h"
Alex Lorenz735c47e2015-06-15 20:30:22 +000029#include "llvm/IR/LLVMContext.h"
Alex Lorenz2bdb4e12015-05-27 18:02:19 +000030#include "llvm/IR/Module.h"
Alex Lorenz4f093bf2015-06-19 17:43:07 +000031#include "llvm/IR/ValueSymbolTable.h"
Alex Lorenz09b832c2015-05-29 17:05:41 +000032#include "llvm/Support/LineIterator.h"
Alex Lorenz2bdb4e12015-05-27 18:02:19 +000033#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
39using namespace llvm;
40
Alex Lorenz735c47e2015-06-15 20:30:22 +000041namespace llvm {
Alex Lorenz2bdb4e12015-05-27 18:02:19 +000042
43/// This class implements the parsing of LLVM IR that's embedded inside a MIR
44/// file.
45class MIRParserImpl {
46 SourceMgr SM;
47 StringRef Filename;
48 LLVMContext &Context;
Alex Lorenz735c47e2015-06-15 20:30:22 +000049 StringMap<std::unique_ptr<yaml::MachineFunction>> Functions;
Alex Lorenz5d6108e2015-06-26 22:56:48 +000050 SlotMapping IRSlots;
Alex Lorenz2bdb4e12015-05-27 18:02:19 +000051
52public:
53 MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents, StringRef Filename,
54 LLVMContext &Context);
55
Alex Lorenz735c47e2015-06-15 20:30:22 +000056 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
Alex Lorenz78d78312015-05-28 22:41:12 +000063 /// Try to parse the optional LLVM module and the machine functions in the MIR
64 /// file.
Alex Lorenz2bdb4e12015-05-27 18:02:19 +000065 ///
Alex Lorenz78d78312015-05-28 22:41:12 +000066 /// Return null if an error occurred.
Alex Lorenz735c47e2015-06-15 20:30:22 +000067 std::unique_ptr<Module> parse();
Alex Lorenz78d78312015-05-28 22:41:12 +000068
69 /// Parse the machine function in the current YAML document.
70 ///
Alex Lorenz8e7a58d72015-06-15 23:07:38 +000071 /// \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 ///
Alex Lorenz78d78312015-05-28 22:41:12 +000075 /// Return true if an error occurred.
Alex Lorenz8e7a58d72015-06-15 23:07:38 +000076 bool parseMachineFunction(yaml::Input &In, Module &M, bool NoLLVMIR);
Alex Lorenz09b832c2015-05-29 17:05:41 +000077
Alex Lorenz735c47e2015-06-15 20:30:22 +000078 /// 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
Alex Lorenz4f093bf2015-06-19 17:43:07 +000084 /// Initialize the machine basic block using it's YAML representation.
85 ///
86 /// Return true if an error occurred.
Alex Lorenz33f0aef2015-06-26 16:46:11 +000087 bool initializeMachineBasicBlock(
88 MachineFunction &MF, MachineBasicBlock &MBB,
89 const yaml::MachineBasicBlock &YamlMBB,
90 const DenseMap<unsigned, MachineBasicBlock *> &MBBSlots);
Alex Lorenz4f093bf2015-06-19 17:43:07 +000091
Alex Lorenz54565cf2015-06-24 19:56:10 +000092 bool initializeRegisterInfo(MachineRegisterInfo &RegInfo,
93 const yaml::MachineFunction &YamlMF);
94
Alex Lorenz09b832c2015-05-29 17:05:41 +000095private:
Alex Lorenz51af1602015-06-23 22:39:23 +000096 /// Return a MIR diagnostic converted from an MI string diagnostic.
97 SMDiagnostic diagFromMIStringDiag(const SMDiagnostic &Error,
98 SMRange SourceRange);
99
Alex Lorenz09b832c2015-05-29 17:05:41 +0000100 /// Return a MIR diagnostic converted from an LLVM assembly diagnostic.
101 SMDiagnostic diagFromLLVMAssemblyDiag(const SMDiagnostic &Error,
102 SMRange SourceRange);
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000103
104 /// Create an empty function with the given name.
105 void createDummyFunction(StringRef Name, Module &M);
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000106};
107
Alex Lorenz735c47e2015-06-15 20:30:22 +0000108} // end namespace llvm
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000109
110MIRParserImpl::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
Alex Lorenz735c47e2015-06-15 20:30:22 +0000116bool MIRParserImpl::error(const Twine &Message) {
117 Context.diagnose(DiagnosticInfoMIRParser(
118 DS_Error, SMDiagnostic(Filename, SourceMgr::DK_Error, Message.str())));
119 return true;
Alex Lorenz78d78312015-05-28 22:41:12 +0000120}
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000121
Alex Lorenz735c47e2015-06-15 20:30:22 +0000122void 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
138static void handleYAMLDiag(const SMDiagnostic &Diag, void *Context) {
139 reinterpret_cast<MIRParserImpl *>(Context)->reportDiagnostic(Diag);
140}
141
142std::unique_ptr<Module> MIRParserImpl::parse() {
Alex Lorenz78d78312015-05-28 22:41:12 +0000143 yaml::Input In(SM.getMemoryBuffer(SM.getMainFileID())->getBuffer(),
Alex Lorenz735c47e2015-06-15 20:30:22 +0000144 /*Ctxt=*/nullptr, handleYAMLDiag, this);
Alex Lorenz51af1602015-06-23 22:39:23 +0000145 In.setContext(&In);
Alex Lorenz78d78312015-05-28 22:41:12 +0000146
147 if (!In.setCurrentDocument()) {
Alex Lorenz735c47e2015-06-15 20:30:22 +0000148 if (In.error())
Alex Lorenz78d78312015-05-28 22:41:12 +0000149 return nullptr;
150 // Create an empty module when the MIR file is empty.
151 return llvm::make_unique<Module>(Filename, Context);
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000152 }
153
Alex Lorenz78d78312015-05-28 22:41:12 +0000154 std::unique_ptr<Module> M;
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000155 bool NoLLVMIR = false;
Alex Lorenz78d78312015-05-28 22:41:12 +0000156 // 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())) {
Alex Lorenz735c47e2015-06-15 20:30:22 +0000160 SMDiagnostic Error;
Alex Lorenz78d78312015-05-28 22:41:12 +0000161 M = parseAssembly(MemoryBufferRef(BSN->getValue(), Filename), Error,
Alex Lorenz5d6108e2015-06-26 22:56:48 +0000162 Context, &IRSlots);
Alex Lorenz09b832c2015-05-29 17:05:41 +0000163 if (!M) {
Alex Lorenz735c47e2015-06-15 20:30:22 +0000164 reportDiagnostic(diagFromLLVMAssemblyDiag(Error, BSN->getSourceRange()));
Alex Lorenz78d78312015-05-28 22:41:12 +0000165 return M;
Alex Lorenz09b832c2015-05-29 17:05:41 +0000166 }
Alex Lorenz78d78312015-05-28 22:41:12 +0000167 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);
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000173 NoLLVMIR = true;
Alex Lorenz78d78312015-05-28 22:41:12 +0000174 }
175
176 // Parse the machine functions.
177 do {
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000178 if (parseMachineFunction(In, *M, NoLLVMIR))
Alex Lorenz78d78312015-05-28 22:41:12 +0000179 return nullptr;
180 In.nextDocument();
181 } while (In.setCurrentDocument());
182
183 return M;
184}
185
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000186bool MIRParserImpl::parseMachineFunction(yaml::Input &In, Module &M,
187 bool NoLLVMIR) {
Alex Lorenz735c47e2015-06-15 20:30:22 +0000188 auto MF = llvm::make_unique<yaml::MachineFunction>();
189 yaml::yamlize(In, *MF, false);
Alex Lorenz78d78312015-05-28 22:41:12 +0000190 if (In.error())
191 return true;
Alex Lorenz735c47e2015-06-15 20:30:22 +0000192 auto FunctionName = MF->Name;
Alex Lorenzfe2aa972015-06-15 22:23:23 +0000193 if (Functions.find(FunctionName) != Functions.end())
194 return error(Twine("redefinition of machine function '") + FunctionName +
195 "'");
Alex Lorenz735c47e2015-06-15 20:30:22 +0000196 Functions.insert(std::make_pair(FunctionName, std::move(MF)));
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000197 if (NoLLVMIR)
198 createDummyFunction(FunctionName, M);
Alex Lorenz5ef16b82015-06-16 17:06:29 +0000199 else if (!M.getFunction(FunctionName))
200 return error(Twine("function '") + FunctionName +
201 "' isn't defined in the provided LLVM IR");
Alex Lorenz735c47e2015-06-15 20:30:22 +0000202 return false;
203}
204
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000205void 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
Alex Lorenz735c47e2015-06-15 20:30:22 +0000213bool 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.
Alex Lorenz5b5f9752015-06-16 00:10:47 +0000219 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);
Alex Lorenz54565cf2015-06-24 19:56:10 +0000224 if (initializeRegisterInfo(MF.getRegInfo(), YamlMF))
225 return true;
226
Alex Lorenz4f093bf2015-06-19 17:43:07 +0000227 const auto &F = *MF.getFunction();
Alex Lorenz33f0aef2015-06-26 16:46:11 +0000228 DenseMap<unsigned, MachineBasicBlock *> MBBSlots;
Alex Lorenz4f093bf2015-06-19 17:43:07 +0000229 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));
Alex Lorenz00302df2015-06-19 20:12:03 +0000234 if (!BB)
235 return error(Twine("basic block '") + YamlMBB.Name +
236 "' is not defined in the function '" + MF.getName() + "'");
Alex Lorenz4f093bf2015-06-19 17:43:07 +0000237 }
238 auto *MBB = MF.CreateMachineBasicBlock(BB);
239 MF.insert(MF.end(), MBB);
Alex Lorenz33f0aef2015-06-26 16:46:11 +0000240 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))
Alex Lorenz4f093bf2015-06-19 17:43:07 +0000252 return true;
253 }
254 return false;
255}
256
257bool MIRParserImpl::initializeMachineBasicBlock(
Alex Lorenz8e0a1b42015-06-22 17:02:30 +0000258 MachineFunction &MF, MachineBasicBlock &MBB,
Alex Lorenz33f0aef2015-06-26 16:46:11 +0000259 const yaml::MachineBasicBlock &YamlMBB,
260 const DenseMap<unsigned, MachineBasicBlock *> &MBBSlots) {
Alex Lorenz4f093bf2015-06-19 17:43:07 +0000261 MBB.setAlignment(YamlMBB.Alignment);
262 if (YamlMBB.AddressTaken)
263 MBB.setHasAddressTaken();
264 MBB.setIsLandingPad(YamlMBB.IsLandingPad);
Alex Lorenz8e0a1b42015-06-22 17:02:30 +0000265 // Parse the instructions.
266 for (const auto &MISource : YamlMBB.Instructions) {
267 SMDiagnostic Error;
Alex Lorenz3708a642015-06-30 17:47:50 +0000268 MachineInstr *MI = nullptr;
269 if (parseMachineInstr(MI, SM, MF, MISource.Value, MBBSlots, IRSlots,
270 Error)) {
271 reportDiagnostic(diagFromMIStringDiag(Error, MISource.SourceRange));
272 return true;
Alex Lorenz8e0a1b42015-06-22 17:02:30 +0000273 }
Alex Lorenz3708a642015-06-30 17:47:50 +0000274 MBB.insert(MBB.end(), MI);
Alex Lorenz8e0a1b42015-06-22 17:02:30 +0000275 }
Alex Lorenz78d78312015-05-28 22:41:12 +0000276 return false;
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000277}
278
Alex Lorenz54565cf2015-06-24 19:56:10 +0000279bool 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
Alex Lorenz51af1602015-06-23 22:39:23 +0000291SMDiagnostic 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
Alex Lorenz09b832c2015-05-29 17:05:41 +0000307SMDiagnostic 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
Alex Lorenz735c47e2015-06-15 20:30:22 +0000338MIRParser::MIRParser(std::unique_ptr<MIRParserImpl> Impl)
339 : Impl(std::move(Impl)) {}
340
341MIRParser::~MIRParser() {}
342
343std::unique_ptr<Module> MIRParser::parseLLVMModule() { return Impl->parse(); }
344
345bool MIRParser::initializeMachineFunction(MachineFunction &MF) {
346 return Impl->initializeMachineFunction(MF);
347}
348
349std::unique_ptr<MIRParser> llvm::createMIRParserFromFile(StringRef Filename,
350 SMDiagnostic &Error,
351 LLVMContext &Context) {
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000352 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());
Alex Lorenz735c47e2015-06-15 20:30:22 +0000356 return nullptr;
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000357 }
Alex Lorenz735c47e2015-06-15 20:30:22 +0000358 return createMIRParser(std::move(FileOrErr.get()), Context);
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000359}
360
Alex Lorenz735c47e2015-06-15 20:30:22 +0000361std::unique_ptr<MIRParser>
362llvm::createMIRParser(std::unique_ptr<MemoryBuffer> Contents,
363 LLVMContext &Context) {
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000364 auto Filename = Contents->getBufferIdentifier();
Alex Lorenz735c47e2015-06-15 20:30:22 +0000365 return llvm::make_unique<MIRParser>(
366 llvm::make_unique<MIRParserImpl>(std::move(Contents), Filename, Context));
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000367}