blob: 79b2ee6c94888c751d334b2bc99eedc45ceacda4 [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 Lorenz735c47e2015-06-15 20:30:22 +000022#include "llvm/CodeGen/MachineFunction.h"
Alex Lorenz54565cf2015-06-24 19:56:10 +000023#include "llvm/CodeGen/MachineRegisterInfo.h"
Alex Lorenz78d78312015-05-28 22:41:12 +000024#include "llvm/CodeGen/MIRYamlMapping.h"
Alex Lorenz4f093bf2015-06-19 17:43:07 +000025#include "llvm/IR/BasicBlock.h"
Alex Lorenz735c47e2015-06-15 20:30:22 +000026#include "llvm/IR/DiagnosticInfo.h"
Alex Lorenz8e7a58d72015-06-15 23:07:38 +000027#include "llvm/IR/Instructions.h"
Alex Lorenz735c47e2015-06-15 20:30:22 +000028#include "llvm/IR/LLVMContext.h"
Alex Lorenz2bdb4e12015-05-27 18:02:19 +000029#include "llvm/IR/Module.h"
Alex Lorenz4f093bf2015-06-19 17:43:07 +000030#include "llvm/IR/ValueSymbolTable.h"
Alex Lorenz09b832c2015-05-29 17:05:41 +000031#include "llvm/Support/LineIterator.h"
Alex Lorenz2bdb4e12015-05-27 18:02:19 +000032#include "llvm/Support/SMLoc.h"
33#include "llvm/Support/SourceMgr.h"
34#include "llvm/Support/MemoryBuffer.h"
35#include "llvm/Support/YAMLTraits.h"
36#include <memory>
37
38using namespace llvm;
39
Alex Lorenz735c47e2015-06-15 20:30:22 +000040namespace llvm {
Alex Lorenz2bdb4e12015-05-27 18:02:19 +000041
42/// This class implements the parsing of LLVM IR that's embedded inside a MIR
43/// file.
44class MIRParserImpl {
45 SourceMgr SM;
46 StringRef Filename;
47 LLVMContext &Context;
Alex Lorenz735c47e2015-06-15 20:30:22 +000048 StringMap<std::unique_ptr<yaml::MachineFunction>> Functions;
Alex Lorenz2bdb4e12015-05-27 18:02:19 +000049
50public:
51 MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents, StringRef Filename,
52 LLVMContext &Context);
53
Alex Lorenz735c47e2015-06-15 20:30:22 +000054 void reportDiagnostic(const SMDiagnostic &Diag);
55
56 /// Report an error with the given message at unknown location.
57 ///
58 /// Always returns true.
59 bool error(const Twine &Message);
60
Alex Lorenz78d78312015-05-28 22:41:12 +000061 /// Try to parse the optional LLVM module and the machine functions in the MIR
62 /// file.
Alex Lorenz2bdb4e12015-05-27 18:02:19 +000063 ///
Alex Lorenz78d78312015-05-28 22:41:12 +000064 /// Return null if an error occurred.
Alex Lorenz735c47e2015-06-15 20:30:22 +000065 std::unique_ptr<Module> parse();
Alex Lorenz78d78312015-05-28 22:41:12 +000066
67 /// Parse the machine function in the current YAML document.
68 ///
Alex Lorenz8e7a58d72015-06-15 23:07:38 +000069 /// \param NoLLVMIR - set to true when the MIR file doesn't have LLVM IR.
70 /// A dummy IR function is created and inserted into the given module when
71 /// this parameter is true.
72 ///
Alex Lorenz78d78312015-05-28 22:41:12 +000073 /// Return true if an error occurred.
Alex Lorenz8e7a58d72015-06-15 23:07:38 +000074 bool parseMachineFunction(yaml::Input &In, Module &M, bool NoLLVMIR);
Alex Lorenz09b832c2015-05-29 17:05:41 +000075
Alex Lorenz735c47e2015-06-15 20:30:22 +000076 /// Initialize the machine function to the state that's described in the MIR
77 /// file.
78 ///
79 /// Return true if error occurred.
80 bool initializeMachineFunction(MachineFunction &MF);
81
Alex Lorenz4f093bf2015-06-19 17:43:07 +000082 /// Initialize the machine basic block using it's YAML representation.
83 ///
84 /// Return true if an error occurred.
Alex Lorenz33f0aef2015-06-26 16:46:11 +000085 bool initializeMachineBasicBlock(
86 MachineFunction &MF, MachineBasicBlock &MBB,
87 const yaml::MachineBasicBlock &YamlMBB,
88 const DenseMap<unsigned, MachineBasicBlock *> &MBBSlots);
Alex Lorenz4f093bf2015-06-19 17:43:07 +000089
Alex Lorenz54565cf2015-06-24 19:56:10 +000090 bool initializeRegisterInfo(MachineRegisterInfo &RegInfo,
91 const yaml::MachineFunction &YamlMF);
92
Alex Lorenz09b832c2015-05-29 17:05:41 +000093private:
Alex Lorenz51af1602015-06-23 22:39:23 +000094 /// Return a MIR diagnostic converted from an MI string diagnostic.
95 SMDiagnostic diagFromMIStringDiag(const SMDiagnostic &Error,
96 SMRange SourceRange);
97
Alex Lorenz09b832c2015-05-29 17:05:41 +000098 /// Return a MIR diagnostic converted from an LLVM assembly diagnostic.
99 SMDiagnostic diagFromLLVMAssemblyDiag(const SMDiagnostic &Error,
100 SMRange SourceRange);
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000101
102 /// Create an empty function with the given name.
103 void createDummyFunction(StringRef Name, Module &M);
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000104};
105
Alex Lorenz735c47e2015-06-15 20:30:22 +0000106} // end namespace llvm
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000107
108MIRParserImpl::MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents,
109 StringRef Filename, LLVMContext &Context)
110 : SM(), Filename(Filename), Context(Context) {
111 SM.AddNewSourceBuffer(std::move(Contents), SMLoc());
112}
113
Alex Lorenz735c47e2015-06-15 20:30:22 +0000114bool MIRParserImpl::error(const Twine &Message) {
115 Context.diagnose(DiagnosticInfoMIRParser(
116 DS_Error, SMDiagnostic(Filename, SourceMgr::DK_Error, Message.str())));
117 return true;
Alex Lorenz78d78312015-05-28 22:41:12 +0000118}
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000119
Alex Lorenz735c47e2015-06-15 20:30:22 +0000120void MIRParserImpl::reportDiagnostic(const SMDiagnostic &Diag) {
121 DiagnosticSeverity Kind;
122 switch (Diag.getKind()) {
123 case SourceMgr::DK_Error:
124 Kind = DS_Error;
125 break;
126 case SourceMgr::DK_Warning:
127 Kind = DS_Warning;
128 break;
129 case SourceMgr::DK_Note:
130 Kind = DS_Note;
131 break;
132 }
133 Context.diagnose(DiagnosticInfoMIRParser(Kind, Diag));
134}
135
136static void handleYAMLDiag(const SMDiagnostic &Diag, void *Context) {
137 reinterpret_cast<MIRParserImpl *>(Context)->reportDiagnostic(Diag);
138}
139
140std::unique_ptr<Module> MIRParserImpl::parse() {
Alex Lorenz78d78312015-05-28 22:41:12 +0000141 yaml::Input In(SM.getMemoryBuffer(SM.getMainFileID())->getBuffer(),
Alex Lorenz735c47e2015-06-15 20:30:22 +0000142 /*Ctxt=*/nullptr, handleYAMLDiag, this);
Alex Lorenz51af1602015-06-23 22:39:23 +0000143 In.setContext(&In);
Alex Lorenz78d78312015-05-28 22:41:12 +0000144
145 if (!In.setCurrentDocument()) {
Alex Lorenz735c47e2015-06-15 20:30:22 +0000146 if (In.error())
Alex Lorenz78d78312015-05-28 22:41:12 +0000147 return nullptr;
148 // Create an empty module when the MIR file is empty.
149 return llvm::make_unique<Module>(Filename, Context);
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000150 }
151
Alex Lorenz78d78312015-05-28 22:41:12 +0000152 std::unique_ptr<Module> M;
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000153 bool NoLLVMIR = false;
Alex Lorenz78d78312015-05-28 22:41:12 +0000154 // Parse the block scalar manually so that we can return unique pointer
155 // without having to go trough YAML traits.
156 if (const auto *BSN =
157 dyn_cast_or_null<yaml::BlockScalarNode>(In.getCurrentNode())) {
Alex Lorenz735c47e2015-06-15 20:30:22 +0000158 SMDiagnostic Error;
Alex Lorenz78d78312015-05-28 22:41:12 +0000159 M = parseAssembly(MemoryBufferRef(BSN->getValue(), Filename), Error,
160 Context);
Alex Lorenz09b832c2015-05-29 17:05:41 +0000161 if (!M) {
Alex Lorenz735c47e2015-06-15 20:30:22 +0000162 reportDiagnostic(diagFromLLVMAssemblyDiag(Error, BSN->getSourceRange()));
Alex Lorenz78d78312015-05-28 22:41:12 +0000163 return M;
Alex Lorenz09b832c2015-05-29 17:05:41 +0000164 }
Alex Lorenz78d78312015-05-28 22:41:12 +0000165 In.nextDocument();
166 if (!In.setCurrentDocument())
167 return M;
168 } else {
169 // Create an new, empty module.
170 M = llvm::make_unique<Module>(Filename, Context);
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000171 NoLLVMIR = true;
Alex Lorenz78d78312015-05-28 22:41:12 +0000172 }
173
174 // Parse the machine functions.
175 do {
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000176 if (parseMachineFunction(In, *M, NoLLVMIR))
Alex Lorenz78d78312015-05-28 22:41:12 +0000177 return nullptr;
178 In.nextDocument();
179 } while (In.setCurrentDocument());
180
181 return M;
182}
183
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000184bool MIRParserImpl::parseMachineFunction(yaml::Input &In, Module &M,
185 bool NoLLVMIR) {
Alex Lorenz735c47e2015-06-15 20:30:22 +0000186 auto MF = llvm::make_unique<yaml::MachineFunction>();
187 yaml::yamlize(In, *MF, false);
Alex Lorenz78d78312015-05-28 22:41:12 +0000188 if (In.error())
189 return true;
Alex Lorenz735c47e2015-06-15 20:30:22 +0000190 auto FunctionName = MF->Name;
Alex Lorenzfe2aa972015-06-15 22:23:23 +0000191 if (Functions.find(FunctionName) != Functions.end())
192 return error(Twine("redefinition of machine function '") + FunctionName +
193 "'");
Alex Lorenz735c47e2015-06-15 20:30:22 +0000194 Functions.insert(std::make_pair(FunctionName, std::move(MF)));
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000195 if (NoLLVMIR)
196 createDummyFunction(FunctionName, M);
Alex Lorenz5ef16b82015-06-16 17:06:29 +0000197 else if (!M.getFunction(FunctionName))
198 return error(Twine("function '") + FunctionName +
199 "' isn't defined in the provided LLVM IR");
Alex Lorenz735c47e2015-06-15 20:30:22 +0000200 return false;
201}
202
Alex Lorenz8e7a58d72015-06-15 23:07:38 +0000203void MIRParserImpl::createDummyFunction(StringRef Name, Module &M) {
204 auto &Context = M.getContext();
205 Function *F = cast<Function>(M.getOrInsertFunction(
206 Name, FunctionType::get(Type::getVoidTy(Context), false)));
207 BasicBlock *BB = BasicBlock::Create(Context, "entry", F);
208 new UnreachableInst(Context, BB);
209}
210
Alex Lorenz735c47e2015-06-15 20:30:22 +0000211bool MIRParserImpl::initializeMachineFunction(MachineFunction &MF) {
212 auto It = Functions.find(MF.getName());
213 if (It == Functions.end())
214 return error(Twine("no machine function information for function '") +
215 MF.getName() + "' in the MIR file");
216 // TODO: Recreate the machine function.
Alex Lorenz5b5f9752015-06-16 00:10:47 +0000217 const yaml::MachineFunction &YamlMF = *It->getValue();
218 if (YamlMF.Alignment)
219 MF.setAlignment(YamlMF.Alignment);
220 MF.setExposesReturnsTwice(YamlMF.ExposesReturnsTwice);
221 MF.setHasInlineAsm(YamlMF.HasInlineAsm);
Alex Lorenz54565cf2015-06-24 19:56:10 +0000222 if (initializeRegisterInfo(MF.getRegInfo(), YamlMF))
223 return true;
224
Alex Lorenz4f093bf2015-06-19 17:43:07 +0000225 const auto &F = *MF.getFunction();
Alex Lorenz33f0aef2015-06-26 16:46:11 +0000226 DenseMap<unsigned, MachineBasicBlock *> MBBSlots;
Alex Lorenz4f093bf2015-06-19 17:43:07 +0000227 for (const auto &YamlMBB : YamlMF.BasicBlocks) {
228 const BasicBlock *BB = nullptr;
229 if (!YamlMBB.Name.empty()) {
230 BB = dyn_cast_or_null<BasicBlock>(
231 F.getValueSymbolTable().lookup(YamlMBB.Name));
Alex Lorenz00302df2015-06-19 20:12:03 +0000232 if (!BB)
233 return error(Twine("basic block '") + YamlMBB.Name +
234 "' is not defined in the function '" + MF.getName() + "'");
Alex Lorenz4f093bf2015-06-19 17:43:07 +0000235 }
236 auto *MBB = MF.CreateMachineBasicBlock(BB);
237 MF.insert(MF.end(), MBB);
Alex Lorenz33f0aef2015-06-26 16:46:11 +0000238 bool WasInserted = MBBSlots.insert(std::make_pair(YamlMBB.ID, MBB)).second;
239 if (!WasInserted)
240 return error(Twine("redefinition of machine basic block with id #") +
241 Twine(YamlMBB.ID));
242 }
243
244 // Initialize the machine basic blocks after creating them all so that the
245 // machine instructions parser can resolve the MBB references.
246 unsigned I = 0;
247 for (const auto &YamlMBB : YamlMF.BasicBlocks) {
248 if (initializeMachineBasicBlock(MF, *MF.getBlockNumbered(I++), YamlMBB,
249 MBBSlots))
Alex Lorenz4f093bf2015-06-19 17:43:07 +0000250 return true;
251 }
252 return false;
253}
254
255bool MIRParserImpl::initializeMachineBasicBlock(
Alex Lorenz8e0a1b42015-06-22 17:02:30 +0000256 MachineFunction &MF, MachineBasicBlock &MBB,
Alex Lorenz33f0aef2015-06-26 16:46:11 +0000257 const yaml::MachineBasicBlock &YamlMBB,
258 const DenseMap<unsigned, MachineBasicBlock *> &MBBSlots) {
Alex Lorenz4f093bf2015-06-19 17:43:07 +0000259 MBB.setAlignment(YamlMBB.Alignment);
260 if (YamlMBB.AddressTaken)
261 MBB.setHasAddressTaken();
262 MBB.setIsLandingPad(YamlMBB.IsLandingPad);
Alex Lorenz8e0a1b42015-06-22 17:02:30 +0000263 // Parse the instructions.
264 for (const auto &MISource : YamlMBB.Instructions) {
265 SMDiagnostic Error;
Alex Lorenz33f0aef2015-06-26 16:46:11 +0000266 if (auto *MI = parseMachineInstr(SM, MF, MISource.Value, MBBSlots, Error)) {
Alex Lorenz8e0a1b42015-06-22 17:02:30 +0000267 MBB.insert(MBB.end(), MI);
268 continue;
269 }
Alex Lorenz51af1602015-06-23 22:39:23 +0000270 reportDiagnostic(diagFromMIStringDiag(Error, MISource.SourceRange));
Alex Lorenz8e0a1b42015-06-22 17:02:30 +0000271 return true;
272 }
Alex Lorenz78d78312015-05-28 22:41:12 +0000273 return false;
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000274}
275
Alex Lorenz54565cf2015-06-24 19:56:10 +0000276bool MIRParserImpl::initializeRegisterInfo(
277 MachineRegisterInfo &RegInfo, const yaml::MachineFunction &YamlMF) {
278 assert(RegInfo.isSSA());
279 if (!YamlMF.IsSSA)
280 RegInfo.leaveSSA();
281 assert(RegInfo.tracksLiveness());
282 if (!YamlMF.TracksRegLiveness)
283 RegInfo.invalidateLiveness();
284 RegInfo.enableSubRegLiveness(YamlMF.TracksSubRegLiveness);
285 return false;
286}
287
Alex Lorenz51af1602015-06-23 22:39:23 +0000288SMDiagnostic MIRParserImpl::diagFromMIStringDiag(const SMDiagnostic &Error,
289 SMRange SourceRange) {
290 assert(SourceRange.isValid() && "Invalid source range");
291 SMLoc Loc = SourceRange.Start;
292 bool HasQuote = Loc.getPointer() < SourceRange.End.getPointer() &&
293 *Loc.getPointer() == '\'';
294 // Translate the location of the error from the location in the MI string to
295 // the corresponding location in the MIR file.
296 Loc = Loc.getFromPointer(Loc.getPointer() + Error.getColumnNo() +
297 (HasQuote ? 1 : 0));
298
299 // TODO: Translate any source ranges as well.
300 return SM.GetMessage(Loc, Error.getKind(), Error.getMessage(), None,
301 Error.getFixIts());
302}
303
Alex Lorenz09b832c2015-05-29 17:05:41 +0000304SMDiagnostic MIRParserImpl::diagFromLLVMAssemblyDiag(const SMDiagnostic &Error,
305 SMRange SourceRange) {
306 assert(SourceRange.isValid());
307
308 // Translate the location of the error from the location in the llvm IR string
309 // to the corresponding location in the MIR file.
310 auto LineAndColumn = SM.getLineAndColumn(SourceRange.Start);
311 unsigned Line = LineAndColumn.first + Error.getLineNo() - 1;
312 unsigned Column = Error.getColumnNo();
313 StringRef LineStr = Error.getLineContents();
314 SMLoc Loc = Error.getLoc();
315
316 // Get the full line and adjust the column number by taking the indentation of
317 // LLVM IR into account.
318 for (line_iterator L(*SM.getMemoryBuffer(SM.getMainFileID()), false), E;
319 L != E; ++L) {
320 if (L.line_number() == Line) {
321 LineStr = *L;
322 Loc = SMLoc::getFromPointer(LineStr.data());
323 auto Indent = LineStr.find(Error.getLineContents());
324 if (Indent != StringRef::npos)
325 Column += Indent;
326 break;
327 }
328 }
329
330 return SMDiagnostic(SM, Loc, Filename, Line, Column, Error.getKind(),
331 Error.getMessage(), LineStr, Error.getRanges(),
332 Error.getFixIts());
333}
334
Alex Lorenz735c47e2015-06-15 20:30:22 +0000335MIRParser::MIRParser(std::unique_ptr<MIRParserImpl> Impl)
336 : Impl(std::move(Impl)) {}
337
338MIRParser::~MIRParser() {}
339
340std::unique_ptr<Module> MIRParser::parseLLVMModule() { return Impl->parse(); }
341
342bool MIRParser::initializeMachineFunction(MachineFunction &MF) {
343 return Impl->initializeMachineFunction(MF);
344}
345
346std::unique_ptr<MIRParser> llvm::createMIRParserFromFile(StringRef Filename,
347 SMDiagnostic &Error,
348 LLVMContext &Context) {
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000349 auto FileOrErr = MemoryBuffer::getFile(Filename);
350 if (std::error_code EC = FileOrErr.getError()) {
351 Error = SMDiagnostic(Filename, SourceMgr::DK_Error,
352 "Could not open input file: " + EC.message());
Alex Lorenz735c47e2015-06-15 20:30:22 +0000353 return nullptr;
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000354 }
Alex Lorenz735c47e2015-06-15 20:30:22 +0000355 return createMIRParser(std::move(FileOrErr.get()), Context);
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000356}
357
Alex Lorenz735c47e2015-06-15 20:30:22 +0000358std::unique_ptr<MIRParser>
359llvm::createMIRParser(std::unique_ptr<MemoryBuffer> Contents,
360 LLVMContext &Context) {
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000361 auto Filename = Contents->getBufferIdentifier();
Alex Lorenz735c47e2015-06-15 20:30:22 +0000362 return llvm::make_unique<MIRParser>(
363 llvm::make_unique<MIRParserImpl>(std::move(Contents), Filename, Context));
Alex Lorenz2bdb4e12015-05-27 18:02:19 +0000364}