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"
16 #include "llvm/ADT/StringRef.h"
17 #include "llvm/ADT/StringMap.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/AsmParser/Parser.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MIRYamlMapping.h"
22 #include "llvm/IR/DiagnosticInfo.h"
23 #include "llvm/IR/Instructions.h"
24 #include "llvm/IR/LLVMContext.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/Support/LineIterator.h"
27 #include "llvm/Support/SMLoc.h"
28 #include "llvm/Support/SourceMgr.h"
29 #include "llvm/Support/MemoryBuffer.h"
30 #include "llvm/Support/YAMLTraits.h"
37 /// This class implements the parsing of LLVM IR that's embedded inside a MIR
43 StringMap<std::unique_ptr<yaml::MachineFunction>> Functions;
46 MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents, StringRef Filename,
47 LLVMContext &Context);
49 void reportDiagnostic(const SMDiagnostic &Diag);
51 /// Report an error with the given message at unknown location.
53 /// Always returns true.
54 bool error(const Twine &Message);
56 /// Try to parse the optional LLVM module and the machine functions in the MIR
59 /// Return null if an error occurred.
60 std::unique_ptr<Module> parse();
62 /// Parse the machine function in the current YAML document.
64 /// \param NoLLVMIR - set to true when the MIR file doesn't have LLVM IR.
65 /// A dummy IR function is created and inserted into the given module when
66 /// this parameter is true.
68 /// Return true if an error occurred.
69 bool parseMachineFunction(yaml::Input &In, Module &M, bool NoLLVMIR);
71 /// Initialize the machine function to the state that's described in the MIR
74 /// Return true if error occurred.
75 bool initializeMachineFunction(MachineFunction &MF);
78 /// Return a MIR diagnostic converted from an LLVM assembly diagnostic.
79 SMDiagnostic diagFromLLVMAssemblyDiag(const SMDiagnostic &Error,
82 /// Create an empty function with the given name.
83 void createDummyFunction(StringRef Name, Module &M);
86 } // end namespace llvm
88 MIRParserImpl::MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents,
89 StringRef Filename, LLVMContext &Context)
90 : SM(), Filename(Filename), Context(Context) {
91 SM.AddNewSourceBuffer(std::move(Contents), SMLoc());
94 bool MIRParserImpl::error(const Twine &Message) {
95 Context.diagnose(DiagnosticInfoMIRParser(
96 DS_Error, SMDiagnostic(Filename, SourceMgr::DK_Error, Message.str())));
100 void MIRParserImpl::reportDiagnostic(const SMDiagnostic &Diag) {
101 DiagnosticSeverity Kind;
102 switch (Diag.getKind()) {
103 case SourceMgr::DK_Error:
106 case SourceMgr::DK_Warning:
109 case SourceMgr::DK_Note:
113 Context.diagnose(DiagnosticInfoMIRParser(Kind, Diag));
116 static void handleYAMLDiag(const SMDiagnostic &Diag, void *Context) {
117 reinterpret_cast<MIRParserImpl *>(Context)->reportDiagnostic(Diag);
120 std::unique_ptr<Module> MIRParserImpl::parse() {
121 yaml::Input In(SM.getMemoryBuffer(SM.getMainFileID())->getBuffer(),
122 /*Ctxt=*/nullptr, handleYAMLDiag, this);
124 if (!In.setCurrentDocument()) {
127 // Create an empty module when the MIR file is empty.
128 return llvm::make_unique<Module>(Filename, Context);
131 std::unique_ptr<Module> M;
132 bool NoLLVMIR = false;
133 // Parse the block scalar manually so that we can return unique pointer
134 // without having to go trough YAML traits.
135 if (const auto *BSN =
136 dyn_cast_or_null<yaml::BlockScalarNode>(In.getCurrentNode())) {
138 M = parseAssembly(MemoryBufferRef(BSN->getValue(), Filename), Error,
141 reportDiagnostic(diagFromLLVMAssemblyDiag(Error, BSN->getSourceRange()));
145 if (!In.setCurrentDocument())
148 // Create an new, empty module.
149 M = llvm::make_unique<Module>(Filename, Context);
153 // Parse the machine functions.
155 if (parseMachineFunction(In, *M, NoLLVMIR))
158 } while (In.setCurrentDocument());
163 bool MIRParserImpl::parseMachineFunction(yaml::Input &In, Module &M,
165 auto MF = llvm::make_unique<yaml::MachineFunction>();
166 yaml::yamlize(In, *MF, false);
169 auto FunctionName = MF->Name;
170 if (Functions.find(FunctionName) != Functions.end())
171 return error(Twine("redefinition of machine function '") + FunctionName +
173 Functions.insert(std::make_pair(FunctionName, std::move(MF)));
175 createDummyFunction(FunctionName, M);
176 else if (!M.getFunction(FunctionName))
177 return error(Twine("function '") + FunctionName +
178 "' isn't defined in the provided LLVM IR");
182 void MIRParserImpl::createDummyFunction(StringRef Name, Module &M) {
183 auto &Context = M.getContext();
184 Function *F = cast<Function>(M.getOrInsertFunction(
185 Name, FunctionType::get(Type::getVoidTy(Context), false)));
186 BasicBlock *BB = BasicBlock::Create(Context, "entry", F);
187 new UnreachableInst(Context, BB);
190 bool MIRParserImpl::initializeMachineFunction(MachineFunction &MF) {
191 auto It = Functions.find(MF.getName());
192 if (It == Functions.end())
193 return error(Twine("no machine function information for function '") +
194 MF.getName() + "' in the MIR file");
195 // TODO: Recreate the machine function.
196 const yaml::MachineFunction &YamlMF = *It->getValue();
197 if (YamlMF.Alignment)
198 MF.setAlignment(YamlMF.Alignment);
199 MF.setExposesReturnsTwice(YamlMF.ExposesReturnsTwice);
200 MF.setHasInlineAsm(YamlMF.HasInlineAsm);
204 SMDiagnostic MIRParserImpl::diagFromLLVMAssemblyDiag(const SMDiagnostic &Error,
205 SMRange SourceRange) {
206 assert(SourceRange.isValid());
208 // Translate the location of the error from the location in the llvm IR string
209 // to the corresponding location in the MIR file.
210 auto LineAndColumn = SM.getLineAndColumn(SourceRange.Start);
211 unsigned Line = LineAndColumn.first + Error.getLineNo() - 1;
212 unsigned Column = Error.getColumnNo();
213 StringRef LineStr = Error.getLineContents();
214 SMLoc Loc = Error.getLoc();
216 // Get the full line and adjust the column number by taking the indentation of
217 // LLVM IR into account.
218 for (line_iterator L(*SM.getMemoryBuffer(SM.getMainFileID()), false), E;
220 if (L.line_number() == Line) {
222 Loc = SMLoc::getFromPointer(LineStr.data());
223 auto Indent = LineStr.find(Error.getLineContents());
224 if (Indent != StringRef::npos)
230 return SMDiagnostic(SM, Loc, Filename, Line, Column, Error.getKind(),
231 Error.getMessage(), LineStr, Error.getRanges(),
235 MIRParser::MIRParser(std::unique_ptr<MIRParserImpl> Impl)
236 : Impl(std::move(Impl)) {}
238 MIRParser::~MIRParser() {}
240 std::unique_ptr<Module> MIRParser::parseLLVMModule() { return Impl->parse(); }
242 bool MIRParser::initializeMachineFunction(MachineFunction &MF) {
243 return Impl->initializeMachineFunction(MF);
246 std::unique_ptr<MIRParser> llvm::createMIRParserFromFile(StringRef Filename,
248 LLVMContext &Context) {
249 auto FileOrErr = MemoryBuffer::getFile(Filename);
250 if (std::error_code EC = FileOrErr.getError()) {
251 Error = SMDiagnostic(Filename, SourceMgr::DK_Error,
252 "Could not open input file: " + EC.message());
255 return createMIRParser(std::move(FileOrErr.get()), Context);
258 std::unique_ptr<MIRParser>
259 llvm::createMIRParser(std::unique_ptr<MemoryBuffer> Contents,
260 LLVMContext &Context) {
261 auto Filename = Contents->getBufferIdentifier();
262 return llvm::make_unique<MIRParser>(
263 llvm::make_unique<MIRParserImpl>(std::move(Contents), Filename, Context));