1 //===- MIRParser.cpp - MIR serialization format parser implementation -----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the class that parses the optional LLVM IR and machine
11 // functions that are stored in MIR files.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/CodeGen/MIRParser/MIRParser.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"
43 /// This class implements the parsing of LLVM IR that's embedded inside a MIR
49 StringMap<std::unique_ptr<yaml::MachineFunction>> Functions;
53 MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents, StringRef Filename,
54 LLVMContext &Context);
56 void reportDiagnostic(const SMDiagnostic &Diag);
58 /// Report an error with the given message at unknown location.
60 /// Always returns true.
61 bool error(const Twine &Message);
63 /// Report an error with the given message at the given location.
65 /// Always returns true.
66 bool error(SMLoc Loc, const Twine &Message);
68 /// Report a given error with the location translated from the location in an
69 /// embedded string literal to a location in the MIR file.
71 /// Always returns true.
72 bool error(const SMDiagnostic &Error, SMRange SourceRange);
74 /// Try to parse the optional LLVM module and the machine functions in the MIR
77 /// Return null if an error occurred.
78 std::unique_ptr<Module> parse();
80 /// Parse the machine function in the current YAML document.
82 /// \param NoLLVMIR - set to true when the MIR file doesn't have LLVM IR.
83 /// A dummy IR function is created and inserted into the given module when
84 /// this parameter is true.
86 /// Return true if an error occurred.
87 bool parseMachineFunction(yaml::Input &In, Module &M, bool NoLLVMIR);
89 /// Initialize the machine function to the state that's described in the MIR
92 /// Return true if error occurred.
93 bool initializeMachineFunction(MachineFunction &MF);
95 /// Initialize the machine basic block using it's YAML representation.
97 /// Return true if an error occurred.
98 bool initializeMachineBasicBlock(MachineFunction &MF, MachineBasicBlock &MBB,
99 const yaml::MachineBasicBlock &YamlMBB,
100 const PerFunctionMIParsingState &PFS);
102 bool initializeRegisterInfo(MachineRegisterInfo &RegInfo,
103 const yaml::MachineFunction &YamlMF);
106 /// Return a MIR diagnostic converted from an MI string diagnostic.
107 SMDiagnostic diagFromMIStringDiag(const SMDiagnostic &Error,
108 SMRange SourceRange);
110 /// Return a MIR diagnostic converted from an LLVM assembly diagnostic.
111 SMDiagnostic diagFromLLVMAssemblyDiag(const SMDiagnostic &Error,
112 SMRange SourceRange);
114 /// Create an empty function with the given name.
115 void createDummyFunction(StringRef Name, Module &M);
118 } // end namespace llvm
120 MIRParserImpl::MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents,
121 StringRef Filename, LLVMContext &Context)
122 : SM(), Filename(Filename), Context(Context) {
123 SM.AddNewSourceBuffer(std::move(Contents), SMLoc());
126 bool MIRParserImpl::error(const Twine &Message) {
127 Context.diagnose(DiagnosticInfoMIRParser(
128 DS_Error, SMDiagnostic(Filename, SourceMgr::DK_Error, Message.str())));
132 bool MIRParserImpl::error(SMLoc Loc, const Twine &Message) {
133 Context.diagnose(DiagnosticInfoMIRParser(
134 DS_Error, SM.GetMessage(Loc, SourceMgr::DK_Error, Message)));
138 bool MIRParserImpl::error(const SMDiagnostic &Error, SMRange SourceRange) {
139 assert(Error.getKind() == SourceMgr::DK_Error && "Expected an error");
140 reportDiagnostic(diagFromMIStringDiag(Error, SourceRange));
144 void MIRParserImpl::reportDiagnostic(const SMDiagnostic &Diag) {
145 DiagnosticSeverity Kind;
146 switch (Diag.getKind()) {
147 case SourceMgr::DK_Error:
150 case SourceMgr::DK_Warning:
153 case SourceMgr::DK_Note:
157 Context.diagnose(DiagnosticInfoMIRParser(Kind, Diag));
160 static void handleYAMLDiag(const SMDiagnostic &Diag, void *Context) {
161 reinterpret_cast<MIRParserImpl *>(Context)->reportDiagnostic(Diag);
164 std::unique_ptr<Module> MIRParserImpl::parse() {
165 yaml::Input In(SM.getMemoryBuffer(SM.getMainFileID())->getBuffer(),
166 /*Ctxt=*/nullptr, handleYAMLDiag, this);
169 if (!In.setCurrentDocument()) {
172 // Create an empty module when the MIR file is empty.
173 return llvm::make_unique<Module>(Filename, Context);
176 std::unique_ptr<Module> M;
177 bool NoLLVMIR = false;
178 // Parse the block scalar manually so that we can return unique pointer
179 // without having to go trough YAML traits.
180 if (const auto *BSN =
181 dyn_cast_or_null<yaml::BlockScalarNode>(In.getCurrentNode())) {
183 M = parseAssembly(MemoryBufferRef(BSN->getValue(), Filename), Error,
186 reportDiagnostic(diagFromLLVMAssemblyDiag(Error, BSN->getSourceRange()));
190 if (!In.setCurrentDocument())
193 // Create an new, empty module.
194 M = llvm::make_unique<Module>(Filename, Context);
198 // Parse the machine functions.
200 if (parseMachineFunction(In, *M, NoLLVMIR))
203 } while (In.setCurrentDocument());
208 bool MIRParserImpl::parseMachineFunction(yaml::Input &In, Module &M,
210 auto MF = llvm::make_unique<yaml::MachineFunction>();
211 yaml::yamlize(In, *MF, false);
214 auto FunctionName = MF->Name;
215 if (Functions.find(FunctionName) != Functions.end())
216 return error(Twine("redefinition of machine function '") + FunctionName +
218 Functions.insert(std::make_pair(FunctionName, std::move(MF)));
220 createDummyFunction(FunctionName, M);
221 else if (!M.getFunction(FunctionName))
222 return error(Twine("function '") + FunctionName +
223 "' isn't defined in the provided LLVM IR");
227 void MIRParserImpl::createDummyFunction(StringRef Name, Module &M) {
228 auto &Context = M.getContext();
229 Function *F = cast<Function>(M.getOrInsertFunction(
230 Name, FunctionType::get(Type::getVoidTy(Context), false)));
231 BasicBlock *BB = BasicBlock::Create(Context, "entry", F);
232 new UnreachableInst(Context, BB);
235 bool MIRParserImpl::initializeMachineFunction(MachineFunction &MF) {
236 auto It = Functions.find(MF.getName());
237 if (It == Functions.end())
238 return error(Twine("no machine function information for function '") +
239 MF.getName() + "' in the MIR file");
240 // TODO: Recreate the machine function.
241 const yaml::MachineFunction &YamlMF = *It->getValue();
242 if (YamlMF.Alignment)
243 MF.setAlignment(YamlMF.Alignment);
244 MF.setExposesReturnsTwice(YamlMF.ExposesReturnsTwice);
245 MF.setHasInlineAsm(YamlMF.HasInlineAsm);
246 if (initializeRegisterInfo(MF.getRegInfo(), YamlMF))
249 PerFunctionMIParsingState PFS;
250 const auto &F = *MF.getFunction();
251 for (const auto &YamlMBB : YamlMF.BasicBlocks) {
252 const BasicBlock *BB = nullptr;
253 const yaml::StringValue &Name = YamlMBB.Name;
254 if (!Name.Value.empty()) {
255 BB = dyn_cast_or_null<BasicBlock>(
256 F.getValueSymbolTable().lookup(Name.Value));
258 return error(Name.SourceRange.Start,
259 Twine("basic block '") + Name.Value +
260 "' is not defined in the function '" + MF.getName() +
263 auto *MBB = MF.CreateMachineBasicBlock(BB);
264 MF.insert(MF.end(), MBB);
266 PFS.MBBSlots.insert(std::make_pair(YamlMBB.ID, MBB)).second;
268 return error(Twine("redefinition of machine basic block with id #") +
272 // Initialize the machine basic blocks after creating them all so that the
273 // machine instructions parser can resolve the MBB references.
275 for (const auto &YamlMBB : YamlMF.BasicBlocks) {
276 if (initializeMachineBasicBlock(MF, *MF.getBlockNumbered(I++), YamlMBB,
283 bool MIRParserImpl::initializeMachineBasicBlock(
284 MachineFunction &MF, MachineBasicBlock &MBB,
285 const yaml::MachineBasicBlock &YamlMBB,
286 const PerFunctionMIParsingState &PFS) {
287 MBB.setAlignment(YamlMBB.Alignment);
288 if (YamlMBB.AddressTaken)
289 MBB.setHasAddressTaken();
290 MBB.setIsLandingPad(YamlMBB.IsLandingPad);
292 // Parse the successors.
293 for (const auto &MBBSource : YamlMBB.Successors) {
294 MachineBasicBlock *SuccMBB = nullptr;
295 if (parseMBBReference(SuccMBB, SM, MF, MBBSource.Value, PFS, IRSlots,
297 return error(Error, MBBSource.SourceRange);
298 // TODO: Report an error when adding the same successor more than once.
299 MBB.addSuccessor(SuccMBB);
301 // Parse the instructions.
302 for (const auto &MISource : YamlMBB.Instructions) {
303 MachineInstr *MI = nullptr;
304 if (parseMachineInstr(MI, SM, MF, MISource.Value, PFS, IRSlots, Error))
305 return error(Error, MISource.SourceRange);
306 MBB.insert(MBB.end(), MI);
311 bool MIRParserImpl::initializeRegisterInfo(
312 MachineRegisterInfo &RegInfo, const yaml::MachineFunction &YamlMF) {
313 assert(RegInfo.isSSA());
316 assert(RegInfo.tracksLiveness());
317 if (!YamlMF.TracksRegLiveness)
318 RegInfo.invalidateLiveness();
319 RegInfo.enableSubRegLiveness(YamlMF.TracksSubRegLiveness);
323 SMDiagnostic MIRParserImpl::diagFromMIStringDiag(const SMDiagnostic &Error,
324 SMRange SourceRange) {
325 assert(SourceRange.isValid() && "Invalid source range");
326 SMLoc Loc = SourceRange.Start;
327 bool HasQuote = Loc.getPointer() < SourceRange.End.getPointer() &&
328 *Loc.getPointer() == '\'';
329 // Translate the location of the error from the location in the MI string to
330 // the corresponding location in the MIR file.
331 Loc = Loc.getFromPointer(Loc.getPointer() + Error.getColumnNo() +
334 // TODO: Translate any source ranges as well.
335 return SM.GetMessage(Loc, Error.getKind(), Error.getMessage(), None,
339 SMDiagnostic MIRParserImpl::diagFromLLVMAssemblyDiag(const SMDiagnostic &Error,
340 SMRange SourceRange) {
341 assert(SourceRange.isValid());
343 // Translate the location of the error from the location in the llvm IR string
344 // to the corresponding location in the MIR file.
345 auto LineAndColumn = SM.getLineAndColumn(SourceRange.Start);
346 unsigned Line = LineAndColumn.first + Error.getLineNo() - 1;
347 unsigned Column = Error.getColumnNo();
348 StringRef LineStr = Error.getLineContents();
349 SMLoc Loc = Error.getLoc();
351 // Get the full line and adjust the column number by taking the indentation of
352 // LLVM IR into account.
353 for (line_iterator L(*SM.getMemoryBuffer(SM.getMainFileID()), false), E;
355 if (L.line_number() == Line) {
357 Loc = SMLoc::getFromPointer(LineStr.data());
358 auto Indent = LineStr.find(Error.getLineContents());
359 if (Indent != StringRef::npos)
365 return SMDiagnostic(SM, Loc, Filename, Line, Column, Error.getKind(),
366 Error.getMessage(), LineStr, Error.getRanges(),
370 MIRParser::MIRParser(std::unique_ptr<MIRParserImpl> Impl)
371 : Impl(std::move(Impl)) {}
373 MIRParser::~MIRParser() {}
375 std::unique_ptr<Module> MIRParser::parseLLVMModule() { return Impl->parse(); }
377 bool MIRParser::initializeMachineFunction(MachineFunction &MF) {
378 return Impl->initializeMachineFunction(MF);
381 std::unique_ptr<MIRParser> llvm::createMIRParserFromFile(StringRef Filename,
383 LLVMContext &Context) {
384 auto FileOrErr = MemoryBuffer::getFile(Filename);
385 if (std::error_code EC = FileOrErr.getError()) {
386 Error = SMDiagnostic(Filename, SourceMgr::DK_Error,
387 "Could not open input file: " + EC.message());
390 return createMIRParser(std::move(FileOrErr.get()), Context);
393 std::unique_ptr<MIRParser>
394 llvm::createMIRParser(std::unique_ptr<MemoryBuffer> Contents,
395 LLVMContext &Context) {
396 auto Filename = Contents->getBufferIdentifier();
397 return llvm::make_unique<MIRParser>(
398 llvm::make_unique<MIRParserImpl>(std::move(Contents), Filename, Context));